repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
naota/hfsplus | drivers/hid/hid-a4tech.c | 8239 | 3731 | /*
* HID driver for some a4tech "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2007 Paul Walmsley
* Copyright (c) 2008 Jiri Slaby
*/
/*
* 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/device.h>
#include <linux/input.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "hid-ids.h"
#define A4_2WHEEL_MOUSE_HACK_7 0x01
#define A4_2WHEEL_MOUSE_HACK_B8 0x02
struct a4tech_sc {
unsigned long quirks;
unsigned int hw_wheel;
__s32 delayed_value;
};
static int a4_input_mapped(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
if (usage->type == EV_REL && usage->code == REL_WHEEL)
set_bit(REL_HWHEEL, *bit);
if ((a4->quirks & A4_2WHEEL_MOUSE_HACK_7) && usage->hid == 0x00090007)
return -1;
return 0;
}
static int a4_event(struct hid_device *hdev, struct hid_field *field,
struct hid_usage *usage, __s32 value)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
struct input_dev *input;
if (!(hdev->claimed & HID_CLAIMED_INPUT) || !field->hidinput ||
!usage->type)
return 0;
input = field->hidinput->input;
if (a4->quirks & A4_2WHEEL_MOUSE_HACK_B8) {
if (usage->type == EV_REL && usage->code == REL_WHEEL) {
a4->delayed_value = value;
return 1;
}
if (usage->hid == 0x000100b8) {
input_event(input, EV_REL, value ? REL_HWHEEL :
REL_WHEEL, a4->delayed_value);
return 1;
}
}
if ((a4->quirks & A4_2WHEEL_MOUSE_HACK_7) && usage->hid == 0x00090007) {
a4->hw_wheel = !!value;
return 1;
}
if (usage->code == REL_WHEEL && a4->hw_wheel) {
input_event(input, usage->type, REL_HWHEEL, value);
return 1;
}
return 0;
}
static int a4_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct a4tech_sc *a4;
int ret;
a4 = kzalloc(sizeof(*a4), GFP_KERNEL);
if (a4 == NULL) {
hid_err(hdev, "can't alloc device descriptor\n");
ret = -ENOMEM;
goto err_free;
}
a4->quirks = id->driver_data;
hid_set_drvdata(hdev, a4);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err_free;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err_free;
}
return 0;
err_free:
kfree(a4);
return ret;
}
static void a4_remove(struct hid_device *hdev)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
hid_hw_stop(hdev);
kfree(a4);
}
static const struct hid_device_id a4_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_WCP32PU),
.driver_data = A4_2WHEEL_MOUSE_HACK_7 },
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_X5_005D),
.driver_data = A4_2WHEEL_MOUSE_HACK_B8 },
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_RP_649),
.driver_data = A4_2WHEEL_MOUSE_HACK_B8 },
{ }
};
MODULE_DEVICE_TABLE(hid, a4_devices);
static struct hid_driver a4_driver = {
.name = "a4tech",
.id_table = a4_devices,
.input_mapped = a4_input_mapped,
.event = a4_event,
.probe = a4_probe,
.remove = a4_remove,
};
static int __init a4_init(void)
{
return hid_register_driver(&a4_driver);
}
static void __exit a4_exit(void)
{
hid_unregister_driver(&a4_driver);
}
module_init(a4_init);
module_exit(a4_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
GlitchKernel/Glitch-i9300 | drivers/hid/hid-a4tech.c | 8239 | 3731 | /*
* HID driver for some a4tech "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2007 Paul Walmsley
* Copyright (c) 2008 Jiri Slaby
*/
/*
* 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/device.h>
#include <linux/input.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "hid-ids.h"
#define A4_2WHEEL_MOUSE_HACK_7 0x01
#define A4_2WHEEL_MOUSE_HACK_B8 0x02
struct a4tech_sc {
unsigned long quirks;
unsigned int hw_wheel;
__s32 delayed_value;
};
static int a4_input_mapped(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
if (usage->type == EV_REL && usage->code == REL_WHEEL)
set_bit(REL_HWHEEL, *bit);
if ((a4->quirks & A4_2WHEEL_MOUSE_HACK_7) && usage->hid == 0x00090007)
return -1;
return 0;
}
static int a4_event(struct hid_device *hdev, struct hid_field *field,
struct hid_usage *usage, __s32 value)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
struct input_dev *input;
if (!(hdev->claimed & HID_CLAIMED_INPUT) || !field->hidinput ||
!usage->type)
return 0;
input = field->hidinput->input;
if (a4->quirks & A4_2WHEEL_MOUSE_HACK_B8) {
if (usage->type == EV_REL && usage->code == REL_WHEEL) {
a4->delayed_value = value;
return 1;
}
if (usage->hid == 0x000100b8) {
input_event(input, EV_REL, value ? REL_HWHEEL :
REL_WHEEL, a4->delayed_value);
return 1;
}
}
if ((a4->quirks & A4_2WHEEL_MOUSE_HACK_7) && usage->hid == 0x00090007) {
a4->hw_wheel = !!value;
return 1;
}
if (usage->code == REL_WHEEL && a4->hw_wheel) {
input_event(input, usage->type, REL_HWHEEL, value);
return 1;
}
return 0;
}
static int a4_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct a4tech_sc *a4;
int ret;
a4 = kzalloc(sizeof(*a4), GFP_KERNEL);
if (a4 == NULL) {
hid_err(hdev, "can't alloc device descriptor\n");
ret = -ENOMEM;
goto err_free;
}
a4->quirks = id->driver_data;
hid_set_drvdata(hdev, a4);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err_free;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err_free;
}
return 0;
err_free:
kfree(a4);
return ret;
}
static void a4_remove(struct hid_device *hdev)
{
struct a4tech_sc *a4 = hid_get_drvdata(hdev);
hid_hw_stop(hdev);
kfree(a4);
}
static const struct hid_device_id a4_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_WCP32PU),
.driver_data = A4_2WHEEL_MOUSE_HACK_7 },
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_X5_005D),
.driver_data = A4_2WHEEL_MOUSE_HACK_B8 },
{ HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_RP_649),
.driver_data = A4_2WHEEL_MOUSE_HACK_B8 },
{ }
};
MODULE_DEVICE_TABLE(hid, a4_devices);
static struct hid_driver a4_driver = {
.name = "a4tech",
.id_table = a4_devices,
.input_mapped = a4_input_mapped,
.event = a4_event,
.probe = a4_probe,
.remove = a4_remove,
};
static int __init a4_init(void)
{
return hid_register_driver(&a4_driver);
}
static void __exit a4_exit(void)
{
hid_unregister_driver(&a4_driver);
}
module_init(a4_init);
module_exit(a4_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
tkawajir/android_kernel_lg_l04e | arch/arm/boot/compressed/sdhi-sh7372.c | 8751 | 2717 | /*
* SuperH Mobile SDHI
*
* Copyright (C) 2010 Magnus Damm
* Copyright (C) 2010 Kuninori Morimoto
* Copyright (C) 2010 Simon Horman
*
* 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.
*
* Parts inspired by u-boot
*/
#include <linux/io.h>
#include <mach/mmc.h>
#include <linux/mmc/boot.h>
#include <linux/mmc/tmio.h>
#include "sdhi-shmobile.h"
#define PORT179CR 0xe60520b3
#define PORT180CR 0xe60520b4
#define PORT181CR 0xe60520b5
#define PORT182CR 0xe60520b6
#define PORT183CR 0xe60520b7
#define PORT184CR 0xe60520b8
#define SMSTPCR3 0xe615013c
#define CR_INPUT_ENABLE 0x10
#define CR_FUNCTION1 0x01
#define SDHI1_BASE (void __iomem *)0xe6860000
#define SDHI_BASE SDHI1_BASE
/* SuperH Mobile SDHI loader
*
* loads the zImage from an SD card starting from block 0
* on physical partition 1
*
* The image must be start with a vrl4 header and
* the zImage must start at offset 512 of the image. That is,
* at block 1 (=byte 512) of physical partition 1
*
* Use the following line to write the vrl4 formated zImage
* to an SD card
* # dd if=vrl4.out of=/dev/sdx bs=512
*/
asmlinkage void mmc_loader(unsigned short *buf, unsigned long len)
{
int high_capacity;
mmc_init_progress();
mmc_update_progress(MMC_PROGRESS_ENTER);
/* Initialise SDHI1 */
/* PORT184CR: GPIO_FN_SDHICMD1 Control */
__raw_writeb(CR_FUNCTION1, PORT184CR);
/* PORT179CR: GPIO_FN_SDHICLK1 Control */
__raw_writeb(CR_INPUT_ENABLE|CR_FUNCTION1, PORT179CR);
/* PORT181CR: GPIO_FN_SDHID1_3 Control */
__raw_writeb(CR_FUNCTION1, PORT183CR);
/* PORT182CR: GPIO_FN_SDHID1_2 Control */
__raw_writeb(CR_FUNCTION1, PORT182CR);
/* PORT183CR: GPIO_FN_SDHID1_1 Control */
__raw_writeb(CR_FUNCTION1, PORT181CR);
/* PORT180CR: GPIO_FN_SDHID1_0 Control */
__raw_writeb(CR_FUNCTION1, PORT180CR);
/* Enable clock to SDHI1 hardware block */
__raw_writel(__raw_readl(SMSTPCR3) & ~(1 << 13), SMSTPCR3);
/* setup SDHI hardware */
mmc_update_progress(MMC_PROGRESS_INIT);
high_capacity = sdhi_boot_init(SDHI_BASE);
if (high_capacity < 0)
goto err;
mmc_update_progress(MMC_PROGRESS_LOAD);
/* load kernel */
if (sdhi_boot_do_read(SDHI_BASE, high_capacity,
0, /* Kernel is at block 1 */
(len + TMIO_BBS - 1) / TMIO_BBS, buf))
goto err;
/* Disable clock to SDHI1 hardware block */
__raw_writel(__raw_readl(SMSTPCR3) | (1 << 13), SMSTPCR3);
mmc_update_progress(MMC_PROGRESS_DONE);
return;
err:
for(;;);
}
| gpl-2.0 |
kibuuka/dv80_2.6_emo | arch/mips/dec/prom/memory.c | 9007 | 2976 | /*
* memory.c: memory initialisation code.
*
* Copyright (C) 1998 Harald Koerfgen, Frieder Streffer and Paul M. Antoine
* Copyright (C) 2000, 2002 Maciej W. Rozycki
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/types.h>
#include <asm/addrspace.h>
#include <asm/bootinfo.h>
#include <asm/dec/machtype.h>
#include <asm/dec/prom.h>
#include <asm/page.h>
#include <asm/sections.h>
volatile unsigned long mem_err; /* So we know an error occurred */
/*
* Probe memory in 4MB chunks, waiting for an error to tell us we've fallen
* off the end of real memory. Only suitable for the 2100/3100's (PMAX).
*/
#define CHUNK_SIZE 0x400000
static inline void pmax_setup_memory_region(void)
{
volatile unsigned char *memory_page, dummy;
char old_handler[0x80];
extern char genexcept_early;
/* Install exception handler */
memcpy(&old_handler, (void *)(CKSEG0 + 0x80), 0x80);
memcpy((void *)(CKSEG0 + 0x80), &genexcept_early, 0x80);
/* read unmapped and uncached (KSEG1)
* DECstations have at least 4MB RAM
* Assume less than 480MB of RAM, as this is max for 5000/2xx
* FIXME this should be replaced by the first free page!
*/
for (memory_page = (unsigned char *)CKSEG1 + CHUNK_SIZE;
mem_err == 0 && memory_page < (unsigned char *)CKSEG1 + 0x1e00000;
memory_page += CHUNK_SIZE) {
dummy = *memory_page;
}
memcpy((void *)(CKSEG0 + 0x80), &old_handler, 0x80);
add_memory_region(0, (unsigned long)memory_page - CKSEG1 - CHUNK_SIZE,
BOOT_MEM_RAM);
}
/*
* Use the REX prom calls to get hold of the memory bitmap, and thence
* determine memory size.
*/
static inline void rex_setup_memory_region(void)
{
int i, bitmap_size;
unsigned long mem_start = 0, mem_size = 0;
memmap *bm;
/* some free 64k */
bm = (memmap *)CKSEG0ADDR(0x28000);
bitmap_size = rex_getbitmap(bm);
for (i = 0; i < bitmap_size; i++) {
/* FIXME: very simplistically only add full sets of pages */
if (bm->bitmap[i] == 0xff)
mem_size += (8 * bm->pagesize);
else if (!mem_size)
mem_start += (8 * bm->pagesize);
else {
add_memory_region(mem_start, mem_size, BOOT_MEM_RAM);
mem_start += mem_size + (8 * bm->pagesize);
mem_size = 0;
}
}
if (mem_size)
add_memory_region(mem_start, mem_size, BOOT_MEM_RAM);
}
void __init prom_meminit(u32 magic)
{
if (!prom_is_rex(magic))
pmax_setup_memory_region();
else
rex_setup_memory_region();
}
void __init prom_free_prom_memory(void)
{
unsigned long end;
/*
* Free everything below the kernel itself but leave
* the first page reserved for the exception handlers.
*/
#if defined(CONFIG_DECLANCE) || defined(CONFIG_DECLANCE_MODULE)
/*
* Leave 128 KB reserved for Lance memory for
* IOASIC DECstations.
*
* XXX: save this address for use in dec_lance.c?
*/
if (IOASIC)
end = __pa(&_text) - 0x00020000;
else
#endif
end = __pa(&_text);
free_init_pages("unused PROM memory", PAGE_SIZE, end);
}
| gpl-2.0 |
daxgirl/2Stroke-kernel-n910f | tools/power/cpupower/utils/idle_monitor/amd_fam14h_idle.c | 9775 | 8644 | /*
* (C) 2010,2011 Thomas Renninger <trenn@suse.de>, Novell Inc.
*
* Licensed under the terms of the GNU GPL License version 2.
*
* PCI initialization based on example code from:
* Andreas Herrmann <andreas.herrmann3@amd.com>
*/
#if defined(__i386__) || defined(__x86_64__)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
#include <pci/pci.h>
#include "idle_monitor/cpupower-monitor.h"
#include "helpers/helpers.h"
#define PCI_NON_PC0_OFFSET 0xb0
#define PCI_PC1_OFFSET 0xb4
#define PCI_PC6_OFFSET 0xb8
#define PCI_MONITOR_ENABLE_REG 0xe0
#define PCI_NON_PC0_ENABLE_BIT 0
#define PCI_PC1_ENABLE_BIT 1
#define PCI_PC6_ENABLE_BIT 2
#define PCI_NBP1_STAT_OFFSET 0x98
#define PCI_NBP1_ACTIVE_BIT 2
#define PCI_NBP1_ENTERED_BIT 1
#define PCI_NBP1_CAP_OFFSET 0x90
#define PCI_NBP1_CAPABLE_BIT 31
#define OVERFLOW_MS 343597 /* 32 bit register filled at 12500 HZ
(1 tick per 80ns) */
enum amd_fam14h_states {NON_PC0 = 0, PC1, PC6, NBP1,
AMD_FAM14H_STATE_NUM};
static int fam14h_get_count_percent(unsigned int self_id, double *percent,
unsigned int cpu);
static int fam14h_nbp1_count(unsigned int id, unsigned long long *count,
unsigned int cpu);
static cstate_t amd_fam14h_cstates[AMD_FAM14H_STATE_NUM] = {
{
.name = "!PC0",
.desc = N_("Package in sleep state (PC1 or deeper)"),
.id = NON_PC0,
.range = RANGE_PACKAGE,
.get_count_percent = fam14h_get_count_percent,
},
{
.name = "PC1",
.desc = N_("Processor Package C1"),
.id = PC1,
.range = RANGE_PACKAGE,
.get_count_percent = fam14h_get_count_percent,
},
{
.name = "PC6",
.desc = N_("Processor Package C6"),
.id = PC6,
.range = RANGE_PACKAGE,
.get_count_percent = fam14h_get_count_percent,
},
{
.name = "NBP1",
.desc = N_("North Bridge P1 boolean counter (returns 0 or 1)"),
.id = NBP1,
.range = RANGE_PACKAGE,
.get_count = fam14h_nbp1_count,
},
};
static struct pci_access *pci_acc;
static struct pci_dev *amd_fam14h_pci_dev;
static int nbp1_entered;
struct timespec start_time;
static unsigned long long timediff;
#ifdef DEBUG
struct timespec dbg_time;
long dbg_timediff;
#endif
static unsigned long long *previous_count[AMD_FAM14H_STATE_NUM];
static unsigned long long *current_count[AMD_FAM14H_STATE_NUM];
static int amd_fam14h_get_pci_info(struct cstate *state,
unsigned int *pci_offset,
unsigned int *enable_bit,
unsigned int cpu)
{
switch (state->id) {
case NON_PC0:
*enable_bit = PCI_NON_PC0_ENABLE_BIT;
*pci_offset = PCI_NON_PC0_OFFSET;
break;
case PC1:
*enable_bit = PCI_PC1_ENABLE_BIT;
*pci_offset = PCI_PC1_OFFSET;
break;
case PC6:
*enable_bit = PCI_PC6_ENABLE_BIT;
*pci_offset = PCI_PC6_OFFSET;
break;
case NBP1:
*enable_bit = PCI_NBP1_ENTERED_BIT;
*pci_offset = PCI_NBP1_STAT_OFFSET;
break;
default:
return -1;
};
return 0;
}
static int amd_fam14h_init(cstate_t *state, unsigned int cpu)
{
int enable_bit, pci_offset, ret;
uint32_t val;
ret = amd_fam14h_get_pci_info(state, &pci_offset, &enable_bit, cpu);
if (ret)
return ret;
/* NBP1 needs extra treating -> write 1 to D18F6x98 bit 1 for init */
if (state->id == NBP1) {
val = pci_read_long(amd_fam14h_pci_dev, pci_offset);
val |= 1 << enable_bit;
val = pci_write_long(amd_fam14h_pci_dev, pci_offset, val);
return ret;
}
/* Enable monitor */
val = pci_read_long(amd_fam14h_pci_dev, PCI_MONITOR_ENABLE_REG);
dprint("Init %s: read at offset: 0x%x val: %u\n", state->name,
PCI_MONITOR_ENABLE_REG, (unsigned int) val);
val |= 1 << enable_bit;
pci_write_long(amd_fam14h_pci_dev, PCI_MONITOR_ENABLE_REG, val);
dprint("Init %s: offset: 0x%x enable_bit: %d - val: %u (%u)\n",
state->name, PCI_MONITOR_ENABLE_REG, enable_bit,
(unsigned int) val, cpu);
/* Set counter to zero */
pci_write_long(amd_fam14h_pci_dev, pci_offset, 0);
previous_count[state->id][cpu] = 0;
return 0;
}
static int amd_fam14h_disable(cstate_t *state, unsigned int cpu)
{
int enable_bit, pci_offset, ret;
uint32_t val;
ret = amd_fam14h_get_pci_info(state, &pci_offset, &enable_bit, cpu);
if (ret)
return ret;
val = pci_read_long(amd_fam14h_pci_dev, pci_offset);
dprint("%s: offset: 0x%x %u\n", state->name, pci_offset, val);
if (state->id == NBP1) {
/* was the bit whether NBP1 got entered set? */
nbp1_entered = (val & (1 << PCI_NBP1_ACTIVE_BIT)) |
(val & (1 << PCI_NBP1_ENTERED_BIT));
dprint("NBP1 was %sentered - 0x%x - enable_bit: "
"%d - pci_offset: 0x%x\n",
nbp1_entered ? "" : "not ",
val, enable_bit, pci_offset);
return ret;
}
current_count[state->id][cpu] = val;
dprint("%s: Current - %llu (%u)\n", state->name,
current_count[state->id][cpu], cpu);
dprint("%s: Previous - %llu (%u)\n", state->name,
previous_count[state->id][cpu], cpu);
val = pci_read_long(amd_fam14h_pci_dev, PCI_MONITOR_ENABLE_REG);
val &= ~(1 << enable_bit);
pci_write_long(amd_fam14h_pci_dev, PCI_MONITOR_ENABLE_REG, val);
return 0;
}
static int fam14h_nbp1_count(unsigned int id, unsigned long long *count,
unsigned int cpu)
{
if (id == NBP1) {
if (nbp1_entered)
*count = 1;
else
*count = 0;
return 0;
}
return -1;
}
static int fam14h_get_count_percent(unsigned int id, double *percent,
unsigned int cpu)
{
unsigned long diff;
if (id >= AMD_FAM14H_STATE_NUM)
return -1;
/* residency count in 80ns -> divide through 12.5 to get us residency */
diff = current_count[id][cpu] - previous_count[id][cpu];
if (timediff == 0)
*percent = 0.0;
else
*percent = 100.0 * diff / timediff / 12.5;
dprint("Timediff: %llu - res~: %lu us - percent: %.2f %%\n",
timediff, diff * 10 / 125, *percent);
return 0;
}
static int amd_fam14h_start(void)
{
int num, cpu;
clock_gettime(CLOCK_REALTIME, &start_time);
for (num = 0; num < AMD_FAM14H_STATE_NUM; num++) {
for (cpu = 0; cpu < cpu_count; cpu++)
amd_fam14h_init(&amd_fam14h_cstates[num], cpu);
}
#ifdef DEBUG
clock_gettime(CLOCK_REALTIME, &dbg_time);
dbg_timediff = timespec_diff_us(start_time, dbg_time);
dprint("Enabling counters took: %lu us\n",
dbg_timediff);
#endif
return 0;
}
static int amd_fam14h_stop(void)
{
int num, cpu;
struct timespec end_time;
clock_gettime(CLOCK_REALTIME, &end_time);
for (num = 0; num < AMD_FAM14H_STATE_NUM; num++) {
for (cpu = 0; cpu < cpu_count; cpu++)
amd_fam14h_disable(&amd_fam14h_cstates[num], cpu);
}
#ifdef DEBUG
clock_gettime(CLOCK_REALTIME, &dbg_time);
dbg_timediff = timespec_diff_us(end_time, dbg_time);
dprint("Disabling counters took: %lu ns\n", dbg_timediff);
#endif
timediff = timespec_diff_us(start_time, end_time);
if (timediff / 1000 > OVERFLOW_MS)
print_overflow_err((unsigned int)timediff / 1000000,
OVERFLOW_MS / 1000);
return 0;
}
static int is_nbp1_capable(void)
{
uint32_t val;
val = pci_read_long(amd_fam14h_pci_dev, PCI_NBP1_CAP_OFFSET);
return val & (1 << 31);
}
struct cpuidle_monitor *amd_fam14h_register(void)
{
int num;
if (cpupower_cpu_info.vendor != X86_VENDOR_AMD)
return NULL;
if (cpupower_cpu_info.family == 0x14)
strncpy(amd_fam14h_monitor.name, "Fam_14h",
MONITOR_NAME_LEN - 1);
else if (cpupower_cpu_info.family == 0x12)
strncpy(amd_fam14h_monitor.name, "Fam_12h",
MONITOR_NAME_LEN - 1);
else
return NULL;
/* We do not alloc for nbp1 machine wide counter */
for (num = 0; num < AMD_FAM14H_STATE_NUM - 1; num++) {
previous_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
current_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
}
/* We need PCI device: Slot 18, Func 6, compare with BKDG
for fam 12h/14h */
amd_fam14h_pci_dev = pci_slot_func_init(&pci_acc, 0x18, 6);
if (amd_fam14h_pci_dev == NULL || pci_acc == NULL)
return NULL;
if (!is_nbp1_capable())
amd_fam14h_monitor.hw_states_num = AMD_FAM14H_STATE_NUM - 1;
amd_fam14h_monitor.name_len = strlen(amd_fam14h_monitor.name);
return &amd_fam14h_monitor;
}
static void amd_fam14h_unregister(void)
{
int num;
for (num = 0; num < AMD_FAM14H_STATE_NUM - 1; num++) {
free(previous_count[num]);
free(current_count[num]);
}
pci_cleanup(pci_acc);
}
struct cpuidle_monitor amd_fam14h_monitor = {
.name = "",
.hw_states = amd_fam14h_cstates,
.hw_states_num = AMD_FAM14H_STATE_NUM,
.start = amd_fam14h_start,
.stop = amd_fam14h_stop,
.do_register = amd_fam14h_register,
.unregister = amd_fam14h_unregister,
.needs_root = 1,
.overflow_s = OVERFLOW_MS / 1000,
};
#endif /* #if defined(__i386__) || defined(__x86_64__) */
| gpl-2.0 |
ShichangXu/hammerhead | arch/powerpc/sysdev/mpic_pasemi_msi.c | 9775 | 4554 | /*
* Copyright 2007, Olof Johansson, PA Semi
*
* Based on arch/powerpc/sysdev/mpic_u3msi.c:
*
* Copyright 2006, Segher Boessenkool, IBM Corporation.
* Copyright 2006-2007, Michael Ellerman, 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; version 2 of the
* License.
*
*/
#undef DEBUG
#include <linux/irq.h>
#include <linux/bootmem.h>
#include <linux/msi.h>
#include <asm/mpic.h>
#include <asm/prom.h>
#include <asm/hw_irq.h>
#include <asm/ppc-pci.h>
#include <asm/msi_bitmap.h>
#include "mpic.h"
/* Allocate 16 interrupts per device, to give an alignment of 16,
* since that's the size of the grouping w.r.t. affinity. If someone
* needs more than 32 MSI's down the road we'll have to rethink this,
* but it should be OK for now.
*/
#define ALLOC_CHUNK 16
#define PASEMI_MSI_ADDR 0xfc080000
/* A bit ugly, can we get this from the pci_dev somehow? */
static struct mpic *msi_mpic;
static void mpic_pasemi_msi_mask_irq(struct irq_data *data)
{
pr_debug("mpic_pasemi_msi_mask_irq %d\n", data->irq);
mask_msi_irq(data);
mpic_mask_irq(data);
}
static void mpic_pasemi_msi_unmask_irq(struct irq_data *data)
{
pr_debug("mpic_pasemi_msi_unmask_irq %d\n", data->irq);
mpic_unmask_irq(data);
unmask_msi_irq(data);
}
static struct irq_chip mpic_pasemi_msi_chip = {
.irq_shutdown = mpic_pasemi_msi_mask_irq,
.irq_mask = mpic_pasemi_msi_mask_irq,
.irq_unmask = mpic_pasemi_msi_unmask_irq,
.irq_eoi = mpic_end_irq,
.irq_set_type = mpic_set_irq_type,
.irq_set_affinity = mpic_set_affinity,
.name = "PASEMI-MSI",
};
static int pasemi_msi_check_device(struct pci_dev *pdev, int nvec, int type)
{
if (type == PCI_CAP_ID_MSIX)
pr_debug("pasemi_msi: MSI-X untested, trying anyway\n");
return 0;
}
static void pasemi_msi_teardown_msi_irqs(struct pci_dev *pdev)
{
struct msi_desc *entry;
pr_debug("pasemi_msi_teardown_msi_irqs, pdev %p\n", pdev);
list_for_each_entry(entry, &pdev->msi_list, list) {
if (entry->irq == NO_IRQ)
continue;
irq_set_msi_desc(entry->irq, NULL);
msi_bitmap_free_hwirqs(&msi_mpic->msi_bitmap,
virq_to_hw(entry->irq), ALLOC_CHUNK);
irq_dispose_mapping(entry->irq);
}
return;
}
static int pasemi_msi_setup_msi_irqs(struct pci_dev *pdev, int nvec, int type)
{
unsigned int virq;
struct msi_desc *entry;
struct msi_msg msg;
int hwirq;
pr_debug("pasemi_msi_setup_msi_irqs, pdev %p nvec %d type %d\n",
pdev, nvec, type);
msg.address_hi = 0;
msg.address_lo = PASEMI_MSI_ADDR;
list_for_each_entry(entry, &pdev->msi_list, list) {
/* Allocate 16 interrupts for now, since that's the grouping for
* affinity. This can be changed later if it turns out 32 is too
* few MSIs for someone, but restrictions will apply to how the
* sources can be changed independently.
*/
hwirq = msi_bitmap_alloc_hwirqs(&msi_mpic->msi_bitmap,
ALLOC_CHUNK);
if (hwirq < 0) {
pr_debug("pasemi_msi: failed allocating hwirq\n");
return hwirq;
}
virq = irq_create_mapping(msi_mpic->irqhost, hwirq);
if (virq == NO_IRQ) {
pr_debug("pasemi_msi: failed mapping hwirq 0x%x\n",
hwirq);
msi_bitmap_free_hwirqs(&msi_mpic->msi_bitmap, hwirq,
ALLOC_CHUNK);
return -ENOSPC;
}
/* Vector on MSI is really an offset, the hardware adds
* it to the value written at the magic address. So set
* it to 0 to remain sane.
*/
mpic_set_vector(virq, 0);
irq_set_msi_desc(virq, entry);
irq_set_chip(virq, &mpic_pasemi_msi_chip);
irq_set_irq_type(virq, IRQ_TYPE_EDGE_RISING);
pr_debug("pasemi_msi: allocated virq 0x%x (hw 0x%x) " \
"addr 0x%x\n", virq, hwirq, msg.address_lo);
/* Likewise, the device writes [0...511] into the target
* register to generate MSI [512...1023]
*/
msg.data = hwirq-0x200;
write_msi_msg(virq, &msg);
}
return 0;
}
int mpic_pasemi_msi_init(struct mpic *mpic)
{
int rc;
if (!mpic->irqhost->of_node ||
!of_device_is_compatible(mpic->irqhost->of_node,
"pasemi,pwrficient-openpic"))
return -ENODEV;
rc = mpic_msi_init_allocator(mpic);
if (rc) {
pr_debug("pasemi_msi: Error allocating bitmap!\n");
return rc;
}
pr_debug("pasemi_msi: Registering PA Semi MPIC MSI callbacks\n");
msi_mpic = mpic;
WARN_ON(ppc_md.setup_msi_irqs);
ppc_md.setup_msi_irqs = pasemi_msi_setup_msi_irqs;
ppc_md.teardown_msi_irqs = pasemi_msi_teardown_msi_irqs;
ppc_md.msi_check_device = pasemi_msi_check_device;
return 0;
}
| gpl-2.0 |
f-andrew-beal/whoi-3.2-kernel | arch/cris/arch-v10/drivers/eeprom.c | 11311 | 22088 | /*!*****************************************************************************
*!
*! Implements an interface for i2c compatible eeproms to run under Linux.
*! Supports 2k, 8k(?) and 16k. Uses adaptive timing adjustments by
*! Johan.Adolfsson@axis.com
*!
*! Probing results:
*! 8k or not is detected (the assumes 2k or 16k)
*! 2k or 16k detected using test reads and writes.
*!
*!------------------------------------------------------------------------
*! HISTORY
*!
*! DATE NAME CHANGES
*! ---- ---- -------
*! Aug 28 1999 Edgar Iglesias Initial Version
*! Aug 31 1999 Edgar Iglesias Allow simultaneous users.
*! Sep 03 1999 Edgar Iglesias Updated probe.
*! Sep 03 1999 Edgar Iglesias Added bail-out stuff if we get interrupted
*! in the spin-lock.
*!
*! (c) 1999 Axis Communications AB, Lund, Sweden
*!*****************************************************************************/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/wait.h>
#include <asm/uaccess.h>
#include "i2c.h"
#define D(x)
/* If we should use adaptive timing or not: */
/* #define EEPROM_ADAPTIVE_TIMING */
#define EEPROM_MAJOR_NR 122 /* use a LOCAL/EXPERIMENTAL major for now */
#define EEPROM_MINOR_NR 0
/* Empirical sane initial value of the delay, the value will be adapted to
* what the chip needs when using EEPROM_ADAPTIVE_TIMING.
*/
#define INITIAL_WRITEDELAY_US 4000
#define MAX_WRITEDELAY_US 10000 /* 10 ms according to spec for 2KB EEPROM */
/* This one defines how many times to try when eeprom fails. */
#define EEPROM_RETRIES 10
#define EEPROM_2KB (2 * 1024)
/*#define EEPROM_4KB (4 * 1024)*/ /* Exists but not used in Axis products */
#define EEPROM_8KB (8 * 1024 - 1 ) /* Last byte has write protection bit */
#define EEPROM_16KB (16 * 1024)
#define i2c_delay(x) udelay(x)
/*
* This structure describes the attached eeprom chip.
* The values are probed for.
*/
struct eeprom_type
{
unsigned long size;
unsigned long sequential_write_pagesize;
unsigned char select_cmd;
unsigned long usec_delay_writecycles; /* Min time between write cycles
(up to 10ms for some models) */
unsigned long usec_delay_step; /* For adaptive algorithm */
int adapt_state; /* 1 = To high , 0 = Even, -1 = To low */
/* this one is to keep the read/write operations atomic */
struct mutex lock;
int retry_cnt_addr; /* Used to keep track of number of retries for
adaptive timing adjustments */
int retry_cnt_read;
};
static int eeprom_open(struct inode * inode, struct file * file);
static loff_t eeprom_lseek(struct file * file, loff_t offset, int orig);
static ssize_t eeprom_read(struct file * file, char * buf, size_t count,
loff_t *off);
static ssize_t eeprom_write(struct file * file, const char * buf, size_t count,
loff_t *off);
static int eeprom_close(struct inode * inode, struct file * file);
static int eeprom_address(unsigned long addr);
static int read_from_eeprom(char * buf, int count);
static int eeprom_write_buf(loff_t addr, const char * buf, int count);
static int eeprom_read_buf(loff_t addr, char * buf, int count);
static void eeprom_disable_write_protect(void);
static const char eeprom_name[] = "eeprom";
/* chip description */
static struct eeprom_type eeprom;
/* This is the exported file-operations structure for this device. */
const struct file_operations eeprom_fops =
{
.llseek = eeprom_lseek,
.read = eeprom_read,
.write = eeprom_write,
.open = eeprom_open,
.release = eeprom_close
};
/* eeprom init call. Probes for different eeprom models. */
int __init eeprom_init(void)
{
mutex_init(&eeprom.lock);
#ifdef CONFIG_ETRAX_I2C_EEPROM_PROBE
#define EETEXT "Found"
#else
#define EETEXT "Assuming"
#endif
if (register_chrdev(EEPROM_MAJOR_NR, eeprom_name, &eeprom_fops))
{
printk(KERN_INFO "%s: unable to get major %d for eeprom device\n",
eeprom_name, EEPROM_MAJOR_NR);
return -1;
}
printk("EEPROM char device v0.3, (c) 2000 Axis Communications AB\n");
/*
* Note: Most of this probing method was taken from the printserver (5470e)
* codebase. It did not contain a way of finding the 16kB chips
* (M24128 or variants). The method used here might not work
* for all models. If you encounter problems the easiest way
* is probably to define your model within #ifdef's, and hard-
* code it.
*/
eeprom.size = 0;
eeprom.usec_delay_writecycles = INITIAL_WRITEDELAY_US;
eeprom.usec_delay_step = 128;
eeprom.adapt_state = 0;
#ifdef CONFIG_ETRAX_I2C_EEPROM_PROBE
i2c_start();
i2c_outbyte(0x80);
if(!i2c_getack())
{
/* It's not 8k.. */
int success = 0;
unsigned char buf_2k_start[16];
/* Im not sure this will work... :) */
/* assume 2kB, if failure go for 16kB */
/* Test with 16kB settings.. */
/* If it's a 2kB EEPROM and we address it outside it's range
* it will mirror the address space:
* 1. We read two locations (that are mirrored),
* if the content differs * it's a 16kB EEPROM.
* 2. if it doesn't differ - write different value to one of the locations,
* check the other - if content still is the same it's a 2k EEPROM,
* restore original data.
*/
#define LOC1 8
#define LOC2 (0x1fb) /*1fb, 3ed, 5df, 7d1 */
/* 2k settings */
i2c_stop();
eeprom.size = EEPROM_2KB;
eeprom.select_cmd = 0xA0;
eeprom.sequential_write_pagesize = 16;
if( eeprom_read_buf( 0, buf_2k_start, 16 ) == 16 )
{
D(printk("2k start: '%16.16s'\n", buf_2k_start));
}
else
{
printk(KERN_INFO "%s: Failed to read in 2k mode!\n", eeprom_name);
}
/* 16k settings */
eeprom.size = EEPROM_16KB;
eeprom.select_cmd = 0xA0;
eeprom.sequential_write_pagesize = 64;
{
unsigned char loc1[4], loc2[4], tmp[4];
if( eeprom_read_buf(LOC2, loc2, 4) == 4)
{
if( eeprom_read_buf(LOC1, loc1, 4) == 4)
{
D(printk("0 loc1: (%i) '%4.4s' loc2 (%i) '%4.4s'\n",
LOC1, loc1, LOC2, loc2));
#if 0
if (memcmp(loc1, loc2, 4) != 0 )
{
/* It's 16k */
printk(KERN_INFO "%s: 16k detected in step 1\n", eeprom_name);
eeprom.size = EEPROM_16KB;
success = 1;
}
else
#endif
{
/* Do step 2 check */
/* Invert value */
loc1[0] = ~loc1[0];
if (eeprom_write_buf(LOC1, loc1, 1) == 1)
{
/* If 2k EEPROM this write will actually write 10 bytes
* from pos 0
*/
D(printk("1 loc1: (%i) '%4.4s' loc2 (%i) '%4.4s'\n",
LOC1, loc1, LOC2, loc2));
if( eeprom_read_buf(LOC1, tmp, 4) == 4)
{
D(printk("2 loc1: (%i) '%4.4s' tmp '%4.4s'\n",
LOC1, loc1, tmp));
if (memcmp(loc1, tmp, 4) != 0 )
{
printk(KERN_INFO "%s: read and write differs! Not 16kB\n",
eeprom_name);
loc1[0] = ~loc1[0];
if (eeprom_write_buf(LOC1, loc1, 1) == 1)
{
success = 1;
}
else
{
printk(KERN_INFO "%s: Restore 2k failed during probe,"
" EEPROM might be corrupt!\n", eeprom_name);
}
i2c_stop();
/* Go to 2k mode and write original data */
eeprom.size = EEPROM_2KB;
eeprom.select_cmd = 0xA0;
eeprom.sequential_write_pagesize = 16;
if( eeprom_write_buf(0, buf_2k_start, 16) == 16)
{
}
else
{
printk(KERN_INFO "%s: Failed to write back 2k start!\n",
eeprom_name);
}
eeprom.size = EEPROM_2KB;
}
}
if(!success)
{
if( eeprom_read_buf(LOC2, loc2, 1) == 1)
{
D(printk("0 loc1: (%i) '%4.4s' loc2 (%i) '%4.4s'\n",
LOC1, loc1, LOC2, loc2));
if (memcmp(loc1, loc2, 4) == 0 )
{
/* Data the same, must be mirrored -> 2k */
/* Restore data */
printk(KERN_INFO "%s: 2k detected in step 2\n", eeprom_name);
loc1[0] = ~loc1[0];
if (eeprom_write_buf(LOC1, loc1, 1) == 1)
{
success = 1;
}
else
{
printk(KERN_INFO "%s: Restore 2k failed during probe,"
" EEPROM might be corrupt!\n", eeprom_name);
}
eeprom.size = EEPROM_2KB;
}
else
{
printk(KERN_INFO "%s: 16k detected in step 2\n",
eeprom_name);
loc1[0] = ~loc1[0];
/* Data differs, assume 16k */
/* Restore data */
if (eeprom_write_buf(LOC1, loc1, 1) == 1)
{
success = 1;
}
else
{
printk(KERN_INFO "%s: Restore 16k failed during probe,"
" EEPROM might be corrupt!\n", eeprom_name);
}
eeprom.size = EEPROM_16KB;
}
}
}
}
} /* read LOC1 */
} /* address LOC1 */
if (!success)
{
printk(KERN_INFO "%s: Probing failed!, using 2KB!\n", eeprom_name);
eeprom.size = EEPROM_2KB;
}
} /* read */
}
}
else
{
i2c_outbyte(0x00);
if(!i2c_getack())
{
/* No 8k */
eeprom.size = EEPROM_2KB;
}
else
{
i2c_start();
i2c_outbyte(0x81);
if (!i2c_getack())
{
eeprom.size = EEPROM_2KB;
}
else
{
/* It's a 8kB */
i2c_inbyte();
eeprom.size = EEPROM_8KB;
}
}
}
i2c_stop();
#elif defined(CONFIG_ETRAX_I2C_EEPROM_16KB)
eeprom.size = EEPROM_16KB;
#elif defined(CONFIG_ETRAX_I2C_EEPROM_8KB)
eeprom.size = EEPROM_8KB;
#elif defined(CONFIG_ETRAX_I2C_EEPROM_2KB)
eeprom.size = EEPROM_2KB;
#endif
switch(eeprom.size)
{
case (EEPROM_2KB):
printk("%s: " EETEXT " i2c compatible 2kB eeprom.\n", eeprom_name);
eeprom.sequential_write_pagesize = 16;
eeprom.select_cmd = 0xA0;
break;
case (EEPROM_8KB):
printk("%s: " EETEXT " i2c compatible 8kB eeprom.\n", eeprom_name);
eeprom.sequential_write_pagesize = 16;
eeprom.select_cmd = 0x80;
break;
case (EEPROM_16KB):
printk("%s: " EETEXT " i2c compatible 16kB eeprom.\n", eeprom_name);
eeprom.sequential_write_pagesize = 64;
eeprom.select_cmd = 0xA0;
break;
default:
eeprom.size = 0;
printk("%s: Did not find a supported eeprom\n", eeprom_name);
break;
}
eeprom_disable_write_protect();
return 0;
}
/* Opens the device. */
static int eeprom_open(struct inode * inode, struct file * file)
{
if(iminor(inode) != EEPROM_MINOR_NR)
return -ENXIO;
if(imajor(inode) != EEPROM_MAJOR_NR)
return -ENXIO;
if( eeprom.size > 0 )
{
/* OK */
return 0;
}
/* No EEprom found */
return -EFAULT;
}
/* Changes the current file position. */
static loff_t eeprom_lseek(struct file * file, loff_t offset, int orig)
{
/*
* orig 0: position from begning of eeprom
* orig 1: relative from current position
* orig 2: position from last eeprom address
*/
switch (orig)
{
case 0:
file->f_pos = offset;
break;
case 1:
file->f_pos += offset;
break;
case 2:
file->f_pos = eeprom.size - offset;
break;
default:
return -EINVAL;
}
/* truncate position */
if (file->f_pos < 0)
{
file->f_pos = 0;
return(-EOVERFLOW);
}
if (file->f_pos >= eeprom.size)
{
file->f_pos = eeprom.size - 1;
return(-EOVERFLOW);
}
return ( file->f_pos );
}
/* Reads data from eeprom. */
static int eeprom_read_buf(loff_t addr, char * buf, int count)
{
return eeprom_read(NULL, buf, count, &addr);
}
/* Reads data from eeprom. */
static ssize_t eeprom_read(struct file * file, char * buf, size_t count, loff_t *off)
{
int read=0;
unsigned long p = *off;
unsigned char page;
if(p >= eeprom.size) /* Address i 0 - (size-1) */
{
return -EFAULT;
}
if (mutex_lock_interruptible(&eeprom.lock))
return -EINTR;
page = (unsigned char) (p >> 8);
if(!eeprom_address(p))
{
printk(KERN_INFO "%s: Read failed to address the eeprom: "
"0x%08X (%i) page: %i\n", eeprom_name, (int)p, (int)p, page);
i2c_stop();
/* don't forget to wake them up */
mutex_unlock(&eeprom.lock);
return -EFAULT;
}
if( (p + count) > eeprom.size)
{
/* truncate count */
count = eeprom.size - p;
}
/* stop dummy write op and initiate the read op */
i2c_start();
/* special case for small eeproms */
if(eeprom.size < EEPROM_16KB)
{
i2c_outbyte( eeprom.select_cmd | 1 | (page << 1) );
}
/* go on with the actual read */
read = read_from_eeprom( buf, count);
if(read > 0)
{
*off += read;
}
mutex_unlock(&eeprom.lock);
return read;
}
/* Writes data to eeprom. */
static int eeprom_write_buf(loff_t addr, const char * buf, int count)
{
return eeprom_write(NULL, buf, count, &addr);
}
/* Writes data to eeprom. */
static ssize_t eeprom_write(struct file * file, const char * buf, size_t count,
loff_t *off)
{
int i, written, restart=1;
unsigned long p;
if (!access_ok(VERIFY_READ, buf, count))
{
return -EFAULT;
}
/* bail out if we get interrupted */
if (mutex_lock_interruptible(&eeprom.lock))
return -EINTR;
for(i = 0; (i < EEPROM_RETRIES) && (restart > 0); i++)
{
restart = 0;
written = 0;
p = *off;
while( (written < count) && (p < eeprom.size))
{
/* address the eeprom */
if(!eeprom_address(p))
{
printk(KERN_INFO "%s: Write failed to address the eeprom: "
"0x%08X (%i) \n", eeprom_name, (int)p, (int)p);
i2c_stop();
/* don't forget to wake them up */
mutex_unlock(&eeprom.lock);
return -EFAULT;
}
#ifdef EEPROM_ADAPTIVE_TIMING
/* Adaptive algorithm to adjust timing */
if (eeprom.retry_cnt_addr > 0)
{
/* To Low now */
D(printk(">D=%i d=%i\n",
eeprom.usec_delay_writecycles, eeprom.usec_delay_step));
if (eeprom.usec_delay_step < 4)
{
eeprom.usec_delay_step++;
eeprom.usec_delay_writecycles += eeprom.usec_delay_step;
}
else
{
if (eeprom.adapt_state > 0)
{
/* To Low before */
eeprom.usec_delay_step *= 2;
if (eeprom.usec_delay_step > 2)
{
eeprom.usec_delay_step--;
}
eeprom.usec_delay_writecycles += eeprom.usec_delay_step;
}
else if (eeprom.adapt_state < 0)
{
/* To High before (toggle dir) */
eeprom.usec_delay_writecycles += eeprom.usec_delay_step;
if (eeprom.usec_delay_step > 1)
{
eeprom.usec_delay_step /= 2;
eeprom.usec_delay_step--;
}
}
}
eeprom.adapt_state = 1;
}
else
{
/* To High (or good) now */
D(printk("<D=%i d=%i\n",
eeprom.usec_delay_writecycles, eeprom.usec_delay_step));
if (eeprom.adapt_state < 0)
{
/* To High before */
if (eeprom.usec_delay_step > 1)
{
eeprom.usec_delay_step *= 2;
eeprom.usec_delay_step--;
if (eeprom.usec_delay_writecycles > eeprom.usec_delay_step)
{
eeprom.usec_delay_writecycles -= eeprom.usec_delay_step;
}
}
}
else if (eeprom.adapt_state > 0)
{
/* To Low before (toggle dir) */
if (eeprom.usec_delay_writecycles > eeprom.usec_delay_step)
{
eeprom.usec_delay_writecycles -= eeprom.usec_delay_step;
}
if (eeprom.usec_delay_step > 1)
{
eeprom.usec_delay_step /= 2;
eeprom.usec_delay_step--;
}
eeprom.adapt_state = -1;
}
if (eeprom.adapt_state > -100)
{
eeprom.adapt_state--;
}
else
{
/* Restart adaption */
D(printk("#Restart\n"));
eeprom.usec_delay_step++;
}
}
#endif /* EEPROM_ADAPTIVE_TIMING */
/* write until we hit a page boundary or count */
do
{
i2c_outbyte(buf[written]);
if(!i2c_getack())
{
restart=1;
printk(KERN_INFO "%s: write error, retrying. %d\n", eeprom_name, i);
i2c_stop();
break;
}
written++;
p++;
} while( written < count && ( p % eeprom.sequential_write_pagesize ));
/* end write cycle */
i2c_stop();
i2c_delay(eeprom.usec_delay_writecycles);
} /* while */
} /* for */
mutex_unlock(&eeprom.lock);
if (written == 0 && p >= eeprom.size){
return -ENOSPC;
}
*off = p;
return written;
}
/* Closes the device. */
static int eeprom_close(struct inode * inode, struct file * file)
{
/* do nothing for now */
return 0;
}
/* Sets the current address of the eeprom. */
static int eeprom_address(unsigned long addr)
{
int i;
unsigned char page, offset;
page = (unsigned char) (addr >> 8);
offset = (unsigned char) addr;
for(i = 0; i < EEPROM_RETRIES; i++)
{
/* start a dummy write for addressing */
i2c_start();
if(eeprom.size == EEPROM_16KB)
{
i2c_outbyte( eeprom.select_cmd );
i2c_getack();
i2c_outbyte(page);
}
else
{
i2c_outbyte( eeprom.select_cmd | (page << 1) );
}
if(!i2c_getack())
{
/* retry */
i2c_stop();
/* Must have a delay here.. 500 works, >50, 100->works 5th time*/
i2c_delay(MAX_WRITEDELAY_US / EEPROM_RETRIES * i);
/* The chip needs up to 10 ms from write stop to next start */
}
else
{
i2c_outbyte(offset);
if(!i2c_getack())
{
/* retry */
i2c_stop();
}
else
break;
}
}
eeprom.retry_cnt_addr = i;
D(printk("%i\n", eeprom.retry_cnt_addr));
if(eeprom.retry_cnt_addr == EEPROM_RETRIES)
{
/* failed */
return 0;
}
return 1;
}
/* Reads from current address. */
static int read_from_eeprom(char * buf, int count)
{
int i, read=0;
for(i = 0; i < EEPROM_RETRIES; i++)
{
if(eeprom.size == EEPROM_16KB)
{
i2c_outbyte( eeprom.select_cmd | 1 );
}
if(i2c_getack())
{
break;
}
}
if(i == EEPROM_RETRIES)
{
printk(KERN_INFO "%s: failed to read from eeprom\n", eeprom_name);
i2c_stop();
return -EFAULT;
}
while( (read < count))
{
if (put_user(i2c_inbyte(), &buf[read++]))
{
i2c_stop();
return -EFAULT;
}
/*
* make sure we don't ack last byte or you will get very strange
* results!
*/
if(read < count)
{
i2c_sendack();
}
}
/* stop the operation */
i2c_stop();
return read;
}
/* Disables write protection if applicable. */
#define DBP_SAVE(x)
#define ax_printf printk
static void eeprom_disable_write_protect(void)
{
/* Disable write protect */
if (eeprom.size == EEPROM_8KB)
{
/* Step 1 Set WEL = 1 (write 00000010 to address 1FFFh */
i2c_start();
i2c_outbyte(0xbe);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false\n"));
}
i2c_outbyte(0xFF);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 2\n"));
}
i2c_outbyte(0x02);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 3\n"));
}
i2c_stop();
i2c_delay(1000);
/* Step 2 Set RWEL = 1 (write 00000110 to address 1FFFh */
i2c_start();
i2c_outbyte(0xbe);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 55\n"));
}
i2c_outbyte(0xFF);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 52\n"));
}
i2c_outbyte(0x06);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 53\n"));
}
i2c_stop();
/* Step 3 Set BP1, BP0, and/or WPEN bits (write 00000110 to address 1FFFh */
i2c_start();
i2c_outbyte(0xbe);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 56\n"));
}
i2c_outbyte(0xFF);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 57\n"));
}
i2c_outbyte(0x06);
if(!i2c_getack())
{
DBP_SAVE(ax_printf("Get ack returns false 58\n"));
}
i2c_stop();
/* Write protect disabled */
}
}
module_init(eeprom_init);
| gpl-2.0 |
tuxillo/aarch64-dragonfly-gcc | libgcc/config/libbid/bid128_quantize.c | 48 | 8031 | /* Copyright (C) 2007-2015 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#define BID_128RES
#include "bid_internal.h"
BID128_FUNCTION_ARG2 (bid128_quantize, x, y)
UINT256 CT;
UINT128 CX, CY, T, CX2, CR, Stemp, res, REM_H, C2N;
UINT64 sign_x, sign_y, remainder_h, carry, CY64, valid_x;
int_float tempx;
int exponent_x, exponent_y, digits_x, extra_digits, amount;
int expon_diff, total_digits, bin_expon_cx, rmode, status;
valid_x = unpack_BID128_value (&sign_x, &exponent_x, &CX, x);
// unpack arguments, check for NaN or Infinity
if (!unpack_BID128_value (&sign_y, &exponent_y, &CY, y)) {
// y is Inf. or NaN
#ifdef SET_STATUS_FLAGS
if ((x.w[1] & SNAN_MASK64) == SNAN_MASK64) // y is sNaN
__set_status_flags (pfpsf, INVALID_EXCEPTION);
#endif
// test if y is NaN
if ((y.w[1] & 0x7c00000000000000ull) == 0x7c00000000000000ull) {
#ifdef SET_STATUS_FLAGS
if ((y.w[1] & 0x7e00000000000000ull) == 0x7e00000000000000ull) {
// set status flags
__set_status_flags (pfpsf, INVALID_EXCEPTION);
}
#endif
if ((x.w[1] & 0x7c00000000000000ull) != 0x7c00000000000000ull) {
res.w[1] = CY.w[1] & QUIET_MASK64;
res.w[0] = CY.w[0];
} else {
res.w[1] = CX.w[1] & QUIET_MASK64;
res.w[0] = CX.w[0];
}
BID_RETURN (res);
}
// y is Infinity?
if ((y.w[1] & 0x7800000000000000ull) == 0x7800000000000000ull) {
// check if x is not Inf.
if (((x.w[1] & 0x7c00000000000000ull) < 0x7800000000000000ull)) {
// return NaN
#ifdef SET_STATUS_FLAGS
// set status flags
__set_status_flags (pfpsf, INVALID_EXCEPTION);
#endif
res.w[1] = 0x7c00000000000000ull;
res.w[0] = 0;
BID_RETURN (res);
} else
if (((x.w[1] & 0x7c00000000000000ull) <= 0x7800000000000000ull)) {
res.w[1] = CX.w[1] & QUIET_MASK64;
res.w[0] = CX.w[0];
BID_RETURN (res);
}
}
}
if (!valid_x) {
// test if x is NaN or Inf
if ((x.w[1] & 0x7c00000000000000ull) == 0x7800000000000000ull) {
#ifdef SET_STATUS_FLAGS
// set status flags
__set_status_flags (pfpsf, INVALID_EXCEPTION);
#endif
res.w[1] = 0x7c00000000000000ull;
res.w[0] = 0;
BID_RETURN (res);
} else if ((x.w[1] & 0x7c00000000000000ull) == 0x7c00000000000000ull) {
if ((x.w[1] & 0x7e00000000000000ull) == 0x7e00000000000000ull) {
#ifdef SET_STATUS_FLAGS
// set status flags
__set_status_flags (pfpsf, INVALID_EXCEPTION);
#endif
}
res.w[1] = CX.w[1] & QUIET_MASK64;
res.w[0] = CX.w[0];
BID_RETURN (res);
}
if (!CX.w[1] && !CX.w[0]) {
get_BID128_very_fast (&res, sign_x, exponent_y, CX);
BID_RETURN (res);
}
}
// get number of decimal digits in coefficient_x
if (CX.w[1]) {
tempx.d = (float) CX.w[1];
bin_expon_cx = ((tempx.i >> 23) & 0xff) - 0x7f + 64;
} else {
tempx.d = (float) CX.w[0];
bin_expon_cx = ((tempx.i >> 23) & 0xff) - 0x7f;
}
digits_x = estimate_decimal_digits[bin_expon_cx];
if (CX.w[1] > power10_table_128[digits_x].w[1]
|| (CX.w[1] == power10_table_128[digits_x].w[1]
&& CX.w[0] >= power10_table_128[digits_x].w[0]))
digits_x++;
expon_diff = exponent_x - exponent_y;
total_digits = digits_x + expon_diff;
if ((UINT32) total_digits <= 34) {
if (expon_diff >= 0) {
T = power10_table_128[expon_diff];
__mul_128x128_low (CX2, T, CX);
get_BID128_very_fast (&res, sign_x, exponent_y, CX2);
BID_RETURN (res);
}
#ifndef IEEE_ROUND_NEAREST_TIES_AWAY
#ifndef IEEE_ROUND_NEAREST
rmode = rnd_mode;
if (sign_x && (unsigned) (rmode - 1) < 2)
rmode = 3 - rmode;
#else
rmode = 0;
#endif
#else
rmode = 0;
#endif
// must round off -expon_diff digits
extra_digits = -expon_diff;
__add_128_128 (CX, CX, round_const_table_128[rmode][extra_digits]);
// get P*(2^M[extra_digits])/10^extra_digits
__mul_128x128_to_256 (CT, CX, reciprocals10_128[extra_digits]);
// now get P/10^extra_digits: shift C64 right by M[extra_digits]-128
amount = recip_scale[extra_digits];
CX2.w[0] = CT.w[2];
CX2.w[1] = CT.w[3];
if (amount >= 64) {
CR.w[1] = 0;
CR.w[0] = CX2.w[1] >> (amount - 64);
} else {
__shr_128 (CR, CX2, amount);
}
#ifndef IEEE_ROUND_NEAREST_TIES_AWAY
#ifndef IEEE_ROUND_NEAREST
if (rnd_mode == 0)
#endif
if (CR.w[0] & 1) {
// check whether fractional part of initial_P/10^extra_digits is
// exactly .5 this is the same as fractional part of
// (initial_P + 0.5*10^extra_digits)/10^extra_digits is exactly zero
// get remainder
if (amount >= 64) {
remainder_h = CX2.w[0] | (CX2.w[1] << (128 - amount));
} else
remainder_h = CX2.w[0] << (64 - amount);
// test whether fractional part is 0
if (!remainder_h
&& (CT.w[1] < reciprocals10_128[extra_digits].w[1]
|| (CT.w[1] == reciprocals10_128[extra_digits].w[1]
&& CT.w[0] < reciprocals10_128[extra_digits].w[0]))) {
CR.w[0]--;
}
}
#endif
#ifdef SET_STATUS_FLAGS
status = INEXACT_EXCEPTION;
// get remainder
if (amount >= 64) {
REM_H.w[1] = (CX2.w[1] << (128 - amount));
REM_H.w[0] = CX2.w[0];
} else {
REM_H.w[1] = CX2.w[0] << (64 - amount);
REM_H.w[0] = 0;
}
switch (rmode) {
case ROUNDING_TO_NEAREST:
case ROUNDING_TIES_AWAY:
// test whether fractional part is 0
if (REM_H.w[1] == 0x8000000000000000ull && !REM_H.w[0]
&& (CT.w[1] < reciprocals10_128[extra_digits].w[1]
|| (CT.w[1] == reciprocals10_128[extra_digits].w[1]
&& CT.w[0] < reciprocals10_128[extra_digits].w[0])))
status = EXACT_STATUS;
break;
case ROUNDING_DOWN:
case ROUNDING_TO_ZERO:
if (!(REM_H.w[1] | REM_H.w[0])
&& (CT.w[1] < reciprocals10_128[extra_digits].w[1]
|| (CT.w[1] == reciprocals10_128[extra_digits].w[1]
&& CT.w[0] < reciprocals10_128[extra_digits].w[0])))
status = EXACT_STATUS;
break;
default:
// round up
__add_carry_out (Stemp.w[0], CY64, CT.w[0],
reciprocals10_128[extra_digits].w[0]);
__add_carry_in_out (Stemp.w[1], carry, CT.w[1],
reciprocals10_128[extra_digits].w[1], CY64);
if (amount < 64) {
C2N.w[1] = 0;
C2N.w[0] = ((UINT64) 1) << amount;
REM_H.w[0] = REM_H.w[1] >> (64 - amount);
REM_H.w[1] = 0;
} else {
C2N.w[1] = ((UINT64) 1) << (amount - 64);
C2N.w[0] = 0;
REM_H.w[1] >>= (128 - amount);
}
REM_H.w[0] += carry;
if (REM_H.w[0] < carry)
REM_H.w[1]++;
if (__unsigned_compare_ge_128 (REM_H, C2N))
status = EXACT_STATUS;
}
__set_status_flags (pfpsf, status);
#endif
get_BID128_very_fast (&res, sign_x, exponent_y, CR);
BID_RETURN (res);
}
if (total_digits < 0) {
CR.w[1] = CR.w[0] = 0;
#ifndef IEEE_ROUND_NEAREST_TIES_AWAY
#ifndef IEEE_ROUND_NEAREST
rmode = rnd_mode;
if (sign_x && (unsigned) (rmode - 1) < 2)
rmode = 3 - rmode;
if (rmode == ROUNDING_UP)
CR.w[0] = 1;
#endif
#endif
#ifdef SET_STATUS_FLAGS
__set_status_flags (pfpsf, INEXACT_EXCEPTION);
#endif
get_BID128_very_fast (&res, sign_x, exponent_y, CR);
BID_RETURN (res);
}
// else more than 34 digits in coefficient
#ifdef SET_STATUS_FLAGS
__set_status_flags (pfpsf, INVALID_EXCEPTION);
#endif
res.w[1] = 0x7c00000000000000ull;
res.w[0] = 0;
BID_RETURN (res);
}
| gpl-2.0 |
lsigithub/axxia_yocto_linux_4.1_pull | drivers/mmc/host/cavium-octeon.c | 48 | 9089 | /*
* Driver for MMC and SSD cards for Cavium OCTEON SOCs.
*
* 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) 2012-2017 Cavium Inc.
*/
#include <linux/dma-mapping.h>
#include <linux/gpio/consumer.h>
#include <linux/interrupt.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/slot-gpio.h>
#include <linux/module.h>
#include <linux/of_platform.h>
#include <asm/octeon/octeon.h>
#include "cavium.h"
#define CVMX_MIO_BOOT_CTL CVMX_ADD_IO_SEG(0x00011800000000D0ull)
/*
* The l2c* functions below are used for the EMMC-17978 workaround.
*
* Due to a bug in the design of the MMC bus hardware, the 2nd to last
* cache block of a DMA read must be locked into the L2 Cache.
* Otherwise, data corruption may occur.
*/
static inline void *phys_to_ptr(u64 address)
{
return (void *)(address | (1ull << 63)); /* XKPHYS */
}
/*
* Lock a single line into L2. The line is zeroed before locking
* to make sure no dram accesses are made.
*/
static void l2c_lock_line(u64 addr)
{
char *addr_ptr = phys_to_ptr(addr);
asm volatile (
"cache 31, %[line]" /* Unlock the line */
::[line] "m" (*addr_ptr));
}
/* Unlock a single line in the L2 cache. */
static void l2c_unlock_line(u64 addr)
{
char *addr_ptr = phys_to_ptr(addr);
asm volatile (
"cache 23, %[line]" /* Unlock the line */
::[line] "m" (*addr_ptr));
}
/* Locks a memory region in the L2 cache. */
static void l2c_lock_mem_region(u64 start, u64 len)
{
u64 end;
/* Round start/end to cache line boundaries */
end = ALIGN(start + len - 1, CVMX_CACHE_LINE_SIZE);
start = ALIGN(start, CVMX_CACHE_LINE_SIZE);
while (start <= end) {
l2c_lock_line(start);
start += CVMX_CACHE_LINE_SIZE;
}
asm volatile("sync");
}
/* Unlock a memory region in the L2 cache. */
static void l2c_unlock_mem_region(u64 start, u64 len)
{
u64 end;
/* Round start/end to cache line boundaries */
end = ALIGN(start + len - 1, CVMX_CACHE_LINE_SIZE);
start = ALIGN(start, CVMX_CACHE_LINE_SIZE);
while (start <= end) {
l2c_unlock_line(start);
start += CVMX_CACHE_LINE_SIZE;
}
}
static void octeon_mmc_acquire_bus(struct cvm_mmc_host *host)
{
if (!host->has_ciu3) {
down(&octeon_bootbus_sem);
/* For CN70XX, switch the MMC controller onto the bus. */
if (OCTEON_IS_MODEL(OCTEON_CN70XX))
writeq(0, (void __iomem *)CVMX_MIO_BOOT_CTL);
} else {
down(&host->mmc_serializer);
}
}
static void octeon_mmc_release_bus(struct cvm_mmc_host *host)
{
if (!host->has_ciu3)
up(&octeon_bootbus_sem);
else
up(&host->mmc_serializer);
}
static void octeon_mmc_int_enable(struct cvm_mmc_host *host, u64 val)
{
writeq(val, host->base + MIO_EMM_INT(host));
if (!host->has_ciu3)
writeq(val, host->base + MIO_EMM_INT_EN(host));
}
static void octeon_mmc_set_shared_power(struct cvm_mmc_host *host, int dir)
{
if (dir == 0)
if (!atomic_dec_return(&host->shared_power_users))
gpiod_set_value_cansleep(host->global_pwr_gpiod, 0);
if (dir == 1)
if (atomic_inc_return(&host->shared_power_users) == 1)
gpiod_set_value_cansleep(host->global_pwr_gpiod, 1);
}
static void octeon_mmc_dmar_fixup(struct cvm_mmc_host *host,
struct mmc_command *cmd,
struct mmc_data *data,
u64 addr)
{
if (cmd->opcode != MMC_WRITE_MULTIPLE_BLOCK)
return;
if (data->blksz * data->blocks <= 1024)
return;
host->n_minus_one = addr + (data->blksz * data->blocks) - 1024;
l2c_lock_mem_region(host->n_minus_one, 512);
}
static void octeon_mmc_dmar_fixup_done(struct cvm_mmc_host *host)
{
if (!host->n_minus_one)
return;
l2c_unlock_mem_region(host->n_minus_one, 512);
host->n_minus_one = 0;
}
static int octeon_mmc_probe(struct platform_device *pdev)
{
struct device_node *cn, *node = pdev->dev.of_node;
struct cvm_mmc_host *host;
struct resource *res;
void __iomem *base;
int mmc_irq[9];
int i, ret = 0;
u64 val;
host = devm_kzalloc(&pdev->dev, sizeof(*host), GFP_KERNEL);
if (!host)
return -ENOMEM;
spin_lock_init(&host->irq_handler_lock);
sema_init(&host->mmc_serializer, 1);
host->dev = &pdev->dev;
host->acquire_bus = octeon_mmc_acquire_bus;
host->release_bus = octeon_mmc_release_bus;
host->int_enable = octeon_mmc_int_enable;
host->set_shared_power = octeon_mmc_set_shared_power;
if (OCTEON_IS_MODEL(OCTEON_CN6XXX) ||
OCTEON_IS_MODEL(OCTEON_CNF7XXX)) {
host->dmar_fixup = octeon_mmc_dmar_fixup;
host->dmar_fixup_done = octeon_mmc_dmar_fixup_done;
}
host->sys_freq = octeon_get_io_clock_rate();
if (of_device_is_compatible(node, "cavium,octeon-7890-mmc")) {
host->big_dma_addr = true;
host->need_irq_handler_lock = true;
host->has_ciu3 = true;
host->use_sg = true;
/*
* First seven are the EMM_INT bits 0..6, then two for
* the EMM_DMA_INT bits
*/
for (i = 0; i < 9; i++) {
mmc_irq[i] = platform_get_irq(pdev, i);
if (mmc_irq[i] < 0)
return mmc_irq[i];
/* work around legacy u-boot device trees */
irq_set_irq_type(mmc_irq[i], IRQ_TYPE_EDGE_RISING);
}
} else {
host->big_dma_addr = false;
host->need_irq_handler_lock = false;
host->has_ciu3 = false;
/* First one is EMM second DMA */
for (i = 0; i < 2; i++) {
mmc_irq[i] = platform_get_irq(pdev, i);
if (mmc_irq[i] < 0)
return mmc_irq[i];
}
}
host->last_slot = -1;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "Platform resource[0] is missing\n");
return -ENXIO;
}
base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
host->base = (void __iomem *)base;
host->reg_off = 0;
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res) {
dev_err(&pdev->dev, "Platform resource[1] is missing\n");
return -EINVAL;
}
base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
host->dma_base = (void __iomem *)base;
/*
* To keep the register addresses shared we intentionaly use
* a negative offset here, first register used on Octeon therefore
* starts at 0x20 (MIO_EMM_DMA_CFG).
*/
host->reg_off_dma = -0x20;
ret = dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
if (ret)
return ret;
/*
* Clear out any pending interrupts that may be left over from
* bootloader.
*/
val = readq(host->base + MIO_EMM_INT(host));
writeq(val, host->base + MIO_EMM_INT(host));
if (host->has_ciu3) {
/* Only CMD_DONE, DMA_DONE, CMD_ERR, DMA_ERR */
for (i = 1; i <= 4; i++) {
ret = devm_request_irq(&pdev->dev, mmc_irq[i],
cvm_mmc_interrupt,
0, cvm_mmc_irq_names[i], host);
if (ret < 0) {
dev_err(&pdev->dev, "Error: devm_request_irq %d\n",
mmc_irq[i]);
return ret;
}
}
} else {
ret = devm_request_irq(&pdev->dev, mmc_irq[0],
cvm_mmc_interrupt, 0, KBUILD_MODNAME,
host);
if (ret < 0) {
dev_err(&pdev->dev, "Error: devm_request_irq %d\n",
mmc_irq[0]);
return ret;
}
}
host->global_pwr_gpiod = devm_gpiod_get_optional(&pdev->dev,
"power",
GPIOD_OUT_HIGH);
if (IS_ERR(host->global_pwr_gpiod)) {
dev_err(&pdev->dev, "Invalid power GPIO\n");
return PTR_ERR(host->global_pwr_gpiod);
}
platform_set_drvdata(pdev, host);
i = 0;
for_each_child_of_node(node, cn) {
host->slot_pdev[i] =
of_platform_device_create(cn, NULL, &pdev->dev);
if (!host->slot_pdev[i]) {
i++;
continue;
}
ret = cvm_mmc_of_slot_probe(&host->slot_pdev[i]->dev, host);
if (ret) {
dev_err(&pdev->dev, "Error populating slots\n");
octeon_mmc_set_shared_power(host, 0);
goto error;
}
i++;
}
return 0;
error:
for (i = 0; i < CAVIUM_MAX_MMC; i++) {
if (host->slot[i])
cvm_mmc_of_slot_remove(host->slot[i]);
if (host->slot_pdev[i])
of_platform_device_destroy(&host->slot_pdev[i]->dev, NULL);
}
return ret;
}
static int octeon_mmc_remove(struct platform_device *pdev)
{
struct cvm_mmc_host *host = platform_get_drvdata(pdev);
u64 dma_cfg;
int i;
for (i = 0; i < CAVIUM_MAX_MMC; i++)
if (host->slot[i])
cvm_mmc_of_slot_remove(host->slot[i]);
dma_cfg = readq(host->dma_base + MIO_EMM_DMA_CFG(host));
dma_cfg &= ~MIO_EMM_DMA_CFG_EN;
writeq(dma_cfg, host->dma_base + MIO_EMM_DMA_CFG(host));
octeon_mmc_set_shared_power(host, 0);
return 0;
}
static const struct of_device_id octeon_mmc_match[] = {
{
.compatible = "cavium,octeon-6130-mmc",
},
{
.compatible = "cavium,octeon-7890-mmc",
},
{},
};
MODULE_DEVICE_TABLE(of, octeon_mmc_match);
static struct platform_driver octeon_mmc_driver = {
.probe = octeon_mmc_probe,
.remove = octeon_mmc_remove,
.driver = {
.name = KBUILD_MODNAME,
.of_match_table = octeon_mmc_match,
},
};
static int __init octeon_mmc_init(void)
{
return platform_driver_register(&octeon_mmc_driver);
}
static void __exit octeon_mmc_cleanup(void)
{
platform_driver_unregister(&octeon_mmc_driver);
}
module_init(octeon_mmc_init);
module_exit(octeon_mmc_cleanup);
MODULE_AUTHOR("Cavium Inc. <support@cavium.com>");
MODULE_DESCRIPTION("Low-level driver for Cavium OCTEON MMC/SSD card");
MODULE_LICENSE("GPL");
| gpl-2.0 |
12019/linux-2.6.34-ts471x | sound/soc/au1x/psc-i2s.c | 48 | 11147 | /*
* Au12x0/Au1550 PSC ALSA ASoC audio support.
*
* (c) 2007-2008 MSC Vertriebsges.m.b.H.,
* Manuel Lauss <manuel.lauss@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Au1xxx-PSC I2S glue.
*
* NOTE: all of these drivers can only work with a SINGLE instance
* of a PSC. Multiple independent audio devices are impossible
* with ASoC v1.
* NOTE: so far only PSC slave mode (bit- and frameclock) is supported.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/suspend.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-au1x00/au1xxx_psc.h>
#include "psc.h"
/* supported I2S DAI hardware formats */
#define AU1XPSC_I2S_DAIFMT \
(SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_LEFT_J | \
SND_SOC_DAIFMT_NB_NF)
/* supported I2S direction */
#define AU1XPSC_I2S_DIR \
(SND_SOC_DAIDIR_PLAYBACK | SND_SOC_DAIDIR_CAPTURE)
#define AU1XPSC_I2S_RATES \
SNDRV_PCM_RATE_8000_192000
#define AU1XPSC_I2S_FMTS \
(SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE)
#define I2SSTAT_BUSY(stype) \
((stype) == PCM_TX ? PSC_I2SSTAT_TB : PSC_I2SSTAT_RB)
#define I2SPCR_START(stype) \
((stype) == PCM_TX ? PSC_I2SPCR_TS : PSC_I2SPCR_RS)
#define I2SPCR_STOP(stype) \
((stype) == PCM_TX ? PSC_I2SPCR_TP : PSC_I2SPCR_RP)
#define I2SPCR_CLRFIFO(stype) \
((stype) == PCM_TX ? PSC_I2SPCR_TC : PSC_I2SPCR_RC)
/* instance data. There can be only one, MacLeod!!!! */
static struct au1xpsc_audio_data *au1xpsc_i2s_workdata;
static int au1xpsc_i2s_set_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
struct au1xpsc_audio_data *pscdata = au1xpsc_i2s_workdata;
unsigned long ct;
int ret;
ret = -EINVAL;
ct = pscdata->cfg;
ct &= ~(PSC_I2SCFG_XM | PSC_I2SCFG_MLJ); /* left-justified */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
ct |= PSC_I2SCFG_XM; /* enable I2S mode */
break;
case SND_SOC_DAIFMT_MSB:
break;
case SND_SOC_DAIFMT_LSB:
ct |= PSC_I2SCFG_MLJ; /* LSB (right-) justified */
break;
default:
goto out;
}
ct &= ~(PSC_I2SCFG_BI | PSC_I2SCFG_WI); /* IB-IF */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
ct |= PSC_I2SCFG_BI | PSC_I2SCFG_WI;
break;
case SND_SOC_DAIFMT_NB_IF:
ct |= PSC_I2SCFG_BI;
break;
case SND_SOC_DAIFMT_IB_NF:
ct |= PSC_I2SCFG_WI;
break;
case SND_SOC_DAIFMT_IB_IF:
break;
default:
goto out;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM: /* CODEC master */
ct |= PSC_I2SCFG_MS; /* PSC I2S slave mode */
break;
case SND_SOC_DAIFMT_CBS_CFS: /* CODEC slave */
ct &= ~PSC_I2SCFG_MS; /* PSC I2S Master mode */
break;
default:
goto out;
}
pscdata->cfg = ct;
ret = 0;
out:
return ret;
}
static int au1xpsc_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *pscdata = au1xpsc_i2s_workdata;
int cfgbits;
unsigned long stat;
/* check if the PSC is already streaming data */
stat = au_readl(I2S_STAT(pscdata));
if (stat & (PSC_I2SSTAT_TB | PSC_I2SSTAT_RB)) {
/* reject parameters not currently set up in hardware */
cfgbits = au_readl(I2S_CFG(pscdata));
if ((PSC_I2SCFG_GET_LEN(cfgbits) != params->msbits) ||
(params_rate(params) != pscdata->rate))
return -EINVAL;
} else {
/* set sample bitdepth */
pscdata->cfg &= ~(0x1f << 4);
pscdata->cfg |= PSC_I2SCFG_SET_LEN(params->msbits);
/* remember current rate for other stream */
pscdata->rate = params_rate(params);
}
return 0;
}
/* Configure PSC late: on my devel systems the codec is I2S master and
* supplies the i2sbitclock __AND__ i2sMclk (!) to the PSC unit. ASoC
* uses aggressive PM and switches the codec off when it is not in use
* which also means the PSC unit doesn't get any clocks and is therefore
* dead. That's why this chunk here gets called from the trigger callback
* because I can be reasonably certain the codec is driving the clocks.
*/
static int au1xpsc_i2s_configure(struct au1xpsc_audio_data *pscdata)
{
unsigned long tmo;
/* bring PSC out of sleep, and configure I2S unit */
au_writel(PSC_CTRL_ENABLE, PSC_CTRL(pscdata));
au_sync();
tmo = 1000000;
while (!(au_readl(I2S_STAT(pscdata)) & PSC_I2SSTAT_SR) && tmo)
tmo--;
if (!tmo)
goto psc_err;
au_writel(0, I2S_CFG(pscdata));
au_sync();
au_writel(pscdata->cfg | PSC_I2SCFG_DE_ENABLE, I2S_CFG(pscdata));
au_sync();
/* wait for I2S controller to become ready */
tmo = 1000000;
while (!(au_readl(I2S_STAT(pscdata)) & PSC_I2SSTAT_DR) && tmo)
tmo--;
if (tmo)
return 0;
psc_err:
au_writel(0, I2S_CFG(pscdata));
au_writel(PSC_CTRL_SUSPEND, PSC_CTRL(pscdata));
au_sync();
return -ETIMEDOUT;
}
static int au1xpsc_i2s_start(struct au1xpsc_audio_data *pscdata, int stype)
{
unsigned long tmo, stat;
int ret;
ret = 0;
/* if both TX and RX are idle, configure the PSC */
stat = au_readl(I2S_STAT(pscdata));
if (!(stat & (PSC_I2SSTAT_TB | PSC_I2SSTAT_RB))) {
ret = au1xpsc_i2s_configure(pscdata);
if (ret)
goto out;
}
au_writel(I2SPCR_CLRFIFO(stype), I2S_PCR(pscdata));
au_sync();
au_writel(I2SPCR_START(stype), I2S_PCR(pscdata));
au_sync();
/* wait for start confirmation */
tmo = 1000000;
while (!(au_readl(I2S_STAT(pscdata)) & I2SSTAT_BUSY(stype)) && tmo)
tmo--;
if (!tmo) {
au_writel(I2SPCR_STOP(stype), I2S_PCR(pscdata));
au_sync();
ret = -ETIMEDOUT;
}
out:
return ret;
}
static int au1xpsc_i2s_stop(struct au1xpsc_audio_data *pscdata, int stype)
{
unsigned long tmo, stat;
au_writel(I2SPCR_STOP(stype), I2S_PCR(pscdata));
au_sync();
/* wait for stop confirmation */
tmo = 1000000;
while ((au_readl(I2S_STAT(pscdata)) & I2SSTAT_BUSY(stype)) && tmo)
tmo--;
/* if both TX and RX are idle, disable PSC */
stat = au_readl(I2S_STAT(pscdata));
if (!(stat & (PSC_I2SSTAT_TB | PSC_I2SSTAT_RB))) {
au_writel(0, I2S_CFG(pscdata));
au_sync();
au_writel(PSC_CTRL_SUSPEND, PSC_CTRL(pscdata));
au_sync();
}
return 0;
}
static int au1xpsc_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *pscdata = au1xpsc_i2s_workdata;
int ret, stype = SUBSTREAM_TYPE(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
ret = au1xpsc_i2s_start(pscdata, stype);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
ret = au1xpsc_i2s_stop(pscdata, stype);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int au1xpsc_i2s_probe(struct platform_device *pdev,
struct snd_soc_dai *dai)
{
return au1xpsc_i2s_workdata ? 0 : -ENODEV;
}
static void au1xpsc_i2s_remove(struct platform_device *pdev,
struct snd_soc_dai *dai)
{
}
static struct snd_soc_dai_ops au1xpsc_i2s_dai_ops = {
.trigger = au1xpsc_i2s_trigger,
.hw_params = au1xpsc_i2s_hw_params,
.set_fmt = au1xpsc_i2s_set_fmt,
};
struct snd_soc_dai au1xpsc_i2s_dai = {
.name = "au1xpsc_i2s",
.probe = au1xpsc_i2s_probe,
.remove = au1xpsc_i2s_remove,
.playback = {
.rates = AU1XPSC_I2S_RATES,
.formats = AU1XPSC_I2S_FMTS,
.channels_min = 2,
.channels_max = 8, /* 2 without external help */
},
.capture = {
.rates = AU1XPSC_I2S_RATES,
.formats = AU1XPSC_I2S_FMTS,
.channels_min = 2,
.channels_max = 8, /* 2 without external help */
},
.ops = &au1xpsc_i2s_dai_ops,
};
EXPORT_SYMBOL(au1xpsc_i2s_dai);
static int __init au1xpsc_i2s_drvprobe(struct platform_device *pdev)
{
struct resource *r;
unsigned long sel;
int ret;
struct au1xpsc_audio_data *wd;
if (au1xpsc_i2s_workdata)
return -EBUSY;
wd = kzalloc(sizeof(struct au1xpsc_audio_data), GFP_KERNEL);
if (!wd)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
ret = -ENODEV;
goto out0;
}
ret = -EBUSY;
wd->ioarea = request_mem_region(r->start, r->end - r->start + 1,
"au1xpsc_i2s");
if (!wd->ioarea)
goto out0;
wd->mmio = ioremap(r->start, 0xffff);
if (!wd->mmio)
goto out1;
/* preserve PSC clock source set up by platform (dev.platform_data
* is already occupied by soc layer)
*/
sel = au_readl(PSC_SEL(wd)) & PSC_SEL_CLK_MASK;
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
au_writel(PSC_SEL_PS_I2SMODE | sel, PSC_SEL(wd));
au_writel(0, I2S_CFG(wd));
au_sync();
/* preconfigure: set max rx/tx fifo depths */
wd->cfg |= PSC_I2SCFG_RT_FIFO8 | PSC_I2SCFG_TT_FIFO8;
/* don't wait for I2S core to become ready now; clocks may not
* be running yet; depending on clock input for PSC a wait might
* time out.
*/
ret = snd_soc_register_dai(&au1xpsc_i2s_dai);
if (ret)
goto out1;
/* finally add the DMA device for this PSC */
wd->dmapd = au1xpsc_pcm_add(pdev);
if (wd->dmapd) {
platform_set_drvdata(pdev, wd);
au1xpsc_i2s_workdata = wd;
return 0;
}
snd_soc_unregister_dai(&au1xpsc_i2s_dai);
out1:
release_resource(wd->ioarea);
kfree(wd->ioarea);
out0:
kfree(wd);
return ret;
}
static int __devexit au1xpsc_i2s_drvremove(struct platform_device *pdev)
{
struct au1xpsc_audio_data *wd = platform_get_drvdata(pdev);
if (wd->dmapd)
au1xpsc_pcm_destroy(wd->dmapd);
snd_soc_unregister_dai(&au1xpsc_i2s_dai);
au_writel(0, I2S_CFG(wd));
au_sync();
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
iounmap(wd->mmio);
release_resource(wd->ioarea);
kfree(wd->ioarea);
kfree(wd);
au1xpsc_i2s_workdata = NULL; /* MDEV */
return 0;
}
#ifdef CONFIG_PM
static int au1xpsc_i2s_drvsuspend(struct device *dev)
{
struct au1xpsc_audio_data *wd = dev_get_drvdata(dev);
/* save interesting register and disable PSC */
wd->pm[0] = au_readl(PSC_SEL(wd));
au_writel(0, I2S_CFG(wd));
au_sync();
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
return 0;
}
static int au1xpsc_i2s_drvresume(struct device *dev)
{
struct au1xpsc_audio_data *wd = dev_get_drvdata(dev);
/* select I2S mode and PSC clock */
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
au_writel(0, PSC_SEL(wd));
au_sync();
au_writel(wd->pm[0], PSC_SEL(wd));
au_sync();
return 0;
}
static struct dev_pm_ops au1xpsci2s_pmops = {
.suspend = au1xpsc_i2s_drvsuspend,
.resume = au1xpsc_i2s_drvresume,
};
#define AU1XPSCI2S_PMOPS &au1xpsci2s_pmops
#else
#define AU1XPSCI2S_PMOPS NULL
#endif
static struct platform_driver au1xpsc_i2s_driver = {
.driver = {
.name = "au1xpsc_i2s",
.owner = THIS_MODULE,
.pm = AU1XPSCI2S_PMOPS,
},
.probe = au1xpsc_i2s_drvprobe,
.remove = __devexit_p(au1xpsc_i2s_drvremove),
};
static int __init au1xpsc_i2s_load(void)
{
au1xpsc_i2s_workdata = NULL;
return platform_driver_register(&au1xpsc_i2s_driver);
}
static void __exit au1xpsc_i2s_unload(void)
{
platform_driver_unregister(&au1xpsc_i2s_driver);
}
module_init(au1xpsc_i2s_load);
module_exit(au1xpsc_i2s_unload);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Au12x0/Au1550 PSC I2S ALSA ASoC audio driver");
MODULE_AUTHOR("Manuel Lauss");
| gpl-2.0 |
AltraMayor/XIA-for-Linux | drivers/net/wireless/ath/wil6210/main.c | 48 | 27702 | /*
* Copyright (c) 2012-2015 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/moduleparam.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include "wil6210.h"
#include "txrx.h"
#include "wmi.h"
#include "boot_loader.h"
#define WAIT_FOR_DISCONNECT_TIMEOUT_MS 2000
#define WAIT_FOR_DISCONNECT_INTERVAL_MS 10
bool debug_fw; /* = false; */
module_param(debug_fw, bool, S_IRUGO);
MODULE_PARM_DESC(debug_fw, " do not perform card reset. For FW debug");
bool no_fw_recovery;
module_param(no_fw_recovery, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(no_fw_recovery, " disable automatic FW error recovery");
/* if not set via modparam, will be set to default value of 1/8 of
* rx ring size during init flow
*/
unsigned short rx_ring_overflow_thrsh = WIL6210_RX_HIGH_TRSH_INIT;
module_param(rx_ring_overflow_thrsh, ushort, S_IRUGO);
MODULE_PARM_DESC(rx_ring_overflow_thrsh,
" RX ring overflow threshold in descriptors.");
/* We allow allocation of more than 1 page buffers to support large packets.
* It is suboptimal behavior performance wise in case MTU above page size.
*/
unsigned int mtu_max = TXRX_BUF_LEN_DEFAULT - WIL_MAX_MPDU_OVERHEAD;
static int mtu_max_set(const char *val, const struct kernel_param *kp)
{
int ret;
/* sets mtu_max directly. no need to restore it in case of
* illegal value since we assume this will fail insmod
*/
ret = param_set_uint(val, kp);
if (ret)
return ret;
if (mtu_max < 68 || mtu_max > WIL_MAX_ETH_MTU)
ret = -EINVAL;
return ret;
}
static const struct kernel_param_ops mtu_max_ops = {
.set = mtu_max_set,
.get = param_get_uint,
};
module_param_cb(mtu_max, &mtu_max_ops, &mtu_max, S_IRUGO);
MODULE_PARM_DESC(mtu_max, " Max MTU value.");
static uint rx_ring_order = WIL_RX_RING_SIZE_ORDER_DEFAULT;
static uint tx_ring_order = WIL_TX_RING_SIZE_ORDER_DEFAULT;
static uint bcast_ring_order = WIL_BCAST_RING_SIZE_ORDER_DEFAULT;
static int ring_order_set(const char *val, const struct kernel_param *kp)
{
int ret;
uint x;
ret = kstrtouint(val, 0, &x);
if (ret)
return ret;
if ((x < WIL_RING_SIZE_ORDER_MIN) || (x > WIL_RING_SIZE_ORDER_MAX))
return -EINVAL;
*((uint *)kp->arg) = x;
return 0;
}
static const struct kernel_param_ops ring_order_ops = {
.set = ring_order_set,
.get = param_get_uint,
};
module_param_cb(rx_ring_order, &ring_order_ops, &rx_ring_order, S_IRUGO);
MODULE_PARM_DESC(rx_ring_order, " Rx ring order; size = 1 << order");
module_param_cb(tx_ring_order, &ring_order_ops, &tx_ring_order, S_IRUGO);
MODULE_PARM_DESC(tx_ring_order, " Tx ring order; size = 1 << order");
module_param_cb(bcast_ring_order, &ring_order_ops, &bcast_ring_order, S_IRUGO);
MODULE_PARM_DESC(bcast_ring_order, " Bcast ring order; size = 1 << order");
#define RST_DELAY (20) /* msec, for loop in @wil_target_reset */
#define RST_COUNT (1 + 1000/RST_DELAY) /* round up to be above 1 sec total */
/*
* Due to a hardware issue,
* one has to read/write to/from NIC in 32-bit chunks;
* regular memcpy_fromio and siblings will
* not work on 64-bit platform - it uses 64-bit transactions
*
* Force 32-bit transactions to enable NIC on 64-bit platforms
*
* To avoid byte swap on big endian host, __raw_{read|write}l
* should be used - {read|write}l would swap bytes to provide
* little endian on PCI value in host endianness.
*/
void wil_memcpy_fromio_32(void *dst, const volatile void __iomem *src,
size_t count)
{
u32 *d = dst;
const volatile u32 __iomem *s = src;
/* size_t is unsigned, if (count%4 != 0) it will wrap */
for (count += 4; count > 4; count -= 4)
*d++ = __raw_readl(s++);
}
void wil_memcpy_toio_32(volatile void __iomem *dst, const void *src,
size_t count)
{
volatile u32 __iomem *d = dst;
const u32 *s = src;
for (count += 4; count > 4; count -= 4)
__raw_writel(*s++, d++);
}
static void wil_disconnect_cid(struct wil6210_priv *wil, int cid,
u16 reason_code, bool from_event)
__acquires(&sta->tid_rx_lock) __releases(&sta->tid_rx_lock)
{
uint i;
struct net_device *ndev = wil_to_ndev(wil);
struct wireless_dev *wdev = wil->wdev;
struct wil_sta_info *sta = &wil->sta[cid];
might_sleep();
wil_dbg_misc(wil, "%s(CID %d, status %d)\n", __func__, cid,
sta->status);
if (sta->status != wil_sta_unused) {
if (!from_event)
wmi_disconnect_sta(wil, sta->addr, reason_code);
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
/* AP-like interface */
cfg80211_del_sta(ndev, sta->addr, GFP_KERNEL);
break;
default:
break;
}
sta->status = wil_sta_unused;
}
for (i = 0; i < WIL_STA_TID_NUM; i++) {
struct wil_tid_ampdu_rx *r;
spin_lock_bh(&sta->tid_rx_lock);
r = sta->tid_rx[i];
sta->tid_rx[i] = NULL;
wil_tid_ampdu_rx_free(wil, r);
spin_unlock_bh(&sta->tid_rx_lock);
}
for (i = 0; i < ARRAY_SIZE(wil->vring_tx); i++) {
if (wil->vring2cid_tid[i][0] == cid)
wil_vring_fini_tx(wil, i);
}
memset(&sta->stats, 0, sizeof(sta->stats));
}
static void _wil6210_disconnect(struct wil6210_priv *wil, const u8 *bssid,
u16 reason_code, bool from_event)
{
int cid = -ENOENT;
struct net_device *ndev = wil_to_ndev(wil);
struct wireless_dev *wdev = wil->wdev;
might_sleep();
wil_dbg_misc(wil, "%s(bssid=%pM, reason=%d, ev%s)\n", __func__, bssid,
reason_code, from_event ? "+" : "-");
/* Cases are:
* - disconnect single STA, still connected
* - disconnect single STA, already disconnected
* - disconnect all
*
* For "disconnect all", there are 3 options:
* - bssid == NULL
* - bssid is broadcast address (ff:ff:ff:ff:ff:ff)
* - bssid is our MAC address
*/
if (bssid && !is_broadcast_ether_addr(bssid) &&
!ether_addr_equal_unaligned(ndev->dev_addr, bssid)) {
cid = wil_find_cid(wil, bssid);
wil_dbg_misc(wil, "Disconnect %pM, CID=%d, reason=%d\n",
bssid, cid, reason_code);
if (cid >= 0) /* disconnect 1 peer */
wil_disconnect_cid(wil, cid, reason_code, from_event);
} else { /* all */
wil_dbg_misc(wil, "Disconnect all\n");
for (cid = 0; cid < WIL6210_MAX_CID; cid++)
wil_disconnect_cid(wil, cid, reason_code, from_event);
}
/* link state */
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
wil_bcast_fini(wil);
netif_tx_stop_all_queues(ndev);
netif_carrier_off(ndev);
if (test_bit(wil_status_fwconnected, wil->status)) {
clear_bit(wil_status_fwconnected, wil->status);
cfg80211_disconnected(ndev, reason_code,
NULL, 0, false, GFP_KERNEL);
} else if (test_bit(wil_status_fwconnecting, wil->status)) {
cfg80211_connect_result(ndev, bssid, NULL, 0, NULL, 0,
WLAN_STATUS_UNSPECIFIED_FAILURE,
GFP_KERNEL);
}
clear_bit(wil_status_fwconnecting, wil->status);
break;
default:
break;
}
}
static void wil_disconnect_worker(struct work_struct *work)
{
struct wil6210_priv *wil = container_of(work,
struct wil6210_priv, disconnect_worker);
mutex_lock(&wil->mutex);
_wil6210_disconnect(wil, NULL, WLAN_REASON_UNSPECIFIED, false);
mutex_unlock(&wil->mutex);
}
static void wil_connect_timer_fn(ulong x)
{
struct wil6210_priv *wil = (void *)x;
wil_dbg_misc(wil, "Connect timeout\n");
/* reschedule to thread context - disconnect won't
* run from atomic context
*/
schedule_work(&wil->disconnect_worker);
}
static void wil_scan_timer_fn(ulong x)
{
struct wil6210_priv *wil = (void *)x;
clear_bit(wil_status_fwready, wil->status);
wil_err(wil, "Scan timeout detected, start fw error recovery\n");
wil_fw_error_recovery(wil);
}
static int wil_wait_for_recovery(struct wil6210_priv *wil)
{
if (wait_event_interruptible(wil->wq, wil->recovery_state !=
fw_recovery_pending)) {
wil_err(wil, "Interrupt, canceling recovery\n");
return -ERESTARTSYS;
}
if (wil->recovery_state != fw_recovery_running) {
wil_info(wil, "Recovery cancelled\n");
return -EINTR;
}
wil_info(wil, "Proceed with recovery\n");
return 0;
}
void wil_set_recovery_state(struct wil6210_priv *wil, int state)
{
wil_dbg_misc(wil, "%s(%d -> %d)\n", __func__,
wil->recovery_state, state);
wil->recovery_state = state;
wake_up_interruptible(&wil->wq);
}
static void wil_fw_error_worker(struct work_struct *work)
{
struct wil6210_priv *wil = container_of(work, struct wil6210_priv,
fw_error_worker);
struct wireless_dev *wdev = wil->wdev;
wil_dbg_misc(wil, "fw error worker\n");
if (!netif_running(wil_to_ndev(wil))) {
wil_info(wil, "No recovery - interface is down\n");
return;
}
/* increment @recovery_count if less then WIL6210_FW_RECOVERY_TO
* passed since last recovery attempt
*/
if (time_is_after_jiffies(wil->last_fw_recovery +
WIL6210_FW_RECOVERY_TO))
wil->recovery_count++;
else
wil->recovery_count = 1; /* fw was alive for a long time */
if (wil->recovery_count > WIL6210_FW_RECOVERY_RETRIES) {
wil_err(wil, "too many recovery attempts (%d), giving up\n",
wil->recovery_count);
return;
}
wil->last_fw_recovery = jiffies;
mutex_lock(&wil->mutex);
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_MONITOR:
wil_info(wil, "fw error recovery requested (try %d)...\n",
wil->recovery_count);
if (!no_fw_recovery)
wil->recovery_state = fw_recovery_running;
if (0 != wil_wait_for_recovery(wil))
break;
__wil_down(wil);
__wil_up(wil);
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
wil_info(wil, "No recovery for AP-like interface\n");
/* recovery in these modes is done by upper layers */
break;
default:
wil_err(wil, "No recovery - unknown interface type %d\n",
wdev->iftype);
break;
}
mutex_unlock(&wil->mutex);
}
static int wil_find_free_vring(struct wil6210_priv *wil)
{
int i;
for (i = 0; i < WIL6210_MAX_TX_RINGS; i++) {
if (!wil->vring_tx[i].va)
return i;
}
return -EINVAL;
}
int wil_bcast_init(struct wil6210_priv *wil)
{
int ri = wil->bcast_vring, rc;
if ((ri >= 0) && wil->vring_tx[ri].va)
return 0;
ri = wil_find_free_vring(wil);
if (ri < 0)
return ri;
wil->bcast_vring = ri;
rc = wil_vring_init_bcast(wil, ri, 1 << bcast_ring_order);
if (rc)
wil->bcast_vring = -1;
return rc;
}
void wil_bcast_fini(struct wil6210_priv *wil)
{
int ri = wil->bcast_vring;
if (ri < 0)
return;
wil->bcast_vring = -1;
wil_vring_fini_tx(wil, ri);
}
static void wil_connect_worker(struct work_struct *work)
{
int rc, cid, ringid;
struct wil6210_priv *wil = container_of(work, struct wil6210_priv,
connect_worker);
struct net_device *ndev = wil_to_ndev(wil);
mutex_lock(&wil->mutex);
cid = wil->pending_connect_cid;
if (cid < 0) {
wil_err(wil, "No connection pending\n");
goto out;
}
ringid = wil_find_free_vring(wil);
if (ringid < 0) {
wil_err(wil, "No free vring found\n");
goto out;
}
wil_dbg_wmi(wil, "Configure for connection CID %d vring %d\n",
cid, ringid);
rc = wil_vring_init_tx(wil, ringid, 1 << tx_ring_order, cid, 0);
wil->pending_connect_cid = -1;
if (rc == 0) {
wil->sta[cid].status = wil_sta_connected;
netif_tx_wake_all_queues(ndev);
} else {
wil_disconnect_cid(wil, cid, WLAN_REASON_UNSPECIFIED, true);
}
out:
mutex_unlock(&wil->mutex);
}
int wil_priv_init(struct wil6210_priv *wil)
{
uint i;
wil_dbg_misc(wil, "%s()\n", __func__);
memset(wil->sta, 0, sizeof(wil->sta));
for (i = 0; i < WIL6210_MAX_CID; i++)
spin_lock_init(&wil->sta[i].tid_rx_lock);
mutex_init(&wil->mutex);
mutex_init(&wil->wmi_mutex);
mutex_init(&wil->back_rx_mutex);
mutex_init(&wil->back_tx_mutex);
mutex_init(&wil->probe_client_mutex);
init_completion(&wil->wmi_ready);
init_completion(&wil->wmi_call);
wil->pending_connect_cid = -1;
wil->bcast_vring = -1;
setup_timer(&wil->connect_timer, wil_connect_timer_fn, (ulong)wil);
setup_timer(&wil->scan_timer, wil_scan_timer_fn, (ulong)wil);
INIT_WORK(&wil->connect_worker, wil_connect_worker);
INIT_WORK(&wil->disconnect_worker, wil_disconnect_worker);
INIT_WORK(&wil->wmi_event_worker, wmi_event_worker);
INIT_WORK(&wil->fw_error_worker, wil_fw_error_worker);
INIT_WORK(&wil->back_rx_worker, wil_back_rx_worker);
INIT_WORK(&wil->back_tx_worker, wil_back_tx_worker);
INIT_WORK(&wil->probe_client_worker, wil_probe_client_worker);
INIT_LIST_HEAD(&wil->pending_wmi_ev);
INIT_LIST_HEAD(&wil->back_rx_pending);
INIT_LIST_HEAD(&wil->back_tx_pending);
INIT_LIST_HEAD(&wil->probe_client_pending);
spin_lock_init(&wil->wmi_ev_lock);
init_waitqueue_head(&wil->wq);
wil->wmi_wq = create_singlethread_workqueue(WIL_NAME "_wmi");
if (!wil->wmi_wq)
return -EAGAIN;
wil->wq_service = create_singlethread_workqueue(WIL_NAME "_service");
if (!wil->wq_service)
goto out_wmi_wq;
wil->last_fw_recovery = jiffies;
wil->tx_interframe_timeout = WIL6210_ITR_TX_INTERFRAME_TIMEOUT_DEFAULT;
wil->rx_interframe_timeout = WIL6210_ITR_RX_INTERFRAME_TIMEOUT_DEFAULT;
wil->tx_max_burst_duration = WIL6210_ITR_TX_MAX_BURST_DURATION_DEFAULT;
wil->rx_max_burst_duration = WIL6210_ITR_RX_MAX_BURST_DURATION_DEFAULT;
if (rx_ring_overflow_thrsh == WIL6210_RX_HIGH_TRSH_INIT)
rx_ring_overflow_thrsh = WIL6210_RX_HIGH_TRSH_DEFAULT;
return 0;
out_wmi_wq:
destroy_workqueue(wil->wmi_wq);
return -EAGAIN;
}
/**
* wil6210_disconnect - disconnect one connection
* @wil: driver context
* @bssid: peer to disconnect, NULL to disconnect all
* @reason_code: Reason code for the Disassociation frame
* @from_event: whether is invoked from FW event handler
*
* Disconnect and release associated resources. If invoked not from the
* FW event handler, issue WMI command(s) to trigger MAC disconnect.
*/
void wil6210_disconnect(struct wil6210_priv *wil, const u8 *bssid,
u16 reason_code, bool from_event)
{
wil_dbg_misc(wil, "%s()\n", __func__);
del_timer_sync(&wil->connect_timer);
_wil6210_disconnect(wil, bssid, reason_code, from_event);
}
void wil_priv_deinit(struct wil6210_priv *wil)
{
wil_dbg_misc(wil, "%s()\n", __func__);
wil_set_recovery_state(wil, fw_recovery_idle);
del_timer_sync(&wil->scan_timer);
cancel_work_sync(&wil->disconnect_worker);
cancel_work_sync(&wil->fw_error_worker);
mutex_lock(&wil->mutex);
wil6210_disconnect(wil, NULL, WLAN_REASON_DEAUTH_LEAVING, false);
mutex_unlock(&wil->mutex);
wmi_event_flush(wil);
wil_back_rx_flush(wil);
cancel_work_sync(&wil->back_rx_worker);
wil_back_tx_flush(wil);
cancel_work_sync(&wil->back_tx_worker);
wil_probe_client_flush(wil);
cancel_work_sync(&wil->probe_client_worker);
destroy_workqueue(wil->wq_service);
destroy_workqueue(wil->wmi_wq);
}
static inline void wil_halt_cpu(struct wil6210_priv *wil)
{
wil_w(wil, RGF_USER_USER_CPU_0, BIT_USER_USER_CPU_MAN_RST);
wil_w(wil, RGF_USER_MAC_CPU_0, BIT_USER_MAC_CPU_MAN_RST);
}
static inline void wil_release_cpu(struct wil6210_priv *wil)
{
/* Start CPU */
wil_w(wil, RGF_USER_USER_CPU_0, 1);
}
static int wil_target_reset(struct wil6210_priv *wil)
{
int delay = 0;
u32 x, x1 = 0;
wil_dbg_misc(wil, "Resetting \"%s\"...\n", wil->hw_name);
/* Clear MAC link up */
wil_s(wil, RGF_HP_CTRL, BIT(15));
wil_s(wil, RGF_USER_CLKS_CTL_SW_RST_MASK_0, BIT_HPAL_PERST_FROM_PAD);
wil_s(wil, RGF_USER_CLKS_CTL_SW_RST_MASK_0, BIT_CAR_PERST_RST);
wil_halt_cpu(wil);
/* clear all boot loader "ready" bits */
wil_w(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v0, boot_loader_ready), 0);
/* Clear Fw Download notification */
wil_c(wil, RGF_USER_USAGE_6, BIT(0));
wil_s(wil, RGF_CAF_OSC_CONTROL, BIT_CAF_OSC_XTAL_EN);
/* XTAL stabilization should take about 3ms */
usleep_range(5000, 7000);
x = wil_r(wil, RGF_CAF_PLL_LOCK_STATUS);
if (!(x & BIT_CAF_OSC_DIG_XTAL_STABLE)) {
wil_err(wil, "Xtal stabilization timeout\n"
"RGF_CAF_PLL_LOCK_STATUS = 0x%08x\n", x);
return -ETIME;
}
/* switch 10k to XTAL*/
wil_c(wil, RGF_USER_SPARROW_M_4, BIT_SPARROW_M_4_SEL_SLEEP_OR_REF);
/* 40 MHz */
wil_c(wil, RGF_USER_CLKS_CTL_0, BIT_USER_CLKS_CAR_AHB_SW_SEL);
wil_w(wil, RGF_USER_CLKS_CTL_EXT_SW_RST_VEC_0, 0x3ff81f);
wil_w(wil, RGF_USER_CLKS_CTL_EXT_SW_RST_VEC_1, 0xf);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_2, 0xFE000000);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_1, 0x0000003F);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_3, 0x000000f0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_0, 0xFFE7FE00);
wil_w(wil, RGF_USER_CLKS_CTL_EXT_SW_RST_VEC_0, 0x0);
wil_w(wil, RGF_USER_CLKS_CTL_EXT_SW_RST_VEC_1, 0x0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_3, 0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_2, 0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_1, 0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_0, 0);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_3, 0x00000003);
/* reset A2 PCIE AHB */
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_2, 0x00008000);
wil_w(wil, RGF_USER_CLKS_CTL_SW_RST_VEC_0, 0);
/* wait until device ready. typical time is 20..80 msec */
do {
msleep(RST_DELAY);
x = wil_r(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v0,
boot_loader_ready));
if (x1 != x) {
wil_dbg_misc(wil, "BL.ready 0x%08x => 0x%08x\n", x1, x);
x1 = x;
}
if (delay++ > RST_COUNT) {
wil_err(wil, "Reset not completed, bl.ready 0x%08x\n",
x);
return -ETIME;
}
} while (x != BL_READY);
wil_c(wil, RGF_USER_CLKS_CTL_0, BIT_USER_CLKS_RST_PWGD);
/* enable fix for HW bug related to the SA/DA swap in AP Rx */
wil_s(wil, RGF_DMA_OFUL_NID_0, BIT_DMA_OFUL_NID_0_RX_EXT_TR_EN |
BIT_DMA_OFUL_NID_0_RX_EXT_A3_SRC);
wil_dbg_misc(wil, "Reset completed in %d ms\n", delay * RST_DELAY);
return 0;
}
void wil_mbox_ring_le2cpus(struct wil6210_mbox_ring *r)
{
le32_to_cpus(&r->base);
le16_to_cpus(&r->entry_size);
le16_to_cpus(&r->size);
le32_to_cpus(&r->tail);
le32_to_cpus(&r->head);
}
static int wil_get_bl_info(struct wil6210_priv *wil)
{
struct net_device *ndev = wil_to_ndev(wil);
union {
struct bl_dedicated_registers_v0 bl0;
struct bl_dedicated_registers_v1 bl1;
} bl;
u32 bl_ver;
u8 *mac;
u16 rf_status;
wil_memcpy_fromio_32(&bl, wil->csr + HOSTADDR(RGF_USER_BL),
sizeof(bl));
bl_ver = le32_to_cpu(bl.bl0.boot_loader_struct_version);
mac = bl.bl0.mac_address;
if (bl_ver == 0) {
le32_to_cpus(&bl.bl0.rf_type);
le32_to_cpus(&bl.bl0.baseband_type);
rf_status = 0; /* actually, unknown */
wil_info(wil,
"Boot Loader struct v%d: MAC = %pM RF = 0x%08x bband = 0x%08x\n",
bl_ver, mac,
bl.bl0.rf_type, bl.bl0.baseband_type);
wil_info(wil, "Boot Loader build unknown for struct v0\n");
} else {
le16_to_cpus(&bl.bl1.rf_type);
rf_status = le16_to_cpu(bl.bl1.rf_status);
le32_to_cpus(&bl.bl1.baseband_type);
le16_to_cpus(&bl.bl1.bl_version_subminor);
le16_to_cpus(&bl.bl1.bl_version_build);
wil_info(wil,
"Boot Loader struct v%d: MAC = %pM RF = 0x%04x (status 0x%04x) bband = 0x%08x\n",
bl_ver, mac,
bl.bl1.rf_type, rf_status,
bl.bl1.baseband_type);
wil_info(wil, "Boot Loader build %d.%d.%d.%d\n",
bl.bl1.bl_version_major, bl.bl1.bl_version_minor,
bl.bl1.bl_version_subminor, bl.bl1.bl_version_build);
}
if (!is_valid_ether_addr(mac)) {
wil_err(wil, "BL: Invalid MAC %pM\n", mac);
return -EINVAL;
}
ether_addr_copy(ndev->perm_addr, mac);
if (!is_valid_ether_addr(ndev->dev_addr))
ether_addr_copy(ndev->dev_addr, mac);
if (rf_status) {/* bad RF cable? */
wil_err(wil, "RF communication error 0x%04x",
rf_status);
return -EAGAIN;
}
return 0;
}
static void wil_bl_crash_info(struct wil6210_priv *wil, bool is_err)
{
u32 bl_assert_code, bl_assert_blink, bl_magic_number;
u32 bl_ver = wil_r(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v0,
boot_loader_struct_version));
if (bl_ver < 2)
return;
bl_assert_code = wil_r(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v1,
bl_assert_code));
bl_assert_blink = wil_r(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v1,
bl_assert_blink));
bl_magic_number = wil_r(wil, RGF_USER_BL +
offsetof(struct bl_dedicated_registers_v1,
bl_magic_number));
if (is_err) {
wil_err(wil,
"BL assert code 0x%08x blink 0x%08x magic 0x%08x\n",
bl_assert_code, bl_assert_blink, bl_magic_number);
} else {
wil_dbg_misc(wil,
"BL assert code 0x%08x blink 0x%08x magic 0x%08x\n",
bl_assert_code, bl_assert_blink, bl_magic_number);
}
}
static int wil_wait_for_fw_ready(struct wil6210_priv *wil)
{
ulong to = msecs_to_jiffies(1000);
ulong left = wait_for_completion_timeout(&wil->wmi_ready, to);
if (0 == left) {
wil_err(wil, "Firmware not ready\n");
return -ETIME;
} else {
wil_info(wil, "FW ready after %d ms. HW version 0x%08x\n",
jiffies_to_msecs(to-left), wil->hw_version);
}
return 0;
}
/*
* We reset all the structures, and we reset the UMAC.
* After calling this routine, you're expected to reload
* the firmware.
*/
int wil_reset(struct wil6210_priv *wil, bool load_fw)
{
int rc;
wil_dbg_misc(wil, "%s()\n", __func__);
WARN_ON(!mutex_is_locked(&wil->mutex));
WARN_ON(test_bit(wil_status_napi_en, wil->status));
if (debug_fw) {
static const u8 mac[ETH_ALEN] = {
0x00, 0xde, 0xad, 0x12, 0x34, 0x56,
};
struct net_device *ndev = wil_to_ndev(wil);
ether_addr_copy(ndev->perm_addr, mac);
ether_addr_copy(ndev->dev_addr, ndev->perm_addr);
return 0;
}
if (wil->hw_version == HW_VER_UNKNOWN)
return -ENODEV;
set_bit(wil_status_resetting, wil->status);
cancel_work_sync(&wil->disconnect_worker);
wil6210_disconnect(wil, NULL, WLAN_REASON_DEAUTH_LEAVING, false);
wil_bcast_fini(wil);
/* prevent NAPI from being scheduled and prevent wmi commands */
mutex_lock(&wil->wmi_mutex);
bitmap_zero(wil->status, wil_status_last);
mutex_unlock(&wil->wmi_mutex);
if (wil->scan_request) {
wil_dbg_misc(wil, "Abort scan_request 0x%p\n",
wil->scan_request);
del_timer_sync(&wil->scan_timer);
cfg80211_scan_done(wil->scan_request, true);
wil->scan_request = NULL;
}
wil_mask_irq(wil);
wmi_event_flush(wil);
flush_workqueue(wil->wq_service);
flush_workqueue(wil->wmi_wq);
wil_bl_crash_info(wil, false);
rc = wil_target_reset(wil);
wil_rx_fini(wil);
if (rc) {
wil_bl_crash_info(wil, true);
return rc;
}
rc = wil_get_bl_info(wil);
if (rc == -EAGAIN && !load_fw) /* ignore RF error if not going up */
rc = 0;
if (rc)
return rc;
if (load_fw) {
wil_info(wil, "Use firmware <%s> + board <%s>\n", WIL_FW_NAME,
WIL_FW2_NAME);
wil_halt_cpu(wil);
/* Loading f/w from the file */
rc = wil_request_firmware(wil, WIL_FW_NAME);
if (rc)
return rc;
rc = wil_request_firmware(wil, WIL_FW2_NAME);
if (rc)
return rc;
/* Mark FW as loaded from host */
wil_s(wil, RGF_USER_USAGE_6, 1);
/* clear any interrupts which on-card-firmware
* may have set
*/
wil6210_clear_irq(wil);
/* CAF_ICR - clear and mask */
/* it is W1C, clear by writing back same value */
wil_s(wil, RGF_CAF_ICR + offsetof(struct RGF_ICR, ICR), 0);
wil_w(wil, RGF_CAF_ICR + offsetof(struct RGF_ICR, IMV), ~0);
wil_release_cpu(wil);
}
/* init after reset */
wil->pending_connect_cid = -1;
wil->ap_isolate = 0;
reinit_completion(&wil->wmi_ready);
reinit_completion(&wil->wmi_call);
if (load_fw) {
wil_configure_interrupt_moderation(wil);
wil_unmask_irq(wil);
/* we just started MAC, wait for FW ready */
rc = wil_wait_for_fw_ready(wil);
if (rc == 0) /* check FW is responsive */
rc = wmi_echo(wil);
}
return rc;
}
void wil_fw_error_recovery(struct wil6210_priv *wil)
{
wil_dbg_misc(wil, "starting fw error recovery\n");
if (test_bit(wil_status_resetting, wil->status)) {
wil_info(wil, "Reset already in progress\n");
return;
}
wil->recovery_state = fw_recovery_pending;
schedule_work(&wil->fw_error_worker);
}
int __wil_up(struct wil6210_priv *wil)
{
struct net_device *ndev = wil_to_ndev(wil);
struct wireless_dev *wdev = wil->wdev;
int rc;
WARN_ON(!mutex_is_locked(&wil->mutex));
rc = wil_reset(wil, true);
if (rc)
return rc;
/* Rx VRING. After MAC and beacon */
rc = wil_rx_init(wil, 1 << rx_ring_order);
if (rc)
return rc;
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
wil_dbg_misc(wil, "type: STATION\n");
ndev->type = ARPHRD_ETHER;
break;
case NL80211_IFTYPE_AP:
wil_dbg_misc(wil, "type: AP\n");
ndev->type = ARPHRD_ETHER;
break;
case NL80211_IFTYPE_P2P_CLIENT:
wil_dbg_misc(wil, "type: P2P_CLIENT\n");
ndev->type = ARPHRD_ETHER;
break;
case NL80211_IFTYPE_P2P_GO:
wil_dbg_misc(wil, "type: P2P_GO\n");
ndev->type = ARPHRD_ETHER;
break;
case NL80211_IFTYPE_MONITOR:
wil_dbg_misc(wil, "type: Monitor\n");
ndev->type = ARPHRD_IEEE80211_RADIOTAP;
/* ARPHRD_IEEE80211 or ARPHRD_IEEE80211_RADIOTAP ? */
break;
default:
return -EOPNOTSUPP;
}
/* MAC address - pre-requisite for other commands */
wmi_set_mac_address(wil, ndev->dev_addr);
wil_dbg_misc(wil, "NAPI enable\n");
napi_enable(&wil->napi_rx);
napi_enable(&wil->napi_tx);
set_bit(wil_status_napi_en, wil->status);
if (wil->platform_ops.bus_request)
wil->platform_ops.bus_request(wil->platform_handle,
WIL_MAX_BUS_REQUEST_KBPS);
return 0;
}
int wil_up(struct wil6210_priv *wil)
{
int rc;
wil_dbg_misc(wil, "%s()\n", __func__);
mutex_lock(&wil->mutex);
rc = __wil_up(wil);
mutex_unlock(&wil->mutex);
return rc;
}
int __wil_down(struct wil6210_priv *wil)
{
int iter = WAIT_FOR_DISCONNECT_TIMEOUT_MS /
WAIT_FOR_DISCONNECT_INTERVAL_MS;
WARN_ON(!mutex_is_locked(&wil->mutex));
if (wil->platform_ops.bus_request)
wil->platform_ops.bus_request(wil->platform_handle, 0);
wil_disable_irq(wil);
if (test_and_clear_bit(wil_status_napi_en, wil->status)) {
napi_disable(&wil->napi_rx);
napi_disable(&wil->napi_tx);
wil_dbg_misc(wil, "NAPI disable\n");
}
wil_enable_irq(wil);
if (wil->scan_request) {
wil_dbg_misc(wil, "Abort scan_request 0x%p\n",
wil->scan_request);
del_timer_sync(&wil->scan_timer);
cfg80211_scan_done(wil->scan_request, true);
wil->scan_request = NULL;
}
if (test_bit(wil_status_fwconnected, wil->status) ||
test_bit(wil_status_fwconnecting, wil->status))
wmi_send(wil, WMI_DISCONNECT_CMDID, NULL, 0);
/* make sure wil is idle (not connected) */
mutex_unlock(&wil->mutex);
while (iter--) {
int idle = !test_bit(wil_status_fwconnected, wil->status) &&
!test_bit(wil_status_fwconnecting, wil->status);
if (idle)
break;
msleep(WAIT_FOR_DISCONNECT_INTERVAL_MS);
}
mutex_lock(&wil->mutex);
if (iter < 0)
wil_err(wil, "timeout waiting for idle FW/HW\n");
wil_reset(wil, false);
return 0;
}
int wil_down(struct wil6210_priv *wil)
{
int rc;
wil_dbg_misc(wil, "%s()\n", __func__);
wil_set_recovery_state(wil, fw_recovery_idle);
mutex_lock(&wil->mutex);
rc = __wil_down(wil);
mutex_unlock(&wil->mutex);
return rc;
}
int wil_find_cid(struct wil6210_priv *wil, const u8 *mac)
{
int i;
int rc = -ENOENT;
for (i = 0; i < ARRAY_SIZE(wil->sta); i++) {
if ((wil->sta[i].status != wil_sta_unused) &&
ether_addr_equal(wil->sta[i].addr, mac)) {
rc = i;
break;
}
}
return rc;
}
| gpl-2.0 |
lizhm82/p4a-kernel | drivers/video/backlight/l4f00242t03.c | 48 | 5708 | /*
* l4f00242t03.c -- support for Epson L4F00242T03 LCD
*
* Copyright 2007-2009 Freescale Semiconductor, Inc. All Rights Reserved.
*
* Copyright (c) 2009 Alberto Panizzo <maramaopercheseimorto@gmail.com>
* Inspired by Marek Vasut work in l4f00242t03.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/lcd.h>
#include <linux/slab.h>
#include <linux/regulator/consumer.h>
#include <linux/spi/spi.h>
#include <linux/spi/l4f00242t03.h>
struct l4f00242t03_priv {
struct spi_device *spi;
struct lcd_device *ld;
int lcd_on:1;
struct regulator *io_reg;
struct regulator *core_reg;
};
static void l4f00242t03_reset(unsigned int gpio)
{
pr_debug("l4f00242t03_reset.\n");
gpio_set_value(gpio, 1);
mdelay(100);
gpio_set_value(gpio, 0);
mdelay(10); /* tRES >= 100us */
gpio_set_value(gpio, 1);
mdelay(20);
}
#define param(x) ((x) | 0x100)
static void l4f00242t03_lcd_init(struct spi_device *spi)
{
struct l4f00242t03_pdata *pdata = spi->dev.platform_data;
struct l4f00242t03_priv *priv = dev_get_drvdata(&spi->dev);
const u16 cmd[] = { 0x36, param(0), 0x3A, param(0x60) };
dev_dbg(&spi->dev, "initializing LCD\n");
if (priv->io_reg) {
regulator_set_voltage(priv->io_reg, 1800000, 1800000);
regulator_enable(priv->io_reg);
}
if (priv->core_reg) {
regulator_set_voltage(priv->core_reg, 2800000, 2800000);
regulator_enable(priv->core_reg);
}
gpio_set_value(pdata->data_enable_gpio, 1);
msleep(60);
spi_write(spi, (const u8 *)cmd, ARRAY_SIZE(cmd) * sizeof(u16));
}
static int l4f00242t03_lcd_power_set(struct lcd_device *ld, int power)
{
struct l4f00242t03_priv *priv = lcd_get_data(ld);
struct spi_device *spi = priv->spi;
const u16 slpout = 0x11;
const u16 dison = 0x29;
const u16 slpin = 0x10;
const u16 disoff = 0x28;
if (power <= FB_BLANK_NORMAL) {
if (priv->lcd_on)
return 0;
dev_dbg(&spi->dev, "turning on LCD\n");
spi_write(spi, (const u8 *)&slpout, sizeof(u16));
msleep(60);
spi_write(spi, (const u8 *)&dison, sizeof(u16));
priv->lcd_on = 1;
} else {
if (!priv->lcd_on)
return 0;
dev_dbg(&spi->dev, "turning off LCD\n");
spi_write(spi, (const u8 *)&disoff, sizeof(u16));
msleep(60);
spi_write(spi, (const u8 *)&slpin, sizeof(u16));
priv->lcd_on = 0;
}
return 0;
}
static struct lcd_ops l4f_ops = {
.set_power = l4f00242t03_lcd_power_set,
.get_power = NULL,
};
static int __devinit l4f00242t03_probe(struct spi_device *spi)
{
struct l4f00242t03_priv *priv;
struct l4f00242t03_pdata *pdata = spi->dev.platform_data;
int ret;
if (pdata == NULL) {
dev_err(&spi->dev, "Uninitialized platform data.\n");
return -EINVAL;
}
priv = kzalloc(sizeof(struct l4f00242t03_priv), GFP_KERNEL);
if (priv == NULL) {
dev_err(&spi->dev, "No memory for this device.\n");
return -ENOMEM;
}
dev_set_drvdata(&spi->dev, priv);
spi->bits_per_word = 9;
spi_setup(spi);
priv->spi = spi;
ret = gpio_request(pdata->reset_gpio, "lcd l4f00242t03 reset");
if (ret) {
dev_err(&spi->dev,
"Unable to get the lcd l4f00242t03 reset gpio.\n");
goto err;
}
ret = gpio_direction_output(pdata->reset_gpio, 1);
if (ret)
goto err2;
ret = gpio_request(pdata->data_enable_gpio,
"lcd l4f00242t03 data enable");
if (ret) {
dev_err(&spi->dev,
"Unable to get the lcd l4f00242t03 data en gpio.\n");
goto err2;
}
ret = gpio_direction_output(pdata->data_enable_gpio, 0);
if (ret)
goto err3;
if (pdata->io_supply) {
priv->io_reg = regulator_get(NULL, pdata->io_supply);
if (IS_ERR(priv->io_reg)) {
pr_err("%s: Unable to get the IO regulator\n",
__func__);
goto err3;
}
}
if (pdata->core_supply) {
priv->core_reg = regulator_get(NULL, pdata->core_supply);
if (IS_ERR(priv->core_reg)) {
pr_err("%s: Unable to get the core regulator\n",
__func__);
goto err4;
}
}
priv->ld = lcd_device_register("l4f00242t03",
&spi->dev, priv, &l4f_ops);
if (IS_ERR(priv->ld)) {
ret = PTR_ERR(priv->ld);
goto err5;
}
/* Init the LCD */
l4f00242t03_reset(pdata->reset_gpio);
l4f00242t03_lcd_init(spi);
l4f00242t03_lcd_power_set(priv->ld, 1);
dev_info(&spi->dev, "Epson l4f00242t03 lcd probed.\n");
return 0;
err5:
if (priv->core_reg)
regulator_put(priv->core_reg);
err4:
if (priv->io_reg)
regulator_put(priv->io_reg);
err3:
gpio_free(pdata->data_enable_gpio);
err2:
gpio_free(pdata->reset_gpio);
err:
kfree(priv);
return ret;
}
static int __devexit l4f00242t03_remove(struct spi_device *spi)
{
struct l4f00242t03_priv *priv = dev_get_drvdata(&spi->dev);
struct l4f00242t03_pdata *pdata = priv->spi->dev.platform_data;
l4f00242t03_lcd_power_set(priv->ld, 0);
lcd_device_unregister(priv->ld);
gpio_free(pdata->data_enable_gpio);
gpio_free(pdata->reset_gpio);
if (priv->io_reg)
regulator_put(priv->io_reg);
if (priv->core_reg)
regulator_put(priv->core_reg);
kfree(priv);
return 0;
}
static struct spi_driver l4f00242t03_driver = {
.driver = {
.name = "l4f00242t03",
.owner = THIS_MODULE,
},
.probe = l4f00242t03_probe,
.remove = __devexit_p(l4f00242t03_remove),
};
static __init int l4f00242t03_init(void)
{
return spi_register_driver(&l4f00242t03_driver);
}
static __exit void l4f00242t03_exit(void)
{
spi_unregister_driver(&l4f00242t03_driver);
}
module_init(l4f00242t03_init);
module_exit(l4f00242t03_exit);
MODULE_AUTHOR("Alberto Panizzo <maramaopercheseimorto@gmail.com>");
MODULE_DESCRIPTION("EPSON L4F00242T03 LCD");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
nimengyu2/jorjin-ap-module-dm37-android-kernel | lib/swiotlb.c | 48 | 26139 | /*
* Dynamic DMA mapping support.
*
* This implementation is a fallback for platforms that do not support
* I/O TLBs (aka DMA address translation hardware).
* Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
* Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
* Copyright (C) 2000, 2003 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
*
* 03/05/07 davidm Switch from PCI-DMA to generic device DMA API.
* 00/12/13 davidm Rename to swiotlb.c and add mark_clean() to avoid
* unnecessary i-cache flushing.
* 04/07/.. ak Better overflow handling. Assorted fixes.
* 05/09/10 linville Add support for syncing ranges, support syncing for
* DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
* 08/12/11 beckyb Add highmem support
*/
#include <linux/cache.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/swiotlb.h>
#include <linux/pfn.h>
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/highmem.h>
#include <linux/gfp.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/scatterlist.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/iommu-helper.h>
#define OFFSET(val,align) ((unsigned long) \
( (val) & ( (align) - 1)))
#define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
/*
* Minimum IO TLB size to bother booting with. Systems with mainly
* 64bit capable cards will only lightly use the swiotlb. If we can't
* allocate a contiguous 1MB, we're probably in trouble anyway.
*/
#define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
int swiotlb_force;
/*
* Used to do a quick range check in swiotlb_tbl_unmap_single and
* swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
* API.
*/
static char *io_tlb_start, *io_tlb_end;
/*
* The number of IO TLB blocks (in groups of 64) betweeen io_tlb_start and
* io_tlb_end. This is command line adjustable via setup_io_tlb_npages.
*/
static unsigned long io_tlb_nslabs;
/*
* When the IOMMU overflows we return a fallback buffer. This sets the size.
*/
static unsigned long io_tlb_overflow = 32*1024;
static void *io_tlb_overflow_buffer;
/*
* This is a free list describing the number of free entries available from
* each index
*/
static unsigned int *io_tlb_list;
static unsigned int io_tlb_index;
/*
* We need to save away the original address corresponding to a mapped entry
* for the sync operations.
*/
static phys_addr_t *io_tlb_orig_addr;
/*
* Protect the above data structures in the map and unmap calls
*/
static DEFINE_SPINLOCK(io_tlb_lock);
static int late_alloc;
static int __init
setup_io_tlb_npages(char *str)
{
if (isdigit(*str)) {
io_tlb_nslabs = simple_strtoul(str, &str, 0);
/* avoid tail segment of size < IO_TLB_SEGSIZE */
io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
}
if (*str == ',')
++str;
if (!strcmp(str, "force"))
swiotlb_force = 1;
return 1;
}
__setup("swiotlb=", setup_io_tlb_npages);
/* make io_tlb_overflow tunable too? */
/* Note that this doesn't work with highmem page */
static dma_addr_t swiotlb_virt_to_bus(struct device *hwdev,
volatile void *address)
{
return phys_to_dma(hwdev, virt_to_phys(address));
}
void swiotlb_print_info(void)
{
unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
phys_addr_t pstart, pend;
pstart = virt_to_phys(io_tlb_start);
pend = virt_to_phys(io_tlb_end);
printk(KERN_INFO "Placing %luMB software IO TLB between %p - %p\n",
bytes >> 20, io_tlb_start, io_tlb_end);
printk(KERN_INFO "software IO TLB at phys %#llx - %#llx\n",
(unsigned long long)pstart,
(unsigned long long)pend);
}
void __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
{
unsigned long i, bytes;
bytes = nslabs << IO_TLB_SHIFT;
io_tlb_nslabs = nslabs;
io_tlb_start = tlb;
io_tlb_end = io_tlb_start + bytes;
/*
* Allocate and initialize the free list array. This array is used
* to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
* between io_tlb_start and io_tlb_end.
*/
io_tlb_list = alloc_bootmem_pages(PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
for (i = 0; i < io_tlb_nslabs; i++)
io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
io_tlb_index = 0;
io_tlb_orig_addr = alloc_bootmem_pages(PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
/*
* Get the overflow emergency buffer
*/
io_tlb_overflow_buffer = alloc_bootmem_low_pages(PAGE_ALIGN(io_tlb_overflow));
if (!io_tlb_overflow_buffer)
panic("Cannot allocate SWIOTLB overflow buffer!\n");
if (verbose)
swiotlb_print_info();
}
/*
* Statically reserve bounce buffer space and initialize bounce buffer data
* structures for the software IO TLB used to implement the DMA API.
*/
void __init
swiotlb_init_with_default_size(size_t default_size, int verbose)
{
unsigned long bytes;
if (!io_tlb_nslabs) {
io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
}
bytes = io_tlb_nslabs << IO_TLB_SHIFT;
/*
* Get IO TLB memory from the low pages
*/
io_tlb_start = alloc_bootmem_low_pages(PAGE_ALIGN(bytes));
if (!io_tlb_start)
panic("Cannot allocate SWIOTLB buffer");
swiotlb_init_with_tbl(io_tlb_start, io_tlb_nslabs, verbose);
}
void __init
swiotlb_init(int verbose)
{
swiotlb_init_with_default_size(64 * (1<<20), verbose); /* default to 64MB */
}
/*
* Systems with larger DMA zones (those that don't support ISA) can
* initialize the swiotlb later using the slab allocator if needed.
* This should be just like above, but with some error catching.
*/
int
swiotlb_late_init_with_default_size(size_t default_size)
{
unsigned long i, bytes, req_nslabs = io_tlb_nslabs;
unsigned int order;
if (!io_tlb_nslabs) {
io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
}
/*
* Get IO TLB memory from the low pages
*/
order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
io_tlb_nslabs = SLABS_PER_PAGE << order;
bytes = io_tlb_nslabs << IO_TLB_SHIFT;
while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
io_tlb_start = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
order);
if (io_tlb_start)
break;
order--;
}
if (!io_tlb_start)
goto cleanup1;
if (order != get_order(bytes)) {
printk(KERN_WARNING "Warning: only able to allocate %ld MB "
"for software IO TLB\n", (PAGE_SIZE << order) >> 20);
io_tlb_nslabs = SLABS_PER_PAGE << order;
bytes = io_tlb_nslabs << IO_TLB_SHIFT;
}
io_tlb_end = io_tlb_start + bytes;
memset(io_tlb_start, 0, bytes);
/*
* Allocate and initialize the free list array. This array is used
* to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
* between io_tlb_start and io_tlb_end.
*/
io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
get_order(io_tlb_nslabs * sizeof(int)));
if (!io_tlb_list)
goto cleanup2;
for (i = 0; i < io_tlb_nslabs; i++)
io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
io_tlb_index = 0;
io_tlb_orig_addr = (phys_addr_t *)
__get_free_pages(GFP_KERNEL,
get_order(io_tlb_nslabs *
sizeof(phys_addr_t)));
if (!io_tlb_orig_addr)
goto cleanup3;
memset(io_tlb_orig_addr, 0, io_tlb_nslabs * sizeof(phys_addr_t));
/*
* Get the overflow emergency buffer
*/
io_tlb_overflow_buffer = (void *)__get_free_pages(GFP_DMA,
get_order(io_tlb_overflow));
if (!io_tlb_overflow_buffer)
goto cleanup4;
swiotlb_print_info();
late_alloc = 1;
return 0;
cleanup4:
free_pages((unsigned long)io_tlb_orig_addr,
get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
io_tlb_orig_addr = NULL;
cleanup3:
free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
sizeof(int)));
io_tlb_list = NULL;
cleanup2:
io_tlb_end = NULL;
free_pages((unsigned long)io_tlb_start, order);
io_tlb_start = NULL;
cleanup1:
io_tlb_nslabs = req_nslabs;
return -ENOMEM;
}
void __init swiotlb_free(void)
{
if (!io_tlb_overflow_buffer)
return;
if (late_alloc) {
free_pages((unsigned long)io_tlb_overflow_buffer,
get_order(io_tlb_overflow));
free_pages((unsigned long)io_tlb_orig_addr,
get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
sizeof(int)));
free_pages((unsigned long)io_tlb_start,
get_order(io_tlb_nslabs << IO_TLB_SHIFT));
} else {
free_bootmem_late(__pa(io_tlb_overflow_buffer),
PAGE_ALIGN(io_tlb_overflow));
free_bootmem_late(__pa(io_tlb_orig_addr),
PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
free_bootmem_late(__pa(io_tlb_list),
PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
free_bootmem_late(__pa(io_tlb_start),
PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
}
}
static int is_swiotlb_buffer(phys_addr_t paddr)
{
return paddr >= virt_to_phys(io_tlb_start) &&
paddr < virt_to_phys(io_tlb_end);
}
/*
* Bounce: copy the swiotlb buffer back to the original dma location
*/
void swiotlb_bounce(phys_addr_t phys, char *dma_addr, size_t size,
enum dma_data_direction dir)
{
unsigned long pfn = PFN_DOWN(phys);
if (PageHighMem(pfn_to_page(pfn))) {
/* The buffer does not have a mapping. Map it in and copy */
unsigned int offset = phys & ~PAGE_MASK;
char *buffer;
unsigned int sz = 0;
unsigned long flags;
while (size) {
sz = min_t(size_t, PAGE_SIZE - offset, size);
local_irq_save(flags);
buffer = kmap_atomic(pfn_to_page(pfn),
KM_BOUNCE_READ);
if (dir == DMA_TO_DEVICE)
memcpy(dma_addr, buffer + offset, sz);
else
memcpy(buffer + offset, dma_addr, sz);
kunmap_atomic(buffer, KM_BOUNCE_READ);
local_irq_restore(flags);
size -= sz;
pfn++;
dma_addr += sz;
offset = 0;
}
} else {
if (dir == DMA_TO_DEVICE)
memcpy(dma_addr, phys_to_virt(phys), size);
else
memcpy(phys_to_virt(phys), dma_addr, size);
}
}
EXPORT_SYMBOL_GPL(swiotlb_bounce);
void *swiotlb_tbl_map_single(struct device *hwdev, dma_addr_t tbl_dma_addr,
phys_addr_t phys, size_t size,
enum dma_data_direction dir)
{
unsigned long flags;
char *dma_addr;
unsigned int nslots, stride, index, wrap;
int i;
unsigned long mask;
unsigned long offset_slots;
unsigned long max_slots;
mask = dma_get_seg_boundary(hwdev);
tbl_dma_addr &= mask;
offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
/*
* Carefully handle integer overflow which can occur when mask == ~0UL.
*/
max_slots = mask + 1
? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
: 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
/*
* For mappings greater than a page, we limit the stride (and
* hence alignment) to a page size.
*/
nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
if (size > PAGE_SIZE)
stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
else
stride = 1;
BUG_ON(!nslots);
/*
* Find suitable number of IO TLB entries size that will fit this
* request and allocate a buffer from that IO TLB pool.
*/
spin_lock_irqsave(&io_tlb_lock, flags);
index = ALIGN(io_tlb_index, stride);
if (index >= io_tlb_nslabs)
index = 0;
wrap = index;
do {
while (iommu_is_span_boundary(index, nslots, offset_slots,
max_slots)) {
index += stride;
if (index >= io_tlb_nslabs)
index = 0;
if (index == wrap)
goto not_found;
}
/*
* If we find a slot that indicates we have 'nslots' number of
* contiguous buffers, we allocate the buffers from that slot
* and mark the entries as '0' indicating unavailable.
*/
if (io_tlb_list[index] >= nslots) {
int count = 0;
for (i = index; i < (int) (index + nslots); i++)
io_tlb_list[i] = 0;
for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
io_tlb_list[i] = ++count;
dma_addr = io_tlb_start + (index << IO_TLB_SHIFT);
/*
* Update the indices to avoid searching in the next
* round.
*/
io_tlb_index = ((index + nslots) < io_tlb_nslabs
? (index + nslots) : 0);
goto found;
}
index += stride;
if (index >= io_tlb_nslabs)
index = 0;
} while (index != wrap);
not_found:
spin_unlock_irqrestore(&io_tlb_lock, flags);
return NULL;
found:
spin_unlock_irqrestore(&io_tlb_lock, flags);
/*
* Save away the mapping from the original address to the DMA address.
* This is needed when we sync the memory. Then we sync the buffer if
* needed.
*/
for (i = 0; i < nslots; i++)
io_tlb_orig_addr[index+i] = phys + (i << IO_TLB_SHIFT);
if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
swiotlb_bounce(phys, dma_addr, size, DMA_TO_DEVICE);
return dma_addr;
}
EXPORT_SYMBOL_GPL(swiotlb_tbl_map_single);
/*
* Allocates bounce buffer and returns its kernel virtual address.
*/
static void *
map_single(struct device *hwdev, phys_addr_t phys, size_t size,
enum dma_data_direction dir)
{
dma_addr_t start_dma_addr = swiotlb_virt_to_bus(hwdev, io_tlb_start);
return swiotlb_tbl_map_single(hwdev, start_dma_addr, phys, size, dir);
}
/*
* dma_addr is the kernel virtual address of the bounce buffer to unmap.
*/
void
swiotlb_tbl_unmap_single(struct device *hwdev, char *dma_addr, size_t size,
enum dma_data_direction dir)
{
unsigned long flags;
int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
int index = (dma_addr - io_tlb_start) >> IO_TLB_SHIFT;
phys_addr_t phys = io_tlb_orig_addr[index];
/*
* First, sync the memory before unmapping the entry
*/
if (phys && ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
swiotlb_bounce(phys, dma_addr, size, DMA_FROM_DEVICE);
/*
* Return the buffer to the free list by setting the corresponding
* entries to indicate the number of contiguous entries available.
* While returning the entries to the free list, we merge the entries
* with slots below and above the pool being returned.
*/
spin_lock_irqsave(&io_tlb_lock, flags);
{
count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
io_tlb_list[index + nslots] : 0);
/*
* Step 1: return the slots to the free list, merging the
* slots with superceeding slots
*/
for (i = index + nslots - 1; i >= index; i--)
io_tlb_list[i] = ++count;
/*
* Step 2: merge the returned slots with the preceding slots,
* if available (non zero)
*/
for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
io_tlb_list[i] = ++count;
}
spin_unlock_irqrestore(&io_tlb_lock, flags);
}
EXPORT_SYMBOL_GPL(swiotlb_tbl_unmap_single);
void
swiotlb_tbl_sync_single(struct device *hwdev, char *dma_addr, size_t size,
enum dma_data_direction dir,
enum dma_sync_target target)
{
int index = (dma_addr - io_tlb_start) >> IO_TLB_SHIFT;
phys_addr_t phys = io_tlb_orig_addr[index];
phys += ((unsigned long)dma_addr & ((1 << IO_TLB_SHIFT) - 1));
switch (target) {
case SYNC_FOR_CPU:
if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
swiotlb_bounce(phys, dma_addr, size, DMA_FROM_DEVICE);
else
BUG_ON(dir != DMA_TO_DEVICE);
break;
case SYNC_FOR_DEVICE:
if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
swiotlb_bounce(phys, dma_addr, size, DMA_TO_DEVICE);
else
BUG_ON(dir != DMA_FROM_DEVICE);
break;
default:
BUG();
}
}
EXPORT_SYMBOL_GPL(swiotlb_tbl_sync_single);
void *
swiotlb_alloc_coherent(struct device *hwdev, size_t size,
dma_addr_t *dma_handle, gfp_t flags)
{
dma_addr_t dev_addr;
void *ret;
int order = get_order(size);
u64 dma_mask = DMA_BIT_MASK(32);
if (hwdev && hwdev->coherent_dma_mask)
dma_mask = hwdev->coherent_dma_mask;
ret = (void *)__get_free_pages(flags, order);
if (ret && swiotlb_virt_to_bus(hwdev, ret) + size - 1 > dma_mask) {
/*
* The allocated memory isn't reachable by the device.
*/
free_pages((unsigned long) ret, order);
ret = NULL;
}
if (!ret) {
/*
* We are either out of memory or the device can't DMA to
* GFP_DMA memory; fall back on map_single(), which
* will grab memory from the lowest available address range.
*/
ret = map_single(hwdev, 0, size, DMA_FROM_DEVICE);
if (!ret)
return NULL;
}
memset(ret, 0, size);
dev_addr = swiotlb_virt_to_bus(hwdev, ret);
/* Confirm address can be DMA'd by device */
if (dev_addr + size - 1 > dma_mask) {
printk("hwdev DMA mask = 0x%016Lx, dev_addr = 0x%016Lx\n",
(unsigned long long)dma_mask,
(unsigned long long)dev_addr);
/* DMA_TO_DEVICE to avoid memcpy in unmap_single */
swiotlb_tbl_unmap_single(hwdev, ret, size, DMA_TO_DEVICE);
return NULL;
}
*dma_handle = dev_addr;
return ret;
}
EXPORT_SYMBOL(swiotlb_alloc_coherent);
void
swiotlb_free_coherent(struct device *hwdev, size_t size, void *vaddr,
dma_addr_t dev_addr)
{
phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
WARN_ON(irqs_disabled());
if (!is_swiotlb_buffer(paddr))
free_pages((unsigned long)vaddr, get_order(size));
else
/* DMA_TO_DEVICE to avoid memcpy in swiotlb_tbl_unmap_single */
swiotlb_tbl_unmap_single(hwdev, vaddr, size, DMA_TO_DEVICE);
}
EXPORT_SYMBOL(swiotlb_free_coherent);
static void
swiotlb_full(struct device *dev, size_t size, enum dma_data_direction dir,
int do_panic)
{
/*
* Ran out of IOMMU space for this operation. This is very bad.
* Unfortunately the drivers cannot handle this operation properly.
* unless they check for dma_mapping_error (most don't)
* When the mapping is small enough return a static buffer to limit
* the damage, or panic when the transfer is too big.
*/
printk(KERN_ERR "DMA: Out of SW-IOMMU space for %zu bytes at "
"device %s\n", size, dev ? dev_name(dev) : "?");
if (size <= io_tlb_overflow || !do_panic)
return;
if (dir == DMA_BIDIRECTIONAL)
panic("DMA: Random memory could be DMA accessed\n");
if (dir == DMA_FROM_DEVICE)
panic("DMA: Random memory could be DMA written\n");
if (dir == DMA_TO_DEVICE)
panic("DMA: Random memory could be DMA read\n");
}
/*
* Map a single buffer of the indicated size for DMA in streaming mode. The
* physical address to use is returned.
*
* Once the device is given the dma address, the device owns this memory until
* either swiotlb_unmap_page or swiotlb_dma_sync_single is performed.
*/
dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
phys_addr_t phys = page_to_phys(page) + offset;
dma_addr_t dev_addr = phys_to_dma(dev, phys);
void *map;
BUG_ON(dir == DMA_NONE);
/*
* If the address happens to be in the device's DMA window,
* we can safely return the device addr and not worry about bounce
* buffering it.
*/
if (dma_capable(dev, dev_addr, size) && !swiotlb_force)
return dev_addr;
/*
* Oh well, have to allocate and map a bounce buffer.
*/
map = map_single(dev, phys, size, dir);
if (!map) {
swiotlb_full(dev, size, dir, 1);
map = io_tlb_overflow_buffer;
}
dev_addr = swiotlb_virt_to_bus(dev, map);
/*
* Ensure that the address returned is DMA'ble
*/
if (!dma_capable(dev, dev_addr, size))
panic("map_single: bounce buffer is not DMA'ble");
return dev_addr;
}
EXPORT_SYMBOL_GPL(swiotlb_map_page);
/*
* Unmap a single streaming mode DMA translation. The dma_addr and size must
* match what was provided for in a previous swiotlb_map_page call. All
* other usages are undefined.
*
* After this call, reads by the cpu to the buffer are guaranteed to see
* whatever the device wrote there.
*/
static void unmap_single(struct device *hwdev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir)
{
phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
BUG_ON(dir == DMA_NONE);
if (is_swiotlb_buffer(paddr)) {
swiotlb_tbl_unmap_single(hwdev, phys_to_virt(paddr), size, dir);
return;
}
if (dir != DMA_FROM_DEVICE)
return;
/*
* phys_to_virt doesn't work with hihgmem page but we could
* call dma_mark_clean() with hihgmem page here. However, we
* are fine since dma_mark_clean() is null on POWERPC. We can
* make dma_mark_clean() take a physical address if necessary.
*/
dma_mark_clean(phys_to_virt(paddr), size);
}
void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
unmap_single(hwdev, dev_addr, size, dir);
}
EXPORT_SYMBOL_GPL(swiotlb_unmap_page);
/*
* Make physical memory consistent for a single streaming mode DMA translation
* after a transfer.
*
* If you perform a swiotlb_map_page() but wish to interrogate the buffer
* using the cpu, yet do not wish to teardown the dma mapping, you must
* call this function before doing so. At the next point you give the dma
* address back to the card, you must first perform a
* swiotlb_dma_sync_for_device, and then the device again owns the buffer
*/
static void
swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir,
enum dma_sync_target target)
{
phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
BUG_ON(dir == DMA_NONE);
if (is_swiotlb_buffer(paddr)) {
swiotlb_tbl_sync_single(hwdev, phys_to_virt(paddr), size, dir,
target);
return;
}
if (dir != DMA_FROM_DEVICE)
return;
dma_mark_clean(phys_to_virt(paddr), size);
}
void
swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir)
{
swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU);
}
EXPORT_SYMBOL(swiotlb_sync_single_for_cpu);
void
swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir)
{
swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE);
}
EXPORT_SYMBOL(swiotlb_sync_single_for_device);
/*
* Map a set of buffers described by scatterlist in streaming mode for DMA.
* This is the scatter-gather version of the above swiotlb_map_page
* interface. Here the scatter gather list elements are each tagged with the
* appropriate dma address and length. They are obtained via
* sg_dma_{address,length}(SG).
*
* NOTE: An implementation may be able to use a smaller number of
* DMA address/length pairs than there are SG table elements.
* (for example via virtual mapping capabilities)
* The routine returns the number of addr/length pairs actually
* used, at most nents.
*
* Device ownership issues as mentioned above for swiotlb_map_page are the
* same here.
*/
int
swiotlb_map_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i;
BUG_ON(dir == DMA_NONE);
for_each_sg(sgl, sg, nelems, i) {
phys_addr_t paddr = sg_phys(sg);
dma_addr_t dev_addr = phys_to_dma(hwdev, paddr);
if (swiotlb_force ||
!dma_capable(hwdev, dev_addr, sg->length)) {
void *map = map_single(hwdev, sg_phys(sg),
sg->length, dir);
if (!map) {
/* Don't panic here, we expect map_sg users
to do proper error handling. */
swiotlb_full(hwdev, sg->length, dir, 0);
swiotlb_unmap_sg_attrs(hwdev, sgl, i, dir,
attrs);
sgl[0].dma_length = 0;
return 0;
}
sg->dma_address = swiotlb_virt_to_bus(hwdev, map);
} else
sg->dma_address = dev_addr;
sg->dma_length = sg->length;
}
return nelems;
}
EXPORT_SYMBOL(swiotlb_map_sg_attrs);
int
swiotlb_map_sg(struct device *hwdev, struct scatterlist *sgl, int nelems,
enum dma_data_direction dir)
{
return swiotlb_map_sg_attrs(hwdev, sgl, nelems, dir, NULL);
}
EXPORT_SYMBOL(swiotlb_map_sg);
/*
* Unmap a set of streaming mode DMA translations. Again, cpu read rules
* concerning calls here are the same as for swiotlb_unmap_page() above.
*/
void
swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl,
int nelems, enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i;
BUG_ON(dir == DMA_NONE);
for_each_sg(sgl, sg, nelems, i)
unmap_single(hwdev, sg->dma_address, sg->dma_length, dir);
}
EXPORT_SYMBOL(swiotlb_unmap_sg_attrs);
void
swiotlb_unmap_sg(struct device *hwdev, struct scatterlist *sgl, int nelems,
enum dma_data_direction dir)
{
return swiotlb_unmap_sg_attrs(hwdev, sgl, nelems, dir, NULL);
}
EXPORT_SYMBOL(swiotlb_unmap_sg);
/*
* Make physical memory consistent for a set of streaming mode DMA translations
* after a transfer.
*
* The same as swiotlb_sync_single_* but for a scatter-gather list, same rules
* and usage.
*/
static void
swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl,
int nelems, enum dma_data_direction dir,
enum dma_sync_target target)
{
struct scatterlist *sg;
int i;
for_each_sg(sgl, sg, nelems, i)
swiotlb_sync_single(hwdev, sg->dma_address,
sg->dma_length, dir, target);
}
void
swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
int nelems, enum dma_data_direction dir)
{
swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU);
}
EXPORT_SYMBOL(swiotlb_sync_sg_for_cpu);
void
swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
int nelems, enum dma_data_direction dir)
{
swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE);
}
EXPORT_SYMBOL(swiotlb_sync_sg_for_device);
int
swiotlb_dma_mapping_error(struct device *hwdev, dma_addr_t dma_addr)
{
return (dma_addr == swiotlb_virt_to_bus(hwdev, io_tlb_overflow_buffer));
}
EXPORT_SYMBOL(swiotlb_dma_mapping_error);
/*
* Return whether the given device DMA address mask can be supported
* properly. For example, if your device can only drive the low 24-bits
* during bus mastering, then you would pass 0x00ffffff as the mask to
* this function.
*/
int
swiotlb_dma_supported(struct device *hwdev, u64 mask)
{
return swiotlb_virt_to_bus(hwdev, io_tlb_end - 1) <= mask;
}
EXPORT_SYMBOL(swiotlb_dma_supported);
| gpl-2.0 |
roadlabs/limbo-android | jni/glib/glib/gdir.c | 48 | 6937 | /* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* gdir.c: Simplified wrapper around the DIRENT functions.
*
* Copyright 2001 Hans Breuer
* Copyright 2004 Tor Lillqvist
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "config.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#ifdef HAVE_DIRENT_H
#include <sys/types.h>
#include <dirent.h>
#endif
#include "gdir.h"
#include "gconvert.h"
#include "gfileutils.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
#include "glibintl.h"
#if defined (_MSC_VER) && !defined (HAVE_DIRENT_H)
#include "../build/win32/dirent/dirent.h"
#include "../build/win32/dirent/wdirent.c"
#endif
struct _GDir
{
#ifdef G_OS_WIN32
_WDIR *wdirp;
#else
DIR *dirp;
#endif
#ifdef G_OS_WIN32
gchar utf8_buf[FILENAME_MAX*4];
#endif
};
/**
* g_dir_open:
* @path: the path to the directory you are interested in. On Unix
* in the on-disk encoding. On Windows in UTF-8
* @flags: Currently must be set to 0. Reserved for future use.
* @error: return location for a #GError, or %NULL.
* If non-%NULL, an error will be set if and only if
* g_dir_open() fails.
*
* Opens a directory for reading. The names of the files in the
* directory can then be retrieved using g_dir_read_name(). Note
* that the ordering is not defined.
*
* Return value: a newly allocated #GDir on success, %NULL on failure.
* If non-%NULL, you must free the result with g_dir_close()
* when you are finished with it.
**/
GDir *
g_dir_open (const gchar *path,
guint flags,
GError **error)
{
GDir *dir;
int errsv;
#ifdef G_OS_WIN32
wchar_t *wpath;
#else
gchar *utf8_path;
#endif
g_return_val_if_fail (path != NULL, NULL);
#ifdef G_OS_WIN32
wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
if (wpath == NULL)
return NULL;
dir = g_new (GDir, 1);
dir->wdirp = _wopendir (wpath);
g_free (wpath);
if (dir->wdirp)
return dir;
/* error case */
errsv = errno;
g_set_error (error,
G_FILE_ERROR,
g_file_error_from_errno (errsv),
_("Error opening directory '%s': %s"),
path, g_strerror (errsv));
g_free (dir);
return NULL;
#else
dir = g_new (GDir, 1);
dir->dirp = opendir (path);
if (dir->dirp)
return dir;
/* error case */
errsv = errno;
utf8_path = g_filename_to_utf8 (path, -1,
NULL, NULL, NULL);
g_set_error (error,
G_FILE_ERROR,
g_file_error_from_errno (errsv),
_("Error opening directory '%s': %s"),
utf8_path, g_strerror (errsv));
g_free (utf8_path);
g_free (dir);
return NULL;
#endif
}
#if defined (G_OS_WIN32) && !defined (_WIN64)
/* The above function actually is called g_dir_open_utf8, and it's
* that what applications compiled with this GLib version will
* use.
*/
#undef g_dir_open
/* Binary compatibility version. Not for newly compiled code. */
GDir *
g_dir_open (const gchar *path,
guint flags,
GError **error)
{
gchar *utf8_path = g_locale_to_utf8 (path, -1, NULL, NULL, error);
GDir *retval;
if (utf8_path == NULL)
return NULL;
retval = g_dir_open_utf8 (utf8_path, flags, error);
g_free (utf8_path);
return retval;
}
#endif
/**
* g_dir_read_name:
* @dir: a #GDir* created by g_dir_open()
*
* Retrieves the name of another entry in the directory, or %NULL.
* The order of entries returned from this function is not defined,
* and may vary by file system or other operating-system dependent
* factors.
*
* On Unix, the '.' and '..' entries are omitted, and the returned
* name is in the on-disk encoding.
*
* On Windows, as is true of all GLib functions which operate on
* filenames, the returned name is in UTF-8.
*
* Return value: The entry's name or %NULL if there are no
* more entries. The return value is owned by GLib and
* must not be modified or freed.
**/
G_CONST_RETURN gchar*
g_dir_read_name (GDir *dir)
{
#ifdef G_OS_WIN32
gchar *utf8_name;
struct _wdirent *wentry;
#else
struct dirent *entry;
#endif
g_return_val_if_fail (dir != NULL, NULL);
#ifdef G_OS_WIN32
while (1)
{
wentry = _wreaddir (dir->wdirp);
while (wentry
&& (0 == wcscmp (wentry->d_name, L".") ||
0 == wcscmp (wentry->d_name, L"..")))
wentry = _wreaddir (dir->wdirp);
if (wentry == NULL)
return NULL;
utf8_name = g_utf16_to_utf8 (wentry->d_name, -1, NULL, NULL, NULL);
if (utf8_name == NULL)
continue; /* Huh, impossible? Skip it anyway */
strcpy (dir->utf8_buf, utf8_name);
g_free (utf8_name);
return dir->utf8_buf;
}
#else
entry = readdir (dir->dirp);
while (entry
&& (0 == strcmp (entry->d_name, ".") ||
0 == strcmp (entry->d_name, "..")))
entry = readdir (dir->dirp);
if (entry)
return entry->d_name;
else
return NULL;
#endif
}
#if defined (G_OS_WIN32) && !defined (_WIN64)
/* Ditto for g_dir_read_name */
#undef g_dir_read_name
/* Binary compatibility version. Not for newly compiled code. */
G_CONST_RETURN gchar*
g_dir_read_name (GDir *dir)
{
while (1)
{
const gchar *utf8_name = g_dir_read_name_utf8 (dir);
gchar *retval;
if (utf8_name == NULL)
return NULL;
retval = g_locale_from_utf8 (utf8_name, -1, NULL, NULL, NULL);
if (retval != NULL)
{
strcpy (dir->utf8_buf, retval);
g_free (retval);
return dir->utf8_buf;
}
}
}
#endif
/**
* g_dir_rewind:
* @dir: a #GDir* created by g_dir_open()
*
* Resets the given directory. The next call to g_dir_read_name()
* will return the first entry again.
**/
void
g_dir_rewind (GDir *dir)
{
g_return_if_fail (dir != NULL);
#ifdef G_OS_WIN32
_wrewinddir (dir->wdirp);
#else
rewinddir (dir->dirp);
#endif
}
/**
* g_dir_close:
* @dir: a #GDir* created by g_dir_open()
*
* Closes the directory and deallocates all related resources.
**/
void
g_dir_close (GDir *dir)
{
g_return_if_fail (dir != NULL);
#ifdef G_OS_WIN32
_wclosedir (dir->wdirp);
#else
closedir (dir->dirp);
#endif
g_free (dir);
}
| gpl-2.0 |
alma-siwon/Solid_Kernel-GPROJ | drivers/input/rmi4/rmi_f11.c | 48 | 47770 | /*
* Copyright (c) 2011 Synaptics Incorporated
* Copyright (c) 2011 Unixphere
*
* 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/slab.h>
#include <linux/input.h>
#include <linux/rmi.h>
#define RESUME_REZERO (1 && defined(CONFIG_PM))
#if RESUME_REZERO
#include <linux/delay.h>
#define DEFAULT_REZERO_WAIT_MS 40
#endif
#ifndef MT_TOOL_MAX
#define MT_TOOL_MAX MT_TOOL_PEN
#endif
#define F11_MAX_NUM_OF_SENSORS 8
#define F11_MAX_NUM_OF_FINGERS 10
#define F11_MAX_NUM_OF_TOUCH_SHAPES 16
#define F11_REL_POS_MIN -128
#define F11_REL_POS_MAX 127
#define FINGER_STATE_MASK 0x03
#define GET_FINGER_STATE(f_states, i) \
((f_states[i / 4] >> (2 * (i % 4))) & FINGER_STATE_MASK)
#define F11_CTRL_SENSOR_MAX_X_POS_OFFSET 6
#define F11_CTRL_SENSOR_MAX_Y_POS_OFFSET 8
#define F11_CEIL(x, y) (((x) + ((y)-1)) / (y))
#define INBOX(x, y, box) (x >= box.x && x < (box.x + box.width) \
&& y >= box.y && y < (box.y + box.height))
#define DEFAULT_XY_MAX 9999
#define DEFAULT_MAX_ABS_MT_PRESSURE 255
#define DEFAULT_MAX_ABS_MT_TOUCH 15
#define DEFAULT_MAX_ABS_MT_ORIENTATION 1
#define DEFAULT_MIN_ABS_MT_TRACKING_ID 1
#define DEFAULT_MAX_ABS_MT_TRACKING_ID 10
#define MAX_NAME_LENGTH 256
static ssize_t f11_flip_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t f11_flip_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_clip_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t f11_clip_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_offset_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t f11_offset_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_swap_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t f11_swap_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_relreport_show(struct device *dev,
struct device_attribute *attr,
char *buf);
static ssize_t f11_relreport_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_maxPos_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t f11_rezero_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
#if RESUME_REZERO
static ssize_t f11_rezeroOnResume_show(struct device *dev,
struct device_attribute *attr,
char *buf);
static ssize_t f11_rezeroOnResume_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
static ssize_t f11_rezeroWait_show(struct device *dev,
struct device_attribute *attr,
char *buf);
static ssize_t f11_rezeroWait_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count);
#endif
static void rmi_f11_free_memory(struct rmi_function_container *fc);
static int rmi_f11_initialize(struct rmi_function_container *fc);
static int rmi_f11_create_sysfs(struct rmi_function_container *fc);
static int rmi_f11_config(struct rmi_function_container *fc);
static int rmi_f11_reset(struct rmi_function_container *fc);
static int rmi_f11_register_devices(struct rmi_function_container *fc);
static void rmi_f11_free_devices(struct rmi_function_container *fc);
static struct device_attribute attrs[] = {
__ATTR(flip, RMI_RW_ATTR, f11_flip_show, f11_flip_store),
__ATTR(clip, RMI_RW_ATTR, f11_clip_show, f11_clip_store),
__ATTR(offset, RMI_RW_ATTR, f11_offset_show, f11_offset_store),
__ATTR(swap, RMI_RW_ATTR, f11_swap_show, f11_swap_store),
__ATTR(relreport, RMI_RW_ATTR, f11_relreport_show, f11_relreport_store),
__ATTR(maxPos, RMI_RO_ATTR, f11_maxPos_show, rmi_store_error),
#if RESUME_REZERO
__ATTR(rezeroOnResume, RMI_RW_ATTR, f11_rezeroOnResume_show,
f11_rezeroOnResume_store),
__ATTR(rezeroWait, RMI_RW_ATTR, f11_rezeroWait_show,
f11_rezeroWait_store),
#endif
__ATTR(rezero, RMI_WO_ATTR, rmi_show_error, f11_rezero_store)
};
union f11_2d_commands {
struct {
u8 rezero:1;
};
u8 reg;
};
struct f11_2d_device_query {
union {
struct {
u8 nbr_of_sensors:3;
u8 has_query9:1;
u8 has_query11:1;
};
u8 f11_2d_query0;
};
union {
struct {
u8 has_z_tuning:1;
u8 has_pos_interpolation_tuning:1;
u8 has_w_tuning:1;
u8 has_pitch_info:1;
u8 has_default_finger_width:1;
u8 has_segmentation_aggressiveness:1;
u8 has_tx_rw_clip:1;
u8 has_drumming_correction:1;
};
u8 f11_2d_query11;
};
};
union f11_2d_query9 {
struct {
u8 has_pen:1;
u8 has_proximity:1;
u8 has_palm_det_sensitivity:1;
u8 has_suppress_on_palm_detect:1;
u8 has_two_pen_thresholds:1;
u8 has_contact_geometry:1;
};
u8 reg;
};
struct f11_2d_sensor_query {
union {
struct {
/* query1 */
u8 number_of_fingers:3;
u8 has_rel:1;
u8 has_abs:1;
u8 has_gestures:1;
u8 has_sensitivity_adjust:1;
u8 configurable:1;
/* query2 */
u8 num_of_x_electrodes:7;
/* query3 */
u8 num_of_y_electrodes:7;
/* query4 */
u8 max_electrodes:7;
};
u8 f11_2d_query1__4[4];
};
union {
struct {
u8 abs_data_size:3;
u8 has_anchored_finger:1;
u8 has_adj_hyst:1;
u8 has_dribble:1;
};
u8 f11_2d_query5;
};
u8 f11_2d_query6;
union {
struct {
u8 has_single_tap:1;
u8 has_tap_n_hold:1;
u8 has_double_tap:1;
u8 has_early_tap:1;
u8 has_flick:1;
u8 has_press:1;
u8 has_pinch:1;
u8 padding:1;
u8 has_palm_det:1;
u8 has_rotate:1;
u8 has_touch_shapes:1;
u8 has_scroll_zones:1;
u8 has_individual_scroll_zones:1;
u8 has_multi_finger_scroll:1;
};
u8 f11_2d_query7__8[2];
};
union f11_2d_query9 query9;
union {
struct {
u8 nbr_touch_shapes:5;
};
u8 f11_2d_query10;
};
};
union f11_2d_ctrl10 {
struct {
u8 single_tap_int_enable:1;
u8 tap_n_hold_int_enable:1;
u8 double_tap_int_enable:1;
u8 early_tap_int_enable:1;
u8 flick_int_enable:1;
u8 press_int_enable:1;
u8 pinch_int_enable:1;
};
u8 reg;
};
union f11_2d_ctrl11 {
struct {
u8 palm_detect_int_enable:1;
u8 rotate_int_enable:1;
u8 touch_shape_int_enable:1;
u8 scroll_zone_int_enable:1;
u8 multi_finger_scroll_int_enable:1;
};
u8 reg;
};
union f11_2d_ctrl12 {
struct {
u8 sensor_map:7;
u8 xy_sel:1;
};
u8 reg;
};
union f11_2d_ctrl14 {
struct {
u8 sens_adjustment:5;
u8 hyst_adjustment:3;
};
u8 reg;
};
union f11_2d_ctrl15 {
struct {
u8 max_tap_time:8;
};
u8 reg;
};
union f11_2d_ctrl16 {
struct {
u8 min_press_time:8;
};
u8 reg;
};
union f11_2d_ctrl17 {
struct {
u8 max_tap_distance:8;
};
u8 reg;
};
union f11_2d_ctrl18_19 {
struct {
u8 min_flick_distance:8;
u8 min_flick_speed:8;
};
u8 reg[2];
};
union f11_2d_ctrl20_21 {
struct {
u8 pen_detect_enable:1;
u8 pen_jitter_filter_enable:1;
u8 ctrl20_reserved:6;
u8 pen_z_threshold:8;
};
u8 reg[2];
};
struct f11_2d_ctrl {
union {
struct {
/* F11_2D_Ctrl0 */
u8 reporting_mode:3;
u8 abs_pos_filt:1;
u8 rel_pos_filt:1;
u8 rel_ballistics:1;
u8 dribble:1;
u8 report_beyond_clip:1;
/* F11_2D_Ctrl1 */
u8 palm_detect_thres:4;
u8 motion_sensitivity:2;
u8 man_track_en:1;
u8 man_tracked_finger:1;
/* F11_2D_Ctrl2 and 3 */
u8 delta_x_threshold:8;
u8 delta_y_threshold:8;
/* F11_2D_Ctrl4 and 5 */
u8 velocity:8;
u8 acceleration:8;
/* F11_2D_Ctrl6 thru 9 */
u16 sensor_max_x_pos:12;
u8 ctrl7_reserved:4;
u16 sensor_max_y_pos:12;
u8 ctrl9_reserved:4;
};
u8 ctrl0_9[10];
};
union f11_2d_ctrl10 *ctrl10;
union f11_2d_ctrl11 *ctrl11;
union f11_2d_ctrl12 *ctrl12;
u8 ctrl12_size;
union f11_2d_ctrl14 *ctrl14;
union f11_2d_ctrl15 *ctrl15;
union f11_2d_ctrl16 *ctrl16;
union f11_2d_ctrl17 *ctrl17;
union f11_2d_ctrl18_19 *ctrl18_19;
union f11_2d_ctrl20_21 *ctrl20_21;
};
struct f11_2d_data_1_5 {
u8 x_msb;
u8 y_msb;
u8 x_lsb:4;
u8 y_lsb:4;
u8 w_y:4;
u8 w_x:4;
u8 z;
};
struct f11_2d_data_6_7 {
s8 delta_x;
s8 delta_y;
};
struct f11_2d_data_8 {
u8 single_tap:1;
u8 tap_and_hold:1;
u8 double_tap:1;
u8 early_tap:1;
u8 flick:1;
u8 press:1;
u8 pinch:1;
};
struct f11_2d_data_9 {
u8 palm_detect:1;
u8 rotate:1;
u8 shape:1;
u8 scrollzone:1;
u8 finger_count:3;
};
struct f11_2d_data_10 {
u8 pinch_motion;
};
struct f11_2d_data_10_12 {
u8 x_flick_dist;
u8 y_flick_dist;
u8 flick_time;
};
struct f11_2d_data_11_12 {
u8 motion;
u8 finger_separation;
};
struct f11_2d_data_13 {
u8 shape_n;
};
struct f11_2d_data_14_15 {
u8 horizontal;
u8 vertical;
};
struct f11_2d_data_14_17 {
u8 x_low;
u8 y_right;
u8 x_upper;
u8 y_left;
};
struct f11_2d_data {
u8 *f_state;
const struct f11_2d_data_1_5 *abs_pos;
const struct f11_2d_data_6_7 *rel_pos;
const struct f11_2d_data_8 *gest_1;
const struct f11_2d_data_9 *gest_2;
const struct f11_2d_data_10 *pinch;
const struct f11_2d_data_10_12 *flick;
const struct f11_2d_data_11_12 *rotate;
const struct f11_2d_data_13 *shapes;
const struct f11_2d_data_14_15 *multi_scroll;
const struct f11_2d_data_14_17 *scroll_zones;
};
struct f11_2d_sensor {
struct rmi_f11_2d_axis_alignment axis_align;
struct f11_2d_sensor_query sens_query;
struct f11_2d_data data;
u16 max_x;
u16 max_y;
u8 nbr_fingers;
u8 finger_tracker[F11_MAX_NUM_OF_FINGERS];
u8 *data_pkt;
int pkt_size;
u8 sensor_index;
struct rmi_f11_virtualbutton_map virtualbutton_map;
char input_name[MAX_NAME_LENGTH];
char input_phys[MAX_NAME_LENGTH];
struct input_dev *input;
struct input_dev *mouse_input;
};
struct f11_data {
struct f11_2d_device_query dev_query;
struct f11_2d_ctrl dev_controls;
#if RESUME_REZERO
u16 rezero_wait_ms;
bool rezero_on_resume;
#endif
struct f11_2d_sensor sensors[F11_MAX_NUM_OF_SENSORS];
};
enum finger_state_values {
F11_NO_FINGER = 0x00,
F11_PRESENT = 0x01,
F11_INACCURATE = 0x02,
F11_RESERVED = 0x03
};
/** F11_INACCURATE state is overloaded to indicate pen present. */
#define F11_PEN F11_INACCURATE
static int get_tool_type(struct f11_2d_sensor *sensor, u8 finger_state) {
if (sensor->sens_query.query9.has_pen && finger_state == F11_PEN)
return MT_TOOL_PEN;
return MT_TOOL_FINGER;
}
static void rmi_f11_rel_pos_report(struct f11_2d_sensor *sensor, u8 n_finger)
{
struct f11_2d_data *data = &sensor->data;
struct rmi_f11_2d_axis_alignment *axis_align = &sensor->axis_align;
s8 x, y;
s8 temp;
x = data->rel_pos[n_finger].delta_x;
y = data->rel_pos[n_finger].delta_y;
x = min(F11_REL_POS_MAX, max(F11_REL_POS_MIN, (int)x));
y = min(F11_REL_POS_MAX, max(F11_REL_POS_MIN, (int)y));
if (axis_align->swap_axes) {
temp = x;
x = y;
y = temp;
}
if (axis_align->flip_x)
x = min(F11_REL_POS_MAX, -x);
if (axis_align->flip_y)
y = min(F11_REL_POS_MAX, -y);
if (x || y) {
input_report_rel(sensor->input, REL_X, x);
input_report_rel(sensor->input, REL_Y, y);
input_report_rel(sensor->mouse_input, REL_X, x);
input_report_rel(sensor->mouse_input, REL_Y, y);
}
input_sync(sensor->mouse_input);
}
static void rmi_f11_abs_pos_report(struct f11_2d_sensor *sensor,
u8 finger_state, u8 n_finger)
{
struct f11_2d_data *data = &sensor->data;
struct rmi_f11_2d_axis_alignment *axis_align = &sensor->axis_align;
int prev_state = sensor->finger_tracker[n_finger];
int x, y, z;
int w_x, w_y, w_max, w_min, orient;
int temp;
if (prev_state && !finger_state) {
/* this is a release */
x = y = z = w_max = w_min = orient = 0;
} else if (!prev_state && !finger_state) {
/* nothing to report */
return;
} else {
x = ((data->abs_pos[n_finger].x_msb << 4) |
data->abs_pos[n_finger].x_lsb);
y = ((data->abs_pos[n_finger].y_msb << 4) |
data->abs_pos[n_finger].y_lsb);
z = data->abs_pos[n_finger].z;
w_x = data->abs_pos[n_finger].w_x;
w_y = data->abs_pos[n_finger].w_y;
w_max = max(w_x, w_y);
w_min = min(w_x, w_y);
if (axis_align->swap_axes) {
temp = x;
x = y;
y = temp;
temp = w_x;
w_x = w_y;
w_y = temp;
}
orient = w_x > w_y ? 1 : 0;
if (axis_align->flip_x)
x = max(sensor->max_x - x, 0);
if (axis_align->flip_y)
y = max(sensor->max_y - y, 0);
/*
** here checking if X offset or y offset are specified is
** redundant. We just add the offsets or, clip the values
**
** note: offsets need to be done before clipping occurs,
** or we could get funny values that are outside
** clipping boundaries.
*/
x += axis_align->offset_X;
y += axis_align->offset_Y;
x = max(axis_align->clip_X_low, x);
y = max(axis_align->clip_Y_low, y);
if (axis_align->clip_X_high)
x = min(axis_align->clip_X_high, x);
if (axis_align->clip_Y_high)
y = min(axis_align->clip_Y_high, y);
}
pr_debug("%s: f_state[%d]:%d - x:%d y:%d z:%d w_max:%d w_min:%d\n",
__func__, n_finger, finger_state, x, y, z, w_max, w_min);
#ifndef CONFIG_RMI4_F11_PEN
/* Some UIs ignore W of zero, so we fudge it to 1 for pens. */
if (sensor->sens_query.query9.has_pen &&
get_tool_type(sensor, finger_state) == MT_TOOL_PEN) {
w_max = max(1, w_max);
w_min = max(1, w_min);
}
#endif
#ifdef ABS_MT_PRESSURE
input_report_abs(sensor->input, ABS_MT_PRESSURE, z);
#endif
input_report_abs(sensor->input, ABS_MT_TOUCH_MAJOR, w_max);
input_report_abs(sensor->input, ABS_MT_TOUCH_MINOR, w_min);
input_report_abs(sensor->input, ABS_MT_ORIENTATION, orient);
input_report_abs(sensor->input, ABS_MT_POSITION_X, x);
input_report_abs(sensor->input, ABS_MT_POSITION_Y, y);
input_report_abs(sensor->input, ABS_MT_TRACKING_ID, n_finger);
#ifdef CONFIG_RMI4_F11_PEN
if (sensor->sens_query.query9.has_pen) {
input_report_abs(sensor->input, ABS_MT_TOOL_TYPE,
get_tool_type(sensor, finger_state));
}
#endif
/* MT sync between fingers */
input_mt_sync(sensor->input);
sensor->finger_tracker[n_finger] = finger_state;
}
#ifdef CONFIG_RMI4_VIRTUAL_BUTTON
static int rmi_f11_virtual_button_handler(struct f11_2d_sensor *sensor)
{
int i;
int x;
int y;
struct rmi_f11_virtualbutton_map *virtualbutton_map;
if (sensor->sens_query.has_gestures &&
sensor->data.gest_1->single_tap) {
virtualbutton_map = &sensor->virtualbutton_map;
x = ((sensor->data.abs_pos[0].x_msb << 4) |
sensor->data.abs_pos[0].x_lsb);
y = ((sensor->data.abs_pos[0].y_msb << 4) |
sensor->data.abs_pos[0].y_lsb);
for (i = 0; i < virtualbutton_map->buttons; i++) {
if (INBOX(x, y, virtualbutton_map->map[i])) {
input_report_key(sensor->input,
virtualbutton_map->map[i].code, 1);
input_report_key(sensor->input,
virtualbutton_map->map[i].code, 0);
input_sync(sensor->input);
return 0;
}
}
}
return 0;
}
#else
#define rmi_f11_virtual_button_handler(sensor)
#endif
static void rmi_f11_finger_handler(struct f11_2d_sensor *sensor)
{
const u8 *f_state = sensor->data.f_state;
u8 finger_state;
u8 finger_pressed_count;
u8 i;
for (i = 0, finger_pressed_count = 0; i < sensor->nbr_fingers; i++) {
/* Possible of having 4 fingers per f_statet register */
finger_state = GET_FINGER_STATE(f_state, i);
if (finger_state == F11_RESERVED) {
pr_err("%s: Invalid finger state[%d]:0x%02x.", __func__,
i, finger_state);
continue;
} else if ((finger_state == F11_PRESENT) ||
(finger_state == F11_INACCURATE)) {
finger_pressed_count++;
}
if (sensor->data.abs_pos)
rmi_f11_abs_pos_report(sensor, finger_state, i);
if (sensor->data.rel_pos)
rmi_f11_rel_pos_report(sensor, i);
}
input_report_key(sensor->input, BTN_TOUCH, finger_pressed_count);
input_sync(sensor->input);
}
static int f11_2d_construct_data(struct f11_2d_sensor *sensor)
{
struct f11_2d_sensor_query *query = &sensor->sens_query;
struct f11_2d_data *data = &sensor->data;
int i;
sensor->nbr_fingers = (query->number_of_fingers == 5 ? 10 :
query->number_of_fingers + 1);
sensor->pkt_size = F11_CEIL(sensor->nbr_fingers, 4);
if (query->has_abs)
sensor->pkt_size += (sensor->nbr_fingers * 5);
if (query->has_rel)
sensor->pkt_size += (sensor->nbr_fingers * 2);
/* Check if F11_2D_Query7 is non-zero */
if (query->f11_2d_query7__8[0])
sensor->pkt_size += sizeof(u8);
/* Check if F11_2D_Query7 or F11_2D_Query8 is non-zero */
if (query->f11_2d_query7__8[0] || query->f11_2d_query7__8[1])
sensor->pkt_size += sizeof(u8);
if (query->has_pinch || query->has_flick || query->has_rotate) {
sensor->pkt_size += 3;
if (!query->has_flick)
sensor->pkt_size--;
if (!query->has_rotate)
sensor->pkt_size--;
}
if (query->has_touch_shapes)
sensor->pkt_size += F11_CEIL(query->nbr_touch_shapes + 1, 8);
sensor->data_pkt = kzalloc(sensor->pkt_size, GFP_KERNEL);
if (!sensor->data_pkt)
return -ENOMEM;
data->f_state = sensor->data_pkt;
i = F11_CEIL(sensor->nbr_fingers, 4);
if (query->has_abs) {
data->abs_pos = (struct f11_2d_data_1_5 *)
&sensor->data_pkt[i];
i += (sensor->nbr_fingers * 5);
}
if (query->has_rel) {
data->rel_pos = (struct f11_2d_data_6_7 *)
&sensor->data_pkt[i];
i += (sensor->nbr_fingers * 2);
}
if (query->f11_2d_query7__8[0]) {
data->gest_1 = (struct f11_2d_data_8 *)&sensor->data_pkt[i];
i++;
}
if (query->f11_2d_query7__8[0] || query->f11_2d_query7__8[1]) {
data->gest_2 = (struct f11_2d_data_9 *)&sensor->data_pkt[i];
i++;
}
if (query->has_pinch) {
data->pinch = (struct f11_2d_data_10 *)&sensor->data_pkt[i];
i++;
}
if (query->has_flick) {
if (query->has_pinch) {
data->flick = (struct f11_2d_data_10_12 *)data->pinch;
i += 2;
} else {
data->flick = (struct f11_2d_data_10_12 *)
&sensor->data_pkt[i];
i += 3;
}
}
if (query->has_rotate) {
if (query->has_flick) {
data->rotate = (struct f11_2d_data_11_12 *)
(data->flick + 1);
} else {
data->rotate = (struct f11_2d_data_11_12 *)
&sensor->data_pkt[i];
i += 2;
}
}
if (query->has_touch_shapes)
data->shapes = (struct f11_2d_data_13 *)&sensor->data_pkt[i];
return 0;
}
static void f11_free_control_regs(struct f11_2d_ctrl *ctrl)
{
kfree(ctrl->ctrl10);
kfree(ctrl->ctrl11);
kfree(ctrl->ctrl14);
kfree(ctrl->ctrl15);
kfree(ctrl->ctrl16);
kfree(ctrl->ctrl17);
kfree(ctrl->ctrl18_19);
kfree(ctrl->ctrl20_21);
ctrl->ctrl10 = NULL;
ctrl->ctrl11 = NULL;
ctrl->ctrl14 = NULL;
ctrl->ctrl15 = NULL;
ctrl->ctrl16 = NULL;
ctrl->ctrl17 = NULL;
ctrl->ctrl18_19 = NULL;
ctrl->ctrl20_21 = NULL;
}
static int f11_read_control_regs(struct rmi_device *rmi_dev,
struct f11_2d_ctrl *ctrl,
int ctrl_base_addr) {
int read_address = ctrl_base_addr;
int error = 0;
error = rmi_read_block(rmi_dev, read_address, ctrl->ctrl0_9,
sizeof(ctrl->ctrl0_9));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl0, code: %d.\n", error);
return error;
}
read_address = read_address + sizeof(ctrl->ctrl0_9);
if (ctrl->ctrl10) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl10->reg, sizeof(union f11_2d_ctrl10));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl10, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl10);
}
if (ctrl->ctrl11) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl11->reg, sizeof(union f11_2d_ctrl11));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl11, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl11);
}
if (ctrl->ctrl14) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl14->reg, sizeof(union f11_2d_ctrl14));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl14, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl14);
}
if (ctrl->ctrl15) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl15->reg, sizeof(union f11_2d_ctrl15));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl15, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl15);
}
if (ctrl->ctrl16) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl16->reg, sizeof(union f11_2d_ctrl16));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl16, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl16);
}
if (ctrl->ctrl17) {
error = rmi_read_block(rmi_dev, read_address,
&ctrl->ctrl17->reg, sizeof(union f11_2d_ctrl17));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl17, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl17);
}
if (ctrl->ctrl18_19) {
error = rmi_read_block(rmi_dev, read_address,
ctrl->ctrl18_19->reg, sizeof(union f11_2d_ctrl18_19));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl18_19, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl18_19);
}
if (ctrl->ctrl20_21) {
error = rmi_read_block(rmi_dev, read_address,
ctrl->ctrl20_21->reg, sizeof(union f11_2d_ctrl20_21));
if (error < 0) {
dev_err(&rmi_dev->dev,
"Failed to read F11 ctrl20_21, code: %d.\n",
error);
return error;
}
read_address = read_address + sizeof(union f11_2d_ctrl20_21);
}
return 0;
}
static int f11_allocate_control_regs(struct rmi_device *rmi_dev,
struct f11_2d_device_query *device_query,
struct f11_2d_sensor_query *sensor_query,
struct f11_2d_ctrl *ctrl,
int ctrl_base_addr) {
int error = 0;
if (sensor_query->f11_2d_query7__8[0]) {
ctrl->ctrl10 = kzalloc(sizeof(union f11_2d_ctrl10),
GFP_KERNEL);
if (!ctrl->ctrl10) {
error = -ENOMEM;
goto error_exit;
}
}
if (sensor_query->f11_2d_query7__8[1]) {
ctrl->ctrl11 = kzalloc(sizeof(union f11_2d_ctrl11),
GFP_KERNEL);
if (!ctrl->ctrl11) {
error = -ENOMEM;
goto error_exit;
}
}
// Wireless Debugging Porting
// Both device_query->has_query9 and sensor_query->query9->has_pen are null pointers.
//if (device_query->has_query9 && sensor_query->query9->has_pen) {
if (1) {
ctrl->ctrl20_21 = kzalloc(sizeof(union f11_2d_ctrl20_21),
GFP_KERNEL);
if (!ctrl->ctrl20_21) {
error = -ENOMEM;
goto error_exit;
}
}
return f11_read_control_regs(rmi_dev, ctrl, ctrl_base_addr);
error_exit:
f11_free_control_regs(ctrl);
return error;
}
static int f11_write_control_regs(struct rmi_device *rmi_dev,
struct f11_2d_sensor_query *query,
struct f11_2d_ctrl *ctrl,
int ctrl_base_addr)
{
int write_address = ctrl_base_addr;
int error;
error = rmi_write_block(rmi_dev, write_address,
ctrl->ctrl0_9, sizeof(ctrl->ctrl0_9));
if (error < 0)
return error;
write_address += sizeof(ctrl->ctrl0_9);
if (ctrl->ctrl10) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl10->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl11) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl11->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl12 && ctrl->ctrl12_size && query->configurable) {
if (ctrl->ctrl12_size > query->max_electrodes) {
dev_err(&rmi_dev->dev,
"%s: invalid cfg size:%d, should be < %d.\n",
__func__, ctrl->ctrl12_size,
query->max_electrodes);
return -EINVAL;
}
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl12->reg,
ctrl->ctrl12_size);
if (error < 0)
return error;
write_address += ctrl->ctrl12_size;
}
if (ctrl->ctrl14) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl14->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl15) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl15->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl16) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl16->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl17) {
error = rmi_write_block(rmi_dev, write_address,
&ctrl->ctrl17->reg, 1);
if (error < 0)
return error;
write_address++;
}
if (ctrl->ctrl18_19) {
error = rmi_write_block(rmi_dev, write_address,
ctrl->ctrl18_19->reg, sizeof(union f11_2d_ctrl18_19));
if (error < 0)
return error;
write_address += sizeof(union f11_2d_ctrl18_19);
}
if (ctrl->ctrl20_21) {
error = rmi_write_block(rmi_dev, write_address,
ctrl->ctrl20_21->reg,
sizeof(union f11_2d_ctrl20_21));
if (error < 0)
return error;
write_address += sizeof(union f11_2d_ctrl20_21);
}
return 0;
}
static int rmi_f11_get_query_parameters(struct rmi_device *rmi_dev,
struct f11_2d_sensor_query *query, u8 query_base_addr)
{
int query_size;
int rc;
rc = rmi_read_block(rmi_dev, query_base_addr, query->f11_2d_query1__4,
sizeof(query->f11_2d_query1__4));
if (rc < 0)
return rc;
query_size = rc;
if (query->has_abs) {
rc = rmi_read(rmi_dev, query_base_addr + query_size,
&query->f11_2d_query5);
if (rc < 0)
return rc;
query_size++;
}
if (query->has_rel) {
rc = rmi_read(rmi_dev, query_base_addr + query_size,
&query->f11_2d_query6);
if (rc < 0)
return rc;
query_size++;
}
if (query->has_gestures) {
rc = rmi_read_block(rmi_dev, query_base_addr + query_size,
query->f11_2d_query7__8,
sizeof(query->f11_2d_query7__8));
if (rc < 0)
return rc;
query_size += sizeof(query->f11_2d_query7__8);
}
if (query->has_touch_shapes) {
rc = rmi_read(rmi_dev, query_base_addr + query_size,
&query->f11_2d_query10);
if (rc < 0)
return rc;
query_size++;
}
return query_size;
}
/* This operation is done in a number of places, so we have a handy routine
* for it.
*/
static void f11_set_abs_params(struct rmi_function_container *fc, int index)
{
struct f11_data *instance_data = fc->data;
struct f11_2d_sensor *sensor = &instance_data->sensors[index];
struct input_dev *input = sensor->input;
int device_x_max =
instance_data->dev_controls.sensor_max_x_pos;
int device_y_max =
instance_data->dev_controls.sensor_max_y_pos;
int x_min, x_max, y_min, y_max;
if (sensor->axis_align.swap_axes) {
int temp = device_x_max;
device_x_max = device_y_max;
device_y_max = temp;
}
/* Use the max X and max Y read from the device, or the clip values,
* whichever is stricter.
*/
x_min = sensor->axis_align.clip_X_low;
if (sensor->axis_align.clip_X_high)
x_max = min((int) device_x_max,
sensor->axis_align.clip_X_high);
else
x_max = device_x_max;
y_min = sensor->axis_align.clip_Y_low;
if (sensor->axis_align.clip_Y_high)
y_max = min((int) device_y_max,
sensor->axis_align.clip_Y_high);
else
y_max = device_y_max;
dev_dbg(&fc->dev, "Set ranges X=[%d..%d] Y=[%d..%d].",
x_min, x_max, y_min, y_max);
#ifdef ABS_MT_PRESSURE
input_set_abs_params(input, ABS_MT_PRESSURE, 0,
DEFAULT_MAX_ABS_MT_PRESSURE, 0, 0);
#endif
input_set_abs_params(input, ABS_MT_TOUCH_MAJOR,
0, DEFAULT_MAX_ABS_MT_TOUCH, 0, 0);
input_set_abs_params(input, ABS_MT_TOUCH_MINOR,
0, DEFAULT_MAX_ABS_MT_TOUCH, 0, 0);
input_set_abs_params(input, ABS_MT_ORIENTATION,
0, DEFAULT_MAX_ABS_MT_ORIENTATION, 0, 0);
input_set_abs_params(input, ABS_MT_TRACKING_ID,
DEFAULT_MIN_ABS_MT_TRACKING_ID,
DEFAULT_MAX_ABS_MT_TRACKING_ID, 0, 0);
/* TODO get max_x_pos (and y) from control registers. */
input_set_abs_params(input, ABS_MT_POSITION_X,
x_min, x_max, 0, 0);
input_set_abs_params(input, ABS_MT_POSITION_Y,
y_min, y_max, 0, 0);
#ifdef CONFIG_RMI4_F11_PEN
if (sensor->sens_query.query9.has_pen)
input_set_abs_params(input, ABS_MT_TOOL_TYPE,
0, MT_TOOL_MAX, 0, 0);
#endif
}
static int rmi_f11_init(struct rmi_function_container *fc)
{
int rc;
rc = rmi_f11_initialize(fc);
if (rc < 0)
goto err_free_data;
rc = rmi_f11_register_devices(fc);
if (rc < 0)
goto err_free_data;
rc = rmi_f11_create_sysfs(fc);
if (rc < 0)
goto err_free_data;
return 0;
err_free_data:
rmi_f11_free_memory(fc);
return rc;
}
static void rmi_f11_free_memory(struct rmi_function_container *fc)
{
struct f11_data *f11 = fc->data;
int i;
if (f11) {
f11_free_control_regs(&f11->dev_controls);
for (i = 0; i < f11->dev_query.nbr_of_sensors + 1; i++)
kfree(f11->sensors[i].virtualbutton_map.map);
kfree(f11);
fc->data = NULL;
}
}
static int rmi_f11_initialize(struct rmi_function_container *fc)
{
struct rmi_device *rmi_dev = fc->rmi_dev;
struct f11_data *f11;
u8 query_offset;
u8 query_base_addr;
u8 control_base_addr;
u16 max_x_pos, max_y_pos, temp;
int rc;
int i;
struct rmi_device_platform_data *pdata = to_rmi_platform_data(rmi_dev);
dev_dbg(&fc->dev, "Initializing F11 values for %s.\n",
pdata->sensor_name);
/*
** init instance data, fill in values and create any sysfs files
*/
f11 = kzalloc(sizeof(struct f11_data), GFP_KERNEL);
if (!f11)
return -ENOMEM;
fc->data = f11;
#if RESUME_REZERO
f11->rezero_on_resume = true;
f11->rezero_wait_ms = DEFAULT_REZERO_WAIT_MS;
#endif
query_base_addr = fc->fd.query_base_addr;
control_base_addr = fc->fd.control_base_addr;
rc = rmi_read(rmi_dev, query_base_addr, &f11->dev_query.f11_2d_query0);
if (rc < 0)
return rc;
query_offset = (query_base_addr + 1);
/* Increase with one since number of sensors is zero based */
for (i = 0; i < (f11->dev_query.nbr_of_sensors + 1); i++) {
f11->sensors[i].sensor_index = i;
rc = rmi_f11_get_query_parameters(rmi_dev,
&f11->sensors[i].sens_query,
query_offset);
if (rc < 0)
return rc;
query_offset += rc;
if (f11->dev_query.has_query9) {
rc = rmi_read(rmi_dev, query_offset,
&f11->sensors[i].sens_query.query9.reg);
if (rc < 0) {
dev_err(&fc->dev, "Failed to read query 9.\n");
return rc;
}
query_offset += rc;
}
rc = f11_allocate_control_regs(rmi_dev,
&f11->dev_query, &f11->sensors[i].sens_query,
&f11->dev_controls, control_base_addr);
if (rc < 0) {
dev_err(&fc->dev,
"Failed to initialize F11 control params.\n");
return rc;
}
f11->sensors[i].axis_align = pdata->axis_align;
rc = rmi_read_block(rmi_dev,
control_base_addr + F11_CTRL_SENSOR_MAX_X_POS_OFFSET,
(u8 *)&max_x_pos, sizeof(max_x_pos));
if (rc < 0)
return rc;
rc = rmi_read_block(rmi_dev,
control_base_addr + F11_CTRL_SENSOR_MAX_Y_POS_OFFSET,
(u8 *)&max_y_pos, sizeof(max_y_pos));
if (rc < 0)
return rc;
if (pdata->axis_align.swap_axes) {
temp = max_x_pos;
max_x_pos = max_y_pos;
max_y_pos = temp;
}
f11->sensors[i].max_x = max_x_pos;
f11->sensors[i].max_y = max_y_pos;
rc = f11_2d_construct_data(&f11->sensors[i]);
if (rc < 0)
return rc;
}
return 0;
}
static int rmi_f11_register_devices(struct rmi_function_container *fc)
{
struct rmi_device *rmi_dev = fc->rmi_dev;
struct f11_data *f11 = fc->data;
struct input_dev *input_dev;
struct input_dev *input_dev_mouse;
int sensors_itertd = 0;
int i;
int rc;
#ifdef CONFIG_RMI4_VIRTUAL_BUTTON
struct rmi_f11_virtualbutton_map *vm_sensor;
struct rmi_f11_virtualbutton_map *vm_pdata;
struct rmi_device_platform_data *pdata = to_rmi_platform_data(rmi_dev);
#endif
for (i = 0; i < (f11->dev_query.nbr_of_sensors + 1); i++) {
sensors_itertd = i;
input_dev = input_allocate_device();
if (!input_dev) {
rc = -ENOMEM;
goto error_unregister;
}
f11->sensors[i].input = input_dev;
/* TODO how to modify the dev name and
* phys name for input device */
sprintf(f11->sensors[i].input_name, "%sfn%02x",
dev_name(&rmi_dev->dev), fc->fd.function_number);
input_dev->name = f11->sensors[i].input_name;
sprintf(f11->sensors[i].input_phys, "%s/input0",
input_dev->name);
input_dev->phys = f11->sensors[i].input_phys;
input_dev->dev.parent = &rmi_dev->dev;
input_set_drvdata(input_dev, f11);
set_bit(EV_SYN, input_dev->evbit);
set_bit(EV_KEY, input_dev->evbit);
set_bit(EV_ABS, input_dev->evbit);
//donguk.ki@lge.com
set_bit(INPUT_PROP_DIRECT, input_dev->propbit);
f11_set_abs_params(fc, i);
dev_dbg(&fc->dev, "%s: Sensor %d hasRel %d.\n",
__func__, i, f11->sensors[i].sens_query.has_rel);
if (f11->sensors[i].sens_query.has_rel) {
set_bit(EV_REL, input_dev->evbit);
set_bit(REL_X, input_dev->relbit);
set_bit(REL_Y, input_dev->relbit);
}
rc = input_register_device(input_dev);
if (rc < 0) {
input_free_device(input_dev);
f11->sensors[i].input = NULL;
goto error_unregister;
}
/* how to register the virtualbutton device */
#ifdef CONFIG_RMI4_VIRTUAL_BUTTON
if (f11->sensors[i].sens_query.has_gestures) {
int j;
vm_sensor = &f11->sensors[i].virtualbutton_map;
vm_pdata = pdata->virtualbutton_map;
if (!vm_pdata) {
dev_err(&fc->dev, "Failed to get the pdata virtualbutton map.\n");
goto error_unregister;
}
vm_sensor->buttons = vm_pdata->buttons;
vm_sensor->map = kcalloc(vm_pdata->buttons,
sizeof(struct virtualbutton_map),
GFP_KERNEL);
if (!vm_sensor->map) {
dev_err(&fc->dev, "Failed to allocate the virtualbutton map.\n");
rc = -ENOMEM;
goto error_unregister;
}
/* set bits for each button... */
for (j = 0; j < vm_pdata->buttons; j++) {
memcpy(&vm_sensor->map[j], &vm_pdata->map[j],
sizeof(struct virtualbutton_map));
set_bit(vm_sensor->map[j].code,
f11->sensors[i].input->keybit);
}
}
#endif
if (f11->sensors[i].sens_query.has_rel) {
/*create input device for mouse events */
input_dev_mouse = input_allocate_device();
if (!input_dev_mouse) {
rc = -ENOMEM;
goto error_unregister;
}
f11->sensors[i].mouse_input = input_dev_mouse;
input_dev_mouse->name = "rmi_mouse";
input_dev_mouse->phys = "rmi_f11/input0";
input_dev_mouse->id.vendor = 0x18d1;
input_dev_mouse->id.product = 0x0210;
input_dev_mouse->id.version = 0x0100;
set_bit(EV_REL, input_dev_mouse->evbit);
set_bit(REL_X, input_dev_mouse->relbit);
set_bit(REL_Y, input_dev_mouse->relbit);
set_bit(BTN_MOUSE, input_dev_mouse->evbit);
/* Register device's buttons and keys */
set_bit(EV_KEY, input_dev_mouse->evbit);
set_bit(BTN_LEFT, input_dev_mouse->keybit);
set_bit(BTN_MIDDLE, input_dev_mouse->keybit);
set_bit(BTN_RIGHT, input_dev_mouse->keybit);
rc = input_register_device(input_dev_mouse);
if (rc < 0) {
input_free_device(input_dev_mouse);
f11->sensors[i].mouse_input = NULL;
goto error_unregister;
}
set_bit(BTN_RIGHT, input_dev_mouse->keybit);
}
}
return 0;
error_unregister:
for (; sensors_itertd > 0; sensors_itertd--) {
if (f11->sensors[sensors_itertd].input) {
if (f11->sensors[sensors_itertd].mouse_input) {
input_unregister_device(
f11->sensors[sensors_itertd].mouse_input);
f11->sensors[sensors_itertd].mouse_input = NULL;
}
input_unregister_device(f11->sensors[i].input);
f11->sensors[i].input = NULL;
}
kfree(f11->sensors[i].virtualbutton_map.map);
}
return rc;
}
static void rmi_f11_free_devices(struct rmi_function_container *fc)
{
struct f11_data *f11 = fc->data;
int i;
for (i = 0; i < (f11->dev_query.nbr_of_sensors + 1); i++) {
if (f11->sensors[i].input)
input_unregister_device(f11->sensors[i].input);
if (f11->sensors[i].sens_query.has_rel &&
f11->sensors[i].mouse_input)
input_unregister_device(f11->sensors[i].mouse_input);
}
}
static int rmi_f11_create_sysfs(struct rmi_function_container *fc)
{
int attr_count = 0;
int rc;
dev_dbg(&fc->dev, "Creating sysfs files.\n");
/* Set up sysfs device attributes. */
for (attr_count = 0; attr_count < ARRAY_SIZE(attrs); attr_count++) {
if (sysfs_create_file
(&fc->dev.kobj, &attrs[attr_count].attr) < 0) {
dev_err(&fc->dev,
"Failed to create sysfs file for %s.",
attrs[attr_count].attr.name);
rc = -ENODEV;
goto err_remove_sysfs;
}
}
return 0;
err_remove_sysfs:
for (attr_count--; attr_count >= 0; attr_count--)
sysfs_remove_file(&fc->dev.kobj,
&attrs[attr_count].attr);
return rc;
}
static int rmi_f11_config(struct rmi_function_container *fc)
{
struct f11_data *f11 = fc->data;
int i;
int rc;
for (i = 0; i < (f11->dev_query.nbr_of_sensors + 1); i++) {
rc = f11_write_control_regs(fc->rmi_dev,
&f11->sensors[i].sens_query,
&f11->dev_controls,
fc->fd.query_base_addr);
if (rc < 0)
return rc;
}
return 0;
}
static int rmi_f11_reset(struct rmi_function_container *fc)
{
/* we do nothing here */
return 0;
}
int rmi_f11_attention(struct rmi_function_container *fc, u8 *irq_bits)
{
struct rmi_device *rmi_dev = fc->rmi_dev;
struct f11_data *f11 = fc->data;
u8 data_base_addr = fc->fd.data_base_addr;
int data_base_addr_offset = 0;
int error;
int i;
for (i = 0; i < f11->dev_query.nbr_of_sensors + 1; i++) {
error = rmi_read_block(rmi_dev,
data_base_addr + data_base_addr_offset,
f11->sensors[i].data_pkt,
f11->sensors[i].pkt_size);
if (error < 0)
return error;
rmi_f11_finger_handler(&f11->sensors[i]);
rmi_f11_virtual_button_handler(&f11->sensors[i]);
data_base_addr_offset += f11->sensors[i].pkt_size;
}
return 0;
}
#if RESUME_REZERO
static int rmi_f11_resume(struct rmi_function_container *fc)
{
struct rmi_device *rmi_dev = fc->rmi_dev;
struct f11_data *data = fc->data;
/* Command register always reads as 0, so we can just use a local. */
union f11_2d_commands commands = {};
int retval = 0;
dev_dbg(&fc->dev, "Resuming...\n");
if (!data->rezero_on_resume)
return 0;
if (data->rezero_wait_ms)
mdelay(data->rezero_wait_ms);
commands.rezero = 1;
retval = rmi_write_block(rmi_dev, fc->fd.command_base_addr,
&commands.reg, sizeof(commands.reg));
if (retval < 0) {
dev_err(&rmi_dev->dev, "%s: failed to issue rezero command, error = %d.",
__func__, retval);
return retval;
}
return retval;
}
#endif /* RESUME_REZERO */
static void rmi_f11_remove(struct rmi_function_container *fc)
{
int attr_count = 0;
for (attr_count = 0; attr_count < ARRAY_SIZE(attrs); attr_count++) {
sysfs_remove_file(&fc->dev.kobj,
&attrs[attr_count].attr);
}
rmi_f11_free_devices(fc);
rmi_f11_free_memory(fc);
}
static struct rmi_function_handler function_handler = {
.func = 0x11,
.init = rmi_f11_init,
.config = rmi_f11_config,
.reset = rmi_f11_reset,
.attention = rmi_f11_attention,
.remove = rmi_f11_remove
#if RESUME_REZERO
#ifdef CONFIG_HAS_EARLYSUSPEND
,
.late_resume = rmi_f11_resume
#else
.resume = rmi_f11_resume
#endif /* CONFIG_HAS_EARLYSUSPEND */
#endif
};
static int __init rmi_f11_module_init(void)
{
int error;
error = rmi_register_function_driver(&function_handler);
if (error < 0) {
pr_err("%s: register failed!\n", __func__);
return error;
}
return 0;
}
static void __exit rmi_f11_module_exit(void)
{
rmi_unregister_function_driver(&function_handler);
}
static ssize_t f11_maxPos_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *data;
fc = to_rmi_function_container(dev);
data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u %u\n",
data->sensors[0].max_x, data->sensors[0].max_y);
}
static ssize_t f11_flip_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *data;
fc = to_rmi_function_container(dev);
data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u %u\n",
data->sensors[0].axis_align.flip_x,
data->sensors[0].axis_align.flip_y);
}
static ssize_t f11_flip_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
unsigned int new_X, new_Y;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u %u", &new_X, &new_Y) != 2)
return -EINVAL;
if (new_X < 0 || new_X > 1 || new_Y < 0 || new_Y > 1)
return -EINVAL;
instance_data->sensors[0].axis_align.flip_x = new_X;
instance_data->sensors[0].axis_align.flip_y = new_Y;
return count;
}
static ssize_t f11_swap_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u\n",
instance_data->sensors[0].axis_align.swap_axes);
}
static ssize_t f11_swap_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
unsigned int newSwap;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u", &newSwap) != 1)
return -EINVAL;
if (newSwap < 0 || newSwap > 1)
return -EINVAL;
instance_data->sensors[0].axis_align.swap_axes = newSwap;
f11_set_abs_params(fc, 0);
return count;
}
static ssize_t f11_relreport_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u\n",
instance_data->
sensors[0].axis_align.rel_report_enabled);
}
static ssize_t f11_relreport_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
unsigned int new_value;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u", &new_value) != 1)
return -EINVAL;
if (new_value < 0 || new_value > 1)
return -EINVAL;
instance_data->sensors[0].axis_align.rel_report_enabled = new_value;
return count;
}
static ssize_t f11_offset_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%d %d\n",
instance_data->sensors[0].axis_align.offset_X,
instance_data->sensors[0].axis_align.offset_Y);
}
static ssize_t f11_offset_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
int new_X, new_Y;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%d %d", &new_X, &new_Y) != 2)
return -EINVAL;
instance_data->sensors[0].axis_align.offset_X = new_X;
instance_data->sensors[0].axis_align.offset_Y = new_Y;
return count;
}
static ssize_t f11_clip_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u %u %u %u\n",
instance_data->sensors[0].axis_align.clip_X_low,
instance_data->sensors[0].axis_align.clip_X_high,
instance_data->sensors[0].axis_align.clip_Y_low,
instance_data->sensors[0].axis_align.clip_Y_high);
}
static ssize_t f11_clip_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
unsigned int new_X_low, new_X_high, new_Y_low, new_Y_high;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u %u %u %u",
&new_X_low, &new_X_high, &new_Y_low, &new_Y_high) != 4)
return -EINVAL;
if (new_X_low < 0 || new_X_low >= new_X_high || new_Y_low < 0
|| new_Y_low >= new_Y_high)
return -EINVAL;
instance_data->sensors[0].axis_align.clip_X_low = new_X_low;
instance_data->sensors[0].axis_align.clip_X_high = new_X_high;
instance_data->sensors[0].axis_align.clip_Y_low = new_Y_low;
instance_data->sensors[0].axis_align.clip_Y_high = new_Y_high;
/*
** for now, we assume this is sensor index 0
*/
f11_set_abs_params(fc, 0);
return count;
}
static ssize_t f11_rezero_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct rmi_function_container *fc = NULL;
unsigned int rezero;
int retval = 0;
/* Command register always reads as 0, so we can just use a local. */
union f11_2d_commands commands = {};
fc = to_rmi_function_container(dev);
if (sscanf(buf, "%u", &rezero) != 1)
return -EINVAL;
if (rezero < 0 || rezero > 1)
return -EINVAL;
/* Per spec, 0 has no effect, so we skip it entirely. */
if (rezero) {
commands.rezero = 1;
retval = rmi_write_block(fc->rmi_dev, fc->fd.command_base_addr,
&commands.reg, sizeof(commands.reg));
if (retval < 0) {
dev_err(dev, "%s: failed to issue rezero command, error = %d.",
__func__, retval);
return retval;
}
}
return count;
}
#if RESUME_REZERO
static ssize_t f11_rezeroOnResume_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct rmi_function_container *fc = NULL;
unsigned int newValue;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u", &newValue) != 1)
return -EINVAL;
if (newValue < 0 || newValue > 1) {
dev_err(dev, "rezeroOnResume must be either 1 or 0.\n");
return -EINVAL;
}
instance_data->rezero_on_resume = (newValue != 0);
return count;
}
static ssize_t f11_rezeroOnResume_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u\n",
instance_data->rezero_on_resume);
}
static ssize_t f11_rezeroWait_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct rmi_function_container *fc = NULL;
unsigned int newValue;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
if (sscanf(buf, "%u", &newValue) != 1)
return -EINVAL;
if (newValue < 0) {
dev_err(dev, "rezeroWait must be 0 or greater.\n");
return -EINVAL;
}
instance_data->rezero_wait_ms = (newValue != 0);
return count;
}
static ssize_t f11_rezeroWait_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct rmi_function_container *fc;
struct f11_data *instance_data;
fc = to_rmi_function_container(dev);
instance_data = fc->data;
return snprintf(buf, PAGE_SIZE, "%u\n",
instance_data->rezero_wait_ms);
}
#endif
module_init(rmi_f11_module_init);
module_exit(rmi_f11_module_exit);
MODULE_AUTHOR("Christopher Heiny <cheiny@synaptics.com");
MODULE_DESCRIPTION("RMI F11 module");
MODULE_LICENSE("GPL");
//MODULE_VERSION(RMI_DRIVER_VERSION); | gpl-2.0 |
Perferom/android_kernel_htc_msm7x27 | net/sched/act_skbedit.c | 816 | 5881 | /*
* Copyright (c) 2008, 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., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
* Author: Alexander Duyck <alexander.h.duyck@intel.com>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
#include <linux/tc_act/tc_skbedit.h>
#include <net/tc_act/tc_skbedit.h>
#define SKBEDIT_TAB_MASK 15
static struct tcf_common *tcf_skbedit_ht[SKBEDIT_TAB_MASK + 1];
static u32 skbedit_idx_gen;
static DEFINE_RWLOCK(skbedit_lock);
static struct tcf_hashinfo skbedit_hash_info = {
.htab = tcf_skbedit_ht,
.hmask = SKBEDIT_TAB_MASK,
.lock = &skbedit_lock,
};
static int tcf_skbedit(struct sk_buff *skb, struct tc_action *a,
struct tcf_result *res)
{
struct tcf_skbedit *d = a->priv;
spin_lock(&d->tcf_lock);
d->tcf_tm.lastuse = jiffies;
d->tcf_bstats.bytes += qdisc_pkt_len(skb);
d->tcf_bstats.packets++;
if (d->flags & SKBEDIT_F_PRIORITY)
skb->priority = d->priority;
if (d->flags & SKBEDIT_F_QUEUE_MAPPING &&
skb->dev->real_num_tx_queues > d->queue_mapping)
skb_set_queue_mapping(skb, d->queue_mapping);
if (d->flags & SKBEDIT_F_MARK)
skb->mark = d->mark;
spin_unlock(&d->tcf_lock);
return d->tcf_action;
}
static const struct nla_policy skbedit_policy[TCA_SKBEDIT_MAX + 1] = {
[TCA_SKBEDIT_PARMS] = { .len = sizeof(struct tc_skbedit) },
[TCA_SKBEDIT_PRIORITY] = { .len = sizeof(u32) },
[TCA_SKBEDIT_QUEUE_MAPPING] = { .len = sizeof(u16) },
[TCA_SKBEDIT_MARK] = { .len = sizeof(u32) },
};
static int tcf_skbedit_init(struct nlattr *nla, struct nlattr *est,
struct tc_action *a, int ovr, int bind)
{
struct nlattr *tb[TCA_SKBEDIT_MAX + 1];
struct tc_skbedit *parm;
struct tcf_skbedit *d;
struct tcf_common *pc;
u32 flags = 0, *priority = NULL, *mark = NULL;
u16 *queue_mapping = NULL;
int ret = 0, err;
if (nla == NULL)
return -EINVAL;
err = nla_parse_nested(tb, TCA_SKBEDIT_MAX, nla, skbedit_policy);
if (err < 0)
return err;
if (tb[TCA_SKBEDIT_PARMS] == NULL)
return -EINVAL;
if (tb[TCA_SKBEDIT_PRIORITY] != NULL) {
flags |= SKBEDIT_F_PRIORITY;
priority = nla_data(tb[TCA_SKBEDIT_PRIORITY]);
}
if (tb[TCA_SKBEDIT_QUEUE_MAPPING] != NULL) {
flags |= SKBEDIT_F_QUEUE_MAPPING;
queue_mapping = nla_data(tb[TCA_SKBEDIT_QUEUE_MAPPING]);
}
if (tb[TCA_SKBEDIT_MARK] != NULL) {
flags |= SKBEDIT_F_MARK;
mark = nla_data(tb[TCA_SKBEDIT_MARK]);
}
if (!flags)
return -EINVAL;
parm = nla_data(tb[TCA_SKBEDIT_PARMS]);
pc = tcf_hash_check(parm->index, a, bind, &skbedit_hash_info);
if (!pc) {
pc = tcf_hash_create(parm->index, est, a, sizeof(*d), bind,
&skbedit_idx_gen, &skbedit_hash_info);
if (IS_ERR(pc))
return PTR_ERR(pc);
d = to_skbedit(pc);
ret = ACT_P_CREATED;
} else {
d = to_skbedit(pc);
if (!ovr) {
tcf_hash_release(pc, bind, &skbedit_hash_info);
return -EEXIST;
}
}
spin_lock_bh(&d->tcf_lock);
d->flags = flags;
if (flags & SKBEDIT_F_PRIORITY)
d->priority = *priority;
if (flags & SKBEDIT_F_QUEUE_MAPPING)
d->queue_mapping = *queue_mapping;
if (flags & SKBEDIT_F_MARK)
d->mark = *mark;
d->tcf_action = parm->action;
spin_unlock_bh(&d->tcf_lock);
if (ret == ACT_P_CREATED)
tcf_hash_insert(pc, &skbedit_hash_info);
return ret;
}
static inline int tcf_skbedit_cleanup(struct tc_action *a, int bind)
{
struct tcf_skbedit *d = a->priv;
if (d)
return tcf_hash_release(&d->common, bind, &skbedit_hash_info);
return 0;
}
static inline int tcf_skbedit_dump(struct sk_buff *skb, struct tc_action *a,
int bind, int ref)
{
unsigned char *b = skb_tail_pointer(skb);
struct tcf_skbedit *d = a->priv;
struct tc_skbedit opt;
struct tcf_t t;
opt.index = d->tcf_index;
opt.refcnt = d->tcf_refcnt - ref;
opt.bindcnt = d->tcf_bindcnt - bind;
opt.action = d->tcf_action;
NLA_PUT(skb, TCA_SKBEDIT_PARMS, sizeof(opt), &opt);
if (d->flags & SKBEDIT_F_PRIORITY)
NLA_PUT(skb, TCA_SKBEDIT_PRIORITY, sizeof(d->priority),
&d->priority);
if (d->flags & SKBEDIT_F_QUEUE_MAPPING)
NLA_PUT(skb, TCA_SKBEDIT_QUEUE_MAPPING,
sizeof(d->queue_mapping), &d->queue_mapping);
if (d->flags & SKBEDIT_F_MARK)
NLA_PUT(skb, TCA_SKBEDIT_MARK, sizeof(d->mark),
&d->mark);
t.install = jiffies_to_clock_t(jiffies - d->tcf_tm.install);
t.lastuse = jiffies_to_clock_t(jiffies - d->tcf_tm.lastuse);
t.expires = jiffies_to_clock_t(d->tcf_tm.expires);
NLA_PUT(skb, TCA_SKBEDIT_TM, sizeof(t), &t);
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct tc_action_ops act_skbedit_ops = {
.kind = "skbedit",
.hinfo = &skbedit_hash_info,
.type = TCA_ACT_SKBEDIT,
.capab = TCA_CAP_NONE,
.owner = THIS_MODULE,
.act = tcf_skbedit,
.dump = tcf_skbedit_dump,
.cleanup = tcf_skbedit_cleanup,
.init = tcf_skbedit_init,
.walk = tcf_generic_walker,
};
MODULE_AUTHOR("Alexander Duyck, <alexander.h.duyck@intel.com>");
MODULE_DESCRIPTION("SKB Editing");
MODULE_LICENSE("GPL");
static int __init skbedit_init_module(void)
{
return tcf_register_action(&act_skbedit_ops);
}
static void __exit skbedit_cleanup_module(void)
{
tcf_unregister_action(&act_skbedit_ops);
}
module_init(skbedit_init_module);
module_exit(skbedit_cleanup_module);
| gpl-2.0 |
andreamerello/linux-analogdevices | fs/btrfs/dir-item.c | 1328 | 13124 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include "ctree.h"
#include "disk-io.h"
#include "hash.h"
#include "transaction.h"
/*
* insert a name into a directory, doing overflow properly if there is a hash
* collision. data_size indicates how big the item inserted should be. On
* success a struct btrfs_dir_item pointer is returned, otherwise it is
* an ERR_PTR.
*
* The name is not copied into the dir item, you have to do that yourself.
*/
static struct btrfs_dir_item *insert_with_overflow(struct btrfs_trans_handle
*trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *cpu_key,
u32 data_size,
const char *name,
int name_len)
{
int ret;
char *ptr;
struct btrfs_item *item;
struct extent_buffer *leaf;
ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
if (ret == -EEXIST) {
struct btrfs_dir_item *di;
di = btrfs_match_dir_item_name(root, path, name, name_len);
if (di)
return ERR_PTR(-EEXIST);
btrfs_extend_item(root, path, data_size);
} else if (ret < 0)
return ERR_PTR(ret);
WARN_ON(ret > 0);
leaf = path->nodes[0];
item = btrfs_item_nr(path->slots[0]);
ptr = btrfs_item_ptr(leaf, path->slots[0], char);
BUG_ON(data_size > btrfs_item_size(leaf, item));
ptr += btrfs_item_size(leaf, item) - data_size;
return (struct btrfs_dir_item *)ptr;
}
/*
* xattrs work a lot like directories, this inserts an xattr item
* into the tree
*/
int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, u64 objectid,
const char *name, u16 name_len,
const void *data, u16 data_len)
{
int ret = 0;
struct btrfs_dir_item *dir_item;
unsigned long name_ptr, data_ptr;
struct btrfs_key key, location;
struct btrfs_disk_key disk_key;
struct extent_buffer *leaf;
u32 data_size;
BUG_ON(name_len + data_len > BTRFS_MAX_XATTR_SIZE(root));
key.objectid = objectid;
key.type = BTRFS_XATTR_ITEM_KEY;
key.offset = btrfs_name_hash(name, name_len);
data_size = sizeof(*dir_item) + name_len + data_len;
dir_item = insert_with_overflow(trans, root, path, &key, data_size,
name, name_len);
if (IS_ERR(dir_item))
return PTR_ERR(dir_item);
memset(&location, 0, sizeof(location));
leaf = path->nodes[0];
btrfs_cpu_key_to_disk(&disk_key, &location);
btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR);
btrfs_set_dir_name_len(leaf, dir_item, name_len);
btrfs_set_dir_transid(leaf, dir_item, trans->transid);
btrfs_set_dir_data_len(leaf, dir_item, data_len);
name_ptr = (unsigned long)(dir_item + 1);
data_ptr = (unsigned long)((char *)name_ptr + name_len);
write_extent_buffer(leaf, name, name_ptr, name_len);
write_extent_buffer(leaf, data, data_ptr, data_len);
btrfs_mark_buffer_dirty(path->nodes[0]);
return ret;
}
/*
* insert a directory item in the tree, doing all the magic for
* both indexes. 'dir' indicates which objectid to insert it into,
* 'location' is the key to stuff into the directory item, 'type' is the
* type of the inode we're pointing to, and 'index' is the sequence number
* to use for the second index (if one is created).
* Will return 0 or -ENOMEM
*/
int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root
*root, const char *name, int name_len,
struct inode *dir, struct btrfs_key *location,
u8 type, u64 index)
{
int ret = 0;
int ret2 = 0;
struct btrfs_path *path;
struct btrfs_dir_item *dir_item;
struct extent_buffer *leaf;
unsigned long name_ptr;
struct btrfs_key key;
struct btrfs_disk_key disk_key;
u32 data_size;
key.objectid = btrfs_ino(dir);
key.type = BTRFS_DIR_ITEM_KEY;
key.offset = btrfs_name_hash(name, name_len);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
btrfs_cpu_key_to_disk(&disk_key, location);
data_size = sizeof(*dir_item) + name_len;
dir_item = insert_with_overflow(trans, root, path, &key, data_size,
name, name_len);
if (IS_ERR(dir_item)) {
ret = PTR_ERR(dir_item);
if (ret == -EEXIST)
goto second_insert;
goto out_free;
}
leaf = path->nodes[0];
btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
btrfs_set_dir_type(leaf, dir_item, type);
btrfs_set_dir_data_len(leaf, dir_item, 0);
btrfs_set_dir_name_len(leaf, dir_item, name_len);
btrfs_set_dir_transid(leaf, dir_item, trans->transid);
name_ptr = (unsigned long)(dir_item + 1);
write_extent_buffer(leaf, name, name_ptr, name_len);
btrfs_mark_buffer_dirty(leaf);
second_insert:
/* FIXME, use some real flag for selecting the extra index */
if (root == root->fs_info->tree_root) {
ret = 0;
goto out_free;
}
btrfs_release_path(path);
ret2 = btrfs_insert_delayed_dir_index(trans, root, name, name_len, dir,
&disk_key, type, index);
out_free:
btrfs_free_path(path);
if (ret)
return ret;
if (ret2)
return ret2;
return 0;
}
/*
* lookup a directory item based on name. 'dir' is the objectid
* we're searching in, and 'mod' tells us if you plan on deleting the
* item (use mod < 0) or changing the options (use mod > 0)
*/
struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, u64 dir,
const char *name, int name_len,
int mod)
{
int ret;
struct btrfs_key key;
int ins_len = mod < 0 ? -1 : 0;
int cow = mod != 0;
key.objectid = dir;
key.type = BTRFS_DIR_ITEM_KEY;
key.offset = btrfs_name_hash(name, name_len);
ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow);
if (ret < 0)
return ERR_PTR(ret);
if (ret > 0)
return NULL;
return btrfs_match_dir_item_name(root, path, name, name_len);
}
int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,
const char *name, int name_len)
{
int ret;
struct btrfs_key key;
struct btrfs_dir_item *di;
int data_size;
struct extent_buffer *leaf;
int slot;
struct btrfs_path *path;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = dir;
key.type = BTRFS_DIR_ITEM_KEY;
key.offset = btrfs_name_hash(name, name_len);
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
/* return back any errors */
if (ret < 0)
goto out;
/* nothing found, we're safe */
if (ret > 0) {
ret = 0;
goto out;
}
/* we found an item, look for our name in the item */
di = btrfs_match_dir_item_name(root, path, name, name_len);
if (di) {
/* our exact name was found */
ret = -EEXIST;
goto out;
}
/*
* see if there is room in the item to insert this
* name
*/
data_size = sizeof(*di) + name_len;
leaf = path->nodes[0];
slot = path->slots[0];
if (data_size + btrfs_item_size_nr(leaf, slot) +
sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root)) {
ret = -EOVERFLOW;
} else {
/* plenty of insertion room */
ret = 0;
}
out:
btrfs_free_path(path);
return ret;
}
/*
* lookup a directory item based on index. 'dir' is the objectid
* we're searching in, and 'mod' tells us if you plan on deleting the
* item (use mod < 0) or changing the options (use mod > 0)
*
* The name is used to make sure the index really points to the name you were
* looking for.
*/
struct btrfs_dir_item *
btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, u64 dir,
u64 objectid, const char *name, int name_len,
int mod)
{
int ret;
struct btrfs_key key;
int ins_len = mod < 0 ? -1 : 0;
int cow = mod != 0;
key.objectid = dir;
key.type = BTRFS_DIR_INDEX_KEY;
key.offset = objectid;
ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow);
if (ret < 0)
return ERR_PTR(ret);
if (ret > 0)
return ERR_PTR(-ENOENT);
return btrfs_match_dir_item_name(root, path, name, name_len);
}
struct btrfs_dir_item *
btrfs_search_dir_index_item(struct btrfs_root *root,
struct btrfs_path *path, u64 dirid,
const char *name, int name_len)
{
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key key;
u32 nritems;
int ret;
key.objectid = dirid;
key.type = BTRFS_DIR_INDEX_KEY;
key.offset = 0;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
return ERR_PTR(ret);
leaf = path->nodes[0];
nritems = btrfs_header_nritems(leaf);
while (1) {
if (path->slots[0] >= nritems) {
ret = btrfs_next_leaf(root, path);
if (ret < 0)
return ERR_PTR(ret);
if (ret > 0)
break;
leaf = path->nodes[0];
nritems = btrfs_header_nritems(leaf);
continue;
}
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY)
break;
di = btrfs_match_dir_item_name(root, path, name, name_len);
if (di)
return di;
path->slots[0]++;
}
return NULL;
}
struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, u64 dir,
const char *name, u16 name_len,
int mod)
{
int ret;
struct btrfs_key key;
int ins_len = mod < 0 ? -1 : 0;
int cow = mod != 0;
key.objectid = dir;
key.type = BTRFS_XATTR_ITEM_KEY;
key.offset = btrfs_name_hash(name, name_len);
ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow);
if (ret < 0)
return ERR_PTR(ret);
if (ret > 0)
return NULL;
return btrfs_match_dir_item_name(root, path, name, name_len);
}
/*
* helper function to look at the directory item pointed to by 'path'
* this walks through all the entries in a dir item and finds one
* for a specific name.
*/
struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
struct btrfs_path *path,
const char *name, int name_len)
{
struct btrfs_dir_item *dir_item;
unsigned long name_ptr;
u32 total_len;
u32 cur = 0;
u32 this_len;
struct extent_buffer *leaf;
leaf = path->nodes[0];
dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
if (verify_dir_item(root, leaf, dir_item))
return NULL;
total_len = btrfs_item_size_nr(leaf, path->slots[0]);
while (cur < total_len) {
this_len = sizeof(*dir_item) +
btrfs_dir_name_len(leaf, dir_item) +
btrfs_dir_data_len(leaf, dir_item);
name_ptr = (unsigned long)(dir_item + 1);
if (btrfs_dir_name_len(leaf, dir_item) == name_len &&
memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)
return dir_item;
cur += this_len;
dir_item = (struct btrfs_dir_item *)((char *)dir_item +
this_len);
}
return NULL;
}
/*
* given a pointer into a directory item, delete it. This
* handles items that have more than one entry in them.
*/
int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_dir_item *di)
{
struct extent_buffer *leaf;
u32 sub_item_len;
u32 item_len;
int ret = 0;
leaf = path->nodes[0];
sub_item_len = sizeof(*di) + btrfs_dir_name_len(leaf, di) +
btrfs_dir_data_len(leaf, di);
item_len = btrfs_item_size_nr(leaf, path->slots[0]);
if (sub_item_len == item_len) {
ret = btrfs_del_item(trans, root, path);
} else {
/* MARKER */
unsigned long ptr = (unsigned long)di;
unsigned long start;
start = btrfs_item_ptr_offset(leaf, path->slots[0]);
memmove_extent_buffer(leaf, ptr, ptr + sub_item_len,
item_len - (ptr + sub_item_len - start));
btrfs_truncate_item(root, path, item_len - sub_item_len, 1);
}
return ret;
}
int verify_dir_item(struct btrfs_root *root,
struct extent_buffer *leaf,
struct btrfs_dir_item *dir_item)
{
u16 namelen = BTRFS_NAME_LEN;
u8 type = btrfs_dir_type(leaf, dir_item);
if (type >= BTRFS_FT_MAX) {
btrfs_crit(root->fs_info, "invalid dir item type: %d",
(int)type);
return 1;
}
if (type == BTRFS_FT_XATTR)
namelen = XATTR_NAME_MAX;
if (btrfs_dir_name_len(leaf, dir_item) > namelen) {
btrfs_crit(root->fs_info, "invalid dir item name len: %u",
(unsigned)btrfs_dir_data_len(leaf, dir_item));
return 1;
}
/* BTRFS_MAX_XATTR_SIZE is the same for all dir items */
if ((btrfs_dir_data_len(leaf, dir_item) +
btrfs_dir_name_len(leaf, dir_item)) > BTRFS_MAX_XATTR_SIZE(root)) {
btrfs_crit(root->fs_info, "invalid dir item name + data len: %u + %u",
(unsigned)btrfs_dir_name_len(leaf, dir_item),
(unsigned)btrfs_dir_data_len(leaf, dir_item));
return 1;
}
return 0;
}
| gpl-2.0 |
MattCrystal/oneXL | drivers/net/wireless/mwifiex/11n_rxreorder.c | 2096 | 17893 | /*
* Marvell Wireless LAN device driver: 802.11n RX Re-ordering
*
* Copyright (C) 2011, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#include "11n_rxreorder.h"
/*
* This function dispatches all packets in the Rx reorder table until the
* start window.
*
* There could be holes in the buffer, which are skipped by the function.
* Since the buffer is linear, the function uses rotation to simulate
* circular buffer.
*/
static void
mwifiex_11n_dispatch_pkt(struct mwifiex_private *priv,
struct mwifiex_rx_reorder_tbl *tbl, int start_win)
{
int pkt_to_send, i;
void *rx_tmp_ptr;
unsigned long flags;
pkt_to_send = (start_win > tbl->start_win) ?
min((start_win - tbl->start_win), tbl->win_size) :
tbl->win_size;
for (i = 0; i < pkt_to_send; ++i) {
spin_lock_irqsave(&priv->rx_pkt_lock, flags);
rx_tmp_ptr = NULL;
if (tbl->rx_reorder_ptr[i]) {
rx_tmp_ptr = tbl->rx_reorder_ptr[i];
tbl->rx_reorder_ptr[i] = NULL;
}
spin_unlock_irqrestore(&priv->rx_pkt_lock, flags);
if (rx_tmp_ptr)
mwifiex_process_rx_packet(priv->adapter, rx_tmp_ptr);
}
spin_lock_irqsave(&priv->rx_pkt_lock, flags);
/*
* We don't have a circular buffer, hence use rotation to simulate
* circular buffer
*/
for (i = 0; i < tbl->win_size - pkt_to_send; ++i) {
tbl->rx_reorder_ptr[i] = tbl->rx_reorder_ptr[pkt_to_send + i];
tbl->rx_reorder_ptr[pkt_to_send + i] = NULL;
}
tbl->start_win = start_win;
spin_unlock_irqrestore(&priv->rx_pkt_lock, flags);
}
/*
* This function dispatches all packets in the Rx reorder table until
* a hole is found.
*
* The start window is adjusted automatically when a hole is located.
* Since the buffer is linear, the function uses rotation to simulate
* circular buffer.
*/
static void
mwifiex_11n_scan_and_dispatch(struct mwifiex_private *priv,
struct mwifiex_rx_reorder_tbl *tbl)
{
int i, j, xchg;
void *rx_tmp_ptr;
unsigned long flags;
for (i = 0; i < tbl->win_size; ++i) {
spin_lock_irqsave(&priv->rx_pkt_lock, flags);
if (!tbl->rx_reorder_ptr[i]) {
spin_unlock_irqrestore(&priv->rx_pkt_lock, flags);
break;
}
rx_tmp_ptr = tbl->rx_reorder_ptr[i];
tbl->rx_reorder_ptr[i] = NULL;
spin_unlock_irqrestore(&priv->rx_pkt_lock, flags);
mwifiex_process_rx_packet(priv->adapter, rx_tmp_ptr);
}
spin_lock_irqsave(&priv->rx_pkt_lock, flags);
/*
* We don't have a circular buffer, hence use rotation to simulate
* circular buffer
*/
if (i > 0) {
xchg = tbl->win_size - i;
for (j = 0; j < xchg; ++j) {
tbl->rx_reorder_ptr[j] = tbl->rx_reorder_ptr[i + j];
tbl->rx_reorder_ptr[i + j] = NULL;
}
}
tbl->start_win = (tbl->start_win + i) & (MAX_TID_VALUE - 1);
spin_unlock_irqrestore(&priv->rx_pkt_lock, flags);
}
/*
* This function deletes the Rx reorder table and frees the memory.
*
* The function stops the associated timer and dispatches all the
* pending packets in the Rx reorder table before deletion.
*/
static void
mwifiex_del_rx_reorder_entry(struct mwifiex_private *priv,
struct mwifiex_rx_reorder_tbl *tbl)
{
unsigned long flags;
if (!tbl)
return;
mwifiex_11n_dispatch_pkt(priv, tbl, (tbl->start_win + tbl->win_size) &
(MAX_TID_VALUE - 1));
del_timer(&tbl->timer_context.timer);
spin_lock_irqsave(&priv->rx_reorder_tbl_lock, flags);
list_del(&tbl->list);
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock, flags);
kfree(tbl->rx_reorder_ptr);
kfree(tbl);
}
/*
* This function returns the pointer to an entry in Rx reordering
* table which matches the given TA/TID pair.
*/
static struct mwifiex_rx_reorder_tbl *
mwifiex_11n_get_rx_reorder_tbl(struct mwifiex_private *priv, int tid, u8 *ta)
{
struct mwifiex_rx_reorder_tbl *tbl;
unsigned long flags;
spin_lock_irqsave(&priv->rx_reorder_tbl_lock, flags);
list_for_each_entry(tbl, &priv->rx_reorder_tbl_ptr, list) {
if (!memcmp(tbl->ta, ta, ETH_ALEN) && tbl->tid == tid) {
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock,
flags);
return tbl;
}
}
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock, flags);
return NULL;
}
/*
* This function finds the last sequence number used in the packets
* buffered in Rx reordering table.
*/
static int
mwifiex_11n_find_last_seq_num(struct mwifiex_rx_reorder_tbl *rx_reorder_tbl_ptr)
{
int i;
for (i = (rx_reorder_tbl_ptr->win_size - 1); i >= 0; --i)
if (rx_reorder_tbl_ptr->rx_reorder_ptr[i])
return i;
return -1;
}
/*
* This function flushes all the packets in Rx reordering table.
*
* The function checks if any packets are currently buffered in the
* table or not. In case there are packets available, it dispatches
* them and then dumps the Rx reordering table.
*/
static void
mwifiex_flush_data(unsigned long context)
{
struct reorder_tmr_cnxt *ctx =
(struct reorder_tmr_cnxt *) context;
int start_win;
start_win = mwifiex_11n_find_last_seq_num(ctx->ptr);
if (start_win < 0)
return;
dev_dbg(ctx->priv->adapter->dev, "info: flush data %d\n", start_win);
mwifiex_11n_dispatch_pkt(ctx->priv, ctx->ptr,
(ctx->ptr->start_win + start_win + 1) &
(MAX_TID_VALUE - 1));
}
/*
* This function creates an entry in Rx reordering table for the
* given TA/TID.
*
* The function also initializes the entry with sequence number, window
* size as well as initializes the timer.
*
* If the received TA/TID pair is already present, all the packets are
* dispatched and the window size is moved until the SSN.
*/
static void
mwifiex_11n_create_rx_reorder_tbl(struct mwifiex_private *priv, u8 *ta,
int tid, int win_size, int seq_num)
{
int i;
struct mwifiex_rx_reorder_tbl *tbl, *new_node;
u16 last_seq = 0;
unsigned long flags;
/*
* If we get a TID, ta pair which is already present dispatch all the
* the packets and move the window size until the ssn
*/
tbl = mwifiex_11n_get_rx_reorder_tbl(priv, tid, ta);
if (tbl) {
mwifiex_11n_dispatch_pkt(priv, tbl, seq_num);
return;
}
/* if !tbl then create one */
new_node = kzalloc(sizeof(struct mwifiex_rx_reorder_tbl), GFP_KERNEL);
if (!new_node) {
dev_err(priv->adapter->dev, "%s: failed to alloc new_node\n",
__func__);
return;
}
INIT_LIST_HEAD(&new_node->list);
new_node->tid = tid;
memcpy(new_node->ta, ta, ETH_ALEN);
new_node->start_win = seq_num;
if (mwifiex_queuing_ra_based(priv))
/* TODO for adhoc */
dev_dbg(priv->adapter->dev,
"info: ADHOC:last_seq=%d start_win=%d\n",
last_seq, new_node->start_win);
else
last_seq = priv->rx_seq[tid];
if (last_seq != MWIFIEX_DEF_11N_RX_SEQ_NUM &&
last_seq >= new_node->start_win)
new_node->start_win = last_seq + 1;
new_node->win_size = win_size;
new_node->rx_reorder_ptr = kzalloc(sizeof(void *) * win_size,
GFP_KERNEL);
if (!new_node->rx_reorder_ptr) {
kfree((u8 *) new_node);
dev_err(priv->adapter->dev,
"%s: failed to alloc reorder_ptr\n", __func__);
return;
}
new_node->timer_context.ptr = new_node;
new_node->timer_context.priv = priv;
init_timer(&new_node->timer_context.timer);
new_node->timer_context.timer.function = mwifiex_flush_data;
new_node->timer_context.timer.data =
(unsigned long) &new_node->timer_context;
for (i = 0; i < win_size; ++i)
new_node->rx_reorder_ptr[i] = NULL;
spin_lock_irqsave(&priv->rx_reorder_tbl_lock, flags);
list_add_tail(&new_node->list, &priv->rx_reorder_tbl_ptr);
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock, flags);
}
/*
* This function prepares command for adding a BA request.
*
* Preparation includes -
* - Setting command ID and proper size
* - Setting add BA request buffer
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_11n_addba_req(struct host_cmd_ds_command *cmd, void *data_buf)
{
struct host_cmd_ds_11n_addba_req *add_ba_req =
(struct host_cmd_ds_11n_addba_req *)
&cmd->params.add_ba_req;
cmd->command = cpu_to_le16(HostCmd_CMD_11N_ADDBA_REQ);
cmd->size = cpu_to_le16(sizeof(*add_ba_req) + S_DS_GEN);
memcpy(add_ba_req, data_buf, sizeof(*add_ba_req));
return 0;
}
/*
* This function prepares command for adding a BA response.
*
* Preparation includes -
* - Setting command ID and proper size
* - Setting add BA response buffer
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_11n_addba_rsp_gen(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
struct host_cmd_ds_11n_addba_req
*cmd_addba_req)
{
struct host_cmd_ds_11n_addba_rsp *add_ba_rsp =
(struct host_cmd_ds_11n_addba_rsp *)
&cmd->params.add_ba_rsp;
u8 tid;
int win_size;
uint16_t block_ack_param_set;
cmd->command = cpu_to_le16(HostCmd_CMD_11N_ADDBA_RSP);
cmd->size = cpu_to_le16(sizeof(*add_ba_rsp) + S_DS_GEN);
memcpy(add_ba_rsp->peer_mac_addr, cmd_addba_req->peer_mac_addr,
ETH_ALEN);
add_ba_rsp->dialog_token = cmd_addba_req->dialog_token;
add_ba_rsp->block_ack_tmo = cmd_addba_req->block_ack_tmo;
add_ba_rsp->ssn = cmd_addba_req->ssn;
block_ack_param_set = le16_to_cpu(cmd_addba_req->block_ack_param_set);
tid = (block_ack_param_set & IEEE80211_ADDBA_PARAM_TID_MASK)
>> BLOCKACKPARAM_TID_POS;
add_ba_rsp->status_code = cpu_to_le16(ADDBA_RSP_STATUS_ACCEPT);
block_ack_param_set &= ~IEEE80211_ADDBA_PARAM_BUF_SIZE_MASK;
/* We donot support AMSDU inside AMPDU, hence reset the bit */
block_ack_param_set &= ~BLOCKACKPARAM_AMSDU_SUPP_MASK;
block_ack_param_set |= (priv->add_ba_param.rx_win_size <<
BLOCKACKPARAM_WINSIZE_POS);
add_ba_rsp->block_ack_param_set = cpu_to_le16(block_ack_param_set);
win_size = (le16_to_cpu(add_ba_rsp->block_ack_param_set)
& IEEE80211_ADDBA_PARAM_BUF_SIZE_MASK)
>> BLOCKACKPARAM_WINSIZE_POS;
cmd_addba_req->block_ack_param_set = cpu_to_le16(block_ack_param_set);
mwifiex_11n_create_rx_reorder_tbl(priv, cmd_addba_req->peer_mac_addr,
tid, win_size,
le16_to_cpu(cmd_addba_req->ssn));
return 0;
}
/*
* This function prepares command for deleting a BA request.
*
* Preparation includes -
* - Setting command ID and proper size
* - Setting del BA request buffer
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_11n_delba(struct host_cmd_ds_command *cmd, void *data_buf)
{
struct host_cmd_ds_11n_delba *del_ba = (struct host_cmd_ds_11n_delba *)
&cmd->params.del_ba;
cmd->command = cpu_to_le16(HostCmd_CMD_11N_DELBA);
cmd->size = cpu_to_le16(sizeof(*del_ba) + S_DS_GEN);
memcpy(del_ba, data_buf, sizeof(*del_ba));
return 0;
}
/*
* This function identifies if Rx reordering is needed for a received packet.
*
* In case reordering is required, the function will do the reordering
* before sending it to kernel.
*
* The Rx reorder table is checked first with the received TID/TA pair. If
* not found, the received packet is dispatched immediately. But if found,
* the packet is reordered and all the packets in the updated Rx reordering
* table is dispatched until a hole is found.
*
* For sequence number less than the starting window, the packet is dropped.
*/
int mwifiex_11n_rx_reorder_pkt(struct mwifiex_private *priv,
u16 seq_num, u16 tid,
u8 *ta, u8 pkt_type, void *payload)
{
struct mwifiex_rx_reorder_tbl *tbl;
int start_win, end_win, win_size;
u16 pkt_index;
tbl = mwifiex_11n_get_rx_reorder_tbl((struct mwifiex_private *) priv,
tid, ta);
if (!tbl) {
if (pkt_type != PKT_TYPE_BAR)
mwifiex_process_rx_packet(priv->adapter, payload);
return 0;
}
start_win = tbl->start_win;
win_size = tbl->win_size;
end_win = ((start_win + win_size) - 1) & (MAX_TID_VALUE - 1);
del_timer(&tbl->timer_context.timer);
mod_timer(&tbl->timer_context.timer,
jiffies + (MIN_FLUSH_TIMER_MS * win_size * HZ) / 1000);
/*
* If seq_num is less then starting win then ignore and drop the
* packet
*/
if ((start_win + TWOPOW11) > (MAX_TID_VALUE - 1)) {/* Wrap */
if (seq_num >= ((start_win + TWOPOW11) &
(MAX_TID_VALUE - 1)) && (seq_num < start_win))
return -1;
} else if ((seq_num < start_win) ||
(seq_num > (start_win + TWOPOW11))) {
return -1;
}
/*
* If this packet is a BAR we adjust seq_num as
* WinStart = seq_num
*/
if (pkt_type == PKT_TYPE_BAR)
seq_num = ((seq_num + win_size) - 1) & (MAX_TID_VALUE - 1);
if (((end_win < start_win) &&
(seq_num < (TWOPOW11 - (MAX_TID_VALUE - start_win))) &&
(seq_num > end_win)) ||
((end_win > start_win) && ((seq_num > end_win) ||
(seq_num < start_win)))) {
end_win = seq_num;
if (((seq_num - win_size) + 1) >= 0)
start_win = (end_win - win_size) + 1;
else
start_win = (MAX_TID_VALUE - (win_size - seq_num)) + 1;
mwifiex_11n_dispatch_pkt(priv, tbl, start_win);
}
if (pkt_type != PKT_TYPE_BAR) {
if (seq_num >= start_win)
pkt_index = seq_num - start_win;
else
pkt_index = (seq_num+MAX_TID_VALUE) - start_win;
if (tbl->rx_reorder_ptr[pkt_index])
return -1;
tbl->rx_reorder_ptr[pkt_index] = payload;
}
/*
* Dispatch all packets sequentially from start_win until a
* hole is found and adjust the start_win appropriately
*/
mwifiex_11n_scan_and_dispatch(priv, tbl);
return 0;
}
/*
* This function deletes an entry for a given TID/TA pair.
*
* The TID/TA are taken from del BA event body.
*/
void
mwifiex_del_ba_tbl(struct mwifiex_private *priv, int tid, u8 *peer_mac,
u8 type, int initiator)
{
struct mwifiex_rx_reorder_tbl *tbl;
struct mwifiex_tx_ba_stream_tbl *ptx_tbl;
u8 cleanup_rx_reorder_tbl;
unsigned long flags;
if (type == TYPE_DELBA_RECEIVE)
cleanup_rx_reorder_tbl = (initiator) ? true : false;
else
cleanup_rx_reorder_tbl = (initiator) ? false : true;
dev_dbg(priv->adapter->dev, "event: DELBA: %pM tid=%d initiator=%d\n",
peer_mac, tid, initiator);
if (cleanup_rx_reorder_tbl) {
tbl = mwifiex_11n_get_rx_reorder_tbl(priv, tid,
peer_mac);
if (!tbl) {
dev_dbg(priv->adapter->dev,
"event: TID, TA not found in table\n");
return;
}
mwifiex_del_rx_reorder_entry(priv, tbl);
} else {
ptx_tbl = mwifiex_get_ba_tbl(priv, tid, peer_mac);
if (!ptx_tbl) {
dev_dbg(priv->adapter->dev,
"event: TID, RA not found in table\n");
return;
}
spin_lock_irqsave(&priv->tx_ba_stream_tbl_lock, flags);
mwifiex_11n_delete_tx_ba_stream_tbl_entry(priv, ptx_tbl);
spin_unlock_irqrestore(&priv->tx_ba_stream_tbl_lock, flags);
}
}
/*
* This function handles the command response of an add BA response.
*
* Handling includes changing the header fields into CPU format and
* creating the stream, provided the add BA is accepted.
*/
int mwifiex_ret_11n_addba_resp(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct host_cmd_ds_11n_addba_rsp *add_ba_rsp =
(struct host_cmd_ds_11n_addba_rsp *)
&resp->params.add_ba_rsp;
int tid, win_size;
struct mwifiex_rx_reorder_tbl *tbl;
uint16_t block_ack_param_set;
block_ack_param_set = le16_to_cpu(add_ba_rsp->block_ack_param_set);
tid = (block_ack_param_set & IEEE80211_ADDBA_PARAM_TID_MASK)
>> BLOCKACKPARAM_TID_POS;
/*
* Check if we had rejected the ADDBA, if yes then do not create
* the stream
*/
if (le16_to_cpu(add_ba_rsp->status_code) == BA_RESULT_SUCCESS) {
win_size = (block_ack_param_set &
IEEE80211_ADDBA_PARAM_BUF_SIZE_MASK)
>> BLOCKACKPARAM_WINSIZE_POS;
dev_dbg(priv->adapter->dev,
"cmd: ADDBA RSP: %pM tid=%d ssn=%d win_size=%d\n",
add_ba_rsp->peer_mac_addr, tid,
add_ba_rsp->ssn, win_size);
} else {
dev_err(priv->adapter->dev, "ADDBA RSP: failed %pM tid=%d)\n",
add_ba_rsp->peer_mac_addr, tid);
tbl = mwifiex_11n_get_rx_reorder_tbl(priv, tid,
add_ba_rsp->peer_mac_addr);
if (tbl)
mwifiex_del_rx_reorder_entry(priv, tbl);
}
return 0;
}
/*
* This function handles BA stream timeout event by preparing and sending
* a command to the firmware.
*/
void mwifiex_11n_ba_stream_timeout(struct mwifiex_private *priv,
struct host_cmd_ds_11n_batimeout *event)
{
struct host_cmd_ds_11n_delba delba;
memset(&delba, 0, sizeof(struct host_cmd_ds_11n_delba));
memcpy(delba.peer_mac_addr, event->peer_mac_addr, ETH_ALEN);
delba.del_ba_param_set |=
cpu_to_le16((u16) event->tid << DELBA_TID_POS);
delba.del_ba_param_set |= cpu_to_le16(
(u16) event->origninator << DELBA_INITIATOR_POS);
delba.reason_code = cpu_to_le16(WLAN_REASON_QSTA_TIMEOUT);
mwifiex_send_cmd_async(priv, HostCmd_CMD_11N_DELBA, 0, 0, &delba);
}
/*
* This function cleans up the Rx reorder table by deleting all the entries
* and re-initializing.
*/
void mwifiex_11n_cleanup_reorder_tbl(struct mwifiex_private *priv)
{
struct mwifiex_rx_reorder_tbl *del_tbl_ptr, *tmp_node;
unsigned long flags;
spin_lock_irqsave(&priv->rx_reorder_tbl_lock, flags);
list_for_each_entry_safe(del_tbl_ptr, tmp_node,
&priv->rx_reorder_tbl_ptr, list) {
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock, flags);
mwifiex_del_rx_reorder_entry(priv, del_tbl_ptr);
spin_lock_irqsave(&priv->rx_reorder_tbl_lock, flags);
}
spin_unlock_irqrestore(&priv->rx_reorder_tbl_lock, flags);
INIT_LIST_HEAD(&priv->rx_reorder_tbl_ptr);
mwifiex_reset_11n_rx_seq_num(priv);
}
| gpl-2.0 |
YUPlayGod/android_kernel_yu_msm8916 | drivers/usb/core/file.c | 2352 | 6383 | /*
* drivers/usb/core/file.c
*
* (C) Copyright Linus Torvalds 1999
* (C) Copyright Johannes Erdfelt 1999-2001
* (C) Copyright Andreas Gal 1999
* (C) Copyright Gregory P. Smith 1999
* (C) Copyright Deti Fliegl 1999 (new USB architecture)
* (C) Copyright Randy Dunlap 2000
* (C) Copyright David Brownell 2000-2001 (kernel hotplug, usb_device_id,
more docs, etc)
* (C) Copyright Yggdrasil Computing, Inc. 2000
* (usb_device_id matching changes by Adam J. Richter)
* (C) Copyright Greg Kroah-Hartman 2002-2003
*
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/rwsem.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include "usb.h"
#define MAX_USB_MINORS 256
static const struct file_operations *usb_minors[MAX_USB_MINORS];
static DECLARE_RWSEM(minor_rwsem);
static int usb_open(struct inode * inode, struct file * file)
{
int minor = iminor(inode);
const struct file_operations *c;
int err = -ENODEV;
const struct file_operations *old_fops, *new_fops = NULL;
down_read(&minor_rwsem);
c = usb_minors[minor];
if (!c || !(new_fops = fops_get(c)))
goto done;
old_fops = file->f_op;
file->f_op = new_fops;
/* Curiouser and curiouser... NULL ->open() as "no device" ? */
if (file->f_op->open)
err = file->f_op->open(inode,file);
if (err) {
fops_put(file->f_op);
file->f_op = fops_get(old_fops);
}
fops_put(old_fops);
done:
up_read(&minor_rwsem);
return err;
}
static const struct file_operations usb_fops = {
.owner = THIS_MODULE,
.open = usb_open,
.llseek = noop_llseek,
};
static struct usb_class {
struct kref kref;
struct class *class;
} *usb_class;
static char *usb_devnode(struct device *dev, umode_t *mode)
{
struct usb_class_driver *drv;
drv = dev_get_drvdata(dev);
if (!drv || !drv->devnode)
return NULL;
return drv->devnode(dev, mode);
}
static int init_usb_class(void)
{
int result = 0;
if (usb_class != NULL) {
kref_get(&usb_class->kref);
goto exit;
}
usb_class = kmalloc(sizeof(*usb_class), GFP_KERNEL);
if (!usb_class) {
result = -ENOMEM;
goto exit;
}
kref_init(&usb_class->kref);
usb_class->class = class_create(THIS_MODULE, "usbmisc");
if (IS_ERR(usb_class->class)) {
result = IS_ERR(usb_class->class);
printk(KERN_ERR "class_create failed for usb devices\n");
kfree(usb_class);
usb_class = NULL;
goto exit;
}
usb_class->class->devnode = usb_devnode;
exit:
return result;
}
static void release_usb_class(struct kref *kref)
{
/* Ok, we cheat as we know we only have one usb_class */
class_destroy(usb_class->class);
kfree(usb_class);
usb_class = NULL;
}
static void destroy_usb_class(void)
{
if (usb_class)
kref_put(&usb_class->kref, release_usb_class);
}
int usb_major_init(void)
{
int error;
error = register_chrdev(USB_MAJOR, "usb", &usb_fops);
if (error)
printk(KERN_ERR "Unable to get major %d for usb devices\n",
USB_MAJOR);
return error;
}
void usb_major_cleanup(void)
{
unregister_chrdev(USB_MAJOR, "usb");
}
/**
* usb_register_dev - register a USB device, and ask for a minor number
* @intf: pointer to the usb_interface that is being registered
* @class_driver: pointer to the usb_class_driver for this device
*
* This should be called by all USB drivers that use the USB major number.
* If CONFIG_USB_DYNAMIC_MINORS is enabled, the minor number will be
* dynamically allocated out of the list of available ones. If it is not
* enabled, the minor number will be based on the next available free minor,
* starting at the class_driver->minor_base.
*
* This function also creates a usb class device in the sysfs tree.
*
* usb_deregister_dev() must be called when the driver is done with
* the minor numbers given out by this function.
*
* Returns -EINVAL if something bad happens with trying to register a
* device, and 0 on success.
*/
int usb_register_dev(struct usb_interface *intf,
struct usb_class_driver *class_driver)
{
int retval;
int minor_base = class_driver->minor_base;
int minor;
char name[20];
char *temp;
#ifdef CONFIG_USB_DYNAMIC_MINORS
/*
* We don't care what the device tries to start at, we want to start
* at zero to pack the devices into the smallest available space with
* no holes in the minor range.
*/
minor_base = 0;
#endif
if (class_driver->fops == NULL)
return -EINVAL;
if (intf->minor >= 0)
return -EADDRINUSE;
retval = init_usb_class();
if (retval)
return retval;
dev_dbg(&intf->dev, "looking for a minor, starting at %d\n", minor_base);
down_write(&minor_rwsem);
for (minor = minor_base; minor < MAX_USB_MINORS; ++minor) {
if (usb_minors[minor])
continue;
usb_minors[minor] = class_driver->fops;
intf->minor = minor;
break;
}
up_write(&minor_rwsem);
if (intf->minor < 0)
return -EXFULL;
/* create a usb class device for this usb interface */
snprintf(name, sizeof(name), class_driver->name, minor - minor_base);
temp = strrchr(name, '/');
if (temp && (temp[1] != '\0'))
++temp;
else
temp = name;
intf->usb_dev = device_create(usb_class->class, &intf->dev,
MKDEV(USB_MAJOR, minor), class_driver,
"%s", temp);
if (IS_ERR(intf->usb_dev)) {
down_write(&minor_rwsem);
usb_minors[minor] = NULL;
intf->minor = -1;
up_write(&minor_rwsem);
retval = PTR_ERR(intf->usb_dev);
}
return retval;
}
EXPORT_SYMBOL_GPL(usb_register_dev);
/**
* usb_deregister_dev - deregister a USB device's dynamic minor.
* @intf: pointer to the usb_interface that is being deregistered
* @class_driver: pointer to the usb_class_driver for this device
*
* Used in conjunction with usb_register_dev(). This function is called
* when the USB driver is finished with the minor numbers gotten from a
* call to usb_register_dev() (usually when the device is disconnected
* from the system.)
*
* This function also removes the usb class device from the sysfs tree.
*
* This should be called by all drivers that use the USB major number.
*/
void usb_deregister_dev(struct usb_interface *intf,
struct usb_class_driver *class_driver)
{
if (intf->minor == -1)
return;
dev_dbg(&intf->dev, "removing %d minor\n", intf->minor);
down_write(&minor_rwsem);
usb_minors[intf->minor] = NULL;
up_write(&minor_rwsem);
device_destroy(usb_class->class, MKDEV(USB_MAJOR, intf->minor));
intf->usb_dev = NULL;
intf->minor = -1;
destroy_usb_class();
}
EXPORT_SYMBOL_GPL(usb_deregister_dev);
| gpl-2.0 |
TREX-ROM/android_kernel_asus_grouper | drivers/gpu/drm/radeon/r600_blit.c | 2608 | 22490 | /*
* Copyright 2009 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the 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 HOLDER(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.
*
* Authors:
* Alex Deucher <alexander.deucher@amd.com>
*/
#include "drmP.h"
#include "drm.h"
#include "radeon_drm.h"
#include "radeon_drv.h"
#include "r600_blit_shaders.h"
#define DI_PT_RECTLIST 0x11
#define DI_INDEX_SIZE_16_BIT 0x0
#define DI_SRC_SEL_AUTO_INDEX 0x2
#define FMT_8 0x1
#define FMT_5_6_5 0x8
#define FMT_8_8_8_8 0x1a
#define COLOR_8 0x1
#define COLOR_5_6_5 0x8
#define COLOR_8_8_8_8 0x1a
static inline void
set_render_target(drm_radeon_private_t *dev_priv, int format, int w, int h, u64 gpu_addr)
{
u32 cb_color_info;
int pitch, slice;
RING_LOCALS;
DRM_DEBUG("\n");
h = ALIGN(h, 8);
if (h < 8)
h = 8;
cb_color_info = ((format << 2) | (1 << 27));
pitch = (w / 8) - 1;
slice = ((w * h) / 64) - 1;
if (((dev_priv->flags & RADEON_FAMILY_MASK) > CHIP_R600) &&
((dev_priv->flags & RADEON_FAMILY_MASK) < CHIP_RV770)) {
BEGIN_RING(21 + 2);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_BASE - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(gpu_addr >> 8);
OUT_RING(CP_PACKET3(R600_IT_SURFACE_BASE_UPDATE, 0));
OUT_RING(2 << 0);
} else {
BEGIN_RING(21);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_BASE - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(gpu_addr >> 8);
}
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_SIZE - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING((pitch << 0) | (slice << 10));
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_VIEW - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_INFO - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(cb_color_info);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_TILE - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_FRAG - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_CB_COLOR0_MASK - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
ADVANCE_RING();
}
static inline void
cp_set_surface_sync(drm_radeon_private_t *dev_priv,
u32 sync_type, u32 size, u64 mc_addr)
{
u32 cp_coher_size;
RING_LOCALS;
DRM_DEBUG("\n");
if (size == 0xffffffff)
cp_coher_size = 0xffffffff;
else
cp_coher_size = ((size + 255) >> 8);
BEGIN_RING(5);
OUT_RING(CP_PACKET3(R600_IT_SURFACE_SYNC, 3));
OUT_RING(sync_type);
OUT_RING(cp_coher_size);
OUT_RING((mc_addr >> 8));
OUT_RING(10); /* poll interval */
ADVANCE_RING();
}
static inline void
set_shaders(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
u64 gpu_addr;
int i;
u32 *vs, *ps;
uint32_t sq_pgm_resources;
RING_LOCALS;
DRM_DEBUG("\n");
/* load shaders */
vs = (u32 *) ((char *)dev->agp_buffer_map->handle + dev_priv->blit_vb->offset);
ps = (u32 *) ((char *)dev->agp_buffer_map->handle + dev_priv->blit_vb->offset + 256);
for (i = 0; i < r6xx_vs_size; i++)
vs[i] = cpu_to_le32(r6xx_vs[i]);
for (i = 0; i < r6xx_ps_size; i++)
ps[i] = cpu_to_le32(r6xx_ps[i]);
dev_priv->blit_vb->used = 512;
gpu_addr = dev_priv->gart_buffers_offset + dev_priv->blit_vb->offset;
/* setup shader regs */
sq_pgm_resources = (1 << 0);
BEGIN_RING(9 + 12);
/* VS */
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_START_VS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(gpu_addr >> 8);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_RESOURCES_VS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(sq_pgm_resources);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_CF_OFFSET_VS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
/* PS */
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_START_PS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING((gpu_addr + 256) >> 8);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_RESOURCES_PS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(sq_pgm_resources | (1 << 28));
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_EXPORTS_PS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(2);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 1));
OUT_RING((R600_SQ_PGM_CF_OFFSET_PS - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING(0);
ADVANCE_RING();
cp_set_surface_sync(dev_priv,
R600_SH_ACTION_ENA, 512, gpu_addr);
}
static inline void
set_vtx_resource(drm_radeon_private_t *dev_priv, u64 gpu_addr)
{
uint32_t sq_vtx_constant_word2;
RING_LOCALS;
DRM_DEBUG("\n");
sq_vtx_constant_word2 = (((gpu_addr >> 32) & 0xff) | (16 << 8));
#ifdef __BIG_ENDIAN
sq_vtx_constant_word2 |= (2 << 30);
#endif
BEGIN_RING(9);
OUT_RING(CP_PACKET3(R600_IT_SET_RESOURCE, 7));
OUT_RING(0x460);
OUT_RING(gpu_addr & 0xffffffff);
OUT_RING(48 - 1);
OUT_RING(sq_vtx_constant_word2);
OUT_RING(1 << 0);
OUT_RING(0);
OUT_RING(0);
OUT_RING(R600_SQ_TEX_VTX_VALID_BUFFER << 30);
ADVANCE_RING();
if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV710))
cp_set_surface_sync(dev_priv,
R600_TC_ACTION_ENA, 48, gpu_addr);
else
cp_set_surface_sync(dev_priv,
R600_VC_ACTION_ENA, 48, gpu_addr);
}
static inline void
set_tex_resource(drm_radeon_private_t *dev_priv,
int format, int w, int h, int pitch, u64 gpu_addr)
{
uint32_t sq_tex_resource_word0, sq_tex_resource_word1, sq_tex_resource_word4;
RING_LOCALS;
DRM_DEBUG("\n");
if (h < 1)
h = 1;
sq_tex_resource_word0 = (1 << 0);
sq_tex_resource_word0 |= ((((pitch >> 3) - 1) << 8) |
((w - 1) << 19));
sq_tex_resource_word1 = (format << 26);
sq_tex_resource_word1 |= ((h - 1) << 0);
sq_tex_resource_word4 = ((1 << 14) |
(0 << 16) |
(1 << 19) |
(2 << 22) |
(3 << 25));
BEGIN_RING(9);
OUT_RING(CP_PACKET3(R600_IT_SET_RESOURCE, 7));
OUT_RING(0);
OUT_RING(sq_tex_resource_word0);
OUT_RING(sq_tex_resource_word1);
OUT_RING(gpu_addr >> 8);
OUT_RING(gpu_addr >> 8);
OUT_RING(sq_tex_resource_word4);
OUT_RING(0);
OUT_RING(R600_SQ_TEX_VTX_VALID_TEXTURE << 30);
ADVANCE_RING();
}
static inline void
set_scissors(drm_radeon_private_t *dev_priv, int x1, int y1, int x2, int y2)
{
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(12);
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 2));
OUT_RING((R600_PA_SC_SCREEN_SCISSOR_TL - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING((x1 << 0) | (y1 << 16));
OUT_RING((x2 << 0) | (y2 << 16));
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 2));
OUT_RING((R600_PA_SC_GENERIC_SCISSOR_TL - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING((x1 << 0) | (y1 << 16) | (1 << 31));
OUT_RING((x2 << 0) | (y2 << 16));
OUT_RING(CP_PACKET3(R600_IT_SET_CONTEXT_REG, 2));
OUT_RING((R600_PA_SC_WINDOW_SCISSOR_TL - R600_SET_CONTEXT_REG_OFFSET) >> 2);
OUT_RING((x1 << 0) | (y1 << 16) | (1 << 31));
OUT_RING((x2 << 0) | (y2 << 16));
ADVANCE_RING();
}
static inline void
draw_auto(drm_radeon_private_t *dev_priv)
{
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(10);
OUT_RING(CP_PACKET3(R600_IT_SET_CONFIG_REG, 1));
OUT_RING((R600_VGT_PRIMITIVE_TYPE - R600_SET_CONFIG_REG_OFFSET) >> 2);
OUT_RING(DI_PT_RECTLIST);
OUT_RING(CP_PACKET3(R600_IT_INDEX_TYPE, 0));
#ifdef __BIG_ENDIAN
OUT_RING((2 << 2) | DI_INDEX_SIZE_16_BIT);
#else
OUT_RING(DI_INDEX_SIZE_16_BIT);
#endif
OUT_RING(CP_PACKET3(R600_IT_NUM_INSTANCES, 0));
OUT_RING(1);
OUT_RING(CP_PACKET3(R600_IT_DRAW_INDEX_AUTO, 1));
OUT_RING(3);
OUT_RING(DI_SRC_SEL_AUTO_INDEX);
ADVANCE_RING();
COMMIT_RING();
}
static inline void
set_default_state(drm_radeon_private_t *dev_priv)
{
int i;
u32 sq_config, sq_gpr_resource_mgmt_1, sq_gpr_resource_mgmt_2;
u32 sq_thread_resource_mgmt, sq_stack_resource_mgmt_1, sq_stack_resource_mgmt_2;
int num_ps_gprs, num_vs_gprs, num_temp_gprs, num_gs_gprs, num_es_gprs;
int num_ps_threads, num_vs_threads, num_gs_threads, num_es_threads;
int num_ps_stack_entries, num_vs_stack_entries, num_gs_stack_entries, num_es_stack_entries;
RING_LOCALS;
switch ((dev_priv->flags & RADEON_FAMILY_MASK)) {
case CHIP_R600:
num_ps_gprs = 192;
num_vs_gprs = 56;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 136;
num_vs_threads = 48;
num_gs_threads = 4;
num_es_threads = 4;
num_ps_stack_entries = 128;
num_vs_stack_entries = 128;
num_gs_stack_entries = 0;
num_es_stack_entries = 0;
break;
case CHIP_RV630:
case CHIP_RV635:
num_ps_gprs = 84;
num_vs_gprs = 36;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 144;
num_vs_threads = 40;
num_gs_threads = 4;
num_es_threads = 4;
num_ps_stack_entries = 40;
num_vs_stack_entries = 40;
num_gs_stack_entries = 32;
num_es_stack_entries = 16;
break;
case CHIP_RV610:
case CHIP_RV620:
case CHIP_RS780:
case CHIP_RS880:
default:
num_ps_gprs = 84;
num_vs_gprs = 36;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 136;
num_vs_threads = 48;
num_gs_threads = 4;
num_es_threads = 4;
num_ps_stack_entries = 40;
num_vs_stack_entries = 40;
num_gs_stack_entries = 32;
num_es_stack_entries = 16;
break;
case CHIP_RV670:
num_ps_gprs = 144;
num_vs_gprs = 40;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 136;
num_vs_threads = 48;
num_gs_threads = 4;
num_es_threads = 4;
num_ps_stack_entries = 40;
num_vs_stack_entries = 40;
num_gs_stack_entries = 32;
num_es_stack_entries = 16;
break;
case CHIP_RV770:
num_ps_gprs = 192;
num_vs_gprs = 56;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 188;
num_vs_threads = 60;
num_gs_threads = 0;
num_es_threads = 0;
num_ps_stack_entries = 256;
num_vs_stack_entries = 256;
num_gs_stack_entries = 0;
num_es_stack_entries = 0;
break;
case CHIP_RV730:
case CHIP_RV740:
num_ps_gprs = 84;
num_vs_gprs = 36;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 188;
num_vs_threads = 60;
num_gs_threads = 0;
num_es_threads = 0;
num_ps_stack_entries = 128;
num_vs_stack_entries = 128;
num_gs_stack_entries = 0;
num_es_stack_entries = 0;
break;
case CHIP_RV710:
num_ps_gprs = 192;
num_vs_gprs = 56;
num_temp_gprs = 4;
num_gs_gprs = 0;
num_es_gprs = 0;
num_ps_threads = 144;
num_vs_threads = 48;
num_gs_threads = 0;
num_es_threads = 0;
num_ps_stack_entries = 128;
num_vs_stack_entries = 128;
num_gs_stack_entries = 0;
num_es_stack_entries = 0;
break;
}
if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV710))
sq_config = 0;
else
sq_config = R600_VC_ENABLE;
sq_config |= (R600_DX9_CONSTS |
R600_ALU_INST_PREFER_VECTOR |
R600_PS_PRIO(0) |
R600_VS_PRIO(1) |
R600_GS_PRIO(2) |
R600_ES_PRIO(3));
sq_gpr_resource_mgmt_1 = (R600_NUM_PS_GPRS(num_ps_gprs) |
R600_NUM_VS_GPRS(num_vs_gprs) |
R600_NUM_CLAUSE_TEMP_GPRS(num_temp_gprs));
sq_gpr_resource_mgmt_2 = (R600_NUM_GS_GPRS(num_gs_gprs) |
R600_NUM_ES_GPRS(num_es_gprs));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS(num_ps_threads) |
R600_NUM_VS_THREADS(num_vs_threads) |
R600_NUM_GS_THREADS(num_gs_threads) |
R600_NUM_ES_THREADS(num_es_threads));
sq_stack_resource_mgmt_1 = (R600_NUM_PS_STACK_ENTRIES(num_ps_stack_entries) |
R600_NUM_VS_STACK_ENTRIES(num_vs_stack_entries));
sq_stack_resource_mgmt_2 = (R600_NUM_GS_STACK_ENTRIES(num_gs_stack_entries) |
R600_NUM_ES_STACK_ENTRIES(num_es_stack_entries));
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770) {
BEGIN_RING(r7xx_default_size + 10);
for (i = 0; i < r7xx_default_size; i++)
OUT_RING(r7xx_default_state[i]);
} else {
BEGIN_RING(r6xx_default_size + 10);
for (i = 0; i < r6xx_default_size; i++)
OUT_RING(r6xx_default_state[i]);
}
OUT_RING(CP_PACKET3(R600_IT_EVENT_WRITE, 0));
OUT_RING(R600_CACHE_FLUSH_AND_INV_EVENT);
/* SQ config */
OUT_RING(CP_PACKET3(R600_IT_SET_CONFIG_REG, 6));
OUT_RING((R600_SQ_CONFIG - R600_SET_CONFIG_REG_OFFSET) >> 2);
OUT_RING(sq_config);
OUT_RING(sq_gpr_resource_mgmt_1);
OUT_RING(sq_gpr_resource_mgmt_2);
OUT_RING(sq_thread_resource_mgmt);
OUT_RING(sq_stack_resource_mgmt_1);
OUT_RING(sq_stack_resource_mgmt_2);
ADVANCE_RING();
}
static inline uint32_t i2f(uint32_t input)
{
u32 result, i, exponent, fraction;
if ((input & 0x3fff) == 0)
result = 0; /* 0 is a special case */
else {
exponent = 140; /* exponent biased by 127; */
fraction = (input & 0x3fff) << 10; /* cheat and only
handle numbers below 2^^15 */
for (i = 0; i < 14; i++) {
if (fraction & 0x800000)
break;
else {
fraction = fraction << 1; /* keep
shifting left until top bit = 1 */
exponent = exponent - 1;
}
}
result = exponent << 23 | (fraction & 0x7fffff); /* mask
off top bit; assumed 1 */
}
return result;
}
static inline int r600_nomm_get_vb(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
dev_priv->blit_vb = radeon_freelist_get(dev);
if (!dev_priv->blit_vb) {
DRM_ERROR("Unable to allocate vertex buffer for blit\n");
return -EAGAIN;
}
return 0;
}
static inline void r600_nomm_put_vb(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
dev_priv->blit_vb->used = 0;
radeon_cp_discard_buffer(dev, dev_priv->blit_vb->file_priv->master, dev_priv->blit_vb);
}
static inline void *r600_nomm_get_vb_ptr(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
return (((char *)dev->agp_buffer_map->handle +
dev_priv->blit_vb->offset + dev_priv->blit_vb->used));
}
int
r600_prepare_blit_copy(struct drm_device *dev, struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
int ret;
DRM_DEBUG("\n");
ret = r600_nomm_get_vb(dev);
if (ret)
return ret;
dev_priv->blit_vb->file_priv = file_priv;
set_default_state(dev_priv);
set_shaders(dev);
return 0;
}
void
r600_done_blit_copy(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(5);
OUT_RING(CP_PACKET3(R600_IT_EVENT_WRITE, 0));
OUT_RING(R600_CACHE_FLUSH_AND_INV_EVENT);
/* wait for 3D idle clean */
OUT_RING(CP_PACKET3(R600_IT_SET_CONFIG_REG, 1));
OUT_RING((R600_WAIT_UNTIL - R600_SET_CONFIG_REG_OFFSET) >> 2);
OUT_RING(RADEON_WAIT_3D_IDLE | RADEON_WAIT_3D_IDLECLEAN);
ADVANCE_RING();
COMMIT_RING();
r600_nomm_put_vb(dev);
}
void
r600_blit_copy(struct drm_device *dev,
uint64_t src_gpu_addr, uint64_t dst_gpu_addr,
int size_bytes)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
int max_bytes;
u64 vb_addr;
u32 *vb;
vb = r600_nomm_get_vb_ptr(dev);
if ((size_bytes & 3) || (src_gpu_addr & 3) || (dst_gpu_addr & 3)) {
max_bytes = 8192;
while (size_bytes) {
int cur_size = size_bytes;
int src_x = src_gpu_addr & 255;
int dst_x = dst_gpu_addr & 255;
int h = 1;
src_gpu_addr = src_gpu_addr & ~255;
dst_gpu_addr = dst_gpu_addr & ~255;
if (!src_x && !dst_x) {
h = (cur_size / max_bytes);
if (h > 8192)
h = 8192;
if (h == 0)
h = 1;
else
cur_size = max_bytes;
} else {
if (cur_size > max_bytes)
cur_size = max_bytes;
if (cur_size > (max_bytes - dst_x))
cur_size = (max_bytes - dst_x);
if (cur_size > (max_bytes - src_x))
cur_size = (max_bytes - src_x);
}
if ((dev_priv->blit_vb->used + 48) > dev_priv->blit_vb->total) {
r600_nomm_put_vb(dev);
r600_nomm_get_vb(dev);
if (!dev_priv->blit_vb)
return;
set_shaders(dev);
vb = r600_nomm_get_vb_ptr(dev);
}
vb[0] = i2f(dst_x);
vb[1] = 0;
vb[2] = i2f(src_x);
vb[3] = 0;
vb[4] = i2f(dst_x);
vb[5] = i2f(h);
vb[6] = i2f(src_x);
vb[7] = i2f(h);
vb[8] = i2f(dst_x + cur_size);
vb[9] = i2f(h);
vb[10] = i2f(src_x + cur_size);
vb[11] = i2f(h);
/* src */
set_tex_resource(dev_priv, FMT_8,
src_x + cur_size, h, src_x + cur_size,
src_gpu_addr);
cp_set_surface_sync(dev_priv,
R600_TC_ACTION_ENA, (src_x + cur_size * h), src_gpu_addr);
/* dst */
set_render_target(dev_priv, COLOR_8,
dst_x + cur_size, h,
dst_gpu_addr);
/* scissors */
set_scissors(dev_priv, dst_x, 0, dst_x + cur_size, h);
/* Vertex buffer setup */
vb_addr = dev_priv->gart_buffers_offset +
dev_priv->blit_vb->offset +
dev_priv->blit_vb->used;
set_vtx_resource(dev_priv, vb_addr);
/* draw */
draw_auto(dev_priv);
cp_set_surface_sync(dev_priv,
R600_CB_ACTION_ENA | R600_CB0_DEST_BASE_ENA,
cur_size * h, dst_gpu_addr);
vb += 12;
dev_priv->blit_vb->used += 12 * 4;
src_gpu_addr += cur_size * h;
dst_gpu_addr += cur_size * h;
size_bytes -= cur_size * h;
}
} else {
max_bytes = 8192 * 4;
while (size_bytes) {
int cur_size = size_bytes;
int src_x = (src_gpu_addr & 255);
int dst_x = (dst_gpu_addr & 255);
int h = 1;
src_gpu_addr = src_gpu_addr & ~255;
dst_gpu_addr = dst_gpu_addr & ~255;
if (!src_x && !dst_x) {
h = (cur_size / max_bytes);
if (h > 8192)
h = 8192;
if (h == 0)
h = 1;
else
cur_size = max_bytes;
} else {
if (cur_size > max_bytes)
cur_size = max_bytes;
if (cur_size > (max_bytes - dst_x))
cur_size = (max_bytes - dst_x);
if (cur_size > (max_bytes - src_x))
cur_size = (max_bytes - src_x);
}
if ((dev_priv->blit_vb->used + 48) > dev_priv->blit_vb->total) {
r600_nomm_put_vb(dev);
r600_nomm_get_vb(dev);
if (!dev_priv->blit_vb)
return;
set_shaders(dev);
vb = r600_nomm_get_vb_ptr(dev);
}
vb[0] = i2f(dst_x / 4);
vb[1] = 0;
vb[2] = i2f(src_x / 4);
vb[3] = 0;
vb[4] = i2f(dst_x / 4);
vb[5] = i2f(h);
vb[6] = i2f(src_x / 4);
vb[7] = i2f(h);
vb[8] = i2f((dst_x + cur_size) / 4);
vb[9] = i2f(h);
vb[10] = i2f((src_x + cur_size) / 4);
vb[11] = i2f(h);
/* src */
set_tex_resource(dev_priv, FMT_8_8_8_8,
(src_x + cur_size) / 4,
h, (src_x + cur_size) / 4,
src_gpu_addr);
cp_set_surface_sync(dev_priv,
R600_TC_ACTION_ENA, (src_x + cur_size * h), src_gpu_addr);
/* dst */
set_render_target(dev_priv, COLOR_8_8_8_8,
(dst_x + cur_size) / 4, h,
dst_gpu_addr);
/* scissors */
set_scissors(dev_priv, (dst_x / 4), 0, (dst_x + cur_size / 4), h);
/* Vertex buffer setup */
vb_addr = dev_priv->gart_buffers_offset +
dev_priv->blit_vb->offset +
dev_priv->blit_vb->used;
set_vtx_resource(dev_priv, vb_addr);
/* draw */
draw_auto(dev_priv);
cp_set_surface_sync(dev_priv,
R600_CB_ACTION_ENA | R600_CB0_DEST_BASE_ENA,
cur_size * h, dst_gpu_addr);
vb += 12;
dev_priv->blit_vb->used += 12 * 4;
src_gpu_addr += cur_size * h;
dst_gpu_addr += cur_size * h;
size_bytes -= cur_size * h;
}
}
}
void
r600_blit_swap(struct drm_device *dev,
uint64_t src_gpu_addr, uint64_t dst_gpu_addr,
int sx, int sy, int dx, int dy,
int w, int h, int src_pitch, int dst_pitch, int cpp)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
int cb_format, tex_format;
int sx2, sy2, dx2, dy2;
u64 vb_addr;
u32 *vb;
if ((dev_priv->blit_vb->used + 48) > dev_priv->blit_vb->total) {
r600_nomm_put_vb(dev);
r600_nomm_get_vb(dev);
if (!dev_priv->blit_vb)
return;
set_shaders(dev);
}
vb = r600_nomm_get_vb_ptr(dev);
sx2 = sx + w;
sy2 = sy + h;
dx2 = dx + w;
dy2 = dy + h;
vb[0] = i2f(dx);
vb[1] = i2f(dy);
vb[2] = i2f(sx);
vb[3] = i2f(sy);
vb[4] = i2f(dx);
vb[5] = i2f(dy2);
vb[6] = i2f(sx);
vb[7] = i2f(sy2);
vb[8] = i2f(dx2);
vb[9] = i2f(dy2);
vb[10] = i2f(sx2);
vb[11] = i2f(sy2);
switch(cpp) {
case 4:
cb_format = COLOR_8_8_8_8;
tex_format = FMT_8_8_8_8;
break;
case 2:
cb_format = COLOR_5_6_5;
tex_format = FMT_5_6_5;
break;
default:
cb_format = COLOR_8;
tex_format = FMT_8;
break;
}
/* src */
set_tex_resource(dev_priv, tex_format,
src_pitch / cpp,
sy2, src_pitch / cpp,
src_gpu_addr);
cp_set_surface_sync(dev_priv,
R600_TC_ACTION_ENA, src_pitch * sy2, src_gpu_addr);
/* dst */
set_render_target(dev_priv, cb_format,
dst_pitch / cpp, dy2,
dst_gpu_addr);
/* scissors */
set_scissors(dev_priv, dx, dy, dx2, dy2);
/* Vertex buffer setup */
vb_addr = dev_priv->gart_buffers_offset +
dev_priv->blit_vb->offset +
dev_priv->blit_vb->used;
set_vtx_resource(dev_priv, vb_addr);
/* draw */
draw_auto(dev_priv);
cp_set_surface_sync(dev_priv,
R600_CB_ACTION_ENA | R600_CB0_DEST_BASE_ENA,
dst_pitch * dy2, dst_gpu_addr);
dev_priv->blit_vb->used += 12 * 4;
}
| gpl-2.0 |
UberSlim/KernelSanders_L90 | arch/sparc/kernel/setup_32.c | 4400 | 8241 | /*
* linux/arch/sparc/kernel/setup.c
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2000 Anton Blanchard (anton@samba.org)
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/initrd.h>
#include <asm/smp.h>
#include <linux/user.h>
#include <linux/screen_info.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/syscalls.h>
#include <linux/kdev_t.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/console.h>
#include <linux/spinlock.h>
#include <linux/root_dev.h>
#include <linux/cpu.h>
#include <linux/kdebug.h>
#include <linux/export.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/traps.h>
#include <asm/vaddrs.h>
#include <asm/mbus.h>
#include <asm/idprom.h>
#include <asm/machines.h>
#include <asm/cpudata.h>
#include <asm/setup.h>
#include <asm/cacheflush.h>
#include "kernel.h"
struct screen_info screen_info = {
0, 0, /* orig-x, orig-y */
0, /* unused */
0, /* orig-video-page */
0, /* orig-video-mode */
128, /* orig-video-cols */
0,0,0, /* ega_ax, ega_bx, ega_cx */
54, /* orig-video-lines */
0, /* orig-video-isVGA */
16 /* orig-video-points */
};
/* Typing sync at the prom prompt calls the function pointed to by
* romvec->pv_synchook which I set to the following function.
* This should sync all filesystems and return, for now it just
* prints out pretty messages and returns.
*/
extern unsigned long trapbase;
/* Pretty sick eh? */
static void prom_sync_me(void)
{
unsigned long prom_tbr, flags;
/* XXX Badly broken. FIX! - Anton */
local_irq_save(flags);
__asm__ __volatile__("rd %%tbr, %0\n\t" : "=r" (prom_tbr));
__asm__ __volatile__("wr %0, 0x0, %%tbr\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t" : : "r" (&trapbase));
prom_printf("PROM SYNC COMMAND...\n");
show_free_areas(0);
if (!is_idle_task(current)) {
local_irq_enable();
sys_sync();
local_irq_disable();
}
prom_printf("Returning to prom\n");
__asm__ __volatile__("wr %0, 0x0, %%tbr\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t" : : "r" (prom_tbr));
local_irq_restore(flags);
}
static unsigned int boot_flags __initdata = 0;
#define BOOTME_DEBUG 0x1
/* Exported for mm/init.c:paging_init. */
unsigned long cmdline_memory_size __initdata = 0;
/* which CPU booted us (0xff = not set) */
unsigned char boot_cpu_id = 0xff; /* 0xff will make it into DATA section... */
unsigned char boot_cpu_id4; /* boot_cpu_id << 2 */
static void
prom_console_write(struct console *con, const char *s, unsigned n)
{
prom_write(s, n);
}
static struct console prom_early_console = {
.name = "earlyprom",
.write = prom_console_write,
.flags = CON_PRINTBUFFER | CON_BOOT,
.index = -1,
};
/*
* Process kernel command line switches that are specific to the
* SPARC or that require special low-level processing.
*/
static void __init process_switch(char c)
{
switch (c) {
case 'd':
boot_flags |= BOOTME_DEBUG;
break;
case 's':
break;
case 'h':
prom_printf("boot_flags_init: Halt!\n");
prom_halt();
break;
case 'p':
prom_early_console.flags &= ~CON_BOOT;
break;
default:
printk("Unknown boot switch (-%c)\n", c);
break;
}
}
static void __init boot_flags_init(char *commands)
{
while (*commands) {
/* Move to the start of the next "argument". */
while (*commands && *commands == ' ')
commands++;
/* Process any command switches, otherwise skip it. */
if (*commands == '\0')
break;
if (*commands == '-') {
commands++;
while (*commands && *commands != ' ')
process_switch(*commands++);
continue;
}
if (!strncmp(commands, "mem=", 4)) {
/*
* "mem=XXX[kKmM] overrides the PROM-reported
* memory size.
*/
cmdline_memory_size = simple_strtoul(commands + 4,
&commands, 0);
if (*commands == 'K' || *commands == 'k') {
cmdline_memory_size <<= 10;
commands++;
} else if (*commands=='M' || *commands=='m') {
cmdline_memory_size <<= 20;
commands++;
}
}
while (*commands && *commands != ' ')
commands++;
}
}
/* This routine will in the future do all the nasty prom stuff
* to probe for the mmu type and its parameters, etc. This will
* also be where SMP things happen.
*/
extern void sun4c_probe_vac(void);
extern unsigned short root_flags;
extern unsigned short root_dev;
extern unsigned short ram_flags;
#define RAMDISK_IMAGE_START_MASK 0x07FF
#define RAMDISK_PROMPT_FLAG 0x8000
#define RAMDISK_LOAD_FLAG 0x4000
extern int root_mountflags;
char reboot_command[COMMAND_LINE_SIZE];
enum sparc_cpu sparc_cpu_model;
EXPORT_SYMBOL(sparc_cpu_model);
struct tt_entry *sparc_ttable;
struct pt_regs fake_swapper_regs;
void __init setup_arch(char **cmdline_p)
{
int i;
unsigned long highest_paddr;
sparc_ttable = (struct tt_entry *) &trapbase;
/* Initialize PROM console and command line. */
*cmdline_p = prom_getbootargs();
strcpy(boot_command_line, *cmdline_p);
parse_early_param();
boot_flags_init(*cmdline_p);
register_console(&prom_early_console);
/* Set sparc_cpu_model */
sparc_cpu_model = sun_unknown;
if (!strcmp(&cputypval[0], "sun4 "))
sparc_cpu_model = sun4;
if (!strcmp(&cputypval[0], "sun4c"))
sparc_cpu_model = sun4c;
if (!strcmp(&cputypval[0], "sun4m"))
sparc_cpu_model = sun4m;
if (!strcmp(&cputypval[0], "sun4s"))
sparc_cpu_model = sun4m; /* CP-1200 with PROM 2.30 -E */
if (!strcmp(&cputypval[0], "sun4d"))
sparc_cpu_model = sun4d;
if (!strcmp(&cputypval[0], "sun4e"))
sparc_cpu_model = sun4e;
if (!strcmp(&cputypval[0], "sun4u"))
sparc_cpu_model = sun4u;
if (!strncmp(&cputypval[0], "leon" , 4))
sparc_cpu_model = sparc_leon;
printk("ARCH: ");
switch(sparc_cpu_model) {
case sun4:
printk("SUN4\n");
break;
case sun4c:
printk("SUN4C\n");
break;
case sun4m:
printk("SUN4M\n");
break;
case sun4d:
printk("SUN4D\n");
break;
case sun4e:
printk("SUN4E\n");
break;
case sun4u:
printk("SUN4U\n");
break;
case sparc_leon:
printk("LEON\n");
break;
default:
printk("UNKNOWN!\n");
break;
}
#ifdef CONFIG_DUMMY_CONSOLE
conswitchp = &dummy_con;
#endif
idprom_init();
if (ARCH_SUN4C)
sun4c_probe_vac();
load_mmu();
phys_base = 0xffffffffUL;
highest_paddr = 0UL;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long top;
if (sp_banks[i].base_addr < phys_base)
phys_base = sp_banks[i].base_addr;
top = sp_banks[i].base_addr +
sp_banks[i].num_bytes;
if (highest_paddr < top)
highest_paddr = top;
}
pfn_base = phys_base >> PAGE_SHIFT;
if (!root_flags)
root_mountflags &= ~MS_RDONLY;
ROOT_DEV = old_decode_dev(root_dev);
#ifdef CONFIG_BLK_DEV_RAM
rd_image_start = ram_flags & RAMDISK_IMAGE_START_MASK;
rd_prompt = ((ram_flags & RAMDISK_PROMPT_FLAG) != 0);
rd_doload = ((ram_flags & RAMDISK_LOAD_FLAG) != 0);
#endif
prom_setsync(prom_sync_me);
if((boot_flags&BOOTME_DEBUG) && (linux_dbvec!=0) &&
((*(short *)linux_dbvec) != -1)) {
printk("Booted under KADB. Syncing trap table.\n");
(*(linux_dbvec->teach_debugger))();
}
init_mm.context = (unsigned long) NO_CONTEXT;
init_task.thread.kregs = &fake_swapper_regs;
paging_init();
smp_setup_cpu_possible_map();
}
extern int stop_a_enabled;
void sun_do_break(void)
{
if (!stop_a_enabled)
return;
printk("\n");
flush_user_windows();
prom_cmdline();
}
EXPORT_SYMBOL(sun_do_break);
int stop_a_enabled = 1;
static int __init topology_init(void)
{
int i, ncpus, err;
/* Count the number of physically present processors in
* the machine, even on uniprocessor, so that /proc/cpuinfo
* output is consistent with 2.4.x
*/
ncpus = 0;
while (!cpu_find_by_instance(ncpus, NULL, NULL))
ncpus++;
ncpus_probed = ncpus;
err = 0;
for_each_online_cpu(i) {
struct cpu *p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p)
err = -ENOMEM;
else
register_cpu(p, i);
}
return err;
}
subsys_initcall(topology_init);
| gpl-2.0 |
schqiushui/kernel_kk_sense_a5 | arch/sparc/kernel/traps_64.c | 4400 | 76560 | /* arch/sparc64/kernel/traps.c
*
* Copyright (C) 1995,1997,2008,2009 David S. Miller (davem@davemloft.net)
* Copyright (C) 1997,1999,2000 Jakub Jelinek (jakub@redhat.com)
*/
/*
* I like traps on v9, :))))
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/linkage.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/smp.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/kdebug.h>
#include <linux/ftrace.h>
#include <linux/gfp.h>
#include <asm/smp.h>
#include <asm/delay.h>
#include <asm/ptrace.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/unistd.h>
#include <asm/uaccess.h>
#include <asm/fpumacro.h>
#include <asm/lsu.h>
#include <asm/dcu.h>
#include <asm/estate.h>
#include <asm/chafsr.h>
#include <asm/sfafsr.h>
#include <asm/psrcompat.h>
#include <asm/processor.h>
#include <asm/timer.h>
#include <asm/head.h>
#include <asm/prom.h>
#include <asm/memctrl.h>
#include <asm/cacheflush.h>
#include "entry.h"
#include "kstack.h"
/* When an irrecoverable trap occurs at tl > 0, the trap entry
* code logs the trap state registers at every level in the trap
* stack. It is found at (pt_regs + sizeof(pt_regs)) and the layout
* is as follows:
*/
struct tl1_traplog {
struct {
unsigned long tstate;
unsigned long tpc;
unsigned long tnpc;
unsigned long tt;
} trapstack[4];
unsigned long tl;
};
static void dump_tl1_traplog(struct tl1_traplog *p)
{
int i, limit;
printk(KERN_EMERG "TRAPLOG: Error at trap level 0x%lx, "
"dumping track stack.\n", p->tl);
limit = (tlb_type == hypervisor) ? 2 : 4;
for (i = 0; i < limit; i++) {
printk(KERN_EMERG
"TRAPLOG: Trap level %d TSTATE[%016lx] TPC[%016lx] "
"TNPC[%016lx] TT[%lx]\n",
i + 1,
p->trapstack[i].tstate, p->trapstack[i].tpc,
p->trapstack[i].tnpc, p->trapstack[i].tt);
printk("TRAPLOG: TPC<%pS>\n", (void *) p->trapstack[i].tpc);
}
}
void bad_trap(struct pt_regs *regs, long lvl)
{
char buffer[32];
siginfo_t info;
if (notify_die(DIE_TRAP, "bad trap", regs,
0, lvl, SIGTRAP) == NOTIFY_STOP)
return;
if (lvl < 0x100) {
sprintf(buffer, "Bad hw trap %lx at tl0\n", lvl);
die_if_kernel(buffer, regs);
}
lvl -= 0x100;
if (regs->tstate & TSTATE_PRIV) {
sprintf(buffer, "Kernel bad sw trap %lx", lvl);
die_if_kernel(buffer, regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLTRP;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = lvl;
force_sig_info(SIGILL, &info, current);
}
void bad_trap_tl1(struct pt_regs *regs, long lvl)
{
char buffer[32];
if (notify_die(DIE_TRAP_TL1, "bad trap tl1", regs,
0, lvl, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sprintf (buffer, "Bad trap %lx at tl>0", lvl);
die_if_kernel (buffer, regs);
}
#ifdef CONFIG_DEBUG_BUGVERBOSE
void do_BUG(const char *file, int line)
{
bust_spinlocks(1);
printk("kernel BUG at %s:%d!\n", file, line);
}
EXPORT_SYMBOL(do_BUG);
#endif
static DEFINE_SPINLOCK(dimm_handler_lock);
static dimm_printer_t dimm_handler;
static int sprintf_dimm(int synd_code, unsigned long paddr, char *buf, int buflen)
{
unsigned long flags;
int ret = -ENODEV;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (dimm_handler) {
ret = dimm_handler(synd_code, paddr, buf, buflen);
} else if (tlb_type == spitfire) {
if (prom_getunumber(synd_code, paddr, buf, buflen) == -1)
ret = -EINVAL;
else
ret = 0;
} else
ret = -ENODEV;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
return ret;
}
int register_dimm_printer(dimm_printer_t func)
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (!dimm_handler)
dimm_handler = func;
else
ret = -EEXIST;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(register_dimm_printer);
void unregister_dimm_printer(dimm_printer_t func)
{
unsigned long flags;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (dimm_handler == func)
dimm_handler = NULL;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
}
EXPORT_SYMBOL_GPL(unregister_dimm_printer);
void spitfire_insn_access_exception(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "instruction access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
printk("spitfire_insn_access_exception: SFSR[%016lx] "
"SFAR[%016lx], going.\n", sfsr, sfar);
die_if_kernel("Iax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void spitfire_insn_access_exception_tl1(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
if (notify_die(DIE_TRAP_TL1, "instruction access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
spitfire_insn_access_exception(regs, sfsr, sfar);
}
void sun4v_insn_access_exception(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
unsigned short type = (type_ctx >> 16);
unsigned short ctx = (type_ctx & 0xffff);
siginfo_t info;
if (notify_die(DIE_TRAP, "instruction access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
printk("sun4v_insn_access_exception: ADDR[%016lx] "
"CTX[%04x] TYPE[%04x], going.\n",
addr, ctx, type);
die_if_kernel("Iax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void sun4v_insn_access_exception_tl1(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
if (notify_die(DIE_TRAP_TL1, "instruction access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sun4v_insn_access_exception(regs, addr, type_ctx);
}
void spitfire_data_access_exception(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "data access exception", regs,
0, 0x30, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
/* Test if this comes from uaccess places. */
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* Ouch, somebody is trying VM hole tricks on us... */
#ifdef DEBUG_EXCEPTIONS
printk("Exception: PC<%016lx> faddr<UNKNOWN>\n", regs->tpc);
printk("EX_TABLE: insn<%016lx> fixup<%016lx>\n",
regs->tpc, entry->fixup);
#endif
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
return;
}
/* Shit... */
printk("spitfire_data_access_exception: SFSR[%016lx] "
"SFAR[%016lx], going.\n", sfsr, sfar);
die_if_kernel("Dax", regs);
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *)sfar;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void spitfire_data_access_exception_tl1(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
if (notify_die(DIE_TRAP_TL1, "data access exception tl1", regs,
0, 0x30, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
spitfire_data_access_exception(regs, sfsr, sfar);
}
void sun4v_data_access_exception(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
unsigned short type = (type_ctx >> 16);
unsigned short ctx = (type_ctx & 0xffff);
siginfo_t info;
if (notify_die(DIE_TRAP, "data access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
/* Test if this comes from uaccess places. */
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* Ouch, somebody is trying VM hole tricks on us... */
#ifdef DEBUG_EXCEPTIONS
printk("Exception: PC<%016lx> faddr<UNKNOWN>\n", regs->tpc);
printk("EX_TABLE: insn<%016lx> fixup<%016lx>\n",
regs->tpc, entry->fixup);
#endif
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
return;
}
printk("sun4v_data_access_exception: ADDR[%016lx] "
"CTX[%04x] TYPE[%04x], going.\n",
addr, ctx, type);
die_if_kernel("Dax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void sun4v_data_access_exception_tl1(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
if (notify_die(DIE_TRAP_TL1, "data access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sun4v_data_access_exception(regs, addr, type_ctx);
}
#ifdef CONFIG_PCI
#include "pci_impl.h"
#endif
/* When access exceptions happen, we must do this. */
static void spitfire_clean_and_reenable_l1_caches(void)
{
unsigned long va;
if (tlb_type != spitfire)
BUG();
/* Clean 'em. */
for (va = 0; va < (PAGE_SIZE << 1); va += 32) {
spitfire_put_icache_tag(va, 0x0);
spitfire_put_dcache_tag(va, 0x0);
}
/* Re-enable in LSU. */
__asm__ __volatile__("flush %%g6\n\t"
"membar #Sync\n\t"
"stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (LSU_CONTROL_IC | LSU_CONTROL_DC |
LSU_CONTROL_IM | LSU_CONTROL_DM),
"i" (ASI_LSU_CONTROL)
: "memory");
}
static void spitfire_enable_estate_errors(void)
{
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (ESTATE_ERR_ALL),
"i" (ASI_ESTATE_ERROR_EN));
}
static char ecc_syndrome_table[] = {
0x4c, 0x40, 0x41, 0x48, 0x42, 0x48, 0x48, 0x49,
0x43, 0x48, 0x48, 0x49, 0x48, 0x49, 0x49, 0x4a,
0x44, 0x48, 0x48, 0x20, 0x48, 0x39, 0x4b, 0x48,
0x48, 0x25, 0x31, 0x48, 0x28, 0x48, 0x48, 0x2c,
0x45, 0x48, 0x48, 0x21, 0x48, 0x3d, 0x04, 0x48,
0x48, 0x4b, 0x35, 0x48, 0x2d, 0x48, 0x48, 0x29,
0x48, 0x00, 0x01, 0x48, 0x0a, 0x48, 0x48, 0x4b,
0x0f, 0x48, 0x48, 0x4b, 0x48, 0x49, 0x49, 0x48,
0x46, 0x48, 0x48, 0x2a, 0x48, 0x3b, 0x27, 0x48,
0x48, 0x4b, 0x33, 0x48, 0x22, 0x48, 0x48, 0x2e,
0x48, 0x19, 0x1d, 0x48, 0x1b, 0x4a, 0x48, 0x4b,
0x1f, 0x48, 0x4a, 0x4b, 0x48, 0x4b, 0x4b, 0x48,
0x48, 0x4b, 0x24, 0x48, 0x07, 0x48, 0x48, 0x36,
0x4b, 0x48, 0x48, 0x3e, 0x48, 0x30, 0x38, 0x48,
0x49, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x16, 0x48,
0x48, 0x12, 0x4b, 0x48, 0x49, 0x48, 0x48, 0x4b,
0x47, 0x48, 0x48, 0x2f, 0x48, 0x3f, 0x4b, 0x48,
0x48, 0x06, 0x37, 0x48, 0x23, 0x48, 0x48, 0x2b,
0x48, 0x05, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x32,
0x26, 0x48, 0x48, 0x3a, 0x48, 0x34, 0x3c, 0x48,
0x48, 0x11, 0x15, 0x48, 0x13, 0x4a, 0x48, 0x4b,
0x17, 0x48, 0x4a, 0x4b, 0x48, 0x4b, 0x4b, 0x48,
0x49, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x1e, 0x48,
0x48, 0x1a, 0x4b, 0x48, 0x49, 0x48, 0x48, 0x4b,
0x48, 0x08, 0x0d, 0x48, 0x02, 0x48, 0x48, 0x49,
0x03, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x4b, 0x48,
0x49, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x10, 0x48,
0x48, 0x14, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x4b,
0x49, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x18, 0x48,
0x48, 0x1c, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x4b,
0x4a, 0x0c, 0x09, 0x48, 0x0e, 0x48, 0x48, 0x4b,
0x0b, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x4b, 0x4a
};
static char *syndrome_unknown = "<Unknown>";
static void spitfire_log_udb_syndrome(unsigned long afar, unsigned long udbh, unsigned long udbl, unsigned long bit)
{
unsigned short scode;
char memmod_str[64], *p;
if (udbl & bit) {
scode = ecc_syndrome_table[udbl & 0xff];
if (sprintf_dimm(scode, afar, memmod_str, sizeof(memmod_str)) < 0)
p = syndrome_unknown;
else
p = memmod_str;
printk(KERN_WARNING "CPU[%d]: UDBL Syndrome[%x] "
"Memory Module \"%s\"\n",
smp_processor_id(), scode, p);
}
if (udbh & bit) {
scode = ecc_syndrome_table[udbh & 0xff];
if (sprintf_dimm(scode, afar, memmod_str, sizeof(memmod_str)) < 0)
p = syndrome_unknown;
else
p = memmod_str;
printk(KERN_WARNING "CPU[%d]: UDBH Syndrome[%x] "
"Memory Module \"%s\"\n",
smp_processor_id(), scode, p);
}
}
static void spitfire_cee_log(unsigned long afsr, unsigned long afar, unsigned long udbh, unsigned long udbl, int tl1, struct pt_regs *regs)
{
printk(KERN_WARNING "CPU[%d]: Correctable ECC Error "
"AFSR[%lx] AFAR[%016lx] UDBL[%lx] UDBH[%lx] TL>1[%d]\n",
smp_processor_id(), afsr, afar, udbl, udbh, tl1);
spitfire_log_udb_syndrome(afar, udbh, udbl, UDBE_CE);
/* We always log it, even if someone is listening for this
* trap.
*/
notify_die(DIE_TRAP, "Correctable ECC Error", regs,
0, TRAP_TYPE_CEE, SIGTRAP);
/* The Correctable ECC Error trap does not disable I/D caches. So
* we only have to restore the ESTATE Error Enable register.
*/
spitfire_enable_estate_errors();
}
static void spitfire_ue_log(unsigned long afsr, unsigned long afar, unsigned long udbh, unsigned long udbl, unsigned long tt, int tl1, struct pt_regs *regs)
{
siginfo_t info;
printk(KERN_WARNING "CPU[%d]: Uncorrectable Error AFSR[%lx] "
"AFAR[%lx] UDBL[%lx] UDBH[%ld] TT[%lx] TL>1[%d]\n",
smp_processor_id(), afsr, afar, udbl, udbh, tt, tl1);
/* XXX add more human friendly logging of the error status
* XXX as is implemented for cheetah
*/
spitfire_log_udb_syndrome(afar, udbh, udbl, UDBE_UE);
/* We always log it, even if someone is listening for this
* trap.
*/
notify_die(DIE_TRAP, "Uncorrectable Error", regs,
0, tt, SIGTRAP);
if (regs->tstate & TSTATE_PRIV) {
if (tl1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("UE", regs);
}
/* XXX need more intelligent processing here, such as is implemented
* XXX for cheetah errors, in fact if the E-cache still holds the
* XXX line with bad parity this will loop
*/
spitfire_clean_and_reenable_l1_caches();
spitfire_enable_estate_errors();
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_OBJERR;
info.si_addr = (void *)0;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void spitfire_access_error(struct pt_regs *regs, unsigned long status_encoded, unsigned long afar)
{
unsigned long afsr, tt, udbh, udbl;
int tl1;
afsr = (status_encoded & SFSTAT_AFSR_MASK) >> SFSTAT_AFSR_SHIFT;
tt = (status_encoded & SFSTAT_TRAP_TYPE) >> SFSTAT_TRAP_TYPE_SHIFT;
tl1 = (status_encoded & SFSTAT_TL_GT_ONE) ? 1 : 0;
udbl = (status_encoded & SFSTAT_UDBL_MASK) >> SFSTAT_UDBL_SHIFT;
udbh = (status_encoded & SFSTAT_UDBH_MASK) >> SFSTAT_UDBH_SHIFT;
#ifdef CONFIG_PCI
if (tt == TRAP_TYPE_DAE &&
pci_poke_in_progress && pci_poke_cpu == smp_processor_id()) {
spitfire_clean_and_reenable_l1_caches();
spitfire_enable_estate_errors();
pci_poke_faulted = 1;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
if (afsr & SFAFSR_UE)
spitfire_ue_log(afsr, afar, udbh, udbl, tt, tl1, regs);
if (tt == TRAP_TYPE_CEE) {
/* Handle the case where we took a CEE trap, but ACK'd
* only the UE state in the UDB error registers.
*/
if (afsr & SFAFSR_UE) {
if (udbh & UDBE_CE) {
__asm__ __volatile__(
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (udbh & UDBE_CE),
"r" (0x0), "i" (ASI_UDB_ERROR_W));
}
if (udbl & UDBE_CE) {
__asm__ __volatile__(
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (udbl & UDBE_CE),
"r" (0x18), "i" (ASI_UDB_ERROR_W));
}
}
spitfire_cee_log(afsr, afar, udbh, udbl, tl1, regs);
}
}
int cheetah_pcache_forced_on;
void cheetah_enable_pcache(void)
{
unsigned long dcr;
printk("CHEETAH: Enabling P-Cache on cpu %d.\n",
smp_processor_id());
__asm__ __volatile__("ldxa [%%g0] %1, %0"
: "=r" (dcr)
: "i" (ASI_DCU_CONTROL_REG));
dcr |= (DCU_PE | DCU_HPE | DCU_SPE | DCU_SL);
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (dcr), "i" (ASI_DCU_CONTROL_REG));
}
/* Cheetah error trap handling. */
static unsigned long ecache_flush_physbase;
static unsigned long ecache_flush_linesize;
static unsigned long ecache_flush_size;
/* This table is ordered in priority of errors and matches the
* AFAR overwrite policy as well.
*/
struct afsr_error_table {
unsigned long mask;
const char *name;
};
static const char CHAFSR_PERR_msg[] =
"System interface protocol error";
static const char CHAFSR_IERR_msg[] =
"Internal processor error";
static const char CHAFSR_ISAP_msg[] =
"System request parity error on incoming address";
static const char CHAFSR_UCU_msg[] =
"Uncorrectable E-cache ECC error for ifetch/data";
static const char CHAFSR_UCC_msg[] =
"SW Correctable E-cache ECC error for ifetch/data";
static const char CHAFSR_UE_msg[] =
"Uncorrectable system bus data ECC error for read";
static const char CHAFSR_EDU_msg[] =
"Uncorrectable E-cache ECC error for stmerge/blkld";
static const char CHAFSR_EMU_msg[] =
"Uncorrectable system bus MTAG error";
static const char CHAFSR_WDU_msg[] =
"Uncorrectable E-cache ECC error for writeback";
static const char CHAFSR_CPU_msg[] =
"Uncorrectable ECC error for copyout";
static const char CHAFSR_CE_msg[] =
"HW corrected system bus data ECC error for read";
static const char CHAFSR_EDC_msg[] =
"HW corrected E-cache ECC error for stmerge/blkld";
static const char CHAFSR_EMC_msg[] =
"HW corrected system bus MTAG ECC error";
static const char CHAFSR_WDC_msg[] =
"HW corrected E-cache ECC error for writeback";
static const char CHAFSR_CPC_msg[] =
"HW corrected ECC error for copyout";
static const char CHAFSR_TO_msg[] =
"Unmapped error from system bus";
static const char CHAFSR_BERR_msg[] =
"Bus error response from system bus";
static const char CHAFSR_IVC_msg[] =
"HW corrected system bus data ECC error for ivec read";
static const char CHAFSR_IVU_msg[] =
"Uncorrectable system bus data ECC error for ivec read";
static struct afsr_error_table __cheetah_error_table[] = {
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ CHAFSR_EMU, CHAFSR_EMU_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ CHAFSR_EMC, CHAFSR_EMC_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVC, CHAFSR_IVC_msg },
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static const char CHPAFSR_DTO_msg[] =
"System bus unmapped error for prefetch/storequeue-read";
static const char CHPAFSR_DBERR_msg[] =
"System bus error for prefetch/storequeue-read";
static const char CHPAFSR_THCE_msg[] =
"Hardware corrected E-cache Tag ECC error";
static const char CHPAFSR_TSCE_msg[] =
"SW handled correctable E-cache Tag ECC error";
static const char CHPAFSR_TUE_msg[] =
"Uncorrectable E-cache Tag ECC error";
static const char CHPAFSR_DUE_msg[] =
"System bus uncorrectable data ECC error due to prefetch/store-fill";
static struct afsr_error_table __cheetah_plus_error_table[] = {
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ CHAFSR_EMU, CHAFSR_EMU_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ CHAFSR_EMC, CHAFSR_EMC_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
{ CHPAFSR_DTO, CHPAFSR_DTO_msg },
{ CHPAFSR_DBERR, CHPAFSR_DBERR_msg },
{ CHPAFSR_THCE, CHPAFSR_THCE_msg },
{ CHPAFSR_TSCE, CHPAFSR_TSCE_msg },
{ CHPAFSR_TUE, CHPAFSR_TUE_msg },
{ CHPAFSR_DUE, CHPAFSR_DUE_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVC, CHAFSR_IVC_msg },
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static const char JPAFSR_JETO_msg[] =
"System interface protocol error, hw timeout caused";
static const char JPAFSR_SCE_msg[] =
"Parity error on system snoop results";
static const char JPAFSR_JEIC_msg[] =
"System interface protocol error, illegal command detected";
static const char JPAFSR_JEIT_msg[] =
"System interface protocol error, illegal ADTYPE detected";
static const char JPAFSR_OM_msg[] =
"Out of range memory error has occurred";
static const char JPAFSR_ETP_msg[] =
"Parity error on L2 cache tag SRAM";
static const char JPAFSR_UMS_msg[] =
"Error due to unsupported store";
static const char JPAFSR_RUE_msg[] =
"Uncorrectable ECC error from remote cache/memory";
static const char JPAFSR_RCE_msg[] =
"Correctable ECC error from remote cache/memory";
static const char JPAFSR_BP_msg[] =
"JBUS parity error on returned read data";
static const char JPAFSR_WBP_msg[] =
"JBUS parity error on data for writeback or block store";
static const char JPAFSR_FRC_msg[] =
"Foreign read to DRAM incurring correctable ECC error";
static const char JPAFSR_FRU_msg[] =
"Foreign read to DRAM incurring uncorrectable ECC error";
static struct afsr_error_table __jalapeno_error_table[] = {
{ JPAFSR_JETO, JPAFSR_JETO_msg },
{ JPAFSR_SCE, JPAFSR_SCE_msg },
{ JPAFSR_JEIC, JPAFSR_JEIC_msg },
{ JPAFSR_JEIT, JPAFSR_JEIT_msg },
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ JPAFSR_OM, JPAFSR_OM_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ JPAFSR_ETP, JPAFSR_ETP_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
{ JPAFSR_UMS, JPAFSR_UMS_msg },
{ JPAFSR_RUE, JPAFSR_RUE_msg },
{ JPAFSR_RCE, JPAFSR_RCE_msg },
{ JPAFSR_BP, JPAFSR_BP_msg },
{ JPAFSR_WBP, JPAFSR_WBP_msg },
{ JPAFSR_FRC, JPAFSR_FRC_msg },
{ JPAFSR_FRU, JPAFSR_FRU_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static struct afsr_error_table *cheetah_error_table;
static unsigned long cheetah_afsr_errors;
struct cheetah_err_info *cheetah_error_log;
static inline struct cheetah_err_info *cheetah_get_error_log(unsigned long afsr)
{
struct cheetah_err_info *p;
int cpu = smp_processor_id();
if (!cheetah_error_log)
return NULL;
p = cheetah_error_log + (cpu * 2);
if ((afsr & CHAFSR_TL1) != 0UL)
p++;
return p;
}
extern unsigned int tl0_icpe[], tl1_icpe[];
extern unsigned int tl0_dcpe[], tl1_dcpe[];
extern unsigned int tl0_fecc[], tl1_fecc[];
extern unsigned int tl0_cee[], tl1_cee[];
extern unsigned int tl0_iae[], tl1_iae[];
extern unsigned int tl0_dae[], tl1_dae[];
extern unsigned int cheetah_plus_icpe_trap_vector[], cheetah_plus_icpe_trap_vector_tl1[];
extern unsigned int cheetah_plus_dcpe_trap_vector[], cheetah_plus_dcpe_trap_vector_tl1[];
extern unsigned int cheetah_fecc_trap_vector[], cheetah_fecc_trap_vector_tl1[];
extern unsigned int cheetah_cee_trap_vector[], cheetah_cee_trap_vector_tl1[];
extern unsigned int cheetah_deferred_trap_vector[], cheetah_deferred_trap_vector_tl1[];
void __init cheetah_ecache_flush_init(void)
{
unsigned long largest_size, smallest_linesize, order, ver;
int i, sz;
/* Scan all cpu device tree nodes, note two values:
* 1) largest E-cache size
* 2) smallest E-cache line size
*/
largest_size = 0UL;
smallest_linesize = ~0UL;
for (i = 0; i < NR_CPUS; i++) {
unsigned long val;
val = cpu_data(i).ecache_size;
if (!val)
continue;
if (val > largest_size)
largest_size = val;
val = cpu_data(i).ecache_line_size;
if (val < smallest_linesize)
smallest_linesize = val;
}
if (largest_size == 0UL || smallest_linesize == ~0UL) {
prom_printf("cheetah_ecache_flush_init: Cannot probe cpu E-cache "
"parameters.\n");
prom_halt();
}
ecache_flush_size = (2 * largest_size);
ecache_flush_linesize = smallest_linesize;
ecache_flush_physbase = find_ecache_flush_span(ecache_flush_size);
if (ecache_flush_physbase == ~0UL) {
prom_printf("cheetah_ecache_flush_init: Cannot find %d byte "
"contiguous physical memory.\n",
ecache_flush_size);
prom_halt();
}
/* Now allocate error trap reporting scoreboard. */
sz = NR_CPUS * (2 * sizeof(struct cheetah_err_info));
for (order = 0; order < MAX_ORDER; order++) {
if ((PAGE_SIZE << order) >= sz)
break;
}
cheetah_error_log = (struct cheetah_err_info *)
__get_free_pages(GFP_KERNEL, order);
if (!cheetah_error_log) {
prom_printf("cheetah_ecache_flush_init: Failed to allocate "
"error logging scoreboard (%d bytes).\n", sz);
prom_halt();
}
memset(cheetah_error_log, 0, PAGE_SIZE << order);
/* Mark all AFSRs as invalid so that the trap handler will
* log new new information there.
*/
for (i = 0; i < 2 * NR_CPUS; i++)
cheetah_error_log[i].afsr = CHAFSR_INVALID;
__asm__ ("rdpr %%ver, %0" : "=r" (ver));
if ((ver >> 32) == __JALAPENO_ID ||
(ver >> 32) == __SERRANO_ID) {
cheetah_error_table = &__jalapeno_error_table[0];
cheetah_afsr_errors = JPAFSR_ERRORS;
} else if ((ver >> 32) == 0x003e0015) {
cheetah_error_table = &__cheetah_plus_error_table[0];
cheetah_afsr_errors = CHPAFSR_ERRORS;
} else {
cheetah_error_table = &__cheetah_error_table[0];
cheetah_afsr_errors = CHAFSR_ERRORS;
}
/* Now patch trap tables. */
memcpy(tl0_fecc, cheetah_fecc_trap_vector, (8 * 4));
memcpy(tl1_fecc, cheetah_fecc_trap_vector_tl1, (8 * 4));
memcpy(tl0_cee, cheetah_cee_trap_vector, (8 * 4));
memcpy(tl1_cee, cheetah_cee_trap_vector_tl1, (8 * 4));
memcpy(tl0_iae, cheetah_deferred_trap_vector, (8 * 4));
memcpy(tl1_iae, cheetah_deferred_trap_vector_tl1, (8 * 4));
memcpy(tl0_dae, cheetah_deferred_trap_vector, (8 * 4));
memcpy(tl1_dae, cheetah_deferred_trap_vector_tl1, (8 * 4));
if (tlb_type == cheetah_plus) {
memcpy(tl0_dcpe, cheetah_plus_dcpe_trap_vector, (8 * 4));
memcpy(tl1_dcpe, cheetah_plus_dcpe_trap_vector_tl1, (8 * 4));
memcpy(tl0_icpe, cheetah_plus_icpe_trap_vector, (8 * 4));
memcpy(tl1_icpe, cheetah_plus_icpe_trap_vector_tl1, (8 * 4));
}
flushi(PAGE_OFFSET);
}
static void cheetah_flush_ecache(void)
{
unsigned long flush_base = ecache_flush_physbase;
unsigned long flush_linesize = ecache_flush_linesize;
unsigned long flush_size = ecache_flush_size;
__asm__ __volatile__("1: subcc %0, %4, %0\n\t"
" bne,pt %%xcc, 1b\n\t"
" ldxa [%2 + %0] %3, %%g0\n\t"
: "=&r" (flush_size)
: "0" (flush_size), "r" (flush_base),
"i" (ASI_PHYS_USE_EC), "r" (flush_linesize));
}
static void cheetah_flush_ecache_line(unsigned long physaddr)
{
unsigned long alias;
physaddr &= ~(8UL - 1UL);
physaddr = (ecache_flush_physbase +
(physaddr & ((ecache_flush_size>>1UL) - 1UL)));
alias = physaddr + (ecache_flush_size >> 1UL);
__asm__ __volatile__("ldxa [%0] %2, %%g0\n\t"
"ldxa [%1] %2, %%g0\n\t"
"membar #Sync"
: /* no outputs */
: "r" (physaddr), "r" (alias),
"i" (ASI_PHYS_USE_EC));
}
/* Unfortunately, the diagnostic access to the I-cache tags we need to
* use to clear the thing interferes with I-cache coherency transactions.
*
* So we must only flush the I-cache when it is disabled.
*/
static void __cheetah_flush_icache(void)
{
unsigned int icache_size, icache_line_size;
unsigned long addr;
icache_size = local_cpu_data().icache_size;
icache_line_size = local_cpu_data().icache_line_size;
/* Clear the valid bits in all the tags. */
for (addr = 0; addr < icache_size; addr += icache_line_size) {
__asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (addr | (2 << 3)),
"i" (ASI_IC_TAG));
}
}
static void cheetah_flush_icache(void)
{
unsigned long dcu_save;
/* Save current DCU, disable I-cache. */
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
"or %0, %2, %%g1\n\t"
"stxa %%g1, [%%g0] %1\n\t"
"membar #Sync"
: "=r" (dcu_save)
: "i" (ASI_DCU_CONTROL_REG), "i" (DCU_IC)
: "g1");
__cheetah_flush_icache();
/* Restore DCU register */
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (dcu_save), "i" (ASI_DCU_CONTROL_REG));
}
static void cheetah_flush_dcache(void)
{
unsigned int dcache_size, dcache_line_size;
unsigned long addr;
dcache_size = local_cpu_data().dcache_size;
dcache_line_size = local_cpu_data().dcache_line_size;
for (addr = 0; addr < dcache_size; addr += dcache_line_size) {
__asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (addr), "i" (ASI_DCACHE_TAG));
}
}
/* In order to make the even parity correct we must do two things.
* First, we clear DC_data_parity and set DC_utag to an appropriate value.
* Next, we clear out all 32-bytes of data for that line. Data of
* all-zero + tag parity value of zero == correct parity.
*/
static void cheetah_plus_zap_dcache_parity(void)
{
unsigned int dcache_size, dcache_line_size;
unsigned long addr;
dcache_size = local_cpu_data().dcache_size;
dcache_line_size = local_cpu_data().dcache_line_size;
for (addr = 0; addr < dcache_size; addr += dcache_line_size) {
unsigned long tag = (addr >> 14);
unsigned long line;
__asm__ __volatile__("membar #Sync\n\t"
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (tag), "r" (addr),
"i" (ASI_DCACHE_UTAG));
for (line = addr; line < addr + dcache_line_size; line += 8)
__asm__ __volatile__("membar #Sync\n\t"
"stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (line),
"i" (ASI_DCACHE_DATA));
}
}
/* Conversion tables used to frob Cheetah AFSR syndrome values into
* something palatable to the memory controller driver get_unumber
* routine.
*/
#define MT0 137
#define MT1 138
#define MT2 139
#define NONE 254
#define MTC0 140
#define MTC1 141
#define MTC2 142
#define MTC3 143
#define C0 128
#define C1 129
#define C2 130
#define C3 131
#define C4 132
#define C5 133
#define C6 134
#define C7 135
#define C8 136
#define M2 144
#define M3 145
#define M4 146
#define M 147
static unsigned char cheetah_ecc_syntab[] = {
/*00*/NONE, C0, C1, M2, C2, M2, M3, 47, C3, M2, M2, 53, M2, 41, 29, M,
/*01*/C4, M, M, 50, M2, 38, 25, M2, M2, 33, 24, M2, 11, M, M2, 16,
/*02*/C5, M, M, 46, M2, 37, 19, M2, M, 31, 32, M, 7, M2, M2, 10,
/*03*/M2, 40, 13, M2, 59, M, M2, 66, M, M2, M2, 0, M2, 67, 71, M,
/*04*/C6, M, M, 43, M, 36, 18, M, M2, 49, 15, M, 63, M2, M2, 6,
/*05*/M2, 44, 28, M2, M, M2, M2, 52, 68, M2, M2, 62, M2, M3, M3, M4,
/*06*/M2, 26, 106, M2, 64, M, M2, 2, 120, M, M2, M3, M, M3, M3, M4,
/*07*/116, M2, M2, M3, M2, M3, M, M4, M2, 58, 54, M2, M, M4, M4, M3,
/*08*/C7, M2, M, 42, M, 35, 17, M2, M, 45, 14, M2, 21, M2, M2, 5,
/*09*/M, 27, M, M, 99, M, M, 3, 114, M2, M2, 20, M2, M3, M3, M,
/*0a*/M2, 23, 113, M2, 112, M2, M, 51, 95, M, M2, M3, M2, M3, M3, M2,
/*0b*/103, M, M2, M3, M2, M3, M3, M4, M2, 48, M, M, 73, M2, M, M3,
/*0c*/M2, 22, 110, M2, 109, M2, M, 9, 108, M2, M, M3, M2, M3, M3, M,
/*0d*/102, M2, M, M, M2, M3, M3, M, M2, M3, M3, M2, M, M4, M, M3,
/*0e*/98, M, M2, M3, M2, M, M3, M4, M2, M3, M3, M4, M3, M, M, M,
/*0f*/M2, M3, M3, M, M3, M, M, M, 56, M4, M, M3, M4, M, M, M,
/*10*/C8, M, M2, 39, M, 34, 105, M2, M, 30, 104, M, 101, M, M, 4,
/*11*/M, M, 100, M, 83, M, M2, 12, 87, M, M, 57, M2, M, M3, M,
/*12*/M2, 97, 82, M2, 78, M2, M2, 1, 96, M, M, M, M, M, M3, M2,
/*13*/94, M, M2, M3, M2, M, M3, M, M2, M, 79, M, 69, M, M4, M,
/*14*/M2, 93, 92, M, 91, M, M2, 8, 90, M2, M2, M, M, M, M, M4,
/*15*/89, M, M, M3, M2, M3, M3, M, M, M, M3, M2, M3, M2, M, M3,
/*16*/86, M, M2, M3, M2, M, M3, M, M2, M, M3, M, M3, M, M, M3,
/*17*/M, M, M3, M2, M3, M2, M4, M, 60, M, M2, M3, M4, M, M, M2,
/*18*/M2, 88, 85, M2, 84, M, M2, 55, 81, M2, M2, M3, M2, M3, M3, M4,
/*19*/77, M, M, M, M2, M3, M, M, M2, M3, M3, M4, M3, M2, M, M,
/*1a*/74, M, M2, M3, M, M, M3, M, M, M, M3, M, M3, M, M4, M3,
/*1b*/M2, 70, 107, M4, 65, M2, M2, M, 127, M, M, M, M2, M3, M3, M,
/*1c*/80, M2, M2, 72, M, 119, 118, M, M2, 126, 76, M, 125, M, M4, M3,
/*1d*/M2, 115, 124, M, 75, M, M, M3, 61, M, M4, M, M4, M, M, M,
/*1e*/M, 123, 122, M4, 121, M4, M, M3, 117, M2, M2, M3, M4, M3, M, M,
/*1f*/111, M, M, M, M4, M3, M3, M, M, M, M3, M, M3, M2, M, M
};
static unsigned char cheetah_mtag_syntab[] = {
NONE, MTC0,
MTC1, NONE,
MTC2, NONE,
NONE, MT0,
MTC3, NONE,
NONE, MT1,
NONE, MT2,
NONE, NONE
};
/* Return the highest priority error conditon mentioned. */
static inline unsigned long cheetah_get_hipri(unsigned long afsr)
{
unsigned long tmp = 0;
int i;
for (i = 0; cheetah_error_table[i].mask; i++) {
if ((tmp = (afsr & cheetah_error_table[i].mask)) != 0UL)
return tmp;
}
return tmp;
}
static const char *cheetah_get_string(unsigned long bit)
{
int i;
for (i = 0; cheetah_error_table[i].mask; i++) {
if ((bit & cheetah_error_table[i].mask) != 0UL)
return cheetah_error_table[i].name;
}
return "???";
}
static void cheetah_log_errors(struct pt_regs *regs, struct cheetah_err_info *info,
unsigned long afsr, unsigned long afar, int recoverable)
{
unsigned long hipri;
char unum[256];
printk("%s" "ERROR(%d): Cheetah error trap taken afsr[%016lx] afar[%016lx] TL1(%d)\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
afsr, afar,
(afsr & CHAFSR_TL1) ? 1 : 0);
printk("%s" "ERROR(%d): TPC[%lx] TNPC[%lx] O7[%lx] TSTATE[%lx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
regs->tpc, regs->tnpc, regs->u_regs[UREG_I7], regs->tstate);
printk("%s" "ERROR(%d): ",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id());
printk("TPC<%pS>\n", (void *) regs->tpc);
printk("%s" "ERROR(%d): M_SYND(%lx), E_SYND(%lx)%s%s\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(afsr & CHAFSR_M_SYNDROME) >> CHAFSR_M_SYNDROME_SHIFT,
(afsr & CHAFSR_E_SYNDROME) >> CHAFSR_E_SYNDROME_SHIFT,
(afsr & CHAFSR_ME) ? ", Multiple Errors" : "",
(afsr & CHAFSR_PRIV) ? ", Privileged" : "");
hipri = cheetah_get_hipri(afsr);
printk("%s" "ERROR(%d): Highest priority error (%016lx) \"%s\"\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
hipri, cheetah_get_string(hipri));
/* Try to get unumber if relevant. */
#define ESYND_ERRORS (CHAFSR_IVC | CHAFSR_IVU | \
CHAFSR_CPC | CHAFSR_CPU | \
CHAFSR_UE | CHAFSR_CE | \
CHAFSR_EDC | CHAFSR_EDU | \
CHAFSR_UCC | CHAFSR_UCU | \
CHAFSR_WDU | CHAFSR_WDC)
#define MSYND_ERRORS (CHAFSR_EMC | CHAFSR_EMU)
if (afsr & ESYND_ERRORS) {
int syndrome;
int ret;
syndrome = (afsr & CHAFSR_E_SYNDROME) >> CHAFSR_E_SYNDROME_SHIFT;
syndrome = cheetah_ecc_syntab[syndrome];
ret = sprintf_dimm(syndrome, afar, unum, sizeof(unum));
if (ret != -1)
printk("%s" "ERROR(%d): AFAR E-syndrome [%s]\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
smp_processor_id(), unum);
} else if (afsr & MSYND_ERRORS) {
int syndrome;
int ret;
syndrome = (afsr & CHAFSR_M_SYNDROME) >> CHAFSR_M_SYNDROME_SHIFT;
syndrome = cheetah_mtag_syntab[syndrome];
ret = sprintf_dimm(syndrome, afar, unum, sizeof(unum));
if (ret != -1)
printk("%s" "ERROR(%d): AFAR M-syndrome [%s]\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
smp_processor_id(), unum);
}
/* Now dump the cache snapshots. */
printk("%s" "ERROR(%d): D-cache idx[%x] tag[%016llx] utag[%016llx] stag[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->dcache_index,
info->dcache_tag,
info->dcache_utag,
info->dcache_stag);
printk("%s" "ERROR(%d): D-cache data0[%016llx] data1[%016llx] data2[%016llx] data3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->dcache_data[0],
info->dcache_data[1],
info->dcache_data[2],
info->dcache_data[3]);
printk("%s" "ERROR(%d): I-cache idx[%x] tag[%016llx] utag[%016llx] stag[%016llx] "
"u[%016llx] l[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->icache_index,
info->icache_tag,
info->icache_utag,
info->icache_stag,
info->icache_upper,
info->icache_lower);
printk("%s" "ERROR(%d): I-cache INSN0[%016llx] INSN1[%016llx] INSN2[%016llx] INSN3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->icache_data[0],
info->icache_data[1],
info->icache_data[2],
info->icache_data[3]);
printk("%s" "ERROR(%d): I-cache INSN4[%016llx] INSN5[%016llx] INSN6[%016llx] INSN7[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->icache_data[4],
info->icache_data[5],
info->icache_data[6],
info->icache_data[7]);
printk("%s" "ERROR(%d): E-cache idx[%x] tag[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->ecache_index, info->ecache_tag);
printk("%s" "ERROR(%d): E-cache data0[%016llx] data1[%016llx] data2[%016llx] data3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->ecache_data[0],
info->ecache_data[1],
info->ecache_data[2],
info->ecache_data[3]);
afsr = (afsr & ~hipri) & cheetah_afsr_errors;
while (afsr != 0UL) {
unsigned long bit = cheetah_get_hipri(afsr);
printk("%s" "ERROR: Multiple-error (%016lx) \"%s\"\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
bit, cheetah_get_string(bit));
afsr &= ~bit;
}
if (!recoverable)
printk(KERN_CRIT "ERROR: This condition is not recoverable.\n");
}
static int cheetah_recheck_errors(struct cheetah_err_info *logp)
{
unsigned long afsr, afar;
int ret = 0;
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
: "=r" (afsr)
: "i" (ASI_AFSR));
if ((afsr & cheetah_afsr_errors) != 0) {
if (logp != NULL) {
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
: "=r" (afar)
: "i" (ASI_AFAR));
logp->afsr = afsr;
logp->afar = afar;
}
ret = 1;
}
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync\n\t"
: : "r" (afsr), "i" (ASI_AFSR));
return ret;
}
void cheetah_fecc_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable;
/* Flush E-cache */
cheetah_flush_ecache();
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early Fast-ECC error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR. What we are looking for here is whether a new
* error was logged while we had error reporting traps disabled.
*/
if (cheetah_recheck_errors(&local_snapshot)) {
unsigned long new_afsr = local_snapshot.afsr;
/* If we got a new asynchronous error, die... */
if (new_afsr & (CHAFSR_EMU | CHAFSR_EDU |
CHAFSR_WDU | CHAFSR_CPU |
CHAFSR_IVU | CHAFSR_UE |
CHAFSR_BERR | CHAFSR_TO))
recoverable = 0;
}
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
if (!recoverable)
panic("Irrecoverable Fast-ECC error trap.\n");
/* Flush E-cache to kick the error trap handlers out. */
cheetah_flush_ecache();
}
/* Try to fix a correctable error by pushing the line out from
* the E-cache. Recheck error reporting registers to see if the
* problem is intermittent.
*/
static int cheetah_fix_ce(unsigned long physaddr)
{
unsigned long orig_estate;
unsigned long alias1, alias2;
int ret;
/* Make sure correctable error traps are disabled. */
__asm__ __volatile__("ldxa [%%g0] %2, %0\n\t"
"andn %0, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %2\n\t"
"membar #Sync"
: "=&r" (orig_estate)
: "i" (ESTATE_ERROR_CEEN),
"i" (ASI_ESTATE_ERROR_EN)
: "g1");
/* We calculate alias addresses that will force the
* cache line in question out of the E-cache. Then
* we bring it back in with an atomic instruction so
* that we get it in some modified/exclusive state,
* then we displace it again to try and get proper ECC
* pushed back into the system.
*/
physaddr &= ~(8UL - 1UL);
alias1 = (ecache_flush_physbase +
(physaddr & ((ecache_flush_size >> 1) - 1)));
alias2 = alias1 + (ecache_flush_size >> 1);
__asm__ __volatile__("ldxa [%0] %3, %%g0\n\t"
"ldxa [%1] %3, %%g0\n\t"
"casxa [%2] %3, %%g0, %%g0\n\t"
"ldxa [%0] %3, %%g0\n\t"
"ldxa [%1] %3, %%g0\n\t"
"membar #Sync"
: /* no outputs */
: "r" (alias1), "r" (alias2),
"r" (physaddr), "i" (ASI_PHYS_USE_EC));
/* Did that trigger another error? */
if (cheetah_recheck_errors(NULL)) {
/* Try one more time. */
__asm__ __volatile__("ldxa [%0] %1, %%g0\n\t"
"membar #Sync"
: : "r" (physaddr), "i" (ASI_PHYS_USE_EC));
if (cheetah_recheck_errors(NULL))
ret = 2;
else
ret = 1;
} else {
/* No new error, intermittent problem. */
ret = 0;
}
/* Restore error enables. */
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: : "r" (orig_estate), "i" (ASI_ESTATE_ERROR_EN));
return ret;
}
/* Return non-zero if PADDR is a valid physical memory address. */
static int cheetah_check_main_memory(unsigned long paddr)
{
unsigned long vaddr = PAGE_OFFSET + paddr;
if (vaddr > (unsigned long) high_memory)
return 0;
return kern_addr_valid(vaddr);
}
void cheetah_cee_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable, is_memory;
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early CEE error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
is_memory = cheetah_check_main_memory(afar);
if (is_memory && (afsr & CHAFSR_CE) != 0UL) {
/* XXX Might want to log the results of this operation
* XXX somewhere... -DaveM
*/
cheetah_fix_ce(afar);
}
{
int flush_all, flush_line;
flush_all = flush_line = 0;
if ((afsr & CHAFSR_EDC) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_EDC)
flush_line = 1;
else
flush_all = 1;
} else if ((afsr & CHAFSR_CPC) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_CPC)
flush_line = 1;
else
flush_all = 1;
}
/* Trap handler only disabled I-cache, flush it. */
cheetah_flush_icache();
/* Re-enable I-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_IC)
: "g1");
if (flush_all)
cheetah_flush_ecache();
else if (flush_line)
cheetah_flush_ecache_line(afar);
}
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR */
(void) cheetah_recheck_errors(&local_snapshot);
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
if (!recoverable)
panic("Irrecoverable Correctable-ECC error trap.\n");
}
void cheetah_deferred_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable, is_memory;
#ifdef CONFIG_PCI
/* Check for the special PCI poke sequence. */
if (pci_poke_in_progress && pci_poke_cpu == smp_processor_id()) {
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
(void) cheetah_recheck_errors(NULL);
pci_poke_faulted = 1;
regs->tpc += 4;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early deferred error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
is_memory = cheetah_check_main_memory(afar);
{
int flush_all, flush_line;
flush_all = flush_line = 0;
if ((afsr & CHAFSR_EDU) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_EDU)
flush_line = 1;
else
flush_all = 1;
} else if ((afsr & CHAFSR_BERR) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_BERR)
flush_line = 1;
else
flush_all = 1;
}
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I/D caches */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_IC | DCU_DC)
: "g1");
if (flush_all)
cheetah_flush_ecache();
else if (flush_line)
cheetah_flush_ecache_line(afar);
}
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR. What we are looking for here is whether a new
* error was logged while we had error reporting traps disabled.
*/
if (cheetah_recheck_errors(&local_snapshot)) {
unsigned long new_afsr = local_snapshot.afsr;
/* If we got a new asynchronous error, die... */
if (new_afsr & (CHAFSR_EMU | CHAFSR_EDU |
CHAFSR_WDU | CHAFSR_CPU |
CHAFSR_IVU | CHAFSR_UE |
CHAFSR_BERR | CHAFSR_TO))
recoverable = 0;
}
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
/* "Recoverable" here means we try to yank the page from ever
* being newly used again. This depends upon a few things:
* 1) Must be main memory, and AFAR must be valid.
* 2) If we trapped from user, OK.
* 3) Else, if we trapped from kernel we must find exception
* table entry (ie. we have to have been accessing user
* space).
*
* If AFAR is not in main memory, or we trapped from kernel
* and cannot find an exception table entry, it is unacceptable
* to try and continue.
*/
if (recoverable && is_memory) {
if ((regs->tstate & TSTATE_PRIV) == 0UL) {
/* OK, usermode access. */
recoverable = 1;
} else {
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* OK, kernel access to userspace. */
recoverable = 1;
} else {
/* BAD, privileged state is corrupted. */
recoverable = 0;
}
if (recoverable) {
if (pfn_valid(afar >> PAGE_SHIFT))
get_page(pfn_to_page(afar >> PAGE_SHIFT));
else
recoverable = 0;
/* Only perform fixup if we still have a
* recoverable condition.
*/
if (recoverable) {
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
}
}
}
} else {
recoverable = 0;
}
if (!recoverable)
panic("Irrecoverable deferred error trap.\n");
}
/* Handle a D/I cache parity error trap. TYPE is encoded as:
*
* Bit0: 0=dcache,1=icache
* Bit1: 0=recoverable,1=unrecoverable
*
* The hardware has disabled both the I-cache and D-cache in
* the %dcr register.
*/
void cheetah_plus_parity_error(int type, struct pt_regs *regs)
{
if (type & 0x1)
__cheetah_flush_icache();
else
cheetah_plus_zap_dcache_parity();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
if (type & 0x2) {
printk(KERN_EMERG "CPU[%d]: Cheetah+ %c-cache parity error at TPC[%016lx]\n",
smp_processor_id(),
(type & 0x1) ? 'I' : 'D',
regs->tpc);
printk(KERN_EMERG "TPC<%pS>\n", (void *) regs->tpc);
panic("Irrecoverable Cheetah+ parity error.");
}
printk(KERN_WARNING "CPU[%d]: Cheetah+ %c-cache parity error at TPC[%016lx]\n",
smp_processor_id(),
(type & 0x1) ? 'I' : 'D',
regs->tpc);
printk(KERN_WARNING "TPC<%pS>\n", (void *) regs->tpc);
}
struct sun4v_error_entry {
u64 err_handle;
u64 err_stick;
u32 err_type;
#define SUN4V_ERR_TYPE_UNDEFINED 0
#define SUN4V_ERR_TYPE_UNCORRECTED_RES 1
#define SUN4V_ERR_TYPE_PRECISE_NONRES 2
#define SUN4V_ERR_TYPE_DEFERRED_NONRES 3
#define SUN4V_ERR_TYPE_WARNING_RES 4
u32 err_attrs;
#define SUN4V_ERR_ATTRS_PROCESSOR 0x00000001
#define SUN4V_ERR_ATTRS_MEMORY 0x00000002
#define SUN4V_ERR_ATTRS_PIO 0x00000004
#define SUN4V_ERR_ATTRS_INT_REGISTERS 0x00000008
#define SUN4V_ERR_ATTRS_FPU_REGISTERS 0x00000010
#define SUN4V_ERR_ATTRS_USER_MODE 0x01000000
#define SUN4V_ERR_ATTRS_PRIV_MODE 0x02000000
#define SUN4V_ERR_ATTRS_RES_QUEUE_FULL 0x80000000
u64 err_raddr;
u32 err_size;
u16 err_cpu;
u16 err_pad;
};
static atomic_t sun4v_resum_oflow_cnt = ATOMIC_INIT(0);
static atomic_t sun4v_nonresum_oflow_cnt = ATOMIC_INIT(0);
static const char *sun4v_err_type_to_str(u32 type)
{
switch (type) {
case SUN4V_ERR_TYPE_UNDEFINED:
return "undefined";
case SUN4V_ERR_TYPE_UNCORRECTED_RES:
return "uncorrected resumable";
case SUN4V_ERR_TYPE_PRECISE_NONRES:
return "precise nonresumable";
case SUN4V_ERR_TYPE_DEFERRED_NONRES:
return "deferred nonresumable";
case SUN4V_ERR_TYPE_WARNING_RES:
return "warning resumable";
default:
return "unknown";
}
}
static void sun4v_log_error(struct pt_regs *regs, struct sun4v_error_entry *ent, int cpu, const char *pfx, atomic_t *ocnt)
{
int cnt;
printk("%s: Reporting on cpu %d\n", pfx, cpu);
printk("%s: err_handle[%llx] err_stick[%llx] err_type[%08x:%s]\n",
pfx,
ent->err_handle, ent->err_stick,
ent->err_type,
sun4v_err_type_to_str(ent->err_type));
printk("%s: err_attrs[%08x:%s %s %s %s %s %s %s %s]\n",
pfx,
ent->err_attrs,
((ent->err_attrs & SUN4V_ERR_ATTRS_PROCESSOR) ?
"processor" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_MEMORY) ?
"memory" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_PIO) ?
"pio" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_INT_REGISTERS) ?
"integer-regs" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_FPU_REGISTERS) ?
"fpu-regs" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_USER_MODE) ?
"user" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_PRIV_MODE) ?
"privileged" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_RES_QUEUE_FULL) ?
"queue-full" : ""));
printk("%s: err_raddr[%016llx] err_size[%u] err_cpu[%u]\n",
pfx,
ent->err_raddr, ent->err_size, ent->err_cpu);
show_regs(regs);
if ((cnt = atomic_read(ocnt)) != 0) {
atomic_set(ocnt, 0);
wmb();
printk("%s: Queue overflowed %d times.\n",
pfx, cnt);
}
}
/* We run with %pil set to PIL_NORMAL_MAX and PSTATE_IE enabled in %pstate.
* Log the event and clear the first word of the entry.
*/
void sun4v_resum_error(struct pt_regs *regs, unsigned long offset)
{
struct sun4v_error_entry *ent, local_copy;
struct trap_per_cpu *tb;
unsigned long paddr;
int cpu;
cpu = get_cpu();
tb = &trap_block[cpu];
paddr = tb->resum_kernel_buf_pa + offset;
ent = __va(paddr);
memcpy(&local_copy, ent, sizeof(struct sun4v_error_entry));
/* We have a local copy now, so release the entry. */
ent->err_handle = 0;
wmb();
put_cpu();
if (ent->err_type == SUN4V_ERR_TYPE_WARNING_RES) {
/* If err_type is 0x4, it's a powerdown request. Do
* not do the usual resumable error log because that
* makes it look like some abnormal error.
*/
printk(KERN_INFO "Power down request...\n");
kill_cad_pid(SIGINT, 1);
return;
}
sun4v_log_error(regs, &local_copy, cpu,
KERN_ERR "RESUMABLE ERROR",
&sun4v_resum_oflow_cnt);
}
/* If we try to printk() we'll probably make matters worse, by trying
* to retake locks this cpu already holds or causing more errors. So
* just bump a counter, and we'll report these counter bumps above.
*/
void sun4v_resum_overflow(struct pt_regs *regs)
{
atomic_inc(&sun4v_resum_oflow_cnt);
}
/* We run with %pil set to PIL_NORMAL_MAX and PSTATE_IE enabled in %pstate.
* Log the event, clear the first word of the entry, and die.
*/
void sun4v_nonresum_error(struct pt_regs *regs, unsigned long offset)
{
struct sun4v_error_entry *ent, local_copy;
struct trap_per_cpu *tb;
unsigned long paddr;
int cpu;
cpu = get_cpu();
tb = &trap_block[cpu];
paddr = tb->nonresum_kernel_buf_pa + offset;
ent = __va(paddr);
memcpy(&local_copy, ent, sizeof(struct sun4v_error_entry));
/* We have a local copy now, so release the entry. */
ent->err_handle = 0;
wmb();
put_cpu();
#ifdef CONFIG_PCI
/* Check for the special PCI poke sequence. */
if (pci_poke_in_progress && pci_poke_cpu == cpu) {
pci_poke_faulted = 1;
regs->tpc += 4;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
sun4v_log_error(regs, &local_copy, cpu,
KERN_EMERG "NON-RESUMABLE ERROR",
&sun4v_nonresum_oflow_cnt);
panic("Non-resumable error.");
}
/* If we try to printk() we'll probably make matters worse, by trying
* to retake locks this cpu already holds or causing more errors. So
* just bump a counter, and we'll report these counter bumps above.
*/
void sun4v_nonresum_overflow(struct pt_regs *regs)
{
/* XXX Actually even this can make not that much sense. Perhaps
* XXX we should just pull the plug and panic directly from here?
*/
atomic_inc(&sun4v_nonresum_oflow_cnt);
}
unsigned long sun4v_err_itlb_vaddr;
unsigned long sun4v_err_itlb_ctx;
unsigned long sun4v_err_itlb_pte;
unsigned long sun4v_err_itlb_error;
void sun4v_itlb_error_report(struct pt_regs *regs, int tl)
{
if (tl > 1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
printk(KERN_EMERG "SUN4V-ITLB: Error at TPC[%lx], tl %d\n",
regs->tpc, tl);
printk(KERN_EMERG "SUN4V-ITLB: TPC<%pS>\n", (void *) regs->tpc);
printk(KERN_EMERG "SUN4V-ITLB: O7[%lx]\n", regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-ITLB: O7<%pS>\n",
(void *) regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-ITLB: vaddr[%lx] ctx[%lx] "
"pte[%lx] error[%lx]\n",
sun4v_err_itlb_vaddr, sun4v_err_itlb_ctx,
sun4v_err_itlb_pte, sun4v_err_itlb_error);
prom_halt();
}
unsigned long sun4v_err_dtlb_vaddr;
unsigned long sun4v_err_dtlb_ctx;
unsigned long sun4v_err_dtlb_pte;
unsigned long sun4v_err_dtlb_error;
void sun4v_dtlb_error_report(struct pt_regs *regs, int tl)
{
if (tl > 1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
printk(KERN_EMERG "SUN4V-DTLB: Error at TPC[%lx], tl %d\n",
regs->tpc, tl);
printk(KERN_EMERG "SUN4V-DTLB: TPC<%pS>\n", (void *) regs->tpc);
printk(KERN_EMERG "SUN4V-DTLB: O7[%lx]\n", regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-DTLB: O7<%pS>\n",
(void *) regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-DTLB: vaddr[%lx] ctx[%lx] "
"pte[%lx] error[%lx]\n",
sun4v_err_dtlb_vaddr, sun4v_err_dtlb_ctx,
sun4v_err_dtlb_pte, sun4v_err_dtlb_error);
prom_halt();
}
void hypervisor_tlbop_error(unsigned long err, unsigned long op)
{
printk(KERN_CRIT "SUN4V: TLB hv call error %lu for op %lu\n",
err, op);
}
void hypervisor_tlbop_error_xcall(unsigned long err, unsigned long op)
{
printk(KERN_CRIT "SUN4V: XCALL TLB hv call error %lu for op %lu\n",
err, op);
}
void do_fpe_common(struct pt_regs *regs)
{
if (regs->tstate & TSTATE_PRIV) {
regs->tpc = regs->tnpc;
regs->tnpc += 4;
} else {
unsigned long fsr = current_thread_info()->xfsr[0];
siginfo_t info;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
info.si_code = __SI_FAULT;
if ((fsr & 0x1c000) == (1 << 14)) {
if (fsr & 0x10)
info.si_code = FPE_FLTINV;
else if (fsr & 0x08)
info.si_code = FPE_FLTOVF;
else if (fsr & 0x04)
info.si_code = FPE_FLTUND;
else if (fsr & 0x02)
info.si_code = FPE_FLTDIV;
else if (fsr & 0x01)
info.si_code = FPE_FLTRES;
}
force_sig_info(SIGFPE, &info, current);
}
}
void do_fpieee(struct pt_regs *regs)
{
if (notify_die(DIE_TRAP, "fpu exception ieee", regs,
0, 0x24, SIGFPE) == NOTIFY_STOP)
return;
do_fpe_common(regs);
}
extern int do_mathemu(struct pt_regs *, struct fpustate *);
void do_fpother(struct pt_regs *regs)
{
struct fpustate *f = FPUSTATE;
int ret = 0;
if (notify_die(DIE_TRAP, "fpu exception other", regs,
0, 0x25, SIGFPE) == NOTIFY_STOP)
return;
switch ((current_thread_info()->xfsr[0] & 0x1c000)) {
case (2 << 14): /* unfinished_FPop */
case (3 << 14): /* unimplemented_FPop */
ret = do_mathemu(regs, f);
break;
}
if (ret)
return;
do_fpe_common(regs);
}
void do_tof(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "tagged arithmetic overflow", regs,
0, 0x26, SIGEMT) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV)
die_if_kernel("Penguin overflow trap from kernel mode", regs);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGEMT;
info.si_errno = 0;
info.si_code = EMT_TAGOVF;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGEMT, &info, current);
}
void do_div0(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "integer division by zero", regs,
0, 0x28, SIGFPE) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV)
die_if_kernel("TL0: Kernel divide by zero.", regs);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_code = FPE_INTDIV;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGFPE, &info, current);
}
static void instruction_dump(unsigned int *pc)
{
int i;
if ((((unsigned long) pc) & 3))
return;
printk("Instruction DUMP:");
for (i = -3; i < 6; i++)
printk("%c%08x%c",i?' ':'<',pc[i],i?' ':'>');
printk("\n");
}
static void user_instruction_dump(unsigned int __user *pc)
{
int i;
unsigned int buf[9];
if ((((unsigned long) pc) & 3))
return;
if (copy_from_user(buf, pc - 3, sizeof(buf)))
return;
printk("Instruction DUMP:");
for (i = 0; i < 9; i++)
printk("%c%08x%c",i==3?' ':'<',buf[i],i==3?' ':'>');
printk("\n");
}
void show_stack(struct task_struct *tsk, unsigned long *_ksp)
{
unsigned long fp, ksp;
struct thread_info *tp;
int count = 0;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
int graph = 0;
#endif
ksp = (unsigned long) _ksp;
if (!tsk)
tsk = current;
tp = task_thread_info(tsk);
if (ksp == 0UL) {
if (tsk == current)
asm("mov %%fp, %0" : "=r" (ksp));
else
ksp = tp->ksp;
}
if (tp == current_thread_info())
flushw_all();
fp = ksp + STACK_BIAS;
printk("Call Trace:\n");
do {
struct sparc_stackf *sf;
struct pt_regs *regs;
unsigned long pc;
if (!kstack_valid(tp, fp))
break;
sf = (struct sparc_stackf *) fp;
regs = (struct pt_regs *) (sf + 1);
if (kstack_is_trap_frame(tp, regs)) {
if (!(regs->tstate & TSTATE_PRIV))
break;
pc = regs->tpc;
fp = regs->u_regs[UREG_I6] + STACK_BIAS;
} else {
pc = sf->callers_pc;
fp = (unsigned long)sf->fp + STACK_BIAS;
}
printk(" [%016lx] %pS\n", pc, (void *) pc);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
if ((pc + 8UL) == (unsigned long) &return_to_handler) {
int index = tsk->curr_ret_stack;
if (tsk->ret_stack && index >= graph) {
pc = tsk->ret_stack[index - graph].ret;
printk(" [%016lx] %pS\n", pc, (void *) pc);
graph++;
}
}
#endif
} while (++count < 16);
}
void dump_stack(void)
{
show_stack(current, NULL);
}
EXPORT_SYMBOL(dump_stack);
static inline struct reg_window *kernel_stack_up(struct reg_window *rw)
{
unsigned long fp = rw->ins[6];
if (!fp)
return NULL;
return (struct reg_window *) (fp + STACK_BIAS);
}
void die_if_kernel(char *str, struct pt_regs *regs)
{
static int die_counter;
int count = 0;
/* Amuse the user. */
printk(
" \\|/ ____ \\|/\n"
" \"@'/ .. \\`@\"\n"
" /_| \\__/ |_\\\n"
" \\__U_/\n");
printk("%s(%d): %s [#%d]\n", current->comm, task_pid_nr(current), str, ++die_counter);
notify_die(DIE_OOPS, str, regs, 0, 255, SIGSEGV);
__asm__ __volatile__("flushw");
show_regs(regs);
add_taint(TAINT_DIE);
if (regs->tstate & TSTATE_PRIV) {
struct thread_info *tp = current_thread_info();
struct reg_window *rw = (struct reg_window *)
(regs->u_regs[UREG_FP] + STACK_BIAS);
/* Stop the back trace when we hit userland or we
* find some badly aligned kernel stack.
*/
while (rw &&
count++ < 30 &&
kstack_valid(tp, (unsigned long) rw)) {
printk("Caller[%016lx]: %pS\n", rw->ins[7],
(void *) rw->ins[7]);
rw = kernel_stack_up(rw);
}
instruction_dump ((unsigned int *) regs->tpc);
} else {
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
user_instruction_dump ((unsigned int __user *) regs->tpc);
}
if (regs->tstate & TSTATE_PRIV)
do_exit(SIGKILL);
do_exit(SIGSEGV);
}
EXPORT_SYMBOL(die_if_kernel);
#define VIS_OPCODE_MASK ((0x3 << 30) | (0x3f << 19))
#define VIS_OPCODE_VAL ((0x2 << 30) | (0x36 << 19))
extern int handle_popc(u32 insn, struct pt_regs *regs);
extern int handle_ldf_stq(u32 insn, struct pt_regs *regs);
void do_illegal_instruction(struct pt_regs *regs)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
siginfo_t info;
if (notify_die(DIE_TRAP, "illegal instruction", regs,
0, 0x10, SIGILL) == NOTIFY_STOP)
return;
if (tstate & TSTATE_PRIV)
die_if_kernel("Kernel illegal instruction", regs);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
if ((insn & 0xc1ffc000) == 0x81700000) /* POPC */ {
if (handle_popc(insn, regs))
return;
} else if ((insn & 0xc1580000) == 0xc1100000) /* LDQ/STQ */ {
if (handle_ldf_stq(insn, regs))
return;
} else if (tlb_type == hypervisor) {
if ((insn & VIS_OPCODE_MASK) == VIS_OPCODE_VAL) {
if (!vis_emul(regs, insn))
return;
} else {
struct fpustate *f = FPUSTATE;
/* XXX maybe verify XFSR bits like
* XXX do_fpother() does?
*/
if (do_mathemu(regs, f))
return;
}
}
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLOPC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
force_sig_info(SIGILL, &info, current);
}
extern void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn);
void mem_address_unaligned(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "memory address unaligned", regs,
0, 0x34, SIGSEGV) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
kernel_unaligned_trap(regs, *((unsigned int *)regs->tpc));
return;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *)sfar;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void sun4v_do_mna(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "memory address unaligned", regs,
0, 0x34, SIGSEGV) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
kernel_unaligned_trap(regs, *((unsigned int *)regs->tpc));
return;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void do_privop(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "privileged operation", regs,
0, 0x11, SIGILL) == NOTIFY_STOP)
return;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_PRVOPC;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGILL, &info, current);
}
void do_privact(struct pt_regs *regs)
{
do_privop(regs);
}
/* Trap level 1 stuff or other traps we should never see... */
void do_cee(struct pt_regs *regs)
{
die_if_kernel("TL0: Cache Error Exception", regs);
}
void do_cee_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Cache Error Exception", regs);
}
void do_dae_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Data Access Exception", regs);
}
void do_iae_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Instruction Access Exception", regs);
}
void do_div0_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: DIV0 Exception", regs);
}
void do_fpdis_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU Disabled", regs);
}
void do_fpieee_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU IEEE Exception", regs);
}
void do_fpother_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU Other Exception", regs);
}
void do_ill_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Illegal Instruction Exception", regs);
}
void do_irq_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: IRQ Exception", regs);
}
void do_lddfmna_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: LDDF Exception", regs);
}
void do_stdfmna_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: STDF Exception", regs);
}
void do_paw(struct pt_regs *regs)
{
die_if_kernel("TL0: Phys Watchpoint Exception", regs);
}
void do_paw_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Phys Watchpoint Exception", regs);
}
void do_vaw(struct pt_regs *regs)
{
die_if_kernel("TL0: Virt Watchpoint Exception", regs);
}
void do_vaw_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Virt Watchpoint Exception", regs);
}
void do_tof_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Tag Overflow Exception", regs);
}
void do_getpsr(struct pt_regs *regs)
{
regs->u_regs[UREG_I0] = tstate_to_psr(regs->tstate);
regs->tpc = regs->tnpc;
regs->tnpc += 4;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
}
struct trap_per_cpu trap_block[NR_CPUS];
EXPORT_SYMBOL(trap_block);
/* This can get invoked before sched_init() so play it super safe
* and use hard_smp_processor_id().
*/
void notrace init_cur_cpu_trap(struct thread_info *t)
{
int cpu = hard_smp_processor_id();
struct trap_per_cpu *p = &trap_block[cpu];
p->thread = t;
p->pgd_paddr = 0;
}
extern void thread_info_offsets_are_bolixed_dave(void);
extern void trap_per_cpu_offsets_are_bolixed_dave(void);
extern void tsb_config_offsets_are_bolixed_dave(void);
/* Only invoked on boot processor. */
void __init trap_init(void)
{
/* Compile time sanity check. */
BUILD_BUG_ON(TI_TASK != offsetof(struct thread_info, task) ||
TI_FLAGS != offsetof(struct thread_info, flags) ||
TI_CPU != offsetof(struct thread_info, cpu) ||
TI_FPSAVED != offsetof(struct thread_info, fpsaved) ||
TI_KSP != offsetof(struct thread_info, ksp) ||
TI_FAULT_ADDR != offsetof(struct thread_info,
fault_address) ||
TI_KREGS != offsetof(struct thread_info, kregs) ||
TI_UTRAPS != offsetof(struct thread_info, utraps) ||
TI_EXEC_DOMAIN != offsetof(struct thread_info,
exec_domain) ||
TI_REG_WINDOW != offsetof(struct thread_info,
reg_window) ||
TI_RWIN_SPTRS != offsetof(struct thread_info,
rwbuf_stkptrs) ||
TI_GSR != offsetof(struct thread_info, gsr) ||
TI_XFSR != offsetof(struct thread_info, xfsr) ||
TI_PRE_COUNT != offsetof(struct thread_info,
preempt_count) ||
TI_NEW_CHILD != offsetof(struct thread_info, new_child) ||
TI_SYS_NOERROR != offsetof(struct thread_info,
syscall_noerror) ||
TI_RESTART_BLOCK != offsetof(struct thread_info,
restart_block) ||
TI_KUNA_REGS != offsetof(struct thread_info,
kern_una_regs) ||
TI_KUNA_INSN != offsetof(struct thread_info,
kern_una_insn) ||
TI_FPREGS != offsetof(struct thread_info, fpregs) ||
(TI_FPREGS & (64 - 1)));
BUILD_BUG_ON(TRAP_PER_CPU_THREAD != offsetof(struct trap_per_cpu,
thread) ||
(TRAP_PER_CPU_PGD_PADDR !=
offsetof(struct trap_per_cpu, pgd_paddr)) ||
(TRAP_PER_CPU_CPU_MONDO_PA !=
offsetof(struct trap_per_cpu, cpu_mondo_pa)) ||
(TRAP_PER_CPU_DEV_MONDO_PA !=
offsetof(struct trap_per_cpu, dev_mondo_pa)) ||
(TRAP_PER_CPU_RESUM_MONDO_PA !=
offsetof(struct trap_per_cpu, resum_mondo_pa)) ||
(TRAP_PER_CPU_RESUM_KBUF_PA !=
offsetof(struct trap_per_cpu, resum_kernel_buf_pa)) ||
(TRAP_PER_CPU_NONRESUM_MONDO_PA !=
offsetof(struct trap_per_cpu, nonresum_mondo_pa)) ||
(TRAP_PER_CPU_NONRESUM_KBUF_PA !=
offsetof(struct trap_per_cpu, nonresum_kernel_buf_pa)) ||
(TRAP_PER_CPU_FAULT_INFO !=
offsetof(struct trap_per_cpu, fault_info)) ||
(TRAP_PER_CPU_CPU_MONDO_BLOCK_PA !=
offsetof(struct trap_per_cpu, cpu_mondo_block_pa)) ||
(TRAP_PER_CPU_CPU_LIST_PA !=
offsetof(struct trap_per_cpu, cpu_list_pa)) ||
(TRAP_PER_CPU_TSB_HUGE !=
offsetof(struct trap_per_cpu, tsb_huge)) ||
(TRAP_PER_CPU_TSB_HUGE_TEMP !=
offsetof(struct trap_per_cpu, tsb_huge_temp)) ||
(TRAP_PER_CPU_IRQ_WORKLIST_PA !=
offsetof(struct trap_per_cpu, irq_worklist_pa)) ||
(TRAP_PER_CPU_CPU_MONDO_QMASK !=
offsetof(struct trap_per_cpu, cpu_mondo_qmask)) ||
(TRAP_PER_CPU_DEV_MONDO_QMASK !=
offsetof(struct trap_per_cpu, dev_mondo_qmask)) ||
(TRAP_PER_CPU_RESUM_QMASK !=
offsetof(struct trap_per_cpu, resum_qmask)) ||
(TRAP_PER_CPU_NONRESUM_QMASK !=
offsetof(struct trap_per_cpu, nonresum_qmask)) ||
(TRAP_PER_CPU_PER_CPU_BASE !=
offsetof(struct trap_per_cpu, __per_cpu_base)));
BUILD_BUG_ON((TSB_CONFIG_TSB !=
offsetof(struct tsb_config, tsb)) ||
(TSB_CONFIG_RSS_LIMIT !=
offsetof(struct tsb_config, tsb_rss_limit)) ||
(TSB_CONFIG_NENTRIES !=
offsetof(struct tsb_config, tsb_nentries)) ||
(TSB_CONFIG_REG_VAL !=
offsetof(struct tsb_config, tsb_reg_val)) ||
(TSB_CONFIG_MAP_VADDR !=
offsetof(struct tsb_config, tsb_map_vaddr)) ||
(TSB_CONFIG_MAP_PTE !=
offsetof(struct tsb_config, tsb_map_pte)));
/* Attach to the address space of init_task. On SMP we
* do this in smp.c:smp_callin for other cpus.
*/
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
}
| gpl-2.0 |
kirananto/RaZorReborn | arch/tile/gxio/trio.c | 4656 | 1189 | /*
* Copyright 2012 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
/*
* Implementation of trio gxio calls.
*/
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/module.h>
#include <gxio/trio.h>
#include <gxio/iorpc_globals.h>
#include <gxio/iorpc_trio.h>
#include <gxio/kiorpc.h>
int gxio_trio_init(gxio_trio_context_t *context, unsigned int trio_index)
{
char file[32];
int fd;
snprintf(file, sizeof(file), "trio/%d/iorpc", trio_index);
fd = hv_dev_open((HV_VirtAddr) file, 0);
if (fd < 0) {
context->fd = -1;
if (fd >= GXIO_ERR_MIN && fd <= GXIO_ERR_MAX)
return fd;
else
return -ENODEV;
}
context->fd = fd;
return 0;
}
EXPORT_SYMBOL_GPL(gxio_trio_init);
| gpl-2.0 |
BrateloSlava/test-sez-cm-kernel | drivers/net/wireless/b43legacy/radio.c | 4912 | 60278 | /*
Broadcom B43legacy wireless driver
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>,
Stefano Brivio <stefano.brivio@polimi.it>
Michael Buesch <m@bues.ch>
Danny van Dyk <kugelfang@gentoo.org>
Andreas Jaggi <andreas.jaggi@waterwave.ch>
Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net>
Some parts of the code in this file are derived from the ipw2200
driver Copyright(c) 2003 - 2004 Intel 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; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <linux/delay.h>
#include "b43legacy.h"
#include "main.h"
#include "phy.h"
#include "radio.h"
#include "ilt.h"
/* Table for b43legacy_radio_calibrationvalue() */
static const u16 rcc_table[16] = {
0x0002, 0x0003, 0x0001, 0x000F,
0x0006, 0x0007, 0x0005, 0x000F,
0x000A, 0x000B, 0x0009, 0x000F,
0x000E, 0x000F, 0x000D, 0x000F,
};
/* Reverse the bits of a 4bit value.
* Example: 1101 is flipped 1011
*/
static u16 flip_4bit(u16 value)
{
u16 flipped = 0x0000;
B43legacy_BUG_ON(!((value & ~0x000F) == 0x0000));
flipped |= (value & 0x0001) << 3;
flipped |= (value & 0x0002) << 1;
flipped |= (value & 0x0004) >> 1;
flipped |= (value & 0x0008) >> 3;
return flipped;
}
/* Get the freq, as it has to be written to the device. */
static inline
u16 channel2freq_bg(u8 channel)
{
/* Frequencies are given as frequencies_bg[index] + 2.4GHz
* Starting with channel 1
*/
static const u16 frequencies_bg[14] = {
12, 17, 22, 27,
32, 37, 42, 47,
52, 57, 62, 67,
72, 84,
};
if (unlikely(channel < 1 || channel > 14)) {
printk(KERN_INFO "b43legacy: Channel %d is out of range\n",
channel);
dump_stack();
return 2412;
}
return frequencies_bg[channel - 1];
}
void b43legacy_radio_lock(struct b43legacy_wldev *dev)
{
u32 status;
status = b43legacy_read32(dev, B43legacy_MMIO_MACCTL);
B43legacy_WARN_ON(status & B43legacy_MACCTL_RADIOLOCK);
status |= B43legacy_MACCTL_RADIOLOCK;
b43legacy_write32(dev, B43legacy_MMIO_MACCTL, status);
mmiowb();
udelay(10);
}
void b43legacy_radio_unlock(struct b43legacy_wldev *dev)
{
u32 status;
b43legacy_read16(dev, B43legacy_MMIO_PHY_VER); /* dummy read */
status = b43legacy_read32(dev, B43legacy_MMIO_MACCTL);
B43legacy_WARN_ON(!(status & B43legacy_MACCTL_RADIOLOCK));
status &= ~B43legacy_MACCTL_RADIOLOCK;
b43legacy_write32(dev, B43legacy_MMIO_MACCTL, status);
mmiowb();
}
u16 b43legacy_radio_read16(struct b43legacy_wldev *dev, u16 offset)
{
struct b43legacy_phy *phy = &dev->phy;
switch (phy->type) {
case B43legacy_PHYTYPE_B:
if (phy->radio_ver == 0x2053) {
if (offset < 0x70)
offset += 0x80;
else if (offset < 0x80)
offset += 0x70;
} else if (phy->radio_ver == 0x2050)
offset |= 0x80;
else
B43legacy_WARN_ON(1);
break;
case B43legacy_PHYTYPE_G:
offset |= 0x80;
break;
default:
B43legacy_BUG_ON(1);
}
b43legacy_write16(dev, B43legacy_MMIO_RADIO_CONTROL, offset);
return b43legacy_read16(dev, B43legacy_MMIO_RADIO_DATA_LOW);
}
void b43legacy_radio_write16(struct b43legacy_wldev *dev, u16 offset, u16 val)
{
b43legacy_write16(dev, B43legacy_MMIO_RADIO_CONTROL, offset);
mmiowb();
b43legacy_write16(dev, B43legacy_MMIO_RADIO_DATA_LOW, val);
}
static void b43legacy_set_all_gains(struct b43legacy_wldev *dev,
s16 first, s16 second, s16 third)
{
struct b43legacy_phy *phy = &dev->phy;
u16 i;
u16 start = 0x08;
u16 end = 0x18;
u16 offset = 0x0400;
u16 tmp;
if (phy->rev <= 1) {
offset = 0x5000;
start = 0x10;
end = 0x20;
}
for (i = 0; i < 4; i++)
b43legacy_ilt_write(dev, offset + i, first);
for (i = start; i < end; i++)
b43legacy_ilt_write(dev, offset + i, second);
if (third != -1) {
tmp = ((u16)third << 14) | ((u16)third << 6);
b43legacy_phy_write(dev, 0x04A0,
(b43legacy_phy_read(dev, 0x04A0) & 0xBFBF)
| tmp);
b43legacy_phy_write(dev, 0x04A1,
(b43legacy_phy_read(dev, 0x04A1) & 0xBFBF)
| tmp);
b43legacy_phy_write(dev, 0x04A2,
(b43legacy_phy_read(dev, 0x04A2) & 0xBFBF)
| tmp);
}
b43legacy_dummy_transmission(dev);
}
static void b43legacy_set_original_gains(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 i;
u16 tmp;
u16 offset = 0x0400;
u16 start = 0x0008;
u16 end = 0x0018;
if (phy->rev <= 1) {
offset = 0x5000;
start = 0x0010;
end = 0x0020;
}
for (i = 0; i < 4; i++) {
tmp = (i & 0xFFFC);
tmp |= (i & 0x0001) << 1;
tmp |= (i & 0x0002) >> 1;
b43legacy_ilt_write(dev, offset + i, tmp);
}
for (i = start; i < end; i++)
b43legacy_ilt_write(dev, offset + i, i - start);
b43legacy_phy_write(dev, 0x04A0,
(b43legacy_phy_read(dev, 0x04A0) & 0xBFBF)
| 0x4040);
b43legacy_phy_write(dev, 0x04A1,
(b43legacy_phy_read(dev, 0x04A1) & 0xBFBF)
| 0x4040);
b43legacy_phy_write(dev, 0x04A2,
(b43legacy_phy_read(dev, 0x04A2) & 0xBFBF)
| 0x4000);
b43legacy_dummy_transmission(dev);
}
/* Synthetic PU workaround */
static void b43legacy_synth_pu_workaround(struct b43legacy_wldev *dev,
u8 channel)
{
struct b43legacy_phy *phy = &dev->phy;
might_sleep();
if (phy->radio_ver != 0x2050 || phy->radio_rev >= 6)
/* We do not need the workaround. */
return;
if (channel <= 10)
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL,
channel2freq_bg(channel + 4));
else
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL,
channel2freq_bg(channel));
msleep(1);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL,
channel2freq_bg(channel));
}
u8 b43legacy_radio_aci_detect(struct b43legacy_wldev *dev, u8 channel)
{
struct b43legacy_phy *phy = &dev->phy;
u8 ret = 0;
u16 saved;
u16 rssi;
u16 temp;
int i;
int j = 0;
saved = b43legacy_phy_read(dev, 0x0403);
b43legacy_radio_selectchannel(dev, channel, 0);
b43legacy_phy_write(dev, 0x0403, (saved & 0xFFF8) | 5);
if (phy->aci_hw_rssi)
rssi = b43legacy_phy_read(dev, 0x048A) & 0x3F;
else
rssi = saved & 0x3F;
/* clamp temp to signed 5bit */
if (rssi > 32)
rssi -= 64;
for (i = 0; i < 100; i++) {
temp = (b43legacy_phy_read(dev, 0x047F) >> 8) & 0x3F;
if (temp > 32)
temp -= 64;
if (temp < rssi)
j++;
if (j >= 20)
ret = 1;
}
b43legacy_phy_write(dev, 0x0403, saved);
return ret;
}
u8 b43legacy_radio_aci_scan(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u8 ret[13];
unsigned int channel = phy->channel;
unsigned int i;
unsigned int j;
unsigned int start;
unsigned int end;
if (!((phy->type == B43legacy_PHYTYPE_G) && (phy->rev > 0)))
return 0;
b43legacy_phy_lock(dev);
b43legacy_radio_lock(dev);
b43legacy_phy_write(dev, 0x0802,
b43legacy_phy_read(dev, 0x0802) & 0xFFFC);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev, B43legacy_PHY_G_CRS)
& 0x7FFF);
b43legacy_set_all_gains(dev, 3, 8, 1);
start = (channel - 5 > 0) ? channel - 5 : 1;
end = (channel + 5 < 14) ? channel + 5 : 13;
for (i = start; i <= end; i++) {
if (abs(channel - i) > 2)
ret[i-1] = b43legacy_radio_aci_detect(dev, i);
}
b43legacy_radio_selectchannel(dev, channel, 0);
b43legacy_phy_write(dev, 0x0802,
(b43legacy_phy_read(dev, 0x0802) & 0xFFFC)
| 0x0003);
b43legacy_phy_write(dev, 0x0403,
b43legacy_phy_read(dev, 0x0403) & 0xFFF8);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev, B43legacy_PHY_G_CRS)
| 0x8000);
b43legacy_set_original_gains(dev);
for (i = 0; i < 13; i++) {
if (!ret[i])
continue;
end = (i + 5 < 13) ? i + 5 : 13;
for (j = i; j < end; j++)
ret[j] = 1;
}
b43legacy_radio_unlock(dev);
b43legacy_phy_unlock(dev);
return ret[channel - 1];
}
/* http://bcm-specs.sipsolutions.net/NRSSILookupTable */
void b43legacy_nrssi_hw_write(struct b43legacy_wldev *dev, u16 offset, s16 val)
{
b43legacy_phy_write(dev, B43legacy_PHY_NRSSILT_CTRL, offset);
mmiowb();
b43legacy_phy_write(dev, B43legacy_PHY_NRSSILT_DATA, (u16)val);
}
/* http://bcm-specs.sipsolutions.net/NRSSILookupTable */
s16 b43legacy_nrssi_hw_read(struct b43legacy_wldev *dev, u16 offset)
{
u16 val;
b43legacy_phy_write(dev, B43legacy_PHY_NRSSILT_CTRL, offset);
val = b43legacy_phy_read(dev, B43legacy_PHY_NRSSILT_DATA);
return (s16)val;
}
/* http://bcm-specs.sipsolutions.net/NRSSILookupTable */
void b43legacy_nrssi_hw_update(struct b43legacy_wldev *dev, u16 val)
{
u16 i;
s16 tmp;
for (i = 0; i < 64; i++) {
tmp = b43legacy_nrssi_hw_read(dev, i);
tmp -= val;
tmp = clamp_val(tmp, -32, 31);
b43legacy_nrssi_hw_write(dev, i, tmp);
}
}
/* http://bcm-specs.sipsolutions.net/NRSSILookupTable */
void b43legacy_nrssi_mem_update(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
s16 i;
s16 delta;
s32 tmp;
delta = 0x1F - phy->nrssi[0];
for (i = 0; i < 64; i++) {
tmp = (i - delta) * phy->nrssislope;
tmp /= 0x10000;
tmp += 0x3A;
tmp = clamp_val(tmp, 0, 0x3F);
phy->nrssi_lt[i] = tmp;
}
}
static void b43legacy_calc_nrssi_offset(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 backup[20] = { 0 };
s16 v47F;
u16 i;
u16 saved = 0xFFFF;
backup[0] = b43legacy_phy_read(dev, 0x0001);
backup[1] = b43legacy_phy_read(dev, 0x0811);
backup[2] = b43legacy_phy_read(dev, 0x0812);
backup[3] = b43legacy_phy_read(dev, 0x0814);
backup[4] = b43legacy_phy_read(dev, 0x0815);
backup[5] = b43legacy_phy_read(dev, 0x005A);
backup[6] = b43legacy_phy_read(dev, 0x0059);
backup[7] = b43legacy_phy_read(dev, 0x0058);
backup[8] = b43legacy_phy_read(dev, 0x000A);
backup[9] = b43legacy_phy_read(dev, 0x0003);
backup[10] = b43legacy_radio_read16(dev, 0x007A);
backup[11] = b43legacy_radio_read16(dev, 0x0043);
b43legacy_phy_write(dev, 0x0429,
b43legacy_phy_read(dev, 0x0429) & 0x7FFF);
b43legacy_phy_write(dev, 0x0001,
(b43legacy_phy_read(dev, 0x0001) & 0x3FFF)
| 0x4000);
b43legacy_phy_write(dev, 0x0811,
b43legacy_phy_read(dev, 0x0811) | 0x000C);
b43legacy_phy_write(dev, 0x0812,
(b43legacy_phy_read(dev, 0x0812) & 0xFFF3)
| 0x0004);
b43legacy_phy_write(dev, 0x0802,
b43legacy_phy_read(dev, 0x0802) & ~(0x1 | 0x2));
if (phy->rev >= 6) {
backup[12] = b43legacy_phy_read(dev, 0x002E);
backup[13] = b43legacy_phy_read(dev, 0x002F);
backup[14] = b43legacy_phy_read(dev, 0x080F);
backup[15] = b43legacy_phy_read(dev, 0x0810);
backup[16] = b43legacy_phy_read(dev, 0x0801);
backup[17] = b43legacy_phy_read(dev, 0x0060);
backup[18] = b43legacy_phy_read(dev, 0x0014);
backup[19] = b43legacy_phy_read(dev, 0x0478);
b43legacy_phy_write(dev, 0x002E, 0);
b43legacy_phy_write(dev, 0x002F, 0);
b43legacy_phy_write(dev, 0x080F, 0);
b43legacy_phy_write(dev, 0x0810, 0);
b43legacy_phy_write(dev, 0x0478,
b43legacy_phy_read(dev, 0x0478) | 0x0100);
b43legacy_phy_write(dev, 0x0801,
b43legacy_phy_read(dev, 0x0801) | 0x0040);
b43legacy_phy_write(dev, 0x0060,
b43legacy_phy_read(dev, 0x0060) | 0x0040);
b43legacy_phy_write(dev, 0x0014,
b43legacy_phy_read(dev, 0x0014) | 0x0200);
}
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A) | 0x0070);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A) | 0x0080);
udelay(30);
v47F = (s16)((b43legacy_phy_read(dev, 0x047F) >> 8) & 0x003F);
if (v47F >= 0x20)
v47F -= 0x40;
if (v47F == 31) {
for (i = 7; i >= 4; i--) {
b43legacy_radio_write16(dev, 0x007B, i);
udelay(20);
v47F = (s16)((b43legacy_phy_read(dev, 0x047F) >> 8)
& 0x003F);
if (v47F >= 0x20)
v47F -= 0x40;
if (v47F < 31 && saved == 0xFFFF)
saved = i;
}
if (saved == 0xFFFF)
saved = 4;
} else {
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
& 0x007F);
b43legacy_phy_write(dev, 0x0814,
b43legacy_phy_read(dev, 0x0814) | 0x0001);
b43legacy_phy_write(dev, 0x0815,
b43legacy_phy_read(dev, 0x0815) & 0xFFFE);
b43legacy_phy_write(dev, 0x0811,
b43legacy_phy_read(dev, 0x0811) | 0x000C);
b43legacy_phy_write(dev, 0x0812,
b43legacy_phy_read(dev, 0x0812) | 0x000C);
b43legacy_phy_write(dev, 0x0811,
b43legacy_phy_read(dev, 0x0811) | 0x0030);
b43legacy_phy_write(dev, 0x0812,
b43legacy_phy_read(dev, 0x0812) | 0x0030);
b43legacy_phy_write(dev, 0x005A, 0x0480);
b43legacy_phy_write(dev, 0x0059, 0x0810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
if (phy->analog == 0)
b43legacy_phy_write(dev, 0x0003, 0x0122);
else
b43legacy_phy_write(dev, 0x000A,
b43legacy_phy_read(dev, 0x000A)
| 0x2000);
b43legacy_phy_write(dev, 0x0814,
b43legacy_phy_read(dev, 0x0814) | 0x0004);
b43legacy_phy_write(dev, 0x0815,
b43legacy_phy_read(dev, 0x0815) & 0xFFFB);
b43legacy_phy_write(dev, 0x0003,
(b43legacy_phy_read(dev, 0x0003) & 0xFF9F)
| 0x0040);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
| 0x000F);
b43legacy_set_all_gains(dev, 3, 0, 1);
b43legacy_radio_write16(dev, 0x0043,
(b43legacy_radio_read16(dev, 0x0043)
& 0x00F0) | 0x000F);
udelay(30);
v47F = (s16)((b43legacy_phy_read(dev, 0x047F) >> 8) & 0x003F);
if (v47F >= 0x20)
v47F -= 0x40;
if (v47F == -32) {
for (i = 0; i < 4; i++) {
b43legacy_radio_write16(dev, 0x007B, i);
udelay(20);
v47F = (s16)((b43legacy_phy_read(dev, 0x047F) >>
8) & 0x003F);
if (v47F >= 0x20)
v47F -= 0x40;
if (v47F > -31 && saved == 0xFFFF)
saved = i;
}
if (saved == 0xFFFF)
saved = 3;
} else
saved = 0;
}
b43legacy_radio_write16(dev, 0x007B, saved);
if (phy->rev >= 6) {
b43legacy_phy_write(dev, 0x002E, backup[12]);
b43legacy_phy_write(dev, 0x002F, backup[13]);
b43legacy_phy_write(dev, 0x080F, backup[14]);
b43legacy_phy_write(dev, 0x0810, backup[15]);
}
b43legacy_phy_write(dev, 0x0814, backup[3]);
b43legacy_phy_write(dev, 0x0815, backup[4]);
b43legacy_phy_write(dev, 0x005A, backup[5]);
b43legacy_phy_write(dev, 0x0059, backup[6]);
b43legacy_phy_write(dev, 0x0058, backup[7]);
b43legacy_phy_write(dev, 0x000A, backup[8]);
b43legacy_phy_write(dev, 0x0003, backup[9]);
b43legacy_radio_write16(dev, 0x0043, backup[11]);
b43legacy_radio_write16(dev, 0x007A, backup[10]);
b43legacy_phy_write(dev, 0x0802,
b43legacy_phy_read(dev, 0x0802) | 0x1 | 0x2);
b43legacy_phy_write(dev, 0x0429,
b43legacy_phy_read(dev, 0x0429) | 0x8000);
b43legacy_set_original_gains(dev);
if (phy->rev >= 6) {
b43legacy_phy_write(dev, 0x0801, backup[16]);
b43legacy_phy_write(dev, 0x0060, backup[17]);
b43legacy_phy_write(dev, 0x0014, backup[18]);
b43legacy_phy_write(dev, 0x0478, backup[19]);
}
b43legacy_phy_write(dev, 0x0001, backup[0]);
b43legacy_phy_write(dev, 0x0812, backup[2]);
b43legacy_phy_write(dev, 0x0811, backup[1]);
}
void b43legacy_calc_nrssi_slope(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 backup[18] = { 0 };
u16 tmp;
s16 nrssi0;
s16 nrssi1;
switch (phy->type) {
case B43legacy_PHYTYPE_B:
backup[0] = b43legacy_radio_read16(dev, 0x007A);
backup[1] = b43legacy_radio_read16(dev, 0x0052);
backup[2] = b43legacy_radio_read16(dev, 0x0043);
backup[3] = b43legacy_phy_read(dev, 0x0030);
backup[4] = b43legacy_phy_read(dev, 0x0026);
backup[5] = b43legacy_phy_read(dev, 0x0015);
backup[6] = b43legacy_phy_read(dev, 0x002A);
backup[7] = b43legacy_phy_read(dev, 0x0020);
backup[8] = b43legacy_phy_read(dev, 0x005A);
backup[9] = b43legacy_phy_read(dev, 0x0059);
backup[10] = b43legacy_phy_read(dev, 0x0058);
backup[11] = b43legacy_read16(dev, 0x03E2);
backup[12] = b43legacy_read16(dev, 0x03E6);
backup[13] = b43legacy_read16(dev, B43legacy_MMIO_CHANNEL_EXT);
tmp = b43legacy_radio_read16(dev, 0x007A);
tmp &= (phy->rev >= 5) ? 0x007F : 0x000F;
b43legacy_radio_write16(dev, 0x007A, tmp);
b43legacy_phy_write(dev, 0x0030, 0x00FF);
b43legacy_write16(dev, 0x03EC, 0x7F7F);
b43legacy_phy_write(dev, 0x0026, 0x0000);
b43legacy_phy_write(dev, 0x0015,
b43legacy_phy_read(dev, 0x0015) | 0x0020);
b43legacy_phy_write(dev, 0x002A, 0x08A3);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
| 0x0080);
nrssi0 = (s16)b43legacy_phy_read(dev, 0x0027);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
& 0x007F);
if (phy->analog >= 2)
b43legacy_write16(dev, 0x03E6, 0x0040);
else if (phy->analog == 0)
b43legacy_write16(dev, 0x03E6, 0x0122);
else
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) & 0x2000);
b43legacy_phy_write(dev, 0x0020, 0x3F3F);
b43legacy_phy_write(dev, 0x0015, 0xF330);
b43legacy_radio_write16(dev, 0x005A, 0x0060);
b43legacy_radio_write16(dev, 0x0043,
b43legacy_radio_read16(dev, 0x0043)
& 0x00F0);
b43legacy_phy_write(dev, 0x005A, 0x0480);
b43legacy_phy_write(dev, 0x0059, 0x0810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
udelay(20);
nrssi1 = (s16)b43legacy_phy_read(dev, 0x0027);
b43legacy_phy_write(dev, 0x0030, backup[3]);
b43legacy_radio_write16(dev, 0x007A, backup[0]);
b43legacy_write16(dev, 0x03E2, backup[11]);
b43legacy_phy_write(dev, 0x0026, backup[4]);
b43legacy_phy_write(dev, 0x0015, backup[5]);
b43legacy_phy_write(dev, 0x002A, backup[6]);
b43legacy_synth_pu_workaround(dev, phy->channel);
if (phy->analog != 0)
b43legacy_write16(dev, 0x03F4, backup[13]);
b43legacy_phy_write(dev, 0x0020, backup[7]);
b43legacy_phy_write(dev, 0x005A, backup[8]);
b43legacy_phy_write(dev, 0x0059, backup[9]);
b43legacy_phy_write(dev, 0x0058, backup[10]);
b43legacy_radio_write16(dev, 0x0052, backup[1]);
b43legacy_radio_write16(dev, 0x0043, backup[2]);
if (nrssi0 == nrssi1)
phy->nrssislope = 0x00010000;
else
phy->nrssislope = 0x00400000 / (nrssi0 - nrssi1);
if (nrssi0 <= -4) {
phy->nrssi[0] = nrssi0;
phy->nrssi[1] = nrssi1;
}
break;
case B43legacy_PHYTYPE_G:
if (phy->radio_rev >= 9)
return;
if (phy->radio_rev == 8)
b43legacy_calc_nrssi_offset(dev);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev, B43legacy_PHY_G_CRS)
& 0x7FFF);
b43legacy_phy_write(dev, 0x0802,
b43legacy_phy_read(dev, 0x0802) & 0xFFFC);
backup[7] = b43legacy_read16(dev, 0x03E2);
b43legacy_write16(dev, 0x03E2,
b43legacy_read16(dev, 0x03E2) | 0x8000);
backup[0] = b43legacy_radio_read16(dev, 0x007A);
backup[1] = b43legacy_radio_read16(dev, 0x0052);
backup[2] = b43legacy_radio_read16(dev, 0x0043);
backup[3] = b43legacy_phy_read(dev, 0x0015);
backup[4] = b43legacy_phy_read(dev, 0x005A);
backup[5] = b43legacy_phy_read(dev, 0x0059);
backup[6] = b43legacy_phy_read(dev, 0x0058);
backup[8] = b43legacy_read16(dev, 0x03E6);
backup[9] = b43legacy_read16(dev, B43legacy_MMIO_CHANNEL_EXT);
if (phy->rev >= 3) {
backup[10] = b43legacy_phy_read(dev, 0x002E);
backup[11] = b43legacy_phy_read(dev, 0x002F);
backup[12] = b43legacy_phy_read(dev, 0x080F);
backup[13] = b43legacy_phy_read(dev,
B43legacy_PHY_G_LO_CONTROL);
backup[14] = b43legacy_phy_read(dev, 0x0801);
backup[15] = b43legacy_phy_read(dev, 0x0060);
backup[16] = b43legacy_phy_read(dev, 0x0014);
backup[17] = b43legacy_phy_read(dev, 0x0478);
b43legacy_phy_write(dev, 0x002E, 0);
b43legacy_phy_write(dev, B43legacy_PHY_G_LO_CONTROL, 0);
switch (phy->rev) {
case 4: case 6: case 7:
b43legacy_phy_write(dev, 0x0478,
b43legacy_phy_read(dev,
0x0478) | 0x0100);
b43legacy_phy_write(dev, 0x0801,
b43legacy_phy_read(dev,
0x0801) | 0x0040);
break;
case 3: case 5:
b43legacy_phy_write(dev, 0x0801,
b43legacy_phy_read(dev,
0x0801) & 0xFFBF);
break;
}
b43legacy_phy_write(dev, 0x0060,
b43legacy_phy_read(dev, 0x0060)
| 0x0040);
b43legacy_phy_write(dev, 0x0014,
b43legacy_phy_read(dev, 0x0014)
| 0x0200);
}
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
| 0x0070);
b43legacy_set_all_gains(dev, 0, 8, 0);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
& 0x00F7);
if (phy->rev >= 2) {
b43legacy_phy_write(dev, 0x0811,
(b43legacy_phy_read(dev, 0x0811)
& 0xFFCF) | 0x0030);
b43legacy_phy_write(dev, 0x0812,
(b43legacy_phy_read(dev, 0x0812)
& 0xFFCF) | 0x0010);
}
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
| 0x0080);
udelay(20);
nrssi0 = (s16)((b43legacy_phy_read(dev, 0x047F) >> 8) & 0x003F);
if (nrssi0 >= 0x0020)
nrssi0 -= 0x0040;
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
& 0x007F);
if (phy->analog >= 2)
b43legacy_phy_write(dev, 0x0003,
(b43legacy_phy_read(dev, 0x0003)
& 0xFF9F) | 0x0040);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) | 0x2000);
b43legacy_radio_write16(dev, 0x007A,
b43legacy_radio_read16(dev, 0x007A)
| 0x000F);
b43legacy_phy_write(dev, 0x0015, 0xF330);
if (phy->rev >= 2) {
b43legacy_phy_write(dev, 0x0812,
(b43legacy_phy_read(dev, 0x0812)
& 0xFFCF) | 0x0020);
b43legacy_phy_write(dev, 0x0811,
(b43legacy_phy_read(dev, 0x0811)
& 0xFFCF) | 0x0020);
}
b43legacy_set_all_gains(dev, 3, 0, 1);
if (phy->radio_rev == 8)
b43legacy_radio_write16(dev, 0x0043, 0x001F);
else {
tmp = b43legacy_radio_read16(dev, 0x0052) & 0xFF0F;
b43legacy_radio_write16(dev, 0x0052, tmp | 0x0060);
tmp = b43legacy_radio_read16(dev, 0x0043) & 0xFFF0;
b43legacy_radio_write16(dev, 0x0043, tmp | 0x0009);
}
b43legacy_phy_write(dev, 0x005A, 0x0480);
b43legacy_phy_write(dev, 0x0059, 0x0810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
udelay(20);
nrssi1 = (s16)((b43legacy_phy_read(dev, 0x047F) >> 8) & 0x003F);
if (nrssi1 >= 0x0020)
nrssi1 -= 0x0040;
if (nrssi0 == nrssi1)
phy->nrssislope = 0x00010000;
else
phy->nrssislope = 0x00400000 / (nrssi0 - nrssi1);
if (nrssi0 >= -4) {
phy->nrssi[0] = nrssi1;
phy->nrssi[1] = nrssi0;
}
if (phy->rev >= 3) {
b43legacy_phy_write(dev, 0x002E, backup[10]);
b43legacy_phy_write(dev, 0x002F, backup[11]);
b43legacy_phy_write(dev, 0x080F, backup[12]);
b43legacy_phy_write(dev, B43legacy_PHY_G_LO_CONTROL,
backup[13]);
}
if (phy->rev >= 2) {
b43legacy_phy_write(dev, 0x0812,
b43legacy_phy_read(dev, 0x0812)
& 0xFFCF);
b43legacy_phy_write(dev, 0x0811,
b43legacy_phy_read(dev, 0x0811)
& 0xFFCF);
}
b43legacy_radio_write16(dev, 0x007A, backup[0]);
b43legacy_radio_write16(dev, 0x0052, backup[1]);
b43legacy_radio_write16(dev, 0x0043, backup[2]);
b43legacy_write16(dev, 0x03E2, backup[7]);
b43legacy_write16(dev, 0x03E6, backup[8]);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT, backup[9]);
b43legacy_phy_write(dev, 0x0015, backup[3]);
b43legacy_phy_write(dev, 0x005A, backup[4]);
b43legacy_phy_write(dev, 0x0059, backup[5]);
b43legacy_phy_write(dev, 0x0058, backup[6]);
b43legacy_synth_pu_workaround(dev, phy->channel);
b43legacy_phy_write(dev, 0x0802,
b43legacy_phy_read(dev, 0x0802) | 0x0003);
b43legacy_set_original_gains(dev);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev, B43legacy_PHY_G_CRS)
| 0x8000);
if (phy->rev >= 3) {
b43legacy_phy_write(dev, 0x0801, backup[14]);
b43legacy_phy_write(dev, 0x0060, backup[15]);
b43legacy_phy_write(dev, 0x0014, backup[16]);
b43legacy_phy_write(dev, 0x0478, backup[17]);
}
b43legacy_nrssi_mem_update(dev);
b43legacy_calc_nrssi_threshold(dev);
break;
default:
B43legacy_BUG_ON(1);
}
}
void b43legacy_calc_nrssi_threshold(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
s32 threshold;
s32 a;
s32 b;
s16 tmp16;
u16 tmp_u16;
switch (phy->type) {
case B43legacy_PHYTYPE_B: {
if (phy->radio_ver != 0x2050)
return;
if (!(dev->dev->bus->sprom.boardflags_lo &
B43legacy_BFL_RSSI))
return;
if (phy->radio_rev >= 6) {
threshold = (phy->nrssi[1] - phy->nrssi[0]) * 32;
threshold += 20 * (phy->nrssi[0] + 1);
threshold /= 40;
} else
threshold = phy->nrssi[1] - 5;
threshold = clamp_val(threshold, 0, 0x3E);
b43legacy_phy_read(dev, 0x0020); /* dummy read */
b43legacy_phy_write(dev, 0x0020, (((u16)threshold) << 8)
| 0x001C);
if (phy->radio_rev >= 6) {
b43legacy_phy_write(dev, 0x0087, 0x0E0D);
b43legacy_phy_write(dev, 0x0086, 0x0C0B);
b43legacy_phy_write(dev, 0x0085, 0x0A09);
b43legacy_phy_write(dev, 0x0084, 0x0808);
b43legacy_phy_write(dev, 0x0083, 0x0808);
b43legacy_phy_write(dev, 0x0082, 0x0604);
b43legacy_phy_write(dev, 0x0081, 0x0302);
b43legacy_phy_write(dev, 0x0080, 0x0100);
}
break;
}
case B43legacy_PHYTYPE_G:
if (!phy->gmode ||
!(dev->dev->bus->sprom.boardflags_lo &
B43legacy_BFL_RSSI)) {
tmp16 = b43legacy_nrssi_hw_read(dev, 0x20);
if (tmp16 >= 0x20)
tmp16 -= 0x40;
if (tmp16 < 3)
b43legacy_phy_write(dev, 0x048A,
(b43legacy_phy_read(dev,
0x048A) & 0xF000) | 0x09EB);
else
b43legacy_phy_write(dev, 0x048A,
(b43legacy_phy_read(dev,
0x048A) & 0xF000) | 0x0AED);
} else {
if (phy->interfmode ==
B43legacy_RADIO_INTERFMODE_NONWLAN) {
a = 0xE;
b = 0xA;
} else if (!phy->aci_wlan_automatic &&
phy->aci_enable) {
a = 0x13;
b = 0x12;
} else {
a = 0xE;
b = 0x11;
}
a = a * (phy->nrssi[1] - phy->nrssi[0]);
a += (phy->nrssi[0] << 6);
if (a < 32)
a += 31;
else
a += 32;
a = a >> 6;
a = clamp_val(a, -31, 31);
b = b * (phy->nrssi[1] - phy->nrssi[0]);
b += (phy->nrssi[0] << 6);
if (b < 32)
b += 31;
else
b += 32;
b = b >> 6;
b = clamp_val(b, -31, 31);
tmp_u16 = b43legacy_phy_read(dev, 0x048A) & 0xF000;
tmp_u16 |= ((u32)b & 0x0000003F);
tmp_u16 |= (((u32)a & 0x0000003F) << 6);
b43legacy_phy_write(dev, 0x048A, tmp_u16);
}
break;
default:
B43legacy_BUG_ON(1);
}
}
/* Stack implementation to save/restore values from the
* interference mitigation code.
* It is save to restore values in random order.
*/
static void _stack_save(u32 *_stackptr, size_t *stackidx,
u8 id, u16 offset, u16 value)
{
u32 *stackptr = &(_stackptr[*stackidx]);
B43legacy_WARN_ON(!((offset & 0xE000) == 0x0000));
B43legacy_WARN_ON(!((id & 0xF8) == 0x00));
*stackptr = offset;
*stackptr |= ((u32)id) << 13;
*stackptr |= ((u32)value) << 16;
(*stackidx)++;
B43legacy_WARN_ON(!(*stackidx < B43legacy_INTERFSTACK_SIZE));
}
static u16 _stack_restore(u32 *stackptr,
u8 id, u16 offset)
{
size_t i;
B43legacy_WARN_ON(!((offset & 0xE000) == 0x0000));
B43legacy_WARN_ON(!((id & 0xF8) == 0x00));
for (i = 0; i < B43legacy_INTERFSTACK_SIZE; i++, stackptr++) {
if ((*stackptr & 0x00001FFF) != offset)
continue;
if (((*stackptr & 0x00007000) >> 13) != id)
continue;
return ((*stackptr & 0xFFFF0000) >> 16);
}
B43legacy_BUG_ON(1);
return 0;
}
#define phy_stacksave(offset) \
do { \
_stack_save(stack, &stackidx, 0x1, (offset), \
b43legacy_phy_read(dev, (offset))); \
} while (0)
#define phy_stackrestore(offset) \
do { \
b43legacy_phy_write(dev, (offset), \
_stack_restore(stack, 0x1, \
(offset))); \
} while (0)
#define radio_stacksave(offset) \
do { \
_stack_save(stack, &stackidx, 0x2, (offset), \
b43legacy_radio_read16(dev, (offset))); \
} while (0)
#define radio_stackrestore(offset) \
do { \
b43legacy_radio_write16(dev, (offset), \
_stack_restore(stack, 0x2, \
(offset))); \
} while (0)
#define ilt_stacksave(offset) \
do { \
_stack_save(stack, &stackidx, 0x3, (offset), \
b43legacy_ilt_read(dev, (offset))); \
} while (0)
#define ilt_stackrestore(offset) \
do { \
b43legacy_ilt_write(dev, (offset), \
_stack_restore(stack, 0x3, \
(offset))); \
} while (0)
static void
b43legacy_radio_interference_mitigation_enable(struct b43legacy_wldev *dev,
int mode)
{
struct b43legacy_phy *phy = &dev->phy;
u16 tmp;
u16 flipped;
u32 tmp32;
size_t stackidx = 0;
u32 *stack = phy->interfstack;
switch (mode) {
case B43legacy_RADIO_INTERFMODE_NONWLAN:
if (phy->rev != 1) {
b43legacy_phy_write(dev, 0x042B,
b43legacy_phy_read(dev, 0x042B)
| 0x0800);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS) & ~0x4000);
break;
}
radio_stacksave(0x0078);
tmp = (b43legacy_radio_read16(dev, 0x0078) & 0x001E);
flipped = flip_4bit(tmp);
if (flipped < 10 && flipped >= 8)
flipped = 7;
else if (flipped >= 10)
flipped -= 3;
flipped = flip_4bit(flipped);
flipped = (flipped << 1) | 0x0020;
b43legacy_radio_write16(dev, 0x0078, flipped);
b43legacy_calc_nrssi_threshold(dev);
phy_stacksave(0x0406);
b43legacy_phy_write(dev, 0x0406, 0x7E28);
b43legacy_phy_write(dev, 0x042B,
b43legacy_phy_read(dev, 0x042B) | 0x0800);
b43legacy_phy_write(dev, B43legacy_PHY_RADIO_BITFIELD,
b43legacy_phy_read(dev,
B43legacy_PHY_RADIO_BITFIELD) | 0x1000);
phy_stacksave(0x04A0);
b43legacy_phy_write(dev, 0x04A0,
(b43legacy_phy_read(dev, 0x04A0) & 0xC0C0)
| 0x0008);
phy_stacksave(0x04A1);
b43legacy_phy_write(dev, 0x04A1,
(b43legacy_phy_read(dev, 0x04A1) & 0xC0C0)
| 0x0605);
phy_stacksave(0x04A2);
b43legacy_phy_write(dev, 0x04A2,
(b43legacy_phy_read(dev, 0x04A2) & 0xC0C0)
| 0x0204);
phy_stacksave(0x04A8);
b43legacy_phy_write(dev, 0x04A8,
(b43legacy_phy_read(dev, 0x04A8) & 0xC0C0)
| 0x0803);
phy_stacksave(0x04AB);
b43legacy_phy_write(dev, 0x04AB,
(b43legacy_phy_read(dev, 0x04AB) & 0xC0C0)
| 0x0605);
phy_stacksave(0x04A7);
b43legacy_phy_write(dev, 0x04A7, 0x0002);
phy_stacksave(0x04A3);
b43legacy_phy_write(dev, 0x04A3, 0x287A);
phy_stacksave(0x04A9);
b43legacy_phy_write(dev, 0x04A9, 0x2027);
phy_stacksave(0x0493);
b43legacy_phy_write(dev, 0x0493, 0x32F5);
phy_stacksave(0x04AA);
b43legacy_phy_write(dev, 0x04AA, 0x2027);
phy_stacksave(0x04AC);
b43legacy_phy_write(dev, 0x04AC, 0x32F5);
break;
case B43legacy_RADIO_INTERFMODE_MANUALWLAN:
if (b43legacy_phy_read(dev, 0x0033) & 0x0800)
break;
phy->aci_enable = true;
phy_stacksave(B43legacy_PHY_RADIO_BITFIELD);
phy_stacksave(B43legacy_PHY_G_CRS);
if (phy->rev < 2)
phy_stacksave(0x0406);
else {
phy_stacksave(0x04C0);
phy_stacksave(0x04C1);
}
phy_stacksave(0x0033);
phy_stacksave(0x04A7);
phy_stacksave(0x04A3);
phy_stacksave(0x04A9);
phy_stacksave(0x04AA);
phy_stacksave(0x04AC);
phy_stacksave(0x0493);
phy_stacksave(0x04A1);
phy_stacksave(0x04A0);
phy_stacksave(0x04A2);
phy_stacksave(0x048A);
phy_stacksave(0x04A8);
phy_stacksave(0x04AB);
if (phy->rev == 2) {
phy_stacksave(0x04AD);
phy_stacksave(0x04AE);
} else if (phy->rev >= 3) {
phy_stacksave(0x04AD);
phy_stacksave(0x0415);
phy_stacksave(0x0416);
phy_stacksave(0x0417);
ilt_stacksave(0x1A00 + 0x2);
ilt_stacksave(0x1A00 + 0x3);
}
phy_stacksave(0x042B);
phy_stacksave(0x048C);
b43legacy_phy_write(dev, B43legacy_PHY_RADIO_BITFIELD,
b43legacy_phy_read(dev,
B43legacy_PHY_RADIO_BITFIELD) & ~0x1000);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
(b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS)
& 0xFFFC) | 0x0002);
b43legacy_phy_write(dev, 0x0033, 0x0800);
b43legacy_phy_write(dev, 0x04A3, 0x2027);
b43legacy_phy_write(dev, 0x04A9, 0x1CA8);
b43legacy_phy_write(dev, 0x0493, 0x287A);
b43legacy_phy_write(dev, 0x04AA, 0x1CA8);
b43legacy_phy_write(dev, 0x04AC, 0x287A);
b43legacy_phy_write(dev, 0x04A0,
(b43legacy_phy_read(dev, 0x04A0)
& 0xFFC0) | 0x001A);
b43legacy_phy_write(dev, 0x04A7, 0x000D);
if (phy->rev < 2)
b43legacy_phy_write(dev, 0x0406, 0xFF0D);
else if (phy->rev == 2) {
b43legacy_phy_write(dev, 0x04C0, 0xFFFF);
b43legacy_phy_write(dev, 0x04C1, 0x00A9);
} else {
b43legacy_phy_write(dev, 0x04C0, 0x00C1);
b43legacy_phy_write(dev, 0x04C1, 0x0059);
}
b43legacy_phy_write(dev, 0x04A1,
(b43legacy_phy_read(dev, 0x04A1)
& 0xC0FF) | 0x1800);
b43legacy_phy_write(dev, 0x04A1,
(b43legacy_phy_read(dev, 0x04A1)
& 0xFFC0) | 0x0015);
b43legacy_phy_write(dev, 0x04A8,
(b43legacy_phy_read(dev, 0x04A8)
& 0xCFFF) | 0x1000);
b43legacy_phy_write(dev, 0x04A8,
(b43legacy_phy_read(dev, 0x04A8)
& 0xF0FF) | 0x0A00);
b43legacy_phy_write(dev, 0x04AB,
(b43legacy_phy_read(dev, 0x04AB)
& 0xCFFF) | 0x1000);
b43legacy_phy_write(dev, 0x04AB,
(b43legacy_phy_read(dev, 0x04AB)
& 0xF0FF) | 0x0800);
b43legacy_phy_write(dev, 0x04AB,
(b43legacy_phy_read(dev, 0x04AB)
& 0xFFCF) | 0x0010);
b43legacy_phy_write(dev, 0x04AB,
(b43legacy_phy_read(dev, 0x04AB)
& 0xFFF0) | 0x0005);
b43legacy_phy_write(dev, 0x04A8,
(b43legacy_phy_read(dev, 0x04A8)
& 0xFFCF) | 0x0010);
b43legacy_phy_write(dev, 0x04A8,
(b43legacy_phy_read(dev, 0x04A8)
& 0xFFF0) | 0x0006);
b43legacy_phy_write(dev, 0x04A2,
(b43legacy_phy_read(dev, 0x04A2)
& 0xF0FF) | 0x0800);
b43legacy_phy_write(dev, 0x04A0,
(b43legacy_phy_read(dev, 0x04A0)
& 0xF0FF) | 0x0500);
b43legacy_phy_write(dev, 0x04A2,
(b43legacy_phy_read(dev, 0x04A2)
& 0xFFF0) | 0x000B);
if (phy->rev >= 3) {
b43legacy_phy_write(dev, 0x048A,
b43legacy_phy_read(dev, 0x048A)
& ~0x8000);
b43legacy_phy_write(dev, 0x0415,
(b43legacy_phy_read(dev, 0x0415)
& 0x8000) | 0x36D8);
b43legacy_phy_write(dev, 0x0416,
(b43legacy_phy_read(dev, 0x0416)
& 0x8000) | 0x36D8);
b43legacy_phy_write(dev, 0x0417,
(b43legacy_phy_read(dev, 0x0417)
& 0xFE00) | 0x016D);
} else {
b43legacy_phy_write(dev, 0x048A,
b43legacy_phy_read(dev, 0x048A)
| 0x1000);
b43legacy_phy_write(dev, 0x048A,
(b43legacy_phy_read(dev, 0x048A)
& 0x9FFF) | 0x2000);
tmp32 = b43legacy_shm_read32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET);
if (!(tmp32 & 0x800)) {
tmp32 |= 0x800;
b43legacy_shm_write32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET,
tmp32);
}
}
if (phy->rev >= 2)
b43legacy_phy_write(dev, 0x042B,
b43legacy_phy_read(dev, 0x042B)
| 0x0800);
b43legacy_phy_write(dev, 0x048C,
(b43legacy_phy_read(dev, 0x048C)
& 0xF0FF) | 0x0200);
if (phy->rev == 2) {
b43legacy_phy_write(dev, 0x04AE,
(b43legacy_phy_read(dev, 0x04AE)
& 0xFF00) | 0x007F);
b43legacy_phy_write(dev, 0x04AD,
(b43legacy_phy_read(dev, 0x04AD)
& 0x00FF) | 0x1300);
} else if (phy->rev >= 6) {
b43legacy_ilt_write(dev, 0x1A00 + 0x3, 0x007F);
b43legacy_ilt_write(dev, 0x1A00 + 0x2, 0x007F);
b43legacy_phy_write(dev, 0x04AD,
b43legacy_phy_read(dev, 0x04AD)
& 0x00FF);
}
b43legacy_calc_nrssi_slope(dev);
break;
default:
B43legacy_BUG_ON(1);
}
}
static void
b43legacy_radio_interference_mitigation_disable(struct b43legacy_wldev *dev,
int mode)
{
struct b43legacy_phy *phy = &dev->phy;
u32 tmp32;
u32 *stack = phy->interfstack;
switch (mode) {
case B43legacy_RADIO_INTERFMODE_NONWLAN:
if (phy->rev != 1) {
b43legacy_phy_write(dev, 0x042B,
b43legacy_phy_read(dev, 0x042B)
& ~0x0800);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS) | 0x4000);
break;
}
phy_stackrestore(0x0078);
b43legacy_calc_nrssi_threshold(dev);
phy_stackrestore(0x0406);
b43legacy_phy_write(dev, 0x042B,
b43legacy_phy_read(dev, 0x042B) & ~0x0800);
if (!dev->bad_frames_preempt)
b43legacy_phy_write(dev, B43legacy_PHY_RADIO_BITFIELD,
b43legacy_phy_read(dev,
B43legacy_PHY_RADIO_BITFIELD)
& ~(1 << 11));
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
b43legacy_phy_read(dev, B43legacy_PHY_G_CRS)
| 0x4000);
phy_stackrestore(0x04A0);
phy_stackrestore(0x04A1);
phy_stackrestore(0x04A2);
phy_stackrestore(0x04A8);
phy_stackrestore(0x04AB);
phy_stackrestore(0x04A7);
phy_stackrestore(0x04A3);
phy_stackrestore(0x04A9);
phy_stackrestore(0x0493);
phy_stackrestore(0x04AA);
phy_stackrestore(0x04AC);
break;
case B43legacy_RADIO_INTERFMODE_MANUALWLAN:
if (!(b43legacy_phy_read(dev, 0x0033) & 0x0800))
break;
phy->aci_enable = false;
phy_stackrestore(B43legacy_PHY_RADIO_BITFIELD);
phy_stackrestore(B43legacy_PHY_G_CRS);
phy_stackrestore(0x0033);
phy_stackrestore(0x04A3);
phy_stackrestore(0x04A9);
phy_stackrestore(0x0493);
phy_stackrestore(0x04AA);
phy_stackrestore(0x04AC);
phy_stackrestore(0x04A0);
phy_stackrestore(0x04A7);
if (phy->rev >= 2) {
phy_stackrestore(0x04C0);
phy_stackrestore(0x04C1);
} else
phy_stackrestore(0x0406);
phy_stackrestore(0x04A1);
phy_stackrestore(0x04AB);
phy_stackrestore(0x04A8);
if (phy->rev == 2) {
phy_stackrestore(0x04AD);
phy_stackrestore(0x04AE);
} else if (phy->rev >= 3) {
phy_stackrestore(0x04AD);
phy_stackrestore(0x0415);
phy_stackrestore(0x0416);
phy_stackrestore(0x0417);
ilt_stackrestore(0x1A00 + 0x2);
ilt_stackrestore(0x1A00 + 0x3);
}
phy_stackrestore(0x04A2);
phy_stackrestore(0x04A8);
phy_stackrestore(0x042B);
phy_stackrestore(0x048C);
tmp32 = b43legacy_shm_read32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET);
if (tmp32 & 0x800) {
tmp32 &= ~0x800;
b43legacy_shm_write32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET,
tmp32);
}
b43legacy_calc_nrssi_slope(dev);
break;
default:
B43legacy_BUG_ON(1);
}
}
#undef phy_stacksave
#undef phy_stackrestore
#undef radio_stacksave
#undef radio_stackrestore
#undef ilt_stacksave
#undef ilt_stackrestore
int b43legacy_radio_set_interference_mitigation(struct b43legacy_wldev *dev,
int mode)
{
struct b43legacy_phy *phy = &dev->phy;
int currentmode;
if ((phy->type != B43legacy_PHYTYPE_G) ||
(phy->rev == 0) || (!phy->gmode))
return -ENODEV;
phy->aci_wlan_automatic = false;
switch (mode) {
case B43legacy_RADIO_INTERFMODE_AUTOWLAN:
phy->aci_wlan_automatic = true;
if (phy->aci_enable)
mode = B43legacy_RADIO_INTERFMODE_MANUALWLAN;
else
mode = B43legacy_RADIO_INTERFMODE_NONE;
break;
case B43legacy_RADIO_INTERFMODE_NONE:
case B43legacy_RADIO_INTERFMODE_NONWLAN:
case B43legacy_RADIO_INTERFMODE_MANUALWLAN:
break;
default:
return -EINVAL;
}
currentmode = phy->interfmode;
if (currentmode == mode)
return 0;
if (currentmode != B43legacy_RADIO_INTERFMODE_NONE)
b43legacy_radio_interference_mitigation_disable(dev,
currentmode);
if (mode == B43legacy_RADIO_INTERFMODE_NONE) {
phy->aci_enable = false;
phy->aci_hw_rssi = false;
} else
b43legacy_radio_interference_mitigation_enable(dev, mode);
phy->interfmode = mode;
return 0;
}
u16 b43legacy_radio_calibrationvalue(struct b43legacy_wldev *dev)
{
u16 reg;
u16 index;
u16 ret;
reg = b43legacy_radio_read16(dev, 0x0060);
index = (reg & 0x001E) >> 1;
ret = rcc_table[index] << 1;
ret |= (reg & 0x0001);
ret |= 0x0020;
return ret;
}
#define LPD(L, P, D) (((L) << 2) | ((P) << 1) | ((D) << 0))
static u16 b43legacy_get_812_value(struct b43legacy_wldev *dev, u8 lpd)
{
struct b43legacy_phy *phy = &dev->phy;
u16 loop_or = 0;
u16 adj_loopback_gain = phy->loopback_gain[0];
u8 loop;
u16 extern_lna_control;
if (!phy->gmode)
return 0;
if (!has_loopback_gain(phy)) {
if (phy->rev < 7 || !(dev->dev->bus->sprom.boardflags_lo
& B43legacy_BFL_EXTLNA)) {
switch (lpd) {
case LPD(0, 1, 1):
return 0x0FB2;
case LPD(0, 0, 1):
return 0x00B2;
case LPD(1, 0, 1):
return 0x30B2;
case LPD(1, 0, 0):
return 0x30B3;
default:
B43legacy_BUG_ON(1);
}
} else {
switch (lpd) {
case LPD(0, 1, 1):
return 0x8FB2;
case LPD(0, 0, 1):
return 0x80B2;
case LPD(1, 0, 1):
return 0x20B2;
case LPD(1, 0, 0):
return 0x20B3;
default:
B43legacy_BUG_ON(1);
}
}
} else {
if (phy->radio_rev == 8)
adj_loopback_gain += 0x003E;
else
adj_loopback_gain += 0x0026;
if (adj_loopback_gain >= 0x46) {
adj_loopback_gain -= 0x46;
extern_lna_control = 0x3000;
} else if (adj_loopback_gain >= 0x3A) {
adj_loopback_gain -= 0x3A;
extern_lna_control = 0x2000;
} else if (adj_loopback_gain >= 0x2E) {
adj_loopback_gain -= 0x2E;
extern_lna_control = 0x1000;
} else {
adj_loopback_gain -= 0x10;
extern_lna_control = 0x0000;
}
for (loop = 0; loop < 16; loop++) {
u16 tmp = adj_loopback_gain - 6 * loop;
if (tmp < 6)
break;
}
loop_or = (loop << 8) | extern_lna_control;
if (phy->rev >= 7 && dev->dev->bus->sprom.boardflags_lo
& B43legacy_BFL_EXTLNA) {
if (extern_lna_control)
loop_or |= 0x8000;
switch (lpd) {
case LPD(0, 1, 1):
return 0x8F92;
case LPD(0, 0, 1):
return (0x8092 | loop_or);
case LPD(1, 0, 1):
return (0x2092 | loop_or);
case LPD(1, 0, 0):
return (0x2093 | loop_or);
default:
B43legacy_BUG_ON(1);
}
} else {
switch (lpd) {
case LPD(0, 1, 1):
return 0x0F92;
case LPD(0, 0, 1):
case LPD(1, 0, 1):
return (0x0092 | loop_or);
case LPD(1, 0, 0):
return (0x0093 | loop_or);
default:
B43legacy_BUG_ON(1);
}
}
}
return 0;
}
u16 b43legacy_radio_init2050(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 backup[21] = { 0 };
u16 ret;
u16 i;
u16 j;
u32 tmp1 = 0;
u32 tmp2 = 0;
backup[0] = b43legacy_radio_read16(dev, 0x0043);
backup[14] = b43legacy_radio_read16(dev, 0x0051);
backup[15] = b43legacy_radio_read16(dev, 0x0052);
backup[1] = b43legacy_phy_read(dev, 0x0015);
backup[16] = b43legacy_phy_read(dev, 0x005A);
backup[17] = b43legacy_phy_read(dev, 0x0059);
backup[18] = b43legacy_phy_read(dev, 0x0058);
if (phy->type == B43legacy_PHYTYPE_B) {
backup[2] = b43legacy_phy_read(dev, 0x0030);
backup[3] = b43legacy_read16(dev, 0x03EC);
b43legacy_phy_write(dev, 0x0030, 0x00FF);
b43legacy_write16(dev, 0x03EC, 0x3F3F);
} else {
if (phy->gmode) {
backup[4] = b43legacy_phy_read(dev, 0x0811);
backup[5] = b43legacy_phy_read(dev, 0x0812);
backup[6] = b43legacy_phy_read(dev, 0x0814);
backup[7] = b43legacy_phy_read(dev, 0x0815);
backup[8] = b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS);
backup[9] = b43legacy_phy_read(dev, 0x0802);
b43legacy_phy_write(dev, 0x0814,
(b43legacy_phy_read(dev, 0x0814)
| 0x0003));
b43legacy_phy_write(dev, 0x0815,
(b43legacy_phy_read(dev, 0x0815)
& 0xFFFC));
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
(b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS) & 0x7FFF));
b43legacy_phy_write(dev, 0x0802,
(b43legacy_phy_read(dev, 0x0802)
& 0xFFFC));
if (phy->rev > 1) { /* loopback gain enabled */
backup[19] = b43legacy_phy_read(dev, 0x080F);
backup[20] = b43legacy_phy_read(dev, 0x0810);
if (phy->rev >= 3)
b43legacy_phy_write(dev, 0x080F,
0xC020);
else
b43legacy_phy_write(dev, 0x080F,
0x8020);
b43legacy_phy_write(dev, 0x0810, 0x0000);
}
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 1, 1)));
if (phy->rev < 7 ||
!(dev->dev->bus->sprom.boardflags_lo
& B43legacy_BFL_EXTLNA))
b43legacy_phy_write(dev, 0x0811, 0x01B3);
else
b43legacy_phy_write(dev, 0x0811, 0x09B3);
}
}
b43legacy_write16(dev, B43legacy_MMIO_PHY_RADIO,
(b43legacy_read16(dev, B43legacy_MMIO_PHY_RADIO)
| 0x8000));
backup[10] = b43legacy_phy_read(dev, 0x0035);
b43legacy_phy_write(dev, 0x0035,
(b43legacy_phy_read(dev, 0x0035) & 0xFF7F));
backup[11] = b43legacy_read16(dev, 0x03E6);
backup[12] = b43legacy_read16(dev, B43legacy_MMIO_CHANNEL_EXT);
/* Initialization */
if (phy->analog == 0)
b43legacy_write16(dev, 0x03E6, 0x0122);
else {
if (phy->analog >= 2)
b43legacy_phy_write(dev, 0x0003,
(b43legacy_phy_read(dev, 0x0003)
& 0xFFBF) | 0x0040);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
(b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) | 0x2000));
}
ret = b43legacy_radio_calibrationvalue(dev);
if (phy->type == B43legacy_PHYTYPE_B)
b43legacy_radio_write16(dev, 0x0078, 0x0026);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 1, 1)));
b43legacy_phy_write(dev, 0x0015, 0xBFAF);
b43legacy_phy_write(dev, 0x002B, 0x1403);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xBFA0);
b43legacy_radio_write16(dev, 0x0051,
(b43legacy_radio_read16(dev, 0x0051)
| 0x0004));
if (phy->radio_rev == 8)
b43legacy_radio_write16(dev, 0x0043, 0x001F);
else {
b43legacy_radio_write16(dev, 0x0052, 0x0000);
b43legacy_radio_write16(dev, 0x0043,
(b43legacy_radio_read16(dev, 0x0043)
& 0xFFF0) | 0x0009);
}
b43legacy_phy_write(dev, 0x0058, 0x0000);
for (i = 0; i < 16; i++) {
b43legacy_phy_write(dev, 0x005A, 0x0480);
b43legacy_phy_write(dev, 0x0059, 0xC810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xEFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 0)));
b43legacy_phy_write(dev, 0x0015, 0xFFF0);
udelay(20);
tmp1 += b43legacy_phy_read(dev, 0x002D);
b43legacy_phy_write(dev, 0x0058, 0x0000);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
}
tmp1++;
tmp1 >>= 9;
udelay(10);
b43legacy_phy_write(dev, 0x0058, 0x0000);
for (i = 0; i < 16; i++) {
b43legacy_radio_write16(dev, 0x0078, (flip_4bit(i) << 1)
| 0x0020);
backup[13] = b43legacy_radio_read16(dev, 0x0078);
udelay(10);
for (j = 0; j < 16; j++) {
b43legacy_phy_write(dev, 0x005A, 0x0D80);
b43legacy_phy_write(dev, 0x0059, 0xC810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xEFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 0)));
b43legacy_phy_write(dev, 0x0015, 0xFFF0);
udelay(10);
tmp2 += b43legacy_phy_read(dev, 0x002D);
b43legacy_phy_write(dev, 0x0058, 0x0000);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
}
tmp2++;
tmp2 >>= 8;
if (tmp1 < tmp2)
break;
}
/* Restore the registers */
b43legacy_phy_write(dev, 0x0015, backup[1]);
b43legacy_radio_write16(dev, 0x0051, backup[14]);
b43legacy_radio_write16(dev, 0x0052, backup[15]);
b43legacy_radio_write16(dev, 0x0043, backup[0]);
b43legacy_phy_write(dev, 0x005A, backup[16]);
b43legacy_phy_write(dev, 0x0059, backup[17]);
b43legacy_phy_write(dev, 0x0058, backup[18]);
b43legacy_write16(dev, 0x03E6, backup[11]);
if (phy->analog != 0)
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT, backup[12]);
b43legacy_phy_write(dev, 0x0035, backup[10]);
b43legacy_radio_selectchannel(dev, phy->channel, 1);
if (phy->type == B43legacy_PHYTYPE_B) {
b43legacy_phy_write(dev, 0x0030, backup[2]);
b43legacy_write16(dev, 0x03EC, backup[3]);
} else {
if (phy->gmode) {
b43legacy_write16(dev, B43legacy_MMIO_PHY_RADIO,
(b43legacy_read16(dev,
B43legacy_MMIO_PHY_RADIO) & 0x7FFF));
b43legacy_phy_write(dev, 0x0811, backup[4]);
b43legacy_phy_write(dev, 0x0812, backup[5]);
b43legacy_phy_write(dev, 0x0814, backup[6]);
b43legacy_phy_write(dev, 0x0815, backup[7]);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
backup[8]);
b43legacy_phy_write(dev, 0x0802, backup[9]);
if (phy->rev > 1) {
b43legacy_phy_write(dev, 0x080F, backup[19]);
b43legacy_phy_write(dev, 0x0810, backup[20]);
}
}
}
if (i >= 15)
ret = backup[13];
return ret;
}
static inline
u16 freq_r3A_value(u16 frequency)
{
u16 value;
if (frequency < 5091)
value = 0x0040;
else if (frequency < 5321)
value = 0x0000;
else if (frequency < 5806)
value = 0x0080;
else
value = 0x0040;
return value;
}
void b43legacy_radio_set_tx_iq(struct b43legacy_wldev *dev)
{
static const u8 data_high[5] = { 0x00, 0x40, 0x80, 0x90, 0xD0 };
static const u8 data_low[5] = { 0x00, 0x01, 0x05, 0x06, 0x0A };
u16 tmp = b43legacy_radio_read16(dev, 0x001E);
int i;
int j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (tmp == (data_high[i] | data_low[j])) {
b43legacy_phy_write(dev, 0x0069, (i - j) << 8 |
0x00C0);
return;
}
}
}
}
int b43legacy_radio_selectchannel(struct b43legacy_wldev *dev,
u8 channel,
int synthetic_pu_workaround)
{
struct b43legacy_phy *phy = &dev->phy;
if (channel == 0xFF) {
switch (phy->type) {
case B43legacy_PHYTYPE_B:
case B43legacy_PHYTYPE_G:
channel = B43legacy_RADIO_DEFAULT_CHANNEL_BG;
break;
default:
B43legacy_WARN_ON(1);
}
}
/* TODO: Check if channel is valid - return -EINVAL if not */
if (synthetic_pu_workaround)
b43legacy_synth_pu_workaround(dev, channel);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL,
channel2freq_bg(channel));
if (channel == 14) {
if (dev->dev->bus->sprom.country_code == 5) /* JAPAN) */
b43legacy_shm_write32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET,
b43legacy_shm_read32(dev,
B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET)
& ~(1 << 7));
else
b43legacy_shm_write32(dev, B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET,
b43legacy_shm_read32(dev,
B43legacy_SHM_SHARED,
B43legacy_UCODEFLAGS_OFFSET)
| (1 << 7));
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) | (1 << 11));
} else
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) & 0xF7BF);
phy->channel = channel;
/*XXX: Using the longer of 2 timeouts (8000 vs 2000 usecs). Specs states
* that 2000 usecs might suffice. */
msleep(8);
return 0;
}
void b43legacy_radio_set_txantenna(struct b43legacy_wldev *dev, u32 val)
{
u16 tmp;
val <<= 8;
tmp = b43legacy_shm_read16(dev, B43legacy_SHM_SHARED, 0x0022) & 0xFCFF;
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0022, tmp | val);
tmp = b43legacy_shm_read16(dev, B43legacy_SHM_SHARED, 0x03A8) & 0xFCFF;
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x03A8, tmp | val);
tmp = b43legacy_shm_read16(dev, B43legacy_SHM_SHARED, 0x0054) & 0xFCFF;
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0054, tmp | val);
}
/* http://bcm-specs.sipsolutions.net/TX_Gain_Base_Band */
static u16 b43legacy_get_txgain_base_band(u16 txpower)
{
u16 ret;
B43legacy_WARN_ON(txpower > 63);
if (txpower >= 54)
ret = 2;
else if (txpower >= 49)
ret = 4;
else if (txpower >= 44)
ret = 5;
else
ret = 6;
return ret;
}
/* http://bcm-specs.sipsolutions.net/TX_Gain_Radio_Frequency_Power_Amplifier */
static u16 b43legacy_get_txgain_freq_power_amp(u16 txpower)
{
u16 ret;
B43legacy_WARN_ON(txpower > 63);
if (txpower >= 32)
ret = 0;
else if (txpower >= 25)
ret = 1;
else if (txpower >= 20)
ret = 2;
else if (txpower >= 12)
ret = 3;
else
ret = 4;
return ret;
}
/* http://bcm-specs.sipsolutions.net/TX_Gain_Digital_Analog_Converter */
static u16 b43legacy_get_txgain_dac(u16 txpower)
{
u16 ret;
B43legacy_WARN_ON(txpower > 63);
if (txpower >= 54)
ret = txpower - 53;
else if (txpower >= 49)
ret = txpower - 42;
else if (txpower >= 44)
ret = txpower - 37;
else if (txpower >= 32)
ret = txpower - 32;
else if (txpower >= 25)
ret = txpower - 20;
else if (txpower >= 20)
ret = txpower - 13;
else if (txpower >= 12)
ret = txpower - 8;
else
ret = txpower;
return ret;
}
void b43legacy_radio_set_txpower_a(struct b43legacy_wldev *dev, u16 txpower)
{
struct b43legacy_phy *phy = &dev->phy;
u16 pamp;
u16 base;
u16 dac;
u16 ilt;
txpower = clamp_val(txpower, 0, 63);
pamp = b43legacy_get_txgain_freq_power_amp(txpower);
pamp <<= 5;
pamp &= 0x00E0;
b43legacy_phy_write(dev, 0x0019, pamp);
base = b43legacy_get_txgain_base_band(txpower);
base &= 0x000F;
b43legacy_phy_write(dev, 0x0017, base | 0x0020);
ilt = b43legacy_ilt_read(dev, 0x3001);
ilt &= 0x0007;
dac = b43legacy_get_txgain_dac(txpower);
dac <<= 3;
dac |= ilt;
b43legacy_ilt_write(dev, 0x3001, dac);
phy->txpwr_offset = txpower;
/* TODO: FuncPlaceholder (Adjust BB loft cancel) */
}
void b43legacy_radio_set_txpower_bg(struct b43legacy_wldev *dev,
u16 baseband_attenuation,
u16 radio_attenuation,
u16 txpower)
{
struct b43legacy_phy *phy = &dev->phy;
if (baseband_attenuation == 0xFFFF)
baseband_attenuation = phy->bbatt;
if (radio_attenuation == 0xFFFF)
radio_attenuation = phy->rfatt;
if (txpower == 0xFFFF)
txpower = phy->txctl1;
phy->bbatt = baseband_attenuation;
phy->rfatt = radio_attenuation;
phy->txctl1 = txpower;
B43legacy_WARN_ON(baseband_attenuation > 11);
if (phy->radio_rev < 6)
B43legacy_WARN_ON(radio_attenuation > 9);
else
B43legacy_WARN_ON(radio_attenuation > 31);
B43legacy_WARN_ON(txpower > 7);
b43legacy_phy_set_baseband_attenuation(dev, baseband_attenuation);
b43legacy_radio_write16(dev, 0x0043, radio_attenuation);
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0064,
radio_attenuation);
if (phy->radio_ver == 0x2050)
b43legacy_radio_write16(dev, 0x0052,
(b43legacy_radio_read16(dev, 0x0052)
& ~0x0070) | ((txpower << 4) & 0x0070));
/* FIXME: The spec is very weird and unclear here. */
if (phy->type == B43legacy_PHYTYPE_G)
b43legacy_phy_lo_adjust(dev, 0);
}
u16 b43legacy_default_baseband_attenuation(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
if (phy->radio_ver == 0x2050 && phy->radio_rev < 6)
return 0;
return 2;
}
u16 b43legacy_default_radio_attenuation(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 att = 0xFFFF;
switch (phy->radio_ver) {
case 0x2053:
switch (phy->radio_rev) {
case 1:
att = 6;
break;
}
break;
case 0x2050:
switch (phy->radio_rev) {
case 0:
att = 5;
break;
case 1:
if (phy->type == B43legacy_PHYTYPE_G) {
if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type == 0x421 &&
dev->dev->bus->boardinfo.rev >= 30)
att = 3;
else if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type == 0x416)
att = 3;
else
att = 1;
} else {
if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type == 0x421 &&
dev->dev->bus->boardinfo.rev >= 30)
att = 7;
else
att = 6;
}
break;
case 2:
if (phy->type == B43legacy_PHYTYPE_G) {
if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type == 0x421 &&
dev->dev->bus->boardinfo.rev >= 30)
att = 3;
else if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type ==
0x416)
att = 5;
else if (dev->dev->bus->chip_id == 0x4320)
att = 4;
else
att = 3;
} else
att = 6;
break;
case 3:
att = 5;
break;
case 4:
case 5:
att = 1;
break;
case 6:
case 7:
att = 5;
break;
case 8:
att = 0x1A;
break;
case 9:
default:
att = 5;
}
}
if (is_bcm_board_vendor(dev) &&
dev->dev->bus->boardinfo.type == 0x421) {
if (dev->dev->bus->boardinfo.rev < 0x43)
att = 2;
else if (dev->dev->bus->boardinfo.rev < 0x51)
att = 3;
}
if (att == 0xFFFF)
att = 5;
return att;
}
u16 b43legacy_default_txctl1(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
if (phy->radio_ver != 0x2050)
return 0;
if (phy->radio_rev == 1)
return 3;
if (phy->radio_rev < 6)
return 2;
if (phy->radio_rev == 8)
return 1;
return 0;
}
void b43legacy_radio_turn_on(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
int err;
u8 channel;
might_sleep();
if (phy->radio_on)
return;
switch (phy->type) {
case B43legacy_PHYTYPE_B:
case B43legacy_PHYTYPE_G:
b43legacy_phy_write(dev, 0x0015, 0x8000);
b43legacy_phy_write(dev, 0x0015, 0xCC00);
b43legacy_phy_write(dev, 0x0015,
(phy->gmode ? 0x00C0 : 0x0000));
if (phy->radio_off_context.valid) {
/* Restore the RFover values. */
b43legacy_phy_write(dev, B43legacy_PHY_RFOVER,
phy->radio_off_context.rfover);
b43legacy_phy_write(dev, B43legacy_PHY_RFOVERVAL,
phy->radio_off_context.rfoverval);
phy->radio_off_context.valid = false;
}
channel = phy->channel;
err = b43legacy_radio_selectchannel(dev,
B43legacy_RADIO_DEFAULT_CHANNEL_BG, 1);
err |= b43legacy_radio_selectchannel(dev, channel, 0);
B43legacy_WARN_ON(err);
break;
default:
B43legacy_BUG_ON(1);
}
phy->radio_on = true;
}
void b43legacy_radio_turn_off(struct b43legacy_wldev *dev, bool force)
{
struct b43legacy_phy *phy = &dev->phy;
if (!phy->radio_on && !force)
return;
if (phy->type == B43legacy_PHYTYPE_G && dev->dev->id.revision >= 5) {
u16 rfover, rfoverval;
rfover = b43legacy_phy_read(dev, B43legacy_PHY_RFOVER);
rfoverval = b43legacy_phy_read(dev, B43legacy_PHY_RFOVERVAL);
if (!force) {
phy->radio_off_context.rfover = rfover;
phy->radio_off_context.rfoverval = rfoverval;
phy->radio_off_context.valid = true;
}
b43legacy_phy_write(dev, B43legacy_PHY_RFOVER, rfover | 0x008C);
b43legacy_phy_write(dev, B43legacy_PHY_RFOVERVAL,
rfoverval & 0xFF73);
} else
b43legacy_phy_write(dev, 0x0015, 0xAA00);
phy->radio_on = false;
b43legacydbg(dev->wl, "Radio initialized\n");
}
void b43legacy_radio_clear_tssi(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
switch (phy->type) {
case B43legacy_PHYTYPE_B:
case B43legacy_PHYTYPE_G:
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0058,
0x7F7F);
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x005a,
0x7F7F);
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0070,
0x7F7F);
b43legacy_shm_write16(dev, B43legacy_SHM_SHARED, 0x0072,
0x7F7F);
break;
}
}
| gpl-2.0 |
pretoriano80/N5MIUI | drivers/input/tablet/kbtab.c | 4912 | 5092 | #include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <asm/unaligned.h>
/*
* Version Information
* v0.0.1 - Original, extremely basic version, 2.4.xx only
* v0.0.2 - Updated, works with 2.5.62 and 2.4.20;
* - added pressure-threshold modules param code from
* Alex Perry <alex.perry@ieee.org>
*/
#define DRIVER_VERSION "v0.0.2"
#define DRIVER_AUTHOR "Josh Myer <josh@joshisanerd.com>"
#define DRIVER_DESC "USB KB Gear JamStudio Tablet driver"
#define DRIVER_LICENSE "GPL"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
#define USB_VENDOR_ID_KBGEAR 0x084e
static int kb_pressure_click = 0x10;
module_param(kb_pressure_click, int, 0);
MODULE_PARM_DESC(kb_pressure_click, "pressure threshold for clicks");
struct kbtab {
unsigned char *data;
dma_addr_t data_dma;
struct input_dev *dev;
struct usb_device *usbdev;
struct urb *irq;
char phys[32];
};
static void kbtab_irq(struct urb *urb)
{
struct kbtab *kbtab = urb->context;
unsigned char *data = kbtab->data;
struct input_dev *dev = kbtab->dev;
int pressure;
int retval;
switch (urb->status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d", __func__, urb->status);
return;
default:
dbg("%s - nonzero urb status received: %d", __func__, urb->status);
goto exit;
}
input_report_key(dev, BTN_TOOL_PEN, 1);
input_report_abs(dev, ABS_X, get_unaligned_le16(&data[1]));
input_report_abs(dev, ABS_Y, get_unaligned_le16(&data[3]));
/*input_report_key(dev, BTN_TOUCH , data[0] & 0x01);*/
input_report_key(dev, BTN_RIGHT, data[0] & 0x02);
pressure = data[5];
if (kb_pressure_click == -1)
input_report_abs(dev, ABS_PRESSURE, pressure);
else
input_report_key(dev, BTN_LEFT, pressure > kb_pressure_click ? 1 : 0);
input_sync(dev);
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
err("%s - usb_submit_urb failed with result %d",
__func__, retval);
}
static struct usb_device_id kbtab_ids[] = {
{ USB_DEVICE(USB_VENDOR_ID_KBGEAR, 0x1001), .driver_info = 0 },
{ }
};
MODULE_DEVICE_TABLE(usb, kbtab_ids);
static int kbtab_open(struct input_dev *dev)
{
struct kbtab *kbtab = input_get_drvdata(dev);
kbtab->irq->dev = kbtab->usbdev;
if (usb_submit_urb(kbtab->irq, GFP_KERNEL))
return -EIO;
return 0;
}
static void kbtab_close(struct input_dev *dev)
{
struct kbtab *kbtab = input_get_drvdata(dev);
usb_kill_urb(kbtab->irq);
}
static int kbtab_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_endpoint_descriptor *endpoint;
struct kbtab *kbtab;
struct input_dev *input_dev;
int error = -ENOMEM;
kbtab = kzalloc(sizeof(struct kbtab), GFP_KERNEL);
input_dev = input_allocate_device();
if (!kbtab || !input_dev)
goto fail1;
kbtab->data = usb_alloc_coherent(dev, 8, GFP_KERNEL, &kbtab->data_dma);
if (!kbtab->data)
goto fail1;
kbtab->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!kbtab->irq)
goto fail2;
kbtab->usbdev = dev;
kbtab->dev = input_dev;
usb_make_path(dev, kbtab->phys, sizeof(kbtab->phys));
strlcat(kbtab->phys, "/input0", sizeof(kbtab->phys));
input_dev->name = "KB Gear Tablet";
input_dev->phys = kbtab->phys;
usb_to_input_id(dev, &input_dev->id);
input_dev->dev.parent = &intf->dev;
input_set_drvdata(input_dev, kbtab);
input_dev->open = kbtab_open;
input_dev->close = kbtab_close;
input_dev->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_LEFT)] |=
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
input_dev->keybit[BIT_WORD(BTN_DIGI)] |=
BIT_MASK(BTN_TOOL_PEN) | BIT_MASK(BTN_TOUCH);
input_set_abs_params(input_dev, ABS_X, 0, 0x2000, 4, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 0x1750, 4, 0);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, 0xff, 0, 0);
endpoint = &intf->cur_altsetting->endpoint[0].desc;
usb_fill_int_urb(kbtab->irq, dev,
usb_rcvintpipe(dev, endpoint->bEndpointAddress),
kbtab->data, 8,
kbtab_irq, kbtab, endpoint->bInterval);
kbtab->irq->transfer_dma = kbtab->data_dma;
kbtab->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(kbtab->dev);
if (error)
goto fail3;
usb_set_intfdata(intf, kbtab);
return 0;
fail3: usb_free_urb(kbtab->irq);
fail2: usb_free_coherent(dev, 8, kbtab->data, kbtab->data_dma);
fail1: input_free_device(input_dev);
kfree(kbtab);
return error;
}
static void kbtab_disconnect(struct usb_interface *intf)
{
struct kbtab *kbtab = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
input_unregister_device(kbtab->dev);
usb_free_urb(kbtab->irq);
usb_free_coherent(kbtab->usbdev, 8, kbtab->data, kbtab->data_dma);
kfree(kbtab);
}
static struct usb_driver kbtab_driver = {
.name = "kbtab",
.probe = kbtab_probe,
.disconnect = kbtab_disconnect,
.id_table = kbtab_ids,
};
module_usb_driver(kbtab_driver);
| gpl-2.0 |
Jazz-823/kernel_sony_togari | drivers/bcma/driver_chipcommon.c | 5168 | 4296 | /*
* Broadcom specific AMBA
* ChipCommon core driver
*
* Copyright 2005, Broadcom Corporation
* Copyright 2006, 2007, Michael Buesch <m@bues.ch>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include "bcma_private.h"
#include <linux/export.h>
#include <linux/bcma/bcma.h>
static inline u32 bcma_cc_write32_masked(struct bcma_drv_cc *cc, u16 offset,
u32 mask, u32 value)
{
value &= mask;
value |= bcma_cc_read32(cc, offset) & ~mask;
bcma_cc_write32(cc, offset, value);
return value;
}
void bcma_core_chipcommon_init(struct bcma_drv_cc *cc)
{
u32 leddc_on = 10;
u32 leddc_off = 90;
if (cc->setup_done)
return;
if (cc->core->id.rev >= 11)
cc->status = bcma_cc_read32(cc, BCMA_CC_CHIPSTAT);
cc->capabilities = bcma_cc_read32(cc, BCMA_CC_CAP);
if (cc->core->id.rev >= 35)
cc->capabilities_ext = bcma_cc_read32(cc, BCMA_CC_CAP_EXT);
if (cc->core->id.rev >= 20) {
bcma_cc_write32(cc, BCMA_CC_GPIOPULLUP, 0);
bcma_cc_write32(cc, BCMA_CC_GPIOPULLDOWN, 0);
}
if (cc->capabilities & BCMA_CC_CAP_PMU)
bcma_pmu_init(cc);
if (cc->capabilities & BCMA_CC_CAP_PCTL)
pr_err("Power control not implemented!\n");
if (cc->core->id.rev >= 16) {
if (cc->core->bus->sprom.leddc_on_time &&
cc->core->bus->sprom.leddc_off_time) {
leddc_on = cc->core->bus->sprom.leddc_on_time;
leddc_off = cc->core->bus->sprom.leddc_off_time;
}
bcma_cc_write32(cc, BCMA_CC_GPIOTIMER,
((leddc_on << BCMA_CC_GPIOTIMER_ONTIME_SHIFT) |
(leddc_off << BCMA_CC_GPIOTIMER_OFFTIME_SHIFT)));
}
cc->setup_done = true;
}
/* Set chip watchdog reset timer to fire in 'ticks' backplane cycles */
void bcma_chipco_watchdog_timer_set(struct bcma_drv_cc *cc, u32 ticks)
{
/* instant NMI */
bcma_cc_write32(cc, BCMA_CC_WATCHDOG, ticks);
}
void bcma_chipco_irq_mask(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
bcma_cc_write32_masked(cc, BCMA_CC_IRQMASK, mask, value);
}
u32 bcma_chipco_irq_status(struct bcma_drv_cc *cc, u32 mask)
{
return bcma_cc_read32(cc, BCMA_CC_IRQSTAT) & mask;
}
u32 bcma_chipco_gpio_in(struct bcma_drv_cc *cc, u32 mask)
{
return bcma_cc_read32(cc, BCMA_CC_GPIOIN) & mask;
}
u32 bcma_chipco_gpio_out(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
return bcma_cc_write32_masked(cc, BCMA_CC_GPIOOUT, mask, value);
}
u32 bcma_chipco_gpio_outen(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
return bcma_cc_write32_masked(cc, BCMA_CC_GPIOOUTEN, mask, value);
}
u32 bcma_chipco_gpio_control(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
return bcma_cc_write32_masked(cc, BCMA_CC_GPIOCTL, mask, value);
}
EXPORT_SYMBOL_GPL(bcma_chipco_gpio_control);
u32 bcma_chipco_gpio_intmask(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
return bcma_cc_write32_masked(cc, BCMA_CC_GPIOIRQ, mask, value);
}
u32 bcma_chipco_gpio_polarity(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
return bcma_cc_write32_masked(cc, BCMA_CC_GPIOPOL, mask, value);
}
#ifdef CONFIG_BCMA_DRIVER_MIPS
void bcma_chipco_serial_init(struct bcma_drv_cc *cc)
{
unsigned int irq;
u32 baud_base;
u32 i;
unsigned int ccrev = cc->core->id.rev;
struct bcma_serial_port *ports = cc->serial_ports;
if (ccrev >= 11 && ccrev != 15) {
/* Fixed ALP clock */
baud_base = bcma_pmu_alp_clock(cc);
if (ccrev >= 21) {
/* Turn off UART clock before switching clocksource. */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
& ~BCMA_CC_CORECTL_UARTCLKEN);
}
/* Set the override bit so we don't divide it */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
| BCMA_CC_CORECTL_UARTCLK0);
if (ccrev >= 21) {
/* Re-enable the UART clock. */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
| BCMA_CC_CORECTL_UARTCLKEN);
}
} else {
pr_err("serial not supported on this device ccrev: 0x%x\n",
ccrev);
return;
}
irq = bcma_core_mips_irq(cc->core);
/* Determine the registers of the UARTs */
cc->nr_serial_ports = (cc->capabilities & BCMA_CC_CAP_NRUART);
for (i = 0; i < cc->nr_serial_ports; i++) {
ports[i].regs = cc->core->io_addr + BCMA_CC_UART0_DATA +
(i * 256);
ports[i].irq = irq;
ports[i].baud_base = baud_base;
ports[i].reg_shift = 0;
}
}
#endif /* CONFIG_BCMA_DRIVER_MIPS */
| gpl-2.0 |
TeamTwisted/kernel_lge_hammerhead | kernel/trace/trace_kdb.c | 8496 | 3087 | /*
* kdb helper for dumping the ftrace buffer
*
* Copyright (C) 2010 Jason Wessel <jason.wessel@windriver.com>
*
* ftrace_dump_buf based on ftrace_dump:
* Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
* Copyright (C) 2008 Ingo Molnar <mingo@redhat.com>
*
*/
#include <linux/init.h>
#include <linux/kgdb.h>
#include <linux/kdb.h>
#include <linux/ftrace.h>
#include "trace.h"
#include "trace_output.h"
static void ftrace_dump_buf(int skip_lines, long cpu_file)
{
/* use static because iter can be a bit big for the stack */
static struct trace_iterator iter;
unsigned int old_userobj;
int cnt = 0, cpu;
trace_init_global_iter(&iter);
for_each_tracing_cpu(cpu) {
atomic_inc(&iter.tr->data[cpu]->disabled);
}
old_userobj = trace_flags;
/* don't look at user memory in panic mode */
trace_flags &= ~TRACE_ITER_SYM_USEROBJ;
kdb_printf("Dumping ftrace buffer:\n");
/* reset all but tr, trace, and overruns */
memset(&iter.seq, 0,
sizeof(struct trace_iterator) -
offsetof(struct trace_iterator, seq));
iter.iter_flags |= TRACE_FILE_LAT_FMT;
iter.pos = -1;
if (cpu_file == TRACE_PIPE_ALL_CPU) {
for_each_tracing_cpu(cpu) {
iter.buffer_iter[cpu] =
ring_buffer_read_prepare(iter.tr->buffer, cpu);
ring_buffer_read_start(iter.buffer_iter[cpu]);
tracing_iter_reset(&iter, cpu);
}
} else {
iter.cpu_file = cpu_file;
iter.buffer_iter[cpu_file] =
ring_buffer_read_prepare(iter.tr->buffer, cpu_file);
ring_buffer_read_start(iter.buffer_iter[cpu_file]);
tracing_iter_reset(&iter, cpu_file);
}
if (!trace_empty(&iter))
trace_find_next_entry_inc(&iter);
while (!trace_empty(&iter)) {
if (!cnt)
kdb_printf("---------------------------------\n");
cnt++;
if (trace_find_next_entry_inc(&iter) != NULL && !skip_lines)
print_trace_line(&iter);
if (!skip_lines)
trace_printk_seq(&iter.seq);
else
skip_lines--;
if (KDB_FLAG(CMD_INTERRUPT))
goto out;
}
if (!cnt)
kdb_printf(" (ftrace buffer empty)\n");
else
kdb_printf("---------------------------------\n");
out:
trace_flags = old_userobj;
for_each_tracing_cpu(cpu) {
atomic_dec(&iter.tr->data[cpu]->disabled);
}
for_each_tracing_cpu(cpu)
if (iter.buffer_iter[cpu])
ring_buffer_read_finish(iter.buffer_iter[cpu]);
}
/*
* kdb_ftdump - Dump the ftrace log buffer
*/
static int kdb_ftdump(int argc, const char **argv)
{
int skip_lines = 0;
long cpu_file;
char *cp;
if (argc > 2)
return KDB_ARGCOUNT;
if (argc) {
skip_lines = simple_strtol(argv[1], &cp, 0);
if (*cp)
skip_lines = 0;
}
if (argc == 2) {
cpu_file = simple_strtol(argv[2], &cp, 0);
if (*cp || cpu_file >= NR_CPUS || cpu_file < 0 ||
!cpu_online(cpu_file))
return KDB_BADINT;
} else {
cpu_file = TRACE_PIPE_ALL_CPU;
}
kdb_trap_printk++;
ftrace_dump_buf(skip_lines, cpu_file);
kdb_trap_printk--;
return 0;
}
static __init int kdb_ftrace_register(void)
{
kdb_register_repeat("ftdump", kdb_ftdump, "[skip_#lines] [cpu]",
"Dump ftrace log", 0, KDB_REPEAT_NONE);
return 0;
}
late_initcall(kdb_ftrace_register);
| gpl-2.0 |
Arakmar/android_kernel_sony_msm8660 | drivers/staging/rtl8192u/ieee80211/michael_mic.c | 12080 | 3669 | /*
* Cryptographic API
*
* Michael MIC (IEEE 802.11i/TKIP) keyed digest
*
* Copyright (c) 2004 Jouni Malinen <jkmaline@cc.hut.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
//#include <linux/crypto.h>
#include "rtl_crypto.h"
struct michael_mic_ctx {
u8 pending[4];
size_t pending_len;
u32 l, r;
};
static inline u32 rotl(u32 val, int bits)
{
return (val << bits) | (val >> (32 - bits));
}
static inline u32 rotr(u32 val, int bits)
{
return (val >> bits) | (val << (32 - bits));
}
static inline u32 xswap(u32 val)
{
return ((val & 0x00ff00ff) << 8) | ((val & 0xff00ff00) >> 8);
}
#define michael_block(l, r) \
do { \
r ^= rotl(l, 17); \
l += r; \
r ^= xswap(l); \
l += r; \
r ^= rotl(l, 3); \
l += r; \
r ^= rotr(l, 2); \
l += r; \
} while (0)
static inline u32 get_le32(const u8 *p)
{
return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
}
static inline void put_le32(u8 *p, u32 v)
{
p[0] = v;
p[1] = v >> 8;
p[2] = v >> 16;
p[3] = v >> 24;
}
static void michael_init(void *ctx)
{
struct michael_mic_ctx *mctx = ctx;
mctx->pending_len = 0;
}
static void michael_update(void *ctx, const u8 *data, unsigned int len)
{
struct michael_mic_ctx *mctx = ctx;
if (mctx->pending_len) {
int flen = 4 - mctx->pending_len;
if (flen > len)
flen = len;
memcpy(&mctx->pending[mctx->pending_len], data, flen);
mctx->pending_len += flen;
data += flen;
len -= flen;
if (mctx->pending_len < 4)
return;
mctx->l ^= get_le32(mctx->pending);
michael_block(mctx->l, mctx->r);
mctx->pending_len = 0;
}
while (len >= 4) {
mctx->l ^= get_le32(data);
michael_block(mctx->l, mctx->r);
data += 4;
len -= 4;
}
if (len > 0) {
mctx->pending_len = len;
memcpy(mctx->pending, data, len);
}
}
static void michael_final(void *ctx, u8 *out)
{
struct michael_mic_ctx *mctx = ctx;
u8 *data = mctx->pending;
/* Last block and padding (0x5a, 4..7 x 0) */
switch (mctx->pending_len) {
case 0:
mctx->l ^= 0x5a;
break;
case 1:
mctx->l ^= data[0] | 0x5a00;
break;
case 2:
mctx->l ^= data[0] | (data[1] << 8) | 0x5a0000;
break;
case 3:
mctx->l ^= data[0] | (data[1] << 8) | (data[2] << 16) |
0x5a000000;
break;
}
michael_block(mctx->l, mctx->r);
/* l ^= 0; */
michael_block(mctx->l, mctx->r);
put_le32(out, mctx->l);
put_le32(out + 4, mctx->r);
}
static int michael_setkey(void *ctx, const u8 *key, unsigned int keylen,
u32 *flags)
{
struct michael_mic_ctx *mctx = ctx;
if (keylen != 8) {
if (flags)
*flags = CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
mctx->l = get_le32(key);
mctx->r = get_le32(key + 4);
return 0;
}
static struct crypto_alg michael_mic_alg = {
.cra_name = "michael_mic",
.cra_flags = CRYPTO_ALG_TYPE_DIGEST,
.cra_blocksize = 8,
.cra_ctxsize = sizeof(struct michael_mic_ctx),
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(michael_mic_alg.cra_list),
.cra_u = { .digest = {
.dia_digestsize = 8,
.dia_init = michael_init,
.dia_update = michael_update,
.dia_final = michael_final,
.dia_setkey = michael_setkey } }
};
static int __init michael_mic_init(void)
{
return crypto_register_alg(&michael_mic_alg);
}
static void __exit michael_mic_exit(void)
{
crypto_unregister_alg(&michael_mic_alg);
}
module_init(michael_mic_init);
module_exit(michael_mic_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Michael MIC");
MODULE_AUTHOR("Jouni Malinen <jkmaline@cc.hut.fi>");
| gpl-2.0 |
matthiasdiener/kmaf | arch/mips/vr41xx/common/init.c | 13360 | 2019 | /*
* init.c, Common initialization routines for NEC VR4100 series.
*
* Copyright (C) 2003-2009 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/string.h>
#include <asm/bootinfo.h>
#include <asm/time.h>
#include <asm/vr41xx/irq.h>
#include <asm/vr41xx/vr41xx.h>
#define IO_MEM_RESOURCE_START 0UL
#define IO_MEM_RESOURCE_END 0x1fffffffUL
static void __init iomem_resource_init(void)
{
iomem_resource.start = IO_MEM_RESOURCE_START;
iomem_resource.end = IO_MEM_RESOURCE_END;
}
void __init plat_time_init(void)
{
unsigned long tclock;
vr41xx_calculate_clock_frequency();
tclock = vr41xx_get_tclock_frequency();
if (current_cpu_data.processor_id == PRID_VR4131_REV2_0 ||
current_cpu_data.processor_id == PRID_VR4131_REV2_1)
mips_hpt_frequency = tclock / 2;
else
mips_hpt_frequency = tclock / 4;
}
void __init plat_mem_setup(void)
{
iomem_resource_init();
vr41xx_siu_setup();
}
void __init prom_init(void)
{
int argc, i;
char **argv;
argc = fw_arg0;
argv = (char **)fw_arg1;
for (i = 1; i < argc; i++) {
strlcat(arcs_cmdline, argv[i], COMMAND_LINE_SIZE);
if (i < (argc - 1))
strlcat(arcs_cmdline, " ", COMMAND_LINE_SIZE);
}
}
void __init prom_free_prom_memory(void)
{
}
| gpl-2.0 |
jorapi/android_kernel_lge_g3 | arch/mips/vr41xx/common/init.c | 13360 | 2019 | /*
* init.c, Common initialization routines for NEC VR4100 series.
*
* Copyright (C) 2003-2009 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/string.h>
#include <asm/bootinfo.h>
#include <asm/time.h>
#include <asm/vr41xx/irq.h>
#include <asm/vr41xx/vr41xx.h>
#define IO_MEM_RESOURCE_START 0UL
#define IO_MEM_RESOURCE_END 0x1fffffffUL
static void __init iomem_resource_init(void)
{
iomem_resource.start = IO_MEM_RESOURCE_START;
iomem_resource.end = IO_MEM_RESOURCE_END;
}
void __init plat_time_init(void)
{
unsigned long tclock;
vr41xx_calculate_clock_frequency();
tclock = vr41xx_get_tclock_frequency();
if (current_cpu_data.processor_id == PRID_VR4131_REV2_0 ||
current_cpu_data.processor_id == PRID_VR4131_REV2_1)
mips_hpt_frequency = tclock / 2;
else
mips_hpt_frequency = tclock / 4;
}
void __init plat_mem_setup(void)
{
iomem_resource_init();
vr41xx_siu_setup();
}
void __init prom_init(void)
{
int argc, i;
char **argv;
argc = fw_arg0;
argv = (char **)fw_arg1;
for (i = 1; i < argc; i++) {
strlcat(arcs_cmdline, argv[i], COMMAND_LINE_SIZE);
if (i < (argc - 1))
strlcat(arcs_cmdline, " ", COMMAND_LINE_SIZE);
}
}
void __init prom_free_prom_memory(void)
{
}
| gpl-2.0 |
buglabs/bug20-2.6.31-omap | drivers/media/common/tuners/tda18271-common.c | 49 | 17561 | /*
tda18271-common.c - driver for the Philips / NXP TDA18271 silicon tuner
Copyright (C) 2007, 2008 Michael Krufky <mkrufky@linuxtv.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "tda18271-priv.h"
static int tda18271_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct tda18271_priv *priv = fe->tuner_priv;
enum tda18271_i2c_gate gate;
int ret = 0;
switch (priv->gate) {
case TDA18271_GATE_DIGITAL:
case TDA18271_GATE_ANALOG:
gate = priv->gate;
break;
case TDA18271_GATE_AUTO:
default:
switch (priv->mode) {
case TDA18271_DIGITAL:
gate = TDA18271_GATE_DIGITAL;
break;
case TDA18271_ANALOG:
default:
gate = TDA18271_GATE_ANALOG;
break;
}
}
switch (gate) {
case TDA18271_GATE_ANALOG:
if (fe->ops.analog_ops.i2c_gate_ctrl)
ret = fe->ops.analog_ops.i2c_gate_ctrl(fe, enable);
break;
case TDA18271_GATE_DIGITAL:
if (fe->ops.i2c_gate_ctrl)
ret = fe->ops.i2c_gate_ctrl(fe, enable);
break;
default:
ret = -EINVAL;
break;
}
return ret;
};
/*---------------------------------------------------------------------*/
static void tda18271_dump_regs(struct dvb_frontend *fe, int extended)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
tda_reg("=== TDA18271 REG DUMP ===\n");
tda_reg("ID_BYTE = 0x%02x\n", 0xff & regs[R_ID]);
tda_reg("THERMO_BYTE = 0x%02x\n", 0xff & regs[R_TM]);
tda_reg("POWER_LEVEL_BYTE = 0x%02x\n", 0xff & regs[R_PL]);
tda_reg("EASY_PROG_BYTE_1 = 0x%02x\n", 0xff & regs[R_EP1]);
tda_reg("EASY_PROG_BYTE_2 = 0x%02x\n", 0xff & regs[R_EP2]);
tda_reg("EASY_PROG_BYTE_3 = 0x%02x\n", 0xff & regs[R_EP3]);
tda_reg("EASY_PROG_BYTE_4 = 0x%02x\n", 0xff & regs[R_EP4]);
tda_reg("EASY_PROG_BYTE_5 = 0x%02x\n", 0xff & regs[R_EP5]);
tda_reg("CAL_POST_DIV_BYTE = 0x%02x\n", 0xff & regs[R_CPD]);
tda_reg("CAL_DIV_BYTE_1 = 0x%02x\n", 0xff & regs[R_CD1]);
tda_reg("CAL_DIV_BYTE_2 = 0x%02x\n", 0xff & regs[R_CD2]);
tda_reg("CAL_DIV_BYTE_3 = 0x%02x\n", 0xff & regs[R_CD3]);
tda_reg("MAIN_POST_DIV_BYTE = 0x%02x\n", 0xff & regs[R_MPD]);
tda_reg("MAIN_DIV_BYTE_1 = 0x%02x\n", 0xff & regs[R_MD1]);
tda_reg("MAIN_DIV_BYTE_2 = 0x%02x\n", 0xff & regs[R_MD2]);
tda_reg("MAIN_DIV_BYTE_3 = 0x%02x\n", 0xff & regs[R_MD3]);
/* only dump extended regs if DBG_ADV is set */
if (!(tda18271_debug & DBG_ADV))
return;
/* W indicates write-only registers.
* Register dump for write-only registers shows last value written. */
tda_reg("EXTENDED_BYTE_1 = 0x%02x\n", 0xff & regs[R_EB1]);
tda_reg("EXTENDED_BYTE_2 = 0x%02x\n", 0xff & regs[R_EB2]);
tda_reg("EXTENDED_BYTE_3 = 0x%02x\n", 0xff & regs[R_EB3]);
tda_reg("EXTENDED_BYTE_4 = 0x%02x\n", 0xff & regs[R_EB4]);
tda_reg("EXTENDED_BYTE_5 = 0x%02x\n", 0xff & regs[R_EB5]);
tda_reg("EXTENDED_BYTE_6 = 0x%02x\n", 0xff & regs[R_EB6]);
tda_reg("EXTENDED_BYTE_7 = 0x%02x\n", 0xff & regs[R_EB7]);
tda_reg("EXTENDED_BYTE_8 = 0x%02x\n", 0xff & regs[R_EB8]);
tda_reg("EXTENDED_BYTE_9 W = 0x%02x\n", 0xff & regs[R_EB9]);
tda_reg("EXTENDED_BYTE_10 = 0x%02x\n", 0xff & regs[R_EB10]);
tda_reg("EXTENDED_BYTE_11 = 0x%02x\n", 0xff & regs[R_EB11]);
tda_reg("EXTENDED_BYTE_12 = 0x%02x\n", 0xff & regs[R_EB12]);
tda_reg("EXTENDED_BYTE_13 = 0x%02x\n", 0xff & regs[R_EB13]);
tda_reg("EXTENDED_BYTE_14 = 0x%02x\n", 0xff & regs[R_EB14]);
tda_reg("EXTENDED_BYTE_15 = 0x%02x\n", 0xff & regs[R_EB15]);
tda_reg("EXTENDED_BYTE_16 W = 0x%02x\n", 0xff & regs[R_EB16]);
tda_reg("EXTENDED_BYTE_17 W = 0x%02x\n", 0xff & regs[R_EB17]);
tda_reg("EXTENDED_BYTE_18 = 0x%02x\n", 0xff & regs[R_EB18]);
tda_reg("EXTENDED_BYTE_19 W = 0x%02x\n", 0xff & regs[R_EB19]);
tda_reg("EXTENDED_BYTE_20 W = 0x%02x\n", 0xff & regs[R_EB20]);
tda_reg("EXTENDED_BYTE_21 = 0x%02x\n", 0xff & regs[R_EB21]);
tda_reg("EXTENDED_BYTE_22 = 0x%02x\n", 0xff & regs[R_EB22]);
tda_reg("EXTENDED_BYTE_23 = 0x%02x\n", 0xff & regs[R_EB23]);
}
int tda18271_read_regs(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char buf = 0x00;
int ret;
struct i2c_msg msg[] = {
{ .addr = priv->i2c_props.addr, .flags = 0,
.buf = &buf, .len = 1 },
{ .addr = priv->i2c_props.addr, .flags = I2C_M_RD,
.buf = regs, .len = 16 }
};
tda18271_i2c_gate_ctrl(fe, 1);
/* read all registers */
ret = i2c_transfer(priv->i2c_props.adap, msg, 2);
tda18271_i2c_gate_ctrl(fe, 0);
if (ret != 2)
tda_err("ERROR: i2c_transfer returned: %d\n", ret);
if (tda18271_debug & DBG_REG)
tda18271_dump_regs(fe, 0);
return (ret == 2 ? 0 : ret);
}
int tda18271_read_extended(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char regdump[TDA18271_NUM_REGS];
unsigned char buf = 0x00;
int ret, i;
struct i2c_msg msg[] = {
{ .addr = priv->i2c_props.addr, .flags = 0,
.buf = &buf, .len = 1 },
{ .addr = priv->i2c_props.addr, .flags = I2C_M_RD,
.buf = regdump, .len = TDA18271_NUM_REGS }
};
tda18271_i2c_gate_ctrl(fe, 1);
/* read all registers */
ret = i2c_transfer(priv->i2c_props.adap, msg, 2);
tda18271_i2c_gate_ctrl(fe, 0);
if (ret != 2)
tda_err("ERROR: i2c_transfer returned: %d\n", ret);
for (i = 0; i < TDA18271_NUM_REGS; i++) {
/* don't update write-only registers */
if ((i != R_EB9) &&
(i != R_EB16) &&
(i != R_EB17) &&
(i != R_EB19) &&
(i != R_EB20))
regs[i] = regdump[i];
}
if (tda18271_debug & DBG_REG)
tda18271_dump_regs(fe, 1);
return (ret == 2 ? 0 : ret);
}
int tda18271_write_regs(struct dvb_frontend *fe, int idx, int len)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char buf[TDA18271_NUM_REGS + 1];
struct i2c_msg msg = { .addr = priv->i2c_props.addr, .flags = 0,
.buf = buf, .len = len + 1 };
int i, ret;
BUG_ON((len == 0) || (idx + len > sizeof(buf)));
buf[0] = idx;
for (i = 1; i <= len; i++)
buf[i] = regs[idx - 1 + i];
tda18271_i2c_gate_ctrl(fe, 1);
/* write registers */
ret = i2c_transfer(priv->i2c_props.adap, &msg, 1);
tda18271_i2c_gate_ctrl(fe, 0);
if (ret != 1)
tda_err("ERROR: i2c_transfer returned: %d\n", ret);
return (ret == 1 ? 0 : ret);
}
/*---------------------------------------------------------------------*/
int tda18271_charge_pump_source(struct dvb_frontend *fe,
enum tda18271_pll pll, int force)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
int r_cp = (pll == TDA18271_CAL_PLL) ? R_EB7 : R_EB4;
regs[r_cp] &= ~0x20;
regs[r_cp] |= ((force & 1) << 5);
return tda18271_write_regs(fe, r_cp, 1);
}
int tda18271_init_regs(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
tda_dbg("initializing registers for device @ %d-%04x\n",
i2c_adapter_id(priv->i2c_props.adap),
priv->i2c_props.addr);
/* initialize registers */
switch (priv->id) {
case TDA18271HDC1:
regs[R_ID] = 0x83;
break;
case TDA18271HDC2:
regs[R_ID] = 0x84;
break;
};
regs[R_TM] = 0x08;
regs[R_PL] = 0x80;
regs[R_EP1] = 0xc6;
regs[R_EP2] = 0xdf;
regs[R_EP3] = 0x16;
regs[R_EP4] = 0x60;
regs[R_EP5] = 0x80;
regs[R_CPD] = 0x80;
regs[R_CD1] = 0x00;
regs[R_CD2] = 0x00;
regs[R_CD3] = 0x00;
regs[R_MPD] = 0x00;
regs[R_MD1] = 0x00;
regs[R_MD2] = 0x00;
regs[R_MD3] = 0x00;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB1] = 0xff;
break;
case TDA18271HDC2:
regs[R_EB1] = 0xfc;
break;
};
regs[R_EB2] = 0x01;
regs[R_EB3] = 0x84;
regs[R_EB4] = 0x41;
regs[R_EB5] = 0x01;
regs[R_EB6] = 0x84;
regs[R_EB7] = 0x40;
regs[R_EB8] = 0x07;
regs[R_EB9] = 0x00;
regs[R_EB10] = 0x00;
regs[R_EB11] = 0x96;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB12] = 0x0f;
break;
case TDA18271HDC2:
regs[R_EB12] = 0x33;
break;
};
regs[R_EB13] = 0xc1;
regs[R_EB14] = 0x00;
regs[R_EB15] = 0x8f;
regs[R_EB16] = 0x00;
regs[R_EB17] = 0x00;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB18] = 0x00;
break;
case TDA18271HDC2:
regs[R_EB18] = 0x8c;
break;
};
regs[R_EB19] = 0x00;
regs[R_EB20] = 0x20;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB21] = 0x33;
break;
case TDA18271HDC2:
regs[R_EB21] = 0xb3;
break;
};
regs[R_EB22] = 0x48;
regs[R_EB23] = 0xb0;
if (priv->small_i2c) {
tda18271_write_regs(fe, 0x00, 0x10);
tda18271_write_regs(fe, 0x10, 0x10);
tda18271_write_regs(fe, 0x20, 0x07);
} else
tda18271_write_regs(fe, 0x00, TDA18271_NUM_REGS);
/* setup agc1 gain */
regs[R_EB17] = 0x00;
tda18271_write_regs(fe, R_EB17, 1);
regs[R_EB17] = 0x03;
tda18271_write_regs(fe, R_EB17, 1);
regs[R_EB17] = 0x43;
tda18271_write_regs(fe, R_EB17, 1);
regs[R_EB17] = 0x4c;
tda18271_write_regs(fe, R_EB17, 1);
/* setup agc2 gain */
if ((priv->id) == TDA18271HDC1) {
regs[R_EB20] = 0xa0;
tda18271_write_regs(fe, R_EB20, 1);
regs[R_EB20] = 0xa7;
tda18271_write_regs(fe, R_EB20, 1);
regs[R_EB20] = 0xe7;
tda18271_write_regs(fe, R_EB20, 1);
regs[R_EB20] = 0xec;
tda18271_write_regs(fe, R_EB20, 1);
}
/* image rejection calibration */
/* low-band */
regs[R_EP3] = 0x1f;
regs[R_EP4] = 0x66;
regs[R_EP5] = 0x81;
regs[R_CPD] = 0xcc;
regs[R_CD1] = 0x6c;
regs[R_CD2] = 0x00;
regs[R_CD3] = 0x00;
regs[R_MPD] = 0xcd;
regs[R_MD1] = 0x77;
regs[R_MD2] = 0x08;
regs[R_MD3] = 0x00;
tda18271_write_regs(fe, R_EP3, 11);
if ((priv->id) == TDA18271HDC2) {
/* main pll cp source on */
tda18271_charge_pump_source(fe, TDA18271_MAIN_PLL, 1);
msleep(1);
/* main pll cp source off */
tda18271_charge_pump_source(fe, TDA18271_MAIN_PLL, 0);
}
msleep(5); /* pll locking */
/* launch detector */
tda18271_write_regs(fe, R_EP1, 1);
msleep(5); /* wanted low measurement */
regs[R_EP5] = 0x85;
regs[R_CPD] = 0xcb;
regs[R_CD1] = 0x66;
regs[R_CD2] = 0x70;
tda18271_write_regs(fe, R_EP3, 7);
msleep(5); /* pll locking */
/* launch optimization algorithm */
tda18271_write_regs(fe, R_EP2, 1);
msleep(30); /* image low optimization completion */
/* mid-band */
regs[R_EP5] = 0x82;
regs[R_CPD] = 0xa8;
regs[R_CD2] = 0x00;
regs[R_MPD] = 0xa9;
regs[R_MD1] = 0x73;
regs[R_MD2] = 0x1a;
tda18271_write_regs(fe, R_EP3, 11);
msleep(5); /* pll locking */
/* launch detector */
tda18271_write_regs(fe, R_EP1, 1);
msleep(5); /* wanted mid measurement */
regs[R_EP5] = 0x86;
regs[R_CPD] = 0xa8;
regs[R_CD1] = 0x66;
regs[R_CD2] = 0xa0;
tda18271_write_regs(fe, R_EP3, 7);
msleep(5); /* pll locking */
/* launch optimization algorithm */
tda18271_write_regs(fe, R_EP2, 1);
msleep(30); /* image mid optimization completion */
/* high-band */
regs[R_EP5] = 0x83;
regs[R_CPD] = 0x98;
regs[R_CD1] = 0x65;
regs[R_CD2] = 0x00;
regs[R_MPD] = 0x99;
regs[R_MD1] = 0x71;
regs[R_MD2] = 0xcd;
tda18271_write_regs(fe, R_EP3, 11);
msleep(5); /* pll locking */
/* launch detector */
tda18271_write_regs(fe, R_EP1, 1);
msleep(5); /* wanted high measurement */
regs[R_EP5] = 0x87;
regs[R_CD1] = 0x65;
regs[R_CD2] = 0x50;
tda18271_write_regs(fe, R_EP3, 7);
msleep(5); /* pll locking */
/* launch optimization algorithm */
tda18271_write_regs(fe, R_EP2, 1);
msleep(30); /* image high optimization completion */
/* return to normal mode */
regs[R_EP4] = 0x64;
tda18271_write_regs(fe, R_EP4, 1);
/* synchronize */
tda18271_write_regs(fe, R_EP1, 1);
return 0;
}
/*---------------------------------------------------------------------*/
/*
* Standby modes, EP3 [7:5]
*
* | SM || SM_LT || SM_XT || mode description
* |=====\\=======\\=======\\===================================
* | 0 || 0 || 0 || normal mode
* |-----||-------||-------||-----------------------------------
* | || || || standby mode w/ slave tuner output
* | 1 || 0 || 0 || & loop thru & xtal oscillator on
* |-----||-------||-------||-----------------------------------
* | 1 || 1 || 0 || standby mode w/ xtal oscillator on
* |-----||-------||-------||-----------------------------------
* | 1 || 1 || 1 || power off
*
*/
int tda18271_set_standby_mode(struct dvb_frontend *fe,
int sm, int sm_lt, int sm_xt)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
if (tda18271_debug & DBG_ADV)
tda_dbg("sm = %d, sm_lt = %d, sm_xt = %d\n", sm, sm_lt, sm_xt);
regs[R_EP3] &= ~0xe0; /* clear sm, sm_lt, sm_xt */
regs[R_EP3] |= (sm ? (1 << 7) : 0) |
(sm_lt ? (1 << 6) : 0) |
(sm_xt ? (1 << 5) : 0);
return tda18271_write_regs(fe, R_EP3, 1);
}
/*---------------------------------------------------------------------*/
int tda18271_calc_main_pll(struct dvb_frontend *fe, u32 freq)
{
/* sets main post divider & divider bytes, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 d, pd;
u32 div;
int ret = tda18271_lookup_pll_map(fe, MAIN_PLL, &freq, &pd, &d);
if (tda_fail(ret))
goto fail;
regs[R_MPD] = (0x77 & pd);
switch (priv->mode) {
case TDA18271_ANALOG:
regs[R_MPD] &= ~0x08;
break;
case TDA18271_DIGITAL:
regs[R_MPD] |= 0x08;
break;
}
div = ((d * (freq / 1000)) << 7) / 125;
regs[R_MD1] = 0x7f & (div >> 16);
regs[R_MD2] = 0xff & (div >> 8);
regs[R_MD3] = 0xff & div;
fail:
return ret;
}
int tda18271_calc_cal_pll(struct dvb_frontend *fe, u32 freq)
{
/* sets cal post divider & divider bytes, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 d, pd;
u32 div;
int ret = tda18271_lookup_pll_map(fe, CAL_PLL, &freq, &pd, &d);
if (tda_fail(ret))
goto fail;
regs[R_CPD] = pd;
div = ((d * (freq / 1000)) << 7) / 125;
regs[R_CD1] = 0x7f & (div >> 16);
regs[R_CD2] = 0xff & (div >> 8);
regs[R_CD3] = 0xff & div;
fail:
return ret;
}
/*---------------------------------------------------------------------*/
int tda18271_calc_bp_filter(struct dvb_frontend *fe, u32 *freq)
{
/* sets bp filter bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, BP_FILTER, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP1] &= ~0x07; /* clear bp filter bits */
regs[R_EP1] |= (0x07 & val);
fail:
return ret;
}
int tda18271_calc_km(struct dvb_frontend *fe, u32 *freq)
{
/* sets K & M bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_CAL_KMCO, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EB13] &= ~0x7c; /* clear k & m bits */
regs[R_EB13] |= (0x7c & val);
fail:
return ret;
}
int tda18271_calc_rf_band(struct dvb_frontend *fe, u32 *freq)
{
/* sets rf band bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_BAND, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP2] &= ~0xe0; /* clear rf band bits */
regs[R_EP2] |= (0xe0 & (val << 5));
fail:
return ret;
}
int tda18271_calc_gain_taper(struct dvb_frontend *fe, u32 *freq)
{
/* sets gain taper bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, GAIN_TAPER, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP2] &= ~0x1f; /* clear gain taper bits */
regs[R_EP2] |= (0x1f & val);
fail:
return ret;
}
int tda18271_calc_ir_measure(struct dvb_frontend *fe, u32 *freq)
{
/* sets IR Meas bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, IR_MEASURE, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP5] &= ~0x07;
regs[R_EP5] |= (0x07 & val);
fail:
return ret;
}
int tda18271_calc_rf_cal(struct dvb_frontend *fe, u32 *freq)
{
/* sets rf cal byte (RFC_Cprog), but does not write it */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_CAL, freq, &val);
/* The TDA18271HD/C1 rf_cal map lookup is expected to go out of range
* for frequencies above 61.1 MHz. In these cases, the internal RF
* tracking filters calibration mechanism is used.
*
* There is no need to warn the user about this.
*/
if (ret < 0)
goto fail;
regs[R_EB14] = val;
fail:
return ret;
}
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* ---------------------------------------------------------------------------
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
promovicz/linux-2.6.33-lpc313x | drivers/staging/batman-adv/bitarray.c | 49 | 4898 | /*
* Copyright (C) 2006-2009 B.A.T.M.A.N. contributors:
*
* Simon Wunderlich, Marek Lindner
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*
*/
#include "main.h"
#include "bitarray.h"
#include "log.h"
/* returns true if the corresponding bit in the given seq_bits indicates true
* and curr_seqno is within range of last_seqno */
uint8_t get_bit_status(TYPE_OF_WORD *seq_bits, uint16_t last_seqno,
uint16_t curr_seqno)
{
int16_t diff, word_offset, word_num;
diff = last_seqno - curr_seqno;
if (diff < 0 || diff >= TQ_LOCAL_WINDOW_SIZE) {
return 0;
} else {
/* which word */
word_num = (last_seqno - curr_seqno) / WORD_BIT_SIZE;
/* which position in the selected word */
word_offset = (last_seqno - curr_seqno) % WORD_BIT_SIZE;
if (seq_bits[word_num] & 1 << word_offset)
return 1;
else
return 0;
}
}
/* turn corresponding bit on, so we can remember that we got the packet */
void bit_mark(TYPE_OF_WORD *seq_bits, int32_t n)
{
int32_t word_offset, word_num;
/* if too old, just drop it */
if (n < 0 || n >= TQ_LOCAL_WINDOW_SIZE)
return;
/* which word */
word_num = n / WORD_BIT_SIZE;
/* which position in the selected word */
word_offset = n % WORD_BIT_SIZE;
seq_bits[word_num] |= 1 << word_offset; /* turn the position on */
}
/* shift the packet array by n places. */
void bit_shift(TYPE_OF_WORD *seq_bits, int32_t n)
{
int32_t word_offset, word_num;
int32_t i;
if (n <= 0)
return;
word_offset = n % WORD_BIT_SIZE;/* shift how much inside each word */
word_num = n / WORD_BIT_SIZE; /* shift over how much (full) words */
for (i = NUM_WORDS - 1; i > word_num; i--) {
/* going from old to new, so we don't overwrite the data we copy
* from.
*
* left is high, right is low: FEDC BA98 7654 3210
* ^^ ^^
* vvvv
* ^^^^ = from, vvvvv =to, we'd have word_num==1 and
* word_offset==WORD_BIT_SIZE/2 ????? in this example.
* (=24 bits)
*
* our desired output would be: 9876 5432 1000 0000
* */
seq_bits[i] =
(seq_bits[i - word_num] << word_offset) +
/* take the lower port from the left half, shift it left
* to its final position */
(seq_bits[i - word_num - 1] >>
(WORD_BIT_SIZE-word_offset));
/* and the upper part of the right half and shift it left to
* it's position */
/* for our example that would be: word[0] = 9800 + 0076 =
* 9876 */
}
/* now for our last word, i==word_num, we only have the it's "left"
* half. that's the 1000 word in our example.*/
seq_bits[i] = (seq_bits[i - word_num] << word_offset);
/* pad the rest with 0, if there is anything */
i--;
for (; i >= 0; i--)
seq_bits[i] = 0;
}
/* receive and process one packet, returns 1 if received seq_num is considered
* new, 0 if old */
char bit_get_packet(TYPE_OF_WORD *seq_bits, int16_t seq_num_diff,
int8_t set_mark)
{
int i;
/* we already got a sequence number higher than this one, so we just
* mark it. this should wrap around the integer just fine */
if ((seq_num_diff < 0) && (seq_num_diff >= -TQ_LOCAL_WINDOW_SIZE)) {
if (set_mark)
bit_mark(seq_bits, -seq_num_diff);
return 0;
}
/* it seems we missed a lot of packets or the other host restarted */
if ((seq_num_diff > TQ_LOCAL_WINDOW_SIZE) ||
(seq_num_diff < -TQ_LOCAL_WINDOW_SIZE)) {
if (seq_num_diff > TQ_LOCAL_WINDOW_SIZE)
debug_log(LOG_TYPE_BATMAN,
"We missed a lot of packets (%i) !\n",
seq_num_diff-1);
if (-seq_num_diff > TQ_LOCAL_WINDOW_SIZE)
debug_log(LOG_TYPE_BATMAN,
"Other host probably restarted !\n");
for (i = 0; i < NUM_WORDS; i++)
seq_bits[i] = 0;
if (set_mark)
seq_bits[0] = 1; /* we only have the latest packet */
} else {
bit_shift(seq_bits, seq_num_diff);
if (set_mark)
bit_mark(seq_bits, 0);
}
return 1;
}
/* count the hamming weight, how many good packets did we receive? just count
* the 1's. The inner loop uses the Kernighan algorithm, see
* http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
*/
int bit_packet_count(TYPE_OF_WORD *seq_bits)
{
int i, hamming = 0;
TYPE_OF_WORD word;
for (i = 0; i < NUM_WORDS; i++) {
word = seq_bits[i];
while (word) {
word &= word-1;
hamming++;
}
}
return hamming;
}
| gpl-2.0 |
pigworlds/asuswrttest | release/src/router/openssl/crypto/camellia/cmll_misc.c | 49 | 3300 | /* crypto/camellia/camellia_misc.c -*- mode:C; c-file-style: "eay" -*- */
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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 <openssl/opensslv.h>
#include <openssl/camellia.h>
#include "cmll_locl.h"
const char CAMELLIA_version[]="CAMELLIA" OPENSSL_VERSION_PTEXT;
int Camellia_set_key(const unsigned char *userKey, const int bits,
CAMELLIA_KEY *key)
{
if(!userKey || !key)
return -1;
if(bits != 128 && bits != 192 && bits != 256)
return -2;
key->grand_rounds = Camellia_Ekeygen(bits , userKey, key->u.rd_key);
return 0;
}
void Camellia_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key)
{
Camellia_EncryptBlock_Rounds(key->grand_rounds, in , key->u.rd_key , out);
}
void Camellia_decrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key)
{
Camellia_DecryptBlock_Rounds(key->grand_rounds, in , key->u.rd_key , out);
}
| gpl-2.0 |
blueskycoco/d2 | drivers/staging/comedi/drivers/vmk80xx.c | 49 | 31845 | /*
comedi/drivers/vmk80xx.c
Velleman USB Board Low-Level Driver
Copyright (C) 2009 Manuel Gebele <forensixs@gmx.de>, Germany
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.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.
*/
/*
Driver: vmk80xx
Description: Velleman USB Board Low-Level Driver
Devices: K8055/K8061 aka VM110/VM140
Author: Manuel Gebele <forensixs@gmx.de>
Updated: Sun, 10 May 2009 11:14:59 +0200
Status: works
Supports:
- analog input
- analog output
- digital input
- digital output
- counter
- pwm
*/
/*
Changelog:
0.8.81 -3- code completely rewritten (adjust driver logic)
0.8.81 -2- full support for K8061
0.8.81 -1- fix some mistaken among others the number of
supported boards and I/O handling
0.7.76 -4- renamed to vmk80xx
0.7.76 -3- detect K8061 (only theoretically supported)
0.7.76 -2- code completely rewritten (adjust driver logic)
0.7.76 -1- support for digital and counter subdevice
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/errno.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/usb.h>
#include <linux/uaccess.h>
#include "../comedidev.h"
MODULE_AUTHOR("Manuel Gebele <forensixs@gmx.de>");
MODULE_DESCRIPTION("Velleman USB Board Low-Level Driver");
MODULE_SUPPORTED_DEVICE("K8055/K8061 aka VM110/VM140");
MODULE_VERSION("0.8.01");
MODULE_LICENSE("GPL");
enum {
DEVICE_VMK8055,
DEVICE_VMK8061
};
static struct usb_device_id vmk80xx_id_table[] = {
{USB_DEVICE(0x10cf, 0x5500), .driver_info = DEVICE_VMK8055},
{USB_DEVICE(0x10cf, 0x5501), .driver_info = DEVICE_VMK8055},
{USB_DEVICE(0x10cf, 0x5502), .driver_info = DEVICE_VMK8055},
{USB_DEVICE(0x10cf, 0x5503), .driver_info = DEVICE_VMK8055},
{USB_DEVICE(0x10cf, 0x8061), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8062), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8063), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8064), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8065), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8066), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8067), .driver_info = DEVICE_VMK8061},
{USB_DEVICE(0x10cf, 0x8068), .driver_info = DEVICE_VMK8061},
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, vmk80xx_id_table);
#define VMK8055_DI_REG 0x00
#define VMK8055_DO_REG 0x01
#define VMK8055_AO1_REG 0x02
#define VMK8055_AO2_REG 0x03
#define VMK8055_AI1_REG 0x02
#define VMK8055_AI2_REG 0x03
#define VMK8055_CNT1_REG 0x04
#define VMK8055_CNT2_REG 0x06
#define VMK8061_CH_REG 0x01
#define VMK8061_DI_REG 0x01
#define VMK8061_DO_REG 0x01
#define VMK8061_PWM_REG1 0x01
#define VMK8061_PWM_REG2 0x02
#define VMK8061_CNT_REG 0x02
#define VMK8061_AO_REG 0x02
#define VMK8061_AI_REG1 0x02
#define VMK8061_AI_REG2 0x03
#define VMK8055_CMD_RST 0x00
#define VMK8055_CMD_DEB1_TIME 0x01
#define VMK8055_CMD_DEB2_TIME 0x02
#define VMK8055_CMD_RST_CNT1 0x03
#define VMK8055_CMD_RST_CNT2 0x04
#define VMK8055_CMD_WRT_AD 0x05
#define VMK8061_CMD_RD_AI 0x00
#define VMK8061_CMR_RD_ALL_AI 0x01 /* !non-active! */
#define VMK8061_CMD_SET_AO 0x02
#define VMK8061_CMD_SET_ALL_AO 0x03 /* !non-active! */
#define VMK8061_CMD_OUT_PWM 0x04
#define VMK8061_CMD_RD_DI 0x05
#define VMK8061_CMD_DO 0x06 /* !non-active! */
#define VMK8061_CMD_CLR_DO 0x07
#define VMK8061_CMD_SET_DO 0x08
#define VMK8061_CMD_RD_CNT 0x09 /* TODO: completely pointless? */
#define VMK8061_CMD_RST_CNT 0x0a /* TODO: completely pointless? */
#define VMK8061_CMD_RD_VERSION 0x0b /* internal usage */
#define VMK8061_CMD_RD_JMP_STAT 0x0c /* TODO: not implemented yet */
#define VMK8061_CMD_RD_PWR_STAT 0x0d /* internal usage */
#define VMK8061_CMD_RD_DO 0x0e
#define VMK8061_CMD_RD_AO 0x0f
#define VMK8061_CMD_RD_PWM 0x10
#define VMK80XX_MAX_BOARDS COMEDI_NUM_BOARD_MINORS
#define TRANS_OUT_BUSY 1
#define TRANS_IN_BUSY 2
#define TRANS_IN_RUNNING 3
#define IC3_VERSION (1 << 0)
#define IC6_VERSION (1 << 1)
#define URB_RCV_FLAG (1 << 0)
#define URB_SND_FLAG (1 << 1)
#define CONFIG_VMK80XX_DEBUG
#undef CONFIG_VMK80XX_DEBUG
#ifdef CONFIG_VMK80XX_DEBUG
static int dbgvm = 1;
#else
static int dbgvm;
#endif
#ifdef CONFIG_COMEDI_DEBUG
static int dbgcm = 1;
#else
static int dbgcm;
#endif
#define dbgvm(fmt, arg...) \
do { \
if (dbgvm) \
printk(KERN_DEBUG fmt, ##arg); \
} while (0)
#define dbgcm(fmt, arg...) \
do { \
if (dbgcm) \
printk(KERN_DEBUG fmt, ##arg); \
} while (0)
enum vmk80xx_model {
VMK8055_MODEL,
VMK8061_MODEL
};
struct firmware_version {
unsigned char ic3_vers[32]; /* USB-Controller */
unsigned char ic6_vers[32]; /* CPU */
};
static const struct comedi_lrange vmk8055_range = {
1, {UNI_RANGE(5)}
};
static const struct comedi_lrange vmk8061_range = {
2, {UNI_RANGE(5), UNI_RANGE(10)}
};
struct vmk80xx_board {
const char *name;
enum vmk80xx_model model;
const struct comedi_lrange *range;
__u8 ai_chans;
__le16 ai_bits;
__u8 ao_chans;
__le16 ao_bits;
__u8 di_chans;
__le16 di_bits;
__u8 do_chans;
__le16 do_bits;
__u8 cnt_chans;
__le16 cnt_bits;
__u8 pwm_chans;
__le16 pwm_bits;
};
enum {
VMK80XX_SUBD_AI,
VMK80XX_SUBD_AO,
VMK80XX_SUBD_DI,
VMK80XX_SUBD_DO,
VMK80XX_SUBD_CNT,
VMK80XX_SUBD_PWM,
};
struct vmk80xx_usb {
struct usb_device *udev;
struct usb_interface *intf;
struct usb_endpoint_descriptor *ep_rx;
struct usb_endpoint_descriptor *ep_tx;
struct usb_anchor rx_anchor;
struct usb_anchor tx_anchor;
struct vmk80xx_board board;
struct firmware_version fw;
struct semaphore limit_sem;
wait_queue_head_t read_wait;
wait_queue_head_t write_wait;
unsigned char *usb_rx_buf;
unsigned char *usb_tx_buf;
unsigned long flags;
int probed;
int attached;
int count;
};
static struct vmk80xx_usb vmb[VMK80XX_MAX_BOARDS];
static DEFINE_MUTEX(glb_mutex);
static void vmk80xx_tx_callback(struct urb *urb)
{
struct vmk80xx_usb *dev = urb->context;
int stat = urb->status;
dbgvm("vmk80xx: %s\n", __func__);
if (stat && !(stat == -ENOENT
|| stat == -ECONNRESET || stat == -ESHUTDOWN))
dbgcm("comedi#: vmk80xx: %s - nonzero urb status (%d)\n",
__func__, stat);
if (!test_bit(TRANS_OUT_BUSY, &dev->flags))
return;
clear_bit(TRANS_OUT_BUSY, &dev->flags);
wake_up_interruptible(&dev->write_wait);
}
static void vmk80xx_rx_callback(struct urb *urb)
{
struct vmk80xx_usb *dev = urb->context;
int stat = urb->status;
dbgvm("vmk80xx: %s\n", __func__);
switch (stat) {
case 0:
break;
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
break;
default:
dbgcm("comedi#: vmk80xx: %s - nonzero urb status (%d)\n",
__func__, stat);
goto resubmit;
}
goto exit;
resubmit:
if (test_bit(TRANS_IN_RUNNING, &dev->flags) && dev->intf) {
usb_anchor_urb(urb, &dev->rx_anchor);
if (!usb_submit_urb(urb, GFP_KERNEL))
goto exit;
err("comedi#: vmk80xx: %s - submit urb failed\n", __func__);
usb_unanchor_urb(urb);
}
exit:
clear_bit(TRANS_IN_BUSY, &dev->flags);
wake_up_interruptible(&dev->read_wait);
}
static int vmk80xx_check_data_link(struct vmk80xx_usb *dev)
{
unsigned int tx_pipe, rx_pipe;
unsigned char tx[1], rx[2];
dbgvm("vmk80xx: %s\n", __func__);
tx_pipe = usb_sndbulkpipe(dev->udev, 0x01);
rx_pipe = usb_rcvbulkpipe(dev->udev, 0x81);
tx[0] = VMK8061_CMD_RD_PWR_STAT;
/* Check that IC6 (PIC16F871) is powered and
* running and the data link between IC3 and
* IC6 is working properly */
usb_bulk_msg(dev->udev, tx_pipe, tx, 1, NULL, dev->ep_tx->bInterval);
usb_bulk_msg(dev->udev, rx_pipe, rx, 2, NULL, HZ * 10);
return (int)rx[1];
}
static void vmk80xx_read_eeprom(struct vmk80xx_usb *dev, int flag)
{
unsigned int tx_pipe, rx_pipe;
unsigned char tx[1], rx[64];
int cnt;
dbgvm("vmk80xx: %s\n", __func__);
tx_pipe = usb_sndbulkpipe(dev->udev, 0x01);
rx_pipe = usb_rcvbulkpipe(dev->udev, 0x81);
tx[0] = VMK8061_CMD_RD_VERSION;
/* Read the firmware version info of IC3 and
* IC6 from the internal EEPROM of the IC */
usb_bulk_msg(dev->udev, tx_pipe, tx, 1, NULL, dev->ep_tx->bInterval);
usb_bulk_msg(dev->udev, rx_pipe, rx, 64, &cnt, HZ * 10);
rx[cnt] = '\0';
if (flag & IC3_VERSION)
strncpy(dev->fw.ic3_vers, rx + 1, 24);
else /* IC6_VERSION */
strncpy(dev->fw.ic6_vers, rx + 25, 24);
}
static int vmk80xx_reset_device(struct vmk80xx_usb *dev)
{
struct urb *urb;
unsigned int tx_pipe;
int ival;
size_t size;
dbgvm("vmk80xx: %s\n", __func__);
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
tx_pipe = usb_sndintpipe(dev->udev, 0x01);
ival = dev->ep_tx->bInterval;
size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
dev->usb_tx_buf[0] = VMK8055_CMD_RST;
dev->usb_tx_buf[1] = 0x00;
dev->usb_tx_buf[2] = 0x00;
dev->usb_tx_buf[3] = 0x00;
dev->usb_tx_buf[4] = 0x00;
dev->usb_tx_buf[5] = 0x00;
dev->usb_tx_buf[6] = 0x00;
dev->usb_tx_buf[7] = 0x00;
usb_fill_int_urb(urb, dev->udev, tx_pipe, dev->usb_tx_buf,
size, vmk80xx_tx_callback, dev, ival);
usb_anchor_urb(urb, &dev->tx_anchor);
return usb_submit_urb(urb, GFP_KERNEL);
}
static void vmk80xx_build_int_urb(struct urb *urb, int flag)
{
struct vmk80xx_usb *dev = urb->context;
__u8 rx_addr, tx_addr;
unsigned int pipe;
unsigned char *buf;
size_t size;
void (*callback) (struct urb *);
int ival;
dbgvm("vmk80xx: %s\n", __func__);
if (flag & URB_RCV_FLAG) {
rx_addr = dev->ep_rx->bEndpointAddress;
pipe = usb_rcvintpipe(dev->udev, rx_addr);
buf = dev->usb_rx_buf;
size = le16_to_cpu(dev->ep_rx->wMaxPacketSize);
callback = vmk80xx_rx_callback;
ival = dev->ep_rx->bInterval;
} else { /* URB_SND_FLAG */
tx_addr = dev->ep_tx->bEndpointAddress;
pipe = usb_sndintpipe(dev->udev, tx_addr);
buf = dev->usb_tx_buf;
size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
callback = vmk80xx_tx_callback;
ival = dev->ep_tx->bInterval;
}
usb_fill_int_urb(urb, dev->udev, pipe, buf, size, callback, dev, ival);
}
static void vmk80xx_do_bulk_msg(struct vmk80xx_usb *dev)
{
__u8 tx_addr, rx_addr;
unsigned int tx_pipe, rx_pipe;
size_t size;
dbgvm("vmk80xx: %s\n", __func__);
set_bit(TRANS_IN_BUSY, &dev->flags);
set_bit(TRANS_OUT_BUSY, &dev->flags);
tx_addr = dev->ep_tx->bEndpointAddress;
rx_addr = dev->ep_rx->bEndpointAddress;
tx_pipe = usb_sndbulkpipe(dev->udev, tx_addr);
rx_pipe = usb_rcvbulkpipe(dev->udev, rx_addr);
/* The max packet size attributes of the K8061
* input/output endpoints are identical */
size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
usb_bulk_msg(dev->udev, tx_pipe, dev->usb_tx_buf,
size, NULL, dev->ep_tx->bInterval);
usb_bulk_msg(dev->udev, rx_pipe, dev->usb_rx_buf, size, NULL, HZ * 10);
clear_bit(TRANS_OUT_BUSY, &dev->flags);
clear_bit(TRANS_IN_BUSY, &dev->flags);
}
static int vmk80xx_read_packet(struct vmk80xx_usb *dev)
{
struct urb *urb;
int retval;
dbgvm("vmk80xx: %s\n", __func__);
if (!dev->intf)
return -ENODEV;
/* Only useful for interrupt transfers */
if (test_bit(TRANS_IN_BUSY, &dev->flags))
if (wait_event_interruptible(dev->read_wait,
!test_bit(TRANS_IN_BUSY,
&dev->flags)))
return -ERESTART;
if (dev->board.model == VMK8061_MODEL) {
vmk80xx_do_bulk_msg(dev);
return 0;
}
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
urb->context = dev;
vmk80xx_build_int_urb(urb, URB_RCV_FLAG);
set_bit(TRANS_IN_RUNNING, &dev->flags);
set_bit(TRANS_IN_BUSY, &dev->flags);
usb_anchor_urb(urb, &dev->rx_anchor);
retval = usb_submit_urb(urb, GFP_KERNEL);
if (!retval)
goto exit;
clear_bit(TRANS_IN_RUNNING, &dev->flags);
usb_unanchor_urb(urb);
exit:
usb_free_urb(urb);
return retval;
}
static int vmk80xx_write_packet(struct vmk80xx_usb *dev, int cmd)
{
struct urb *urb;
int retval;
dbgvm("vmk80xx: %s\n", __func__);
if (!dev->intf)
return -ENODEV;
if (test_bit(TRANS_OUT_BUSY, &dev->flags))
if (wait_event_interruptible(dev->write_wait,
!test_bit(TRANS_OUT_BUSY,
&dev->flags)))
return -ERESTART;
if (dev->board.model == VMK8061_MODEL) {
dev->usb_tx_buf[0] = cmd;
vmk80xx_do_bulk_msg(dev);
return 0;
}
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
urb->context = dev;
vmk80xx_build_int_urb(urb, URB_SND_FLAG);
set_bit(TRANS_OUT_BUSY, &dev->flags);
usb_anchor_urb(urb, &dev->tx_anchor);
dev->usb_tx_buf[0] = cmd;
retval = usb_submit_urb(urb, GFP_KERNEL);
if (!retval)
goto exit;
clear_bit(TRANS_OUT_BUSY, &dev->flags);
usb_unanchor_urb(urb);
exit:
usb_free_urb(urb);
return retval;
}
#define DIR_IN 1
#define DIR_OUT 2
#define rudimentary_check(dir) \
do { \
if (!dev) \
return -EFAULT; \
if (!dev->probed) \
return -ENODEV; \
if (!dev->attached) \
return -ENODEV; \
if ((dir) & DIR_IN) { \
if (test_bit(TRANS_IN_BUSY, &dev->flags)) \
return -EBUSY; \
} else { /* DIR_OUT */ \
if (test_bit(TRANS_OUT_BUSY, &dev->flags)) \
return -EBUSY; \
} \
} while (0)
static int vmk80xx_ai_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan, reg[2];
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
switch (dev->board.model) {
case VMK8055_MODEL:
if (!chan)
reg[0] = VMK8055_AI1_REG;
else
reg[0] = VMK8055_AI2_REG;
break;
case VMK8061_MODEL:
reg[0] = VMK8061_AI_REG1;
reg[1] = VMK8061_AI_REG2;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_AI;
dev->usb_tx_buf[VMK8061_CH_REG] = chan;
break;
}
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
if (dev->board.model == VMK8055_MODEL) {
data[n] = dev->usb_rx_buf[reg[0]];
continue;
}
/* VMK8061_MODEL */
data[n] = dev->usb_rx_buf[reg[0]] + 256 *
dev->usb_rx_buf[reg[1]];
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_ao_winsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan, cmd, reg;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_OUT);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
switch (dev->board.model) {
case VMK8055_MODEL:
cmd = VMK8055_CMD_WRT_AD;
if (!chan)
reg = VMK8055_AO1_REG;
else
reg = VMK8055_AO2_REG;
break;
default: /* NOTE: avoid compiler warnings */
cmd = VMK8061_CMD_SET_AO;
reg = VMK8061_AO_REG;
dev->usb_tx_buf[VMK8061_CH_REG] = chan;
break;
}
for (n = 0; n < insn->n; n++) {
dev->usb_tx_buf[reg] = data[n];
if (vmk80xx_write_packet(dev, cmd))
break;
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_ao_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan, reg;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
reg = VMK8061_AO_REG - 1;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_AO;
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
data[n] = dev->usb_rx_buf[reg + chan];
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_di_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan;
unsigned char *rx_buf;
int reg, inp;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
rx_buf = dev->usb_rx_buf;
if (dev->board.model == VMK8061_MODEL) {
reg = VMK8061_DI_REG;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_DI;
} else
reg = VMK8055_DI_REG;
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
if (dev->board.model == VMK8055_MODEL)
inp = (((rx_buf[reg] >> 4) & 0x03) |
((rx_buf[reg] << 2) & 0x04) |
((rx_buf[reg] >> 3) & 0x18));
else
inp = rx_buf[reg];
data[n] = ((inp & (1 << chan)) > 0);
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_do_winsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan;
unsigned char *tx_buf;
int reg, cmd;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_OUT);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
tx_buf = dev->usb_tx_buf;
for (n = 0; n < insn->n; n++) {
if (dev->board.model == VMK8055_MODEL) {
reg = VMK8055_DO_REG;
cmd = VMK8055_CMD_WRT_AD;
if (data[n] == 1)
tx_buf[reg] |= (1 << chan);
else
tx_buf[reg] ^= (1 << chan);
goto write_packet;
}
/* VMK8061_MODEL */
reg = VMK8061_DO_REG;
if (data[n] == 1) {
cmd = VMK8061_CMD_SET_DO;
tx_buf[reg] = 1 << chan;
} else {
cmd = VMK8061_CMD_CLR_DO;
tx_buf[reg] = 0xff - (1 << chan);
}
write_packet:
if (vmk80xx_write_packet(dev, cmd))
break;
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_do_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan, reg, mask;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
reg = VMK8061_DO_REG;
mask = 1 << chan;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_DO;
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
data[n] = (dev->usb_rx_buf[reg] & mask) >> chan;
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_cnt_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int chan, reg[2];
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
switch (dev->board.model) {
case VMK8055_MODEL:
if (!chan)
reg[0] = VMK8055_CNT1_REG;
else
reg[0] = VMK8055_CNT2_REG;
break;
case VMK8061_MODEL:
reg[0] = VMK8061_CNT_REG;
reg[1] = VMK8061_CNT_REG;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_CNT;
break;
}
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
if (dev->board.model == VMK8055_MODEL) {
data[n] = dev->usb_rx_buf[reg[0]];
continue;
}
/* VMK8061_MODEL */
data[n] = dev->usb_rx_buf[reg[0] * (chan + 1) + 1]
+ 256 * dev->usb_rx_buf[reg[1] * 2 + 2];
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_cnt_cinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
unsigned int insn_cmd;
int chan, cmd, reg;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_OUT);
down(&dev->limit_sem);
insn_cmd = data[0];
if (insn_cmd != INSN_CONFIG_RESET && insn_cmd != GPCT_RESET)
return -EINVAL;
chan = CR_CHAN(insn->chanspec);
if (dev->board.model == VMK8055_MODEL) {
if (!chan) {
cmd = VMK8055_CMD_RST_CNT1;
reg = VMK8055_CNT1_REG;
} else {
cmd = VMK8055_CMD_RST_CNT2;
reg = VMK8055_CNT2_REG;
}
dev->usb_tx_buf[reg] = 0x00;
} else
cmd = VMK8061_CMD_RST_CNT;
for (n = 0; n < insn->n; n++)
if (vmk80xx_write_packet(dev, cmd))
break;
up(&dev->limit_sem);
return n;
}
static int vmk80xx_cnt_winsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
unsigned long debtime, val;
int chan, cmd;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_OUT);
down(&dev->limit_sem);
chan = CR_CHAN(insn->chanspec);
if (!chan)
cmd = VMK8055_CMD_DEB1_TIME;
else
cmd = VMK8055_CMD_DEB2_TIME;
for (n = 0; n < insn->n; n++) {
debtime = data[n];
if (debtime == 0)
debtime = 1;
/* TODO: Prevent overflows */
if (debtime > 7450)
debtime = 7450;
val = int_sqrt(debtime * 1000 / 115);
if (((val + 1) * val) < debtime * 1000 / 115)
val += 1;
dev->usb_tx_buf[6 + chan] = val;
if (vmk80xx_write_packet(dev, cmd))
break;
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_pwm_rinsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
int reg[2];
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_IN);
down(&dev->limit_sem);
reg[0] = VMK8061_PWM_REG1;
reg[1] = VMK8061_PWM_REG2;
dev->usb_tx_buf[0] = VMK8061_CMD_RD_PWM;
for (n = 0; n < insn->n; n++) {
if (vmk80xx_read_packet(dev))
break;
data[n] = dev->usb_rx_buf[reg[0]] + 4 * dev->usb_rx_buf[reg[1]];
}
up(&dev->limit_sem);
return n;
}
static int vmk80xx_pwm_winsn(struct comedi_device *cdev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct vmk80xx_usb *dev = cdev->private;
unsigned char *tx_buf;
int reg[2], cmd;
int n;
dbgvm("vmk80xx: %s\n", __func__);
rudimentary_check(DIR_OUT);
down(&dev->limit_sem);
tx_buf = dev->usb_tx_buf;
reg[0] = VMK8061_PWM_REG1;
reg[1] = VMK8061_PWM_REG2;
cmd = VMK8061_CMD_OUT_PWM;
/*
* The followin piece of code was translated from the inline
* assembler code in the DLL source code.
*
* asm
* mov eax, k ; k is the value (data[n])
* and al, 03h ; al are the lower 8 bits of eax
* mov lo, al ; lo is the low part (tx_buf[reg[0]])
* mov eax, k
* shr eax, 2 ; right shift eax register by 2
* mov hi, al ; hi is the high part (tx_buf[reg[1]])
* end;
*/
for (n = 0; n < insn->n; n++) {
tx_buf[reg[0]] = (unsigned char)(data[n] & 0x03);
tx_buf[reg[1]] = (unsigned char)(data[n] >> 2) & 0xff;
if (vmk80xx_write_packet(dev, cmd))
break;
}
up(&dev->limit_sem);
return n;
}
static int
vmk80xx_attach(struct comedi_device *cdev, struct comedi_devconfig *it)
{
int i;
struct vmk80xx_usb *dev;
int n_subd;
struct comedi_subdevice *s;
int minor;
dbgvm("vmk80xx: %s\n", __func__);
mutex_lock(&glb_mutex);
for (i = 0; i < VMK80XX_MAX_BOARDS; i++)
if (vmb[i].probed && !vmb[i].attached)
break;
if (i == VMK80XX_MAX_BOARDS) {
mutex_unlock(&glb_mutex);
return -ENODEV;
}
dev = &vmb[i];
down(&dev->limit_sem);
cdev->board_name = dev->board.name;
cdev->private = dev;
if (dev->board.model == VMK8055_MODEL)
n_subd = 5;
else
n_subd = 6;
if (alloc_subdevices(cdev, n_subd) < 0) {
up(&dev->limit_sem);
mutex_unlock(&glb_mutex);
return -ENOMEM;
}
/* Analog input subdevice */
s = cdev->subdevices + VMK80XX_SUBD_AI;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_GROUND;
s->n_chan = dev->board.ai_chans;
s->maxdata = (1 << dev->board.ai_bits) - 1;
s->range_table = dev->board.range;
s->insn_read = vmk80xx_ai_rinsn;
/* Analog output subdevice */
s = cdev->subdevices + VMK80XX_SUBD_AO;
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITEABLE | SDF_GROUND;
s->n_chan = dev->board.ao_chans;
s->maxdata = (1 << dev->board.ao_bits) - 1;
s->range_table = dev->board.range;
s->insn_write = vmk80xx_ao_winsn;
if (dev->board.model == VMK8061_MODEL) {
s->subdev_flags |= SDF_READABLE;
s->insn_read = vmk80xx_ao_rinsn;
}
/* Digital input subdevice */
s = cdev->subdevices + VMK80XX_SUBD_DI;
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE | SDF_GROUND;
s->n_chan = dev->board.di_chans;
s->maxdata = (1 << dev->board.di_bits) - 1;
s->insn_read = vmk80xx_di_rinsn;
/* Digital output subdevice */
s = cdev->subdevices + VMK80XX_SUBD_DO;
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITEABLE | SDF_GROUND;
s->n_chan = dev->board.do_chans;
s->maxdata = (1 << dev->board.do_bits) - 1;
s->insn_write = vmk80xx_do_winsn;
if (dev->board.model == VMK8061_MODEL) {
s->subdev_flags |= SDF_READABLE;
s->insn_read = vmk80xx_do_rinsn;
}
/* Counter subdevice */
s = cdev->subdevices + VMK80XX_SUBD_CNT;
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_READABLE;
s->n_chan = dev->board.cnt_chans;
s->insn_read = vmk80xx_cnt_rinsn;
s->insn_config = vmk80xx_cnt_cinsn;
if (dev->board.model == VMK8055_MODEL) {
s->subdev_flags |= SDF_WRITEABLE;
s->maxdata = (1 << dev->board.cnt_bits) - 1;
s->insn_write = vmk80xx_cnt_winsn;
}
/* PWM subdevice */
if (dev->board.model == VMK8061_MODEL) {
s = cdev->subdevices + VMK80XX_SUBD_PWM;
s->type = COMEDI_SUBD_PWM;
s->subdev_flags = SDF_READABLE | SDF_WRITEABLE;
s->n_chan = dev->board.pwm_chans;
s->maxdata = (1 << dev->board.pwm_bits) - 1;
s->insn_read = vmk80xx_pwm_rinsn;
s->insn_write = vmk80xx_pwm_winsn;
}
dev->attached = 1;
minor = cdev->minor;
printk(KERN_INFO
"comedi%d: vmk80xx: board #%d [%s] attached to comedi\n",
minor, dev->count, dev->board.name);
up(&dev->limit_sem);
mutex_unlock(&glb_mutex);
return 0;
}
static int vmk80xx_detach(struct comedi_device *cdev)
{
struct vmk80xx_usb *dev;
int minor;
dbgvm("vmk80xx: %s\n", __func__);
if (!cdev)
return -EFAULT;
dev = cdev->private;
if (!dev)
return -EFAULT;
down(&dev->limit_sem);
cdev->private = NULL;
dev->attached = 0;
minor = cdev->minor;
printk(KERN_INFO
"comedi%d: vmk80xx: board #%d [%s] detached from comedi\n",
minor, dev->count, dev->board.name);
up(&dev->limit_sem);
return 0;
}
static int
vmk80xx_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
int i;
struct vmk80xx_usb *dev;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *ep_desc;
size_t size;
dbgvm("vmk80xx: %s\n", __func__);
mutex_lock(&glb_mutex);
for (i = 0; i < VMK80XX_MAX_BOARDS; i++)
if (!vmb[i].probed)
break;
if (i == VMK80XX_MAX_BOARDS) {
mutex_unlock(&glb_mutex);
return -EMFILE;
}
dev = &vmb[i];
memset(dev, 0x00, sizeof(struct vmk80xx_usb));
dev->count = i;
iface_desc = intf->cur_altsetting;
if (iface_desc->desc.bNumEndpoints != 2)
goto error;
for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
ep_desc = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_int_in(ep_desc)) {
dev->ep_rx = ep_desc;
continue;
}
if (usb_endpoint_is_int_out(ep_desc)) {
dev->ep_tx = ep_desc;
continue;
}
if (usb_endpoint_is_bulk_in(ep_desc)) {
dev->ep_rx = ep_desc;
continue;
}
if (usb_endpoint_is_bulk_out(ep_desc)) {
dev->ep_tx = ep_desc;
continue;
}
}
if (!dev->ep_rx || !dev->ep_tx)
goto error;
size = le16_to_cpu(dev->ep_rx->wMaxPacketSize);
dev->usb_rx_buf = kmalloc(size, GFP_KERNEL);
if (!dev->usb_rx_buf) {
mutex_unlock(&glb_mutex);
return -ENOMEM;
}
size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
dev->usb_tx_buf = kmalloc(size, GFP_KERNEL);
if (!dev->usb_tx_buf) {
kfree(dev->usb_rx_buf);
mutex_unlock(&glb_mutex);
return -ENOMEM;
}
dev->udev = interface_to_usbdev(intf);
dev->intf = intf;
sema_init(&dev->limit_sem, 8);
init_waitqueue_head(&dev->read_wait);
init_waitqueue_head(&dev->write_wait);
init_usb_anchor(&dev->rx_anchor);
init_usb_anchor(&dev->tx_anchor);
usb_set_intfdata(intf, dev);
switch (id->driver_info) {
case DEVICE_VMK8055:
dev->board.name = "K8055 (VM110)";
dev->board.model = VMK8055_MODEL;
dev->board.range = &vmk8055_range;
dev->board.ai_chans = 2;
dev->board.ai_bits = 8;
dev->board.ao_chans = 2;
dev->board.ao_bits = 8;
dev->board.di_chans = 5;
dev->board.di_bits = 1;
dev->board.do_chans = 8;
dev->board.do_bits = 1;
dev->board.cnt_chans = 2;
dev->board.cnt_bits = 16;
dev->board.pwm_chans = 0;
dev->board.pwm_bits = 0;
break;
case DEVICE_VMK8061:
dev->board.name = "K8061 (VM140)";
dev->board.model = VMK8061_MODEL;
dev->board.range = &vmk8061_range;
dev->board.ai_chans = 8;
dev->board.ai_bits = 10;
dev->board.ao_chans = 8;
dev->board.ao_bits = 8;
dev->board.di_chans = 8;
dev->board.di_bits = 1;
dev->board.do_chans = 8;
dev->board.do_bits = 1;
dev->board.cnt_chans = 2;
dev->board.cnt_bits = 0;
dev->board.pwm_chans = 1;
dev->board.pwm_bits = 10;
break;
}
if (dev->board.model == VMK8061_MODEL) {
vmk80xx_read_eeprom(dev, IC3_VERSION);
printk(KERN_INFO "comedi#: vmk80xx: %s\n", dev->fw.ic3_vers);
if (vmk80xx_check_data_link(dev)) {
vmk80xx_read_eeprom(dev, IC6_VERSION);
printk(KERN_INFO "comedi#: vmk80xx: %s\n",
dev->fw.ic6_vers);
} else
dbgcm("comedi#: vmk80xx: no conn. to CPU\n");
}
if (dev->board.model == VMK8055_MODEL)
vmk80xx_reset_device(dev);
dev->probed = 1;
printk(KERN_INFO "comedi#: vmk80xx: board #%d [%s] now attached\n",
dev->count, dev->board.name);
mutex_unlock(&glb_mutex);
return 0;
error:
mutex_unlock(&glb_mutex);
return -ENODEV;
}
static void vmk80xx_disconnect(struct usb_interface *intf)
{
struct vmk80xx_usb *dev = usb_get_intfdata(intf);
dbgvm("vmk80xx: %s\n", __func__);
if (!dev)
return;
mutex_lock(&glb_mutex);
down(&dev->limit_sem);
dev->probed = 0;
usb_set_intfdata(dev->intf, NULL);
usb_kill_anchored_urbs(&dev->rx_anchor);
usb_kill_anchored_urbs(&dev->tx_anchor);
kfree(dev->usb_rx_buf);
kfree(dev->usb_tx_buf);
printk(KERN_INFO "comedi#: vmk80xx: board #%d [%s] now detached\n",
dev->count, dev->board.name);
up(&dev->limit_sem);
mutex_unlock(&glb_mutex);
}
/* TODO: Add support for suspend, resume, pre_reset,
* post_reset and flush */
static struct usb_driver vmk80xx_driver = {
.name = "vmk80xx",
.probe = vmk80xx_probe,
.disconnect = vmk80xx_disconnect,
.id_table = vmk80xx_id_table
};
static struct comedi_driver driver_vmk80xx = {
.module = THIS_MODULE,
.driver_name = "vmk80xx",
.attach = vmk80xx_attach,
.detach = vmk80xx_detach
};
static int __init vmk80xx_init(void)
{
printk(KERN_INFO "vmk80xx: version 0.8.01 "
"Manuel Gebele <forensixs@gmx.de>\n");
usb_register(&vmk80xx_driver);
return comedi_driver_register(&driver_vmk80xx);
}
static void __exit vmk80xx_exit(void)
{
comedi_driver_unregister(&driver_vmk80xx);
usb_deregister(&vmk80xx_driver);
}
module_init(vmk80xx_init);
module_exit(vmk80xx_exit);
| gpl-2.0 |
Excito/kernel-3.18 | drivers/gpu/drm/i915/i915_gem_render_state.c | 305 | 4149 | /*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Mika Kuoppala <mika.kuoppala@intel.com>
*
*/
#include "i915_drv.h"
#include "intel_renderstate.h"
static const struct intel_renderstate_rodata *
render_state_get_rodata(struct drm_device *dev, const int gen)
{
switch (gen) {
case 6:
return &gen6_null_state;
case 7:
return &gen7_null_state;
case 8:
return &gen8_null_state;
}
return NULL;
}
static int render_state_init(struct render_state *so, struct drm_device *dev)
{
int ret;
so->gen = INTEL_INFO(dev)->gen;
so->rodata = render_state_get_rodata(dev, so->gen);
if (so->rodata == NULL)
return 0;
if (so->rodata->batch_items * 4 > 4096)
return -EINVAL;
so->obj = i915_gem_alloc_object(dev, 4096);
if (so->obj == NULL)
return -ENOMEM;
ret = i915_gem_obj_ggtt_pin(so->obj, 4096, 0);
if (ret)
goto free_gem;
so->ggtt_offset = i915_gem_obj_ggtt_offset(so->obj);
return 0;
free_gem:
drm_gem_object_unreference(&so->obj->base);
return ret;
}
static int render_state_setup(struct render_state *so)
{
const struct intel_renderstate_rodata *rodata = so->rodata;
unsigned int i = 0, reloc_index = 0;
struct page *page;
u32 *d;
int ret;
ret = i915_gem_object_set_to_cpu_domain(so->obj, true);
if (ret)
return ret;
page = sg_page(so->obj->pages->sgl);
d = kmap(page);
while (i < rodata->batch_items) {
u32 s = rodata->batch[i];
if (i * 4 == rodata->reloc[reloc_index]) {
u64 r = s + so->ggtt_offset;
s = lower_32_bits(r);
if (so->gen >= 8) {
if (i + 1 >= rodata->batch_items ||
rodata->batch[i + 1] != 0)
return -EINVAL;
d[i++] = s;
s = upper_32_bits(r);
}
reloc_index++;
}
d[i++] = s;
}
kunmap(page);
ret = i915_gem_object_set_to_gtt_domain(so->obj, false);
if (ret)
return ret;
if (rodata->reloc[reloc_index] != -1) {
DRM_ERROR("only %d relocs resolved\n", reloc_index);
return -EINVAL;
}
return 0;
}
void i915_gem_render_state_fini(struct render_state *so)
{
i915_gem_object_ggtt_unpin(so->obj);
drm_gem_object_unreference(&so->obj->base);
}
int i915_gem_render_state_prepare(struct intel_engine_cs *ring,
struct render_state *so)
{
int ret;
if (WARN_ON(ring->id != RCS))
return -ENOENT;
ret = render_state_init(so, ring->dev);
if (ret)
return ret;
if (so->rodata == NULL)
return 0;
ret = render_state_setup(so);
if (ret) {
i915_gem_render_state_fini(so);
return ret;
}
return 0;
}
int i915_gem_render_state_init(struct intel_engine_cs *ring)
{
struct render_state so;
int ret;
ret = i915_gem_render_state_prepare(ring, &so);
if (ret)
return ret;
if (so.rodata == NULL)
return 0;
ret = ring->dispatch_execbuffer(ring,
so.ggtt_offset,
so.rodata->batch_items * 4,
I915_DISPATCH_SECURE);
if (ret)
goto out;
i915_vma_move_to_active(i915_gem_obj_to_ggtt(so.obj), ring);
ret = __i915_add_request(ring, NULL, so.obj, NULL);
/* __i915_add_request moves object to inactive if it fails */
out:
i915_gem_render_state_fini(&so);
return ret;
}
| gpl-2.0 |
riverzhou/kernel-c8500 | mm/quicklist.c | 561 | 2457 | /*
* Quicklist support.
*
* Quicklists are light weight lists of pages that have a defined state
* on alloc and free. Pages must be in the quicklist specific defined state
* (zero by default) when the page is freed. It seems that the initial idea
* for such lists first came from Dave Miller and then various other people
* improved on it.
*
* Copyright (C) 2007 SGI,
* Christoph Lameter <clameter@sgi.com>
* Generalized, added support for multiple lists and
* constructors / destructors.
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/quicklist.h>
DEFINE_PER_CPU(struct quicklist [CONFIG_NR_QUICK], quicklist);
#define FRACTION_OF_NODE_MEM 16
static unsigned long max_pages(unsigned long min_pages)
{
unsigned long node_free_pages, max;
int node = numa_node_id();
struct zone *zones = NODE_DATA(node)->node_zones;
int num_cpus_on_node;
node_free_pages =
#ifdef CONFIG_ZONE_DMA
zone_page_state(&zones[ZONE_DMA], NR_FREE_PAGES) +
#endif
#ifdef CONFIG_ZONE_DMA32
zone_page_state(&zones[ZONE_DMA32], NR_FREE_PAGES) +
#endif
zone_page_state(&zones[ZONE_NORMAL], NR_FREE_PAGES);
max = node_free_pages / FRACTION_OF_NODE_MEM;
num_cpus_on_node = cpumask_weight(cpumask_of_node(node));
max /= num_cpus_on_node;
return max(max, min_pages);
}
static long min_pages_to_free(struct quicklist *q,
unsigned long min_pages, long max_free)
{
long pages_to_free;
pages_to_free = q->nr_pages - max_pages(min_pages);
return min(pages_to_free, max_free);
}
/*
* Trim down the number of pages in the quicklist
*/
void quicklist_trim(int nr, void (*dtor)(void *),
unsigned long min_pages, unsigned long max_free)
{
long pages_to_free;
struct quicklist *q;
q = &get_cpu_var(quicklist)[nr];
if (q->nr_pages > min_pages) {
pages_to_free = min_pages_to_free(q, min_pages, max_free);
while (pages_to_free > 0) {
/*
* We pass a gfp_t of 0 to quicklist_alloc here
* because we will never call into the page allocator.
*/
void *p = quicklist_alloc(nr, 0, NULL);
if (dtor)
dtor(p);
free_page((unsigned long)p);
pages_to_free--;
}
}
put_cpu_var(quicklist);
}
unsigned long quicklist_total_size(void)
{
unsigned long count = 0;
int cpu;
struct quicklist *ql, *q;
for_each_online_cpu(cpu) {
ql = per_cpu(quicklist, cpu);
for (q = ql; q < ql + CONFIG_NR_QUICK; q++)
count += q->nr_pages;
}
return count;
}
| gpl-2.0 |
lvming/linux | drivers/media/platform/omap3isp/isph3a_af.c | 561 | 11096 | /*
* isph3a_af.c
*
* TI OMAP3 ISP - H3A AF module
*
* Copyright (C) 2010 Nokia Corporation
* Copyright (C) 2009 Texas Instruments, Inc.
*
* Contacts: David Cohen <dacohen@gmail.com>
* Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Linux specific include files */
#include <linux/device.h>
#include <linux/slab.h>
#include "isp.h"
#include "isph3a.h"
#include "ispstat.h"
#define IS_OUT_OF_BOUNDS(value, min, max) \
(((value) < (min)) || ((value) > (max)))
static void h3a_af_setup_regs(struct ispstat *af, void *priv)
{
struct omap3isp_h3a_af_config *conf = priv;
u32 pcr;
u32 pax1;
u32 pax2;
u32 paxstart;
u32 coef;
u32 base_coef_set0;
u32 base_coef_set1;
int index;
if (af->state == ISPSTAT_DISABLED)
return;
isp_reg_writel(af->isp, af->active_buf->dma_addr, OMAP3_ISP_IOMEM_H3A,
ISPH3A_AFBUFST);
if (!af->update)
return;
/* Configure Hardware Registers */
pax1 = ((conf->paxel.width >> 1) - 1) << AF_PAXW_SHIFT;
/* Set height in AFPAX1 */
pax1 |= (conf->paxel.height >> 1) - 1;
isp_reg_writel(af->isp, pax1, OMAP3_ISP_IOMEM_H3A, ISPH3A_AFPAX1);
/* Configure AFPAX2 Register */
/* Set Line Increment in AFPAX2 Register */
pax2 = ((conf->paxel.line_inc >> 1) - 1) << AF_LINE_INCR_SHIFT;
/* Set Vertical Count */
pax2 |= (conf->paxel.v_cnt - 1) << AF_VT_COUNT_SHIFT;
/* Set Horizontal Count */
pax2 |= (conf->paxel.h_cnt - 1);
isp_reg_writel(af->isp, pax2, OMAP3_ISP_IOMEM_H3A, ISPH3A_AFPAX2);
/* Configure PAXSTART Register */
/*Configure Horizontal Start */
paxstart = conf->paxel.h_start << AF_HZ_START_SHIFT;
/* Configure Vertical Start */
paxstart |= conf->paxel.v_start;
isp_reg_writel(af->isp, paxstart, OMAP3_ISP_IOMEM_H3A,
ISPH3A_AFPAXSTART);
/*SetIIRSH Register */
isp_reg_writel(af->isp, conf->iir.h_start,
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFIIRSH);
base_coef_set0 = ISPH3A_AFCOEF010;
base_coef_set1 = ISPH3A_AFCOEF110;
for (index = 0; index <= 8; index += 2) {
/*Set IIR Filter0 Coefficients */
coef = 0;
coef |= conf->iir.coeff_set0[index];
coef |= conf->iir.coeff_set0[index + 1] <<
AF_COEF_SHIFT;
isp_reg_writel(af->isp, coef, OMAP3_ISP_IOMEM_H3A,
base_coef_set0);
base_coef_set0 += AFCOEF_OFFSET;
/*Set IIR Filter1 Coefficients */
coef = 0;
coef |= conf->iir.coeff_set1[index];
coef |= conf->iir.coeff_set1[index + 1] <<
AF_COEF_SHIFT;
isp_reg_writel(af->isp, coef, OMAP3_ISP_IOMEM_H3A,
base_coef_set1);
base_coef_set1 += AFCOEF_OFFSET;
}
/* set AFCOEF0010 Register */
isp_reg_writel(af->isp, conf->iir.coeff_set0[10],
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFCOEF0010);
/* set AFCOEF1010 Register */
isp_reg_writel(af->isp, conf->iir.coeff_set1[10],
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFCOEF1010);
/* PCR Register */
/* Set RGB Position */
pcr = conf->rgb_pos << AF_RGBPOS_SHIFT;
/* Set Accumulator Mode */
if (conf->fvmode == OMAP3ISP_AF_MODE_PEAK)
pcr |= AF_FVMODE;
/* Set A-law */
if (conf->alaw_enable)
pcr |= AF_ALAW_EN;
/* HMF Configurations */
if (conf->hmf.enable) {
/* Enable HMF */
pcr |= AF_MED_EN;
/* Set Median Threshold */
pcr |= conf->hmf.threshold << AF_MED_TH_SHIFT;
}
/* Set PCR Register */
isp_reg_clr_set(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
AF_PCR_MASK, pcr);
af->update = 0;
af->config_counter += af->inc_config;
af->inc_config = 0;
af->buf_size = conf->buf_size;
}
static void h3a_af_enable(struct ispstat *af, int enable)
{
if (enable) {
isp_reg_set(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
ISPH3A_PCR_AF_EN);
omap3isp_subclk_enable(af->isp, OMAP3_ISP_SUBCLK_AF);
} else {
isp_reg_clr(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
ISPH3A_PCR_AF_EN);
omap3isp_subclk_disable(af->isp, OMAP3_ISP_SUBCLK_AF);
}
}
static int h3a_af_busy(struct ispstat *af)
{
return isp_reg_readl(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR)
& ISPH3A_PCR_BUSYAF;
}
static u32 h3a_af_get_buf_size(struct omap3isp_h3a_af_config *conf)
{
return conf->paxel.h_cnt * conf->paxel.v_cnt * OMAP3ISP_AF_PAXEL_SIZE;
}
/* Function to check paxel parameters */
static int h3a_af_validate_params(struct ispstat *af, void *new_conf)
{
struct omap3isp_h3a_af_config *user_cfg = new_conf;
struct omap3isp_h3a_af_paxel *paxel_cfg = &user_cfg->paxel;
struct omap3isp_h3a_af_iir *iir_cfg = &user_cfg->iir;
int index;
u32 buf_size;
/* Check horizontal Count */
if (IS_OUT_OF_BOUNDS(paxel_cfg->h_cnt,
OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MIN,
OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MAX))
return -EINVAL;
/* Check Vertical Count */
if (IS_OUT_OF_BOUNDS(paxel_cfg->v_cnt,
OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MIN,
OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MAX))
return -EINVAL;
if (IS_OUT_OF_BOUNDS(paxel_cfg->height, OMAP3ISP_AF_PAXEL_HEIGHT_MIN,
OMAP3ISP_AF_PAXEL_HEIGHT_MAX) ||
paxel_cfg->height % 2)
return -EINVAL;
/* Check width */
if (IS_OUT_OF_BOUNDS(paxel_cfg->width, OMAP3ISP_AF_PAXEL_WIDTH_MIN,
OMAP3ISP_AF_PAXEL_WIDTH_MAX) ||
paxel_cfg->width % 2)
return -EINVAL;
/* Check Line Increment */
if (IS_OUT_OF_BOUNDS(paxel_cfg->line_inc,
OMAP3ISP_AF_PAXEL_INCREMENT_MIN,
OMAP3ISP_AF_PAXEL_INCREMENT_MAX) ||
paxel_cfg->line_inc % 2)
return -EINVAL;
/* Check Horizontal Start */
if ((paxel_cfg->h_start < iir_cfg->h_start) ||
IS_OUT_OF_BOUNDS(paxel_cfg->h_start,
OMAP3ISP_AF_PAXEL_HZSTART_MIN,
OMAP3ISP_AF_PAXEL_HZSTART_MAX))
return -EINVAL;
/* Check IIR */
for (index = 0; index < OMAP3ISP_AF_NUM_COEF; index++) {
if ((iir_cfg->coeff_set0[index]) > OMAP3ISP_AF_COEF_MAX)
return -EINVAL;
if ((iir_cfg->coeff_set1[index]) > OMAP3ISP_AF_COEF_MAX)
return -EINVAL;
}
if (IS_OUT_OF_BOUNDS(iir_cfg->h_start, OMAP3ISP_AF_IIRSH_MIN,
OMAP3ISP_AF_IIRSH_MAX))
return -EINVAL;
/* Hack: If paxel size is 12, the 10th AF window may be corrupted */
if ((paxel_cfg->h_cnt * paxel_cfg->v_cnt > 9) &&
(paxel_cfg->width * paxel_cfg->height == 12))
return -EINVAL;
buf_size = h3a_af_get_buf_size(user_cfg);
if (buf_size > user_cfg->buf_size)
/* User buf_size request wasn't enough */
user_cfg->buf_size = buf_size;
else if (user_cfg->buf_size > OMAP3ISP_AF_MAX_BUF_SIZE)
user_cfg->buf_size = OMAP3ISP_AF_MAX_BUF_SIZE;
return 0;
}
/* Update local parameters */
static void h3a_af_set_params(struct ispstat *af, void *new_conf)
{
struct omap3isp_h3a_af_config *user_cfg = new_conf;
struct omap3isp_h3a_af_config *cur_cfg = af->priv;
int update = 0;
int index;
/* alaw */
if (cur_cfg->alaw_enable != user_cfg->alaw_enable) {
update = 1;
goto out;
}
/* hmf */
if (cur_cfg->hmf.enable != user_cfg->hmf.enable) {
update = 1;
goto out;
}
if (cur_cfg->hmf.threshold != user_cfg->hmf.threshold) {
update = 1;
goto out;
}
/* rgbpos */
if (cur_cfg->rgb_pos != user_cfg->rgb_pos) {
update = 1;
goto out;
}
/* iir */
if (cur_cfg->iir.h_start != user_cfg->iir.h_start) {
update = 1;
goto out;
}
for (index = 0; index < OMAP3ISP_AF_NUM_COEF; index++) {
if (cur_cfg->iir.coeff_set0[index] !=
user_cfg->iir.coeff_set0[index]) {
update = 1;
goto out;
}
if (cur_cfg->iir.coeff_set1[index] !=
user_cfg->iir.coeff_set1[index]) {
update = 1;
goto out;
}
}
/* paxel */
if ((cur_cfg->paxel.width != user_cfg->paxel.width) ||
(cur_cfg->paxel.height != user_cfg->paxel.height) ||
(cur_cfg->paxel.h_start != user_cfg->paxel.h_start) ||
(cur_cfg->paxel.v_start != user_cfg->paxel.v_start) ||
(cur_cfg->paxel.h_cnt != user_cfg->paxel.h_cnt) ||
(cur_cfg->paxel.v_cnt != user_cfg->paxel.v_cnt) ||
(cur_cfg->paxel.line_inc != user_cfg->paxel.line_inc)) {
update = 1;
goto out;
}
/* af_mode */
if (cur_cfg->fvmode != user_cfg->fvmode)
update = 1;
out:
if (update || !af->configured) {
memcpy(cur_cfg, user_cfg, sizeof(*cur_cfg));
af->inc_config++;
af->update = 1;
/*
* User might be asked for a bigger buffer than necessary for
* this configuration. In order to return the right amount of
* data during buffer request, let's calculate the size here
* instead of stick with user_cfg->buf_size.
*/
cur_cfg->buf_size = h3a_af_get_buf_size(cur_cfg);
}
}
static long h3a_af_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
struct ispstat *stat = v4l2_get_subdevdata(sd);
switch (cmd) {
case VIDIOC_OMAP3ISP_AF_CFG:
return omap3isp_stat_config(stat, arg);
case VIDIOC_OMAP3ISP_STAT_REQ:
return omap3isp_stat_request_statistics(stat, arg);
case VIDIOC_OMAP3ISP_STAT_EN: {
int *en = arg;
return omap3isp_stat_enable(stat, !!*en);
}
}
return -ENOIOCTLCMD;
}
static const struct ispstat_ops h3a_af_ops = {
.validate_params = h3a_af_validate_params,
.set_params = h3a_af_set_params,
.setup_regs = h3a_af_setup_regs,
.enable = h3a_af_enable,
.busy = h3a_af_busy,
};
static const struct v4l2_subdev_core_ops h3a_af_subdev_core_ops = {
.ioctl = h3a_af_ioctl,
.subscribe_event = omap3isp_stat_subscribe_event,
.unsubscribe_event = omap3isp_stat_unsubscribe_event,
};
static const struct v4l2_subdev_video_ops h3a_af_subdev_video_ops = {
.s_stream = omap3isp_stat_s_stream,
};
static const struct v4l2_subdev_ops h3a_af_subdev_ops = {
.core = &h3a_af_subdev_core_ops,
.video = &h3a_af_subdev_video_ops,
};
/* Function to register the AF character device driver. */
int omap3isp_h3a_af_init(struct isp_device *isp)
{
struct ispstat *af = &isp->isp_af;
struct omap3isp_h3a_af_config *af_cfg;
struct omap3isp_h3a_af_config *af_recover_cfg;
af_cfg = devm_kzalloc(isp->dev, sizeof(*af_cfg), GFP_KERNEL);
if (af_cfg == NULL)
return -ENOMEM;
af->ops = &h3a_af_ops;
af->priv = af_cfg;
af->dma_ch = -1;
af->event_type = V4L2_EVENT_OMAP3ISP_AF;
af->isp = isp;
/* Set recover state configuration */
af_recover_cfg = devm_kzalloc(isp->dev, sizeof(*af_recover_cfg),
GFP_KERNEL);
if (!af_recover_cfg) {
dev_err(af->isp->dev, "AF: cannot allocate memory for recover "
"configuration.\n");
return -ENOMEM;
}
af_recover_cfg->paxel.h_start = OMAP3ISP_AF_PAXEL_HZSTART_MIN;
af_recover_cfg->paxel.width = OMAP3ISP_AF_PAXEL_WIDTH_MIN;
af_recover_cfg->paxel.height = OMAP3ISP_AF_PAXEL_HEIGHT_MIN;
af_recover_cfg->paxel.h_cnt = OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MIN;
af_recover_cfg->paxel.v_cnt = OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MIN;
af_recover_cfg->paxel.line_inc = OMAP3ISP_AF_PAXEL_INCREMENT_MIN;
if (h3a_af_validate_params(af, af_recover_cfg)) {
dev_err(af->isp->dev, "AF: recover configuration is "
"invalid.\n");
return -EINVAL;
}
af_recover_cfg->buf_size = h3a_af_get_buf_size(af_recover_cfg);
af->recover_priv = af_recover_cfg;
return omap3isp_stat_init(af, "AF", &h3a_af_subdev_ops);
}
void omap3isp_h3a_af_cleanup(struct isp_device *isp)
{
omap3isp_stat_cleanup(&isp->isp_af);
}
| gpl-2.0 |
jdheiner/SGH-T769_Kernel | drivers/gpu/drm/radeon/r600_cp.c | 817 | 79896 | /*
* Copyright 2008-2009 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (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 HOLDER(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.
*
* Authors:
* Dave Airlie <airlied@redhat.com>
* Alex Deucher <alexander.deucher@amd.com>
*/
#include "drmP.h"
#include "drm.h"
#include "radeon_drm.h"
#include "radeon_drv.h"
#define PFP_UCODE_SIZE 576
#define PM4_UCODE_SIZE 1792
#define R700_PFP_UCODE_SIZE 848
#define R700_PM4_UCODE_SIZE 1360
/* Firmware Names */
MODULE_FIRMWARE("radeon/R600_pfp.bin");
MODULE_FIRMWARE("radeon/R600_me.bin");
MODULE_FIRMWARE("radeon/RV610_pfp.bin");
MODULE_FIRMWARE("radeon/RV610_me.bin");
MODULE_FIRMWARE("radeon/RV630_pfp.bin");
MODULE_FIRMWARE("radeon/RV630_me.bin");
MODULE_FIRMWARE("radeon/RV620_pfp.bin");
MODULE_FIRMWARE("radeon/RV620_me.bin");
MODULE_FIRMWARE("radeon/RV635_pfp.bin");
MODULE_FIRMWARE("radeon/RV635_me.bin");
MODULE_FIRMWARE("radeon/RV670_pfp.bin");
MODULE_FIRMWARE("radeon/RV670_me.bin");
MODULE_FIRMWARE("radeon/RS780_pfp.bin");
MODULE_FIRMWARE("radeon/RS780_me.bin");
MODULE_FIRMWARE("radeon/RV770_pfp.bin");
MODULE_FIRMWARE("radeon/RV770_me.bin");
MODULE_FIRMWARE("radeon/RV730_pfp.bin");
MODULE_FIRMWARE("radeon/RV730_me.bin");
MODULE_FIRMWARE("radeon/RV710_pfp.bin");
MODULE_FIRMWARE("radeon/RV710_me.bin");
int r600_cs_legacy(struct drm_device *dev, void *data, struct drm_file *filp,
unsigned family, u32 *ib, int *l);
void r600_cs_legacy_init(void);
# define ATI_PCIGART_PAGE_SIZE 4096 /**< PCI GART page size */
# define ATI_PCIGART_PAGE_MASK (~(ATI_PCIGART_PAGE_SIZE-1))
#define R600_PTE_VALID (1 << 0)
#define R600_PTE_SYSTEM (1 << 1)
#define R600_PTE_SNOOPED (1 << 2)
#define R600_PTE_READABLE (1 << 5)
#define R600_PTE_WRITEABLE (1 << 6)
/* MAX values used for gfx init */
#define R6XX_MAX_SH_GPRS 256
#define R6XX_MAX_TEMP_GPRS 16
#define R6XX_MAX_SH_THREADS 256
#define R6XX_MAX_SH_STACK_ENTRIES 4096
#define R6XX_MAX_BACKENDS 8
#define R6XX_MAX_BACKENDS_MASK 0xff
#define R6XX_MAX_SIMDS 8
#define R6XX_MAX_SIMDS_MASK 0xff
#define R6XX_MAX_PIPES 8
#define R6XX_MAX_PIPES_MASK 0xff
#define R7XX_MAX_SH_GPRS 256
#define R7XX_MAX_TEMP_GPRS 16
#define R7XX_MAX_SH_THREADS 256
#define R7XX_MAX_SH_STACK_ENTRIES 4096
#define R7XX_MAX_BACKENDS 8
#define R7XX_MAX_BACKENDS_MASK 0xff
#define R7XX_MAX_SIMDS 16
#define R7XX_MAX_SIMDS_MASK 0xffff
#define R7XX_MAX_PIPES 8
#define R7XX_MAX_PIPES_MASK 0xff
static int r600_do_wait_for_fifo(drm_radeon_private_t *dev_priv, int entries)
{
int i;
dev_priv->stats.boxes |= RADEON_BOX_WAIT_IDLE;
for (i = 0; i < dev_priv->usec_timeout; i++) {
int slots;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770)
slots = (RADEON_READ(R600_GRBM_STATUS)
& R700_CMDFIFO_AVAIL_MASK);
else
slots = (RADEON_READ(R600_GRBM_STATUS)
& R600_CMDFIFO_AVAIL_MASK);
if (slots >= entries)
return 0;
DRM_UDELAY(1);
}
DRM_INFO("wait for fifo failed status : 0x%08X 0x%08X\n",
RADEON_READ(R600_GRBM_STATUS),
RADEON_READ(R600_GRBM_STATUS2));
return -EBUSY;
}
static int r600_do_wait_for_idle(drm_radeon_private_t *dev_priv)
{
int i, ret;
dev_priv->stats.boxes |= RADEON_BOX_WAIT_IDLE;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770)
ret = r600_do_wait_for_fifo(dev_priv, 8);
else
ret = r600_do_wait_for_fifo(dev_priv, 16);
if (ret)
return ret;
for (i = 0; i < dev_priv->usec_timeout; i++) {
if (!(RADEON_READ(R600_GRBM_STATUS) & R600_GUI_ACTIVE))
return 0;
DRM_UDELAY(1);
}
DRM_INFO("wait idle failed status : 0x%08X 0x%08X\n",
RADEON_READ(R600_GRBM_STATUS),
RADEON_READ(R600_GRBM_STATUS2));
return -EBUSY;
}
void r600_page_table_cleanup(struct drm_device *dev, struct drm_ati_pcigart_info *gart_info)
{
struct drm_sg_mem *entry = dev->sg;
int max_pages;
int pages;
int i;
if (!entry)
return;
if (gart_info->bus_addr) {
max_pages = (gart_info->table_size / sizeof(u64));
pages = (entry->pages <= max_pages)
? entry->pages : max_pages;
for (i = 0; i < pages; i++) {
if (!entry->busaddr[i])
break;
pci_unmap_page(dev->pdev, entry->busaddr[i],
PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
}
if (gart_info->gart_table_location == DRM_ATI_GART_MAIN)
gart_info->bus_addr = 0;
}
}
/* R600 has page table setup */
int r600_page_table_init(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
struct drm_ati_pcigart_info *gart_info = &dev_priv->gart_info;
struct drm_local_map *map = &gart_info->mapping;
struct drm_sg_mem *entry = dev->sg;
int ret = 0;
int i, j;
int pages;
u64 page_base;
dma_addr_t entry_addr;
int max_ati_pages, max_real_pages, gart_idx;
/* okay page table is available - lets rock */
max_ati_pages = (gart_info->table_size / sizeof(u64));
max_real_pages = max_ati_pages / (PAGE_SIZE / ATI_PCIGART_PAGE_SIZE);
pages = (entry->pages <= max_real_pages) ?
entry->pages : max_real_pages;
memset_io((void __iomem *)map->handle, 0, max_ati_pages * sizeof(u64));
gart_idx = 0;
for (i = 0; i < pages; i++) {
entry->busaddr[i] = pci_map_page(dev->pdev,
entry->pagelist[i], 0,
PAGE_SIZE,
PCI_DMA_BIDIRECTIONAL);
if (entry->busaddr[i] == 0) {
DRM_ERROR("unable to map PCIGART pages!\n");
r600_page_table_cleanup(dev, gart_info);
goto done;
}
entry_addr = entry->busaddr[i];
for (j = 0; j < (PAGE_SIZE / ATI_PCIGART_PAGE_SIZE); j++) {
page_base = (u64) entry_addr & ATI_PCIGART_PAGE_MASK;
page_base |= R600_PTE_VALID | R600_PTE_SYSTEM | R600_PTE_SNOOPED;
page_base |= R600_PTE_READABLE | R600_PTE_WRITEABLE;
DRM_WRITE64(map, gart_idx * sizeof(u64), page_base);
gart_idx++;
if ((i % 128) == 0)
DRM_DEBUG("page entry %d: 0x%016llx\n",
i, (unsigned long long)page_base);
entry_addr += ATI_PCIGART_PAGE_SIZE;
}
}
ret = 1;
done:
return ret;
}
static void r600_vm_flush_gart_range(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
u32 resp, countdown = 1000;
RADEON_WRITE(R600_VM_CONTEXT0_INVALIDATION_LOW_ADDR, dev_priv->gart_vm_start >> 12);
RADEON_WRITE(R600_VM_CONTEXT0_INVALIDATION_HIGH_ADDR, (dev_priv->gart_vm_start + dev_priv->gart_size - 1) >> 12);
RADEON_WRITE(R600_VM_CONTEXT0_REQUEST_RESPONSE, 2);
do {
resp = RADEON_READ(R600_VM_CONTEXT0_REQUEST_RESPONSE);
countdown--;
DRM_UDELAY(1);
} while (((resp & 0xf0) == 0) && countdown);
}
static void r600_vm_init(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
/* initialise the VM to use the page table we constructed up there */
u32 vm_c0, i;
u32 mc_rd_a;
u32 vm_l2_cntl, vm_l2_cntl3;
/* okay set up the PCIE aperture type thingo */
RADEON_WRITE(R600_MC_VM_SYSTEM_APERTURE_LOW_ADDR, dev_priv->gart_vm_start >> 12);
RADEON_WRITE(R600_MC_VM_SYSTEM_APERTURE_HIGH_ADDR, (dev_priv->gart_vm_start + dev_priv->gart_size - 1) >> 12);
RADEON_WRITE(R600_MC_VM_SYSTEM_APERTURE_DEFAULT_ADDR, 0);
/* setup MC RD a */
mc_rd_a = R600_MCD_L1_TLB | R600_MCD_L1_FRAG_PROC | R600_MCD_SYSTEM_ACCESS_MODE_IN_SYS |
R600_MCD_SYSTEM_APERTURE_UNMAPPED_ACCESS_PASS_THRU | R600_MCD_EFFECTIVE_L1_TLB_SIZE(5) |
R600_MCD_EFFECTIVE_L1_QUEUE_SIZE(5) | R600_MCD_WAIT_L2_QUERY;
RADEON_WRITE(R600_MCD_RD_A_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_RD_B_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_WR_A_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_WR_B_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_RD_GFX_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_WR_GFX_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_RD_SYS_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_WR_SYS_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_RD_HDP_CNTL, mc_rd_a | R600_MCD_L1_STRICT_ORDERING);
RADEON_WRITE(R600_MCD_WR_HDP_CNTL, mc_rd_a /*| R600_MCD_L1_STRICT_ORDERING*/);
RADEON_WRITE(R600_MCD_RD_PDMA_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_WR_PDMA_CNTL, mc_rd_a);
RADEON_WRITE(R600_MCD_RD_SEM_CNTL, mc_rd_a | R600_MCD_SEMAPHORE_MODE);
RADEON_WRITE(R600_MCD_WR_SEM_CNTL, mc_rd_a);
vm_l2_cntl = R600_VM_L2_CACHE_EN | R600_VM_L2_FRAG_PROC | R600_VM_ENABLE_PTE_CACHE_LRU_W;
vm_l2_cntl |= R600_VM_L2_CNTL_QUEUE_SIZE(7);
RADEON_WRITE(R600_VM_L2_CNTL, vm_l2_cntl);
RADEON_WRITE(R600_VM_L2_CNTL2, 0);
vm_l2_cntl3 = (R600_VM_L2_CNTL3_BANK_SELECT_0(0) |
R600_VM_L2_CNTL3_BANK_SELECT_1(1) |
R600_VM_L2_CNTL3_CACHE_UPDATE_MODE(2));
RADEON_WRITE(R600_VM_L2_CNTL3, vm_l2_cntl3);
vm_c0 = R600_VM_ENABLE_CONTEXT | R600_VM_PAGE_TABLE_DEPTH_FLAT;
RADEON_WRITE(R600_VM_CONTEXT0_CNTL, vm_c0);
vm_c0 &= ~R600_VM_ENABLE_CONTEXT;
/* disable all other contexts */
for (i = 1; i < 8; i++)
RADEON_WRITE(R600_VM_CONTEXT0_CNTL + (i * 4), vm_c0);
RADEON_WRITE(R600_VM_CONTEXT0_PAGE_TABLE_BASE_ADDR, dev_priv->gart_info.bus_addr >> 12);
RADEON_WRITE(R600_VM_CONTEXT0_PAGE_TABLE_START_ADDR, dev_priv->gart_vm_start >> 12);
RADEON_WRITE(R600_VM_CONTEXT0_PAGE_TABLE_END_ADDR, (dev_priv->gart_vm_start + dev_priv->gart_size - 1) >> 12);
r600_vm_flush_gart_range(dev);
}
static int r600_cp_init_microcode(drm_radeon_private_t *dev_priv)
{
struct platform_device *pdev;
const char *chip_name;
size_t pfp_req_size, me_req_size;
char fw_name[30];
int err;
pdev = platform_device_register_simple("r600_cp", 0, NULL, 0);
err = IS_ERR(pdev);
if (err) {
printk(KERN_ERR "r600_cp: Failed to register firmware\n");
return -EINVAL;
}
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_R600: chip_name = "R600"; break;
case CHIP_RV610: chip_name = "RV610"; break;
case CHIP_RV630: chip_name = "RV630"; break;
case CHIP_RV620: chip_name = "RV620"; break;
case CHIP_RV635: chip_name = "RV635"; break;
case CHIP_RV670: chip_name = "RV670"; break;
case CHIP_RS780:
case CHIP_RS880: chip_name = "RS780"; break;
case CHIP_RV770: chip_name = "RV770"; break;
case CHIP_RV730:
case CHIP_RV740: chip_name = "RV730"; break;
case CHIP_RV710: chip_name = "RV710"; break;
default: BUG();
}
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770) {
pfp_req_size = R700_PFP_UCODE_SIZE * 4;
me_req_size = R700_PM4_UCODE_SIZE * 4;
} else {
pfp_req_size = PFP_UCODE_SIZE * 4;
me_req_size = PM4_UCODE_SIZE * 12;
}
DRM_INFO("Loading %s CP Microcode\n", chip_name);
snprintf(fw_name, sizeof(fw_name), "radeon/%s_pfp.bin", chip_name);
err = request_firmware(&dev_priv->pfp_fw, fw_name, &pdev->dev);
if (err)
goto out;
if (dev_priv->pfp_fw->size != pfp_req_size) {
printk(KERN_ERR
"r600_cp: Bogus length %zu in firmware \"%s\"\n",
dev_priv->pfp_fw->size, fw_name);
err = -EINVAL;
goto out;
}
snprintf(fw_name, sizeof(fw_name), "radeon/%s_me.bin", chip_name);
err = request_firmware(&dev_priv->me_fw, fw_name, &pdev->dev);
if (err)
goto out;
if (dev_priv->me_fw->size != me_req_size) {
printk(KERN_ERR
"r600_cp: Bogus length %zu in firmware \"%s\"\n",
dev_priv->me_fw->size, fw_name);
err = -EINVAL;
}
out:
platform_device_unregister(pdev);
if (err) {
if (err != -EINVAL)
printk(KERN_ERR
"r600_cp: Failed to load firmware \"%s\"\n",
fw_name);
release_firmware(dev_priv->pfp_fw);
dev_priv->pfp_fw = NULL;
release_firmware(dev_priv->me_fw);
dev_priv->me_fw = NULL;
}
return err;
}
static void r600_cp_load_microcode(drm_radeon_private_t *dev_priv)
{
const __be32 *fw_data;
int i;
if (!dev_priv->me_fw || !dev_priv->pfp_fw)
return;
r600_do_cp_stop(dev_priv);
RADEON_WRITE(R600_CP_RB_CNTL,
R600_RB_NO_UPDATE |
R600_RB_BLKSZ(15) |
R600_RB_BUFSZ(3));
RADEON_WRITE(R600_GRBM_SOFT_RESET, R600_SOFT_RESET_CP);
RADEON_READ(R600_GRBM_SOFT_RESET);
DRM_UDELAY(15000);
RADEON_WRITE(R600_GRBM_SOFT_RESET, 0);
fw_data = (const __be32 *)dev_priv->me_fw->data;
RADEON_WRITE(R600_CP_ME_RAM_WADDR, 0);
for (i = 0; i < PM4_UCODE_SIZE * 3; i++)
RADEON_WRITE(R600_CP_ME_RAM_DATA,
be32_to_cpup(fw_data++));
fw_data = (const __be32 *)dev_priv->pfp_fw->data;
RADEON_WRITE(R600_CP_PFP_UCODE_ADDR, 0);
for (i = 0; i < PFP_UCODE_SIZE; i++)
RADEON_WRITE(R600_CP_PFP_UCODE_DATA,
be32_to_cpup(fw_data++));
RADEON_WRITE(R600_CP_PFP_UCODE_ADDR, 0);
RADEON_WRITE(R600_CP_ME_RAM_WADDR, 0);
RADEON_WRITE(R600_CP_ME_RAM_RADDR, 0);
}
static void r700_vm_init(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
/* initialise the VM to use the page table we constructed up there */
u32 vm_c0, i;
u32 mc_vm_md_l1;
u32 vm_l2_cntl, vm_l2_cntl3;
/* okay set up the PCIE aperture type thingo */
RADEON_WRITE(R700_MC_VM_SYSTEM_APERTURE_LOW_ADDR, dev_priv->gart_vm_start >> 12);
RADEON_WRITE(R700_MC_VM_SYSTEM_APERTURE_HIGH_ADDR, (dev_priv->gart_vm_start + dev_priv->gart_size - 1) >> 12);
RADEON_WRITE(R700_MC_VM_SYSTEM_APERTURE_DEFAULT_ADDR, 0);
mc_vm_md_l1 = R700_ENABLE_L1_TLB |
R700_ENABLE_L1_FRAGMENT_PROCESSING |
R700_SYSTEM_ACCESS_MODE_IN_SYS |
R700_SYSTEM_APERTURE_UNMAPPED_ACCESS_PASS_THRU |
R700_EFFECTIVE_L1_TLB_SIZE(5) |
R700_EFFECTIVE_L1_QUEUE_SIZE(5);
RADEON_WRITE(R700_MC_VM_MD_L1_TLB0_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MD_L1_TLB1_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MD_L1_TLB2_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MB_L1_TLB0_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MB_L1_TLB1_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MB_L1_TLB2_CNTL, mc_vm_md_l1);
RADEON_WRITE(R700_MC_VM_MB_L1_TLB3_CNTL, mc_vm_md_l1);
vm_l2_cntl = R600_VM_L2_CACHE_EN | R600_VM_L2_FRAG_PROC | R600_VM_ENABLE_PTE_CACHE_LRU_W;
vm_l2_cntl |= R700_VM_L2_CNTL_QUEUE_SIZE(7);
RADEON_WRITE(R600_VM_L2_CNTL, vm_l2_cntl);
RADEON_WRITE(R600_VM_L2_CNTL2, 0);
vm_l2_cntl3 = R700_VM_L2_CNTL3_BANK_SELECT(0) | R700_VM_L2_CNTL3_CACHE_UPDATE_MODE(2);
RADEON_WRITE(R600_VM_L2_CNTL3, vm_l2_cntl3);
vm_c0 = R600_VM_ENABLE_CONTEXT | R600_VM_PAGE_TABLE_DEPTH_FLAT;
RADEON_WRITE(R600_VM_CONTEXT0_CNTL, vm_c0);
vm_c0 &= ~R600_VM_ENABLE_CONTEXT;
/* disable all other contexts */
for (i = 1; i < 8; i++)
RADEON_WRITE(R600_VM_CONTEXT0_CNTL + (i * 4), vm_c0);
RADEON_WRITE(R700_VM_CONTEXT0_PAGE_TABLE_BASE_ADDR, dev_priv->gart_info.bus_addr >> 12);
RADEON_WRITE(R700_VM_CONTEXT0_PAGE_TABLE_START_ADDR, dev_priv->gart_vm_start >> 12);
RADEON_WRITE(R700_VM_CONTEXT0_PAGE_TABLE_END_ADDR, (dev_priv->gart_vm_start + dev_priv->gart_size - 1) >> 12);
r600_vm_flush_gart_range(dev);
}
static void r700_cp_load_microcode(drm_radeon_private_t *dev_priv)
{
const __be32 *fw_data;
int i;
if (!dev_priv->me_fw || !dev_priv->pfp_fw)
return;
r600_do_cp_stop(dev_priv);
RADEON_WRITE(R600_CP_RB_CNTL,
R600_RB_NO_UPDATE |
(15 << 8) |
(3 << 0));
RADEON_WRITE(R600_GRBM_SOFT_RESET, R600_SOFT_RESET_CP);
RADEON_READ(R600_GRBM_SOFT_RESET);
DRM_UDELAY(15000);
RADEON_WRITE(R600_GRBM_SOFT_RESET, 0);
fw_data = (const __be32 *)dev_priv->pfp_fw->data;
RADEON_WRITE(R600_CP_PFP_UCODE_ADDR, 0);
for (i = 0; i < R700_PFP_UCODE_SIZE; i++)
RADEON_WRITE(R600_CP_PFP_UCODE_DATA, be32_to_cpup(fw_data++));
RADEON_WRITE(R600_CP_PFP_UCODE_ADDR, 0);
fw_data = (const __be32 *)dev_priv->me_fw->data;
RADEON_WRITE(R600_CP_ME_RAM_WADDR, 0);
for (i = 0; i < R700_PM4_UCODE_SIZE; i++)
RADEON_WRITE(R600_CP_ME_RAM_DATA, be32_to_cpup(fw_data++));
RADEON_WRITE(R600_CP_ME_RAM_WADDR, 0);
RADEON_WRITE(R600_CP_PFP_UCODE_ADDR, 0);
RADEON_WRITE(R600_CP_ME_RAM_WADDR, 0);
RADEON_WRITE(R600_CP_ME_RAM_RADDR, 0);
}
static void r600_test_writeback(drm_radeon_private_t *dev_priv)
{
u32 tmp;
/* Start with assuming that writeback doesn't work */
dev_priv->writeback_works = 0;
/* Writeback doesn't seem to work everywhere, test it here and possibly
* enable it if it appears to work
*/
radeon_write_ring_rptr(dev_priv, R600_SCRATCHOFF(1), 0);
RADEON_WRITE(R600_SCRATCH_REG1, 0xdeadbeef);
for (tmp = 0; tmp < dev_priv->usec_timeout; tmp++) {
u32 val;
val = radeon_read_ring_rptr(dev_priv, R600_SCRATCHOFF(1));
if (val == 0xdeadbeef)
break;
DRM_UDELAY(1);
}
if (tmp < dev_priv->usec_timeout) {
dev_priv->writeback_works = 1;
DRM_INFO("writeback test succeeded in %d usecs\n", tmp);
} else {
dev_priv->writeback_works = 0;
DRM_INFO("writeback test failed\n");
}
if (radeon_no_wb == 1) {
dev_priv->writeback_works = 0;
DRM_INFO("writeback forced off\n");
}
if (!dev_priv->writeback_works) {
/* Disable writeback to avoid unnecessary bus master transfer */
RADEON_WRITE(R600_CP_RB_CNTL, RADEON_READ(R600_CP_RB_CNTL) |
RADEON_RB_NO_UPDATE);
RADEON_WRITE(R600_SCRATCH_UMSK, 0);
}
}
int r600_do_engine_reset(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
u32 cp_ptr, cp_me_cntl, cp_rb_cntl;
DRM_INFO("Resetting GPU\n");
cp_ptr = RADEON_READ(R600_CP_RB_WPTR);
cp_me_cntl = RADEON_READ(R600_CP_ME_CNTL);
RADEON_WRITE(R600_CP_ME_CNTL, R600_CP_ME_HALT);
RADEON_WRITE(R600_GRBM_SOFT_RESET, 0x7fff);
RADEON_READ(R600_GRBM_SOFT_RESET);
DRM_UDELAY(50);
RADEON_WRITE(R600_GRBM_SOFT_RESET, 0);
RADEON_READ(R600_GRBM_SOFT_RESET);
RADEON_WRITE(R600_CP_RB_WPTR_DELAY, 0);
cp_rb_cntl = RADEON_READ(R600_CP_RB_CNTL);
RADEON_WRITE(R600_CP_RB_CNTL, R600_RB_RPTR_WR_ENA);
RADEON_WRITE(R600_CP_RB_RPTR_WR, cp_ptr);
RADEON_WRITE(R600_CP_RB_WPTR, cp_ptr);
RADEON_WRITE(R600_CP_RB_CNTL, cp_rb_cntl);
RADEON_WRITE(R600_CP_ME_CNTL, cp_me_cntl);
/* Reset the CP ring */
r600_do_cp_reset(dev_priv);
/* The CP is no longer running after an engine reset */
dev_priv->cp_running = 0;
/* Reset any pending vertex, indirect buffers */
radeon_freelist_reset(dev);
return 0;
}
static u32 r600_get_tile_pipe_to_backend_map(u32 num_tile_pipes,
u32 num_backends,
u32 backend_disable_mask)
{
u32 backend_map = 0;
u32 enabled_backends_mask;
u32 enabled_backends_count;
u32 cur_pipe;
u32 swizzle_pipe[R6XX_MAX_PIPES];
u32 cur_backend;
u32 i;
if (num_tile_pipes > R6XX_MAX_PIPES)
num_tile_pipes = R6XX_MAX_PIPES;
if (num_tile_pipes < 1)
num_tile_pipes = 1;
if (num_backends > R6XX_MAX_BACKENDS)
num_backends = R6XX_MAX_BACKENDS;
if (num_backends < 1)
num_backends = 1;
enabled_backends_mask = 0;
enabled_backends_count = 0;
for (i = 0; i < R6XX_MAX_BACKENDS; ++i) {
if (((backend_disable_mask >> i) & 1) == 0) {
enabled_backends_mask |= (1 << i);
++enabled_backends_count;
}
if (enabled_backends_count == num_backends)
break;
}
if (enabled_backends_count == 0) {
enabled_backends_mask = 1;
enabled_backends_count = 1;
}
if (enabled_backends_count != num_backends)
num_backends = enabled_backends_count;
memset((uint8_t *)&swizzle_pipe[0], 0, sizeof(u32) * R6XX_MAX_PIPES);
switch (num_tile_pipes) {
case 1:
swizzle_pipe[0] = 0;
break;
case 2:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
break;
case 3:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
break;
case 4:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
break;
case 5:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
swizzle_pipe[4] = 4;
break;
case 6:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 5;
swizzle_pipe[4] = 1;
swizzle_pipe[5] = 3;
break;
case 7:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 6;
swizzle_pipe[4] = 1;
swizzle_pipe[5] = 3;
swizzle_pipe[6] = 5;
break;
case 8:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 6;
swizzle_pipe[4] = 1;
swizzle_pipe[5] = 3;
swizzle_pipe[6] = 5;
swizzle_pipe[7] = 7;
break;
}
cur_backend = 0;
for (cur_pipe = 0; cur_pipe < num_tile_pipes; ++cur_pipe) {
while (((1 << cur_backend) & enabled_backends_mask) == 0)
cur_backend = (cur_backend + 1) % R6XX_MAX_BACKENDS;
backend_map |= (u32)(((cur_backend & 3) << (swizzle_pipe[cur_pipe] * 2)));
cur_backend = (cur_backend + 1) % R6XX_MAX_BACKENDS;
}
return backend_map;
}
static int r600_count_pipe_bits(uint32_t val)
{
int i, ret = 0;
for (i = 0; i < 32; i++) {
ret += val & 1;
val >>= 1;
}
return ret;
}
static void r600_gfx_init(struct drm_device *dev,
drm_radeon_private_t *dev_priv)
{
int i, j, num_qd_pipes;
u32 sx_debug_1;
u32 tc_cntl;
u32 arb_pop;
u32 num_gs_verts_per_thread;
u32 vgt_gs_per_es;
u32 gs_prim_buffer_depth = 0;
u32 sq_ms_fifo_sizes;
u32 sq_config;
u32 sq_gpr_resource_mgmt_1 = 0;
u32 sq_gpr_resource_mgmt_2 = 0;
u32 sq_thread_resource_mgmt = 0;
u32 sq_stack_resource_mgmt_1 = 0;
u32 sq_stack_resource_mgmt_2 = 0;
u32 hdp_host_path_cntl;
u32 backend_map;
u32 gb_tiling_config = 0;
u32 cc_rb_backend_disable;
u32 cc_gc_shader_pipe_config;
u32 ramcfg;
/* setup chip specs */
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_R600:
dev_priv->r600_max_pipes = 4;
dev_priv->r600_max_tile_pipes = 8;
dev_priv->r600_max_simds = 4;
dev_priv->r600_max_backends = 4;
dev_priv->r600_max_gprs = 256;
dev_priv->r600_max_threads = 192;
dev_priv->r600_max_stack_entries = 256;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 16;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 128;
dev_priv->r600_sq_num_cf_insts = 2;
break;
case CHIP_RV630:
case CHIP_RV635:
dev_priv->r600_max_pipes = 2;
dev_priv->r600_max_tile_pipes = 2;
dev_priv->r600_max_simds = 3;
dev_priv->r600_max_backends = 1;
dev_priv->r600_max_gprs = 128;
dev_priv->r600_max_threads = 192;
dev_priv->r600_max_stack_entries = 128;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 4;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 128;
dev_priv->r600_sq_num_cf_insts = 2;
break;
case CHIP_RV610:
case CHIP_RS780:
case CHIP_RS880:
case CHIP_RV620:
dev_priv->r600_max_pipes = 1;
dev_priv->r600_max_tile_pipes = 1;
dev_priv->r600_max_simds = 2;
dev_priv->r600_max_backends = 1;
dev_priv->r600_max_gprs = 128;
dev_priv->r600_max_threads = 192;
dev_priv->r600_max_stack_entries = 128;
dev_priv->r600_max_hw_contexts = 4;
dev_priv->r600_max_gs_threads = 4;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 128;
dev_priv->r600_sq_num_cf_insts = 1;
break;
case CHIP_RV670:
dev_priv->r600_max_pipes = 4;
dev_priv->r600_max_tile_pipes = 4;
dev_priv->r600_max_simds = 4;
dev_priv->r600_max_backends = 4;
dev_priv->r600_max_gprs = 192;
dev_priv->r600_max_threads = 192;
dev_priv->r600_max_stack_entries = 256;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 16;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 128;
dev_priv->r600_sq_num_cf_insts = 2;
break;
default:
break;
}
/* Initialize HDP */
j = 0;
for (i = 0; i < 32; i++) {
RADEON_WRITE((0x2c14 + j), 0x00000000);
RADEON_WRITE((0x2c18 + j), 0x00000000);
RADEON_WRITE((0x2c1c + j), 0x00000000);
RADEON_WRITE((0x2c20 + j), 0x00000000);
RADEON_WRITE((0x2c24 + j), 0x00000000);
j += 0x18;
}
RADEON_WRITE(R600_GRBM_CNTL, R600_GRBM_READ_TIMEOUT(0xff));
/* setup tiling, simd, pipe config */
ramcfg = RADEON_READ(R600_RAMCFG);
switch (dev_priv->r600_max_tile_pipes) {
case 1:
gb_tiling_config |= R600_PIPE_TILING(0);
break;
case 2:
gb_tiling_config |= R600_PIPE_TILING(1);
break;
case 4:
gb_tiling_config |= R600_PIPE_TILING(2);
break;
case 8:
gb_tiling_config |= R600_PIPE_TILING(3);
break;
default:
break;
}
gb_tiling_config |= R600_BANK_TILING((ramcfg >> R600_NOOFBANK_SHIFT) & R600_NOOFBANK_MASK);
gb_tiling_config |= R600_GROUP_SIZE(0);
if (((ramcfg >> R600_NOOFROWS_SHIFT) & R600_NOOFROWS_MASK) > 3) {
gb_tiling_config |= R600_ROW_TILING(3);
gb_tiling_config |= R600_SAMPLE_SPLIT(3);
} else {
gb_tiling_config |=
R600_ROW_TILING(((ramcfg >> R600_NOOFROWS_SHIFT) & R600_NOOFROWS_MASK));
gb_tiling_config |=
R600_SAMPLE_SPLIT(((ramcfg >> R600_NOOFROWS_SHIFT) & R600_NOOFROWS_MASK));
}
gb_tiling_config |= R600_BANK_SWAPS(1);
cc_rb_backend_disable = RADEON_READ(R600_CC_RB_BACKEND_DISABLE) & 0x00ff0000;
cc_rb_backend_disable |=
R600_BACKEND_DISABLE((R6XX_MAX_BACKENDS_MASK << dev_priv->r600_max_backends) & R6XX_MAX_BACKENDS_MASK);
cc_gc_shader_pipe_config = RADEON_READ(R600_CC_GC_SHADER_PIPE_CONFIG) & 0xffffff00;
cc_gc_shader_pipe_config |=
R600_INACTIVE_QD_PIPES((R6XX_MAX_PIPES_MASK << dev_priv->r600_max_pipes) & R6XX_MAX_PIPES_MASK);
cc_gc_shader_pipe_config |=
R600_INACTIVE_SIMDS((R6XX_MAX_SIMDS_MASK << dev_priv->r600_max_simds) & R6XX_MAX_SIMDS_MASK);
backend_map = r600_get_tile_pipe_to_backend_map(dev_priv->r600_max_tile_pipes,
(R6XX_MAX_BACKENDS -
r600_count_pipe_bits((cc_rb_backend_disable &
R6XX_MAX_BACKENDS_MASK) >> 16)),
(cc_rb_backend_disable >> 16));
gb_tiling_config |= R600_BACKEND_MAP(backend_map);
RADEON_WRITE(R600_GB_TILING_CONFIG, gb_tiling_config);
RADEON_WRITE(R600_DCP_TILING_CONFIG, (gb_tiling_config & 0xffff));
RADEON_WRITE(R600_HDP_TILING_CONFIG, (gb_tiling_config & 0xffff));
if (gb_tiling_config & 0xc0) {
dev_priv->r600_group_size = 512;
} else {
dev_priv->r600_group_size = 256;
}
dev_priv->r600_npipes = 1 << ((gb_tiling_config >> 1) & 0x7);
if (gb_tiling_config & 0x30) {
dev_priv->r600_nbanks = 8;
} else {
dev_priv->r600_nbanks = 4;
}
RADEON_WRITE(R600_CC_RB_BACKEND_DISABLE, cc_rb_backend_disable);
RADEON_WRITE(R600_CC_GC_SHADER_PIPE_CONFIG, cc_gc_shader_pipe_config);
RADEON_WRITE(R600_GC_USER_SHADER_PIPE_CONFIG, cc_gc_shader_pipe_config);
num_qd_pipes =
R6XX_MAX_PIPES - r600_count_pipe_bits((cc_gc_shader_pipe_config & R600_INACTIVE_QD_PIPES_MASK) >> 8);
RADEON_WRITE(R600_VGT_OUT_DEALLOC_CNTL, (num_qd_pipes * 4) & R600_DEALLOC_DIST_MASK);
RADEON_WRITE(R600_VGT_VERTEX_REUSE_BLOCK_CNTL, ((num_qd_pipes * 4) - 2) & R600_VTX_REUSE_DEPTH_MASK);
/* set HW defaults for 3D engine */
RADEON_WRITE(R600_CP_QUEUE_THRESHOLDS, (R600_ROQ_IB1_START(0x16) |
R600_ROQ_IB2_START(0x2b)));
RADEON_WRITE(R600_CP_MEQ_THRESHOLDS, (R600_MEQ_END(0x40) |
R600_ROQ_END(0x40)));
RADEON_WRITE(R600_TA_CNTL_AUX, (R600_DISABLE_CUBE_ANISO |
R600_SYNC_GRADIENT |
R600_SYNC_WALKER |
R600_SYNC_ALIGNER));
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV670)
RADEON_WRITE(R600_ARB_GDEC_RD_CNTL, 0x00000021);
sx_debug_1 = RADEON_READ(R600_SX_DEBUG_1);
sx_debug_1 |= R600_SMX_EVENT_RELEASE;
if (((dev_priv->flags & RADEON_FAMILY_MASK) > CHIP_R600))
sx_debug_1 |= R600_ENABLE_NEW_SMX_ADDRESS;
RADEON_WRITE(R600_SX_DEBUG_1, sx_debug_1);
if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_R600) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV630) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880))
RADEON_WRITE(R600_DB_DEBUG, R600_PREZ_MUST_WAIT_FOR_POSTZ_DONE);
else
RADEON_WRITE(R600_DB_DEBUG, 0);
RADEON_WRITE(R600_DB_WATERMARKS, (R600_DEPTH_FREE(4) |
R600_DEPTH_FLUSH(16) |
R600_DEPTH_PENDING_FREE(4) |
R600_DEPTH_CACHELINE_FREE(16)));
RADEON_WRITE(R600_PA_SC_MULTI_CHIP_CNTL, 0);
RADEON_WRITE(R600_VGT_NUM_INSTANCES, 0);
RADEON_WRITE(R600_SPI_CONFIG_CNTL, R600_GPR_WRITE_PRIORITY(0));
RADEON_WRITE(R600_SPI_CONFIG_CNTL_1, R600_VTX_DONE_DELAY(0));
sq_ms_fifo_sizes = RADEON_READ(R600_SQ_MS_FIFO_SIZES);
if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880)) {
sq_ms_fifo_sizes = (R600_CACHE_FIFO_SIZE(0xa) |
R600_FETCH_FIFO_HIWATER(0xa) |
R600_DONE_FIFO_HIWATER(0xe0) |
R600_ALU_UPDATE_FIFO_HIWATER(0x8));
} else if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_R600) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV630)) {
sq_ms_fifo_sizes &= ~R600_DONE_FIFO_HIWATER(0xff);
sq_ms_fifo_sizes |= R600_DONE_FIFO_HIWATER(0x4);
}
RADEON_WRITE(R600_SQ_MS_FIFO_SIZES, sq_ms_fifo_sizes);
/* SQ_CONFIG, SQ_GPR_RESOURCE_MGMT, SQ_THREAD_RESOURCE_MGMT, SQ_STACK_RESOURCE_MGMT
* should be adjusted as needed by the 2D/3D drivers. This just sets default values
*/
sq_config = RADEON_READ(R600_SQ_CONFIG);
sq_config &= ~(R600_PS_PRIO(3) |
R600_VS_PRIO(3) |
R600_GS_PRIO(3) |
R600_ES_PRIO(3));
sq_config |= (R600_DX9_CONSTS |
R600_VC_ENABLE |
R600_PS_PRIO(0) |
R600_VS_PRIO(1) |
R600_GS_PRIO(2) |
R600_ES_PRIO(3));
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_R600) {
sq_gpr_resource_mgmt_1 = (R600_NUM_PS_GPRS(124) |
R600_NUM_VS_GPRS(124) |
R600_NUM_CLAUSE_TEMP_GPRS(4));
sq_gpr_resource_mgmt_2 = (R600_NUM_GS_GPRS(0) |
R600_NUM_ES_GPRS(0));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS(136) |
R600_NUM_VS_THREADS(48) |
R600_NUM_GS_THREADS(4) |
R600_NUM_ES_THREADS(4));
sq_stack_resource_mgmt_1 = (R600_NUM_PS_STACK_ENTRIES(128) |
R600_NUM_VS_STACK_ENTRIES(128));
sq_stack_resource_mgmt_2 = (R600_NUM_GS_STACK_ENTRIES(0) |
R600_NUM_ES_STACK_ENTRIES(0));
} else if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880)) {
/* no vertex cache */
sq_config &= ~R600_VC_ENABLE;
sq_gpr_resource_mgmt_1 = (R600_NUM_PS_GPRS(44) |
R600_NUM_VS_GPRS(44) |
R600_NUM_CLAUSE_TEMP_GPRS(2));
sq_gpr_resource_mgmt_2 = (R600_NUM_GS_GPRS(17) |
R600_NUM_ES_GPRS(17));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS(79) |
R600_NUM_VS_THREADS(78) |
R600_NUM_GS_THREADS(4) |
R600_NUM_ES_THREADS(31));
sq_stack_resource_mgmt_1 = (R600_NUM_PS_STACK_ENTRIES(40) |
R600_NUM_VS_STACK_ENTRIES(40));
sq_stack_resource_mgmt_2 = (R600_NUM_GS_STACK_ENTRIES(32) |
R600_NUM_ES_STACK_ENTRIES(16));
} else if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV630) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV635)) {
sq_gpr_resource_mgmt_1 = (R600_NUM_PS_GPRS(44) |
R600_NUM_VS_GPRS(44) |
R600_NUM_CLAUSE_TEMP_GPRS(2));
sq_gpr_resource_mgmt_2 = (R600_NUM_GS_GPRS(18) |
R600_NUM_ES_GPRS(18));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS(79) |
R600_NUM_VS_THREADS(78) |
R600_NUM_GS_THREADS(4) |
R600_NUM_ES_THREADS(31));
sq_stack_resource_mgmt_1 = (R600_NUM_PS_STACK_ENTRIES(40) |
R600_NUM_VS_STACK_ENTRIES(40));
sq_stack_resource_mgmt_2 = (R600_NUM_GS_STACK_ENTRIES(32) |
R600_NUM_ES_STACK_ENTRIES(16));
} else if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV670) {
sq_gpr_resource_mgmt_1 = (R600_NUM_PS_GPRS(44) |
R600_NUM_VS_GPRS(44) |
R600_NUM_CLAUSE_TEMP_GPRS(2));
sq_gpr_resource_mgmt_2 = (R600_NUM_GS_GPRS(17) |
R600_NUM_ES_GPRS(17));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS(79) |
R600_NUM_VS_THREADS(78) |
R600_NUM_GS_THREADS(4) |
R600_NUM_ES_THREADS(31));
sq_stack_resource_mgmt_1 = (R600_NUM_PS_STACK_ENTRIES(64) |
R600_NUM_VS_STACK_ENTRIES(64));
sq_stack_resource_mgmt_2 = (R600_NUM_GS_STACK_ENTRIES(64) |
R600_NUM_ES_STACK_ENTRIES(64));
}
RADEON_WRITE(R600_SQ_CONFIG, sq_config);
RADEON_WRITE(R600_SQ_GPR_RESOURCE_MGMT_1, sq_gpr_resource_mgmt_1);
RADEON_WRITE(R600_SQ_GPR_RESOURCE_MGMT_2, sq_gpr_resource_mgmt_2);
RADEON_WRITE(R600_SQ_THREAD_RESOURCE_MGMT, sq_thread_resource_mgmt);
RADEON_WRITE(R600_SQ_STACK_RESOURCE_MGMT_1, sq_stack_resource_mgmt_1);
RADEON_WRITE(R600_SQ_STACK_RESOURCE_MGMT_2, sq_stack_resource_mgmt_2);
if (((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV610) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV620) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS780) ||
((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RS880))
RADEON_WRITE(R600_VGT_CACHE_INVALIDATION, R600_CACHE_INVALIDATION(R600_TC_ONLY));
else
RADEON_WRITE(R600_VGT_CACHE_INVALIDATION, R600_CACHE_INVALIDATION(R600_VC_AND_TC));
RADEON_WRITE(R600_PA_SC_AA_SAMPLE_LOCS_2S, (R600_S0_X(0xc) |
R600_S0_Y(0x4) |
R600_S1_X(0x4) |
R600_S1_Y(0xc)));
RADEON_WRITE(R600_PA_SC_AA_SAMPLE_LOCS_4S, (R600_S0_X(0xe) |
R600_S0_Y(0xe) |
R600_S1_X(0x2) |
R600_S1_Y(0x2) |
R600_S2_X(0xa) |
R600_S2_Y(0x6) |
R600_S3_X(0x6) |
R600_S3_Y(0xa)));
RADEON_WRITE(R600_PA_SC_AA_SAMPLE_LOCS_8S_WD0, (R600_S0_X(0xe) |
R600_S0_Y(0xb) |
R600_S1_X(0x4) |
R600_S1_Y(0xc) |
R600_S2_X(0x1) |
R600_S2_Y(0x6) |
R600_S3_X(0xa) |
R600_S3_Y(0xe)));
RADEON_WRITE(R600_PA_SC_AA_SAMPLE_LOCS_8S_WD1, (R600_S4_X(0x6) |
R600_S4_Y(0x1) |
R600_S5_X(0x0) |
R600_S5_Y(0x0) |
R600_S6_X(0xb) |
R600_S6_Y(0x4) |
R600_S7_X(0x7) |
R600_S7_Y(0x8)));
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_R600:
case CHIP_RV630:
case CHIP_RV635:
gs_prim_buffer_depth = 0;
break;
case CHIP_RV610:
case CHIP_RS780:
case CHIP_RS880:
case CHIP_RV620:
gs_prim_buffer_depth = 32;
break;
case CHIP_RV670:
gs_prim_buffer_depth = 128;
break;
default:
break;
}
num_gs_verts_per_thread = dev_priv->r600_max_pipes * 16;
vgt_gs_per_es = gs_prim_buffer_depth + num_gs_verts_per_thread;
/* Max value for this is 256 */
if (vgt_gs_per_es > 256)
vgt_gs_per_es = 256;
RADEON_WRITE(R600_VGT_ES_PER_GS, 128);
RADEON_WRITE(R600_VGT_GS_PER_ES, vgt_gs_per_es);
RADEON_WRITE(R600_VGT_GS_PER_VS, 2);
RADEON_WRITE(R600_VGT_GS_VERTEX_REUSE, 16);
/* more default values. 2D/3D driver should adjust as needed */
RADEON_WRITE(R600_PA_SC_LINE_STIPPLE_STATE, 0);
RADEON_WRITE(R600_VGT_STRMOUT_EN, 0);
RADEON_WRITE(R600_SX_MISC, 0);
RADEON_WRITE(R600_PA_SC_MODE_CNTL, 0);
RADEON_WRITE(R600_PA_SC_AA_CONFIG, 0);
RADEON_WRITE(R600_PA_SC_LINE_STIPPLE, 0);
RADEON_WRITE(R600_SPI_INPUT_Z, 0);
RADEON_WRITE(R600_SPI_PS_IN_CONTROL_0, R600_NUM_INTERP(2));
RADEON_WRITE(R600_CB_COLOR7_FRAG, 0);
/* clear render buffer base addresses */
RADEON_WRITE(R600_CB_COLOR0_BASE, 0);
RADEON_WRITE(R600_CB_COLOR1_BASE, 0);
RADEON_WRITE(R600_CB_COLOR2_BASE, 0);
RADEON_WRITE(R600_CB_COLOR3_BASE, 0);
RADEON_WRITE(R600_CB_COLOR4_BASE, 0);
RADEON_WRITE(R600_CB_COLOR5_BASE, 0);
RADEON_WRITE(R600_CB_COLOR6_BASE, 0);
RADEON_WRITE(R600_CB_COLOR7_BASE, 0);
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV610:
case CHIP_RS780:
case CHIP_RS880:
case CHIP_RV620:
tc_cntl = R600_TC_L2_SIZE(8);
break;
case CHIP_RV630:
case CHIP_RV635:
tc_cntl = R600_TC_L2_SIZE(4);
break;
case CHIP_R600:
tc_cntl = R600_TC_L2_SIZE(0) | R600_L2_DISABLE_LATE_HIT;
break;
default:
tc_cntl = R600_TC_L2_SIZE(0);
break;
}
RADEON_WRITE(R600_TC_CNTL, tc_cntl);
hdp_host_path_cntl = RADEON_READ(R600_HDP_HOST_PATH_CNTL);
RADEON_WRITE(R600_HDP_HOST_PATH_CNTL, hdp_host_path_cntl);
arb_pop = RADEON_READ(R600_ARB_POP);
arb_pop |= R600_ENABLE_TC128;
RADEON_WRITE(R600_ARB_POP, arb_pop);
RADEON_WRITE(R600_PA_SC_MULTI_CHIP_CNTL, 0);
RADEON_WRITE(R600_PA_CL_ENHANCE, (R600_CLIP_VTX_REORDER_ENA |
R600_NUM_CLIP_SEQ(3)));
RADEON_WRITE(R600_PA_SC_ENHANCE, R600_FORCE_EOV_MAX_CLK_CNT(4095));
}
static u32 r700_get_tile_pipe_to_backend_map(drm_radeon_private_t *dev_priv,
u32 num_tile_pipes,
u32 num_backends,
u32 backend_disable_mask)
{
u32 backend_map = 0;
u32 enabled_backends_mask;
u32 enabled_backends_count;
u32 cur_pipe;
u32 swizzle_pipe[R7XX_MAX_PIPES];
u32 cur_backend;
u32 i;
bool force_no_swizzle;
if (num_tile_pipes > R7XX_MAX_PIPES)
num_tile_pipes = R7XX_MAX_PIPES;
if (num_tile_pipes < 1)
num_tile_pipes = 1;
if (num_backends > R7XX_MAX_BACKENDS)
num_backends = R7XX_MAX_BACKENDS;
if (num_backends < 1)
num_backends = 1;
enabled_backends_mask = 0;
enabled_backends_count = 0;
for (i = 0; i < R7XX_MAX_BACKENDS; ++i) {
if (((backend_disable_mask >> i) & 1) == 0) {
enabled_backends_mask |= (1 << i);
++enabled_backends_count;
}
if (enabled_backends_count == num_backends)
break;
}
if (enabled_backends_count == 0) {
enabled_backends_mask = 1;
enabled_backends_count = 1;
}
if (enabled_backends_count != num_backends)
num_backends = enabled_backends_count;
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV770:
case CHIP_RV730:
force_no_swizzle = false;
break;
case CHIP_RV710:
case CHIP_RV740:
default:
force_no_swizzle = true;
break;
}
memset((uint8_t *)&swizzle_pipe[0], 0, sizeof(u32) * R7XX_MAX_PIPES);
switch (num_tile_pipes) {
case 1:
swizzle_pipe[0] = 0;
break;
case 2:
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
break;
case 3:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 1;
}
break;
case 4:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 3;
swizzle_pipe[3] = 1;
}
break;
case 5:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
swizzle_pipe[4] = 4;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 1;
swizzle_pipe[4] = 3;
}
break;
case 6:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
swizzle_pipe[4] = 4;
swizzle_pipe[5] = 5;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 5;
swizzle_pipe[4] = 3;
swizzle_pipe[5] = 1;
}
break;
case 7:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
swizzle_pipe[4] = 4;
swizzle_pipe[5] = 5;
swizzle_pipe[6] = 6;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 6;
swizzle_pipe[4] = 3;
swizzle_pipe[5] = 1;
swizzle_pipe[6] = 5;
}
break;
case 8:
if (force_no_swizzle) {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 1;
swizzle_pipe[2] = 2;
swizzle_pipe[3] = 3;
swizzle_pipe[4] = 4;
swizzle_pipe[5] = 5;
swizzle_pipe[6] = 6;
swizzle_pipe[7] = 7;
} else {
swizzle_pipe[0] = 0;
swizzle_pipe[1] = 2;
swizzle_pipe[2] = 4;
swizzle_pipe[3] = 6;
swizzle_pipe[4] = 3;
swizzle_pipe[5] = 1;
swizzle_pipe[6] = 7;
swizzle_pipe[7] = 5;
}
break;
}
cur_backend = 0;
for (cur_pipe = 0; cur_pipe < num_tile_pipes; ++cur_pipe) {
while (((1 << cur_backend) & enabled_backends_mask) == 0)
cur_backend = (cur_backend + 1) % R7XX_MAX_BACKENDS;
backend_map |= (u32)(((cur_backend & 3) << (swizzle_pipe[cur_pipe] * 2)));
cur_backend = (cur_backend + 1) % R7XX_MAX_BACKENDS;
}
return backend_map;
}
static void r700_gfx_init(struct drm_device *dev,
drm_radeon_private_t *dev_priv)
{
int i, j, num_qd_pipes;
u32 ta_aux_cntl;
u32 sx_debug_1;
u32 smx_dc_ctl0;
u32 db_debug3;
u32 num_gs_verts_per_thread;
u32 vgt_gs_per_es;
u32 gs_prim_buffer_depth = 0;
u32 sq_ms_fifo_sizes;
u32 sq_config;
u32 sq_thread_resource_mgmt;
u32 hdp_host_path_cntl;
u32 sq_dyn_gpr_size_simd_ab_0;
u32 backend_map;
u32 gb_tiling_config = 0;
u32 cc_rb_backend_disable;
u32 cc_gc_shader_pipe_config;
u32 mc_arb_ramcfg;
u32 db_debug4;
/* setup chip specs */
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV770:
dev_priv->r600_max_pipes = 4;
dev_priv->r600_max_tile_pipes = 8;
dev_priv->r600_max_simds = 10;
dev_priv->r600_max_backends = 4;
dev_priv->r600_max_gprs = 256;
dev_priv->r600_max_threads = 248;
dev_priv->r600_max_stack_entries = 512;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 16 * 2;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 112;
dev_priv->r600_sq_num_cf_insts = 2;
dev_priv->r700_sx_num_of_sets = 7;
dev_priv->r700_sc_prim_fifo_size = 0xF9;
dev_priv->r700_sc_hiz_tile_fifo_size = 0x30;
dev_priv->r700_sc_earlyz_tile_fifo_fize = 0x130;
break;
case CHIP_RV730:
dev_priv->r600_max_pipes = 2;
dev_priv->r600_max_tile_pipes = 4;
dev_priv->r600_max_simds = 8;
dev_priv->r600_max_backends = 2;
dev_priv->r600_max_gprs = 128;
dev_priv->r600_max_threads = 248;
dev_priv->r600_max_stack_entries = 256;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 16 * 2;
dev_priv->r600_sx_max_export_size = 256;
dev_priv->r600_sx_max_export_pos_size = 32;
dev_priv->r600_sx_max_export_smx_size = 224;
dev_priv->r600_sq_num_cf_insts = 2;
dev_priv->r700_sx_num_of_sets = 7;
dev_priv->r700_sc_prim_fifo_size = 0xf9;
dev_priv->r700_sc_hiz_tile_fifo_size = 0x30;
dev_priv->r700_sc_earlyz_tile_fifo_fize = 0x130;
if (dev_priv->r600_sx_max_export_pos_size > 16) {
dev_priv->r600_sx_max_export_pos_size -= 16;
dev_priv->r600_sx_max_export_smx_size += 16;
}
break;
case CHIP_RV710:
dev_priv->r600_max_pipes = 2;
dev_priv->r600_max_tile_pipes = 2;
dev_priv->r600_max_simds = 2;
dev_priv->r600_max_backends = 1;
dev_priv->r600_max_gprs = 256;
dev_priv->r600_max_threads = 192;
dev_priv->r600_max_stack_entries = 256;
dev_priv->r600_max_hw_contexts = 4;
dev_priv->r600_max_gs_threads = 8 * 2;
dev_priv->r600_sx_max_export_size = 128;
dev_priv->r600_sx_max_export_pos_size = 16;
dev_priv->r600_sx_max_export_smx_size = 112;
dev_priv->r600_sq_num_cf_insts = 1;
dev_priv->r700_sx_num_of_sets = 7;
dev_priv->r700_sc_prim_fifo_size = 0x40;
dev_priv->r700_sc_hiz_tile_fifo_size = 0x30;
dev_priv->r700_sc_earlyz_tile_fifo_fize = 0x130;
break;
case CHIP_RV740:
dev_priv->r600_max_pipes = 4;
dev_priv->r600_max_tile_pipes = 4;
dev_priv->r600_max_simds = 8;
dev_priv->r600_max_backends = 4;
dev_priv->r600_max_gprs = 256;
dev_priv->r600_max_threads = 248;
dev_priv->r600_max_stack_entries = 512;
dev_priv->r600_max_hw_contexts = 8;
dev_priv->r600_max_gs_threads = 16 * 2;
dev_priv->r600_sx_max_export_size = 256;
dev_priv->r600_sx_max_export_pos_size = 32;
dev_priv->r600_sx_max_export_smx_size = 224;
dev_priv->r600_sq_num_cf_insts = 2;
dev_priv->r700_sx_num_of_sets = 7;
dev_priv->r700_sc_prim_fifo_size = 0x100;
dev_priv->r700_sc_hiz_tile_fifo_size = 0x30;
dev_priv->r700_sc_earlyz_tile_fifo_fize = 0x130;
if (dev_priv->r600_sx_max_export_pos_size > 16) {
dev_priv->r600_sx_max_export_pos_size -= 16;
dev_priv->r600_sx_max_export_smx_size += 16;
}
break;
default:
break;
}
/* Initialize HDP */
j = 0;
for (i = 0; i < 32; i++) {
RADEON_WRITE((0x2c14 + j), 0x00000000);
RADEON_WRITE((0x2c18 + j), 0x00000000);
RADEON_WRITE((0x2c1c + j), 0x00000000);
RADEON_WRITE((0x2c20 + j), 0x00000000);
RADEON_WRITE((0x2c24 + j), 0x00000000);
j += 0x18;
}
RADEON_WRITE(R600_GRBM_CNTL, R600_GRBM_READ_TIMEOUT(0xff));
/* setup tiling, simd, pipe config */
mc_arb_ramcfg = RADEON_READ(R700_MC_ARB_RAMCFG);
switch (dev_priv->r600_max_tile_pipes) {
case 1:
gb_tiling_config |= R600_PIPE_TILING(0);
break;
case 2:
gb_tiling_config |= R600_PIPE_TILING(1);
break;
case 4:
gb_tiling_config |= R600_PIPE_TILING(2);
break;
case 8:
gb_tiling_config |= R600_PIPE_TILING(3);
break;
default:
break;
}
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV770)
gb_tiling_config |= R600_BANK_TILING(1);
else
gb_tiling_config |= R600_BANK_TILING((mc_arb_ramcfg >> R700_NOOFBANK_SHIFT) & R700_NOOFBANK_MASK);
gb_tiling_config |= R600_GROUP_SIZE(0);
if (((mc_arb_ramcfg >> R700_NOOFROWS_SHIFT) & R700_NOOFROWS_MASK) > 3) {
gb_tiling_config |= R600_ROW_TILING(3);
gb_tiling_config |= R600_SAMPLE_SPLIT(3);
} else {
gb_tiling_config |=
R600_ROW_TILING(((mc_arb_ramcfg >> R700_NOOFROWS_SHIFT) & R700_NOOFROWS_MASK));
gb_tiling_config |=
R600_SAMPLE_SPLIT(((mc_arb_ramcfg >> R700_NOOFROWS_SHIFT) & R700_NOOFROWS_MASK));
}
gb_tiling_config |= R600_BANK_SWAPS(1);
cc_rb_backend_disable = RADEON_READ(R600_CC_RB_BACKEND_DISABLE) & 0x00ff0000;
cc_rb_backend_disable |=
R600_BACKEND_DISABLE((R7XX_MAX_BACKENDS_MASK << dev_priv->r600_max_backends) & R7XX_MAX_BACKENDS_MASK);
cc_gc_shader_pipe_config = RADEON_READ(R600_CC_GC_SHADER_PIPE_CONFIG) & 0xffffff00;
cc_gc_shader_pipe_config |=
R600_INACTIVE_QD_PIPES((R7XX_MAX_PIPES_MASK << dev_priv->r600_max_pipes) & R7XX_MAX_PIPES_MASK);
cc_gc_shader_pipe_config |=
R600_INACTIVE_SIMDS((R7XX_MAX_SIMDS_MASK << dev_priv->r600_max_simds) & R7XX_MAX_SIMDS_MASK);
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV740)
backend_map = 0x28;
else
backend_map = r700_get_tile_pipe_to_backend_map(dev_priv,
dev_priv->r600_max_tile_pipes,
(R7XX_MAX_BACKENDS -
r600_count_pipe_bits((cc_rb_backend_disable &
R7XX_MAX_BACKENDS_MASK) >> 16)),
(cc_rb_backend_disable >> 16));
gb_tiling_config |= R600_BACKEND_MAP(backend_map);
RADEON_WRITE(R600_GB_TILING_CONFIG, gb_tiling_config);
RADEON_WRITE(R600_DCP_TILING_CONFIG, (gb_tiling_config & 0xffff));
RADEON_WRITE(R600_HDP_TILING_CONFIG, (gb_tiling_config & 0xffff));
if (gb_tiling_config & 0xc0) {
dev_priv->r600_group_size = 512;
} else {
dev_priv->r600_group_size = 256;
}
dev_priv->r600_npipes = 1 << ((gb_tiling_config >> 1) & 0x7);
if (gb_tiling_config & 0x30) {
dev_priv->r600_nbanks = 8;
} else {
dev_priv->r600_nbanks = 4;
}
RADEON_WRITE(R600_CC_RB_BACKEND_DISABLE, cc_rb_backend_disable);
RADEON_WRITE(R600_CC_GC_SHADER_PIPE_CONFIG, cc_gc_shader_pipe_config);
RADEON_WRITE(R600_GC_USER_SHADER_PIPE_CONFIG, cc_gc_shader_pipe_config);
RADEON_WRITE(R700_CC_SYS_RB_BACKEND_DISABLE, cc_rb_backend_disable);
RADEON_WRITE(R700_CGTS_SYS_TCC_DISABLE, 0);
RADEON_WRITE(R700_CGTS_TCC_DISABLE, 0);
RADEON_WRITE(R700_CGTS_USER_SYS_TCC_DISABLE, 0);
RADEON_WRITE(R700_CGTS_USER_TCC_DISABLE, 0);
num_qd_pipes =
R7XX_MAX_PIPES - r600_count_pipe_bits((cc_gc_shader_pipe_config & R600_INACTIVE_QD_PIPES_MASK) >> 8);
RADEON_WRITE(R600_VGT_OUT_DEALLOC_CNTL, (num_qd_pipes * 4) & R600_DEALLOC_DIST_MASK);
RADEON_WRITE(R600_VGT_VERTEX_REUSE_BLOCK_CNTL, ((num_qd_pipes * 4) - 2) & R600_VTX_REUSE_DEPTH_MASK);
/* set HW defaults for 3D engine */
RADEON_WRITE(R600_CP_QUEUE_THRESHOLDS, (R600_ROQ_IB1_START(0x16) |
R600_ROQ_IB2_START(0x2b)));
RADEON_WRITE(R600_CP_MEQ_THRESHOLDS, R700_STQ_SPLIT(0x30));
ta_aux_cntl = RADEON_READ(R600_TA_CNTL_AUX);
RADEON_WRITE(R600_TA_CNTL_AUX, ta_aux_cntl | R600_DISABLE_CUBE_ANISO);
sx_debug_1 = RADEON_READ(R700_SX_DEBUG_1);
sx_debug_1 |= R700_ENABLE_NEW_SMX_ADDRESS;
RADEON_WRITE(R700_SX_DEBUG_1, sx_debug_1);
smx_dc_ctl0 = RADEON_READ(R600_SMX_DC_CTL0);
smx_dc_ctl0 &= ~R700_CACHE_DEPTH(0x1ff);
smx_dc_ctl0 |= R700_CACHE_DEPTH((dev_priv->r700_sx_num_of_sets * 64) - 1);
RADEON_WRITE(R600_SMX_DC_CTL0, smx_dc_ctl0);
if ((dev_priv->flags & RADEON_FAMILY_MASK) != CHIP_RV740)
RADEON_WRITE(R700_SMX_EVENT_CTL, (R700_ES_FLUSH_CTL(4) |
R700_GS_FLUSH_CTL(4) |
R700_ACK_FLUSH_CTL(3) |
R700_SYNC_FLUSH_CTL));
db_debug3 = RADEON_READ(R700_DB_DEBUG3);
db_debug3 &= ~R700_DB_CLK_OFF_DELAY(0x1f);
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV770:
case CHIP_RV740:
db_debug3 |= R700_DB_CLK_OFF_DELAY(0x1f);
break;
case CHIP_RV710:
case CHIP_RV730:
default:
db_debug3 |= R700_DB_CLK_OFF_DELAY(2);
break;
}
RADEON_WRITE(R700_DB_DEBUG3, db_debug3);
if ((dev_priv->flags & RADEON_FAMILY_MASK) != CHIP_RV770) {
db_debug4 = RADEON_READ(RV700_DB_DEBUG4);
db_debug4 |= RV700_DISABLE_TILE_COVERED_FOR_PS_ITER;
RADEON_WRITE(RV700_DB_DEBUG4, db_debug4);
}
RADEON_WRITE(R600_SX_EXPORT_BUFFER_SIZES, (R600_COLOR_BUFFER_SIZE((dev_priv->r600_sx_max_export_size / 4) - 1) |
R600_POSITION_BUFFER_SIZE((dev_priv->r600_sx_max_export_pos_size / 4) - 1) |
R600_SMX_BUFFER_SIZE((dev_priv->r600_sx_max_export_smx_size / 4) - 1)));
RADEON_WRITE(R700_PA_SC_FIFO_SIZE_R7XX, (R700_SC_PRIM_FIFO_SIZE(dev_priv->r700_sc_prim_fifo_size) |
R700_SC_HIZ_TILE_FIFO_SIZE(dev_priv->r700_sc_hiz_tile_fifo_size) |
R700_SC_EARLYZ_TILE_FIFO_SIZE(dev_priv->r700_sc_earlyz_tile_fifo_fize)));
RADEON_WRITE(R600_PA_SC_MULTI_CHIP_CNTL, 0);
RADEON_WRITE(R600_VGT_NUM_INSTANCES, 1);
RADEON_WRITE(R600_SPI_CONFIG_CNTL, R600_GPR_WRITE_PRIORITY(0));
RADEON_WRITE(R600_SPI_CONFIG_CNTL_1, R600_VTX_DONE_DELAY(4));
RADEON_WRITE(R600_CP_PERFMON_CNTL, 0);
sq_ms_fifo_sizes = (R600_CACHE_FIFO_SIZE(16 * dev_priv->r600_sq_num_cf_insts) |
R600_DONE_FIFO_HIWATER(0xe0) |
R600_ALU_UPDATE_FIFO_HIWATER(0x8));
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV770:
case CHIP_RV730:
case CHIP_RV710:
sq_ms_fifo_sizes |= R600_FETCH_FIFO_HIWATER(0x1);
break;
case CHIP_RV740:
default:
sq_ms_fifo_sizes |= R600_FETCH_FIFO_HIWATER(0x4);
break;
}
RADEON_WRITE(R600_SQ_MS_FIFO_SIZES, sq_ms_fifo_sizes);
/* SQ_CONFIG, SQ_GPR_RESOURCE_MGMT, SQ_THREAD_RESOURCE_MGMT, SQ_STACK_RESOURCE_MGMT
* should be adjusted as needed by the 2D/3D drivers. This just sets default values
*/
sq_config = RADEON_READ(R600_SQ_CONFIG);
sq_config &= ~(R600_PS_PRIO(3) |
R600_VS_PRIO(3) |
R600_GS_PRIO(3) |
R600_ES_PRIO(3));
sq_config |= (R600_DX9_CONSTS |
R600_VC_ENABLE |
R600_EXPORT_SRC_C |
R600_PS_PRIO(0) |
R600_VS_PRIO(1) |
R600_GS_PRIO(2) |
R600_ES_PRIO(3));
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV710)
/* no vertex cache */
sq_config &= ~R600_VC_ENABLE;
RADEON_WRITE(R600_SQ_CONFIG, sq_config);
RADEON_WRITE(R600_SQ_GPR_RESOURCE_MGMT_1, (R600_NUM_PS_GPRS((dev_priv->r600_max_gprs * 24)/64) |
R600_NUM_VS_GPRS((dev_priv->r600_max_gprs * 24)/64) |
R600_NUM_CLAUSE_TEMP_GPRS(((dev_priv->r600_max_gprs * 24)/64)/2)));
RADEON_WRITE(R600_SQ_GPR_RESOURCE_MGMT_2, (R600_NUM_GS_GPRS((dev_priv->r600_max_gprs * 7)/64) |
R600_NUM_ES_GPRS((dev_priv->r600_max_gprs * 7)/64)));
sq_thread_resource_mgmt = (R600_NUM_PS_THREADS((dev_priv->r600_max_threads * 4)/8) |
R600_NUM_VS_THREADS((dev_priv->r600_max_threads * 2)/8) |
R600_NUM_ES_THREADS((dev_priv->r600_max_threads * 1)/8));
if (((dev_priv->r600_max_threads * 1) / 8) > dev_priv->r600_max_gs_threads)
sq_thread_resource_mgmt |= R600_NUM_GS_THREADS(dev_priv->r600_max_gs_threads);
else
sq_thread_resource_mgmt |= R600_NUM_GS_THREADS((dev_priv->r600_max_gs_threads * 1)/8);
RADEON_WRITE(R600_SQ_THREAD_RESOURCE_MGMT, sq_thread_resource_mgmt);
RADEON_WRITE(R600_SQ_STACK_RESOURCE_MGMT_1, (R600_NUM_PS_STACK_ENTRIES((dev_priv->r600_max_stack_entries * 1)/4) |
R600_NUM_VS_STACK_ENTRIES((dev_priv->r600_max_stack_entries * 1)/4)));
RADEON_WRITE(R600_SQ_STACK_RESOURCE_MGMT_2, (R600_NUM_GS_STACK_ENTRIES((dev_priv->r600_max_stack_entries * 1)/4) |
R600_NUM_ES_STACK_ENTRIES((dev_priv->r600_max_stack_entries * 1)/4)));
sq_dyn_gpr_size_simd_ab_0 = (R700_SIMDA_RING0((dev_priv->r600_max_gprs * 38)/64) |
R700_SIMDA_RING1((dev_priv->r600_max_gprs * 38)/64) |
R700_SIMDB_RING0((dev_priv->r600_max_gprs * 38)/64) |
R700_SIMDB_RING1((dev_priv->r600_max_gprs * 38)/64));
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_0, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_1, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_2, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_3, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_4, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_5, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_6, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_SQ_DYN_GPR_SIZE_SIMD_AB_7, sq_dyn_gpr_size_simd_ab_0);
RADEON_WRITE(R700_PA_SC_FORCE_EOV_MAX_CNTS, (R700_FORCE_EOV_MAX_CLK_CNT(4095) |
R700_FORCE_EOV_MAX_REZ_CNT(255)));
if ((dev_priv->flags & RADEON_FAMILY_MASK) == CHIP_RV710)
RADEON_WRITE(R600_VGT_CACHE_INVALIDATION, (R600_CACHE_INVALIDATION(R600_TC_ONLY) |
R700_AUTO_INVLD_EN(R700_ES_AND_GS_AUTO)));
else
RADEON_WRITE(R600_VGT_CACHE_INVALIDATION, (R600_CACHE_INVALIDATION(R600_VC_AND_TC) |
R700_AUTO_INVLD_EN(R700_ES_AND_GS_AUTO)));
switch (dev_priv->flags & RADEON_FAMILY_MASK) {
case CHIP_RV770:
case CHIP_RV730:
case CHIP_RV740:
gs_prim_buffer_depth = 384;
break;
case CHIP_RV710:
gs_prim_buffer_depth = 128;
break;
default:
break;
}
num_gs_verts_per_thread = dev_priv->r600_max_pipes * 16;
vgt_gs_per_es = gs_prim_buffer_depth + num_gs_verts_per_thread;
/* Max value for this is 256 */
if (vgt_gs_per_es > 256)
vgt_gs_per_es = 256;
RADEON_WRITE(R600_VGT_ES_PER_GS, 128);
RADEON_WRITE(R600_VGT_GS_PER_ES, vgt_gs_per_es);
RADEON_WRITE(R600_VGT_GS_PER_VS, 2);
/* more default values. 2D/3D driver should adjust as needed */
RADEON_WRITE(R600_VGT_GS_VERTEX_REUSE, 16);
RADEON_WRITE(R600_PA_SC_LINE_STIPPLE_STATE, 0);
RADEON_WRITE(R600_VGT_STRMOUT_EN, 0);
RADEON_WRITE(R600_SX_MISC, 0);
RADEON_WRITE(R600_PA_SC_MODE_CNTL, 0);
RADEON_WRITE(R700_PA_SC_EDGERULE, 0xaaaaaaaa);
RADEON_WRITE(R600_PA_SC_AA_CONFIG, 0);
RADEON_WRITE(R600_PA_SC_CLIPRECT_RULE, 0xffff);
RADEON_WRITE(R600_PA_SC_LINE_STIPPLE, 0);
RADEON_WRITE(R600_SPI_INPUT_Z, 0);
RADEON_WRITE(R600_SPI_PS_IN_CONTROL_0, R600_NUM_INTERP(2));
RADEON_WRITE(R600_CB_COLOR7_FRAG, 0);
/* clear render buffer base addresses */
RADEON_WRITE(R600_CB_COLOR0_BASE, 0);
RADEON_WRITE(R600_CB_COLOR1_BASE, 0);
RADEON_WRITE(R600_CB_COLOR2_BASE, 0);
RADEON_WRITE(R600_CB_COLOR3_BASE, 0);
RADEON_WRITE(R600_CB_COLOR4_BASE, 0);
RADEON_WRITE(R600_CB_COLOR5_BASE, 0);
RADEON_WRITE(R600_CB_COLOR6_BASE, 0);
RADEON_WRITE(R600_CB_COLOR7_BASE, 0);
RADEON_WRITE(R700_TCP_CNTL, 0);
hdp_host_path_cntl = RADEON_READ(R600_HDP_HOST_PATH_CNTL);
RADEON_WRITE(R600_HDP_HOST_PATH_CNTL, hdp_host_path_cntl);
RADEON_WRITE(R600_PA_SC_MULTI_CHIP_CNTL, 0);
RADEON_WRITE(R600_PA_CL_ENHANCE, (R600_CLIP_VTX_REORDER_ENA |
R600_NUM_CLIP_SEQ(3)));
}
static void r600_cp_init_ring_buffer(struct drm_device *dev,
drm_radeon_private_t *dev_priv,
struct drm_file *file_priv)
{
struct drm_radeon_master_private *master_priv;
u32 ring_start;
u64 rptr_addr;
if (((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770))
r700_gfx_init(dev, dev_priv);
else
r600_gfx_init(dev, dev_priv);
RADEON_WRITE(R600_GRBM_SOFT_RESET, R600_SOFT_RESET_CP);
RADEON_READ(R600_GRBM_SOFT_RESET);
DRM_UDELAY(15000);
RADEON_WRITE(R600_GRBM_SOFT_RESET, 0);
/* Set ring buffer size */
#ifdef __BIG_ENDIAN
RADEON_WRITE(R600_CP_RB_CNTL,
RADEON_BUF_SWAP_32BIT |
RADEON_RB_NO_UPDATE |
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#else
RADEON_WRITE(R600_CP_RB_CNTL,
RADEON_RB_NO_UPDATE |
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#endif
RADEON_WRITE(R600_CP_SEM_WAIT_TIMER, 0x4);
/* Set the write pointer delay */
RADEON_WRITE(R600_CP_RB_WPTR_DELAY, 0);
#ifdef __BIG_ENDIAN
RADEON_WRITE(R600_CP_RB_CNTL,
RADEON_BUF_SWAP_32BIT |
RADEON_RB_NO_UPDATE |
RADEON_RB_RPTR_WR_ENA |
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#else
RADEON_WRITE(R600_CP_RB_CNTL,
RADEON_RB_NO_UPDATE |
RADEON_RB_RPTR_WR_ENA |
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#endif
/* Initialize the ring buffer's read and write pointers */
RADEON_WRITE(R600_CP_RB_RPTR_WR, 0);
RADEON_WRITE(R600_CP_RB_WPTR, 0);
SET_RING_HEAD(dev_priv, 0);
dev_priv->ring.tail = 0;
#if __OS_HAS_AGP
if (dev_priv->flags & RADEON_IS_AGP) {
rptr_addr = dev_priv->ring_rptr->offset
- dev->agp->base +
dev_priv->gart_vm_start;
} else
#endif
{
rptr_addr = dev_priv->ring_rptr->offset
- ((unsigned long) dev->sg->virtual)
+ dev_priv->gart_vm_start;
}
RADEON_WRITE(R600_CP_RB_RPTR_ADDR,
rptr_addr & 0xffffffff);
RADEON_WRITE(R600_CP_RB_RPTR_ADDR_HI,
upper_32_bits(rptr_addr));
#ifdef __BIG_ENDIAN
RADEON_WRITE(R600_CP_RB_CNTL,
RADEON_BUF_SWAP_32BIT |
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#else
RADEON_WRITE(R600_CP_RB_CNTL,
(dev_priv->ring.rptr_update_l2qw << 8) |
dev_priv->ring.size_l2qw);
#endif
#if __OS_HAS_AGP
if (dev_priv->flags & RADEON_IS_AGP) {
/* XXX */
radeon_write_agp_base(dev_priv, dev->agp->base);
/* XXX */
radeon_write_agp_location(dev_priv,
(((dev_priv->gart_vm_start - 1 +
dev_priv->gart_size) & 0xffff0000) |
(dev_priv->gart_vm_start >> 16)));
ring_start = (dev_priv->cp_ring->offset
- dev->agp->base
+ dev_priv->gart_vm_start);
} else
#endif
ring_start = (dev_priv->cp_ring->offset
- (unsigned long)dev->sg->virtual
+ dev_priv->gart_vm_start);
RADEON_WRITE(R600_CP_RB_BASE, ring_start >> 8);
RADEON_WRITE(R600_CP_ME_CNTL, 0xff);
RADEON_WRITE(R600_CP_DEBUG, (1 << 27) | (1 << 28));
/* Initialize the scratch register pointer. This will cause
* the scratch register values to be written out to memory
* whenever they are updated.
*
* We simply put this behind the ring read pointer, this works
* with PCI GART as well as (whatever kind of) AGP GART
*/
{
u64 scratch_addr;
scratch_addr = RADEON_READ(R600_CP_RB_RPTR_ADDR);
scratch_addr |= ((u64)RADEON_READ(R600_CP_RB_RPTR_ADDR_HI)) << 32;
scratch_addr += R600_SCRATCH_REG_OFFSET;
scratch_addr >>= 8;
scratch_addr &= 0xffffffff;
RADEON_WRITE(R600_SCRATCH_ADDR, (uint32_t)scratch_addr);
}
RADEON_WRITE(R600_SCRATCH_UMSK, 0x7);
/* Turn on bus mastering */
radeon_enable_bm(dev_priv);
radeon_write_ring_rptr(dev_priv, R600_SCRATCHOFF(0), 0);
RADEON_WRITE(R600_LAST_FRAME_REG, 0);
radeon_write_ring_rptr(dev_priv, R600_SCRATCHOFF(1), 0);
RADEON_WRITE(R600_LAST_DISPATCH_REG, 0);
radeon_write_ring_rptr(dev_priv, R600_SCRATCHOFF(2), 0);
RADEON_WRITE(R600_LAST_CLEAR_REG, 0);
/* reset sarea copies of these */
master_priv = file_priv->master->driver_priv;
if (master_priv->sarea_priv) {
master_priv->sarea_priv->last_frame = 0;
master_priv->sarea_priv->last_dispatch = 0;
master_priv->sarea_priv->last_clear = 0;
}
r600_do_wait_for_idle(dev_priv);
}
int r600_do_cleanup_cp(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
/* Make sure interrupts are disabled here because the uninstall ioctl
* may not have been called from userspace and after dev_private
* is freed, it's too late.
*/
if (dev->irq_enabled)
drm_irq_uninstall(dev);
#if __OS_HAS_AGP
if (dev_priv->flags & RADEON_IS_AGP) {
if (dev_priv->cp_ring != NULL) {
drm_core_ioremapfree(dev_priv->cp_ring, dev);
dev_priv->cp_ring = NULL;
}
if (dev_priv->ring_rptr != NULL) {
drm_core_ioremapfree(dev_priv->ring_rptr, dev);
dev_priv->ring_rptr = NULL;
}
if (dev->agp_buffer_map != NULL) {
drm_core_ioremapfree(dev->agp_buffer_map, dev);
dev->agp_buffer_map = NULL;
}
} else
#endif
{
if (dev_priv->gart_info.bus_addr)
r600_page_table_cleanup(dev, &dev_priv->gart_info);
if (dev_priv->gart_info.gart_table_location == DRM_ATI_GART_FB) {
drm_core_ioremapfree(&dev_priv->gart_info.mapping, dev);
dev_priv->gart_info.addr = NULL;
}
}
/* only clear to the start of flags */
memset(dev_priv, 0, offsetof(drm_radeon_private_t, flags));
return 0;
}
int r600_do_init_cp(struct drm_device *dev, drm_radeon_init_t *init,
struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
struct drm_radeon_master_private *master_priv = file_priv->master->driver_priv;
DRM_DEBUG("\n");
mutex_init(&dev_priv->cs_mutex);
r600_cs_legacy_init();
/* if we require new memory map but we don't have it fail */
if ((dev_priv->flags & RADEON_NEW_MEMMAP) && !dev_priv->new_memmap) {
DRM_ERROR("Cannot initialise DRM on this card\nThis card requires a new X.org DDX for 3D\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
if (init->is_pci && (dev_priv->flags & RADEON_IS_AGP)) {
DRM_DEBUG("Forcing AGP card to PCI mode\n");
dev_priv->flags &= ~RADEON_IS_AGP;
/* The writeback test succeeds, but when writeback is enabled,
* the ring buffer read ptr update fails after first 128 bytes.
*/
radeon_no_wb = 1;
} else if (!(dev_priv->flags & (RADEON_IS_AGP | RADEON_IS_PCI | RADEON_IS_PCIE))
&& !init->is_pci) {
DRM_DEBUG("Restoring AGP flag\n");
dev_priv->flags |= RADEON_IS_AGP;
}
dev_priv->usec_timeout = init->usec_timeout;
if (dev_priv->usec_timeout < 1 ||
dev_priv->usec_timeout > RADEON_MAX_USEC_TIMEOUT) {
DRM_DEBUG("TIMEOUT problem!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
/* Enable vblank on CRTC1 for older X servers
*/
dev_priv->vblank_crtc = DRM_RADEON_VBLANK_CRTC1;
dev_priv->do_boxes = 0;
dev_priv->cp_mode = init->cp_mode;
/* We don't support anything other than bus-mastering ring mode,
* but the ring can be in either AGP or PCI space for the ring
* read pointer.
*/
if ((init->cp_mode != RADEON_CSQ_PRIBM_INDDIS) &&
(init->cp_mode != RADEON_CSQ_PRIBM_INDBM)) {
DRM_DEBUG("BAD cp_mode (%x)!\n", init->cp_mode);
r600_do_cleanup_cp(dev);
return -EINVAL;
}
switch (init->fb_bpp) {
case 16:
dev_priv->color_fmt = RADEON_COLOR_FORMAT_RGB565;
break;
case 32:
default:
dev_priv->color_fmt = RADEON_COLOR_FORMAT_ARGB8888;
break;
}
dev_priv->front_offset = init->front_offset;
dev_priv->front_pitch = init->front_pitch;
dev_priv->back_offset = init->back_offset;
dev_priv->back_pitch = init->back_pitch;
dev_priv->ring_offset = init->ring_offset;
dev_priv->ring_rptr_offset = init->ring_rptr_offset;
dev_priv->buffers_offset = init->buffers_offset;
dev_priv->gart_textures_offset = init->gart_textures_offset;
master_priv->sarea = drm_getsarea(dev);
if (!master_priv->sarea) {
DRM_ERROR("could not find sarea!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
dev_priv->cp_ring = drm_core_findmap(dev, init->ring_offset);
if (!dev_priv->cp_ring) {
DRM_ERROR("could not find cp ring region!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
dev_priv->ring_rptr = drm_core_findmap(dev, init->ring_rptr_offset);
if (!dev_priv->ring_rptr) {
DRM_ERROR("could not find ring read pointer!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
dev->agp_buffer_token = init->buffers_offset;
dev->agp_buffer_map = drm_core_findmap(dev, init->buffers_offset);
if (!dev->agp_buffer_map) {
DRM_ERROR("could not find dma buffer region!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
if (init->gart_textures_offset) {
dev_priv->gart_textures =
drm_core_findmap(dev, init->gart_textures_offset);
if (!dev_priv->gart_textures) {
DRM_ERROR("could not find GART texture region!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
}
#if __OS_HAS_AGP
/* XXX */
if (dev_priv->flags & RADEON_IS_AGP) {
drm_core_ioremap_wc(dev_priv->cp_ring, dev);
drm_core_ioremap_wc(dev_priv->ring_rptr, dev);
drm_core_ioremap_wc(dev->agp_buffer_map, dev);
if (!dev_priv->cp_ring->handle ||
!dev_priv->ring_rptr->handle ||
!dev->agp_buffer_map->handle) {
DRM_ERROR("could not find ioremap agp regions!\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
} else
#endif
{
dev_priv->cp_ring->handle = (void *)(unsigned long)dev_priv->cp_ring->offset;
dev_priv->ring_rptr->handle =
(void *)(unsigned long)dev_priv->ring_rptr->offset;
dev->agp_buffer_map->handle =
(void *)(unsigned long)dev->agp_buffer_map->offset;
DRM_DEBUG("dev_priv->cp_ring->handle %p\n",
dev_priv->cp_ring->handle);
DRM_DEBUG("dev_priv->ring_rptr->handle %p\n",
dev_priv->ring_rptr->handle);
DRM_DEBUG("dev->agp_buffer_map->handle %p\n",
dev->agp_buffer_map->handle);
}
dev_priv->fb_location = (radeon_read_fb_location(dev_priv) & 0xffff) << 24;
dev_priv->fb_size =
(((radeon_read_fb_location(dev_priv) & 0xffff0000u) << 8) + 0x1000000)
- dev_priv->fb_location;
dev_priv->front_pitch_offset = (((dev_priv->front_pitch / 64) << 22) |
((dev_priv->front_offset
+ dev_priv->fb_location) >> 10));
dev_priv->back_pitch_offset = (((dev_priv->back_pitch / 64) << 22) |
((dev_priv->back_offset
+ dev_priv->fb_location) >> 10));
dev_priv->depth_pitch_offset = (((dev_priv->depth_pitch / 64) << 22) |
((dev_priv->depth_offset
+ dev_priv->fb_location) >> 10));
dev_priv->gart_size = init->gart_size;
/* New let's set the memory map ... */
if (dev_priv->new_memmap) {
u32 base = 0;
DRM_INFO("Setting GART location based on new memory map\n");
/* If using AGP, try to locate the AGP aperture at the same
* location in the card and on the bus, though we have to
* align it down.
*/
#if __OS_HAS_AGP
/* XXX */
if (dev_priv->flags & RADEON_IS_AGP) {
base = dev->agp->base;
/* Check if valid */
if ((base + dev_priv->gart_size - 1) >= dev_priv->fb_location &&
base < (dev_priv->fb_location + dev_priv->fb_size - 1)) {
DRM_INFO("Can't use AGP base @0x%08lx, won't fit\n",
dev->agp->base);
base = 0;
}
}
#endif
/* If not or if AGP is at 0 (Macs), try to put it elsewhere */
if (base == 0) {
base = dev_priv->fb_location + dev_priv->fb_size;
if (base < dev_priv->fb_location ||
((base + dev_priv->gart_size) & 0xfffffffful) < base)
base = dev_priv->fb_location
- dev_priv->gart_size;
}
dev_priv->gart_vm_start = base & 0xffc00000u;
if (dev_priv->gart_vm_start != base)
DRM_INFO("GART aligned down from 0x%08x to 0x%08x\n",
base, dev_priv->gart_vm_start);
}
#if __OS_HAS_AGP
/* XXX */
if (dev_priv->flags & RADEON_IS_AGP)
dev_priv->gart_buffers_offset = (dev->agp_buffer_map->offset
- dev->agp->base
+ dev_priv->gart_vm_start);
else
#endif
dev_priv->gart_buffers_offset = (dev->agp_buffer_map->offset
- (unsigned long)dev->sg->virtual
+ dev_priv->gart_vm_start);
DRM_DEBUG("fb 0x%08x size %d\n",
(unsigned int) dev_priv->fb_location,
(unsigned int) dev_priv->fb_size);
DRM_DEBUG("dev_priv->gart_size %d\n", dev_priv->gart_size);
DRM_DEBUG("dev_priv->gart_vm_start 0x%08x\n",
(unsigned int) dev_priv->gart_vm_start);
DRM_DEBUG("dev_priv->gart_buffers_offset 0x%08lx\n",
dev_priv->gart_buffers_offset);
dev_priv->ring.start = (u32 *) dev_priv->cp_ring->handle;
dev_priv->ring.end = ((u32 *) dev_priv->cp_ring->handle
+ init->ring_size / sizeof(u32));
dev_priv->ring.size = init->ring_size;
dev_priv->ring.size_l2qw = drm_order(init->ring_size / 8);
dev_priv->ring.rptr_update = /* init->rptr_update */ 4096;
dev_priv->ring.rptr_update_l2qw = drm_order(/* init->rptr_update */ 4096 / 8);
dev_priv->ring.fetch_size = /* init->fetch_size */ 32;
dev_priv->ring.fetch_size_l2ow = drm_order(/* init->fetch_size */ 32 / 16);
dev_priv->ring.tail_mask = (dev_priv->ring.size / sizeof(u32)) - 1;
dev_priv->ring.high_mark = RADEON_RING_HIGH_MARK;
#if __OS_HAS_AGP
if (dev_priv->flags & RADEON_IS_AGP) {
/* XXX turn off pcie gart */
} else
#endif
{
dev_priv->gart_info.table_mask = DMA_BIT_MASK(32);
/* if we have an offset set from userspace */
if (!dev_priv->pcigart_offset_set) {
DRM_ERROR("Need gart offset from userspace\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
DRM_DEBUG("Using gart offset 0x%08lx\n", dev_priv->pcigart_offset);
dev_priv->gart_info.bus_addr =
dev_priv->pcigart_offset + dev_priv->fb_location;
dev_priv->gart_info.mapping.offset =
dev_priv->pcigart_offset + dev_priv->fb_aper_offset;
dev_priv->gart_info.mapping.size =
dev_priv->gart_info.table_size;
drm_core_ioremap_wc(&dev_priv->gart_info.mapping, dev);
if (!dev_priv->gart_info.mapping.handle) {
DRM_ERROR("ioremap failed.\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
dev_priv->gart_info.addr =
dev_priv->gart_info.mapping.handle;
DRM_DEBUG("Setting phys_pci_gart to %p %08lX\n",
dev_priv->gart_info.addr,
dev_priv->pcigart_offset);
if (!r600_page_table_init(dev)) {
DRM_ERROR("Failed to init GART table\n");
r600_do_cleanup_cp(dev);
return -EINVAL;
}
if (((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770))
r700_vm_init(dev);
else
r600_vm_init(dev);
}
if (!dev_priv->me_fw || !dev_priv->pfp_fw) {
int err = r600_cp_init_microcode(dev_priv);
if (err) {
DRM_ERROR("Failed to load firmware!\n");
r600_do_cleanup_cp(dev);
return err;
}
}
if (((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770))
r700_cp_load_microcode(dev_priv);
else
r600_cp_load_microcode(dev_priv);
r600_cp_init_ring_buffer(dev, dev_priv, file_priv);
dev_priv->last_buf = 0;
r600_do_engine_reset(dev);
r600_test_writeback(dev_priv);
return 0;
}
int r600_do_resume_cp(struct drm_device *dev, struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
if (((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RV770)) {
r700_vm_init(dev);
r700_cp_load_microcode(dev_priv);
} else {
r600_vm_init(dev);
r600_cp_load_microcode(dev_priv);
}
r600_cp_init_ring_buffer(dev, dev_priv, file_priv);
r600_do_engine_reset(dev);
return 0;
}
/* Wait for the CP to go idle.
*/
int r600_do_cp_idle(drm_radeon_private_t *dev_priv)
{
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(5);
OUT_RING(CP_PACKET3(R600_IT_EVENT_WRITE, 0));
OUT_RING(R600_CACHE_FLUSH_AND_INV_EVENT);
/* wait for 3D idle clean */
OUT_RING(CP_PACKET3(R600_IT_SET_CONFIG_REG, 1));
OUT_RING((R600_WAIT_UNTIL - R600_SET_CONFIG_REG_OFFSET) >> 2);
OUT_RING(RADEON_WAIT_3D_IDLE | RADEON_WAIT_3D_IDLECLEAN);
ADVANCE_RING();
COMMIT_RING();
return r600_do_wait_for_idle(dev_priv);
}
/* Start the Command Processor.
*/
void r600_do_cp_start(drm_radeon_private_t *dev_priv)
{
u32 cp_me;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(7);
OUT_RING(CP_PACKET3(R600_IT_ME_INITIALIZE, 5));
OUT_RING(0x00000001);
if (((dev_priv->flags & RADEON_FAMILY_MASK) < CHIP_RV770))
OUT_RING(0x00000003);
else
OUT_RING(0x00000000);
OUT_RING((dev_priv->r600_max_hw_contexts - 1));
OUT_RING(R600_ME_INITIALIZE_DEVICE_ID(1));
OUT_RING(0x00000000);
OUT_RING(0x00000000);
ADVANCE_RING();
COMMIT_RING();
/* set the mux and reset the halt bit */
cp_me = 0xff;
RADEON_WRITE(R600_CP_ME_CNTL, cp_me);
dev_priv->cp_running = 1;
}
void r600_do_cp_reset(drm_radeon_private_t *dev_priv)
{
u32 cur_read_ptr;
DRM_DEBUG("\n");
cur_read_ptr = RADEON_READ(R600_CP_RB_RPTR);
RADEON_WRITE(R600_CP_RB_WPTR, cur_read_ptr);
SET_RING_HEAD(dev_priv, cur_read_ptr);
dev_priv->ring.tail = cur_read_ptr;
}
void r600_do_cp_stop(drm_radeon_private_t *dev_priv)
{
uint32_t cp_me;
DRM_DEBUG("\n");
cp_me = 0xff | R600_CP_ME_HALT;
RADEON_WRITE(R600_CP_ME_CNTL, cp_me);
dev_priv->cp_running = 0;
}
int r600_cp_dispatch_indirect(struct drm_device *dev,
struct drm_buf *buf, int start, int end)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
RING_LOCALS;
if (start != end) {
unsigned long offset = (dev_priv->gart_buffers_offset
+ buf->offset + start);
int dwords = (end - start + 3) / sizeof(u32);
DRM_DEBUG("dwords:%d\n", dwords);
DRM_DEBUG("offset 0x%lx\n", offset);
/* Indirect buffer data must be a multiple of 16 dwords.
* pad the data with a Type-2 CP packet.
*/
while (dwords & 0xf) {
u32 *data = (u32 *)
((char *)dev->agp_buffer_map->handle
+ buf->offset + start);
data[dwords++] = RADEON_CP_PACKET2;
}
/* Fire off the indirect buffer */
BEGIN_RING(4);
OUT_RING(CP_PACKET3(R600_IT_INDIRECT_BUFFER, 2));
OUT_RING((offset & 0xfffffffc));
OUT_RING((upper_32_bits(offset) & 0xff));
OUT_RING(dwords);
ADVANCE_RING();
}
return 0;
}
void r600_cp_dispatch_swap(struct drm_device *dev, struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
struct drm_master *master = file_priv->master;
struct drm_radeon_master_private *master_priv = master->driver_priv;
drm_radeon_sarea_t *sarea_priv = master_priv->sarea_priv;
int nbox = sarea_priv->nbox;
struct drm_clip_rect *pbox = sarea_priv->boxes;
int i, cpp, src_pitch, dst_pitch;
uint64_t src, dst;
RING_LOCALS;
DRM_DEBUG("\n");
if (dev_priv->color_fmt == RADEON_COLOR_FORMAT_ARGB8888)
cpp = 4;
else
cpp = 2;
if (sarea_priv->pfCurrentPage == 0) {
src_pitch = dev_priv->back_pitch;
dst_pitch = dev_priv->front_pitch;
src = dev_priv->back_offset + dev_priv->fb_location;
dst = dev_priv->front_offset + dev_priv->fb_location;
} else {
src_pitch = dev_priv->front_pitch;
dst_pitch = dev_priv->back_pitch;
src = dev_priv->front_offset + dev_priv->fb_location;
dst = dev_priv->back_offset + dev_priv->fb_location;
}
if (r600_prepare_blit_copy(dev, file_priv)) {
DRM_ERROR("unable to allocate vertex buffer for swap buffer\n");
return;
}
for (i = 0; i < nbox; i++) {
int x = pbox[i].x1;
int y = pbox[i].y1;
int w = pbox[i].x2 - x;
int h = pbox[i].y2 - y;
DRM_DEBUG("%d,%d-%d,%d\n", x, y, w, h);
r600_blit_swap(dev,
src, dst,
x, y, x, y, w, h,
src_pitch, dst_pitch, cpp);
}
r600_done_blit_copy(dev);
/* Increment the frame counter. The client-side 3D driver must
* throttle the framerate by waiting for this value before
* performing the swapbuffer ioctl.
*/
sarea_priv->last_frame++;
BEGIN_RING(3);
R600_FRAME_AGE(sarea_priv->last_frame);
ADVANCE_RING();
}
int r600_cp_dispatch_texture(struct drm_device *dev,
struct drm_file *file_priv,
drm_radeon_texture_t *tex,
drm_radeon_tex_image_t *image)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
struct drm_buf *buf;
u32 *buffer;
const u8 __user *data;
int size, pass_size;
u64 src_offset, dst_offset;
if (!radeon_check_offset(dev_priv, tex->offset)) {
DRM_ERROR("Invalid destination offset\n");
return -EINVAL;
}
/* this might fail for zero-sized uploads - are those illegal? */
if (!radeon_check_offset(dev_priv, tex->offset + tex->height * tex->pitch - 1)) {
DRM_ERROR("Invalid final destination offset\n");
return -EINVAL;
}
size = tex->height * tex->pitch;
if (size == 0)
return 0;
dst_offset = tex->offset;
if (r600_prepare_blit_copy(dev, file_priv)) {
DRM_ERROR("unable to allocate vertex buffer for swap buffer\n");
return -EAGAIN;
}
do {
data = (const u8 __user *)image->data;
pass_size = size;
buf = radeon_freelist_get(dev);
if (!buf) {
DRM_DEBUG("EAGAIN\n");
if (DRM_COPY_TO_USER(tex->image, image, sizeof(*image)))
return -EFAULT;
return -EAGAIN;
}
if (pass_size > buf->total)
pass_size = buf->total;
/* Dispatch the indirect buffer.
*/
buffer =
(u32 *) ((char *)dev->agp_buffer_map->handle + buf->offset);
if (DRM_COPY_FROM_USER(buffer, data, pass_size)) {
DRM_ERROR("EFAULT on pad, %d bytes\n", pass_size);
return -EFAULT;
}
buf->file_priv = file_priv;
buf->used = pass_size;
src_offset = dev_priv->gart_buffers_offset + buf->offset;
r600_blit_copy(dev, src_offset, dst_offset, pass_size);
radeon_cp_discard_buffer(dev, file_priv->master, buf);
/* Update the input parameters for next time */
image->data = (const u8 __user *)image->data + pass_size;
dst_offset += pass_size;
size -= pass_size;
} while (size > 0);
r600_done_blit_copy(dev);
return 0;
}
/*
* Legacy cs ioctl
*/
static u32 radeon_cs_id_get(struct drm_radeon_private *radeon)
{
/* FIXME: check if wrap affect last reported wrap & sequence */
radeon->cs_id_scnt = (radeon->cs_id_scnt + 1) & 0x00FFFFFF;
if (!radeon->cs_id_scnt) {
/* increment wrap counter */
radeon->cs_id_wcnt += 0x01000000;
/* valid sequence counter start at 1 */
radeon->cs_id_scnt = 1;
}
return (radeon->cs_id_scnt | radeon->cs_id_wcnt);
}
static void r600_cs_id_emit(drm_radeon_private_t *dev_priv, u32 *id)
{
RING_LOCALS;
*id = radeon_cs_id_get(dev_priv);
/* SCRATCH 2 */
BEGIN_RING(3);
R600_CLEAR_AGE(*id);
ADVANCE_RING();
COMMIT_RING();
}
static int r600_ib_get(struct drm_device *dev,
struct drm_file *fpriv,
struct drm_buf **buffer)
{
struct drm_buf *buf;
*buffer = NULL;
buf = radeon_freelist_get(dev);
if (!buf) {
return -EBUSY;
}
buf->file_priv = fpriv;
*buffer = buf;
return 0;
}
static void r600_ib_free(struct drm_device *dev, struct drm_buf *buf,
struct drm_file *fpriv, int l, int r)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if (buf) {
if (!r)
r600_cp_dispatch_indirect(dev, buf, 0, l * 4);
radeon_cp_discard_buffer(dev, fpriv->master, buf);
COMMIT_RING();
}
}
int r600_cs_legacy_ioctl(struct drm_device *dev, void *data, struct drm_file *fpriv)
{
struct drm_radeon_private *dev_priv = dev->dev_private;
struct drm_radeon_cs *cs = data;
struct drm_buf *buf;
unsigned family;
int l, r = 0;
u32 *ib, cs_id = 0;
if (dev_priv == NULL) {
DRM_ERROR("called with no initialization\n");
return -EINVAL;
}
family = dev_priv->flags & RADEON_FAMILY_MASK;
if (family < CHIP_R600) {
DRM_ERROR("cs ioctl valid only for R6XX & R7XX in legacy mode\n");
return -EINVAL;
}
mutex_lock(&dev_priv->cs_mutex);
/* get ib */
r = r600_ib_get(dev, fpriv, &buf);
if (r) {
DRM_ERROR("ib_get failed\n");
goto out;
}
ib = dev->agp_buffer_map->handle + buf->offset;
/* now parse command stream */
r = r600_cs_legacy(dev, data, fpriv, family, ib, &l);
if (r) {
goto out;
}
out:
r600_ib_free(dev, buf, fpriv, l, r);
/* emit cs id sequence */
r600_cs_id_emit(dev_priv, &cs_id);
cs->cs_id = cs_id;
mutex_unlock(&dev_priv->cs_mutex);
return r;
}
void r600_cs_legacy_get_tiling_conf(struct drm_device *dev, u32 *npipes, u32 *nbanks, u32 *group_size)
{
struct drm_radeon_private *dev_priv = dev->dev_private;
*npipes = dev_priv->r600_npipes;
*nbanks = dev_priv->r600_nbanks;
*group_size = dev_priv->r600_group_size;
}
| gpl-2.0 |
Sawed0ff/g3_kernel | drivers/staging/rtl8712/rtl871x_recv.c | 817 | 21590 | /******************************************************************************
* rtl871x_recv.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_RECV_C_
#include <linux/slab.h>
#include <linux/kmemleak.h>
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "mlme_osdep.h"
#include "ip.h"
#include "if_ether.h"
#include "ethernet.h"
#include "usb_ops.h"
#include "wifi.h"
static const u8 SNAP_ETH_TYPE_IPX[2] = {0x81, 0x37};
/* Datagram Delivery Protocol */
static const u8 SNAP_ETH_TYPE_APPLETALK_AARP[2] = {0x80, 0xf3};
/* Bridge-Tunnel header (for EtherTypes ETH_P_AARP and ETH_P_IPX) */
static const u8 bridge_tunnel_header[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8};
/* Ethernet-II snap header (RFC1042 for most EtherTypes) */
static const u8 rfc1042_header[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
void _r8712_init_sta_recv_priv(struct sta_recv_priv *psta_recvpriv)
{
memset((u8 *)psta_recvpriv, 0, sizeof(struct sta_recv_priv));
spin_lock_init(&psta_recvpriv->lock);
_init_queue(&psta_recvpriv->defrag_q);
}
sint _r8712_init_recv_priv(struct recv_priv *precvpriv,
struct _adapter *padapter)
{
sint i;
union recv_frame *precvframe;
memset((unsigned char *)precvpriv, 0, sizeof(struct recv_priv));
spin_lock_init(&precvpriv->lock);
_init_queue(&precvpriv->free_recv_queue);
_init_queue(&precvpriv->recv_pending_queue);
precvpriv->adapter = padapter;
precvpriv->free_recvframe_cnt = NR_RECVFRAME;
precvpriv->pallocated_frame_buf = _malloc(NR_RECVFRAME *
sizeof(union recv_frame) +
RXFRAME_ALIGN_SZ);
if (precvpriv->pallocated_frame_buf == NULL)
return _FAIL;
kmemleak_not_leak(precvpriv->pallocated_frame_buf);
memset(precvpriv->pallocated_frame_buf, 0, NR_RECVFRAME *
sizeof(union recv_frame) + RXFRAME_ALIGN_SZ);
precvpriv->precv_frame_buf = precvpriv->pallocated_frame_buf +
RXFRAME_ALIGN_SZ -
((addr_t)(precvpriv->pallocated_frame_buf) &
(RXFRAME_ALIGN_SZ-1));
precvframe = (union recv_frame *)precvpriv->precv_frame_buf;
for (i = 0; i < NR_RECVFRAME; i++) {
_init_listhead(&(precvframe->u.list));
list_insert_tail(&(precvframe->u.list),
&(precvpriv->free_recv_queue.queue));
r8712_os_recv_resource_alloc(padapter, precvframe);
precvframe->u.hdr.adapter = padapter;
precvframe++;
}
precvpriv->rx_pending_cnt = 1;
return r8712_init_recv_priv(precvpriv, padapter);
}
void _r8712_free_recv_priv(struct recv_priv *precvpriv)
{
kfree(precvpriv->pallocated_frame_buf);
r8712_free_recv_priv(precvpriv);
}
union recv_frame *r8712_alloc_recvframe(struct __queue *pfree_recv_queue)
{
unsigned long irqL;
union recv_frame *precvframe;
struct list_head *plist, *phead;
struct _adapter *padapter;
struct recv_priv *precvpriv;
spin_lock_irqsave(&pfree_recv_queue->lock, irqL);
if (_queue_empty(pfree_recv_queue) == true)
precvframe = NULL;
else {
phead = get_list_head(pfree_recv_queue);
plist = get_next(phead);
precvframe = LIST_CONTAINOR(plist, union recv_frame, u);
list_delete(&precvframe->u.hdr.list);
padapter = precvframe->u.hdr.adapter;
if (padapter != NULL) {
precvpriv = &padapter->recvpriv;
if (pfree_recv_queue == &precvpriv->free_recv_queue)
precvpriv->free_recvframe_cnt--;
}
}
spin_unlock_irqrestore(&pfree_recv_queue->lock, irqL);
return precvframe;
}
/*
caller : defrag; recvframe_chk_defrag in recv_thread (passive)
pframequeue: defrag_queue : will be accessed in recv_thread (passive)
using spin_lock to protect
*/
void r8712_free_recvframe_queue(struct __queue *pframequeue,
struct __queue *pfree_recv_queue)
{
union recv_frame *precvframe;
struct list_head *plist, *phead;
spin_lock(&pframequeue->lock);
phead = get_list_head(pframequeue);
plist = get_next(phead);
while (end_of_queue_search(phead, plist) == false) {
precvframe = LIST_CONTAINOR(plist, union recv_frame, u);
plist = get_next(plist);
r8712_free_recvframe(precvframe, pfree_recv_queue);
}
spin_unlock(&pframequeue->lock);
}
sint r8712_recvframe_chkmic(struct _adapter *adapter,
union recv_frame *precvframe)
{
sint i, res = _SUCCESS;
u32 datalen;
u8 miccode[8];
u8 bmic_err = false;
u8 *pframe, *payload, *pframemic;
u8 *mickey, idx, *iv;
struct sta_info *stainfo;
struct rx_pkt_attrib *prxattrib = &precvframe->u.hdr.attrib;
struct security_priv *psecuritypriv = &adapter->securitypriv;
stainfo = r8712_get_stainfo(&adapter->stapriv, &prxattrib->ta[0]);
if (prxattrib->encrypt == _TKIP_) {
/* calculate mic code */
if (stainfo != NULL) {
if (IS_MCAST(prxattrib->ra)) {
iv = precvframe->u.hdr.rx_data +
prxattrib->hdrlen;
idx = iv[3];
mickey = &psecuritypriv->XGrprxmickey[(((idx >>
6) & 0x3)) - 1].skey[0];
if (psecuritypriv->binstallGrpkey == false)
return _FAIL;
} else
mickey = &stainfo->tkiprxmickey.skey[0];
/*icv_len included the mic code*/
datalen = precvframe->u.hdr.len - prxattrib->hdrlen -
prxattrib->iv_len - prxattrib->icv_len - 8;
pframe = precvframe->u.hdr.rx_data;
payload = pframe + prxattrib->hdrlen +
prxattrib->iv_len;
seccalctkipmic(mickey, pframe, payload, datalen,
&miccode[0],
(unsigned char)prxattrib->priority);
pframemic = payload + datalen;
bmic_err = false;
for (i = 0; i < 8; i++) {
if (miccode[i] != *(pframemic + i))
bmic_err = true;
}
if (bmic_err == true) {
if (prxattrib->bdecrypted == true)
r8712_handle_tkip_mic_err(adapter,
(u8)IS_MCAST(prxattrib->ra));
res = _FAIL;
} else {
/* mic checked ok */
if ((psecuritypriv->bcheck_grpkey ==
false) && (IS_MCAST(prxattrib->ra) ==
true))
psecuritypriv->bcheck_grpkey = true;
}
recvframe_pull_tail(precvframe, 8);
}
}
return res;
}
/* decrypt and set the ivlen,icvlen of the recv_frame */
union recv_frame *r8712_decryptor(struct _adapter *padapter,
union recv_frame *precv_frame)
{
struct rx_pkt_attrib *prxattrib = &precv_frame->u.hdr.attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
union recv_frame *return_packet = precv_frame;
if ((prxattrib->encrypt > 0) && ((prxattrib->bdecrypted == 0) ||
(psecuritypriv->sw_decrypt == true))) {
psecuritypriv->hw_decrypted = false;
switch (prxattrib->encrypt) {
case _WEP40_:
case _WEP104_:
r8712_wep_decrypt(padapter, (u8 *)precv_frame);
break;
case _TKIP_:
r8712_tkip_decrypt(padapter, (u8 *)precv_frame);
break;
case _AES_:
r8712_aes_decrypt(padapter, (u8 *)precv_frame);
break;
default:
break;
}
} else if (prxattrib->bdecrypted == 1)
psecuritypriv->hw_decrypted = true;
return return_packet;
}
/*###set the security information in the recv_frame */
union recv_frame *r8712_portctrl(struct _adapter *adapter,
union recv_frame *precv_frame)
{
u8 *psta_addr, *ptr;
uint auth_alg;
struct recv_frame_hdr *pfhdr;
struct sta_info *psta;
struct sta_priv *pstapriv;
union recv_frame *prtnframe;
u16 ether_type;
pstapriv = &adapter->stapriv;
ptr = get_recvframe_data(precv_frame);
pfhdr = &precv_frame->u.hdr;
psta_addr = pfhdr->attrib.ta;
psta = r8712_get_stainfo(pstapriv, psta_addr);
auth_alg = adapter->securitypriv.AuthAlgrthm;
if (auth_alg == 2) {
/* get ether_type */
ptr = ptr + pfhdr->attrib.hdrlen + LLC_HEADER_SIZE;
memcpy(ðer_type, ptr, 2);
ether_type = ntohs((unsigned short)ether_type);
if ((psta != NULL) && (psta->ieee8021x_blocked)) {
/* blocked
* only accept EAPOL frame */
if (ether_type == 0x888e)
prtnframe = precv_frame;
else {
/*free this frame*/
r8712_free_recvframe(precv_frame,
&adapter->recvpriv.free_recv_queue);
prtnframe = NULL;
}
} else {
/* allowed
* check decryption status, and decrypt the
* frame if needed */
prtnframe = precv_frame;
/* check is the EAPOL frame or not (Rekey) */
if (ether_type == 0x888e) {
/* check Rekey */
prtnframe = precv_frame;
}
}
} else
prtnframe = precv_frame;
return prtnframe;
}
static sint recv_decache(union recv_frame *precv_frame, u8 bretry,
struct stainfo_rxcache *prxcache)
{
sint tid = precv_frame->u.hdr.attrib.priority;
u16 seq_ctrl = ((precv_frame->u.hdr.attrib.seq_num&0xffff) << 4) |
(precv_frame->u.hdr.attrib.frag_num & 0xf);
if (tid > 15)
return _FAIL;
if (seq_ctrl == prxcache->tid_rxseq[tid])
return _FAIL;
prxcache->tid_rxseq[tid] = seq_ctrl;
return _SUCCESS;
}
static sint sta2sta_data_frame(struct _adapter *adapter,
union recv_frame *precv_frame,
struct sta_info **psta)
{
u8 *ptr = precv_frame->u.hdr.rx_data;
sint ret = _SUCCESS;
struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib;
struct sta_priv *pstapriv = &adapter->stapriv;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
u8 *mybssid = get_bssid(pmlmepriv);
u8 *myhwaddr = myid(&adapter->eeprompriv);
u8 *sta_addr = NULL;
sint bmcast = IS_MCAST(pattrib->dst);
if ((check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == true) ||
(check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == true)) {
/* filter packets that SA is myself or multicast or broadcast */
if (!memcmp(myhwaddr, pattrib->src, ETH_ALEN))
return _FAIL;
if ((memcmp(myhwaddr, pattrib->dst, ETH_ALEN)) && (!bmcast))
return _FAIL;
if (!memcmp(pattrib->bssid, "\x0\x0\x0\x0\x0\x0", ETH_ALEN) ||
!memcmp(mybssid, "\x0\x0\x0\x0\x0\x0", ETH_ALEN) ||
(memcmp(pattrib->bssid, mybssid, ETH_ALEN)))
return _FAIL;
sta_addr = pattrib->src;
} else if (check_fwstate(pmlmepriv, WIFI_STATION_STATE) == true) {
/* For Station mode, sa and bssid should always be BSSID,
* and DA is my mac-address */
if (memcmp(pattrib->bssid, pattrib->src, ETH_ALEN))
return _FAIL;
sta_addr = pattrib->bssid;
} else if (check_fwstate(pmlmepriv, WIFI_AP_STATE) == true) {
if (bmcast) {
/* For AP mode, if DA == MCAST, then BSSID should
* be also MCAST */
if (!IS_MCAST(pattrib->bssid))
return _FAIL;
} else { /* not mc-frame */
/* For AP mode, if DA is non-MCAST, then it must be
* BSSID, and bssid == BSSID */
if (memcmp(pattrib->bssid, pattrib->dst, ETH_ALEN))
return _FAIL;
sta_addr = pattrib->src;
}
} else if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) {
memcpy(pattrib->dst, GetAddr1Ptr(ptr), ETH_ALEN);
memcpy(pattrib->src, GetAddr2Ptr(ptr), ETH_ALEN);
memcpy(pattrib->bssid, GetAddr3Ptr(ptr), ETH_ALEN);
memcpy(pattrib->ra, pattrib->dst, ETH_ALEN);
memcpy(pattrib->ta, pattrib->src, ETH_ALEN);
sta_addr = mybssid;
} else
ret = _FAIL;
if (bmcast)
*psta = r8712_get_bcmc_stainfo(adapter);
else
*psta = r8712_get_stainfo(pstapriv, sta_addr); /* get ap_info */
if (*psta == NULL) {
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true)
adapter->mppriv.rx_pktloss++;
return _FAIL;
}
return ret;
}
static sint ap2sta_data_frame(struct _adapter *adapter,
union recv_frame *precv_frame,
struct sta_info **psta)
{
u8 *ptr = precv_frame->u.hdr.rx_data;
struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib;
struct sta_priv *pstapriv = &adapter->stapriv;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
u8 *mybssid = get_bssid(pmlmepriv);
u8 *myhwaddr = myid(&adapter->eeprompriv);
sint bmcast = IS_MCAST(pattrib->dst);
if ((check_fwstate(pmlmepriv, WIFI_STATION_STATE) == true)
&& (check_fwstate(pmlmepriv, _FW_LINKED) == true)) {
/* if NULL-frame, drop packet */
if ((GetFrameSubType(ptr)) == WIFI_DATA_NULL)
return _FAIL;
/* drop QoS-SubType Data, including QoS NULL,
* excluding QoS-Data */
if ((GetFrameSubType(ptr) & WIFI_QOS_DATA_TYPE) ==
WIFI_QOS_DATA_TYPE) {
if (GetFrameSubType(ptr) & (BIT(4) | BIT(5) | BIT(6)))
return _FAIL;
}
/* filter packets that SA is myself or multicast or broadcast */
if (!memcmp(myhwaddr, pattrib->src, ETH_ALEN))
return _FAIL;
/* da should be for me */
if ((memcmp(myhwaddr, pattrib->dst, ETH_ALEN)) && (!bmcast))
return _FAIL;
/* check BSSID */
if (!memcmp(pattrib->bssid, "\x0\x0\x0\x0\x0\x0", ETH_ALEN) ||
!memcmp(mybssid, "\x0\x0\x0\x0\x0\x0", ETH_ALEN) ||
(memcmp(pattrib->bssid, mybssid, ETH_ALEN)))
return _FAIL;
if (bmcast)
*psta = r8712_get_bcmc_stainfo(adapter);
else
*psta = r8712_get_stainfo(pstapriv, pattrib->bssid);
if (*psta == NULL)
return _FAIL;
} else if ((check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) &&
(check_fwstate(pmlmepriv, _FW_LINKED) == true)) {
memcpy(pattrib->dst, GetAddr1Ptr(ptr), ETH_ALEN);
memcpy(pattrib->src, GetAddr2Ptr(ptr), ETH_ALEN);
memcpy(pattrib->bssid, GetAddr3Ptr(ptr), ETH_ALEN);
memcpy(pattrib->ra, pattrib->dst, ETH_ALEN);
memcpy(pattrib->ta, pattrib->src, ETH_ALEN);
memcpy(pattrib->bssid, mybssid, ETH_ALEN);
*psta = r8712_get_stainfo(pstapriv, pattrib->bssid);
if (*psta == NULL)
return _FAIL;
} else
return _FAIL;
return _SUCCESS;
}
static sint sta2ap_data_frame(struct _adapter *adapter,
union recv_frame *precv_frame,
struct sta_info **psta)
{
struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib;
struct sta_priv *pstapriv = &adapter->stapriv;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
unsigned char *mybssid = get_bssid(pmlmepriv);
if (check_fwstate(pmlmepriv, WIFI_AP_STATE) == true) {
/* For AP mode, if DA is non-MCAST, then it must be BSSID,
* and bssid == BSSID
* For AP mode, RA=BSSID, TX=STA(SRC_ADDR), A3=DST_ADDR */
if (memcmp(pattrib->bssid, mybssid, ETH_ALEN))
return _FAIL;
*psta = r8712_get_stainfo(pstapriv, pattrib->src);
if (*psta == NULL)
return _FAIL;
}
return _SUCCESS;
}
static sint validate_recv_ctrl_frame(struct _adapter *adapter,
union recv_frame *precv_frame)
{
return _FAIL;
}
static sint validate_recv_mgnt_frame(struct _adapter *adapter,
union recv_frame *precv_frame)
{
return _FAIL;
}
static sint validate_recv_data_frame(struct _adapter *adapter,
union recv_frame *precv_frame)
{
int res;
u8 bretry;
u8 *psa, *pda, *pbssid;
struct sta_info *psta = NULL;
u8 *ptr = precv_frame->u.hdr.rx_data;
struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib;
struct security_priv *psecuritypriv = &adapter->securitypriv;
bretry = GetRetry(ptr);
pda = get_da(ptr);
psa = get_sa(ptr);
pbssid = get_hdr_bssid(ptr);
if (pbssid == NULL)
return _FAIL;
memcpy(pattrib->dst, pda, ETH_ALEN);
memcpy(pattrib->src, psa, ETH_ALEN);
memcpy(pattrib->bssid, pbssid, ETH_ALEN);
switch (pattrib->to_fr_ds) {
case 0:
memcpy(pattrib->ra, pda, ETH_ALEN);
memcpy(pattrib->ta, psa, ETH_ALEN);
res = sta2sta_data_frame(adapter, precv_frame, &psta);
break;
case 1:
memcpy(pattrib->ra, pda, ETH_ALEN);
memcpy(pattrib->ta, pbssid, ETH_ALEN);
res = ap2sta_data_frame(adapter, precv_frame, &psta);
break;
case 2:
memcpy(pattrib->ra, pbssid, ETH_ALEN);
memcpy(pattrib->ta, psa, ETH_ALEN);
res = sta2ap_data_frame(adapter, precv_frame, &psta);
break;
case 3:
memcpy(pattrib->ra, GetAddr1Ptr(ptr), ETH_ALEN);
memcpy(pattrib->ta, GetAddr2Ptr(ptr), ETH_ALEN);
return _FAIL;
default:
return _FAIL;
}
if (res == _FAIL)
return _FAIL;
if (psta == NULL)
return _FAIL;
else
precv_frame->u.hdr.psta = psta;
pattrib->amsdu = 0;
/* parsing QC field */
if (pattrib->qos == 1) {
pattrib->priority = GetPriority((ptr + 24));
pattrib->ack_policy = GetAckpolicy((ptr + 24));
pattrib->amsdu = GetAMsdu((ptr + 24));
pattrib->hdrlen = pattrib->to_fr_ds == 3 ? 32 : 26;
} else {
pattrib->priority = 0;
pattrib->hdrlen = (pattrib->to_fr_ds == 3) ? 30 : 24;
}
if (pattrib->order)/*HT-CTRL 11n*/
pattrib->hdrlen += 4;
precv_frame->u.hdr.preorder_ctrl =
&psta->recvreorder_ctrl[pattrib->priority];
/* decache, drop duplicate recv packets */
if (recv_decache(precv_frame, bretry, &psta->sta_recvpriv.rxcache) ==
_FAIL)
return _FAIL;
if (pattrib->privacy) {
GET_ENCRY_ALGO(psecuritypriv, psta, pattrib->encrypt,
IS_MCAST(pattrib->ra));
SET_ICE_IV_LEN(pattrib->iv_len, pattrib->icv_len,
pattrib->encrypt);
} else {
pattrib->encrypt = 0;
pattrib->iv_len = pattrib->icv_len = 0;
}
return _SUCCESS;
}
sint r8712_validate_recv_frame(struct _adapter *adapter,
union recv_frame *precv_frame)
{
/*shall check frame subtype, to / from ds, da, bssid */
/*then call check if rx seq/frag. duplicated.*/
u8 type;
u8 subtype;
sint retval = _SUCCESS;
struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib;
u8 *ptr = precv_frame->u.hdr.rx_data;
u8 ver = (unsigned char)(*ptr) & 0x3;
/*add version chk*/
if (ver != 0)
return _FAIL;
type = GetFrameType(ptr);
subtype = GetFrameSubType(ptr); /*bit(7)~bit(2)*/
pattrib->to_fr_ds = get_tofr_ds(ptr);
pattrib->frag_num = GetFragNum(ptr);
pattrib->seq_num = GetSequence(ptr);
pattrib->pw_save = GetPwrMgt(ptr);
pattrib->mfrag = GetMFrag(ptr);
pattrib->mdata = GetMData(ptr);
pattrib->privacy = GetPrivacy(ptr);
pattrib->order = GetOrder(ptr);
switch (type) {
case WIFI_MGT_TYPE: /*mgnt*/
retval = validate_recv_mgnt_frame(adapter, precv_frame);
break;
case WIFI_CTRL_TYPE:/*ctrl*/
retval = validate_recv_ctrl_frame(adapter, precv_frame);
break;
case WIFI_DATA_TYPE: /*data*/
pattrib->qos = (subtype & BIT(7)) ? 1 : 0;
retval = validate_recv_data_frame(adapter, precv_frame);
break;
default:
return _FAIL;
}
return retval;
}
sint r8712_wlanhdr_to_ethhdr(union recv_frame *precvframe)
{
/*remove the wlanhdr and add the eth_hdr*/
sint rmv_len;
u16 eth_type, len;
u8 bsnaphdr;
u8 *psnap_type;
struct ieee80211_snap_hdr *psnap;
sint ret = _SUCCESS;
struct _adapter *adapter = precvframe->u.hdr.adapter;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
u8 *ptr = get_recvframe_data(precvframe); /*point to frame_ctrl field*/
struct rx_pkt_attrib *pattrib = &precvframe->u.hdr.attrib;
if (pattrib->encrypt)
recvframe_pull_tail(precvframe, pattrib->icv_len);
psnap = (struct ieee80211_snap_hdr *)(ptr + pattrib->hdrlen +
pattrib->iv_len);
psnap_type = ptr + pattrib->hdrlen + pattrib->iv_len + SNAP_SIZE;
/* convert hdr + possible LLC headers into Ethernet header */
if ((!memcmp(psnap, (void *)rfc1042_header, SNAP_SIZE) &&
(memcmp(psnap_type, (void *)SNAP_ETH_TYPE_IPX, 2)) &&
(memcmp(psnap_type, (void *)SNAP_ETH_TYPE_APPLETALK_AARP, 2))) ||
!memcmp(psnap, (void *)bridge_tunnel_header, SNAP_SIZE)) {
/* remove RFC1042 or Bridge-Tunnel encapsulation and
* replace EtherType */
bsnaphdr = true;
} else {
/* Leave Ethernet header part of hdr and full payload */
bsnaphdr = false;
}
rmv_len = pattrib->hdrlen + pattrib->iv_len +
(bsnaphdr ? SNAP_SIZE : 0);
len = precvframe->u.hdr.len - rmv_len;
if ((check_fwstate(pmlmepriv, WIFI_MP_STATE) == true)) {
ptr += rmv_len;
*ptr = 0x87;
*(ptr+1) = 0x12;
eth_type = 0x8712;
/* append rx status for mp test packets */
ptr = recvframe_pull(precvframe, (rmv_len -
sizeof(struct ethhdr) + 2) - 24);
memcpy(ptr, get_rxmem(precvframe), 24);
ptr += 24;
} else
ptr = recvframe_pull(precvframe, (rmv_len -
sizeof(struct ethhdr) + (bsnaphdr ? 2 : 0)));
memcpy(ptr, pattrib->dst, ETH_ALEN);
memcpy(ptr+ETH_ALEN, pattrib->src, ETH_ALEN);
if (!bsnaphdr) {
len = htons(len);
memcpy(ptr + 12, &len, 2);
}
return ret;
}
s32 r8712_recv_entry(union recv_frame *precvframe)
{
struct _adapter *padapter;
struct recv_priv *precvpriv;
struct mlme_priv *pmlmepriv;
struct recv_stat *prxstat;
struct dvobj_priv *pdev;
u8 *phead, *pdata, *ptail, *pend;
struct __queue *pfree_recv_queue, *ppending_recv_queue;
s32 ret = _SUCCESS;
struct intf_hdl *pintfhdl;
padapter = precvframe->u.hdr.adapter;
pintfhdl = &padapter->pio_queue->intf;
pmlmepriv = &padapter->mlmepriv;
precvpriv = &(padapter->recvpriv);
pdev = &padapter->dvobjpriv;
pfree_recv_queue = &(precvpriv->free_recv_queue);
ppending_recv_queue = &(precvpriv->recv_pending_queue);
phead = precvframe->u.hdr.rx_head;
pdata = precvframe->u.hdr.rx_data;
ptail = precvframe->u.hdr.rx_tail;
pend = precvframe->u.hdr.rx_end;
prxstat = (struct recv_stat *)phead;
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_RX);
ret = recv_func(padapter, precvframe);
if (ret == _FAIL)
goto _recv_entry_drop;
precvpriv->rx_pkts++;
precvpriv->rx_bytes += (uint)(precvframe->u.hdr.rx_tail -
precvframe->u.hdr.rx_data);
return ret;
_recv_entry_drop:
precvpriv->rx_drop++;
padapter->mppriv.rx_pktloss = precvpriv->rx_drop;
return ret;
}
| gpl-2.0 |
Ateeq72/hTC_Pico_Kernel | sound/pci/ens1370.c | 2609 | 80877 | /*
* Driver for Ensoniq ES1370/ES1371 AudioPCI soundcard
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>,
* Thomas Sailer <sailer@ife.ee.ethz.ch>
*
* 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
*
*/
/* Power-Management-Code ( CONFIG_PM )
* for ens1371 only ( FIXME )
* derived from cs4281.c, atiixp.c and via82xx.c
* using http://www.alsa-project.org/~tiwai/writing-an-alsa-driver/
* by Kurt J. Bosch
*/
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#ifdef CHIP1371
#include <sound/ac97_codec.h>
#else
#include <sound/ak4531_codec.h>
#endif
#include <sound/initval.h>
#include <sound/asoundef.h>
#ifndef CHIP1371
#undef CHIP1370
#define CHIP1370
#endif
#ifdef CHIP1370
#define DRIVER_NAME "ENS1370"
#else
#define DRIVER_NAME "ENS1371"
#endif
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Thomas Sailer <sailer@ife.ee.ethz.ch>");
MODULE_LICENSE("GPL");
#ifdef CHIP1370
MODULE_DESCRIPTION("Ensoniq AudioPCI ES1370");
MODULE_SUPPORTED_DEVICE("{{Ensoniq,AudioPCI-97 ES1370},"
"{Creative Labs,SB PCI64/128 (ES1370)}}");
#endif
#ifdef CHIP1371
MODULE_DESCRIPTION("Ensoniq/Creative AudioPCI ES1371+");
MODULE_SUPPORTED_DEVICE("{{Ensoniq,AudioPCI ES1371/73},"
"{Ensoniq,AudioPCI ES1373},"
"{Creative Labs,Ectiva EV1938},"
"{Creative Labs,SB PCI64/128 (ES1371/73)},"
"{Creative Labs,Vibra PCI128},"
"{Ectiva,EV1938}}");
#endif
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
#define SUPPORT_JOYSTICK
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable switches */
#ifdef SUPPORT_JOYSTICK
#ifdef CHIP1371
static int joystick_port[SNDRV_CARDS];
#else
static int joystick[SNDRV_CARDS];
#endif
#endif
#ifdef CHIP1371
static int spdif[SNDRV_CARDS];
static int lineio[SNDRV_CARDS];
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Ensoniq AudioPCI soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Ensoniq AudioPCI soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Ensoniq AudioPCI soundcard.");
#ifdef SUPPORT_JOYSTICK
#ifdef CHIP1371
module_param_array(joystick_port, int, NULL, 0444);
MODULE_PARM_DESC(joystick_port, "Joystick port address.");
#else
module_param_array(joystick, bool, NULL, 0444);
MODULE_PARM_DESC(joystick, "Enable joystick.");
#endif
#endif /* SUPPORT_JOYSTICK */
#ifdef CHIP1371
module_param_array(spdif, int, NULL, 0444);
MODULE_PARM_DESC(spdif, "S/PDIF output (-1 = none, 0 = auto, 1 = force).");
module_param_array(lineio, int, NULL, 0444);
MODULE_PARM_DESC(lineio, "Line In to Rear Out (0 = auto, 1 = force).");
#endif
/* ES1371 chip ID */
/* This is a little confusing because all ES1371 compatible chips have the
same DEVICE_ID, the only thing differentiating them is the REV_ID field.
This is only significant if you want to enable features on the later parts.
Yes, I know it's stupid and why didn't we use the sub IDs?
*/
#define ES1371REV_ES1373_A 0x04
#define ES1371REV_ES1373_B 0x06
#define ES1371REV_CT5880_A 0x07
#define CT5880REV_CT5880_C 0x02
#define CT5880REV_CT5880_D 0x03 /* ??? -jk */
#define CT5880REV_CT5880_E 0x04 /* mw */
#define ES1371REV_ES1371_B 0x09
#define EV1938REV_EV1938_A 0x00
#define ES1371REV_ES1373_8 0x08
/*
* Direct registers
*/
#define ES_REG(ensoniq, x) ((ensoniq)->port + ES_REG_##x)
#define ES_REG_CONTROL 0x00 /* R/W: Interrupt/Chip select control register */
#define ES_1370_ADC_STOP (1<<31) /* disable capture buffer transfers */
#define ES_1370_XCTL1 (1<<30) /* general purpose output bit */
#define ES_1373_BYPASS_P1 (1<<31) /* bypass SRC for PB1 */
#define ES_1373_BYPASS_P2 (1<<30) /* bypass SRC for PB2 */
#define ES_1373_BYPASS_R (1<<29) /* bypass SRC for REC */
#define ES_1373_TEST_BIT (1<<28) /* should be set to 0 for normal operation */
#define ES_1373_RECEN_B (1<<27) /* mix record with playback for I2S/SPDIF out */
#define ES_1373_SPDIF_THRU (1<<26) /* 0 = SPDIF thru mode, 1 = SPDIF == dig out */
#define ES_1371_JOY_ASEL(o) (((o)&0x03)<<24)/* joystick port mapping */
#define ES_1371_JOY_ASELM (0x03<<24) /* mask for above */
#define ES_1371_JOY_ASELI(i) (((i)>>24)&0x03)
#define ES_1371_GPIO_IN(i) (((i)>>20)&0x0f)/* GPIO in [3:0] pins - R/O */
#define ES_1370_PCLKDIVO(o) (((o)&0x1fff)<<16)/* clock divide ratio for DAC2 */
#define ES_1370_PCLKDIVM ((0x1fff)<<16) /* mask for above */
#define ES_1370_PCLKDIVI(i) (((i)>>16)&0x1fff)/* clock divide ratio for DAC2 */
#define ES_1371_GPIO_OUT(o) (((o)&0x0f)<<16)/* GPIO out [3:0] pins - W/R */
#define ES_1371_GPIO_OUTM (0x0f<<16) /* mask for above */
#define ES_MSFMTSEL (1<<15) /* MPEG serial data format; 0 = SONY, 1 = I2S */
#define ES_1370_M_SBB (1<<14) /* clock source for DAC - 0 = clock generator; 1 = MPEG clocks */
#define ES_1371_SYNC_RES (1<<14) /* Warm AC97 reset */
#define ES_1370_WTSRSEL(o) (((o)&0x03)<<12)/* fixed frequency clock for DAC1 */
#define ES_1370_WTSRSELM (0x03<<12) /* mask for above */
#define ES_1371_ADC_STOP (1<<13) /* disable CCB transfer capture information */
#define ES_1371_PWR_INTRM (1<<12) /* power level change interrupts enable */
#define ES_1370_DAC_SYNC (1<<11) /* DAC's are synchronous */
#define ES_1371_M_CB (1<<11) /* capture clock source; 0 = AC'97 ADC; 1 = I2S */
#define ES_CCB_INTRM (1<<10) /* CCB voice interrupts enable */
#define ES_1370_M_CB (1<<9) /* capture clock source; 0 = ADC; 1 = MPEG */
#define ES_1370_XCTL0 (1<<8) /* generap purpose output bit */
#define ES_1371_PDLEV(o) (((o)&0x03)<<8) /* current power down level */
#define ES_1371_PDLEVM (0x03<<8) /* mask for above */
#define ES_BREQ (1<<7) /* memory bus request enable */
#define ES_DAC1_EN (1<<6) /* DAC1 playback channel enable */
#define ES_DAC2_EN (1<<5) /* DAC2 playback channel enable */
#define ES_ADC_EN (1<<4) /* ADC capture channel enable */
#define ES_UART_EN (1<<3) /* UART enable */
#define ES_JYSTK_EN (1<<2) /* Joystick module enable */
#define ES_1370_CDC_EN (1<<1) /* Codec interface enable */
#define ES_1371_XTALCKDIS (1<<1) /* Xtal clock disable */
#define ES_1370_SERR_DISABLE (1<<0) /* PCI serr signal disable */
#define ES_1371_PCICLKDIS (1<<0) /* PCI clock disable */
#define ES_REG_STATUS 0x04 /* R/O: Interrupt/Chip select status register */
#define ES_INTR (1<<31) /* Interrupt is pending */
#define ES_1371_ST_AC97_RST (1<<29) /* CT5880 AC'97 Reset bit */
#define ES_1373_REAR_BIT27 (1<<27) /* rear bits: 000 - front, 010 - mirror, 101 - separate */
#define ES_1373_REAR_BIT26 (1<<26)
#define ES_1373_REAR_BIT24 (1<<24)
#define ES_1373_GPIO_INT_EN(o)(((o)&0x0f)<<20)/* GPIO [3:0] pins - interrupt enable */
#define ES_1373_SPDIF_EN (1<<18) /* SPDIF enable */
#define ES_1373_SPDIF_TEST (1<<17) /* SPDIF test */
#define ES_1371_TEST (1<<16) /* test ASIC */
#define ES_1373_GPIO_INT(i) (((i)&0x0f)>>12)/* GPIO [3:0] pins - interrupt pending */
#define ES_1370_CSTAT (1<<10) /* CODEC is busy or register write in progress */
#define ES_1370_CBUSY (1<<9) /* CODEC is busy */
#define ES_1370_CWRIP (1<<8) /* CODEC register write in progress */
#define ES_1371_SYNC_ERR (1<<8) /* CODEC synchronization error occurred */
#define ES_1371_VC(i) (((i)>>6)&0x03) /* voice code from CCB module */
#define ES_1370_VC(i) (((i)>>5)&0x03) /* voice code from CCB module */
#define ES_1371_MPWR (1<<5) /* power level interrupt pending */
#define ES_MCCB (1<<4) /* CCB interrupt pending */
#define ES_UART (1<<3) /* UART interrupt pending */
#define ES_DAC1 (1<<2) /* DAC1 channel interrupt pending */
#define ES_DAC2 (1<<1) /* DAC2 channel interrupt pending */
#define ES_ADC (1<<0) /* ADC channel interrupt pending */
#define ES_REG_UART_DATA 0x08 /* R/W: UART data register */
#define ES_REG_UART_STATUS 0x09 /* R/O: UART status register */
#define ES_RXINT (1<<7) /* RX interrupt occurred */
#define ES_TXINT (1<<2) /* TX interrupt occurred */
#define ES_TXRDY (1<<1) /* transmitter ready */
#define ES_RXRDY (1<<0) /* receiver ready */
#define ES_REG_UART_CONTROL 0x09 /* W/O: UART control register */
#define ES_RXINTEN (1<<7) /* RX interrupt enable */
#define ES_TXINTENO(o) (((o)&0x03)<<5) /* TX interrupt enable */
#define ES_TXINTENM (0x03<<5) /* mask for above */
#define ES_TXINTENI(i) (((i)>>5)&0x03)
#define ES_CNTRL(o) (((o)&0x03)<<0) /* control */
#define ES_CNTRLM (0x03<<0) /* mask for above */
#define ES_REG_UART_RES 0x0a /* R/W: UART reserver register */
#define ES_TEST_MODE (1<<0) /* test mode enabled */
#define ES_REG_MEM_PAGE 0x0c /* R/W: Memory page register */
#define ES_MEM_PAGEO(o) (((o)&0x0f)<<0) /* memory page select - out */
#define ES_MEM_PAGEM (0x0f<<0) /* mask for above */
#define ES_MEM_PAGEI(i) (((i)>>0)&0x0f) /* memory page select - in */
#define ES_REG_1370_CODEC 0x10 /* W/O: Codec write register address */
#define ES_1370_CODEC_WRITE(a,d) ((((a)&0xff)<<8)|(((d)&0xff)<<0))
#define ES_REG_1371_CODEC 0x14 /* W/R: Codec Read/Write register address */
#define ES_1371_CODEC_RDY (1<<31) /* codec ready */
#define ES_1371_CODEC_WIP (1<<30) /* codec register access in progress */
#define EV_1938_CODEC_MAGIC (1<<26)
#define ES_1371_CODEC_PIRD (1<<23) /* codec read/write select register */
#define ES_1371_CODEC_WRITE(a,d) ((((a)&0x7f)<<16)|(((d)&0xffff)<<0))
#define ES_1371_CODEC_READS(a) ((((a)&0x7f)<<16)|ES_1371_CODEC_PIRD)
#define ES_1371_CODEC_READ(i) (((i)>>0)&0xffff)
#define ES_REG_1371_SMPRATE 0x10 /* W/R: Codec rate converter interface register */
#define ES_1371_SRC_RAM_ADDRO(o) (((o)&0x7f)<<25)/* address of the sample rate converter */
#define ES_1371_SRC_RAM_ADDRM (0x7f<<25) /* mask for above */
#define ES_1371_SRC_RAM_ADDRI(i) (((i)>>25)&0x7f)/* address of the sample rate converter */
#define ES_1371_SRC_RAM_WE (1<<24) /* R/W: read/write control for sample rate converter */
#define ES_1371_SRC_RAM_BUSY (1<<23) /* R/O: sample rate memory is busy */
#define ES_1371_SRC_DISABLE (1<<22) /* sample rate converter disable */
#define ES_1371_DIS_P1 (1<<21) /* playback channel 1 accumulator update disable */
#define ES_1371_DIS_P2 (1<<20) /* playback channel 1 accumulator update disable */
#define ES_1371_DIS_R1 (1<<19) /* capture channel accumulator update disable */
#define ES_1371_SRC_RAM_DATAO(o) (((o)&0xffff)<<0)/* current value of the sample rate converter */
#define ES_1371_SRC_RAM_DATAM (0xffff<<0) /* mask for above */
#define ES_1371_SRC_RAM_DATAI(i) (((i)>>0)&0xffff)/* current value of the sample rate converter */
#define ES_REG_1371_LEGACY 0x18 /* W/R: Legacy control/status register */
#define ES_1371_JFAST (1<<31) /* fast joystick timing */
#define ES_1371_HIB (1<<30) /* host interrupt blocking enable */
#define ES_1371_VSB (1<<29) /* SB; 0 = addr 0x220xH, 1 = 0x22FxH */
#define ES_1371_VMPUO(o) (((o)&0x03)<<27)/* base register address; 0 = 0x320xH; 1 = 0x330xH; 2 = 0x340xH; 3 = 0x350xH */
#define ES_1371_VMPUM (0x03<<27) /* mask for above */
#define ES_1371_VMPUI(i) (((i)>>27)&0x03)/* base register address */
#define ES_1371_VCDCO(o) (((o)&0x03)<<25)/* CODEC; 0 = 0x530xH; 1 = undefined; 2 = 0xe80xH; 3 = 0xF40xH */
#define ES_1371_VCDCM (0x03<<25) /* mask for above */
#define ES_1371_VCDCI(i) (((i)>>25)&0x03)/* CODEC address */
#define ES_1371_FIRQ (1<<24) /* force an interrupt */
#define ES_1371_SDMACAP (1<<23) /* enable event capture for slave DMA controller */
#define ES_1371_SPICAP (1<<22) /* enable event capture for slave IRQ controller */
#define ES_1371_MDMACAP (1<<21) /* enable event capture for master DMA controller */
#define ES_1371_MPICAP (1<<20) /* enable event capture for master IRQ controller */
#define ES_1371_ADCAP (1<<19) /* enable event capture for ADLIB register; 0x388xH */
#define ES_1371_SVCAP (1<<18) /* enable event capture for SB registers */
#define ES_1371_CDCCAP (1<<17) /* enable event capture for CODEC registers */
#define ES_1371_BACAP (1<<16) /* enable event capture for SoundScape base address */
#define ES_1371_EXI(i) (((i)>>8)&0x07) /* event number */
#define ES_1371_AI(i) (((i)>>3)&0x1f) /* event significant I/O address */
#define ES_1371_WR (1<<2) /* event capture; 0 = read; 1 = write */
#define ES_1371_LEGINT (1<<0) /* interrupt for legacy events; 0 = interrupt did occur */
#define ES_REG_CHANNEL_STATUS 0x1c /* R/W: first 32-bits from S/PDIF channel status block, es1373 */
#define ES_REG_SERIAL 0x20 /* R/W: Serial interface control register */
#define ES_1371_DAC_TEST (1<<22) /* DAC test mode enable */
#define ES_P2_END_INCO(o) (((o)&0x07)<<19)/* binary offset value to increment / loop end */
#define ES_P2_END_INCM (0x07<<19) /* mask for above */
#define ES_P2_END_INCI(i) (((i)>>16)&0x07)/* binary offset value to increment / loop end */
#define ES_P2_ST_INCO(o) (((o)&0x07)<<16)/* binary offset value to increment / start */
#define ES_P2_ST_INCM (0x07<<16) /* mask for above */
#define ES_P2_ST_INCI(i) (((i)<<16)&0x07)/* binary offset value to increment / start */
#define ES_R1_LOOP_SEL (1<<15) /* ADC; 0 - loop mode; 1 = stop mode */
#define ES_P2_LOOP_SEL (1<<14) /* DAC2; 0 - loop mode; 1 = stop mode */
#define ES_P1_LOOP_SEL (1<<13) /* DAC1; 0 - loop mode; 1 = stop mode */
#define ES_P2_PAUSE (1<<12) /* DAC2; 0 - play mode; 1 = pause mode */
#define ES_P1_PAUSE (1<<11) /* DAC1; 0 - play mode; 1 = pause mode */
#define ES_R1_INT_EN (1<<10) /* ADC interrupt enable */
#define ES_P2_INT_EN (1<<9) /* DAC2 interrupt enable */
#define ES_P1_INT_EN (1<<8) /* DAC1 interrupt enable */
#define ES_P1_SCT_RLD (1<<7) /* force sample counter reload for DAC1 */
#define ES_P2_DAC_SEN (1<<6) /* when stop mode: 0 - DAC2 play back zeros; 1 = DAC2 play back last sample */
#define ES_R1_MODEO(o) (((o)&0x03)<<4) /* ADC mode; 0 = 8-bit mono; 1 = 8-bit stereo; 2 = 16-bit mono; 3 = 16-bit stereo */
#define ES_R1_MODEM (0x03<<4) /* mask for above */
#define ES_R1_MODEI(i) (((i)>>4)&0x03)
#define ES_P2_MODEO(o) (((o)&0x03)<<2) /* DAC2 mode; -- '' -- */
#define ES_P2_MODEM (0x03<<2) /* mask for above */
#define ES_P2_MODEI(i) (((i)>>2)&0x03)
#define ES_P1_MODEO(o) (((o)&0x03)<<0) /* DAC1 mode; -- '' -- */
#define ES_P1_MODEM (0x03<<0) /* mask for above */
#define ES_P1_MODEI(i) (((i)>>0)&0x03)
#define ES_REG_DAC1_COUNT 0x24 /* R/W: DAC1 sample count register */
#define ES_REG_DAC2_COUNT 0x28 /* R/W: DAC2 sample count register */
#define ES_REG_ADC_COUNT 0x2c /* R/W: ADC sample count register */
#define ES_REG_CURR_COUNT(i) (((i)>>16)&0xffff)
#define ES_REG_COUNTO(o) (((o)&0xffff)<<0)
#define ES_REG_COUNTM (0xffff<<0)
#define ES_REG_COUNTI(i) (((i)>>0)&0xffff)
#define ES_REG_DAC1_FRAME 0x30 /* R/W: PAGE 0x0c; DAC1 frame address */
#define ES_REG_DAC1_SIZE 0x34 /* R/W: PAGE 0x0c; DAC1 frame size */
#define ES_REG_DAC2_FRAME 0x38 /* R/W: PAGE 0x0c; DAC2 frame address */
#define ES_REG_DAC2_SIZE 0x3c /* R/W: PAGE 0x0c; DAC2 frame size */
#define ES_REG_ADC_FRAME 0x30 /* R/W: PAGE 0x0d; ADC frame address */
#define ES_REG_ADC_SIZE 0x34 /* R/W: PAGE 0x0d; ADC frame size */
#define ES_REG_FCURR_COUNTO(o) (((o)&0xffff)<<16)
#define ES_REG_FCURR_COUNTM (0xffff<<16)
#define ES_REG_FCURR_COUNTI(i) (((i)>>14)&0x3fffc)
#define ES_REG_FSIZEO(o) (((o)&0xffff)<<0)
#define ES_REG_FSIZEM (0xffff<<0)
#define ES_REG_FSIZEI(i) (((i)>>0)&0xffff)
#define ES_REG_PHANTOM_FRAME 0x38 /* R/W: PAGE 0x0d: phantom frame address */
#define ES_REG_PHANTOM_COUNT 0x3c /* R/W: PAGE 0x0d: phantom frame count */
#define ES_REG_UART_FIFO 0x30 /* R/W: PAGE 0x0e; UART FIFO register */
#define ES_REG_UF_VALID (1<<8)
#define ES_REG_UF_BYTEO(o) (((o)&0xff)<<0)
#define ES_REG_UF_BYTEM (0xff<<0)
#define ES_REG_UF_BYTEI(i) (((i)>>0)&0xff)
/*
* Pages
*/
#define ES_PAGE_DAC 0x0c
#define ES_PAGE_ADC 0x0d
#define ES_PAGE_UART 0x0e
#define ES_PAGE_UART1 0x0f
/*
* Sample rate converter addresses
*/
#define ES_SMPREG_DAC1 0x70
#define ES_SMPREG_DAC2 0x74
#define ES_SMPREG_ADC 0x78
#define ES_SMPREG_VOL_ADC 0x6c
#define ES_SMPREG_VOL_DAC1 0x7c
#define ES_SMPREG_VOL_DAC2 0x7e
#define ES_SMPREG_TRUNC_N 0x00
#define ES_SMPREG_INT_REGS 0x01
#define ES_SMPREG_ACCUM_FRAC 0x02
#define ES_SMPREG_VFREQ_FRAC 0x03
/*
* Some contants
*/
#define ES_1370_SRCLOCK 1411200
#define ES_1370_SRTODIV(x) (ES_1370_SRCLOCK/(x)-2)
/*
* Open modes
*/
#define ES_MODE_PLAY1 0x0001
#define ES_MODE_PLAY2 0x0002
#define ES_MODE_CAPTURE 0x0004
#define ES_MODE_OUTPUT 0x0001 /* for MIDI */
#define ES_MODE_INPUT 0x0002 /* for MIDI */
/*
*/
struct ensoniq {
spinlock_t reg_lock;
struct mutex src_mutex;
int irq;
unsigned long playback1size;
unsigned long playback2size;
unsigned long capture3size;
unsigned long port;
unsigned int mode;
unsigned int uartm; /* UART mode */
unsigned int ctrl; /* control register */
unsigned int sctrl; /* serial control register */
unsigned int cssr; /* control status register */
unsigned int uartc; /* uart control register */
unsigned int rev; /* chip revision */
union {
#ifdef CHIP1371
struct {
struct snd_ac97 *ac97;
} es1371;
#else
struct {
int pclkdiv_lock;
struct snd_ak4531 *ak4531;
} es1370;
#endif
} u;
struct pci_dev *pci;
struct snd_card *card;
struct snd_pcm *pcm1; /* DAC1/ADC PCM */
struct snd_pcm *pcm2; /* DAC2 PCM */
struct snd_pcm_substream *playback1_substream;
struct snd_pcm_substream *playback2_substream;
struct snd_pcm_substream *capture_substream;
unsigned int p1_dma_size;
unsigned int p2_dma_size;
unsigned int c_dma_size;
unsigned int p1_period_size;
unsigned int p2_period_size;
unsigned int c_period_size;
struct snd_rawmidi *rmidi;
struct snd_rawmidi_substream *midi_input;
struct snd_rawmidi_substream *midi_output;
unsigned int spdif;
unsigned int spdif_default;
unsigned int spdif_stream;
#ifdef CHIP1370
struct snd_dma_buffer dma_bug;
#endif
#ifdef SUPPORT_JOYSTICK
struct gameport *gameport;
#endif
};
static irqreturn_t snd_audiopci_interrupt(int irq, void *dev_id);
static DEFINE_PCI_DEVICE_TABLE(snd_audiopci_ids) = {
#ifdef CHIP1370
{ PCI_VDEVICE(ENSONIQ, 0x5000), 0, }, /* ES1370 */
#endif
#ifdef CHIP1371
{ PCI_VDEVICE(ENSONIQ, 0x1371), 0, }, /* ES1371 */
{ PCI_VDEVICE(ENSONIQ, 0x5880), 0, }, /* ES1373 - CT5880 */
{ PCI_VDEVICE(ECTIVA, 0x8938), 0, }, /* Ectiva EV1938 */
#endif
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_audiopci_ids);
/*
* constants
*/
#define POLL_COUNT 0xa000
#ifdef CHIP1370
static unsigned int snd_es1370_fixed_rates[] =
{5512, 11025, 22050, 44100};
static struct snd_pcm_hw_constraint_list snd_es1370_hw_constraints_rates = {
.count = 4,
.list = snd_es1370_fixed_rates,
.mask = 0,
};
static struct snd_ratnum es1370_clock = {
.num = ES_1370_SRCLOCK,
.den_min = 29,
.den_max = 353,
.den_step = 1,
};
static struct snd_pcm_hw_constraint_ratnums snd_es1370_hw_constraints_clock = {
.nrats = 1,
.rats = &es1370_clock,
};
#else
static struct snd_ratden es1371_dac_clock = {
.num_min = 3000 * (1 << 15),
.num_max = 48000 * (1 << 15),
.num_step = 3000,
.den = 1 << 15,
};
static struct snd_pcm_hw_constraint_ratdens snd_es1371_hw_constraints_dac_clock = {
.nrats = 1,
.rats = &es1371_dac_clock,
};
static struct snd_ratnum es1371_adc_clock = {
.num = 48000 << 15,
.den_min = 32768,
.den_max = 393216,
.den_step = 1,
};
static struct snd_pcm_hw_constraint_ratnums snd_es1371_hw_constraints_adc_clock = {
.nrats = 1,
.rats = &es1371_adc_clock,
};
#endif
static const unsigned int snd_ensoniq_sample_shift[] =
{0, 1, 1, 2};
/*
* common I/O routines
*/
#ifdef CHIP1371
static unsigned int snd_es1371_wait_src_ready(struct ensoniq * ensoniq)
{
unsigned int t, r = 0;
for (t = 0; t < POLL_COUNT; t++) {
r = inl(ES_REG(ensoniq, 1371_SMPRATE));
if ((r & ES_1371_SRC_RAM_BUSY) == 0)
return r;
cond_resched();
}
snd_printk(KERN_ERR "wait src ready timeout 0x%lx [0x%x]\n",
ES_REG(ensoniq, 1371_SMPRATE), r);
return 0;
}
static unsigned int snd_es1371_src_read(struct ensoniq * ensoniq, unsigned short reg)
{
unsigned int temp, i, orig, r;
/* wait for ready */
temp = orig = snd_es1371_wait_src_ready(ensoniq);
/* expose the SRC state bits */
r = temp & (ES_1371_SRC_DISABLE | ES_1371_DIS_P1 |
ES_1371_DIS_P2 | ES_1371_DIS_R1);
r |= ES_1371_SRC_RAM_ADDRO(reg) | 0x10000;
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
/* now, wait for busy and the correct time to read */
temp = snd_es1371_wait_src_ready(ensoniq);
if ((temp & 0x00870000) != 0x00010000) {
/* wait for the right state */
for (i = 0; i < POLL_COUNT; i++) {
temp = inl(ES_REG(ensoniq, 1371_SMPRATE));
if ((temp & 0x00870000) == 0x00010000)
break;
}
}
/* hide the state bits */
r = orig & (ES_1371_SRC_DISABLE | ES_1371_DIS_P1 |
ES_1371_DIS_P2 | ES_1371_DIS_R1);
r |= ES_1371_SRC_RAM_ADDRO(reg);
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
return temp;
}
static void snd_es1371_src_write(struct ensoniq * ensoniq,
unsigned short reg, unsigned short data)
{
unsigned int r;
r = snd_es1371_wait_src_ready(ensoniq) &
(ES_1371_SRC_DISABLE | ES_1371_DIS_P1 |
ES_1371_DIS_P2 | ES_1371_DIS_R1);
r |= ES_1371_SRC_RAM_ADDRO(reg) | ES_1371_SRC_RAM_DATAO(data);
outl(r | ES_1371_SRC_RAM_WE, ES_REG(ensoniq, 1371_SMPRATE));
}
#endif /* CHIP1371 */
#ifdef CHIP1370
static void snd_es1370_codec_write(struct snd_ak4531 *ak4531,
unsigned short reg, unsigned short val)
{
struct ensoniq *ensoniq = ak4531->private_data;
unsigned long end_time = jiffies + HZ / 10;
#if 0
printk(KERN_DEBUG
"CODEC WRITE: reg = 0x%x, val = 0x%x (0x%x), creg = 0x%x\n",
reg, val, ES_1370_CODEC_WRITE(reg, val), ES_REG(ensoniq, 1370_CODEC));
#endif
do {
if (!(inl(ES_REG(ensoniq, STATUS)) & ES_1370_CSTAT)) {
outw(ES_1370_CODEC_WRITE(reg, val), ES_REG(ensoniq, 1370_CODEC));
return;
}
schedule_timeout_uninterruptible(1);
} while (time_after(end_time, jiffies));
snd_printk(KERN_ERR "codec write timeout, status = 0x%x\n",
inl(ES_REG(ensoniq, STATUS)));
}
#endif /* CHIP1370 */
#ifdef CHIP1371
static inline bool is_ev1938(struct ensoniq *ensoniq)
{
return ensoniq->pci->device == 0x8938;
}
static void snd_es1371_codec_write(struct snd_ac97 *ac97,
unsigned short reg, unsigned short val)
{
struct ensoniq *ensoniq = ac97->private_data;
unsigned int t, x, flag;
flag = is_ev1938(ensoniq) ? EV_1938_CODEC_MAGIC : 0;
mutex_lock(&ensoniq->src_mutex);
for (t = 0; t < POLL_COUNT; t++) {
if (!(inl(ES_REG(ensoniq, 1371_CODEC)) & ES_1371_CODEC_WIP)) {
/* save the current state for latter */
x = snd_es1371_wait_src_ready(ensoniq);
outl((x & (ES_1371_SRC_DISABLE | ES_1371_DIS_P1 |
ES_1371_DIS_P2 | ES_1371_DIS_R1)) | 0x00010000,
ES_REG(ensoniq, 1371_SMPRATE));
/* wait for not busy (state 0) first to avoid
transition states */
for (t = 0; t < POLL_COUNT; t++) {
if ((inl(ES_REG(ensoniq, 1371_SMPRATE)) & 0x00870000) ==
0x00000000)
break;
}
/* wait for a SAFE time to write addr/data and then do it, dammit */
for (t = 0; t < POLL_COUNT; t++) {
if ((inl(ES_REG(ensoniq, 1371_SMPRATE)) & 0x00870000) ==
0x00010000)
break;
}
outl(ES_1371_CODEC_WRITE(reg, val) | flag,
ES_REG(ensoniq, 1371_CODEC));
/* restore SRC reg */
snd_es1371_wait_src_ready(ensoniq);
outl(x, ES_REG(ensoniq, 1371_SMPRATE));
mutex_unlock(&ensoniq->src_mutex);
return;
}
}
mutex_unlock(&ensoniq->src_mutex);
snd_printk(KERN_ERR "codec write timeout at 0x%lx [0x%x]\n",
ES_REG(ensoniq, 1371_CODEC), inl(ES_REG(ensoniq, 1371_CODEC)));
}
static unsigned short snd_es1371_codec_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct ensoniq *ensoniq = ac97->private_data;
unsigned int t, x, flag, fail = 0;
flag = is_ev1938(ensoniq) ? EV_1938_CODEC_MAGIC : 0;
__again:
mutex_lock(&ensoniq->src_mutex);
for (t = 0; t < POLL_COUNT; t++) {
if (!(inl(ES_REG(ensoniq, 1371_CODEC)) & ES_1371_CODEC_WIP)) {
/* save the current state for latter */
x = snd_es1371_wait_src_ready(ensoniq);
outl((x & (ES_1371_SRC_DISABLE | ES_1371_DIS_P1 |
ES_1371_DIS_P2 | ES_1371_DIS_R1)) | 0x00010000,
ES_REG(ensoniq, 1371_SMPRATE));
/* wait for not busy (state 0) first to avoid
transition states */
for (t = 0; t < POLL_COUNT; t++) {
if ((inl(ES_REG(ensoniq, 1371_SMPRATE)) & 0x00870000) ==
0x00000000)
break;
}
/* wait for a SAFE time to write addr/data and then do it, dammit */
for (t = 0; t < POLL_COUNT; t++) {
if ((inl(ES_REG(ensoniq, 1371_SMPRATE)) & 0x00870000) ==
0x00010000)
break;
}
outl(ES_1371_CODEC_READS(reg) | flag,
ES_REG(ensoniq, 1371_CODEC));
/* restore SRC reg */
snd_es1371_wait_src_ready(ensoniq);
outl(x, ES_REG(ensoniq, 1371_SMPRATE));
/* wait for WIP again */
for (t = 0; t < POLL_COUNT; t++) {
if (!(inl(ES_REG(ensoniq, 1371_CODEC)) & ES_1371_CODEC_WIP))
break;
}
/* now wait for the stinkin' data (RDY) */
for (t = 0; t < POLL_COUNT; t++) {
if ((x = inl(ES_REG(ensoniq, 1371_CODEC))) & ES_1371_CODEC_RDY) {
if (is_ev1938(ensoniq)) {
for (t = 0; t < 100; t++)
inl(ES_REG(ensoniq, CONTROL));
x = inl(ES_REG(ensoniq, 1371_CODEC));
}
mutex_unlock(&ensoniq->src_mutex);
return ES_1371_CODEC_READ(x);
}
}
mutex_unlock(&ensoniq->src_mutex);
if (++fail > 10) {
snd_printk(KERN_ERR "codec read timeout (final) "
"at 0x%lx, reg = 0x%x [0x%x]\n",
ES_REG(ensoniq, 1371_CODEC), reg,
inl(ES_REG(ensoniq, 1371_CODEC)));
return 0;
}
goto __again;
}
}
mutex_unlock(&ensoniq->src_mutex);
snd_printk(KERN_ERR "es1371: codec read timeout at 0x%lx [0x%x]\n",
ES_REG(ensoniq, 1371_CODEC), inl(ES_REG(ensoniq, 1371_CODEC)));
return 0;
}
static void snd_es1371_codec_wait(struct snd_ac97 *ac97)
{
msleep(750);
snd_es1371_codec_read(ac97, AC97_RESET);
snd_es1371_codec_read(ac97, AC97_VENDOR_ID1);
snd_es1371_codec_read(ac97, AC97_VENDOR_ID2);
msleep(50);
}
static void snd_es1371_adc_rate(struct ensoniq * ensoniq, unsigned int rate)
{
unsigned int n, truncm, freq, result;
mutex_lock(&ensoniq->src_mutex);
n = rate / 3000;
if ((1 << n) & ((1 << 15) | (1 << 13) | (1 << 11) | (1 << 9)))
n--;
truncm = (21 * n - 1) | 1;
freq = ((48000UL << 15) / rate) * n;
result = (48000UL << 15) / (freq / n);
if (rate >= 24000) {
if (truncm > 239)
truncm = 239;
snd_es1371_src_write(ensoniq, ES_SMPREG_ADC + ES_SMPREG_TRUNC_N,
(((239 - truncm) >> 1) << 9) | (n << 4));
} else {
if (truncm > 119)
truncm = 119;
snd_es1371_src_write(ensoniq, ES_SMPREG_ADC + ES_SMPREG_TRUNC_N,
0x8000 | (((119 - truncm) >> 1) << 9) | (n << 4));
}
snd_es1371_src_write(ensoniq, ES_SMPREG_ADC + ES_SMPREG_INT_REGS,
(snd_es1371_src_read(ensoniq, ES_SMPREG_ADC +
ES_SMPREG_INT_REGS) & 0x00ff) |
((freq >> 5) & 0xfc00));
snd_es1371_src_write(ensoniq, ES_SMPREG_ADC + ES_SMPREG_VFREQ_FRAC, freq & 0x7fff);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_ADC, n << 8);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_ADC + 1, n << 8);
mutex_unlock(&ensoniq->src_mutex);
}
static void snd_es1371_dac1_rate(struct ensoniq * ensoniq, unsigned int rate)
{
unsigned int freq, r;
mutex_lock(&ensoniq->src_mutex);
freq = ((rate << 15) + 1500) / 3000;
r = (snd_es1371_wait_src_ready(ensoniq) & (ES_1371_SRC_DISABLE |
ES_1371_DIS_P2 | ES_1371_DIS_R1)) |
ES_1371_DIS_P1;
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC1 + ES_SMPREG_INT_REGS,
(snd_es1371_src_read(ensoniq, ES_SMPREG_DAC1 +
ES_SMPREG_INT_REGS) & 0x00ff) |
((freq >> 5) & 0xfc00));
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC1 + ES_SMPREG_VFREQ_FRAC, freq & 0x7fff);
r = (snd_es1371_wait_src_ready(ensoniq) & (ES_1371_SRC_DISABLE |
ES_1371_DIS_P2 | ES_1371_DIS_R1));
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
mutex_unlock(&ensoniq->src_mutex);
}
static void snd_es1371_dac2_rate(struct ensoniq * ensoniq, unsigned int rate)
{
unsigned int freq, r;
mutex_lock(&ensoniq->src_mutex);
freq = ((rate << 15) + 1500) / 3000;
r = (snd_es1371_wait_src_ready(ensoniq) & (ES_1371_SRC_DISABLE |
ES_1371_DIS_P1 | ES_1371_DIS_R1)) |
ES_1371_DIS_P2;
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC2 + ES_SMPREG_INT_REGS,
(snd_es1371_src_read(ensoniq, ES_SMPREG_DAC2 +
ES_SMPREG_INT_REGS) & 0x00ff) |
((freq >> 5) & 0xfc00));
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC2 + ES_SMPREG_VFREQ_FRAC,
freq & 0x7fff);
r = (snd_es1371_wait_src_ready(ensoniq) & (ES_1371_SRC_DISABLE |
ES_1371_DIS_P1 | ES_1371_DIS_R1));
outl(r, ES_REG(ensoniq, 1371_SMPRATE));
mutex_unlock(&ensoniq->src_mutex);
}
#endif /* CHIP1371 */
static int snd_ensoniq_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
{
unsigned int what = 0;
struct snd_pcm_substream *s;
snd_pcm_group_for_each_entry(s, substream) {
if (s == ensoniq->playback1_substream) {
what |= ES_P1_PAUSE;
snd_pcm_trigger_done(s, substream);
} else if (s == ensoniq->playback2_substream) {
what |= ES_P2_PAUSE;
snd_pcm_trigger_done(s, substream);
} else if (s == ensoniq->capture_substream)
return -EINVAL;
}
spin_lock(&ensoniq->reg_lock);
if (cmd == SNDRV_PCM_TRIGGER_PAUSE_PUSH)
ensoniq->sctrl |= what;
else
ensoniq->sctrl &= ~what;
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
spin_unlock(&ensoniq->reg_lock);
break;
}
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_STOP:
{
unsigned int what = 0;
struct snd_pcm_substream *s;
snd_pcm_group_for_each_entry(s, substream) {
if (s == ensoniq->playback1_substream) {
what |= ES_DAC1_EN;
snd_pcm_trigger_done(s, substream);
} else if (s == ensoniq->playback2_substream) {
what |= ES_DAC2_EN;
snd_pcm_trigger_done(s, substream);
} else if (s == ensoniq->capture_substream) {
what |= ES_ADC_EN;
snd_pcm_trigger_done(s, substream);
}
}
spin_lock(&ensoniq->reg_lock);
if (cmd == SNDRV_PCM_TRIGGER_START)
ensoniq->ctrl |= what;
else
ensoniq->ctrl &= ~what;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock(&ensoniq->reg_lock);
break;
}
default:
return -EINVAL;
}
return 0;
}
/*
* PCM part
*/
static int snd_ensoniq_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_ensoniq_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_ensoniq_playback1_prepare(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int mode = 0;
ensoniq->p1_dma_size = snd_pcm_lib_buffer_bytes(substream);
ensoniq->p1_period_size = snd_pcm_lib_period_bytes(substream);
if (snd_pcm_format_width(runtime->format) == 16)
mode |= 0x02;
if (runtime->channels > 1)
mode |= 0x01;
spin_lock_irq(&ensoniq->reg_lock);
ensoniq->ctrl &= ~ES_DAC1_EN;
#ifdef CHIP1371
/* 48k doesn't need SRC (it breaks AC3-passthru) */
if (runtime->rate == 48000)
ensoniq->ctrl |= ES_1373_BYPASS_P1;
else
ensoniq->ctrl &= ~ES_1373_BYPASS_P1;
#endif
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ES_MEM_PAGEO(ES_PAGE_DAC), ES_REG(ensoniq, MEM_PAGE));
outl(runtime->dma_addr, ES_REG(ensoniq, DAC1_FRAME));
outl((ensoniq->p1_dma_size >> 2) - 1, ES_REG(ensoniq, DAC1_SIZE));
ensoniq->sctrl &= ~(ES_P1_LOOP_SEL | ES_P1_PAUSE | ES_P1_SCT_RLD | ES_P1_MODEM);
ensoniq->sctrl |= ES_P1_INT_EN | ES_P1_MODEO(mode);
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
outl((ensoniq->p1_period_size >> snd_ensoniq_sample_shift[mode]) - 1,
ES_REG(ensoniq, DAC1_COUNT));
#ifdef CHIP1370
ensoniq->ctrl &= ~ES_1370_WTSRSELM;
switch (runtime->rate) {
case 5512: ensoniq->ctrl |= ES_1370_WTSRSEL(0); break;
case 11025: ensoniq->ctrl |= ES_1370_WTSRSEL(1); break;
case 22050: ensoniq->ctrl |= ES_1370_WTSRSEL(2); break;
case 44100: ensoniq->ctrl |= ES_1370_WTSRSEL(3); break;
default: snd_BUG();
}
#endif
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock_irq(&ensoniq->reg_lock);
#ifndef CHIP1370
snd_es1371_dac1_rate(ensoniq, runtime->rate);
#endif
return 0;
}
static int snd_ensoniq_playback2_prepare(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int mode = 0;
ensoniq->p2_dma_size = snd_pcm_lib_buffer_bytes(substream);
ensoniq->p2_period_size = snd_pcm_lib_period_bytes(substream);
if (snd_pcm_format_width(runtime->format) == 16)
mode |= 0x02;
if (runtime->channels > 1)
mode |= 0x01;
spin_lock_irq(&ensoniq->reg_lock);
ensoniq->ctrl &= ~ES_DAC2_EN;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ES_MEM_PAGEO(ES_PAGE_DAC), ES_REG(ensoniq, MEM_PAGE));
outl(runtime->dma_addr, ES_REG(ensoniq, DAC2_FRAME));
outl((ensoniq->p2_dma_size >> 2) - 1, ES_REG(ensoniq, DAC2_SIZE));
ensoniq->sctrl &= ~(ES_P2_LOOP_SEL | ES_P2_PAUSE | ES_P2_DAC_SEN |
ES_P2_END_INCM | ES_P2_ST_INCM | ES_P2_MODEM);
ensoniq->sctrl |= ES_P2_INT_EN | ES_P2_MODEO(mode) |
ES_P2_END_INCO(mode & 2 ? 2 : 1) | ES_P2_ST_INCO(0);
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
outl((ensoniq->p2_period_size >> snd_ensoniq_sample_shift[mode]) - 1,
ES_REG(ensoniq, DAC2_COUNT));
#ifdef CHIP1370
if (!(ensoniq->u.es1370.pclkdiv_lock & ES_MODE_CAPTURE)) {
ensoniq->ctrl &= ~ES_1370_PCLKDIVM;
ensoniq->ctrl |= ES_1370_PCLKDIVO(ES_1370_SRTODIV(runtime->rate));
ensoniq->u.es1370.pclkdiv_lock |= ES_MODE_PLAY2;
}
#endif
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock_irq(&ensoniq->reg_lock);
#ifndef CHIP1370
snd_es1371_dac2_rate(ensoniq, runtime->rate);
#endif
return 0;
}
static int snd_ensoniq_capture_prepare(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int mode = 0;
ensoniq->c_dma_size = snd_pcm_lib_buffer_bytes(substream);
ensoniq->c_period_size = snd_pcm_lib_period_bytes(substream);
if (snd_pcm_format_width(runtime->format) == 16)
mode |= 0x02;
if (runtime->channels > 1)
mode |= 0x01;
spin_lock_irq(&ensoniq->reg_lock);
ensoniq->ctrl &= ~ES_ADC_EN;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ES_MEM_PAGEO(ES_PAGE_ADC), ES_REG(ensoniq, MEM_PAGE));
outl(runtime->dma_addr, ES_REG(ensoniq, ADC_FRAME));
outl((ensoniq->c_dma_size >> 2) - 1, ES_REG(ensoniq, ADC_SIZE));
ensoniq->sctrl &= ~(ES_R1_LOOP_SEL | ES_R1_MODEM);
ensoniq->sctrl |= ES_R1_INT_EN | ES_R1_MODEO(mode);
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
outl((ensoniq->c_period_size >> snd_ensoniq_sample_shift[mode]) - 1,
ES_REG(ensoniq, ADC_COUNT));
#ifdef CHIP1370
if (!(ensoniq->u.es1370.pclkdiv_lock & ES_MODE_PLAY2)) {
ensoniq->ctrl &= ~ES_1370_PCLKDIVM;
ensoniq->ctrl |= ES_1370_PCLKDIVO(ES_1370_SRTODIV(runtime->rate));
ensoniq->u.es1370.pclkdiv_lock |= ES_MODE_CAPTURE;
}
#endif
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock_irq(&ensoniq->reg_lock);
#ifndef CHIP1370
snd_es1371_adc_rate(ensoniq, runtime->rate);
#endif
return 0;
}
static snd_pcm_uframes_t snd_ensoniq_playback1_pointer(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
size_t ptr;
spin_lock(&ensoniq->reg_lock);
if (inl(ES_REG(ensoniq, CONTROL)) & ES_DAC1_EN) {
outl(ES_MEM_PAGEO(ES_PAGE_DAC), ES_REG(ensoniq, MEM_PAGE));
ptr = ES_REG_FCURR_COUNTI(inl(ES_REG(ensoniq, DAC1_SIZE)));
ptr = bytes_to_frames(substream->runtime, ptr);
} else {
ptr = 0;
}
spin_unlock(&ensoniq->reg_lock);
return ptr;
}
static snd_pcm_uframes_t snd_ensoniq_playback2_pointer(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
size_t ptr;
spin_lock(&ensoniq->reg_lock);
if (inl(ES_REG(ensoniq, CONTROL)) & ES_DAC2_EN) {
outl(ES_MEM_PAGEO(ES_PAGE_DAC), ES_REG(ensoniq, MEM_PAGE));
ptr = ES_REG_FCURR_COUNTI(inl(ES_REG(ensoniq, DAC2_SIZE)));
ptr = bytes_to_frames(substream->runtime, ptr);
} else {
ptr = 0;
}
spin_unlock(&ensoniq->reg_lock);
return ptr;
}
static snd_pcm_uframes_t snd_ensoniq_capture_pointer(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
size_t ptr;
spin_lock(&ensoniq->reg_lock);
if (inl(ES_REG(ensoniq, CONTROL)) & ES_ADC_EN) {
outl(ES_MEM_PAGEO(ES_PAGE_ADC), ES_REG(ensoniq, MEM_PAGE));
ptr = ES_REG_FCURR_COUNTI(inl(ES_REG(ensoniq, ADC_SIZE)));
ptr = bytes_to_frames(substream->runtime, ptr);
} else {
ptr = 0;
}
spin_unlock(&ensoniq->reg_lock);
return ptr;
}
static struct snd_pcm_hardware snd_ensoniq_playback1 =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_SYNC_START),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates =
#ifndef CHIP1370
SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
#else
(SNDRV_PCM_RATE_KNOT | /* 5512Hz rate */
SNDRV_PCM_RATE_11025 | SNDRV_PCM_RATE_22050 |
SNDRV_PCM_RATE_44100),
#endif
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_ensoniq_playback2 =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_SYNC_START),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_ensoniq_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_SYNC_START),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static int snd_ensoniq_playback1_open(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
ensoniq->mode |= ES_MODE_PLAY1;
ensoniq->playback1_substream = substream;
runtime->hw = snd_ensoniq_playback1;
snd_pcm_set_sync(substream);
spin_lock_irq(&ensoniq->reg_lock);
if (ensoniq->spdif && ensoniq->playback2_substream == NULL)
ensoniq->spdif_stream = ensoniq->spdif_default;
spin_unlock_irq(&ensoniq->reg_lock);
#ifdef CHIP1370
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1370_hw_constraints_rates);
#else
snd_pcm_hw_constraint_ratdens(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1371_hw_constraints_dac_clock);
#endif
return 0;
}
static int snd_ensoniq_playback2_open(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
ensoniq->mode |= ES_MODE_PLAY2;
ensoniq->playback2_substream = substream;
runtime->hw = snd_ensoniq_playback2;
snd_pcm_set_sync(substream);
spin_lock_irq(&ensoniq->reg_lock);
if (ensoniq->spdif && ensoniq->playback1_substream == NULL)
ensoniq->spdif_stream = ensoniq->spdif_default;
spin_unlock_irq(&ensoniq->reg_lock);
#ifdef CHIP1370
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1370_hw_constraints_clock);
#else
snd_pcm_hw_constraint_ratdens(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1371_hw_constraints_dac_clock);
#endif
return 0;
}
static int snd_ensoniq_capture_open(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
ensoniq->mode |= ES_MODE_CAPTURE;
ensoniq->capture_substream = substream;
runtime->hw = snd_ensoniq_capture;
snd_pcm_set_sync(substream);
#ifdef CHIP1370
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1370_hw_constraints_clock);
#else
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&snd_es1371_hw_constraints_adc_clock);
#endif
return 0;
}
static int snd_ensoniq_playback1_close(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
ensoniq->playback1_substream = NULL;
ensoniq->mode &= ~ES_MODE_PLAY1;
return 0;
}
static int snd_ensoniq_playback2_close(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
ensoniq->playback2_substream = NULL;
spin_lock_irq(&ensoniq->reg_lock);
#ifdef CHIP1370
ensoniq->u.es1370.pclkdiv_lock &= ~ES_MODE_PLAY2;
#endif
ensoniq->mode &= ~ES_MODE_PLAY2;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ensoniq_capture_close(struct snd_pcm_substream *substream)
{
struct ensoniq *ensoniq = snd_pcm_substream_chip(substream);
ensoniq->capture_substream = NULL;
spin_lock_irq(&ensoniq->reg_lock);
#ifdef CHIP1370
ensoniq->u.es1370.pclkdiv_lock &= ~ES_MODE_CAPTURE;
#endif
ensoniq->mode &= ~ES_MODE_CAPTURE;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static struct snd_pcm_ops snd_ensoniq_playback1_ops = {
.open = snd_ensoniq_playback1_open,
.close = snd_ensoniq_playback1_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ensoniq_hw_params,
.hw_free = snd_ensoniq_hw_free,
.prepare = snd_ensoniq_playback1_prepare,
.trigger = snd_ensoniq_trigger,
.pointer = snd_ensoniq_playback1_pointer,
};
static struct snd_pcm_ops snd_ensoniq_playback2_ops = {
.open = snd_ensoniq_playback2_open,
.close = snd_ensoniq_playback2_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ensoniq_hw_params,
.hw_free = snd_ensoniq_hw_free,
.prepare = snd_ensoniq_playback2_prepare,
.trigger = snd_ensoniq_trigger,
.pointer = snd_ensoniq_playback2_pointer,
};
static struct snd_pcm_ops snd_ensoniq_capture_ops = {
.open = snd_ensoniq_capture_open,
.close = snd_ensoniq_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ensoniq_hw_params,
.hw_free = snd_ensoniq_hw_free,
.prepare = snd_ensoniq_capture_prepare,
.trigger = snd_ensoniq_trigger,
.pointer = snd_ensoniq_capture_pointer,
};
static int __devinit snd_ensoniq_pcm(struct ensoniq * ensoniq, int device,
struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
#ifdef CHIP1370
err = snd_pcm_new(ensoniq->card, "ES1370/1", device, 1, 1, &pcm);
#else
err = snd_pcm_new(ensoniq->card, "ES1371/1", device, 1, 1, &pcm);
#endif
if (err < 0)
return err;
#ifdef CHIP1370
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ensoniq_playback2_ops);
#else
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ensoniq_playback1_ops);
#endif
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ensoniq_capture_ops);
pcm->private_data = ensoniq;
pcm->info_flags = 0;
#ifdef CHIP1370
strcpy(pcm->name, "ES1370 DAC2/ADC");
#else
strcpy(pcm->name, "ES1371 DAC2/ADC");
#endif
ensoniq->pcm1 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(ensoniq->pci), 64*1024, 128*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static int __devinit snd_ensoniq_pcm2(struct ensoniq * ensoniq, int device,
struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
#ifdef CHIP1370
err = snd_pcm_new(ensoniq->card, "ES1370/2", device, 1, 0, &pcm);
#else
err = snd_pcm_new(ensoniq->card, "ES1371/2", device, 1, 0, &pcm);
#endif
if (err < 0)
return err;
#ifdef CHIP1370
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ensoniq_playback1_ops);
#else
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ensoniq_playback2_ops);
#endif
pcm->private_data = ensoniq;
pcm->info_flags = 0;
#ifdef CHIP1370
strcpy(pcm->name, "ES1370 DAC1");
#else
strcpy(pcm->name, "ES1371 DAC1");
#endif
ensoniq->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(ensoniq->pci), 64*1024, 128*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
/*
* Mixer section
*/
/*
* ENS1371 mixer (including SPDIF interface)
*/
#ifdef CHIP1371
static int snd_ens1373_spdif_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ens1373_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&ensoniq->reg_lock);
ucontrol->value.iec958.status[0] = (ensoniq->spdif_default >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (ensoniq->spdif_default >> 8) & 0xff;
ucontrol->value.iec958.status[2] = (ensoniq->spdif_default >> 16) & 0xff;
ucontrol->value.iec958.status[3] = (ensoniq->spdif_default >> 24) & 0xff;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ens1373_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((u32)ucontrol->value.iec958.status[0] << 0) |
((u32)ucontrol->value.iec958.status[1] << 8) |
((u32)ucontrol->value.iec958.status[2] << 16) |
((u32)ucontrol->value.iec958.status[3] << 24);
spin_lock_irq(&ensoniq->reg_lock);
change = ensoniq->spdif_default != val;
ensoniq->spdif_default = val;
if (change && ensoniq->playback1_substream == NULL &&
ensoniq->playback2_substream == NULL)
outl(val, ES_REG(ensoniq, CHANNEL_STATUS));
spin_unlock_irq(&ensoniq->reg_lock);
return change;
}
static int snd_ens1373_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.iec958.status[0] = 0xff;
ucontrol->value.iec958.status[1] = 0xff;
ucontrol->value.iec958.status[2] = 0xff;
ucontrol->value.iec958.status[3] = 0xff;
return 0;
}
static int snd_ens1373_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&ensoniq->reg_lock);
ucontrol->value.iec958.status[0] = (ensoniq->spdif_stream >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (ensoniq->spdif_stream >> 8) & 0xff;
ucontrol->value.iec958.status[2] = (ensoniq->spdif_stream >> 16) & 0xff;
ucontrol->value.iec958.status[3] = (ensoniq->spdif_stream >> 24) & 0xff;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ens1373_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((u32)ucontrol->value.iec958.status[0] << 0) |
((u32)ucontrol->value.iec958.status[1] << 8) |
((u32)ucontrol->value.iec958.status[2] << 16) |
((u32)ucontrol->value.iec958.status[3] << 24);
spin_lock_irq(&ensoniq->reg_lock);
change = ensoniq->spdif_stream != val;
ensoniq->spdif_stream = val;
if (change && (ensoniq->playback1_substream != NULL ||
ensoniq->playback2_substream != NULL))
outl(val, ES_REG(ensoniq, CHANNEL_STATUS));
spin_unlock_irq(&ensoniq->reg_lock);
return change;
}
#define ES1371_SPDIF(xname) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .info = snd_es1371_spdif_info, \
.get = snd_es1371_spdif_get, .put = snd_es1371_spdif_put }
#define snd_es1371_spdif_info snd_ctl_boolean_mono_info
static int snd_es1371_spdif_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&ensoniq->reg_lock);
ucontrol->value.integer.value[0] = ensoniq->ctrl & ES_1373_SPDIF_THRU ? 1 : 0;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_es1371_spdif_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
unsigned int nval1, nval2;
int change;
nval1 = ucontrol->value.integer.value[0] ? ES_1373_SPDIF_THRU : 0;
nval2 = ucontrol->value.integer.value[0] ? ES_1373_SPDIF_EN : 0;
spin_lock_irq(&ensoniq->reg_lock);
change = (ensoniq->ctrl & ES_1373_SPDIF_THRU) != nval1;
ensoniq->ctrl &= ~ES_1373_SPDIF_THRU;
ensoniq->ctrl |= nval1;
ensoniq->cssr &= ~ES_1373_SPDIF_EN;
ensoniq->cssr |= nval2;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ensoniq->cssr, ES_REG(ensoniq, STATUS));
spin_unlock_irq(&ensoniq->reg_lock);
return change;
}
/* spdif controls */
static struct snd_kcontrol_new snd_es1371_mixer_spdif[] __devinitdata = {
ES1371_SPDIF(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH)),
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_ens1373_spdif_info,
.get = snd_ens1373_spdif_default_get,
.put = snd_ens1373_spdif_default_put,
},
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,MASK),
.info = snd_ens1373_spdif_info,
.get = snd_ens1373_spdif_mask_get
},
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_ens1373_spdif_info,
.get = snd_ens1373_spdif_stream_get,
.put = snd_ens1373_spdif_stream_put
},
};
#define snd_es1373_rear_info snd_ctl_boolean_mono_info
static int snd_es1373_rear_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
int val = 0;
spin_lock_irq(&ensoniq->reg_lock);
if ((ensoniq->cssr & (ES_1373_REAR_BIT27|ES_1373_REAR_BIT26|
ES_1373_REAR_BIT24)) == ES_1373_REAR_BIT26)
val = 1;
ucontrol->value.integer.value[0] = val;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_es1373_rear_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
unsigned int nval1;
int change;
nval1 = ucontrol->value.integer.value[0] ?
ES_1373_REAR_BIT26 : (ES_1373_REAR_BIT27|ES_1373_REAR_BIT24);
spin_lock_irq(&ensoniq->reg_lock);
change = (ensoniq->cssr & (ES_1373_REAR_BIT27|
ES_1373_REAR_BIT26|ES_1373_REAR_BIT24)) != nval1;
ensoniq->cssr &= ~(ES_1373_REAR_BIT27|ES_1373_REAR_BIT26|ES_1373_REAR_BIT24);
ensoniq->cssr |= nval1;
outl(ensoniq->cssr, ES_REG(ensoniq, STATUS));
spin_unlock_irq(&ensoniq->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ens1373_rear __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "AC97 2ch->4ch Copy Switch",
.info = snd_es1373_rear_info,
.get = snd_es1373_rear_get,
.put = snd_es1373_rear_put,
};
#define snd_es1373_line_info snd_ctl_boolean_mono_info
static int snd_es1373_line_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
int val = 0;
spin_lock_irq(&ensoniq->reg_lock);
if ((ensoniq->ctrl & ES_1371_GPIO_OUTM) >= 4)
val = 1;
ucontrol->value.integer.value[0] = val;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_es1373_line_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
int changed;
unsigned int ctrl;
spin_lock_irq(&ensoniq->reg_lock);
ctrl = ensoniq->ctrl;
if (ucontrol->value.integer.value[0])
ensoniq->ctrl |= ES_1371_GPIO_OUT(4); /* switch line-in -> rear out */
else
ensoniq->ctrl &= ~ES_1371_GPIO_OUT(4);
changed = (ctrl != ensoniq->ctrl);
if (changed)
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock_irq(&ensoniq->reg_lock);
return changed;
}
static struct snd_kcontrol_new snd_ens1373_line __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line In->Rear Out Switch",
.info = snd_es1373_line_info,
.get = snd_es1373_line_get,
.put = snd_es1373_line_put,
};
static void snd_ensoniq_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct ensoniq *ensoniq = ac97->private_data;
ensoniq->u.es1371.ac97 = NULL;
}
struct es1371_quirk {
unsigned short vid; /* vendor ID */
unsigned short did; /* device ID */
unsigned char rev; /* revision */
};
static int es1371_quirk_lookup(struct ensoniq *ensoniq,
struct es1371_quirk *list)
{
while (list->vid != (unsigned short)PCI_ANY_ID) {
if (ensoniq->pci->vendor == list->vid &&
ensoniq->pci->device == list->did &&
ensoniq->rev == list->rev)
return 1;
list++;
}
return 0;
}
static struct es1371_quirk es1371_spdif_present[] __devinitdata = {
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_C },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_D },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_E },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_ES1371, .rev = ES1371REV_CT5880_A },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_ES1371, .rev = ES1371REV_ES1373_8 },
{ .vid = PCI_ANY_ID, .did = PCI_ANY_ID }
};
static struct snd_pci_quirk ens1373_line_quirk[] __devinitdata = {
SND_PCI_QUIRK_ID(0x1274, 0x2000), /* GA-7DXR */
SND_PCI_QUIRK_ID(0x1458, 0xa000), /* GA-8IEXP */
{ } /* end */
};
static int __devinit snd_ensoniq_1371_mixer(struct ensoniq *ensoniq,
int has_spdif, int has_line)
{
struct snd_card *card = ensoniq->card;
struct snd_ac97_bus *pbus;
struct snd_ac97_template ac97;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_es1371_codec_write,
.read = snd_es1371_codec_read,
.wait = snd_es1371_codec_wait,
};
if ((err = snd_ac97_bus(card, 0, &ops, NULL, &pbus)) < 0)
return err;
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = ensoniq;
ac97.private_free = snd_ensoniq_mixer_free_ac97;
ac97.pci = ensoniq->pci;
ac97.scaps = AC97_SCAP_AUDIO;
if ((err = snd_ac97_mixer(pbus, &ac97, &ensoniq->u.es1371.ac97)) < 0)
return err;
if (has_spdif > 0 ||
(!has_spdif && es1371_quirk_lookup(ensoniq, es1371_spdif_present))) {
struct snd_kcontrol *kctl;
int i, is_spdif = 0;
ensoniq->spdif_default = ensoniq->spdif_stream =
SNDRV_PCM_DEFAULT_CON_SPDIF;
outl(ensoniq->spdif_default, ES_REG(ensoniq, CHANNEL_STATUS));
if (ensoniq->u.es1371.ac97->ext_id & AC97_EI_SPDIF)
is_spdif++;
for (i = 0; i < ARRAY_SIZE(snd_es1371_mixer_spdif); i++) {
kctl = snd_ctl_new1(&snd_es1371_mixer_spdif[i], ensoniq);
if (!kctl)
return -ENOMEM;
kctl->id.index = is_spdif;
err = snd_ctl_add(card, kctl);
if (err < 0)
return err;
}
}
if (ensoniq->u.es1371.ac97->ext_id & AC97_EI_SDAC) {
/* mirror rear to front speakers */
ensoniq->cssr &= ~(ES_1373_REAR_BIT27|ES_1373_REAR_BIT24);
ensoniq->cssr |= ES_1373_REAR_BIT26;
err = snd_ctl_add(card, snd_ctl_new1(&snd_ens1373_rear, ensoniq));
if (err < 0)
return err;
}
if (has_line > 0 ||
snd_pci_quirk_lookup(ensoniq->pci, ens1373_line_quirk)) {
err = snd_ctl_add(card, snd_ctl_new1(&snd_ens1373_line,
ensoniq));
if (err < 0)
return err;
}
return 0;
}
#endif /* CHIP1371 */
/* generic control callbacks for ens1370 */
#ifdef CHIP1370
#define ENSONIQ_CONTROL(xname, mask) \
{ .iface = SNDRV_CTL_ELEM_IFACE_CARD, .name = xname, .info = snd_ensoniq_control_info, \
.get = snd_ensoniq_control_get, .put = snd_ensoniq_control_put, \
.private_value = mask }
#define snd_ensoniq_control_info snd_ctl_boolean_mono_info
static int snd_ensoniq_control_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
int mask = kcontrol->private_value;
spin_lock_irq(&ensoniq->reg_lock);
ucontrol->value.integer.value[0] = ensoniq->ctrl & mask ? 1 : 0;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ensoniq_control_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct ensoniq *ensoniq = snd_kcontrol_chip(kcontrol);
int mask = kcontrol->private_value;
unsigned int nval;
int change;
nval = ucontrol->value.integer.value[0] ? mask : 0;
spin_lock_irq(&ensoniq->reg_lock);
change = (ensoniq->ctrl & mask) != nval;
ensoniq->ctrl &= ~mask;
ensoniq->ctrl |= nval;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
spin_unlock_irq(&ensoniq->reg_lock);
return change;
}
/*
* ENS1370 mixer
*/
static struct snd_kcontrol_new snd_es1370_controls[2] __devinitdata = {
ENSONIQ_CONTROL("PCM 0 Output also on Line-In Jack", ES_1370_XCTL0),
ENSONIQ_CONTROL("Mic +5V bias", ES_1370_XCTL1)
};
#define ES1370_CONTROLS ARRAY_SIZE(snd_es1370_controls)
static void snd_ensoniq_mixer_free_ak4531(struct snd_ak4531 *ak4531)
{
struct ensoniq *ensoniq = ak4531->private_data;
ensoniq->u.es1370.ak4531 = NULL;
}
static int __devinit snd_ensoniq_1370_mixer(struct ensoniq * ensoniq)
{
struct snd_card *card = ensoniq->card;
struct snd_ak4531 ak4531;
unsigned int idx;
int err;
/* try reset AK4531 */
outw(ES_1370_CODEC_WRITE(AK4531_RESET, 0x02), ES_REG(ensoniq, 1370_CODEC));
inw(ES_REG(ensoniq, 1370_CODEC));
udelay(100);
outw(ES_1370_CODEC_WRITE(AK4531_RESET, 0x03), ES_REG(ensoniq, 1370_CODEC));
inw(ES_REG(ensoniq, 1370_CODEC));
udelay(100);
memset(&ak4531, 0, sizeof(ak4531));
ak4531.write = snd_es1370_codec_write;
ak4531.private_data = ensoniq;
ak4531.private_free = snd_ensoniq_mixer_free_ak4531;
if ((err = snd_ak4531_mixer(card, &ak4531, &ensoniq->u.es1370.ak4531)) < 0)
return err;
for (idx = 0; idx < ES1370_CONTROLS; idx++) {
err = snd_ctl_add(card, snd_ctl_new1(&snd_es1370_controls[idx], ensoniq));
if (err < 0)
return err;
}
return 0;
}
#endif /* CHIP1370 */
#ifdef SUPPORT_JOYSTICK
#ifdef CHIP1371
static int __devinit snd_ensoniq_get_joystick_port(int dev)
{
switch (joystick_port[dev]) {
case 0: /* disabled */
case 1: /* auto-detect */
case 0x200:
case 0x208:
case 0x210:
case 0x218:
return joystick_port[dev];
default:
printk(KERN_ERR "ens1371: invalid joystick port %#x", joystick_port[dev]);
return 0;
}
}
#else
static inline int snd_ensoniq_get_joystick_port(int dev)
{
return joystick[dev] ? 0x200 : 0;
}
#endif
static int __devinit snd_ensoniq_create_gameport(struct ensoniq *ensoniq, int dev)
{
struct gameport *gp;
int io_port;
io_port = snd_ensoniq_get_joystick_port(dev);
switch (io_port) {
case 0:
return -ENOSYS;
case 1: /* auto_detect */
for (io_port = 0x200; io_port <= 0x218; io_port += 8)
if (request_region(io_port, 8, "ens137x: gameport"))
break;
if (io_port > 0x218) {
printk(KERN_WARNING "ens137x: no gameport ports available\n");
return -EBUSY;
}
break;
default:
if (!request_region(io_port, 8, "ens137x: gameport")) {
printk(KERN_WARNING "ens137x: gameport io port 0x%#x in use\n",
io_port);
return -EBUSY;
}
break;
}
ensoniq->gameport = gp = gameport_allocate_port();
if (!gp) {
printk(KERN_ERR "ens137x: cannot allocate memory for gameport\n");
release_region(io_port, 8);
return -ENOMEM;
}
gameport_set_name(gp, "ES137x");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(ensoniq->pci));
gameport_set_dev_parent(gp, &ensoniq->pci->dev);
gp->io = io_port;
ensoniq->ctrl |= ES_JYSTK_EN;
#ifdef CHIP1371
ensoniq->ctrl &= ~ES_1371_JOY_ASELM;
ensoniq->ctrl |= ES_1371_JOY_ASEL((io_port - 0x200) / 8);
#endif
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
gameport_register_port(ensoniq->gameport);
return 0;
}
static void snd_ensoniq_free_gameport(struct ensoniq *ensoniq)
{
if (ensoniq->gameport) {
int port = ensoniq->gameport->io;
gameport_unregister_port(ensoniq->gameport);
ensoniq->gameport = NULL;
ensoniq->ctrl &= ~ES_JYSTK_EN;
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
release_region(port, 8);
}
}
#else
static inline int snd_ensoniq_create_gameport(struct ensoniq *ensoniq, long port) { return -ENOSYS; }
static inline void snd_ensoniq_free_gameport(struct ensoniq *ensoniq) { }
#endif /* SUPPORT_JOYSTICK */
/*
*/
static void snd_ensoniq_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct ensoniq *ensoniq = entry->private_data;
#ifdef CHIP1370
snd_iprintf(buffer, "Ensoniq AudioPCI ES1370\n\n");
#else
snd_iprintf(buffer, "Ensoniq AudioPCI ES1371\n\n");
#endif
snd_iprintf(buffer, "Joystick enable : %s\n",
ensoniq->ctrl & ES_JYSTK_EN ? "on" : "off");
#ifdef CHIP1370
snd_iprintf(buffer, "MIC +5V bias : %s\n",
ensoniq->ctrl & ES_1370_XCTL1 ? "on" : "off");
snd_iprintf(buffer, "Line In to AOUT : %s\n",
ensoniq->ctrl & ES_1370_XCTL0 ? "on" : "off");
#else
snd_iprintf(buffer, "Joystick port : 0x%x\n",
(ES_1371_JOY_ASELI(ensoniq->ctrl) * 8) + 0x200);
#endif
}
static void __devinit snd_ensoniq_proc_init(struct ensoniq * ensoniq)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(ensoniq->card, "audiopci", &entry))
snd_info_set_text_ops(entry, ensoniq, snd_ensoniq_proc_read);
}
/*
*/
static int snd_ensoniq_free(struct ensoniq *ensoniq)
{
snd_ensoniq_free_gameport(ensoniq);
if (ensoniq->irq < 0)
goto __hw_end;
#ifdef CHIP1370
outl(ES_1370_SERR_DISABLE, ES_REG(ensoniq, CONTROL)); /* switch everything off */
outl(0, ES_REG(ensoniq, SERIAL)); /* clear serial interface */
#else
outl(0, ES_REG(ensoniq, CONTROL)); /* switch everything off */
outl(0, ES_REG(ensoniq, SERIAL)); /* clear serial interface */
#endif
if (ensoniq->irq >= 0)
synchronize_irq(ensoniq->irq);
pci_set_power_state(ensoniq->pci, 3);
__hw_end:
#ifdef CHIP1370
if (ensoniq->dma_bug.area)
snd_dma_free_pages(&ensoniq->dma_bug);
#endif
if (ensoniq->irq >= 0)
free_irq(ensoniq->irq, ensoniq);
pci_release_regions(ensoniq->pci);
pci_disable_device(ensoniq->pci);
kfree(ensoniq);
return 0;
}
static int snd_ensoniq_dev_free(struct snd_device *device)
{
struct ensoniq *ensoniq = device->device_data;
return snd_ensoniq_free(ensoniq);
}
#ifdef CHIP1371
static struct snd_pci_quirk es1371_amplifier_hack[] __devinitdata = {
SND_PCI_QUIRK_ID(0x107b, 0x2150), /* Gateway Solo 2150 */
SND_PCI_QUIRK_ID(0x13bd, 0x100c), /* EV1938 on Mebius PC-MJ100V */
SND_PCI_QUIRK_ID(0x1102, 0x5938), /* Targa Xtender300 */
SND_PCI_QUIRK_ID(0x1102, 0x8938), /* IPC Topnote G notebook */
{ } /* end */
};
static struct es1371_quirk es1371_ac97_reset_hack[] = {
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_C },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_D },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_CT5880, .rev = CT5880REV_CT5880_E },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_ES1371, .rev = ES1371REV_CT5880_A },
{ .vid = PCI_VENDOR_ID_ENSONIQ, .did = PCI_DEVICE_ID_ENSONIQ_ES1371, .rev = ES1371REV_ES1373_8 },
{ .vid = PCI_ANY_ID, .did = PCI_ANY_ID }
};
#endif
static void snd_ensoniq_chip_init(struct ensoniq *ensoniq)
{
#ifdef CHIP1371
int idx;
#endif
/* this code was part of snd_ensoniq_create before intruduction
* of suspend/resume
*/
#ifdef CHIP1370
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
outl(ES_MEM_PAGEO(ES_PAGE_ADC), ES_REG(ensoniq, MEM_PAGE));
outl(ensoniq->dma_bug.addr, ES_REG(ensoniq, PHANTOM_FRAME));
outl(0, ES_REG(ensoniq, PHANTOM_COUNT));
#else
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
outl(0, ES_REG(ensoniq, 1371_LEGACY));
if (es1371_quirk_lookup(ensoniq, es1371_ac97_reset_hack)) {
outl(ensoniq->cssr, ES_REG(ensoniq, STATUS));
/* need to delay around 20ms(bleech) to give
some CODECs enough time to wakeup */
msleep(20);
}
/* AC'97 warm reset to start the bitclk */
outl(ensoniq->ctrl | ES_1371_SYNC_RES, ES_REG(ensoniq, CONTROL));
inl(ES_REG(ensoniq, CONTROL));
udelay(20);
outl(ensoniq->ctrl, ES_REG(ensoniq, CONTROL));
/* Init the sample rate converter */
snd_es1371_wait_src_ready(ensoniq);
outl(ES_1371_SRC_DISABLE, ES_REG(ensoniq, 1371_SMPRATE));
for (idx = 0; idx < 0x80; idx++)
snd_es1371_src_write(ensoniq, idx, 0);
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC1 + ES_SMPREG_TRUNC_N, 16 << 4);
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC1 + ES_SMPREG_INT_REGS, 16 << 10);
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC2 + ES_SMPREG_TRUNC_N, 16 << 4);
snd_es1371_src_write(ensoniq, ES_SMPREG_DAC2 + ES_SMPREG_INT_REGS, 16 << 10);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_ADC, 1 << 12);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_ADC + 1, 1 << 12);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_DAC1, 1 << 12);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_DAC1 + 1, 1 << 12);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_DAC2, 1 << 12);
snd_es1371_src_write(ensoniq, ES_SMPREG_VOL_DAC2 + 1, 1 << 12);
snd_es1371_adc_rate(ensoniq, 22050);
snd_es1371_dac1_rate(ensoniq, 22050);
snd_es1371_dac2_rate(ensoniq, 22050);
/* WARNING:
* enabling the sample rate converter without properly programming
* its parameters causes the chip to lock up (the SRC busy bit will
* be stuck high, and I've found no way to rectify this other than
* power cycle) - Thomas Sailer
*/
snd_es1371_wait_src_ready(ensoniq);
outl(0, ES_REG(ensoniq, 1371_SMPRATE));
/* try reset codec directly */
outl(ES_1371_CODEC_WRITE(0, 0), ES_REG(ensoniq, 1371_CODEC));
#endif
outb(ensoniq->uartc = 0x00, ES_REG(ensoniq, UART_CONTROL));
outb(0x00, ES_REG(ensoniq, UART_RES));
outl(ensoniq->cssr, ES_REG(ensoniq, STATUS));
synchronize_irq(ensoniq->irq);
}
#ifdef CONFIG_PM
static int snd_ensoniq_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct ensoniq *ensoniq = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(ensoniq->pcm1);
snd_pcm_suspend_all(ensoniq->pcm2);
#ifdef CHIP1371
snd_ac97_suspend(ensoniq->u.es1371.ac97);
#else
/* try to reset AK4531 */
outw(ES_1370_CODEC_WRITE(AK4531_RESET, 0x02), ES_REG(ensoniq, 1370_CODEC));
inw(ES_REG(ensoniq, 1370_CODEC));
udelay(100);
outw(ES_1370_CODEC_WRITE(AK4531_RESET, 0x03), ES_REG(ensoniq, 1370_CODEC));
inw(ES_REG(ensoniq, 1370_CODEC));
udelay(100);
snd_ak4531_suspend(ensoniq->u.es1370.ak4531);
#endif
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int snd_ensoniq_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct ensoniq *ensoniq = card->private_data;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR DRIVER_NAME ": pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_ensoniq_chip_init(ensoniq);
#ifdef CHIP1371
snd_ac97_resume(ensoniq->u.es1371.ac97);
#else
snd_ak4531_resume(ensoniq->u.es1370.ak4531);
#endif
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static int __devinit snd_ensoniq_create(struct snd_card *card,
struct pci_dev *pci,
struct ensoniq ** rensoniq)
{
struct ensoniq *ensoniq;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_ensoniq_dev_free,
};
*rensoniq = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
ensoniq = kzalloc(sizeof(*ensoniq), GFP_KERNEL);
if (ensoniq == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&ensoniq->reg_lock);
mutex_init(&ensoniq->src_mutex);
ensoniq->card = card;
ensoniq->pci = pci;
ensoniq->irq = -1;
if ((err = pci_request_regions(pci, "Ensoniq AudioPCI")) < 0) {
kfree(ensoniq);
pci_disable_device(pci);
return err;
}
ensoniq->port = pci_resource_start(pci, 0);
if (request_irq(pci->irq, snd_audiopci_interrupt, IRQF_SHARED,
"Ensoniq AudioPCI", ensoniq)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_ensoniq_free(ensoniq);
return -EBUSY;
}
ensoniq->irq = pci->irq;
#ifdef CHIP1370
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
16, &ensoniq->dma_bug) < 0) {
snd_printk(KERN_ERR "unable to allocate space for phantom area - dma_bug\n");
snd_ensoniq_free(ensoniq);
return -EBUSY;
}
#endif
pci_set_master(pci);
ensoniq->rev = pci->revision;
#ifdef CHIP1370
#if 0
ensoniq->ctrl = ES_1370_CDC_EN | ES_1370_SERR_DISABLE |
ES_1370_PCLKDIVO(ES_1370_SRTODIV(8000));
#else /* get microphone working */
ensoniq->ctrl = ES_1370_CDC_EN | ES_1370_PCLKDIVO(ES_1370_SRTODIV(8000));
#endif
ensoniq->sctrl = 0;
#else
ensoniq->ctrl = 0;
ensoniq->sctrl = 0;
ensoniq->cssr = 0;
if (snd_pci_quirk_lookup(pci, es1371_amplifier_hack))
ensoniq->ctrl |= ES_1371_GPIO_OUT(1); /* turn amplifier on */
if (es1371_quirk_lookup(ensoniq, es1371_ac97_reset_hack))
ensoniq->cssr |= ES_1371_ST_AC97_RST;
#endif
snd_ensoniq_chip_init(ensoniq);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, ensoniq, &ops)) < 0) {
snd_ensoniq_free(ensoniq);
return err;
}
snd_ensoniq_proc_init(ensoniq);
snd_card_set_dev(card, &pci->dev);
*rensoniq = ensoniq;
return 0;
}
/*
* MIDI section
*/
static void snd_ensoniq_midi_interrupt(struct ensoniq * ensoniq)
{
struct snd_rawmidi *rmidi = ensoniq->rmidi;
unsigned char status, mask, byte;
if (rmidi == NULL)
return;
/* do Rx at first */
spin_lock(&ensoniq->reg_lock);
mask = ensoniq->uartm & ES_MODE_INPUT ? ES_RXRDY : 0;
while (mask) {
status = inb(ES_REG(ensoniq, UART_STATUS));
if ((status & mask) == 0)
break;
byte = inb(ES_REG(ensoniq, UART_DATA));
snd_rawmidi_receive(ensoniq->midi_input, &byte, 1);
}
spin_unlock(&ensoniq->reg_lock);
/* do Tx at second */
spin_lock(&ensoniq->reg_lock);
mask = ensoniq->uartm & ES_MODE_OUTPUT ? ES_TXRDY : 0;
while (mask) {
status = inb(ES_REG(ensoniq, UART_STATUS));
if ((status & mask) == 0)
break;
if (snd_rawmidi_transmit(ensoniq->midi_output, &byte, 1) != 1) {
ensoniq->uartc &= ~ES_TXINTENM;
outb(ensoniq->uartc, ES_REG(ensoniq, UART_CONTROL));
mask &= ~ES_TXRDY;
} else {
outb(byte, ES_REG(ensoniq, UART_DATA));
}
}
spin_unlock(&ensoniq->reg_lock);
}
static int snd_ensoniq_midi_input_open(struct snd_rawmidi_substream *substream)
{
struct ensoniq *ensoniq = substream->rmidi->private_data;
spin_lock_irq(&ensoniq->reg_lock);
ensoniq->uartm |= ES_MODE_INPUT;
ensoniq->midi_input = substream;
if (!(ensoniq->uartm & ES_MODE_OUTPUT)) {
outb(ES_CNTRL(3), ES_REG(ensoniq, UART_CONTROL));
outb(ensoniq->uartc = 0, ES_REG(ensoniq, UART_CONTROL));
outl(ensoniq->ctrl |= ES_UART_EN, ES_REG(ensoniq, CONTROL));
}
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ensoniq_midi_input_close(struct snd_rawmidi_substream *substream)
{
struct ensoniq *ensoniq = substream->rmidi->private_data;
spin_lock_irq(&ensoniq->reg_lock);
if (!(ensoniq->uartm & ES_MODE_OUTPUT)) {
outb(ensoniq->uartc = 0, ES_REG(ensoniq, UART_CONTROL));
outl(ensoniq->ctrl &= ~ES_UART_EN, ES_REG(ensoniq, CONTROL));
} else {
outb(ensoniq->uartc &= ~ES_RXINTEN, ES_REG(ensoniq, UART_CONTROL));
}
ensoniq->midi_input = NULL;
ensoniq->uartm &= ~ES_MODE_INPUT;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ensoniq_midi_output_open(struct snd_rawmidi_substream *substream)
{
struct ensoniq *ensoniq = substream->rmidi->private_data;
spin_lock_irq(&ensoniq->reg_lock);
ensoniq->uartm |= ES_MODE_OUTPUT;
ensoniq->midi_output = substream;
if (!(ensoniq->uartm & ES_MODE_INPUT)) {
outb(ES_CNTRL(3), ES_REG(ensoniq, UART_CONTROL));
outb(ensoniq->uartc = 0, ES_REG(ensoniq, UART_CONTROL));
outl(ensoniq->ctrl |= ES_UART_EN, ES_REG(ensoniq, CONTROL));
}
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static int snd_ensoniq_midi_output_close(struct snd_rawmidi_substream *substream)
{
struct ensoniq *ensoniq = substream->rmidi->private_data;
spin_lock_irq(&ensoniq->reg_lock);
if (!(ensoniq->uartm & ES_MODE_INPUT)) {
outb(ensoniq->uartc = 0, ES_REG(ensoniq, UART_CONTROL));
outl(ensoniq->ctrl &= ~ES_UART_EN, ES_REG(ensoniq, CONTROL));
} else {
outb(ensoniq->uartc &= ~ES_TXINTENM, ES_REG(ensoniq, UART_CONTROL));
}
ensoniq->midi_output = NULL;
ensoniq->uartm &= ~ES_MODE_OUTPUT;
spin_unlock_irq(&ensoniq->reg_lock);
return 0;
}
static void snd_ensoniq_midi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
struct ensoniq *ensoniq = substream->rmidi->private_data;
int idx;
spin_lock_irqsave(&ensoniq->reg_lock, flags);
if (up) {
if ((ensoniq->uartc & ES_RXINTEN) == 0) {
/* empty input FIFO */
for (idx = 0; idx < 32; idx++)
inb(ES_REG(ensoniq, UART_DATA));
ensoniq->uartc |= ES_RXINTEN;
outb(ensoniq->uartc, ES_REG(ensoniq, UART_CONTROL));
}
} else {
if (ensoniq->uartc & ES_RXINTEN) {
ensoniq->uartc &= ~ES_RXINTEN;
outb(ensoniq->uartc, ES_REG(ensoniq, UART_CONTROL));
}
}
spin_unlock_irqrestore(&ensoniq->reg_lock, flags);
}
static void snd_ensoniq_midi_output_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
struct ensoniq *ensoniq = substream->rmidi->private_data;
unsigned char byte;
spin_lock_irqsave(&ensoniq->reg_lock, flags);
if (up) {
if (ES_TXINTENI(ensoniq->uartc) == 0) {
ensoniq->uartc |= ES_TXINTENO(1);
/* fill UART FIFO buffer at first, and turn Tx interrupts only if necessary */
while (ES_TXINTENI(ensoniq->uartc) == 1 &&
(inb(ES_REG(ensoniq, UART_STATUS)) & ES_TXRDY)) {
if (snd_rawmidi_transmit(substream, &byte, 1) != 1) {
ensoniq->uartc &= ~ES_TXINTENM;
} else {
outb(byte, ES_REG(ensoniq, UART_DATA));
}
}
outb(ensoniq->uartc, ES_REG(ensoniq, UART_CONTROL));
}
} else {
if (ES_TXINTENI(ensoniq->uartc) == 1) {
ensoniq->uartc &= ~ES_TXINTENM;
outb(ensoniq->uartc, ES_REG(ensoniq, UART_CONTROL));
}
}
spin_unlock_irqrestore(&ensoniq->reg_lock, flags);
}
static struct snd_rawmidi_ops snd_ensoniq_midi_output =
{
.open = snd_ensoniq_midi_output_open,
.close = snd_ensoniq_midi_output_close,
.trigger = snd_ensoniq_midi_output_trigger,
};
static struct snd_rawmidi_ops snd_ensoniq_midi_input =
{
.open = snd_ensoniq_midi_input_open,
.close = snd_ensoniq_midi_input_close,
.trigger = snd_ensoniq_midi_input_trigger,
};
static int __devinit snd_ensoniq_midi(struct ensoniq * ensoniq, int device,
struct snd_rawmidi **rrawmidi)
{
struct snd_rawmidi *rmidi;
int err;
if (rrawmidi)
*rrawmidi = NULL;
if ((err = snd_rawmidi_new(ensoniq->card, "ES1370/1", device, 1, 1, &rmidi)) < 0)
return err;
#ifdef CHIP1370
strcpy(rmidi->name, "ES1370");
#else
strcpy(rmidi->name, "ES1371");
#endif
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_ensoniq_midi_output);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_ensoniq_midi_input);
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_INPUT |
SNDRV_RAWMIDI_INFO_DUPLEX;
rmidi->private_data = ensoniq;
ensoniq->rmidi = rmidi;
if (rrawmidi)
*rrawmidi = rmidi;
return 0;
}
/*
* Interrupt handler
*/
static irqreturn_t snd_audiopci_interrupt(int irq, void *dev_id)
{
struct ensoniq *ensoniq = dev_id;
unsigned int status, sctrl;
if (ensoniq == NULL)
return IRQ_NONE;
status = inl(ES_REG(ensoniq, STATUS));
if (!(status & ES_INTR))
return IRQ_NONE;
spin_lock(&ensoniq->reg_lock);
sctrl = ensoniq->sctrl;
if (status & ES_DAC1)
sctrl &= ~ES_P1_INT_EN;
if (status & ES_DAC2)
sctrl &= ~ES_P2_INT_EN;
if (status & ES_ADC)
sctrl &= ~ES_R1_INT_EN;
outl(sctrl, ES_REG(ensoniq, SERIAL));
outl(ensoniq->sctrl, ES_REG(ensoniq, SERIAL));
spin_unlock(&ensoniq->reg_lock);
if (status & ES_UART)
snd_ensoniq_midi_interrupt(ensoniq);
if ((status & ES_DAC2) && ensoniq->playback2_substream)
snd_pcm_period_elapsed(ensoniq->playback2_substream);
if ((status & ES_ADC) && ensoniq->capture_substream)
snd_pcm_period_elapsed(ensoniq->capture_substream);
if ((status & ES_DAC1) && ensoniq->playback1_substream)
snd_pcm_period_elapsed(ensoniq->playback1_substream);
return IRQ_HANDLED;
}
static int __devinit snd_audiopci_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct ensoniq *ensoniq;
int err, pcm_devs[2];
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
if ((err = snd_ensoniq_create(card, pci, &ensoniq)) < 0) {
snd_card_free(card);
return err;
}
card->private_data = ensoniq;
pcm_devs[0] = 0; pcm_devs[1] = 1;
#ifdef CHIP1370
if ((err = snd_ensoniq_1370_mixer(ensoniq)) < 0) {
snd_card_free(card);
return err;
}
#endif
#ifdef CHIP1371
if ((err = snd_ensoniq_1371_mixer(ensoniq, spdif[dev], lineio[dev])) < 0) {
snd_card_free(card);
return err;
}
#endif
if ((err = snd_ensoniq_pcm(ensoniq, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ensoniq_pcm2(ensoniq, 1, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ensoniq_midi(ensoniq, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
snd_ensoniq_create_gameport(ensoniq, dev);
strcpy(card->driver, DRIVER_NAME);
strcpy(card->shortname, "Ensoniq AudioPCI");
sprintf(card->longname, "%s %s at 0x%lx, irq %i",
card->shortname,
card->driver,
ensoniq->port,
ensoniq->irq);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_audiopci_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = DRIVER_NAME,
.id_table = snd_audiopci_ids,
.probe = snd_audiopci_probe,
.remove = __devexit_p(snd_audiopci_remove),
#ifdef CONFIG_PM
.suspend = snd_ensoniq_suspend,
.resume = snd_ensoniq_resume,
#endif
};
static int __init alsa_card_ens137x_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_ens137x_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_ens137x_init)
module_exit(alsa_card_ens137x_exit)
| gpl-2.0 |
TeamExodus/kernel_asus_fugu | drivers/isdn/capi/capi.c | 2609 | 32979 | /* $Id: capi.c,v 1.1.2.7 2004/04/28 09:48:59 armin Exp $
*
* CAPI 2.0 Interface for Linux
*
* Copyright 1996 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/errno.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/fs.h>
#include <linux/signal.h>
#include <linux/mutex.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/wait.h>
#include <linux/tty.h>
#include <linux/netdevice.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/capi.h>
#include <linux/kernelcapi.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/isdn/capiutil.h>
#include <linux/isdn/capicmd.h>
MODULE_DESCRIPTION("CAPI4Linux: Userspace /dev/capi20 interface");
MODULE_AUTHOR("Carsten Paeth");
MODULE_LICENSE("GPL");
/* -------- driver information -------------------------------------- */
static DEFINE_MUTEX(capi_mutex);
static struct class *capi_class;
static int capi_major = 68; /* allocated */
module_param_named(major, capi_major, uint, 0);
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
#define CAPINC_NR_PORTS 32
#define CAPINC_MAX_PORTS 256
static int capi_ttyminors = CAPINC_NR_PORTS;
module_param_named(ttyminors, capi_ttyminors, uint, 0);
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
/* -------- defines ------------------------------------------------- */
#define CAPINC_MAX_RECVQUEUE 10
#define CAPINC_MAX_SENDQUEUE 10
#define CAPI_MAX_BLKSIZE 2048
/* -------- data structures ----------------------------------------- */
struct capidev;
struct capincci;
struct capiminor;
struct ackqueue_entry {
struct list_head list;
u16 datahandle;
};
struct capiminor {
unsigned int minor;
struct capi20_appl *ap;
u32 ncci;
atomic_t datahandle;
atomic_t msgid;
struct tty_port port;
int ttyinstop;
int ttyoutstop;
struct sk_buff_head inqueue;
struct sk_buff_head outqueue;
int outbytes;
struct sk_buff *outskb;
spinlock_t outlock;
/* transmit path */
struct list_head ackqueue;
int nack;
spinlock_t ackqlock;
};
struct capincci {
struct list_head list;
u32 ncci;
struct capidev *cdev;
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
struct capiminor *minorp;
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
};
struct capidev {
struct list_head list;
struct capi20_appl ap;
u16 errcode;
unsigned userflags;
struct sk_buff_head recvqueue;
wait_queue_head_t recvwait;
struct list_head nccis;
struct mutex lock;
};
/* -------- global variables ---------------------------------------- */
static DEFINE_MUTEX(capidev_list_lock);
static LIST_HEAD(capidev_list);
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
static DEFINE_SPINLOCK(capiminors_lock);
static struct capiminor **capiminors;
static struct tty_driver *capinc_tty_driver;
/* -------- datahandles --------------------------------------------- */
static int capiminor_add_ack(struct capiminor *mp, u16 datahandle)
{
struct ackqueue_entry *n;
n = kmalloc(sizeof(*n), GFP_ATOMIC);
if (unlikely(!n)) {
printk(KERN_ERR "capi: alloc datahandle failed\n");
return -1;
}
n->datahandle = datahandle;
INIT_LIST_HEAD(&n->list);
spin_lock_bh(&mp->ackqlock);
list_add_tail(&n->list, &mp->ackqueue);
mp->nack++;
spin_unlock_bh(&mp->ackqlock);
return 0;
}
static int capiminor_del_ack(struct capiminor *mp, u16 datahandle)
{
struct ackqueue_entry *p, *tmp;
spin_lock_bh(&mp->ackqlock);
list_for_each_entry_safe(p, tmp, &mp->ackqueue, list) {
if (p->datahandle == datahandle) {
list_del(&p->list);
mp->nack--;
spin_unlock_bh(&mp->ackqlock);
kfree(p);
return 0;
}
}
spin_unlock_bh(&mp->ackqlock);
return -1;
}
static void capiminor_del_all_ack(struct capiminor *mp)
{
struct ackqueue_entry *p, *tmp;
list_for_each_entry_safe(p, tmp, &mp->ackqueue, list) {
list_del(&p->list);
kfree(p);
mp->nack--;
}
}
/* -------- struct capiminor ---------------------------------------- */
static void capiminor_destroy(struct tty_port *port)
{
struct capiminor *mp = container_of(port, struct capiminor, port);
kfree_skb(mp->outskb);
skb_queue_purge(&mp->inqueue);
skb_queue_purge(&mp->outqueue);
capiminor_del_all_ack(mp);
kfree(mp);
}
static const struct tty_port_operations capiminor_port_ops = {
.destruct = capiminor_destroy,
};
static struct capiminor *capiminor_alloc(struct capi20_appl *ap, u32 ncci)
{
struct capiminor *mp;
struct device *dev;
unsigned int minor;
mp = kzalloc(sizeof(*mp), GFP_KERNEL);
if (!mp) {
printk(KERN_ERR "capi: can't alloc capiminor\n");
return NULL;
}
mp->ap = ap;
mp->ncci = ncci;
INIT_LIST_HEAD(&mp->ackqueue);
spin_lock_init(&mp->ackqlock);
skb_queue_head_init(&mp->inqueue);
skb_queue_head_init(&mp->outqueue);
spin_lock_init(&mp->outlock);
tty_port_init(&mp->port);
mp->port.ops = &capiminor_port_ops;
/* Allocate the least unused minor number. */
spin_lock(&capiminors_lock);
for (minor = 0; minor < capi_ttyminors; minor++)
if (!capiminors[minor]) {
capiminors[minor] = mp;
break;
}
spin_unlock(&capiminors_lock);
if (minor == capi_ttyminors) {
printk(KERN_NOTICE "capi: out of minors\n");
goto err_out1;
}
mp->minor = minor;
dev = tty_port_register_device(&mp->port, capinc_tty_driver, minor,
NULL);
if (IS_ERR(dev))
goto err_out2;
return mp;
err_out2:
spin_lock(&capiminors_lock);
capiminors[minor] = NULL;
spin_unlock(&capiminors_lock);
err_out1:
tty_port_put(&mp->port);
return NULL;
}
static struct capiminor *capiminor_get(unsigned int minor)
{
struct capiminor *mp;
spin_lock(&capiminors_lock);
mp = capiminors[minor];
if (mp)
tty_port_get(&mp->port);
spin_unlock(&capiminors_lock);
return mp;
}
static inline void capiminor_put(struct capiminor *mp)
{
tty_port_put(&mp->port);
}
static void capiminor_free(struct capiminor *mp)
{
tty_unregister_device(capinc_tty_driver, mp->minor);
spin_lock(&capiminors_lock);
capiminors[mp->minor] = NULL;
spin_unlock(&capiminors_lock);
capiminor_put(mp);
}
/* -------- struct capincci ----------------------------------------- */
static void capincci_alloc_minor(struct capidev *cdev, struct capincci *np)
{
if (cdev->userflags & CAPIFLAG_HIGHJACKING)
np->minorp = capiminor_alloc(&cdev->ap, np->ncci);
}
static void capincci_free_minor(struct capincci *np)
{
struct capiminor *mp = np->minorp;
struct tty_struct *tty;
if (mp) {
tty = tty_port_tty_get(&mp->port);
if (tty) {
tty_vhangup(tty);
tty_kref_put(tty);
}
capiminor_free(mp);
}
}
static inline unsigned int capincci_minor_opencount(struct capincci *np)
{
struct capiminor *mp = np->minorp;
unsigned int count = 0;
struct tty_struct *tty;
if (mp) {
tty = tty_port_tty_get(&mp->port);
if (tty) {
count = tty->count;
tty_kref_put(tty);
}
}
return count;
}
#else /* !CONFIG_ISDN_CAPI_MIDDLEWARE */
static inline void
capincci_alloc_minor(struct capidev *cdev, struct capincci *np) { }
static inline void capincci_free_minor(struct capincci *np) { }
#endif /* !CONFIG_ISDN_CAPI_MIDDLEWARE */
static struct capincci *capincci_alloc(struct capidev *cdev, u32 ncci)
{
struct capincci *np;
np = kzalloc(sizeof(*np), GFP_KERNEL);
if (!np)
return NULL;
np->ncci = ncci;
np->cdev = cdev;
capincci_alloc_minor(cdev, np);
list_add_tail(&np->list, &cdev->nccis);
return np;
}
static void capincci_free(struct capidev *cdev, u32 ncci)
{
struct capincci *np, *tmp;
list_for_each_entry_safe(np, tmp, &cdev->nccis, list)
if (ncci == 0xffffffff || np->ncci == ncci) {
capincci_free_minor(np);
list_del(&np->list);
kfree(np);
}
}
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
static struct capincci *capincci_find(struct capidev *cdev, u32 ncci)
{
struct capincci *np;
list_for_each_entry(np, &cdev->nccis, list)
if (np->ncci == ncci)
return np;
return NULL;
}
/* -------- handle data queue --------------------------------------- */
static struct sk_buff *
gen_data_b3_resp_for(struct capiminor *mp, struct sk_buff *skb)
{
struct sk_buff *nskb;
nskb = alloc_skb(CAPI_DATA_B3_RESP_LEN, GFP_KERNEL);
if (nskb) {
u16 datahandle = CAPIMSG_U16(skb->data, CAPIMSG_BASELEN + 4 + 4 + 2);
unsigned char *s = skb_put(nskb, CAPI_DATA_B3_RESP_LEN);
capimsg_setu16(s, 0, CAPI_DATA_B3_RESP_LEN);
capimsg_setu16(s, 2, mp->ap->applid);
capimsg_setu8 (s, 4, CAPI_DATA_B3);
capimsg_setu8 (s, 5, CAPI_RESP);
capimsg_setu16(s, 6, atomic_inc_return(&mp->msgid));
capimsg_setu32(s, 8, mp->ncci);
capimsg_setu16(s, 12, datahandle);
}
return nskb;
}
static int handle_recv_skb(struct capiminor *mp, struct sk_buff *skb)
{
unsigned int datalen = skb->len - CAPIMSG_LEN(skb->data);
struct tty_struct *tty;
struct sk_buff *nskb;
u16 errcode, datahandle;
struct tty_ldisc *ld;
int ret = -1;
tty = tty_port_tty_get(&mp->port);
if (!tty) {
pr_debug("capi: currently no receiver\n");
return -1;
}
ld = tty_ldisc_ref(tty);
if (!ld) {
/* fatal error, do not requeue */
ret = 0;
kfree_skb(skb);
goto deref_tty;
}
if (ld->ops->receive_buf == NULL) {
pr_debug("capi: ldisc has no receive_buf function\n");
/* fatal error, do not requeue */
goto free_skb;
}
if (mp->ttyinstop) {
pr_debug("capi: recv tty throttled\n");
goto deref_ldisc;
}
if (tty->receive_room < datalen) {
pr_debug("capi: no room in tty\n");
goto deref_ldisc;
}
nskb = gen_data_b3_resp_for(mp, skb);
if (!nskb) {
printk(KERN_ERR "capi: gen_data_b3_resp failed\n");
goto deref_ldisc;
}
datahandle = CAPIMSG_U16(skb->data, CAPIMSG_BASELEN + 4);
errcode = capi20_put_message(mp->ap, nskb);
if (errcode == CAPI_NOERROR) {
skb_pull(skb, CAPIMSG_LEN(skb->data));
pr_debug("capi: DATA_B3_RESP %u len=%d => ldisc\n",
datahandle, skb->len);
ld->ops->receive_buf(tty, skb->data, NULL, skb->len);
} else {
printk(KERN_ERR "capi: send DATA_B3_RESP failed=%x\n",
errcode);
kfree_skb(nskb);
if (errcode == CAPI_SENDQUEUEFULL)
goto deref_ldisc;
}
free_skb:
ret = 0;
kfree_skb(skb);
deref_ldisc:
tty_ldisc_deref(ld);
deref_tty:
tty_kref_put(tty);
return ret;
}
static void handle_minor_recv(struct capiminor *mp)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(&mp->inqueue)) != NULL)
if (handle_recv_skb(mp, skb) < 0) {
skb_queue_head(&mp->inqueue, skb);
return;
}
}
static void handle_minor_send(struct capiminor *mp)
{
struct tty_struct *tty;
struct sk_buff *skb;
u16 len;
u16 errcode;
u16 datahandle;
tty = tty_port_tty_get(&mp->port);
if (!tty)
return;
if (mp->ttyoutstop) {
pr_debug("capi: send: tty stopped\n");
tty_kref_put(tty);
return;
}
while (1) {
spin_lock_bh(&mp->outlock);
skb = __skb_dequeue(&mp->outqueue);
if (!skb) {
spin_unlock_bh(&mp->outlock);
break;
}
len = (u16)skb->len;
mp->outbytes -= len;
spin_unlock_bh(&mp->outlock);
datahandle = atomic_inc_return(&mp->datahandle);
skb_push(skb, CAPI_DATA_B3_REQ_LEN);
memset(skb->data, 0, CAPI_DATA_B3_REQ_LEN);
capimsg_setu16(skb->data, 0, CAPI_DATA_B3_REQ_LEN);
capimsg_setu16(skb->data, 2, mp->ap->applid);
capimsg_setu8 (skb->data, 4, CAPI_DATA_B3);
capimsg_setu8 (skb->data, 5, CAPI_REQ);
capimsg_setu16(skb->data, 6, atomic_inc_return(&mp->msgid));
capimsg_setu32(skb->data, 8, mp->ncci); /* NCCI */
capimsg_setu32(skb->data, 12, (u32)(long)skb->data);/* Data32 */
capimsg_setu16(skb->data, 16, len); /* Data length */
capimsg_setu16(skb->data, 18, datahandle);
capimsg_setu16(skb->data, 20, 0); /* Flags */
if (capiminor_add_ack(mp, datahandle) < 0) {
skb_pull(skb, CAPI_DATA_B3_REQ_LEN);
spin_lock_bh(&mp->outlock);
__skb_queue_head(&mp->outqueue, skb);
mp->outbytes += len;
spin_unlock_bh(&mp->outlock);
break;
}
errcode = capi20_put_message(mp->ap, skb);
if (errcode == CAPI_NOERROR) {
pr_debug("capi: DATA_B3_REQ %u len=%u\n",
datahandle, len);
continue;
}
capiminor_del_ack(mp, datahandle);
if (errcode == CAPI_SENDQUEUEFULL) {
skb_pull(skb, CAPI_DATA_B3_REQ_LEN);
spin_lock_bh(&mp->outlock);
__skb_queue_head(&mp->outqueue, skb);
mp->outbytes += len;
spin_unlock_bh(&mp->outlock);
break;
}
/* ups, drop packet */
printk(KERN_ERR "capi: put_message = %x\n", errcode);
kfree_skb(skb);
}
tty_kref_put(tty);
}
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
/* -------- function called by lower level -------------------------- */
static void capi_recv_message(struct capi20_appl *ap, struct sk_buff *skb)
{
struct capidev *cdev = ap->private;
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
struct capiminor *mp;
u16 datahandle;
struct capincci *np;
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
mutex_lock(&cdev->lock);
if (CAPIMSG_CMD(skb->data) == CAPI_CONNECT_B3_CONF) {
u16 info = CAPIMSG_U16(skb->data, 12); // Info field
if ((info & 0xff00) == 0)
capincci_alloc(cdev, CAPIMSG_NCCI(skb->data));
}
if (CAPIMSG_CMD(skb->data) == CAPI_CONNECT_B3_IND)
capincci_alloc(cdev, CAPIMSG_NCCI(skb->data));
if (CAPIMSG_COMMAND(skb->data) != CAPI_DATA_B3) {
skb_queue_tail(&cdev->recvqueue, skb);
wake_up_interruptible(&cdev->recvwait);
goto unlock_out;
}
#ifndef CONFIG_ISDN_CAPI_MIDDLEWARE
skb_queue_tail(&cdev->recvqueue, skb);
wake_up_interruptible(&cdev->recvwait);
#else /* CONFIG_ISDN_CAPI_MIDDLEWARE */
np = capincci_find(cdev, CAPIMSG_CONTROL(skb->data));
if (!np) {
printk(KERN_ERR "BUG: capi_signal: ncci not found\n");
skb_queue_tail(&cdev->recvqueue, skb);
wake_up_interruptible(&cdev->recvwait);
goto unlock_out;
}
mp = np->minorp;
if (!mp) {
skb_queue_tail(&cdev->recvqueue, skb);
wake_up_interruptible(&cdev->recvwait);
goto unlock_out;
}
if (CAPIMSG_SUBCOMMAND(skb->data) == CAPI_IND) {
datahandle = CAPIMSG_U16(skb->data, CAPIMSG_BASELEN + 4 + 4 + 2);
pr_debug("capi_signal: DATA_B3_IND %u len=%d\n",
datahandle, skb->len-CAPIMSG_LEN(skb->data));
skb_queue_tail(&mp->inqueue, skb);
handle_minor_recv(mp);
} else if (CAPIMSG_SUBCOMMAND(skb->data) == CAPI_CONF) {
datahandle = CAPIMSG_U16(skb->data, CAPIMSG_BASELEN + 4);
pr_debug("capi_signal: DATA_B3_CONF %u 0x%x\n",
datahandle,
CAPIMSG_U16(skb->data, CAPIMSG_BASELEN + 4 + 2));
kfree_skb(skb);
capiminor_del_ack(mp, datahandle);
tty_port_tty_wakeup(&mp->port);
handle_minor_send(mp);
} else {
/* ups, let capi application handle it :-) */
skb_queue_tail(&cdev->recvqueue, skb);
wake_up_interruptible(&cdev->recvwait);
}
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
unlock_out:
mutex_unlock(&cdev->lock);
}
/* -------- file_operations for capidev ----------------------------- */
static ssize_t
capi_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct capidev *cdev = file->private_data;
struct sk_buff *skb;
size_t copied;
int err;
if (!cdev->ap.applid)
return -ENODEV;
skb = skb_dequeue(&cdev->recvqueue);
if (!skb) {
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
err = wait_event_interruptible(cdev->recvwait,
(skb = skb_dequeue(&cdev->recvqueue)));
if (err)
return err;
}
if (skb->len > count) {
skb_queue_head(&cdev->recvqueue, skb);
return -EMSGSIZE;
}
if (copy_to_user(buf, skb->data, skb->len)) {
skb_queue_head(&cdev->recvqueue, skb);
return -EFAULT;
}
copied = skb->len;
kfree_skb(skb);
return copied;
}
static ssize_t
capi_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct capidev *cdev = file->private_data;
struct sk_buff *skb;
u16 mlen;
if (!cdev->ap.applid)
return -ENODEV;
skb = alloc_skb(count, GFP_USER);
if (!skb)
return -ENOMEM;
if (copy_from_user(skb_put(skb, count), buf, count)) {
kfree_skb(skb);
return -EFAULT;
}
mlen = CAPIMSG_LEN(skb->data);
if (CAPIMSG_CMD(skb->data) == CAPI_DATA_B3_REQ) {
if ((size_t)(mlen + CAPIMSG_DATALEN(skb->data)) != count) {
kfree_skb(skb);
return -EINVAL;
}
} else {
if (mlen != count) {
kfree_skb(skb);
return -EINVAL;
}
}
CAPIMSG_SETAPPID(skb->data, cdev->ap.applid);
if (CAPIMSG_CMD(skb->data) == CAPI_DISCONNECT_B3_RESP) {
mutex_lock(&cdev->lock);
capincci_free(cdev, CAPIMSG_NCCI(skb->data));
mutex_unlock(&cdev->lock);
}
cdev->errcode = capi20_put_message(&cdev->ap, skb);
if (cdev->errcode) {
kfree_skb(skb);
return -EIO;
}
return count;
}
static unsigned int
capi_poll(struct file *file, poll_table *wait)
{
struct capidev *cdev = file->private_data;
unsigned int mask = 0;
if (!cdev->ap.applid)
return POLLERR;
poll_wait(file, &(cdev->recvwait), wait);
mask = POLLOUT | POLLWRNORM;
if (!skb_queue_empty(&cdev->recvqueue))
mask |= POLLIN | POLLRDNORM;
return mask;
}
static int
capi_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct capidev *cdev = file->private_data;
capi_ioctl_struct data;
int retval = -EINVAL;
void __user *argp = (void __user *)arg;
switch (cmd) {
case CAPI_REGISTER:
mutex_lock(&cdev->lock);
if (cdev->ap.applid) {
retval = -EEXIST;
goto register_out;
}
if (copy_from_user(&cdev->ap.rparam, argp,
sizeof(struct capi_register_params))) {
retval = -EFAULT;
goto register_out;
}
cdev->ap.private = cdev;
cdev->ap.recv_message = capi_recv_message;
cdev->errcode = capi20_register(&cdev->ap);
retval = (int)cdev->ap.applid;
if (cdev->errcode) {
cdev->ap.applid = 0;
retval = -EIO;
}
register_out:
mutex_unlock(&cdev->lock);
return retval;
case CAPI_GET_VERSION:
if (copy_from_user(&data.contr, argp,
sizeof(data.contr)))
return -EFAULT;
cdev->errcode = capi20_get_version(data.contr, &data.version);
if (cdev->errcode)
return -EIO;
if (copy_to_user(argp, &data.version,
sizeof(data.version)))
return -EFAULT;
return 0;
case CAPI_GET_SERIAL:
if (copy_from_user(&data.contr, argp,
sizeof(data.contr)))
return -EFAULT;
cdev->errcode = capi20_get_serial(data.contr, data.serial);
if (cdev->errcode)
return -EIO;
if (copy_to_user(argp, data.serial,
sizeof(data.serial)))
return -EFAULT;
return 0;
case CAPI_GET_PROFILE:
if (copy_from_user(&data.contr, argp,
sizeof(data.contr)))
return -EFAULT;
if (data.contr == 0) {
cdev->errcode = capi20_get_profile(data.contr, &data.profile);
if (cdev->errcode)
return -EIO;
retval = copy_to_user(argp,
&data.profile.ncontroller,
sizeof(data.profile.ncontroller));
} else {
cdev->errcode = capi20_get_profile(data.contr, &data.profile);
if (cdev->errcode)
return -EIO;
retval = copy_to_user(argp, &data.profile,
sizeof(data.profile));
}
if (retval)
return -EFAULT;
return 0;
case CAPI_GET_MANUFACTURER:
if (copy_from_user(&data.contr, argp,
sizeof(data.contr)))
return -EFAULT;
cdev->errcode = capi20_get_manufacturer(data.contr, data.manufacturer);
if (cdev->errcode)
return -EIO;
if (copy_to_user(argp, data.manufacturer,
sizeof(data.manufacturer)))
return -EFAULT;
return 0;
case CAPI_GET_ERRCODE:
data.errcode = cdev->errcode;
cdev->errcode = CAPI_NOERROR;
if (arg) {
if (copy_to_user(argp, &data.errcode,
sizeof(data.errcode)))
return -EFAULT;
}
return data.errcode;
case CAPI_INSTALLED:
if (capi20_isinstalled() == CAPI_NOERROR)
return 0;
return -ENXIO;
case CAPI_MANUFACTURER_CMD: {
struct capi_manufacturer_cmd mcmd;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (copy_from_user(&mcmd, argp, sizeof(mcmd)))
return -EFAULT;
return capi20_manufacturer(mcmd.cmd, mcmd.data);
}
case CAPI_SET_FLAGS:
case CAPI_CLR_FLAGS: {
unsigned userflags;
if (copy_from_user(&userflags, argp, sizeof(userflags)))
return -EFAULT;
mutex_lock(&cdev->lock);
if (cmd == CAPI_SET_FLAGS)
cdev->userflags |= userflags;
else
cdev->userflags &= ~userflags;
mutex_unlock(&cdev->lock);
return 0;
}
case CAPI_GET_FLAGS:
if (copy_to_user(argp, &cdev->userflags,
sizeof(cdev->userflags)))
return -EFAULT;
return 0;
#ifndef CONFIG_ISDN_CAPI_MIDDLEWARE
case CAPI_NCCI_OPENCOUNT:
return 0;
#else /* CONFIG_ISDN_CAPI_MIDDLEWARE */
case CAPI_NCCI_OPENCOUNT: {
struct capincci *nccip;
unsigned ncci;
int count = 0;
if (copy_from_user(&ncci, argp, sizeof(ncci)))
return -EFAULT;
mutex_lock(&cdev->lock);
nccip = capincci_find(cdev, (u32)ncci);
if (nccip)
count = capincci_minor_opencount(nccip);
mutex_unlock(&cdev->lock);
return count;
}
case CAPI_NCCI_GETUNIT: {
struct capincci *nccip;
struct capiminor *mp;
unsigned ncci;
int unit = -ESRCH;
if (copy_from_user(&ncci, argp, sizeof(ncci)))
return -EFAULT;
mutex_lock(&cdev->lock);
nccip = capincci_find(cdev, (u32)ncci);
if (nccip) {
mp = nccip->minorp;
if (mp)
unit = mp->minor;
}
mutex_unlock(&cdev->lock);
return unit;
}
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
default:
return -EINVAL;
}
}
static long
capi_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&capi_mutex);
ret = capi_ioctl(file, cmd, arg);
mutex_unlock(&capi_mutex);
return ret;
}
static int capi_open(struct inode *inode, struct file *file)
{
struct capidev *cdev;
cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
if (!cdev)
return -ENOMEM;
mutex_init(&cdev->lock);
skb_queue_head_init(&cdev->recvqueue);
init_waitqueue_head(&cdev->recvwait);
INIT_LIST_HEAD(&cdev->nccis);
file->private_data = cdev;
mutex_lock(&capidev_list_lock);
list_add_tail(&cdev->list, &capidev_list);
mutex_unlock(&capidev_list_lock);
return nonseekable_open(inode, file);
}
static int capi_release(struct inode *inode, struct file *file)
{
struct capidev *cdev = file->private_data;
mutex_lock(&capidev_list_lock);
list_del(&cdev->list);
mutex_unlock(&capidev_list_lock);
if (cdev->ap.applid)
capi20_release(&cdev->ap);
skb_queue_purge(&cdev->recvqueue);
capincci_free(cdev, 0xffffffff);
kfree(cdev);
return 0;
}
static const struct file_operations capi_fops =
{
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = capi_read,
.write = capi_write,
.poll = capi_poll,
.unlocked_ioctl = capi_unlocked_ioctl,
.open = capi_open,
.release = capi_release,
};
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
/* -------- tty_operations for capincci ----------------------------- */
static int
capinc_tty_install(struct tty_driver *driver, struct tty_struct *tty)
{
struct capiminor *mp = capiminor_get(tty->index);
int ret = tty_standard_install(driver, tty);
if (ret == 0)
tty->driver_data = mp;
else
capiminor_put(mp);
return ret;
}
static void capinc_tty_cleanup(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
tty->driver_data = NULL;
capiminor_put(mp);
}
static int capinc_tty_open(struct tty_struct *tty, struct file *filp)
{
struct capiminor *mp = tty->driver_data;
int err;
err = tty_port_open(&mp->port, tty, filp);
if (err)
return err;
handle_minor_recv(mp);
return 0;
}
static void capinc_tty_close(struct tty_struct *tty, struct file *filp)
{
struct capiminor *mp = tty->driver_data;
tty_port_close(&mp->port, tty, filp);
}
static int capinc_tty_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct capiminor *mp = tty->driver_data;
struct sk_buff *skb;
pr_debug("capinc_tty_write(count=%d)\n", count);
spin_lock_bh(&mp->outlock);
skb = mp->outskb;
if (skb) {
mp->outskb = NULL;
__skb_queue_tail(&mp->outqueue, skb);
mp->outbytes += skb->len;
}
skb = alloc_skb(CAPI_DATA_B3_REQ_LEN + count, GFP_ATOMIC);
if (!skb) {
printk(KERN_ERR "capinc_tty_write: alloc_skb failed\n");
spin_unlock_bh(&mp->outlock);
return -ENOMEM;
}
skb_reserve(skb, CAPI_DATA_B3_REQ_LEN);
memcpy(skb_put(skb, count), buf, count);
__skb_queue_tail(&mp->outqueue, skb);
mp->outbytes += skb->len;
spin_unlock_bh(&mp->outlock);
handle_minor_send(mp);
return count;
}
static int capinc_tty_put_char(struct tty_struct *tty, unsigned char ch)
{
struct capiminor *mp = tty->driver_data;
bool invoke_send = false;
struct sk_buff *skb;
int ret = 1;
pr_debug("capinc_put_char(%u)\n", ch);
spin_lock_bh(&mp->outlock);
skb = mp->outskb;
if (skb) {
if (skb_tailroom(skb) > 0) {
*(skb_put(skb, 1)) = ch;
goto unlock_out;
}
mp->outskb = NULL;
__skb_queue_tail(&mp->outqueue, skb);
mp->outbytes += skb->len;
invoke_send = true;
}
skb = alloc_skb(CAPI_DATA_B3_REQ_LEN + CAPI_MAX_BLKSIZE, GFP_ATOMIC);
if (skb) {
skb_reserve(skb, CAPI_DATA_B3_REQ_LEN);
*(skb_put(skb, 1)) = ch;
mp->outskb = skb;
} else {
printk(KERN_ERR "capinc_put_char: char %u lost\n", ch);
ret = 0;
}
unlock_out:
spin_unlock_bh(&mp->outlock);
if (invoke_send)
handle_minor_send(mp);
return ret;
}
static void capinc_tty_flush_chars(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
struct sk_buff *skb;
pr_debug("capinc_tty_flush_chars\n");
spin_lock_bh(&mp->outlock);
skb = mp->outskb;
if (skb) {
mp->outskb = NULL;
__skb_queue_tail(&mp->outqueue, skb);
mp->outbytes += skb->len;
spin_unlock_bh(&mp->outlock);
handle_minor_send(mp);
} else
spin_unlock_bh(&mp->outlock);
handle_minor_recv(mp);
}
static int capinc_tty_write_room(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
int room;
room = CAPINC_MAX_SENDQUEUE-skb_queue_len(&mp->outqueue);
room *= CAPI_MAX_BLKSIZE;
pr_debug("capinc_tty_write_room = %d\n", room);
return room;
}
static int capinc_tty_chars_in_buffer(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_chars_in_buffer = %d nack=%d sq=%d rq=%d\n",
mp->outbytes, mp->nack,
skb_queue_len(&mp->outqueue),
skb_queue_len(&mp->inqueue));
return mp->outbytes;
}
static int capinc_tty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
return -ENOIOCTLCMD;
}
static void capinc_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
pr_debug("capinc_tty_set_termios\n");
}
static void capinc_tty_throttle(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_throttle\n");
mp->ttyinstop = 1;
}
static void capinc_tty_unthrottle(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_unthrottle\n");
mp->ttyinstop = 0;
handle_minor_recv(mp);
}
static void capinc_tty_stop(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_stop\n");
mp->ttyoutstop = 1;
}
static void capinc_tty_start(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_start\n");
mp->ttyoutstop = 0;
handle_minor_send(mp);
}
static void capinc_tty_hangup(struct tty_struct *tty)
{
struct capiminor *mp = tty->driver_data;
pr_debug("capinc_tty_hangup\n");
tty_port_hangup(&mp->port);
}
static int capinc_tty_break_ctl(struct tty_struct *tty, int state)
{
pr_debug("capinc_tty_break_ctl(%d)\n", state);
return 0;
}
static void capinc_tty_flush_buffer(struct tty_struct *tty)
{
pr_debug("capinc_tty_flush_buffer\n");
}
static void capinc_tty_set_ldisc(struct tty_struct *tty)
{
pr_debug("capinc_tty_set_ldisc\n");
}
static void capinc_tty_send_xchar(struct tty_struct *tty, char ch)
{
pr_debug("capinc_tty_send_xchar(%d)\n", ch);
}
static const struct tty_operations capinc_ops = {
.open = capinc_tty_open,
.close = capinc_tty_close,
.write = capinc_tty_write,
.put_char = capinc_tty_put_char,
.flush_chars = capinc_tty_flush_chars,
.write_room = capinc_tty_write_room,
.chars_in_buffer = capinc_tty_chars_in_buffer,
.ioctl = capinc_tty_ioctl,
.set_termios = capinc_tty_set_termios,
.throttle = capinc_tty_throttle,
.unthrottle = capinc_tty_unthrottle,
.stop = capinc_tty_stop,
.start = capinc_tty_start,
.hangup = capinc_tty_hangup,
.break_ctl = capinc_tty_break_ctl,
.flush_buffer = capinc_tty_flush_buffer,
.set_ldisc = capinc_tty_set_ldisc,
.send_xchar = capinc_tty_send_xchar,
.install = capinc_tty_install,
.cleanup = capinc_tty_cleanup,
};
static int __init capinc_tty_init(void)
{
struct tty_driver *drv;
int err;
if (capi_ttyminors > CAPINC_MAX_PORTS)
capi_ttyminors = CAPINC_MAX_PORTS;
if (capi_ttyminors <= 0)
capi_ttyminors = CAPINC_NR_PORTS;
capiminors = kzalloc(sizeof(struct capi_minor *) * capi_ttyminors,
GFP_KERNEL);
if (!capiminors)
return -ENOMEM;
drv = alloc_tty_driver(capi_ttyminors);
if (!drv) {
kfree(capiminors);
return -ENOMEM;
}
drv->driver_name = "capi_nc";
drv->name = "capi";
drv->major = 0;
drv->minor_start = 0;
drv->type = TTY_DRIVER_TYPE_SERIAL;
drv->subtype = SERIAL_TYPE_NORMAL;
drv->init_termios = tty_std_termios;
drv->init_termios.c_iflag = ICRNL;
drv->init_termios.c_oflag = OPOST | ONLCR;
drv->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
drv->init_termios.c_lflag = 0;
drv->flags =
TTY_DRIVER_REAL_RAW | TTY_DRIVER_RESET_TERMIOS |
TTY_DRIVER_DYNAMIC_DEV;
tty_set_operations(drv, &capinc_ops);
err = tty_register_driver(drv);
if (err) {
put_tty_driver(drv);
kfree(capiminors);
printk(KERN_ERR "Couldn't register capi_nc driver\n");
return err;
}
capinc_tty_driver = drv;
return 0;
}
static void __exit capinc_tty_exit(void)
{
tty_unregister_driver(capinc_tty_driver);
put_tty_driver(capinc_tty_driver);
kfree(capiminors);
}
#else /* !CONFIG_ISDN_CAPI_MIDDLEWARE */
static inline int capinc_tty_init(void)
{
return 0;
}
static inline void capinc_tty_exit(void) { }
#endif /* !CONFIG_ISDN_CAPI_MIDDLEWARE */
/* -------- /proc functions ----------------------------------------- */
/*
* /proc/capi/capi20:
* minor applid nrecvctlpkt nrecvdatapkt nsendctlpkt nsenddatapkt
*/
static int capi20_proc_show(struct seq_file *m, void *v)
{
struct capidev *cdev;
struct list_head *l;
mutex_lock(&capidev_list_lock);
list_for_each(l, &capidev_list) {
cdev = list_entry(l, struct capidev, list);
seq_printf(m, "0 %d %lu %lu %lu %lu\n",
cdev->ap.applid,
cdev->ap.nrecvctlpkt,
cdev->ap.nrecvdatapkt,
cdev->ap.nsentctlpkt,
cdev->ap.nsentdatapkt);
}
mutex_unlock(&capidev_list_lock);
return 0;
}
static int capi20_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, capi20_proc_show, NULL);
}
static const struct file_operations capi20_proc_fops = {
.owner = THIS_MODULE,
.open = capi20_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/*
* /proc/capi/capi20ncci:
* applid ncci
*/
static int capi20ncci_proc_show(struct seq_file *m, void *v)
{
struct capidev *cdev;
struct capincci *np;
mutex_lock(&capidev_list_lock);
list_for_each_entry(cdev, &capidev_list, list) {
mutex_lock(&cdev->lock);
list_for_each_entry(np, &cdev->nccis, list)
seq_printf(m, "%d 0x%x\n", cdev->ap.applid, np->ncci);
mutex_unlock(&cdev->lock);
}
mutex_unlock(&capidev_list_lock);
return 0;
}
static int capi20ncci_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, capi20ncci_proc_show, NULL);
}
static const struct file_operations capi20ncci_proc_fops = {
.owner = THIS_MODULE,
.open = capi20ncci_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void __init proc_init(void)
{
proc_create("capi/capi20", 0, NULL, &capi20_proc_fops);
proc_create("capi/capi20ncci", 0, NULL, &capi20ncci_proc_fops);
}
static void __exit proc_exit(void)
{
remove_proc_entry("capi/capi20", NULL);
remove_proc_entry("capi/capi20ncci", NULL);
}
/* -------- init function and module interface ---------------------- */
static int __init capi_init(void)
{
const char *compileinfo;
int major_ret;
major_ret = register_chrdev(capi_major, "capi20", &capi_fops);
if (major_ret < 0) {
printk(KERN_ERR "capi20: unable to get major %d\n", capi_major);
return major_ret;
}
capi_class = class_create(THIS_MODULE, "capi");
if (IS_ERR(capi_class)) {
unregister_chrdev(capi_major, "capi20");
return PTR_ERR(capi_class);
}
device_create(capi_class, NULL, MKDEV(capi_major, 0), NULL, "capi");
if (capinc_tty_init() < 0) {
device_destroy(capi_class, MKDEV(capi_major, 0));
class_destroy(capi_class);
unregister_chrdev(capi_major, "capi20");
return -ENOMEM;
}
proc_init();
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
compileinfo = " (middleware)";
#else
compileinfo = " (no middleware)";
#endif
printk(KERN_NOTICE "CAPI 2.0 started up with major %d%s\n",
capi_major, compileinfo);
return 0;
}
static void __exit capi_exit(void)
{
proc_exit();
device_destroy(capi_class, MKDEV(capi_major, 0));
class_destroy(capi_class);
unregister_chrdev(capi_major, "capi20");
capinc_tty_exit();
}
module_init(capi_init);
module_exit(capi_exit);
| gpl-2.0 |
Team-Blackout/EvilZ.213.BLACKOUT_edition | arch/powerpc/kernel/module.c | 2609 | 2775 | /* Kernel module help for powerpc.
Copyright (C) 2001, 2003 Rusty Russell IBM Corporation.
Copyright (C) 2008 Freescale Semiconductor, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/elf.h>
#include <linux/moduleloader.h>
#include <linux/err.h>
#include <linux/vmalloc.h>
#include <linux/bug.h>
#include <asm/module.h>
#include <asm/uaccess.h>
#include <asm/firmware.h>
#include <linux/sort.h>
#include "setup.h"
LIST_HEAD(module_bug_list);
void *module_alloc(unsigned long size)
{
if (size == 0)
return NULL;
return vmalloc_exec(size);
}
/* Free memory returned from module_alloc */
void module_free(struct module *mod, void *module_region)
{
vfree(module_region);
}
static const Elf_Shdr *find_section(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs,
const char *name)
{
char *secstrings;
unsigned int i;
secstrings = (char *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
for (i = 1; i < hdr->e_shnum; i++)
if (strcmp(secstrings+sechdrs[i].sh_name, name) == 0)
return &sechdrs[i];
return NULL;
}
int module_finalize(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs, struct module *me)
{
const Elf_Shdr *sect;
/* Apply feature fixups */
sect = find_section(hdr, sechdrs, "__ftr_fixup");
if (sect != NULL)
do_feature_fixups(cur_cpu_spec->cpu_features,
(void *)sect->sh_addr,
(void *)sect->sh_addr + sect->sh_size);
sect = find_section(hdr, sechdrs, "__mmu_ftr_fixup");
if (sect != NULL)
do_feature_fixups(cur_cpu_spec->mmu_features,
(void *)sect->sh_addr,
(void *)sect->sh_addr + sect->sh_size);
#ifdef CONFIG_PPC64
sect = find_section(hdr, sechdrs, "__fw_ftr_fixup");
if (sect != NULL)
do_feature_fixups(powerpc_firmware_features,
(void *)sect->sh_addr,
(void *)sect->sh_addr + sect->sh_size);
#endif
sect = find_section(hdr, sechdrs, "__lwsync_fixup");
if (sect != NULL)
do_lwsync_fixups(cur_cpu_spec->cpu_features,
(void *)sect->sh_addr,
(void *)sect->sh_addr + sect->sh_size);
return 0;
}
void module_arch_cleanup(struct module *mod)
{
}
| gpl-2.0 |
meizuosc/m03x | crypto/blkcipher.c | 3121 | 19013 | /*
* Block chaining cipher operations.
*
* Generic encrypt/decrypt wrapper for ciphers, handles operations across
* multiple page boundaries by using temporary blocks. In user context,
* the kernel is given a chance to schedule us once per page.
*
* Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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 <crypto/internal/skcipher.h>
#include <crypto/scatterwalk.h>
#include <linux/errno.h>
#include <linux/hardirq.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/scatterlist.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/string.h>
#include "internal.h"
enum {
BLKCIPHER_WALK_PHYS = 1 << 0,
BLKCIPHER_WALK_SLOW = 1 << 1,
BLKCIPHER_WALK_COPY = 1 << 2,
BLKCIPHER_WALK_DIFF = 1 << 3,
};
static int blkcipher_walk_next(struct blkcipher_desc *desc,
struct blkcipher_walk *walk);
static int blkcipher_walk_first(struct blkcipher_desc *desc,
struct blkcipher_walk *walk);
static inline void blkcipher_map_src(struct blkcipher_walk *walk)
{
walk->src.virt.addr = scatterwalk_map(&walk->in, 0);
}
static inline void blkcipher_map_dst(struct blkcipher_walk *walk)
{
walk->dst.virt.addr = scatterwalk_map(&walk->out, 1);
}
static inline void blkcipher_unmap_src(struct blkcipher_walk *walk)
{
scatterwalk_unmap(walk->src.virt.addr, 0);
}
static inline void blkcipher_unmap_dst(struct blkcipher_walk *walk)
{
scatterwalk_unmap(walk->dst.virt.addr, 1);
}
/* Get a spot of the specified length that does not straddle a page.
* The caller needs to ensure that there is enough space for this operation.
*/
static inline u8 *blkcipher_get_spot(u8 *start, unsigned int len)
{
u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK);
return max(start, end_page);
}
static inline unsigned int blkcipher_done_slow(struct crypto_blkcipher *tfm,
struct blkcipher_walk *walk,
unsigned int bsize)
{
u8 *addr;
unsigned int alignmask = crypto_blkcipher_alignmask(tfm);
addr = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1);
addr = blkcipher_get_spot(addr, bsize);
scatterwalk_copychunks(addr, &walk->out, bsize, 1);
return bsize;
}
static inline unsigned int blkcipher_done_fast(struct blkcipher_walk *walk,
unsigned int n)
{
if (walk->flags & BLKCIPHER_WALK_COPY) {
blkcipher_map_dst(walk);
memcpy(walk->dst.virt.addr, walk->page, n);
blkcipher_unmap_dst(walk);
} else if (!(walk->flags & BLKCIPHER_WALK_PHYS)) {
if (walk->flags & BLKCIPHER_WALK_DIFF)
blkcipher_unmap_dst(walk);
blkcipher_unmap_src(walk);
}
scatterwalk_advance(&walk->in, n);
scatterwalk_advance(&walk->out, n);
return n;
}
int blkcipher_walk_done(struct blkcipher_desc *desc,
struct blkcipher_walk *walk, int err)
{
struct crypto_blkcipher *tfm = desc->tfm;
unsigned int nbytes = 0;
if (likely(err >= 0)) {
unsigned int n = walk->nbytes - err;
if (likely(!(walk->flags & BLKCIPHER_WALK_SLOW)))
n = blkcipher_done_fast(walk, n);
else if (WARN_ON(err)) {
err = -EINVAL;
goto err;
} else
n = blkcipher_done_slow(tfm, walk, n);
nbytes = walk->total - n;
err = 0;
}
scatterwalk_done(&walk->in, 0, nbytes);
scatterwalk_done(&walk->out, 1, nbytes);
err:
walk->total = nbytes;
walk->nbytes = nbytes;
if (nbytes) {
crypto_yield(desc->flags);
return blkcipher_walk_next(desc, walk);
}
if (walk->iv != desc->info)
memcpy(desc->info, walk->iv, crypto_blkcipher_ivsize(tfm));
if (walk->buffer != walk->page)
kfree(walk->buffer);
if (walk->page)
free_page((unsigned long)walk->page);
return err;
}
EXPORT_SYMBOL_GPL(blkcipher_walk_done);
static inline int blkcipher_next_slow(struct blkcipher_desc *desc,
struct blkcipher_walk *walk,
unsigned int bsize,
unsigned int alignmask)
{
unsigned int n;
unsigned aligned_bsize = ALIGN(bsize, alignmask + 1);
if (walk->buffer)
goto ok;
walk->buffer = walk->page;
if (walk->buffer)
goto ok;
n = aligned_bsize * 3 - (alignmask + 1) +
(alignmask & ~(crypto_tfm_ctx_alignment() - 1));
walk->buffer = kmalloc(n, GFP_ATOMIC);
if (!walk->buffer)
return blkcipher_walk_done(desc, walk, -ENOMEM);
ok:
walk->dst.virt.addr = (u8 *)ALIGN((unsigned long)walk->buffer,
alignmask + 1);
walk->dst.virt.addr = blkcipher_get_spot(walk->dst.virt.addr, bsize);
walk->src.virt.addr = blkcipher_get_spot(walk->dst.virt.addr +
aligned_bsize, bsize);
scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0);
walk->nbytes = bsize;
walk->flags |= BLKCIPHER_WALK_SLOW;
return 0;
}
static inline int blkcipher_next_copy(struct blkcipher_walk *walk)
{
u8 *tmp = walk->page;
blkcipher_map_src(walk);
memcpy(tmp, walk->src.virt.addr, walk->nbytes);
blkcipher_unmap_src(walk);
walk->src.virt.addr = tmp;
walk->dst.virt.addr = tmp;
return 0;
}
static inline int blkcipher_next_fast(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
unsigned long diff;
walk->src.phys.page = scatterwalk_page(&walk->in);
walk->src.phys.offset = offset_in_page(walk->in.offset);
walk->dst.phys.page = scatterwalk_page(&walk->out);
walk->dst.phys.offset = offset_in_page(walk->out.offset);
if (walk->flags & BLKCIPHER_WALK_PHYS)
return 0;
diff = walk->src.phys.offset - walk->dst.phys.offset;
diff |= walk->src.virt.page - walk->dst.virt.page;
blkcipher_map_src(walk);
walk->dst.virt.addr = walk->src.virt.addr;
if (diff) {
walk->flags |= BLKCIPHER_WALK_DIFF;
blkcipher_map_dst(walk);
}
return 0;
}
static int blkcipher_walk_next(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct crypto_blkcipher *tfm = desc->tfm;
unsigned int alignmask = crypto_blkcipher_alignmask(tfm);
unsigned int bsize;
unsigned int n;
int err;
n = walk->total;
if (unlikely(n < crypto_blkcipher_blocksize(tfm))) {
desc->flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN;
return blkcipher_walk_done(desc, walk, -EINVAL);
}
walk->flags &= ~(BLKCIPHER_WALK_SLOW | BLKCIPHER_WALK_COPY |
BLKCIPHER_WALK_DIFF);
if (!scatterwalk_aligned(&walk->in, alignmask) ||
!scatterwalk_aligned(&walk->out, alignmask)) {
walk->flags |= BLKCIPHER_WALK_COPY;
if (!walk->page) {
walk->page = (void *)__get_free_page(GFP_ATOMIC);
if (!walk->page)
n = 0;
}
}
bsize = min(walk->blocksize, n);
n = scatterwalk_clamp(&walk->in, n);
n = scatterwalk_clamp(&walk->out, n);
if (unlikely(n < bsize)) {
err = blkcipher_next_slow(desc, walk, bsize, alignmask);
goto set_phys_lowmem;
}
walk->nbytes = n;
if (walk->flags & BLKCIPHER_WALK_COPY) {
err = blkcipher_next_copy(walk);
goto set_phys_lowmem;
}
return blkcipher_next_fast(desc, walk);
set_phys_lowmem:
if (walk->flags & BLKCIPHER_WALK_PHYS) {
walk->src.phys.page = virt_to_page(walk->src.virt.addr);
walk->dst.phys.page = virt_to_page(walk->dst.virt.addr);
walk->src.phys.offset &= PAGE_SIZE - 1;
walk->dst.phys.offset &= PAGE_SIZE - 1;
}
return err;
}
static inline int blkcipher_copy_iv(struct blkcipher_walk *walk,
struct crypto_blkcipher *tfm,
unsigned int alignmask)
{
unsigned bs = walk->blocksize;
unsigned int ivsize = crypto_blkcipher_ivsize(tfm);
unsigned aligned_bs = ALIGN(bs, alignmask + 1);
unsigned int size = aligned_bs * 2 + ivsize + max(aligned_bs, ivsize) -
(alignmask + 1);
u8 *iv;
size += alignmask & ~(crypto_tfm_ctx_alignment() - 1);
walk->buffer = kmalloc(size, GFP_ATOMIC);
if (!walk->buffer)
return -ENOMEM;
iv = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1);
iv = blkcipher_get_spot(iv, bs) + aligned_bs;
iv = blkcipher_get_spot(iv, bs) + aligned_bs;
iv = blkcipher_get_spot(iv, ivsize);
walk->iv = memcpy(iv, walk->iv, ivsize);
return 0;
}
int blkcipher_walk_virt(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
walk->flags &= ~BLKCIPHER_WALK_PHYS;
walk->blocksize = crypto_blkcipher_blocksize(desc->tfm);
return blkcipher_walk_first(desc, walk);
}
EXPORT_SYMBOL_GPL(blkcipher_walk_virt);
int blkcipher_walk_phys(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
walk->flags |= BLKCIPHER_WALK_PHYS;
walk->blocksize = crypto_blkcipher_blocksize(desc->tfm);
return blkcipher_walk_first(desc, walk);
}
EXPORT_SYMBOL_GPL(blkcipher_walk_phys);
static int blkcipher_walk_first(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct crypto_blkcipher *tfm = desc->tfm;
unsigned int alignmask = crypto_blkcipher_alignmask(tfm);
if (WARN_ON_ONCE(in_irq()))
return -EDEADLK;
walk->nbytes = walk->total;
if (unlikely(!walk->total))
return 0;
walk->buffer = NULL;
walk->iv = desc->info;
if (unlikely(((unsigned long)walk->iv & alignmask))) {
int err = blkcipher_copy_iv(walk, tfm, alignmask);
if (err)
return err;
}
scatterwalk_start(&walk->in, walk->in.sg);
scatterwalk_start(&walk->out, walk->out.sg);
walk->page = NULL;
return blkcipher_walk_next(desc, walk);
}
int blkcipher_walk_virt_block(struct blkcipher_desc *desc,
struct blkcipher_walk *walk,
unsigned int blocksize)
{
walk->flags &= ~BLKCIPHER_WALK_PHYS;
walk->blocksize = blocksize;
return blkcipher_walk_first(desc, walk);
}
EXPORT_SYMBOL_GPL(blkcipher_walk_virt_block);
static int setkey_unaligned(struct crypto_tfm *tfm, const u8 *key,
unsigned int keylen)
{
struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher;
unsigned long alignmask = crypto_tfm_alg_alignmask(tfm);
int ret;
u8 *buffer, *alignbuffer;
unsigned long absize;
absize = keylen + alignmask;
buffer = kmalloc(absize, GFP_ATOMIC);
if (!buffer)
return -ENOMEM;
alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1);
memcpy(alignbuffer, key, keylen);
ret = cipher->setkey(tfm, alignbuffer, keylen);
memset(alignbuffer, 0, keylen);
kfree(buffer);
return ret;
}
static int setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen)
{
struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher;
unsigned long alignmask = crypto_tfm_alg_alignmask(tfm);
if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) {
tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
if ((unsigned long)key & alignmask)
return setkey_unaligned(tfm, key, keylen);
return cipher->setkey(tfm, key, keylen);
}
static int async_setkey(struct crypto_ablkcipher *tfm, const u8 *key,
unsigned int keylen)
{
return setkey(crypto_ablkcipher_tfm(tfm), key, keylen);
}
static int async_encrypt(struct ablkcipher_request *req)
{
struct crypto_tfm *tfm = req->base.tfm;
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
struct blkcipher_desc desc = {
.tfm = __crypto_blkcipher_cast(tfm),
.info = req->info,
.flags = req->base.flags,
};
return alg->encrypt(&desc, req->dst, req->src, req->nbytes);
}
static int async_decrypt(struct ablkcipher_request *req)
{
struct crypto_tfm *tfm = req->base.tfm;
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
struct blkcipher_desc desc = {
.tfm = __crypto_blkcipher_cast(tfm),
.info = req->info,
.flags = req->base.flags,
};
return alg->decrypt(&desc, req->dst, req->src, req->nbytes);
}
static unsigned int crypto_blkcipher_ctxsize(struct crypto_alg *alg, u32 type,
u32 mask)
{
struct blkcipher_alg *cipher = &alg->cra_blkcipher;
unsigned int len = alg->cra_ctxsize;
if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK &&
cipher->ivsize) {
len = ALIGN(len, (unsigned long)alg->cra_alignmask + 1);
len += cipher->ivsize;
}
return len;
}
static int crypto_init_blkcipher_ops_async(struct crypto_tfm *tfm)
{
struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher;
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
crt->setkey = async_setkey;
crt->encrypt = async_encrypt;
crt->decrypt = async_decrypt;
if (!alg->ivsize) {
crt->givencrypt = skcipher_null_givencrypt;
crt->givdecrypt = skcipher_null_givdecrypt;
}
crt->base = __crypto_ablkcipher_cast(tfm);
crt->ivsize = alg->ivsize;
return 0;
}
static int crypto_init_blkcipher_ops_sync(struct crypto_tfm *tfm)
{
struct blkcipher_tfm *crt = &tfm->crt_blkcipher;
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
unsigned long align = crypto_tfm_alg_alignmask(tfm) + 1;
unsigned long addr;
crt->setkey = setkey;
crt->encrypt = alg->encrypt;
crt->decrypt = alg->decrypt;
addr = (unsigned long)crypto_tfm_ctx(tfm);
addr = ALIGN(addr, align);
addr += ALIGN(tfm->__crt_alg->cra_ctxsize, align);
crt->iv = (void *)addr;
return 0;
}
static int crypto_init_blkcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask)
{
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
if (alg->ivsize > PAGE_SIZE / 8)
return -EINVAL;
if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK)
return crypto_init_blkcipher_ops_sync(tfm);
else
return crypto_init_blkcipher_ops_async(tfm);
}
static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg)
__attribute__ ((unused));
static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg)
{
seq_printf(m, "type : blkcipher\n");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "min keysize : %u\n", alg->cra_blkcipher.min_keysize);
seq_printf(m, "max keysize : %u\n", alg->cra_blkcipher.max_keysize);
seq_printf(m, "ivsize : %u\n", alg->cra_blkcipher.ivsize);
seq_printf(m, "geniv : %s\n", alg->cra_blkcipher.geniv ?:
"<default>");
}
const struct crypto_type crypto_blkcipher_type = {
.ctxsize = crypto_blkcipher_ctxsize,
.init = crypto_init_blkcipher_ops,
#ifdef CONFIG_PROC_FS
.show = crypto_blkcipher_show,
#endif
};
EXPORT_SYMBOL_GPL(crypto_blkcipher_type);
static int crypto_grab_nivcipher(struct crypto_skcipher_spawn *spawn,
const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
int err;
type = crypto_skcipher_type(type);
mask = crypto_skcipher_mask(mask)| CRYPTO_ALG_GENIV;
alg = crypto_alg_mod_lookup(name, type, mask);
if (IS_ERR(alg))
return PTR_ERR(alg);
err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask);
crypto_mod_put(alg);
return err;
}
struct crypto_instance *skcipher_geniv_alloc(struct crypto_template *tmpl,
struct rtattr **tb, u32 type,
u32 mask)
{
struct {
int (*setkey)(struct crypto_ablkcipher *tfm, const u8 *key,
unsigned int keylen);
int (*encrypt)(struct ablkcipher_request *req);
int (*decrypt)(struct ablkcipher_request *req);
unsigned int min_keysize;
unsigned int max_keysize;
unsigned int ivsize;
const char *geniv;
} balg;
const char *name;
struct crypto_skcipher_spawn *spawn;
struct crypto_attr_type *algt;
struct crypto_instance *inst;
struct crypto_alg *alg;
int err;
algt = crypto_get_attr_type(tb);
err = PTR_ERR(algt);
if (IS_ERR(algt))
return ERR_PTR(err);
if ((algt->type ^ (CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV)) &
algt->mask)
return ERR_PTR(-EINVAL);
name = crypto_attr_alg_name(tb[1]);
err = PTR_ERR(name);
if (IS_ERR(name))
return ERR_PTR(err);
inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL);
if (!inst)
return ERR_PTR(-ENOMEM);
spawn = crypto_instance_ctx(inst);
/* Ignore async algorithms if necessary. */
mask |= crypto_requires_sync(algt->type, algt->mask);
crypto_set_skcipher_spawn(spawn, inst);
err = crypto_grab_nivcipher(spawn, name, type, mask);
if (err)
goto err_free_inst;
alg = crypto_skcipher_spawn_alg(spawn);
if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) ==
CRYPTO_ALG_TYPE_BLKCIPHER) {
balg.ivsize = alg->cra_blkcipher.ivsize;
balg.min_keysize = alg->cra_blkcipher.min_keysize;
balg.max_keysize = alg->cra_blkcipher.max_keysize;
balg.setkey = async_setkey;
balg.encrypt = async_encrypt;
balg.decrypt = async_decrypt;
balg.geniv = alg->cra_blkcipher.geniv;
} else {
balg.ivsize = alg->cra_ablkcipher.ivsize;
balg.min_keysize = alg->cra_ablkcipher.min_keysize;
balg.max_keysize = alg->cra_ablkcipher.max_keysize;
balg.setkey = alg->cra_ablkcipher.setkey;
balg.encrypt = alg->cra_ablkcipher.encrypt;
balg.decrypt = alg->cra_ablkcipher.decrypt;
balg.geniv = alg->cra_ablkcipher.geniv;
}
err = -EINVAL;
if (!balg.ivsize)
goto err_drop_alg;
/*
* This is only true if we're constructing an algorithm with its
* default IV generator. For the default generator we elide the
* template name and double-check the IV generator.
*/
if (algt->mask & CRYPTO_ALG_GENIV) {
if (!balg.geniv)
balg.geniv = crypto_default_geniv(alg);
err = -EAGAIN;
if (strcmp(tmpl->name, balg.geniv))
goto err_drop_alg;
memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME);
memcpy(inst->alg.cra_driver_name, alg->cra_driver_name,
CRYPTO_MAX_ALG_NAME);
} else {
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME,
"%s(%s)", tmpl->name, alg->cra_name) >=
CRYPTO_MAX_ALG_NAME)
goto err_drop_alg;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"%s(%s)", tmpl->name, alg->cra_driver_name) >=
CRYPTO_MAX_ALG_NAME)
goto err_drop_alg;
}
inst->alg.cra_flags = CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV;
inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC;
inst->alg.cra_priority = alg->cra_priority;
inst->alg.cra_blocksize = alg->cra_blocksize;
inst->alg.cra_alignmask = alg->cra_alignmask;
inst->alg.cra_type = &crypto_givcipher_type;
inst->alg.cra_ablkcipher.ivsize = balg.ivsize;
inst->alg.cra_ablkcipher.min_keysize = balg.min_keysize;
inst->alg.cra_ablkcipher.max_keysize = balg.max_keysize;
inst->alg.cra_ablkcipher.geniv = balg.geniv;
inst->alg.cra_ablkcipher.setkey = balg.setkey;
inst->alg.cra_ablkcipher.encrypt = balg.encrypt;
inst->alg.cra_ablkcipher.decrypt = balg.decrypt;
out:
return inst;
err_drop_alg:
crypto_drop_skcipher(spawn);
err_free_inst:
kfree(inst);
inst = ERR_PTR(err);
goto out;
}
EXPORT_SYMBOL_GPL(skcipher_geniv_alloc);
void skcipher_geniv_free(struct crypto_instance *inst)
{
crypto_drop_skcipher(crypto_instance_ctx(inst));
kfree(inst);
}
EXPORT_SYMBOL_GPL(skcipher_geniv_free);
int skcipher_geniv_init(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_ablkcipher *cipher;
cipher = crypto_spawn_skcipher(crypto_instance_ctx(inst));
if (IS_ERR(cipher))
return PTR_ERR(cipher);
tfm->crt_ablkcipher.base = cipher;
tfm->crt_ablkcipher.reqsize += crypto_ablkcipher_reqsize(cipher);
return 0;
}
EXPORT_SYMBOL_GPL(skcipher_geniv_init);
void skcipher_geniv_exit(struct crypto_tfm *tfm)
{
crypto_free_ablkcipher(tfm->crt_ablkcipher.base);
}
EXPORT_SYMBOL_GPL(skcipher_geniv_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Generic block chaining cipher type");
| gpl-2.0 |
sssemil/kernel_sniper-ICS | fs/ocfs2/stack_o2cb.c | 3121 | 10138 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* stack_o2cb.c
*
* Code which interfaces ocfs2 with the o2cb stack.
*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/crc32.h>
#include <linux/slab.h>
#include <linux/module.h>
/* Needed for AOP_TRUNCATED_PAGE in mlog_errno() */
#include <linux/fs.h>
#include "cluster/masklog.h"
#include "cluster/nodemanager.h"
#include "cluster/heartbeat.h"
#include "stackglue.h"
struct o2dlm_private {
struct dlm_eviction_cb op_eviction_cb;
};
static struct ocfs2_stack_plugin o2cb_stack;
/* These should be identical */
#if (DLM_LOCK_IV != LKM_IVMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_NL != LKM_NLMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_CR != LKM_CRMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_CW != LKM_CWMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_PR != LKM_PRMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_PW != LKM_PWMODE)
# error Lock modes do not match
#endif
#if (DLM_LOCK_EX != LKM_EXMODE)
# error Lock modes do not match
#endif
static inline int mode_to_o2dlm(int mode)
{
BUG_ON(mode > LKM_MAXMODE);
return mode;
}
#define map_flag(_generic, _o2dlm) \
if (flags & (_generic)) { \
flags &= ~(_generic); \
o2dlm_flags |= (_o2dlm); \
}
static int flags_to_o2dlm(u32 flags)
{
int o2dlm_flags = 0;
map_flag(DLM_LKF_NOQUEUE, LKM_NOQUEUE);
map_flag(DLM_LKF_CANCEL, LKM_CANCEL);
map_flag(DLM_LKF_CONVERT, LKM_CONVERT);
map_flag(DLM_LKF_VALBLK, LKM_VALBLK);
map_flag(DLM_LKF_IVVALBLK, LKM_INVVALBLK);
map_flag(DLM_LKF_ORPHAN, LKM_ORPHAN);
map_flag(DLM_LKF_FORCEUNLOCK, LKM_FORCE);
map_flag(DLM_LKF_TIMEOUT, LKM_TIMEOUT);
map_flag(DLM_LKF_LOCAL, LKM_LOCAL);
/* map_flag() should have cleared every flag passed in */
BUG_ON(flags != 0);
return o2dlm_flags;
}
#undef map_flag
/*
* Map an o2dlm status to standard errno values.
*
* o2dlm only uses a handful of these, and returns even fewer to the
* caller. Still, we try to assign sane values to each error.
*
* The following value pairs have special meanings to dlmglue, thus
* the right hand side needs to stay unique - never duplicate the
* mapping elsewhere in the table!
*
* DLM_NORMAL: 0
* DLM_NOTQUEUED: -EAGAIN
* DLM_CANCELGRANT: -EBUSY
* DLM_CANCEL: -DLM_ECANCEL
*/
/* Keep in sync with dlmapi.h */
static int status_map[] = {
[DLM_NORMAL] = 0, /* Success */
[DLM_GRANTED] = -EINVAL,
[DLM_DENIED] = -EACCES,
[DLM_DENIED_NOLOCKS] = -EACCES,
[DLM_WORKING] = -EACCES,
[DLM_BLOCKED] = -EINVAL,
[DLM_BLOCKED_ORPHAN] = -EINVAL,
[DLM_DENIED_GRACE_PERIOD] = -EACCES,
[DLM_SYSERR] = -ENOMEM, /* It is what it is */
[DLM_NOSUPPORT] = -EPROTO,
[DLM_CANCELGRANT] = -EBUSY, /* Cancel after grant */
[DLM_IVLOCKID] = -EINVAL,
[DLM_SYNC] = -EINVAL,
[DLM_BADTYPE] = -EINVAL,
[DLM_BADRESOURCE] = -EINVAL,
[DLM_MAXHANDLES] = -ENOMEM,
[DLM_NOCLINFO] = -EINVAL,
[DLM_NOLOCKMGR] = -EINVAL,
[DLM_NOPURGED] = -EINVAL,
[DLM_BADARGS] = -EINVAL,
[DLM_VOID] = -EINVAL,
[DLM_NOTQUEUED] = -EAGAIN, /* Trylock failed */
[DLM_IVBUFLEN] = -EINVAL,
[DLM_CVTUNGRANT] = -EPERM,
[DLM_BADPARAM] = -EINVAL,
[DLM_VALNOTVALID] = -EINVAL,
[DLM_REJECTED] = -EPERM,
[DLM_ABORT] = -EINVAL,
[DLM_CANCEL] = -DLM_ECANCEL, /* Successful cancel */
[DLM_IVRESHANDLE] = -EINVAL,
[DLM_DEADLOCK] = -EDEADLK,
[DLM_DENIED_NOASTS] = -EINVAL,
[DLM_FORWARD] = -EINVAL,
[DLM_TIMEOUT] = -ETIMEDOUT,
[DLM_IVGROUPID] = -EINVAL,
[DLM_VERS_CONFLICT] = -EOPNOTSUPP,
[DLM_BAD_DEVICE_PATH] = -ENOENT,
[DLM_NO_DEVICE_PERMISSION] = -EPERM,
[DLM_NO_CONTROL_DEVICE] = -ENOENT,
[DLM_RECOVERING] = -ENOTCONN,
[DLM_MIGRATING] = -ERESTART,
[DLM_MAXSTATS] = -EINVAL,
};
static int dlm_status_to_errno(enum dlm_status status)
{
BUG_ON(status < 0 || status >= ARRAY_SIZE(status_map));
return status_map[status];
}
static void o2dlm_lock_ast_wrapper(void *astarg)
{
struct ocfs2_dlm_lksb *lksb = astarg;
lksb->lksb_conn->cc_proto->lp_lock_ast(lksb);
}
static void o2dlm_blocking_ast_wrapper(void *astarg, int level)
{
struct ocfs2_dlm_lksb *lksb = astarg;
lksb->lksb_conn->cc_proto->lp_blocking_ast(lksb, level);
}
static void o2dlm_unlock_ast_wrapper(void *astarg, enum dlm_status status)
{
struct ocfs2_dlm_lksb *lksb = astarg;
int error = dlm_status_to_errno(status);
/*
* In o2dlm, you can get both the lock_ast() for the lock being
* granted and the unlock_ast() for the CANCEL failing. A
* successful cancel sends DLM_NORMAL here. If the
* lock grant happened before the cancel arrived, you get
* DLM_CANCELGRANT.
*
* There's no need for the double-ast. If we see DLM_CANCELGRANT,
* we just ignore it. We expect the lock_ast() to handle the
* granted lock.
*/
if (status == DLM_CANCELGRANT)
return;
lksb->lksb_conn->cc_proto->lp_unlock_ast(lksb, error);
}
static int o2cb_dlm_lock(struct ocfs2_cluster_connection *conn,
int mode,
struct ocfs2_dlm_lksb *lksb,
u32 flags,
void *name,
unsigned int namelen)
{
enum dlm_status status;
int o2dlm_mode = mode_to_o2dlm(mode);
int o2dlm_flags = flags_to_o2dlm(flags);
int ret;
status = dlmlock(conn->cc_lockspace, o2dlm_mode, &lksb->lksb_o2dlm,
o2dlm_flags, name, namelen,
o2dlm_lock_ast_wrapper, lksb,
o2dlm_blocking_ast_wrapper);
ret = dlm_status_to_errno(status);
return ret;
}
static int o2cb_dlm_unlock(struct ocfs2_cluster_connection *conn,
struct ocfs2_dlm_lksb *lksb,
u32 flags)
{
enum dlm_status status;
int o2dlm_flags = flags_to_o2dlm(flags);
int ret;
status = dlmunlock(conn->cc_lockspace, &lksb->lksb_o2dlm,
o2dlm_flags, o2dlm_unlock_ast_wrapper, lksb);
ret = dlm_status_to_errno(status);
return ret;
}
static int o2cb_dlm_lock_status(struct ocfs2_dlm_lksb *lksb)
{
return dlm_status_to_errno(lksb->lksb_o2dlm.status);
}
/*
* o2dlm aways has a "valid" LVB. If the dlm loses track of the LVB
* contents, it will zero out the LVB. Thus the caller can always trust
* the contents.
*/
static int o2cb_dlm_lvb_valid(struct ocfs2_dlm_lksb *lksb)
{
return 1;
}
static void *o2cb_dlm_lvb(struct ocfs2_dlm_lksb *lksb)
{
return (void *)(lksb->lksb_o2dlm.lvb);
}
static void o2cb_dump_lksb(struct ocfs2_dlm_lksb *lksb)
{
dlm_print_one_lock(lksb->lksb_o2dlm.lockid);
}
/*
* Called from the dlm when it's about to evict a node. This is how the
* classic stack signals node death.
*/
static void o2dlm_eviction_cb(int node_num, void *data)
{
struct ocfs2_cluster_connection *conn = data;
mlog(ML_NOTICE, "o2dlm has evicted node %d from group %.*s\n",
node_num, conn->cc_namelen, conn->cc_name);
conn->cc_recovery_handler(node_num, conn->cc_recovery_data);
}
static int o2cb_cluster_connect(struct ocfs2_cluster_connection *conn)
{
int rc = 0;
u32 dlm_key;
struct dlm_ctxt *dlm;
struct o2dlm_private *priv;
struct dlm_protocol_version fs_version;
BUG_ON(conn == NULL);
BUG_ON(conn->cc_proto == NULL);
/* for now we only have one cluster/node, make sure we see it
* in the heartbeat universe */
if (!o2hb_check_local_node_heartbeating()) {
if (o2hb_global_heartbeat_active())
mlog(ML_ERROR, "Global heartbeat not started\n");
rc = -EINVAL;
goto out;
}
priv = kzalloc(sizeof(struct o2dlm_private), GFP_KERNEL);
if (!priv) {
rc = -ENOMEM;
goto out_free;
}
/* This just fills the structure in. It is safe to pass conn. */
dlm_setup_eviction_cb(&priv->op_eviction_cb, o2dlm_eviction_cb,
conn);
conn->cc_private = priv;
/* used by the dlm code to make message headers unique, each
* node in this domain must agree on this. */
dlm_key = crc32_le(0, conn->cc_name, conn->cc_namelen);
fs_version.pv_major = conn->cc_version.pv_major;
fs_version.pv_minor = conn->cc_version.pv_minor;
dlm = dlm_register_domain(conn->cc_name, dlm_key, &fs_version);
if (IS_ERR(dlm)) {
rc = PTR_ERR(dlm);
mlog_errno(rc);
goto out_free;
}
conn->cc_version.pv_major = fs_version.pv_major;
conn->cc_version.pv_minor = fs_version.pv_minor;
conn->cc_lockspace = dlm;
dlm_register_eviction_cb(dlm, &priv->op_eviction_cb);
out_free:
if (rc && conn->cc_private)
kfree(conn->cc_private);
out:
return rc;
}
static int o2cb_cluster_disconnect(struct ocfs2_cluster_connection *conn)
{
struct dlm_ctxt *dlm = conn->cc_lockspace;
struct o2dlm_private *priv = conn->cc_private;
dlm_unregister_eviction_cb(&priv->op_eviction_cb);
conn->cc_private = NULL;
kfree(priv);
dlm_unregister_domain(dlm);
conn->cc_lockspace = NULL;
return 0;
}
static int o2cb_cluster_this_node(unsigned int *node)
{
int node_num;
node_num = o2nm_this_node();
if (node_num == O2NM_INVALID_NODE_NUM)
return -ENOENT;
if (node_num >= O2NM_MAX_NODES)
return -EOVERFLOW;
*node = node_num;
return 0;
}
static struct ocfs2_stack_operations o2cb_stack_ops = {
.connect = o2cb_cluster_connect,
.disconnect = o2cb_cluster_disconnect,
.this_node = o2cb_cluster_this_node,
.dlm_lock = o2cb_dlm_lock,
.dlm_unlock = o2cb_dlm_unlock,
.lock_status = o2cb_dlm_lock_status,
.lvb_valid = o2cb_dlm_lvb_valid,
.lock_lvb = o2cb_dlm_lvb,
.dump_lksb = o2cb_dump_lksb,
};
static struct ocfs2_stack_plugin o2cb_stack = {
.sp_name = "o2cb",
.sp_ops = &o2cb_stack_ops,
.sp_owner = THIS_MODULE,
};
static int __init o2cb_stack_init(void)
{
return ocfs2_stack_glue_register(&o2cb_stack);
}
static void __exit o2cb_stack_exit(void)
{
ocfs2_stack_glue_unregister(&o2cb_stack);
}
MODULE_AUTHOR("Oracle");
MODULE_DESCRIPTION("ocfs2 driver for the classic o2cb stack");
MODULE_LICENSE("GPL");
module_init(o2cb_stack_init);
module_exit(o2cb_stack_exit);
| gpl-2.0 |
AOKP/kernel_oppo_find5 | arch/arm/mach-msm/clock-pcom.c | 3121 | 5171 | /*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2007-2011, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/err.h>
#include <mach/clk.h>
#include <mach/clk-provider.h>
#include <mach/socinfo.h>
#include <mach/proc_comm.h>
#include "clock.h"
#include "clock-pcom.h"
/*
* glue for the proc_comm interface
*/
static int pc_clk_enable(struct clk *clk)
{
int rc;
int id = to_pcom_clk(clk)->id;
/* Ignore clocks that are always on */
if (id == P_EBI1_CLK || id == P_EBI1_FIXED_CLK)
return 0;
rc = msm_proc_comm(PCOM_CLKCTL_RPC_ENABLE, &id, NULL);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static void pc_clk_disable(struct clk *clk)
{
int id = to_pcom_clk(clk)->id;
/* Ignore clocks that are always on */
if (id == P_EBI1_CLK || id == P_EBI1_FIXED_CLK)
return;
msm_proc_comm(PCOM_CLKCTL_RPC_DISABLE, &id, NULL);
}
int pc_clk_reset(unsigned id, enum clk_reset_action action)
{
int rc;
if (action == CLK_RESET_ASSERT)
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_ASSERT, &id, NULL);
else
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_DEASSERT, &id, NULL);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static int pc_reset(struct clk *clk, enum clk_reset_action action)
{
int id = to_pcom_clk(clk)->id;
return pc_clk_reset(id, action);
}
static int _pc_clk_set_rate(struct clk *clk, unsigned long rate)
{
/* The rate _might_ be rounded off to the nearest KHz value by the
* remote function. So a return value of 0 doesn't necessarily mean
* that the exact rate was set successfully.
*/
unsigned r = rate;
int id = to_pcom_clk(clk)->id;
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_RATE, &id, &r);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static int _pc_clk_set_min_rate(struct clk *clk, unsigned long rate)
{
int rc;
int id = to_pcom_clk(clk)->id;
bool ignore_error = (cpu_is_msm7x27() && id == P_EBI1_CLK &&
rate >= INT_MAX);
unsigned r = rate;
rc = msm_proc_comm(PCOM_CLKCTL_RPC_MIN_RATE, &id, &r);
if (rc < 0)
return rc;
else if (ignore_error)
return 0;
else
return (int)id < 0 ? -EINVAL : 0;
}
static int pc_clk_set_rate(struct clk *clk, unsigned long rate)
{
if (clk->flags & CLKFLAG_MIN)
return _pc_clk_set_min_rate(clk, rate);
else
return _pc_clk_set_rate(clk, rate);
}
static int pc_clk_set_max_rate(struct clk *clk, unsigned long rate)
{
int id = to_pcom_clk(clk)->id;
unsigned r = rate;
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_MAX_RATE, &id, &r);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static int pc_clk_set_flags(struct clk *clk, unsigned flags)
{
int id = to_pcom_clk(clk)->id;
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_FLAGS, &id, &flags);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static int pc_clk_set_ext_config(struct clk *clk, unsigned long config)
{
int id = to_pcom_clk(clk)->id;
unsigned c = config;
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_EXT_CONFIG, &id, &c);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
static unsigned long pc_clk_get_rate(struct clk *clk)
{
int id = to_pcom_clk(clk)->id;
if (msm_proc_comm(PCOM_CLKCTL_RPC_RATE, &id, NULL))
return 0;
else
return id;
}
static int pc_clk_is_enabled(struct clk *clk)
{
int id = to_pcom_clk(clk)->id;
if (msm_proc_comm(PCOM_CLKCTL_RPC_ENABLED, &id, NULL))
return 0;
else
return id;
}
static long pc_clk_round_rate(struct clk *clk, unsigned long rate)
{
/* Not really supported; pc_clk_set_rate() does rounding on it's own. */
return rate;
}
static bool pc_clk_is_local(struct clk *clk)
{
return false;
}
static enum handoff pc_clk_handoff(struct clk *clk)
{
/*
* Handoff clock state only since querying and caching the rate here
* would incur more overhead than it would ever save.
*/
if (pc_clk_is_enabled(clk))
return HANDOFF_ENABLED_CLK;
return HANDOFF_DISABLED_CLK;
}
struct clk_ops clk_ops_pcom = {
.enable = pc_clk_enable,
.disable = pc_clk_disable,
.reset = pc_reset,
.set_rate = pc_clk_set_rate,
.set_max_rate = pc_clk_set_max_rate,
.set_flags = pc_clk_set_flags,
.get_rate = pc_clk_get_rate,
.is_enabled = pc_clk_is_enabled,
.round_rate = pc_clk_round_rate,
.is_local = pc_clk_is_local,
.handoff = pc_clk_handoff,
};
struct clk_ops clk_ops_pcom_ext_config = {
.enable = pc_clk_enable,
.disable = pc_clk_disable,
.reset = pc_reset,
.set_rate = pc_clk_set_ext_config,
.set_max_rate = pc_clk_set_max_rate,
.set_flags = pc_clk_set_flags,
.get_rate = pc_clk_get_rate,
.is_enabled = pc_clk_is_enabled,
.round_rate = pc_clk_round_rate,
.is_local = pc_clk_is_local,
.handoff = pc_clk_handoff,
};
| gpl-2.0 |
Pafcholini/kernel-msm-3.10 | arch/tile/gxio/kiorpc.c | 4657 | 1768 | /*
* Copyright 2012 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*
* TILE-Gx IORPC support for kernel I/O drivers.
*/
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/io.h>
#include <gxio/iorpc_globals.h>
#include <gxio/kiorpc.h>
#ifdef DEBUG_IORPC
#define TRACE(FMT, ...) pr_info(SIMPLE_MSG_LINE FMT, ## __VA_ARGS__)
#else
#define TRACE(...)
#endif
/* Create kernel-VA-space MMIO mapping for an on-chip IO device. */
void __iomem *iorpc_ioremap(int hv_fd, resource_size_t offset,
unsigned long size)
{
pgprot_t mmio_base, prot = { 0 };
unsigned long pfn;
int err;
/* Look up the shim's lotar and base PA. */
err = __iorpc_get_mmio_base(hv_fd, &mmio_base);
if (err) {
TRACE("get_mmio_base() failure: %d\n", err);
return NULL;
}
/* Make sure the HV driver approves of our offset and size. */
err = __iorpc_check_mmio_offset(hv_fd, offset, size);
if (err) {
TRACE("check_mmio_offset() failure: %d\n", err);
return NULL;
}
/*
* mmio_base contains a base pfn and homing coordinates. Turn
* it into an MMIO pgprot and offset pfn.
*/
prot = hv_pte_set_lotar(prot, hv_pte_get_lotar(mmio_base));
pfn = pte_pfn(mmio_base) + PFN_DOWN(offset);
return ioremap_prot(PFN_PHYS(pfn), size, prot);
}
EXPORT_SYMBOL(iorpc_ioremap);
| gpl-2.0 |
Maxr1998/hellsCore-mako | drivers/staging/comedi/drivers/pcmad.c | 8241 | 4707 | /*
comedi/drivers/pcmad.c
Hardware driver for Winsystems PCM-A/D12 and PCM-A/D16
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000,2001 David A. Schleef <ds@schleef.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.
*/
/*
Driver: pcmad
Description: Winsystems PCM-A/D12, PCM-A/D16
Author: ds
Devices: [Winsystems] PCM-A/D12 (pcmad12), PCM-A/D16 (pcmad16)
Status: untested
This driver was written on a bet that I couldn't write a driver
in less than 2 hours. I won the bet, but never got paid. =(
Configuration options:
[0] - I/O port base
[1] - unused
[2] - Analog input reference
0 = single ended
1 = differential
[3] - Analog input encoding (must match jumpers)
0 = straight binary
1 = two's complement
*/
#include <linux/interrupt.h>
#include "../comedidev.h"
#include <linux/ioport.h>
#define PCMAD_SIZE 4
#define PCMAD_STATUS 0
#define PCMAD_LSB 1
#define PCMAD_MSB 2
#define PCMAD_CONVERT 1
struct pcmad_board_struct {
const char *name;
int n_ai_bits;
};
static const struct pcmad_board_struct pcmad_boards[] = {
{
.name = "pcmad12",
.n_ai_bits = 12,
},
{
.name = "pcmad16",
.n_ai_bits = 16,
},
};
#define this_board ((const struct pcmad_board_struct *)(dev->board_ptr))
#define n_pcmad_boards ARRAY_SIZE(pcmad_boards)
struct pcmad_priv_struct {
int differential;
int twos_comp;
};
#define devpriv ((struct pcmad_priv_struct *)dev->private)
static int pcmad_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int pcmad_detach(struct comedi_device *dev);
static struct comedi_driver driver_pcmad = {
.driver_name = "pcmad",
.module = THIS_MODULE,
.attach = pcmad_attach,
.detach = pcmad_detach,
.board_name = &pcmad_boards[0].name,
.num_names = n_pcmad_boards,
.offset = sizeof(pcmad_boards[0]),
};
static int __init driver_pcmad_init_module(void)
{
return comedi_driver_register(&driver_pcmad);
}
static void __exit driver_pcmad_cleanup_module(void)
{
comedi_driver_unregister(&driver_pcmad);
}
module_init(driver_pcmad_init_module);
module_exit(driver_pcmad_cleanup_module);
#define TIMEOUT 100
static int pcmad_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan;
int n;
chan = CR_CHAN(insn->chanspec);
for (n = 0; n < insn->n; n++) {
outb(chan, dev->iobase + PCMAD_CONVERT);
for (i = 0; i < TIMEOUT; i++) {
if ((inb(dev->iobase + PCMAD_STATUS) & 0x3) == 0x3)
break;
}
data[n] = inb(dev->iobase + PCMAD_LSB);
data[n] |= (inb(dev->iobase + PCMAD_MSB) << 8);
if (devpriv->twos_comp)
data[n] ^= (1 << (this_board->n_ai_bits - 1));
}
return n;
}
/*
* options:
* 0 i/o base
* 1 unused
* 2 0=single ended 1=differential
* 3 0=straight binary 1=two's comp
*/
static int pcmad_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
int ret;
struct comedi_subdevice *s;
unsigned long iobase;
iobase = it->options[0];
printk(KERN_INFO "comedi%d: pcmad: 0x%04lx ", dev->minor, iobase);
if (!request_region(iobase, PCMAD_SIZE, "pcmad")) {
printk(KERN_CONT "I/O port conflict\n");
return -EIO;
}
printk(KERN_CONT "\n");
dev->iobase = iobase;
ret = alloc_subdevices(dev, 1);
if (ret < 0)
return ret;
ret = alloc_private(dev, sizeof(struct pcmad_priv_struct));
if (ret < 0)
return ret;
dev->board_name = this_board->name;
s = dev->subdevices + 0;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | AREF_GROUND;
s->n_chan = 16; /* XXX */
s->len_chanlist = 1;
s->insn_read = pcmad_ai_insn_read;
s->maxdata = (1 << this_board->n_ai_bits) - 1;
s->range_table = &range_unknown;
return 0;
}
static int pcmad_detach(struct comedi_device *dev)
{
printk(KERN_INFO "comedi%d: pcmad: remove\n", dev->minor);
if (dev->irq)
free_irq(dev->irq, dev);
if (dev->iobase)
release_region(dev->iobase, PCMAD_SIZE);
return 0;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mythos234/cmkernel_zeroltexx | drivers/infiniband/hw/amso1100/c2_cm.c | 11569 | 10009 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, 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/slab.h>
#include "c2.h"
#include "c2_wr.h"
#include "c2_vq.h"
#include <rdma/iw_cm.h>
int c2_llp_connect(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
struct c2_dev *c2dev = to_c2dev(cm_id->device);
struct ib_qp *ibqp;
struct c2_qp *qp;
struct c2wr_qp_connect_req *wr; /* variable size needs a malloc. */
struct c2_vq_req *vq_req;
int err;
ibqp = c2_get_qp(cm_id->device, iw_param->qpn);
if (!ibqp)
return -EINVAL;
qp = to_c2qp(ibqp);
/* Associate QP <--> CM_ID */
cm_id->provider_data = qp;
cm_id->add_ref(cm_id);
qp->cm_id = cm_id;
/*
* only support the max private_data length
*/
if (iw_param->private_data_len > C2_MAX_PRIVATE_DATA_SIZE) {
err = -EINVAL;
goto bail0;
}
/*
* Set the rdma read limits
*/
err = c2_qp_set_read_limits(c2dev, qp, iw_param->ord, iw_param->ird);
if (err)
goto bail0;
/*
* Create and send a WR_QP_CONNECT...
*/
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
vq_req = vq_req_alloc(c2dev);
if (!vq_req) {
err = -ENOMEM;
goto bail1;
}
c2_wr_set_id(wr, CCWR_QP_CONNECT);
wr->hdr.context = 0;
wr->rnic_handle = c2dev->adapter_handle;
wr->qp_handle = qp->adapter_handle;
wr->remote_addr = cm_id->remote_addr.sin_addr.s_addr;
wr->remote_port = cm_id->remote_addr.sin_port;
/*
* Move any private data from the callers's buf into
* the WR.
*/
if (iw_param->private_data) {
wr->private_data_length =
cpu_to_be32(iw_param->private_data_len);
memcpy(&wr->private_data[0], iw_param->private_data,
iw_param->private_data_len);
} else
wr->private_data_length = 0;
/*
* Send WR to adapter. NOTE: There is no synch reply from
* the adapter.
*/
err = vq_send_wr(c2dev, (union c2wr *) wr);
vq_req_free(c2dev, vq_req);
bail1:
kfree(wr);
bail0:
if (err) {
/*
* If we fail, release reference on QP and
* disassociate QP from CM_ID
*/
cm_id->provider_data = NULL;
qp->cm_id = NULL;
cm_id->rem_ref(cm_id);
}
return err;
}
int c2_llp_service_create(struct iw_cm_id *cm_id, int backlog)
{
struct c2_dev *c2dev;
struct c2wr_ep_listen_create_req wr;
struct c2wr_ep_listen_create_rep *reply;
struct c2_vq_req *vq_req;
int err;
c2dev = to_c2dev(cm_id->device);
if (c2dev == NULL)
return -EINVAL;
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_EP_LISTEN_CREATE);
wr.hdr.context = (u64) (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.local_addr = cm_id->local_addr.sin_addr.s_addr;
wr.local_port = cm_id->local_addr.sin_port;
wr.backlog = cpu_to_be32(backlog);
wr.user_context = (u64) (unsigned long) cm_id;
/*
* Reference the request struct. Dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply =
(struct c2wr_ep_listen_create_rep *) (unsigned long) vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail1;
}
if ((err = c2_errno(reply)) != 0)
goto bail1;
/*
* Keep the adapter handle. Used in subsequent destroy
*/
cm_id->provider_data = (void*)(unsigned long) reply->ep_handle;
/*
* free vq stuff
*/
vq_repbuf_free(c2dev, reply);
vq_req_free(c2dev, vq_req);
return 0;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
int c2_llp_service_destroy(struct iw_cm_id *cm_id)
{
struct c2_dev *c2dev;
struct c2wr_ep_listen_destroy_req wr;
struct c2wr_ep_listen_destroy_rep *reply;
struct c2_vq_req *vq_req;
int err;
c2dev = to_c2dev(cm_id->device);
if (c2dev == NULL)
return -EINVAL;
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_EP_LISTEN_DESTROY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.ep_handle = (u32)(unsigned long)cm_id->provider_data;
/*
* reference the request struct. dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply=(struct c2wr_ep_listen_destroy_rep *)(unsigned long)vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0)
goto bail1;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
int c2_llp_accept(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
struct c2_dev *c2dev = to_c2dev(cm_id->device);
struct c2_qp *qp;
struct ib_qp *ibqp;
struct c2wr_cr_accept_req *wr; /* variable length WR */
struct c2_vq_req *vq_req;
struct c2wr_cr_accept_rep *reply; /* VQ Reply msg ptr. */
int err;
ibqp = c2_get_qp(cm_id->device, iw_param->qpn);
if (!ibqp)
return -EINVAL;
qp = to_c2qp(ibqp);
/* Set the RDMA read limits */
err = c2_qp_set_read_limits(c2dev, qp, iw_param->ord, iw_param->ird);
if (err)
goto bail0;
/* Allocate verbs request. */
vq_req = vq_req_alloc(c2dev);
if (!vq_req) {
err = -ENOMEM;
goto bail0;
}
vq_req->qp = qp;
vq_req->cm_id = cm_id;
vq_req->event = IW_CM_EVENT_ESTABLISHED;
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail1;
}
/* Build the WR */
c2_wr_set_id(wr, CCWR_CR_ACCEPT);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->ep_handle = (u32) (unsigned long) cm_id->provider_data;
wr->qp_handle = qp->adapter_handle;
/* Replace the cr_handle with the QP after accept */
cm_id->provider_data = qp;
cm_id->add_ref(cm_id);
qp->cm_id = cm_id;
cm_id->provider_data = qp;
/* Validate private_data length */
if (iw_param->private_data_len > C2_MAX_PRIVATE_DATA_SIZE) {
err = -EINVAL;
goto bail1;
}
if (iw_param->private_data) {
wr->private_data_length = cpu_to_be32(iw_param->private_data_len);
memcpy(&wr->private_data[0],
iw_param->private_data, iw_param->private_data_len);
} else
wr->private_data_length = 0;
/* Reference the request struct. Dereferenced in the int handler. */
vq_req_get(c2dev, vq_req);
/* Send WR to adapter */
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
/* Wait for reply from adapter */
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
/* Check that reply is present */
reply = (struct c2wr_cr_accept_rep *) (unsigned long) vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
if (!err)
c2_set_qp_state(qp, C2_QP_STATE_RTS);
bail1:
kfree(wr);
vq_req_free(c2dev, vq_req);
bail0:
if (err) {
/*
* If we fail, release reference on QP and
* disassociate QP from CM_ID
*/
cm_id->provider_data = NULL;
qp->cm_id = NULL;
cm_id->rem_ref(cm_id);
}
return err;
}
int c2_llp_reject(struct iw_cm_id *cm_id, const void *pdata, u8 pdata_len)
{
struct c2_dev *c2dev;
struct c2wr_cr_reject_req wr;
struct c2_vq_req *vq_req;
struct c2wr_cr_reject_rep *reply;
int err;
c2dev = to_c2dev(cm_id->device);
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_CR_REJECT);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.ep_handle = (u32) (unsigned long) cm_id->provider_data;
/*
* reference the request struct. dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply = (struct c2wr_cr_reject_rep *) (unsigned long)
vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
err = c2_errno(reply);
/*
* free vq stuff
*/
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_A450CG | linux/kernel/arch/m32r/platforms/m32104ut/io.c | 13873 | 7447 | /*
* linux/arch/m32r/platforms/m32104ut/io.c
*
* Typical I/O routines for M32104UT board.
*
* Copyright (c) 2001-2005 Hiroyuki Kondo, Hirokazu Takata,
* Hitoshi Yamamoto, Mamoru Sakugawa,
* Naoto Sugai, Hayato Fujiwara
*/
#include <asm/m32r.h>
#include <asm/page.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#if defined(CONFIG_PCMCIA) && defined(CONFIG_M32R_CFC)
#include <linux/types.h>
#define M32R_PCC_IOMAP_SIZE 0x1000
#define M32R_PCC_IOSTART0 0x1000
#define M32R_PCC_IOEND0 (M32R_PCC_IOSTART0 + M32R_PCC_IOMAP_SIZE - 1)
extern void pcc_ioread_byte(int, unsigned long, void *, size_t, size_t, int);
extern void pcc_ioread_word(int, unsigned long, void *, size_t, size_t, int);
extern void pcc_iowrite_byte(int, unsigned long, void *, size_t, size_t, int);
extern void pcc_iowrite_word(int, unsigned long, void *, size_t, size_t, int);
#endif /* CONFIG_PCMCIA && CONFIG_M32R_CFC */
#define PORT2ADDR(port) _port2addr(port)
static inline void *_port2addr(unsigned long port)
{
return (void *)(port | NONCACHE_OFFSET);
}
#if defined(CONFIG_IDE) && !defined(CONFIG_M32R_CFC)
static inline void *__port2addr_ata(unsigned long port)
{
static int dummy_reg;
switch (port) {
case 0x1f0: return (void *)(0x0c002000 | NONCACHE_OFFSET);
case 0x1f1: return (void *)(0x0c012800 | NONCACHE_OFFSET);
case 0x1f2: return (void *)(0x0c012002 | NONCACHE_OFFSET);
case 0x1f3: return (void *)(0x0c012802 | NONCACHE_OFFSET);
case 0x1f4: return (void *)(0x0c012004 | NONCACHE_OFFSET);
case 0x1f5: return (void *)(0x0c012804 | NONCACHE_OFFSET);
case 0x1f6: return (void *)(0x0c012006 | NONCACHE_OFFSET);
case 0x1f7: return (void *)(0x0c012806 | NONCACHE_OFFSET);
case 0x3f6: return (void *)(0x0c01200e | NONCACHE_OFFSET);
default: return (void *)&dummy_reg;
}
}
#endif
/*
* M32104T-LAN is located in the extended bus space
* from 0x01000000 to 0x01ffffff on physical address.
* The base address of LAN controller(LAN91C111) is 0x300.
*/
#define LAN_IOSTART (0x300 | NONCACHE_OFFSET)
#define LAN_IOEND (0x320 | NONCACHE_OFFSET)
static inline void *_port2addr_ne(unsigned long port)
{
return (void *)(port + NONCACHE_OFFSET + 0x01000000);
}
static inline void delay(void)
{
__asm__ __volatile__ ("push r0; \n\t pop r0;" : : :"memory");
}
/*
* NIC I/O function
*/
#define PORT2ADDR_NE(port) _port2addr_ne(port)
static inline unsigned char _ne_inb(void *portp)
{
return *(volatile unsigned char *)portp;
}
static inline unsigned short _ne_inw(void *portp)
{
return (unsigned short)le16_to_cpu(*(volatile unsigned short *)portp);
}
static inline void _ne_insb(void *portp, void *addr, unsigned long count)
{
unsigned char *buf = (unsigned char *)addr;
while (count--)
*buf++ = _ne_inb(portp);
}
static inline void _ne_outb(unsigned char b, void *portp)
{
*(volatile unsigned char *)portp = b;
}
static inline void _ne_outw(unsigned short w, void *portp)
{
*(volatile unsigned short *)portp = cpu_to_le16(w);
}
unsigned char _inb(unsigned long port)
{
if (port >= LAN_IOSTART && port < LAN_IOEND)
return _ne_inb(PORT2ADDR_NE(port));
return *(volatile unsigned char *)PORT2ADDR(port);
}
unsigned short _inw(unsigned long port)
{
if (port >= LAN_IOSTART && port < LAN_IOEND)
return _ne_inw(PORT2ADDR_NE(port));
return *(volatile unsigned short *)PORT2ADDR(port);
}
unsigned long _inl(unsigned long port)
{
return *(volatile unsigned long *)PORT2ADDR(port);
}
unsigned char _inb_p(unsigned long port)
{
unsigned char v = _inb(port);
delay();
return (v);
}
unsigned short _inw_p(unsigned long port)
{
unsigned short v = _inw(port);
delay();
return (v);
}
unsigned long _inl_p(unsigned long port)
{
unsigned long v = _inl(port);
delay();
return (v);
}
void _outb(unsigned char b, unsigned long port)
{
if (port >= LAN_IOSTART && port < LAN_IOEND)
_ne_outb(b, PORT2ADDR_NE(port));
else
*(volatile unsigned char *)PORT2ADDR(port) = b;
}
void _outw(unsigned short w, unsigned long port)
{
if (port >= LAN_IOSTART && port < LAN_IOEND)
_ne_outw(w, PORT2ADDR_NE(port));
else
*(volatile unsigned short *)PORT2ADDR(port) = w;
}
void _outl(unsigned long l, unsigned long port)
{
*(volatile unsigned long *)PORT2ADDR(port) = l;
}
void _outb_p(unsigned char b, unsigned long port)
{
_outb(b, port);
delay();
}
void _outw_p(unsigned short w, unsigned long port)
{
_outw(w, port);
delay();
}
void _outl_p(unsigned long l, unsigned long port)
{
_outl(l, port);
delay();
}
void _insb(unsigned int port, void *addr, unsigned long count)
{
if (port >= LAN_IOSTART && port < LAN_IOEND)
_ne_insb(PORT2ADDR_NE(port), addr, count);
else {
unsigned char *buf = addr;
unsigned char *portp = PORT2ADDR(port);
while (count--)
*buf++ = *(volatile unsigned char *)portp;
}
}
void _insw(unsigned int port, void *addr, unsigned long count)
{
unsigned short *buf = addr;
unsigned short *portp;
if (port >= LAN_IOSTART && port < LAN_IOEND) {
/*
* This portion is only used by smc91111.c to read data
* from the DATA_REG. Do not swap the data.
*/
portp = PORT2ADDR_NE(port);
while (count--)
*buf++ = *(volatile unsigned short *)portp;
#if defined(CONFIG_PCMCIA) && defined(CONFIG_M32R_CFC)
} else if (port >= M32R_PCC_IOSTART0 && port <= M32R_PCC_IOEND0) {
pcc_ioread_word(9, port, (void *)addr, sizeof(unsigned short),
count, 1);
#endif
#if defined(CONFIG_IDE) && !defined(CONFIG_M32R_CFC)
} else if ((port >= 0x1f0 && port <=0x1f7) || port == 0x3f6) {
portp = __port2addr_ata(port);
while (count--)
*buf++ = *(volatile unsigned short *)portp;
#endif
} else {
portp = PORT2ADDR(port);
while (count--)
*buf++ = *(volatile unsigned short *)portp;
}
}
void _insl(unsigned int port, void *addr, unsigned long count)
{
unsigned long *buf = addr;
unsigned long *portp;
portp = PORT2ADDR(port);
while (count--)
*buf++ = *(volatile unsigned long *)portp;
}
void _outsb(unsigned int port, const void *addr, unsigned long count)
{
const unsigned char *buf = addr;
unsigned char *portp;
if (port >= LAN_IOSTART && port < LAN_IOEND) {
portp = PORT2ADDR_NE(port);
while (count--)
_ne_outb(*buf++, portp);
} else {
portp = PORT2ADDR(port);
while (count--)
*(volatile unsigned char *)portp = *buf++;
}
}
void _outsw(unsigned int port, const void *addr, unsigned long count)
{
const unsigned short *buf = addr;
unsigned short *portp;
if (port >= LAN_IOSTART && port < LAN_IOEND) {
/*
* This portion is only used by smc91111.c to write data
* into the DATA_REG. Do not swap the data.
*/
portp = PORT2ADDR_NE(port);
while (count--)
*(volatile unsigned short *)portp = *buf++;
#if defined(CONFIG_IDE) && !defined(CONFIG_M32R_CFC)
} else if ((port >= 0x1f0 && port <=0x1f7) || port == 0x3f6) {
portp = __port2addr_ata(port);
while (count--)
*(volatile unsigned short *)portp = *buf++;
#endif
#if defined(CONFIG_PCMCIA) && defined(CONFIG_M32R_CFC)
} else if (port >= M32R_PCC_IOSTART0 && port <= M32R_PCC_IOEND0) {
pcc_iowrite_word(9, port, (void *)addr, sizeof(unsigned short),
count, 1);
#endif
} else {
portp = PORT2ADDR(port);
while (count--)
*(volatile unsigned short *)portp = *buf++;
}
}
void _outsl(unsigned int port, const void *addr, unsigned long count)
{
const unsigned long *buf = addr;
unsigned char *portp;
portp = PORT2ADDR(port);
while (count--)
*(volatile unsigned long *)portp = *buf++;
}
| gpl-2.0 |
javelinanddart/kernel_samsung_msm8660 | drivers/media/dvb/b2c2/flexcop-eeprom.c | 14385 | 3274 | /*
* Linux driver for digital TV devices equipped with B2C2 FlexcopII(b)/III
* flexcop-eeprom.c - eeprom access methods (currently only MAC address reading)
* see flexcop.c for copyright information
*/
#include "flexcop.h"
#if 0
/*EEPROM (Skystar2 has one "24LC08B" chip on board) */
static int eeprom_write(struct adapter *adapter, u16 addr, u8 *buf, u16 len)
{
return flex_i2c_write(adapter, 0x20000000, 0x50, addr, buf, len);
}
static int eeprom_lrc_write(struct adapter *adapter, u32 addr,
u32 len, u8 *wbuf, u8 *rbuf, int retries)
{
int i;
for (i = 0; i < retries; i++) {
if (eeprom_write(adapter, addr, wbuf, len) == len) {
if (eeprom_lrc_read(adapter, addr, len, rbuf, retries) == 1)
return 1;
}
}
return 0;
}
/* These functions could be used to unlock SkyStar2 cards. */
static int eeprom_writeKey(struct adapter *adapter, u8 *key, u32 len)
{
u8 rbuf[20];
u8 wbuf[20];
if (len != 16)
return 0;
memcpy(wbuf, key, len);
wbuf[16] = 0;
wbuf[17] = 0;
wbuf[18] = 0;
wbuf[19] = calc_lrc(wbuf, 19);
return eeprom_lrc_write(adapter, 0x3e4, 20, wbuf, rbuf, 4);
}
static int eeprom_readKey(struct adapter *adapter, u8 *key, u32 len)
{
u8 buf[20];
if (len != 16)
return 0;
if (eeprom_lrc_read(adapter, 0x3e4, 20, buf, 4) == 0)
return 0;
memcpy(key, buf, len);
return 1;
}
static char eeprom_set_mac_addr(struct adapter *adapter, char type, u8 *mac)
{
u8 tmp[8];
if (type != 0) {
tmp[0] = mac[0];
tmp[1] = mac[1];
tmp[2] = mac[2];
tmp[3] = mac[5];
tmp[4] = mac[6];
tmp[5] = mac[7];
} else {
tmp[0] = mac[0];
tmp[1] = mac[1];
tmp[2] = mac[2];
tmp[3] = mac[3];
tmp[4] = mac[4];
tmp[5] = mac[5];
}
tmp[6] = 0;
tmp[7] = calc_lrc(tmp, 7);
if (eeprom_write(adapter, 0x3f8, tmp, 8) == 8)
return 1;
return 0;
}
static int flexcop_eeprom_read(struct flexcop_device *fc,
u16 addr, u8 *buf, u16 len)
{
return fc->i2c_request(fc,FC_READ,FC_I2C_PORT_EEPROM,0x50,addr,buf,len);
}
#endif
static u8 calc_lrc(u8 *buf, int len)
{
int i;
u8 sum = 0;
for (i = 0; i < len; i++)
sum = sum ^ buf[i];
return sum;
}
static int flexcop_eeprom_request(struct flexcop_device *fc,
flexcop_access_op_t op, u16 addr, u8 *buf, u16 len, int retries)
{
int i,ret = 0;
u8 chipaddr = 0x50 | ((addr >> 8) & 3);
for (i = 0; i < retries; i++) {
ret = fc->i2c_request(&fc->fc_i2c_adap[1], op, chipaddr,
addr & 0xff, buf, len);
if (ret == 0)
break;
}
return ret;
}
static int flexcop_eeprom_lrc_read(struct flexcop_device *fc, u16 addr,
u8 *buf, u16 len, int retries)
{
int ret = flexcop_eeprom_request(fc, FC_READ, addr, buf, len, retries);
if (ret == 0)
if (calc_lrc(buf, len - 1) != buf[len - 1])
ret = -EINVAL;
return ret;
}
/* JJ's comment about extended == 1: it is not presently used anywhere but was
* added to the low-level functions for possible support of EUI64 */
int flexcop_eeprom_check_mac_addr(struct flexcop_device *fc, int extended)
{
u8 buf[8];
int ret = 0;
if ((ret = flexcop_eeprom_lrc_read(fc,0x3f8,buf,8,4)) == 0) {
if (extended != 0) {
err("TODO: extended (EUI64) MAC addresses aren't "
"completely supported yet");
ret = -EINVAL;
} else
memcpy(fc->dvb_adapter.proposed_mac,buf,6);
}
return ret;
}
EXPORT_SYMBOL(flexcop_eeprom_check_mac_addr);
| gpl-2.0 |
micchie/mptcp | drivers/net/ethernet/neterion/s2io.c | 50 | 246331 | /************************************************************************
* s2io.c: A Linux PCI-X Ethernet driver for Neterion 10GbE Server NIC
* Copyright(c) 2002-2010 Exar Corp.
*
* This software may be used and distributed according to the terms of
* the GNU General Public License (GPL), incorporated herein by reference.
* Drivers based on or derived from this code fall under the GPL and must
* retain the authorship, copyright and license notice. This file is not
* a complete program and may only be used when the entire operating
* system is licensed under the GPL.
* See the file COPYING in this distribution for more information.
*
* Credits:
* Jeff Garzik : For pointing out the improper error condition
* check in the s2io_xmit routine and also some
* issues in the Tx watch dog function. Also for
* patiently answering all those innumerable
* questions regaring the 2.6 porting issues.
* Stephen Hemminger : Providing proper 2.6 porting mechanism for some
* macros available only in 2.6 Kernel.
* Francois Romieu : For pointing out all code part that were
* deprecated and also styling related comments.
* Grant Grundler : For helping me get rid of some Architecture
* dependent code.
* Christopher Hellwig : Some more 2.6 specific issues in the driver.
*
* The module loadable parameters that are supported by the driver and a brief
* explanation of all the variables.
*
* rx_ring_num : This can be used to program the number of receive rings used
* in the driver.
* rx_ring_sz: This defines the number of receive blocks each ring can have.
* This is also an array of size 8.
* rx_ring_mode: This defines the operation mode of all 8 rings. The valid
* values are 1, 2.
* tx_fifo_num: This defines the number of Tx FIFOs thats used int the driver.
* tx_fifo_len: This too is an array of 8. Each element defines the number of
* Tx descriptors that can be associated with each corresponding FIFO.
* intr_type: This defines the type of interrupt. The values can be 0(INTA),
* 2(MSI_X). Default value is '2(MSI_X)'
* lro_max_pkts: This parameter defines maximum number of packets can be
* aggregated as a single large packet
* napi: This parameter used to enable/disable NAPI (polling Rx)
* Possible values '1' for enable and '0' for disable. Default is '1'
* ufo: This parameter used to enable/disable UDP Fragmentation Offload(UFO)
* Possible values '1' for enable and '0' for disable. Default is '0'
* vlan_tag_strip: This can be used to enable or disable vlan stripping.
* Possible values '1' for enable , '0' for disable.
* Default is '2' - which means disable in promisc mode
* and enable in non-promiscuous mode.
* multiq: This parameter used to enable/disable MULTIQUEUE support.
* Possible values '1' for enable and '0' for disable. Default is '0'
************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/mdio.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/stddef.h>
#include <linux/ioctl.h>
#include <linux/timex.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/prefetch.h>
#include <net/tcp.h>
#include <asm/div64.h>
#include <asm/irq.h>
/* local include */
#include "s2io.h"
#include "s2io-regs.h"
#define DRV_VERSION "2.0.26.28"
/* S2io Driver name & version. */
static const char s2io_driver_name[] = "Neterion";
static const char s2io_driver_version[] = DRV_VERSION;
static const int rxd_size[2] = {32, 48};
static const int rxd_count[2] = {127, 85};
static inline int RXD_IS_UP2DT(struct RxD_t *rxdp)
{
int ret;
ret = ((!(rxdp->Control_1 & RXD_OWN_XENA)) &&
(GET_RXD_MARKER(rxdp->Control_2) != THE_RXD_MARK));
return ret;
}
/*
* Cards with following subsystem_id have a link state indication
* problem, 600B, 600C, 600D, 640B, 640C and 640D.
* macro below identifies these cards given the subsystem_id.
*/
#define CARDS_WITH_FAULTY_LINK_INDICATORS(dev_type, subid) \
(dev_type == XFRAME_I_DEVICE) ? \
((((subid >= 0x600B) && (subid <= 0x600D)) || \
((subid >= 0x640B) && (subid <= 0x640D))) ? 1 : 0) : 0
#define LINK_IS_UP(val64) (!(val64 & (ADAPTER_STATUS_RMAC_REMOTE_FAULT | \
ADAPTER_STATUS_RMAC_LOCAL_FAULT)))
static inline int is_s2io_card_up(const struct s2io_nic *sp)
{
return test_bit(__S2IO_STATE_CARD_UP, &sp->state);
}
/* Ethtool related variables and Macros. */
static const char s2io_gstrings[][ETH_GSTRING_LEN] = {
"Register test\t(offline)",
"Eeprom test\t(offline)",
"Link test\t(online)",
"RLDRAM test\t(offline)",
"BIST Test\t(offline)"
};
static const char ethtool_xena_stats_keys[][ETH_GSTRING_LEN] = {
{"tmac_frms"},
{"tmac_data_octets"},
{"tmac_drop_frms"},
{"tmac_mcst_frms"},
{"tmac_bcst_frms"},
{"tmac_pause_ctrl_frms"},
{"tmac_ttl_octets"},
{"tmac_ucst_frms"},
{"tmac_nucst_frms"},
{"tmac_any_err_frms"},
{"tmac_ttl_less_fb_octets"},
{"tmac_vld_ip_octets"},
{"tmac_vld_ip"},
{"tmac_drop_ip"},
{"tmac_icmp"},
{"tmac_rst_tcp"},
{"tmac_tcp"},
{"tmac_udp"},
{"rmac_vld_frms"},
{"rmac_data_octets"},
{"rmac_fcs_err_frms"},
{"rmac_drop_frms"},
{"rmac_vld_mcst_frms"},
{"rmac_vld_bcst_frms"},
{"rmac_in_rng_len_err_frms"},
{"rmac_out_rng_len_err_frms"},
{"rmac_long_frms"},
{"rmac_pause_ctrl_frms"},
{"rmac_unsup_ctrl_frms"},
{"rmac_ttl_octets"},
{"rmac_accepted_ucst_frms"},
{"rmac_accepted_nucst_frms"},
{"rmac_discarded_frms"},
{"rmac_drop_events"},
{"rmac_ttl_less_fb_octets"},
{"rmac_ttl_frms"},
{"rmac_usized_frms"},
{"rmac_osized_frms"},
{"rmac_frag_frms"},
{"rmac_jabber_frms"},
{"rmac_ttl_64_frms"},
{"rmac_ttl_65_127_frms"},
{"rmac_ttl_128_255_frms"},
{"rmac_ttl_256_511_frms"},
{"rmac_ttl_512_1023_frms"},
{"rmac_ttl_1024_1518_frms"},
{"rmac_ip"},
{"rmac_ip_octets"},
{"rmac_hdr_err_ip"},
{"rmac_drop_ip"},
{"rmac_icmp"},
{"rmac_tcp"},
{"rmac_udp"},
{"rmac_err_drp_udp"},
{"rmac_xgmii_err_sym"},
{"rmac_frms_q0"},
{"rmac_frms_q1"},
{"rmac_frms_q2"},
{"rmac_frms_q3"},
{"rmac_frms_q4"},
{"rmac_frms_q5"},
{"rmac_frms_q6"},
{"rmac_frms_q7"},
{"rmac_full_q0"},
{"rmac_full_q1"},
{"rmac_full_q2"},
{"rmac_full_q3"},
{"rmac_full_q4"},
{"rmac_full_q5"},
{"rmac_full_q6"},
{"rmac_full_q7"},
{"rmac_pause_cnt"},
{"rmac_xgmii_data_err_cnt"},
{"rmac_xgmii_ctrl_err_cnt"},
{"rmac_accepted_ip"},
{"rmac_err_tcp"},
{"rd_req_cnt"},
{"new_rd_req_cnt"},
{"new_rd_req_rtry_cnt"},
{"rd_rtry_cnt"},
{"wr_rtry_rd_ack_cnt"},
{"wr_req_cnt"},
{"new_wr_req_cnt"},
{"new_wr_req_rtry_cnt"},
{"wr_rtry_cnt"},
{"wr_disc_cnt"},
{"rd_rtry_wr_ack_cnt"},
{"txp_wr_cnt"},
{"txd_rd_cnt"},
{"txd_wr_cnt"},
{"rxd_rd_cnt"},
{"rxd_wr_cnt"},
{"txf_rd_cnt"},
{"rxf_wr_cnt"}
};
static const char ethtool_enhanced_stats_keys[][ETH_GSTRING_LEN] = {
{"rmac_ttl_1519_4095_frms"},
{"rmac_ttl_4096_8191_frms"},
{"rmac_ttl_8192_max_frms"},
{"rmac_ttl_gt_max_frms"},
{"rmac_osized_alt_frms"},
{"rmac_jabber_alt_frms"},
{"rmac_gt_max_alt_frms"},
{"rmac_vlan_frms"},
{"rmac_len_discard"},
{"rmac_fcs_discard"},
{"rmac_pf_discard"},
{"rmac_da_discard"},
{"rmac_red_discard"},
{"rmac_rts_discard"},
{"rmac_ingm_full_discard"},
{"link_fault_cnt"}
};
static const char ethtool_driver_stats_keys[][ETH_GSTRING_LEN] = {
{"\n DRIVER STATISTICS"},
{"single_bit_ecc_errs"},
{"double_bit_ecc_errs"},
{"parity_err_cnt"},
{"serious_err_cnt"},
{"soft_reset_cnt"},
{"fifo_full_cnt"},
{"ring_0_full_cnt"},
{"ring_1_full_cnt"},
{"ring_2_full_cnt"},
{"ring_3_full_cnt"},
{"ring_4_full_cnt"},
{"ring_5_full_cnt"},
{"ring_6_full_cnt"},
{"ring_7_full_cnt"},
{"alarm_transceiver_temp_high"},
{"alarm_transceiver_temp_low"},
{"alarm_laser_bias_current_high"},
{"alarm_laser_bias_current_low"},
{"alarm_laser_output_power_high"},
{"alarm_laser_output_power_low"},
{"warn_transceiver_temp_high"},
{"warn_transceiver_temp_low"},
{"warn_laser_bias_current_high"},
{"warn_laser_bias_current_low"},
{"warn_laser_output_power_high"},
{"warn_laser_output_power_low"},
{"lro_aggregated_pkts"},
{"lro_flush_both_count"},
{"lro_out_of_sequence_pkts"},
{"lro_flush_due_to_max_pkts"},
{"lro_avg_aggr_pkts"},
{"mem_alloc_fail_cnt"},
{"pci_map_fail_cnt"},
{"watchdog_timer_cnt"},
{"mem_allocated"},
{"mem_freed"},
{"link_up_cnt"},
{"link_down_cnt"},
{"link_up_time"},
{"link_down_time"},
{"tx_tcode_buf_abort_cnt"},
{"tx_tcode_desc_abort_cnt"},
{"tx_tcode_parity_err_cnt"},
{"tx_tcode_link_loss_cnt"},
{"tx_tcode_list_proc_err_cnt"},
{"rx_tcode_parity_err_cnt"},
{"rx_tcode_abort_cnt"},
{"rx_tcode_parity_abort_cnt"},
{"rx_tcode_rda_fail_cnt"},
{"rx_tcode_unkn_prot_cnt"},
{"rx_tcode_fcs_err_cnt"},
{"rx_tcode_buf_size_err_cnt"},
{"rx_tcode_rxd_corrupt_cnt"},
{"rx_tcode_unkn_err_cnt"},
{"tda_err_cnt"},
{"pfc_err_cnt"},
{"pcc_err_cnt"},
{"tti_err_cnt"},
{"tpa_err_cnt"},
{"sm_err_cnt"},
{"lso_err_cnt"},
{"mac_tmac_err_cnt"},
{"mac_rmac_err_cnt"},
{"xgxs_txgxs_err_cnt"},
{"xgxs_rxgxs_err_cnt"},
{"rc_err_cnt"},
{"prc_pcix_err_cnt"},
{"rpa_err_cnt"},
{"rda_err_cnt"},
{"rti_err_cnt"},
{"mc_err_cnt"}
};
#define S2IO_XENA_STAT_LEN ARRAY_SIZE(ethtool_xena_stats_keys)
#define S2IO_ENHANCED_STAT_LEN ARRAY_SIZE(ethtool_enhanced_stats_keys)
#define S2IO_DRIVER_STAT_LEN ARRAY_SIZE(ethtool_driver_stats_keys)
#define XFRAME_I_STAT_LEN (S2IO_XENA_STAT_LEN + S2IO_DRIVER_STAT_LEN)
#define XFRAME_II_STAT_LEN (XFRAME_I_STAT_LEN + S2IO_ENHANCED_STAT_LEN)
#define XFRAME_I_STAT_STRINGS_LEN (XFRAME_I_STAT_LEN * ETH_GSTRING_LEN)
#define XFRAME_II_STAT_STRINGS_LEN (XFRAME_II_STAT_LEN * ETH_GSTRING_LEN)
#define S2IO_TEST_LEN ARRAY_SIZE(s2io_gstrings)
#define S2IO_STRINGS_LEN (S2IO_TEST_LEN * ETH_GSTRING_LEN)
#define S2IO_TIMER_CONF(timer, handle, arg, exp) \
init_timer(&timer); \
timer.function = handle; \
timer.data = (unsigned long)arg; \
mod_timer(&timer, (jiffies + exp)) \
/* copy mac addr to def_mac_addr array */
static void do_s2io_copy_mac_addr(struct s2io_nic *sp, int offset, u64 mac_addr)
{
sp->def_mac_addr[offset].mac_addr[5] = (u8) (mac_addr);
sp->def_mac_addr[offset].mac_addr[4] = (u8) (mac_addr >> 8);
sp->def_mac_addr[offset].mac_addr[3] = (u8) (mac_addr >> 16);
sp->def_mac_addr[offset].mac_addr[2] = (u8) (mac_addr >> 24);
sp->def_mac_addr[offset].mac_addr[1] = (u8) (mac_addr >> 32);
sp->def_mac_addr[offset].mac_addr[0] = (u8) (mac_addr >> 40);
}
/*
* Constants to be programmed into the Xena's registers, to configure
* the XAUI.
*/
#define END_SIGN 0x0
static const u64 herc_act_dtx_cfg[] = {
/* Set address */
0x8000051536750000ULL, 0x80000515367500E0ULL,
/* Write data */
0x8000051536750004ULL, 0x80000515367500E4ULL,
/* Set address */
0x80010515003F0000ULL, 0x80010515003F00E0ULL,
/* Write data */
0x80010515003F0004ULL, 0x80010515003F00E4ULL,
/* Set address */
0x801205150D440000ULL, 0x801205150D4400E0ULL,
/* Write data */
0x801205150D440004ULL, 0x801205150D4400E4ULL,
/* Set address */
0x80020515F2100000ULL, 0x80020515F21000E0ULL,
/* Write data */
0x80020515F2100004ULL, 0x80020515F21000E4ULL,
/* Done */
END_SIGN
};
static const u64 xena_dtx_cfg[] = {
/* Set address */
0x8000051500000000ULL, 0x80000515000000E0ULL,
/* Write data */
0x80000515D9350004ULL, 0x80000515D93500E4ULL,
/* Set address */
0x8001051500000000ULL, 0x80010515000000E0ULL,
/* Write data */
0x80010515001E0004ULL, 0x80010515001E00E4ULL,
/* Set address */
0x8002051500000000ULL, 0x80020515000000E0ULL,
/* Write data */
0x80020515F2100004ULL, 0x80020515F21000E4ULL,
END_SIGN
};
/*
* Constants for Fixing the MacAddress problem seen mostly on
* Alpha machines.
*/
static const u64 fix_mac[] = {
0x0060000000000000ULL, 0x0060600000000000ULL,
0x0040600000000000ULL, 0x0000600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0060600000000000ULL,
0x0020600000000000ULL, 0x0000600000000000ULL,
0x0040600000000000ULL, 0x0060600000000000ULL,
END_SIGN
};
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
/* Module Loadable parameters. */
S2IO_PARM_INT(tx_fifo_num, FIFO_DEFAULT_NUM);
S2IO_PARM_INT(rx_ring_num, 1);
S2IO_PARM_INT(multiq, 0);
S2IO_PARM_INT(rx_ring_mode, 1);
S2IO_PARM_INT(use_continuous_tx_intrs, 1);
S2IO_PARM_INT(rmac_pause_time, 0x100);
S2IO_PARM_INT(mc_pause_threshold_q0q3, 187);
S2IO_PARM_INT(mc_pause_threshold_q4q7, 187);
S2IO_PARM_INT(shared_splits, 0);
S2IO_PARM_INT(tmac_util_period, 5);
S2IO_PARM_INT(rmac_util_period, 5);
S2IO_PARM_INT(l3l4hdr_size, 128);
/* 0 is no steering, 1 is Priority steering, 2 is Default steering */
S2IO_PARM_INT(tx_steering_type, TX_DEFAULT_STEERING);
/* Frequency of Rx desc syncs expressed as power of 2 */
S2IO_PARM_INT(rxsync_frequency, 3);
/* Interrupt type. Values can be 0(INTA), 2(MSI_X) */
S2IO_PARM_INT(intr_type, 2);
/* Large receive offload feature */
/* Max pkts to be aggregated by LRO at one time. If not specified,
* aggregation happens until we hit max IP pkt size(64K)
*/
S2IO_PARM_INT(lro_max_pkts, 0xFFFF);
S2IO_PARM_INT(indicate_max_pkts, 0);
S2IO_PARM_INT(napi, 1);
S2IO_PARM_INT(ufo, 0);
S2IO_PARM_INT(vlan_tag_strip, NO_STRIP_IN_PROMISC);
static unsigned int tx_fifo_len[MAX_TX_FIFOS] =
{DEFAULT_FIFO_0_LEN, [1 ...(MAX_TX_FIFOS - 1)] = DEFAULT_FIFO_1_7_LEN};
static unsigned int rx_ring_sz[MAX_RX_RINGS] =
{[0 ...(MAX_RX_RINGS - 1)] = SMALL_BLK_CNT};
static unsigned int rts_frm_len[MAX_RX_RINGS] =
{[0 ...(MAX_RX_RINGS - 1)] = 0 };
module_param_array(tx_fifo_len, uint, NULL, 0);
module_param_array(rx_ring_sz, uint, NULL, 0);
module_param_array(rts_frm_len, uint, NULL, 0);
/*
* S2IO device table.
* This table lists all the devices that this driver supports.
*/
static DEFINE_PCI_DEVICE_TABLE(s2io_tbl) = {
{PCI_VENDOR_ID_S2IO, PCI_DEVICE_ID_S2IO_WIN,
PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_S2IO, PCI_DEVICE_ID_S2IO_UNI,
PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_S2IO, PCI_DEVICE_ID_HERC_WIN,
PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_S2IO, PCI_DEVICE_ID_HERC_UNI,
PCI_ANY_ID, PCI_ANY_ID},
{0,}
};
MODULE_DEVICE_TABLE(pci, s2io_tbl);
static struct pci_error_handlers s2io_err_handler = {
.error_detected = s2io_io_error_detected,
.slot_reset = s2io_io_slot_reset,
.resume = s2io_io_resume,
};
static struct pci_driver s2io_driver = {
.name = "S2IO",
.id_table = s2io_tbl,
.probe = s2io_init_nic,
.remove = __devexit_p(s2io_rem_nic),
.err_handler = &s2io_err_handler,
};
/* A simplifier macro used both by init and free shared_mem Fns(). */
#define TXD_MEM_PAGE_CNT(len, per_each) ((len+per_each - 1) / per_each)
/* netqueue manipulation helper functions */
static inline void s2io_stop_all_tx_queue(struct s2io_nic *sp)
{
if (!sp->config.multiq) {
int i;
for (i = 0; i < sp->config.tx_fifo_num; i++)
sp->mac_control.fifos[i].queue_state = FIFO_QUEUE_STOP;
}
netif_tx_stop_all_queues(sp->dev);
}
static inline void s2io_stop_tx_queue(struct s2io_nic *sp, int fifo_no)
{
if (!sp->config.multiq)
sp->mac_control.fifos[fifo_no].queue_state =
FIFO_QUEUE_STOP;
netif_tx_stop_all_queues(sp->dev);
}
static inline void s2io_start_all_tx_queue(struct s2io_nic *sp)
{
if (!sp->config.multiq) {
int i;
for (i = 0; i < sp->config.tx_fifo_num; i++)
sp->mac_control.fifos[i].queue_state = FIFO_QUEUE_START;
}
netif_tx_start_all_queues(sp->dev);
}
static inline void s2io_start_tx_queue(struct s2io_nic *sp, int fifo_no)
{
if (!sp->config.multiq)
sp->mac_control.fifos[fifo_no].queue_state =
FIFO_QUEUE_START;
netif_tx_start_all_queues(sp->dev);
}
static inline void s2io_wake_all_tx_queue(struct s2io_nic *sp)
{
if (!sp->config.multiq) {
int i;
for (i = 0; i < sp->config.tx_fifo_num; i++)
sp->mac_control.fifos[i].queue_state = FIFO_QUEUE_START;
}
netif_tx_wake_all_queues(sp->dev);
}
static inline void s2io_wake_tx_queue(
struct fifo_info *fifo, int cnt, u8 multiq)
{
if (multiq) {
if (cnt && __netif_subqueue_stopped(fifo->dev, fifo->fifo_no))
netif_wake_subqueue(fifo->dev, fifo->fifo_no);
} else if (cnt && (fifo->queue_state == FIFO_QUEUE_STOP)) {
if (netif_queue_stopped(fifo->dev)) {
fifo->queue_state = FIFO_QUEUE_START;
netif_wake_queue(fifo->dev);
}
}
}
/**
* init_shared_mem - Allocation and Initialization of Memory
* @nic: Device private variable.
* Description: The function allocates all the memory areas shared
* between the NIC and the driver. This includes Tx descriptors,
* Rx descriptors and the statistics block.
*/
static int init_shared_mem(struct s2io_nic *nic)
{
u32 size;
void *tmp_v_addr, *tmp_v_addr_next;
dma_addr_t tmp_p_addr, tmp_p_addr_next;
struct RxD_block *pre_rxd_blk = NULL;
int i, j, blk_cnt;
int lst_size, lst_per_page;
struct net_device *dev = nic->dev;
unsigned long tmp;
struct buffAdd *ba;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
unsigned long long mem_allocated = 0;
/* Allocation and initialization of TXDLs in FIFOs */
size = 0;
for (i = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
size += tx_cfg->fifo_len;
}
if (size > MAX_AVAILABLE_TXDS) {
DBG_PRINT(ERR_DBG,
"Too many TxDs requested: %d, max supported: %d\n",
size, MAX_AVAILABLE_TXDS);
return -EINVAL;
}
size = 0;
for (i = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
size = tx_cfg->fifo_len;
/*
* Legal values are from 2 to 8192
*/
if (size < 2) {
DBG_PRINT(ERR_DBG, "Fifo %d: Invalid length (%d) - "
"Valid lengths are 2 through 8192\n",
i, size);
return -EINVAL;
}
}
lst_size = (sizeof(struct TxD) * config->max_txds);
lst_per_page = PAGE_SIZE / lst_size;
for (i = 0; i < config->tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
int fifo_len = tx_cfg->fifo_len;
int list_holder_size = fifo_len * sizeof(struct list_info_hold);
fifo->list_info = kzalloc(list_holder_size, GFP_KERNEL);
if (!fifo->list_info) {
DBG_PRINT(INFO_DBG, "Malloc failed for list_info\n");
return -ENOMEM;
}
mem_allocated += list_holder_size;
}
for (i = 0; i < config->tx_fifo_num; i++) {
int page_num = TXD_MEM_PAGE_CNT(config->tx_cfg[i].fifo_len,
lst_per_page);
struct fifo_info *fifo = &mac_control->fifos[i];
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
fifo->tx_curr_put_info.offset = 0;
fifo->tx_curr_put_info.fifo_len = tx_cfg->fifo_len - 1;
fifo->tx_curr_get_info.offset = 0;
fifo->tx_curr_get_info.fifo_len = tx_cfg->fifo_len - 1;
fifo->fifo_no = i;
fifo->nic = nic;
fifo->max_txds = MAX_SKB_FRAGS + 2;
fifo->dev = dev;
for (j = 0; j < page_num; j++) {
int k = 0;
dma_addr_t tmp_p;
void *tmp_v;
tmp_v = pci_alloc_consistent(nic->pdev,
PAGE_SIZE, &tmp_p);
if (!tmp_v) {
DBG_PRINT(INFO_DBG,
"pci_alloc_consistent failed for TxDL\n");
return -ENOMEM;
}
/* If we got a zero DMA address(can happen on
* certain platforms like PPC), reallocate.
* Store virtual address of page we don't want,
* to be freed later.
*/
if (!tmp_p) {
mac_control->zerodma_virt_addr = tmp_v;
DBG_PRINT(INIT_DBG,
"%s: Zero DMA address for TxDL. "
"Virtual address %p\n",
dev->name, tmp_v);
tmp_v = pci_alloc_consistent(nic->pdev,
PAGE_SIZE, &tmp_p);
if (!tmp_v) {
DBG_PRINT(INFO_DBG,
"pci_alloc_consistent failed for TxDL\n");
return -ENOMEM;
}
mem_allocated += PAGE_SIZE;
}
while (k < lst_per_page) {
int l = (j * lst_per_page) + k;
if (l == tx_cfg->fifo_len)
break;
fifo->list_info[l].list_virt_addr =
tmp_v + (k * lst_size);
fifo->list_info[l].list_phy_addr =
tmp_p + (k * lst_size);
k++;
}
}
}
for (i = 0; i < config->tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
size = tx_cfg->fifo_len;
fifo->ufo_in_band_v = kcalloc(size, sizeof(u64), GFP_KERNEL);
if (!fifo->ufo_in_band_v)
return -ENOMEM;
mem_allocated += (size * sizeof(u64));
}
/* Allocation and initialization of RXDs in Rings */
size = 0;
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
if (rx_cfg->num_rxd % (rxd_count[nic->rxd_mode] + 1)) {
DBG_PRINT(ERR_DBG, "%s: Ring%d RxD count is not a "
"multiple of RxDs per Block\n",
dev->name, i);
return FAILURE;
}
size += rx_cfg->num_rxd;
ring->block_count = rx_cfg->num_rxd /
(rxd_count[nic->rxd_mode] + 1);
ring->pkt_cnt = rx_cfg->num_rxd - ring->block_count;
}
if (nic->rxd_mode == RXD_MODE_1)
size = (size * (sizeof(struct RxD1)));
else
size = (size * (sizeof(struct RxD3)));
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
ring->rx_curr_get_info.block_index = 0;
ring->rx_curr_get_info.offset = 0;
ring->rx_curr_get_info.ring_len = rx_cfg->num_rxd - 1;
ring->rx_curr_put_info.block_index = 0;
ring->rx_curr_put_info.offset = 0;
ring->rx_curr_put_info.ring_len = rx_cfg->num_rxd - 1;
ring->nic = nic;
ring->ring_no = i;
blk_cnt = rx_cfg->num_rxd / (rxd_count[nic->rxd_mode] + 1);
/* Allocating all the Rx blocks */
for (j = 0; j < blk_cnt; j++) {
struct rx_block_info *rx_blocks;
int l;
rx_blocks = &ring->rx_blocks[j];
size = SIZE_OF_BLOCK; /* size is always page size */
tmp_v_addr = pci_alloc_consistent(nic->pdev, size,
&tmp_p_addr);
if (tmp_v_addr == NULL) {
/*
* In case of failure, free_shared_mem()
* is called, which should free any
* memory that was alloced till the
* failure happened.
*/
rx_blocks->block_virt_addr = tmp_v_addr;
return -ENOMEM;
}
mem_allocated += size;
memset(tmp_v_addr, 0, size);
size = sizeof(struct rxd_info) *
rxd_count[nic->rxd_mode];
rx_blocks->block_virt_addr = tmp_v_addr;
rx_blocks->block_dma_addr = tmp_p_addr;
rx_blocks->rxds = kmalloc(size, GFP_KERNEL);
if (!rx_blocks->rxds)
return -ENOMEM;
mem_allocated += size;
for (l = 0; l < rxd_count[nic->rxd_mode]; l++) {
rx_blocks->rxds[l].virt_addr =
rx_blocks->block_virt_addr +
(rxd_size[nic->rxd_mode] * l);
rx_blocks->rxds[l].dma_addr =
rx_blocks->block_dma_addr +
(rxd_size[nic->rxd_mode] * l);
}
}
/* Interlinking all Rx Blocks */
for (j = 0; j < blk_cnt; j++) {
int next = (j + 1) % blk_cnt;
tmp_v_addr = ring->rx_blocks[j].block_virt_addr;
tmp_v_addr_next = ring->rx_blocks[next].block_virt_addr;
tmp_p_addr = ring->rx_blocks[j].block_dma_addr;
tmp_p_addr_next = ring->rx_blocks[next].block_dma_addr;
pre_rxd_blk = tmp_v_addr;
pre_rxd_blk->reserved_2_pNext_RxD_block =
(unsigned long)tmp_v_addr_next;
pre_rxd_blk->pNext_RxD_Blk_physical =
(u64)tmp_p_addr_next;
}
}
if (nic->rxd_mode == RXD_MODE_3B) {
/*
* Allocation of Storages for buffer addresses in 2BUFF mode
* and the buffers as well.
*/
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
blk_cnt = rx_cfg->num_rxd /
(rxd_count[nic->rxd_mode] + 1);
size = sizeof(struct buffAdd *) * blk_cnt;
ring->ba = kmalloc(size, GFP_KERNEL);
if (!ring->ba)
return -ENOMEM;
mem_allocated += size;
for (j = 0; j < blk_cnt; j++) {
int k = 0;
size = sizeof(struct buffAdd) *
(rxd_count[nic->rxd_mode] + 1);
ring->ba[j] = kmalloc(size, GFP_KERNEL);
if (!ring->ba[j])
return -ENOMEM;
mem_allocated += size;
while (k != rxd_count[nic->rxd_mode]) {
ba = &ring->ba[j][k];
size = BUF0_LEN + ALIGN_SIZE;
ba->ba_0_org = kmalloc(size, GFP_KERNEL);
if (!ba->ba_0_org)
return -ENOMEM;
mem_allocated += size;
tmp = (unsigned long)ba->ba_0_org;
tmp += ALIGN_SIZE;
tmp &= ~((unsigned long)ALIGN_SIZE);
ba->ba_0 = (void *)tmp;
size = BUF1_LEN + ALIGN_SIZE;
ba->ba_1_org = kmalloc(size, GFP_KERNEL);
if (!ba->ba_1_org)
return -ENOMEM;
mem_allocated += size;
tmp = (unsigned long)ba->ba_1_org;
tmp += ALIGN_SIZE;
tmp &= ~((unsigned long)ALIGN_SIZE);
ba->ba_1 = (void *)tmp;
k++;
}
}
}
}
/* Allocation and initialization of Statistics block */
size = sizeof(struct stat_block);
mac_control->stats_mem =
pci_alloc_consistent(nic->pdev, size,
&mac_control->stats_mem_phy);
if (!mac_control->stats_mem) {
/*
* In case of failure, free_shared_mem() is called, which
* should free any memory that was alloced till the
* failure happened.
*/
return -ENOMEM;
}
mem_allocated += size;
mac_control->stats_mem_sz = size;
tmp_v_addr = mac_control->stats_mem;
mac_control->stats_info = tmp_v_addr;
memset(tmp_v_addr, 0, size);
DBG_PRINT(INIT_DBG, "%s: Ring Mem PHY: 0x%llx\n",
dev_name(&nic->pdev->dev), (unsigned long long)tmp_p_addr);
mac_control->stats_info->sw_stat.mem_allocated += mem_allocated;
return SUCCESS;
}
/**
* free_shared_mem - Free the allocated Memory
* @nic: Device private variable.
* Description: This function is to free all memory locations allocated by
* the init_shared_mem() function and return it to the kernel.
*/
static void free_shared_mem(struct s2io_nic *nic)
{
int i, j, blk_cnt, size;
void *tmp_v_addr;
dma_addr_t tmp_p_addr;
int lst_size, lst_per_page;
struct net_device *dev;
int page_num = 0;
struct config_param *config;
struct mac_info *mac_control;
struct stat_block *stats;
struct swStat *swstats;
if (!nic)
return;
dev = nic->dev;
config = &nic->config;
mac_control = &nic->mac_control;
stats = mac_control->stats_info;
swstats = &stats->sw_stat;
lst_size = sizeof(struct TxD) * config->max_txds;
lst_per_page = PAGE_SIZE / lst_size;
for (i = 0; i < config->tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
page_num = TXD_MEM_PAGE_CNT(tx_cfg->fifo_len, lst_per_page);
for (j = 0; j < page_num; j++) {
int mem_blks = (j * lst_per_page);
struct list_info_hold *fli;
if (!fifo->list_info)
return;
fli = &fifo->list_info[mem_blks];
if (!fli->list_virt_addr)
break;
pci_free_consistent(nic->pdev, PAGE_SIZE,
fli->list_virt_addr,
fli->list_phy_addr);
swstats->mem_freed += PAGE_SIZE;
}
/* If we got a zero DMA address during allocation,
* free the page now
*/
if (mac_control->zerodma_virt_addr) {
pci_free_consistent(nic->pdev, PAGE_SIZE,
mac_control->zerodma_virt_addr,
(dma_addr_t)0);
DBG_PRINT(INIT_DBG,
"%s: Freeing TxDL with zero DMA address. "
"Virtual address %p\n",
dev->name, mac_control->zerodma_virt_addr);
swstats->mem_freed += PAGE_SIZE;
}
kfree(fifo->list_info);
swstats->mem_freed += tx_cfg->fifo_len *
sizeof(struct list_info_hold);
}
size = SIZE_OF_BLOCK;
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
blk_cnt = ring->block_count;
for (j = 0; j < blk_cnt; j++) {
tmp_v_addr = ring->rx_blocks[j].block_virt_addr;
tmp_p_addr = ring->rx_blocks[j].block_dma_addr;
if (tmp_v_addr == NULL)
break;
pci_free_consistent(nic->pdev, size,
tmp_v_addr, tmp_p_addr);
swstats->mem_freed += size;
kfree(ring->rx_blocks[j].rxds);
swstats->mem_freed += sizeof(struct rxd_info) *
rxd_count[nic->rxd_mode];
}
}
if (nic->rxd_mode == RXD_MODE_3B) {
/* Freeing buffer storage addresses in 2BUFF mode. */
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
blk_cnt = rx_cfg->num_rxd /
(rxd_count[nic->rxd_mode] + 1);
for (j = 0; j < blk_cnt; j++) {
int k = 0;
if (!ring->ba[j])
continue;
while (k != rxd_count[nic->rxd_mode]) {
struct buffAdd *ba = &ring->ba[j][k];
kfree(ba->ba_0_org);
swstats->mem_freed +=
BUF0_LEN + ALIGN_SIZE;
kfree(ba->ba_1_org);
swstats->mem_freed +=
BUF1_LEN + ALIGN_SIZE;
k++;
}
kfree(ring->ba[j]);
swstats->mem_freed += sizeof(struct buffAdd) *
(rxd_count[nic->rxd_mode] + 1);
}
kfree(ring->ba);
swstats->mem_freed += sizeof(struct buffAdd *) *
blk_cnt;
}
}
for (i = 0; i < nic->config.tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
if (fifo->ufo_in_band_v) {
swstats->mem_freed += tx_cfg->fifo_len *
sizeof(u64);
kfree(fifo->ufo_in_band_v);
}
}
if (mac_control->stats_mem) {
swstats->mem_freed += mac_control->stats_mem_sz;
pci_free_consistent(nic->pdev,
mac_control->stats_mem_sz,
mac_control->stats_mem,
mac_control->stats_mem_phy);
}
}
/**
* s2io_verify_pci_mode -
*/
static int s2io_verify_pci_mode(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64 = 0;
int mode;
val64 = readq(&bar0->pci_mode);
mode = (u8)GET_PCI_MODE(val64);
if (val64 & PCI_MODE_UNKNOWN_MODE)
return -1; /* Unknown PCI mode */
return mode;
}
#define NEC_VENID 0x1033
#define NEC_DEVID 0x0125
static int s2io_on_nec_bridge(struct pci_dev *s2io_pdev)
{
struct pci_dev *tdev = NULL;
while ((tdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, tdev)) != NULL) {
if (tdev->vendor == NEC_VENID && tdev->device == NEC_DEVID) {
if (tdev->bus == s2io_pdev->bus->parent) {
pci_dev_put(tdev);
return 1;
}
}
}
return 0;
}
static int bus_speed[8] = {33, 133, 133, 200, 266, 133, 200, 266};
/**
* s2io_print_pci_mode -
*/
static int s2io_print_pci_mode(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64 = 0;
int mode;
struct config_param *config = &nic->config;
const char *pcimode;
val64 = readq(&bar0->pci_mode);
mode = (u8)GET_PCI_MODE(val64);
if (val64 & PCI_MODE_UNKNOWN_MODE)
return -1; /* Unknown PCI mode */
config->bus_speed = bus_speed[mode];
if (s2io_on_nec_bridge(nic->pdev)) {
DBG_PRINT(ERR_DBG, "%s: Device is on PCI-E bus\n",
nic->dev->name);
return mode;
}
switch (mode) {
case PCI_MODE_PCI_33:
pcimode = "33MHz PCI bus";
break;
case PCI_MODE_PCI_66:
pcimode = "66MHz PCI bus";
break;
case PCI_MODE_PCIX_M1_66:
pcimode = "66MHz PCIX(M1) bus";
break;
case PCI_MODE_PCIX_M1_100:
pcimode = "100MHz PCIX(M1) bus";
break;
case PCI_MODE_PCIX_M1_133:
pcimode = "133MHz PCIX(M1) bus";
break;
case PCI_MODE_PCIX_M2_66:
pcimode = "133MHz PCIX(M2) bus";
break;
case PCI_MODE_PCIX_M2_100:
pcimode = "200MHz PCIX(M2) bus";
break;
case PCI_MODE_PCIX_M2_133:
pcimode = "266MHz PCIX(M2) bus";
break;
default:
pcimode = "unsupported bus!";
mode = -1;
}
DBG_PRINT(ERR_DBG, "%s: Device is on %d bit %s\n",
nic->dev->name, val64 & PCI_MODE_32_BITS ? 32 : 64, pcimode);
return mode;
}
/**
* init_tti - Initialization transmit traffic interrupt scheme
* @nic: device private variable
* @link: link status (UP/DOWN) used to enable/disable continuous
* transmit interrupts
* Description: The function configures transmit traffic interrupts
* Return Value: SUCCESS on success and
* '-1' on failure
*/
static int init_tti(struct s2io_nic *nic, int link)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64 = 0;
int i;
struct config_param *config = &nic->config;
for (i = 0; i < config->tx_fifo_num; i++) {
/*
* TTI Initialization. Default Tx timer gets us about
* 250 interrupts per sec. Continuous interrupts are enabled
* by default.
*/
if (nic->device_type == XFRAME_II_DEVICE) {
int count = (nic->config.bus_speed * 125)/2;
val64 = TTI_DATA1_MEM_TX_TIMER_VAL(count);
} else
val64 = TTI_DATA1_MEM_TX_TIMER_VAL(0x2078);
val64 |= TTI_DATA1_MEM_TX_URNG_A(0xA) |
TTI_DATA1_MEM_TX_URNG_B(0x10) |
TTI_DATA1_MEM_TX_URNG_C(0x30) |
TTI_DATA1_MEM_TX_TIMER_AC_EN;
if (i == 0)
if (use_continuous_tx_intrs && (link == LINK_UP))
val64 |= TTI_DATA1_MEM_TX_TIMER_CI_EN;
writeq(val64, &bar0->tti_data1_mem);
if (nic->config.intr_type == MSI_X) {
val64 = TTI_DATA2_MEM_TX_UFC_A(0x10) |
TTI_DATA2_MEM_TX_UFC_B(0x100) |
TTI_DATA2_MEM_TX_UFC_C(0x200) |
TTI_DATA2_MEM_TX_UFC_D(0x300);
} else {
if ((nic->config.tx_steering_type ==
TX_DEFAULT_STEERING) &&
(config->tx_fifo_num > 1) &&
(i >= nic->udp_fifo_idx) &&
(i < (nic->udp_fifo_idx +
nic->total_udp_fifos)))
val64 = TTI_DATA2_MEM_TX_UFC_A(0x50) |
TTI_DATA2_MEM_TX_UFC_B(0x80) |
TTI_DATA2_MEM_TX_UFC_C(0x100) |
TTI_DATA2_MEM_TX_UFC_D(0x120);
else
val64 = TTI_DATA2_MEM_TX_UFC_A(0x10) |
TTI_DATA2_MEM_TX_UFC_B(0x20) |
TTI_DATA2_MEM_TX_UFC_C(0x40) |
TTI_DATA2_MEM_TX_UFC_D(0x80);
}
writeq(val64, &bar0->tti_data2_mem);
val64 = TTI_CMD_MEM_WE |
TTI_CMD_MEM_STROBE_NEW_CMD |
TTI_CMD_MEM_OFFSET(i);
writeq(val64, &bar0->tti_command_mem);
if (wait_for_cmd_complete(&bar0->tti_command_mem,
TTI_CMD_MEM_STROBE_NEW_CMD,
S2IO_BIT_RESET) != SUCCESS)
return FAILURE;
}
return SUCCESS;
}
/**
* init_nic - Initialization of hardware
* @nic: device private variable
* Description: The function sequentially configures every block
* of the H/W from their reset values.
* Return Value: SUCCESS on success and
* '-1' on failure (endian settings incorrect).
*/
static int init_nic(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
struct net_device *dev = nic->dev;
register u64 val64 = 0;
void __iomem *add;
u32 time;
int i, j;
int dtx_cnt = 0;
unsigned long long mem_share;
int mem_size;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
/* to set the swapper controle on the card */
if (s2io_set_swapper(nic)) {
DBG_PRINT(ERR_DBG, "ERROR: Setting Swapper failed\n");
return -EIO;
}
/*
* Herc requires EOI to be removed from reset before XGXS, so..
*/
if (nic->device_type & XFRAME_II_DEVICE) {
val64 = 0xA500000000ULL;
writeq(val64, &bar0->sw_reset);
msleep(500);
val64 = readq(&bar0->sw_reset);
}
/* Remove XGXS from reset state */
val64 = 0;
writeq(val64, &bar0->sw_reset);
msleep(500);
val64 = readq(&bar0->sw_reset);
/* Ensure that it's safe to access registers by checking
* RIC_RUNNING bit is reset. Check is valid only for XframeII.
*/
if (nic->device_type == XFRAME_II_DEVICE) {
for (i = 0; i < 50; i++) {
val64 = readq(&bar0->adapter_status);
if (!(val64 & ADAPTER_STATUS_RIC_RUNNING))
break;
msleep(10);
}
if (i == 50)
return -ENODEV;
}
/* Enable Receiving broadcasts */
add = &bar0->mac_cfg;
val64 = readq(&bar0->mac_cfg);
val64 |= MAC_RMAC_BCAST_ENABLE;
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32)val64, add);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64 >> 32), (add + 4));
/* Read registers in all blocks */
val64 = readq(&bar0->mac_int_mask);
val64 = readq(&bar0->mc_int_mask);
val64 = readq(&bar0->xgxs_int_mask);
/* Set MTU */
val64 = dev->mtu;
writeq(vBIT(val64, 2, 14), &bar0->rmac_max_pyld_len);
if (nic->device_type & XFRAME_II_DEVICE) {
while (herc_act_dtx_cfg[dtx_cnt] != END_SIGN) {
SPECIAL_REG_WRITE(herc_act_dtx_cfg[dtx_cnt],
&bar0->dtx_control, UF);
if (dtx_cnt & 0x1)
msleep(1); /* Necessary!! */
dtx_cnt++;
}
} else {
while (xena_dtx_cfg[dtx_cnt] != END_SIGN) {
SPECIAL_REG_WRITE(xena_dtx_cfg[dtx_cnt],
&bar0->dtx_control, UF);
val64 = readq(&bar0->dtx_control);
dtx_cnt++;
}
}
/* Tx DMA Initialization */
val64 = 0;
writeq(val64, &bar0->tx_fifo_partition_0);
writeq(val64, &bar0->tx_fifo_partition_1);
writeq(val64, &bar0->tx_fifo_partition_2);
writeq(val64, &bar0->tx_fifo_partition_3);
for (i = 0, j = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
val64 |= vBIT(tx_cfg->fifo_len - 1, ((j * 32) + 19), 13) |
vBIT(tx_cfg->fifo_priority, ((j * 32) + 5), 3);
if (i == (config->tx_fifo_num - 1)) {
if (i % 2 == 0)
i++;
}
switch (i) {
case 1:
writeq(val64, &bar0->tx_fifo_partition_0);
val64 = 0;
j = 0;
break;
case 3:
writeq(val64, &bar0->tx_fifo_partition_1);
val64 = 0;
j = 0;
break;
case 5:
writeq(val64, &bar0->tx_fifo_partition_2);
val64 = 0;
j = 0;
break;
case 7:
writeq(val64, &bar0->tx_fifo_partition_3);
val64 = 0;
j = 0;
break;
default:
j++;
break;
}
}
/*
* Disable 4 PCCs for Xena1, 2 and 3 as per H/W bug
* SXE-008 TRANSMIT DMA ARBITRATION ISSUE.
*/
if ((nic->device_type == XFRAME_I_DEVICE) && (nic->pdev->revision < 4))
writeq(PCC_ENABLE_FOUR, &bar0->pcc_enable);
val64 = readq(&bar0->tx_fifo_partition_0);
DBG_PRINT(INIT_DBG, "Fifo partition at: 0x%p is: 0x%llx\n",
&bar0->tx_fifo_partition_0, (unsigned long long)val64);
/*
* Initialization of Tx_PA_CONFIG register to ignore packet
* integrity checking.
*/
val64 = readq(&bar0->tx_pa_cfg);
val64 |= TX_PA_CFG_IGNORE_FRM_ERR |
TX_PA_CFG_IGNORE_SNAP_OUI |
TX_PA_CFG_IGNORE_LLC_CTRL |
TX_PA_CFG_IGNORE_L2_ERR;
writeq(val64, &bar0->tx_pa_cfg);
/* Rx DMA intialization. */
val64 = 0;
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
val64 |= vBIT(rx_cfg->ring_priority, (5 + (i * 8)), 3);
}
writeq(val64, &bar0->rx_queue_priority);
/*
* Allocating equal share of memory to all the
* configured Rings.
*/
val64 = 0;
if (nic->device_type & XFRAME_II_DEVICE)
mem_size = 32;
else
mem_size = 64;
for (i = 0; i < config->rx_ring_num; i++) {
switch (i) {
case 0:
mem_share = (mem_size / config->rx_ring_num +
mem_size % config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q0_SZ(mem_share);
continue;
case 1:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q1_SZ(mem_share);
continue;
case 2:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q2_SZ(mem_share);
continue;
case 3:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q3_SZ(mem_share);
continue;
case 4:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q4_SZ(mem_share);
continue;
case 5:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q5_SZ(mem_share);
continue;
case 6:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q6_SZ(mem_share);
continue;
case 7:
mem_share = (mem_size / config->rx_ring_num);
val64 |= RX_QUEUE_CFG_Q7_SZ(mem_share);
continue;
}
}
writeq(val64, &bar0->rx_queue_cfg);
/*
* Filling Tx round robin registers
* as per the number of FIFOs for equal scheduling priority
*/
switch (config->tx_fifo_num) {
case 1:
val64 = 0x0;
writeq(val64, &bar0->tx_w_round_robin_0);
writeq(val64, &bar0->tx_w_round_robin_1);
writeq(val64, &bar0->tx_w_round_robin_2);
writeq(val64, &bar0->tx_w_round_robin_3);
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 2:
val64 = 0x0001000100010001ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
writeq(val64, &bar0->tx_w_round_robin_1);
writeq(val64, &bar0->tx_w_round_robin_2);
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0001000100000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 3:
val64 = 0x0001020001020001ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
val64 = 0x0200010200010200ULL;
writeq(val64, &bar0->tx_w_round_robin_1);
val64 = 0x0102000102000102ULL;
writeq(val64, &bar0->tx_w_round_robin_2);
val64 = 0x0001020001020001ULL;
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0200010200000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 4:
val64 = 0x0001020300010203ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
writeq(val64, &bar0->tx_w_round_robin_1);
writeq(val64, &bar0->tx_w_round_robin_2);
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0001020300000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 5:
val64 = 0x0001020304000102ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
val64 = 0x0304000102030400ULL;
writeq(val64, &bar0->tx_w_round_robin_1);
val64 = 0x0102030400010203ULL;
writeq(val64, &bar0->tx_w_round_robin_2);
val64 = 0x0400010203040001ULL;
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0203040000000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 6:
val64 = 0x0001020304050001ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
val64 = 0x0203040500010203ULL;
writeq(val64, &bar0->tx_w_round_robin_1);
val64 = 0x0405000102030405ULL;
writeq(val64, &bar0->tx_w_round_robin_2);
val64 = 0x0001020304050001ULL;
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0203040500000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 7:
val64 = 0x0001020304050600ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
val64 = 0x0102030405060001ULL;
writeq(val64, &bar0->tx_w_round_robin_1);
val64 = 0x0203040506000102ULL;
writeq(val64, &bar0->tx_w_round_robin_2);
val64 = 0x0304050600010203ULL;
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0405060000000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
case 8:
val64 = 0x0001020304050607ULL;
writeq(val64, &bar0->tx_w_round_robin_0);
writeq(val64, &bar0->tx_w_round_robin_1);
writeq(val64, &bar0->tx_w_round_robin_2);
writeq(val64, &bar0->tx_w_round_robin_3);
val64 = 0x0001020300000000ULL;
writeq(val64, &bar0->tx_w_round_robin_4);
break;
}
/* Enable all configured Tx FIFO partitions */
val64 = readq(&bar0->tx_fifo_partition_0);
val64 |= (TX_FIFO_PARTITION_EN);
writeq(val64, &bar0->tx_fifo_partition_0);
/* Filling the Rx round robin registers as per the
* number of Rings and steering based on QoS with
* equal priority.
*/
switch (config->rx_ring_num) {
case 1:
val64 = 0x0;
writeq(val64, &bar0->rx_w_round_robin_0);
writeq(val64, &bar0->rx_w_round_robin_1);
writeq(val64, &bar0->rx_w_round_robin_2);
writeq(val64, &bar0->rx_w_round_robin_3);
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080808080808080ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 2:
val64 = 0x0001000100010001ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
writeq(val64, &bar0->rx_w_round_robin_1);
writeq(val64, &bar0->rx_w_round_robin_2);
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0001000100000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080808040404040ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 3:
val64 = 0x0001020001020001ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
val64 = 0x0200010200010200ULL;
writeq(val64, &bar0->rx_w_round_robin_1);
val64 = 0x0102000102000102ULL;
writeq(val64, &bar0->rx_w_round_robin_2);
val64 = 0x0001020001020001ULL;
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0200010200000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080804040402020ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 4:
val64 = 0x0001020300010203ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
writeq(val64, &bar0->rx_w_round_robin_1);
writeq(val64, &bar0->rx_w_round_robin_2);
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0001020300000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080404020201010ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 5:
val64 = 0x0001020304000102ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
val64 = 0x0304000102030400ULL;
writeq(val64, &bar0->rx_w_round_robin_1);
val64 = 0x0102030400010203ULL;
writeq(val64, &bar0->rx_w_round_robin_2);
val64 = 0x0400010203040001ULL;
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0203040000000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080404020201008ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 6:
val64 = 0x0001020304050001ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
val64 = 0x0203040500010203ULL;
writeq(val64, &bar0->rx_w_round_robin_1);
val64 = 0x0405000102030405ULL;
writeq(val64, &bar0->rx_w_round_robin_2);
val64 = 0x0001020304050001ULL;
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0203040500000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080404020100804ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 7:
val64 = 0x0001020304050600ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
val64 = 0x0102030405060001ULL;
writeq(val64, &bar0->rx_w_round_robin_1);
val64 = 0x0203040506000102ULL;
writeq(val64, &bar0->rx_w_round_robin_2);
val64 = 0x0304050600010203ULL;
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0405060000000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8080402010080402ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
case 8:
val64 = 0x0001020304050607ULL;
writeq(val64, &bar0->rx_w_round_robin_0);
writeq(val64, &bar0->rx_w_round_robin_1);
writeq(val64, &bar0->rx_w_round_robin_2);
writeq(val64, &bar0->rx_w_round_robin_3);
val64 = 0x0001020300000000ULL;
writeq(val64, &bar0->rx_w_round_robin_4);
val64 = 0x8040201008040201ULL;
writeq(val64, &bar0->rts_qos_steering);
break;
}
/* UDP Fix */
val64 = 0;
for (i = 0; i < 8; i++)
writeq(val64, &bar0->rts_frm_len_n[i]);
/* Set the default rts frame length for the rings configured */
val64 = MAC_RTS_FRM_LEN_SET(dev->mtu+22);
for (i = 0 ; i < config->rx_ring_num ; i++)
writeq(val64, &bar0->rts_frm_len_n[i]);
/* Set the frame length for the configured rings
* desired by the user
*/
for (i = 0; i < config->rx_ring_num; i++) {
/* If rts_frm_len[i] == 0 then it is assumed that user not
* specified frame length steering.
* If the user provides the frame length then program
* the rts_frm_len register for those values or else
* leave it as it is.
*/
if (rts_frm_len[i] != 0) {
writeq(MAC_RTS_FRM_LEN_SET(rts_frm_len[i]),
&bar0->rts_frm_len_n[i]);
}
}
/* Disable differentiated services steering logic */
for (i = 0; i < 64; i++) {
if (rts_ds_steer(nic, i, 0) == FAILURE) {
DBG_PRINT(ERR_DBG,
"%s: rts_ds_steer failed on codepoint %d\n",
dev->name, i);
return -ENODEV;
}
}
/* Program statistics memory */
writeq(mac_control->stats_mem_phy, &bar0->stat_addr);
if (nic->device_type == XFRAME_II_DEVICE) {
val64 = STAT_BC(0x320);
writeq(val64, &bar0->stat_byte_cnt);
}
/*
* Initializing the sampling rate for the device to calculate the
* bandwidth utilization.
*/
val64 = MAC_TX_LINK_UTIL_VAL(tmac_util_period) |
MAC_RX_LINK_UTIL_VAL(rmac_util_period);
writeq(val64, &bar0->mac_link_util);
/*
* Initializing the Transmit and Receive Traffic Interrupt
* Scheme.
*/
/* Initialize TTI */
if (SUCCESS != init_tti(nic, nic->last_link_state))
return -ENODEV;
/* RTI Initialization */
if (nic->device_type == XFRAME_II_DEVICE) {
/*
* Programmed to generate Apprx 500 Intrs per
* second
*/
int count = (nic->config.bus_speed * 125)/4;
val64 = RTI_DATA1_MEM_RX_TIMER_VAL(count);
} else
val64 = RTI_DATA1_MEM_RX_TIMER_VAL(0xFFF);
val64 |= RTI_DATA1_MEM_RX_URNG_A(0xA) |
RTI_DATA1_MEM_RX_URNG_B(0x10) |
RTI_DATA1_MEM_RX_URNG_C(0x30) |
RTI_DATA1_MEM_RX_TIMER_AC_EN;
writeq(val64, &bar0->rti_data1_mem);
val64 = RTI_DATA2_MEM_RX_UFC_A(0x1) |
RTI_DATA2_MEM_RX_UFC_B(0x2) ;
if (nic->config.intr_type == MSI_X)
val64 |= (RTI_DATA2_MEM_RX_UFC_C(0x20) |
RTI_DATA2_MEM_RX_UFC_D(0x40));
else
val64 |= (RTI_DATA2_MEM_RX_UFC_C(0x40) |
RTI_DATA2_MEM_RX_UFC_D(0x80));
writeq(val64, &bar0->rti_data2_mem);
for (i = 0; i < config->rx_ring_num; i++) {
val64 = RTI_CMD_MEM_WE |
RTI_CMD_MEM_STROBE_NEW_CMD |
RTI_CMD_MEM_OFFSET(i);
writeq(val64, &bar0->rti_command_mem);
/*
* Once the operation completes, the Strobe bit of the
* command register will be reset. We poll for this
* particular condition. We wait for a maximum of 500ms
* for the operation to complete, if it's not complete
* by then we return error.
*/
time = 0;
while (true) {
val64 = readq(&bar0->rti_command_mem);
if (!(val64 & RTI_CMD_MEM_STROBE_NEW_CMD))
break;
if (time > 10) {
DBG_PRINT(ERR_DBG, "%s: RTI init failed\n",
dev->name);
return -ENODEV;
}
time++;
msleep(50);
}
}
/*
* Initializing proper values as Pause threshold into all
* the 8 Queues on Rx side.
*/
writeq(0xffbbffbbffbbffbbULL, &bar0->mc_pause_thresh_q0q3);
writeq(0xffbbffbbffbbffbbULL, &bar0->mc_pause_thresh_q4q7);
/* Disable RMAC PAD STRIPPING */
add = &bar0->mac_cfg;
val64 = readq(&bar0->mac_cfg);
val64 &= ~(MAC_CFG_RMAC_STRIP_PAD);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64), add);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64 >> 32), (add + 4));
val64 = readq(&bar0->mac_cfg);
/* Enable FCS stripping by adapter */
add = &bar0->mac_cfg;
val64 = readq(&bar0->mac_cfg);
val64 |= MAC_CFG_RMAC_STRIP_FCS;
if (nic->device_type == XFRAME_II_DEVICE)
writeq(val64, &bar0->mac_cfg);
else {
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64), add);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64 >> 32), (add + 4));
}
/*
* Set the time value to be inserted in the pause frame
* generated by xena.
*/
val64 = readq(&bar0->rmac_pause_cfg);
val64 &= ~(RMAC_PAUSE_HG_PTIME(0xffff));
val64 |= RMAC_PAUSE_HG_PTIME(nic->mac_control.rmac_pause_time);
writeq(val64, &bar0->rmac_pause_cfg);
/*
* Set the Threshold Limit for Generating the pause frame
* If the amount of data in any Queue exceeds ratio of
* (mac_control.mc_pause_threshold_q0q3 or q4q7)/256
* pause frame is generated
*/
val64 = 0;
for (i = 0; i < 4; i++) {
val64 |= (((u64)0xFF00 |
nic->mac_control.mc_pause_threshold_q0q3)
<< (i * 2 * 8));
}
writeq(val64, &bar0->mc_pause_thresh_q0q3);
val64 = 0;
for (i = 0; i < 4; i++) {
val64 |= (((u64)0xFF00 |
nic->mac_control.mc_pause_threshold_q4q7)
<< (i * 2 * 8));
}
writeq(val64, &bar0->mc_pause_thresh_q4q7);
/*
* TxDMA will stop Read request if the number of read split has
* exceeded the limit pointed by shared_splits
*/
val64 = readq(&bar0->pic_control);
val64 |= PIC_CNTL_SHARED_SPLITS(shared_splits);
writeq(val64, &bar0->pic_control);
if (nic->config.bus_speed == 266) {
writeq(TXREQTO_VAL(0x7f) | TXREQTO_EN, &bar0->txreqtimeout);
writeq(0x0, &bar0->read_retry_delay);
writeq(0x0, &bar0->write_retry_delay);
}
/*
* Programming the Herc to split every write transaction
* that does not start on an ADB to reduce disconnects.
*/
if (nic->device_type == XFRAME_II_DEVICE) {
val64 = FAULT_BEHAVIOUR | EXT_REQ_EN |
MISC_LINK_STABILITY_PRD(3);
writeq(val64, &bar0->misc_control);
val64 = readq(&bar0->pic_control2);
val64 &= ~(s2BIT(13)|s2BIT(14)|s2BIT(15));
writeq(val64, &bar0->pic_control2);
}
if (strstr(nic->product_name, "CX4")) {
val64 = TMAC_AVG_IPG(0x17);
writeq(val64, &bar0->tmac_avg_ipg);
}
return SUCCESS;
}
#define LINK_UP_DOWN_INTERRUPT 1
#define MAC_RMAC_ERR_TIMER 2
static int s2io_link_fault_indication(struct s2io_nic *nic)
{
if (nic->device_type == XFRAME_II_DEVICE)
return LINK_UP_DOWN_INTERRUPT;
else
return MAC_RMAC_ERR_TIMER;
}
/**
* do_s2io_write_bits - update alarm bits in alarm register
* @value: alarm bits
* @flag: interrupt status
* @addr: address value
* Description: update alarm bits in alarm register
* Return Value:
* NONE.
*/
static void do_s2io_write_bits(u64 value, int flag, void __iomem *addr)
{
u64 temp64;
temp64 = readq(addr);
if (flag == ENABLE_INTRS)
temp64 &= ~((u64)value);
else
temp64 |= ((u64)value);
writeq(temp64, addr);
}
static void en_dis_err_alarms(struct s2io_nic *nic, u16 mask, int flag)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 gen_int_mask = 0;
u64 interruptible;
writeq(DISABLE_ALL_INTRS, &bar0->general_int_mask);
if (mask & TX_DMA_INTR) {
gen_int_mask |= TXDMA_INT_M;
do_s2io_write_bits(TXDMA_TDA_INT | TXDMA_PFC_INT |
TXDMA_PCC_INT | TXDMA_TTI_INT |
TXDMA_LSO_INT | TXDMA_TPA_INT |
TXDMA_SM_INT, flag, &bar0->txdma_int_mask);
do_s2io_write_bits(PFC_ECC_DB_ERR | PFC_SM_ERR_ALARM |
PFC_MISC_0_ERR | PFC_MISC_1_ERR |
PFC_PCIX_ERR | PFC_ECC_SG_ERR, flag,
&bar0->pfc_err_mask);
do_s2io_write_bits(TDA_Fn_ECC_DB_ERR | TDA_SM0_ERR_ALARM |
TDA_SM1_ERR_ALARM | TDA_Fn_ECC_SG_ERR |
TDA_PCIX_ERR, flag, &bar0->tda_err_mask);
do_s2io_write_bits(PCC_FB_ECC_DB_ERR | PCC_TXB_ECC_DB_ERR |
PCC_SM_ERR_ALARM | PCC_WR_ERR_ALARM |
PCC_N_SERR | PCC_6_COF_OV_ERR |
PCC_7_COF_OV_ERR | PCC_6_LSO_OV_ERR |
PCC_7_LSO_OV_ERR | PCC_FB_ECC_SG_ERR |
PCC_TXB_ECC_SG_ERR,
flag, &bar0->pcc_err_mask);
do_s2io_write_bits(TTI_SM_ERR_ALARM | TTI_ECC_SG_ERR |
TTI_ECC_DB_ERR, flag, &bar0->tti_err_mask);
do_s2io_write_bits(LSO6_ABORT | LSO7_ABORT |
LSO6_SM_ERR_ALARM | LSO7_SM_ERR_ALARM |
LSO6_SEND_OFLOW | LSO7_SEND_OFLOW,
flag, &bar0->lso_err_mask);
do_s2io_write_bits(TPA_SM_ERR_ALARM | TPA_TX_FRM_DROP,
flag, &bar0->tpa_err_mask);
do_s2io_write_bits(SM_SM_ERR_ALARM, flag, &bar0->sm_err_mask);
}
if (mask & TX_MAC_INTR) {
gen_int_mask |= TXMAC_INT_M;
do_s2io_write_bits(MAC_INT_STATUS_TMAC_INT, flag,
&bar0->mac_int_mask);
do_s2io_write_bits(TMAC_TX_BUF_OVRN | TMAC_TX_SM_ERR |
TMAC_ECC_SG_ERR | TMAC_ECC_DB_ERR |
TMAC_DESC_ECC_SG_ERR | TMAC_DESC_ECC_DB_ERR,
flag, &bar0->mac_tmac_err_mask);
}
if (mask & TX_XGXS_INTR) {
gen_int_mask |= TXXGXS_INT_M;
do_s2io_write_bits(XGXS_INT_STATUS_TXGXS, flag,
&bar0->xgxs_int_mask);
do_s2io_write_bits(TXGXS_ESTORE_UFLOW | TXGXS_TX_SM_ERR |
TXGXS_ECC_SG_ERR | TXGXS_ECC_DB_ERR,
flag, &bar0->xgxs_txgxs_err_mask);
}
if (mask & RX_DMA_INTR) {
gen_int_mask |= RXDMA_INT_M;
do_s2io_write_bits(RXDMA_INT_RC_INT_M | RXDMA_INT_RPA_INT_M |
RXDMA_INT_RDA_INT_M | RXDMA_INT_RTI_INT_M,
flag, &bar0->rxdma_int_mask);
do_s2io_write_bits(RC_PRCn_ECC_DB_ERR | RC_FTC_ECC_DB_ERR |
RC_PRCn_SM_ERR_ALARM | RC_FTC_SM_ERR_ALARM |
RC_PRCn_ECC_SG_ERR | RC_FTC_ECC_SG_ERR |
RC_RDA_FAIL_WR_Rn, flag, &bar0->rc_err_mask);
do_s2io_write_bits(PRC_PCI_AB_RD_Rn | PRC_PCI_AB_WR_Rn |
PRC_PCI_AB_F_WR_Rn | PRC_PCI_DP_RD_Rn |
PRC_PCI_DP_WR_Rn | PRC_PCI_DP_F_WR_Rn, flag,
&bar0->prc_pcix_err_mask);
do_s2io_write_bits(RPA_SM_ERR_ALARM | RPA_CREDIT_ERR |
RPA_ECC_SG_ERR | RPA_ECC_DB_ERR, flag,
&bar0->rpa_err_mask);
do_s2io_write_bits(RDA_RXDn_ECC_DB_ERR | RDA_FRM_ECC_DB_N_AERR |
RDA_SM1_ERR_ALARM | RDA_SM0_ERR_ALARM |
RDA_RXD_ECC_DB_SERR | RDA_RXDn_ECC_SG_ERR |
RDA_FRM_ECC_SG_ERR |
RDA_MISC_ERR|RDA_PCIX_ERR,
flag, &bar0->rda_err_mask);
do_s2io_write_bits(RTI_SM_ERR_ALARM |
RTI_ECC_SG_ERR | RTI_ECC_DB_ERR,
flag, &bar0->rti_err_mask);
}
if (mask & RX_MAC_INTR) {
gen_int_mask |= RXMAC_INT_M;
do_s2io_write_bits(MAC_INT_STATUS_RMAC_INT, flag,
&bar0->mac_int_mask);
interruptible = (RMAC_RX_BUFF_OVRN | RMAC_RX_SM_ERR |
RMAC_UNUSED_INT | RMAC_SINGLE_ECC_ERR |
RMAC_DOUBLE_ECC_ERR);
if (s2io_link_fault_indication(nic) == MAC_RMAC_ERR_TIMER)
interruptible |= RMAC_LINK_STATE_CHANGE_INT;
do_s2io_write_bits(interruptible,
flag, &bar0->mac_rmac_err_mask);
}
if (mask & RX_XGXS_INTR) {
gen_int_mask |= RXXGXS_INT_M;
do_s2io_write_bits(XGXS_INT_STATUS_RXGXS, flag,
&bar0->xgxs_int_mask);
do_s2io_write_bits(RXGXS_ESTORE_OFLOW | RXGXS_RX_SM_ERR, flag,
&bar0->xgxs_rxgxs_err_mask);
}
if (mask & MC_INTR) {
gen_int_mask |= MC_INT_M;
do_s2io_write_bits(MC_INT_MASK_MC_INT,
flag, &bar0->mc_int_mask);
do_s2io_write_bits(MC_ERR_REG_SM_ERR | MC_ERR_REG_ECC_ALL_SNG |
MC_ERR_REG_ECC_ALL_DBL | PLL_LOCK_N, flag,
&bar0->mc_err_mask);
}
nic->general_int_mask = gen_int_mask;
/* Remove this line when alarm interrupts are enabled */
nic->general_int_mask = 0;
}
/**
* en_dis_able_nic_intrs - Enable or Disable the interrupts
* @nic: device private variable,
* @mask: A mask indicating which Intr block must be modified and,
* @flag: A flag indicating whether to enable or disable the Intrs.
* Description: This function will either disable or enable the interrupts
* depending on the flag argument. The mask argument can be used to
* enable/disable any Intr block.
* Return Value: NONE.
*/
static void en_dis_able_nic_intrs(struct s2io_nic *nic, u16 mask, int flag)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 temp64 = 0, intr_mask = 0;
intr_mask = nic->general_int_mask;
/* Top level interrupt classification */
/* PIC Interrupts */
if (mask & TX_PIC_INTR) {
/* Enable PIC Intrs in the general intr mask register */
intr_mask |= TXPIC_INT_M;
if (flag == ENABLE_INTRS) {
/*
* If Hercules adapter enable GPIO otherwise
* disable all PCIX, Flash, MDIO, IIC and GPIO
* interrupts for now.
* TODO
*/
if (s2io_link_fault_indication(nic) ==
LINK_UP_DOWN_INTERRUPT) {
do_s2io_write_bits(PIC_INT_GPIO, flag,
&bar0->pic_int_mask);
do_s2io_write_bits(GPIO_INT_MASK_LINK_UP, flag,
&bar0->gpio_int_mask);
} else
writeq(DISABLE_ALL_INTRS, &bar0->pic_int_mask);
} else if (flag == DISABLE_INTRS) {
/*
* Disable PIC Intrs in the general
* intr mask register
*/
writeq(DISABLE_ALL_INTRS, &bar0->pic_int_mask);
}
}
/* Tx traffic interrupts */
if (mask & TX_TRAFFIC_INTR) {
intr_mask |= TXTRAFFIC_INT_M;
if (flag == ENABLE_INTRS) {
/*
* Enable all the Tx side interrupts
* writing 0 Enables all 64 TX interrupt levels
*/
writeq(0x0, &bar0->tx_traffic_mask);
} else if (flag == DISABLE_INTRS) {
/*
* Disable Tx Traffic Intrs in the general intr mask
* register.
*/
writeq(DISABLE_ALL_INTRS, &bar0->tx_traffic_mask);
}
}
/* Rx traffic interrupts */
if (mask & RX_TRAFFIC_INTR) {
intr_mask |= RXTRAFFIC_INT_M;
if (flag == ENABLE_INTRS) {
/* writing 0 Enables all 8 RX interrupt levels */
writeq(0x0, &bar0->rx_traffic_mask);
} else if (flag == DISABLE_INTRS) {
/*
* Disable Rx Traffic Intrs in the general intr mask
* register.
*/
writeq(DISABLE_ALL_INTRS, &bar0->rx_traffic_mask);
}
}
temp64 = readq(&bar0->general_int_mask);
if (flag == ENABLE_INTRS)
temp64 &= ~((u64)intr_mask);
else
temp64 = DISABLE_ALL_INTRS;
writeq(temp64, &bar0->general_int_mask);
nic->general_int_mask = readq(&bar0->general_int_mask);
}
/**
* verify_pcc_quiescent- Checks for PCC quiescent state
* Return: 1 If PCC is quiescence
* 0 If PCC is not quiescence
*/
static int verify_pcc_quiescent(struct s2io_nic *sp, int flag)
{
int ret = 0, herc;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64 = readq(&bar0->adapter_status);
herc = (sp->device_type == XFRAME_II_DEVICE);
if (flag == false) {
if ((!herc && (sp->pdev->revision >= 4)) || herc) {
if (!(val64 & ADAPTER_STATUS_RMAC_PCC_IDLE))
ret = 1;
} else {
if (!(val64 & ADAPTER_STATUS_RMAC_PCC_FOUR_IDLE))
ret = 1;
}
} else {
if ((!herc && (sp->pdev->revision >= 4)) || herc) {
if (((val64 & ADAPTER_STATUS_RMAC_PCC_IDLE) ==
ADAPTER_STATUS_RMAC_PCC_IDLE))
ret = 1;
} else {
if (((val64 & ADAPTER_STATUS_RMAC_PCC_FOUR_IDLE) ==
ADAPTER_STATUS_RMAC_PCC_FOUR_IDLE))
ret = 1;
}
}
return ret;
}
/**
* verify_xena_quiescence - Checks whether the H/W is ready
* Description: Returns whether the H/W is ready to go or not. Depending
* on whether adapter enable bit was written or not the comparison
* differs and the calling function passes the input argument flag to
* indicate this.
* Return: 1 If xena is quiescence
* 0 If Xena is not quiescence
*/
static int verify_xena_quiescence(struct s2io_nic *sp)
{
int mode;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64 = readq(&bar0->adapter_status);
mode = s2io_verify_pci_mode(sp);
if (!(val64 & ADAPTER_STATUS_TDMA_READY)) {
DBG_PRINT(ERR_DBG, "TDMA is not ready!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_RDMA_READY)) {
DBG_PRINT(ERR_DBG, "RDMA is not ready!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_PFC_READY)) {
DBG_PRINT(ERR_DBG, "PFC is not ready!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_TMAC_BUF_EMPTY)) {
DBG_PRINT(ERR_DBG, "TMAC BUF is not empty!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_PIC_QUIESCENT)) {
DBG_PRINT(ERR_DBG, "PIC is not QUIESCENT!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_MC_DRAM_READY)) {
DBG_PRINT(ERR_DBG, "MC_DRAM is not ready!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_MC_QUEUES_READY)) {
DBG_PRINT(ERR_DBG, "MC_QUEUES is not ready!\n");
return 0;
}
if (!(val64 & ADAPTER_STATUS_M_PLL_LOCK)) {
DBG_PRINT(ERR_DBG, "M_PLL is not locked!\n");
return 0;
}
/*
* In PCI 33 mode, the P_PLL is not used, and therefore,
* the the P_PLL_LOCK bit in the adapter_status register will
* not be asserted.
*/
if (!(val64 & ADAPTER_STATUS_P_PLL_LOCK) &&
sp->device_type == XFRAME_II_DEVICE &&
mode != PCI_MODE_PCI_33) {
DBG_PRINT(ERR_DBG, "P_PLL is not locked!\n");
return 0;
}
if (!((val64 & ADAPTER_STATUS_RC_PRC_QUIESCENT) ==
ADAPTER_STATUS_RC_PRC_QUIESCENT)) {
DBG_PRINT(ERR_DBG, "RC_PRC is not QUIESCENT!\n");
return 0;
}
return 1;
}
/**
* fix_mac_address - Fix for Mac addr problem on Alpha platforms
* @sp: Pointer to device specifc structure
* Description :
* New procedure to clear mac address reading problems on Alpha platforms
*
*/
static void fix_mac_address(struct s2io_nic *sp)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
int i = 0;
while (fix_mac[i] != END_SIGN) {
writeq(fix_mac[i++], &bar0->gpio_control);
udelay(10);
(void) readq(&bar0->gpio_control);
}
}
/**
* start_nic - Turns the device on
* @nic : device private variable.
* Description:
* This function actually turns the device on. Before this function is
* called,all Registers are configured from their reset states
* and shared memory is allocated but the NIC is still quiescent. On
* calling this function, the device interrupts are cleared and the NIC is
* literally switched on by writing into the adapter control register.
* Return Value:
* SUCCESS on success and -1 on failure.
*/
static int start_nic(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
struct net_device *dev = nic->dev;
register u64 val64 = 0;
u16 subid, i;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
/* PRC Initialization and configuration */
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
writeq((u64)ring->rx_blocks[0].block_dma_addr,
&bar0->prc_rxd0_n[i]);
val64 = readq(&bar0->prc_ctrl_n[i]);
if (nic->rxd_mode == RXD_MODE_1)
val64 |= PRC_CTRL_RC_ENABLED;
else
val64 |= PRC_CTRL_RC_ENABLED | PRC_CTRL_RING_MODE_3;
if (nic->device_type == XFRAME_II_DEVICE)
val64 |= PRC_CTRL_GROUP_READS;
val64 &= ~PRC_CTRL_RXD_BACKOFF_INTERVAL(0xFFFFFF);
val64 |= PRC_CTRL_RXD_BACKOFF_INTERVAL(0x1000);
writeq(val64, &bar0->prc_ctrl_n[i]);
}
if (nic->rxd_mode == RXD_MODE_3B) {
/* Enabling 2 buffer mode by writing into Rx_pa_cfg reg. */
val64 = readq(&bar0->rx_pa_cfg);
val64 |= RX_PA_CFG_IGNORE_L2_ERR;
writeq(val64, &bar0->rx_pa_cfg);
}
if (vlan_tag_strip == 0) {
val64 = readq(&bar0->rx_pa_cfg);
val64 &= ~RX_PA_CFG_STRIP_VLAN_TAG;
writeq(val64, &bar0->rx_pa_cfg);
nic->vlan_strip_flag = 0;
}
/*
* Enabling MC-RLDRAM. After enabling the device, we timeout
* for around 100ms, which is approximately the time required
* for the device to be ready for operation.
*/
val64 = readq(&bar0->mc_rldram_mrs);
val64 |= MC_RLDRAM_QUEUE_SIZE_ENABLE | MC_RLDRAM_MRS_ENABLE;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_mrs, UF);
val64 = readq(&bar0->mc_rldram_mrs);
msleep(100); /* Delay by around 100 ms. */
/* Enabling ECC Protection. */
val64 = readq(&bar0->adapter_control);
val64 &= ~ADAPTER_ECC_EN;
writeq(val64, &bar0->adapter_control);
/*
* Verify if the device is ready to be enabled, if so enable
* it.
*/
val64 = readq(&bar0->adapter_status);
if (!verify_xena_quiescence(nic)) {
DBG_PRINT(ERR_DBG, "%s: device is not ready, "
"Adapter status reads: 0x%llx\n",
dev->name, (unsigned long long)val64);
return FAILURE;
}
/*
* With some switches, link might be already up at this point.
* Because of this weird behavior, when we enable laser,
* we may not get link. We need to handle this. We cannot
* figure out which switch is misbehaving. So we are forced to
* make a global change.
*/
/* Enabling Laser. */
val64 = readq(&bar0->adapter_control);
val64 |= ADAPTER_EOI_TX_ON;
writeq(val64, &bar0->adapter_control);
if (s2io_link_fault_indication(nic) == MAC_RMAC_ERR_TIMER) {
/*
* Dont see link state interrupts initially on some switches,
* so directly scheduling the link state task here.
*/
schedule_work(&nic->set_link_task);
}
/* SXE-002: Initialize link and activity LED */
subid = nic->pdev->subsystem_device;
if (((subid & 0xFF) >= 0x07) &&
(nic->device_type == XFRAME_I_DEVICE)) {
val64 = readq(&bar0->gpio_control);
val64 |= 0x0000800000000000ULL;
writeq(val64, &bar0->gpio_control);
val64 = 0x0411040400000000ULL;
writeq(val64, (void __iomem *)bar0 + 0x2700);
}
return SUCCESS;
}
/**
* s2io_txdl_getskb - Get the skb from txdl, unmap and return skb
*/
static struct sk_buff *s2io_txdl_getskb(struct fifo_info *fifo_data,
struct TxD *txdlp, int get_off)
{
struct s2io_nic *nic = fifo_data->nic;
struct sk_buff *skb;
struct TxD *txds;
u16 j, frg_cnt;
txds = txdlp;
if (txds->Host_Control == (u64)(long)fifo_data->ufo_in_band_v) {
pci_unmap_single(nic->pdev, (dma_addr_t)txds->Buffer_Pointer,
sizeof(u64), PCI_DMA_TODEVICE);
txds++;
}
skb = (struct sk_buff *)((unsigned long)txds->Host_Control);
if (!skb) {
memset(txdlp, 0, (sizeof(struct TxD) * fifo_data->max_txds));
return NULL;
}
pci_unmap_single(nic->pdev, (dma_addr_t)txds->Buffer_Pointer,
skb_headlen(skb), PCI_DMA_TODEVICE);
frg_cnt = skb_shinfo(skb)->nr_frags;
if (frg_cnt) {
txds++;
for (j = 0; j < frg_cnt; j++, txds++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[j];
if (!txds->Buffer_Pointer)
break;
pci_unmap_page(nic->pdev,
(dma_addr_t)txds->Buffer_Pointer,
skb_frag_size(frag), PCI_DMA_TODEVICE);
}
}
memset(txdlp, 0, (sizeof(struct TxD) * fifo_data->max_txds));
return skb;
}
/**
* free_tx_buffers - Free all queued Tx buffers
* @nic : device private variable.
* Description:
* Free all queued Tx buffers.
* Return Value: void
*/
static void free_tx_buffers(struct s2io_nic *nic)
{
struct net_device *dev = nic->dev;
struct sk_buff *skb;
struct TxD *txdp;
int i, j;
int cnt = 0;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
struct stat_block *stats = mac_control->stats_info;
struct swStat *swstats = &stats->sw_stat;
for (i = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
struct fifo_info *fifo = &mac_control->fifos[i];
unsigned long flags;
spin_lock_irqsave(&fifo->tx_lock, flags);
for (j = 0; j < tx_cfg->fifo_len; j++) {
txdp = fifo->list_info[j].list_virt_addr;
skb = s2io_txdl_getskb(&mac_control->fifos[i], txdp, j);
if (skb) {
swstats->mem_freed += skb->truesize;
dev_kfree_skb(skb);
cnt++;
}
}
DBG_PRINT(INTR_DBG,
"%s: forcibly freeing %d skbs on FIFO%d\n",
dev->name, cnt, i);
fifo->tx_curr_get_info.offset = 0;
fifo->tx_curr_put_info.offset = 0;
spin_unlock_irqrestore(&fifo->tx_lock, flags);
}
}
/**
* stop_nic - To stop the nic
* @nic ; device private variable.
* Description:
* This function does exactly the opposite of what the start_nic()
* function does. This function is called to stop the device.
* Return Value:
* void.
*/
static void stop_nic(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64 = 0;
u16 interruptible;
/* Disable all interrupts */
en_dis_err_alarms(nic, ENA_ALL_INTRS, DISABLE_INTRS);
interruptible = TX_TRAFFIC_INTR | RX_TRAFFIC_INTR;
interruptible |= TX_PIC_INTR;
en_dis_able_nic_intrs(nic, interruptible, DISABLE_INTRS);
/* Clearing Adapter_En bit of ADAPTER_CONTROL Register */
val64 = readq(&bar0->adapter_control);
val64 &= ~(ADAPTER_CNTL_EN);
writeq(val64, &bar0->adapter_control);
}
/**
* fill_rx_buffers - Allocates the Rx side skbs
* @ring_info: per ring structure
* @from_card_up: If this is true, we will map the buffer to get
* the dma address for buf0 and buf1 to give it to the card.
* Else we will sync the already mapped buffer to give it to the card.
* Description:
* The function allocates Rx side skbs and puts the physical
* address of these buffers into the RxD buffer pointers, so that the NIC
* can DMA the received frame into these locations.
* The NIC supports 3 receive modes, viz
* 1. single buffer,
* 2. three buffer and
* 3. Five buffer modes.
* Each mode defines how many fragments the received frame will be split
* up into by the NIC. The frame is split into L3 header, L4 Header,
* L4 payload in three buffer mode and in 5 buffer mode, L4 payload itself
* is split into 3 fragments. As of now only single buffer mode is
* supported.
* Return Value:
* SUCCESS on success or an appropriate -ve value on failure.
*/
static int fill_rx_buffers(struct s2io_nic *nic, struct ring_info *ring,
int from_card_up)
{
struct sk_buff *skb;
struct RxD_t *rxdp;
int off, size, block_no, block_no1;
u32 alloc_tab = 0;
u32 alloc_cnt;
u64 tmp;
struct buffAdd *ba;
struct RxD_t *first_rxdp = NULL;
u64 Buffer0_ptr = 0, Buffer1_ptr = 0;
int rxd_index = 0;
struct RxD1 *rxdp1;
struct RxD3 *rxdp3;
struct swStat *swstats = &ring->nic->mac_control.stats_info->sw_stat;
alloc_cnt = ring->pkt_cnt - ring->rx_bufs_left;
block_no1 = ring->rx_curr_get_info.block_index;
while (alloc_tab < alloc_cnt) {
block_no = ring->rx_curr_put_info.block_index;
off = ring->rx_curr_put_info.offset;
rxdp = ring->rx_blocks[block_no].rxds[off].virt_addr;
rxd_index = off + 1;
if (block_no)
rxd_index += (block_no * ring->rxd_count);
if ((block_no == block_no1) &&
(off == ring->rx_curr_get_info.offset) &&
(rxdp->Host_Control)) {
DBG_PRINT(INTR_DBG, "%s: Get and Put info equated\n",
ring->dev->name);
goto end;
}
if (off && (off == ring->rxd_count)) {
ring->rx_curr_put_info.block_index++;
if (ring->rx_curr_put_info.block_index ==
ring->block_count)
ring->rx_curr_put_info.block_index = 0;
block_no = ring->rx_curr_put_info.block_index;
off = 0;
ring->rx_curr_put_info.offset = off;
rxdp = ring->rx_blocks[block_no].block_virt_addr;
DBG_PRINT(INTR_DBG, "%s: Next block at: %p\n",
ring->dev->name, rxdp);
}
if ((rxdp->Control_1 & RXD_OWN_XENA) &&
((ring->rxd_mode == RXD_MODE_3B) &&
(rxdp->Control_2 & s2BIT(0)))) {
ring->rx_curr_put_info.offset = off;
goto end;
}
/* calculate size of skb based on ring mode */
size = ring->mtu +
HEADER_ETHERNET_II_802_3_SIZE +
HEADER_802_2_SIZE + HEADER_SNAP_SIZE;
if (ring->rxd_mode == RXD_MODE_1)
size += NET_IP_ALIGN;
else
size = ring->mtu + ALIGN_SIZE + BUF0_LEN + 4;
/* allocate skb */
skb = netdev_alloc_skb(nic->dev, size);
if (!skb) {
DBG_PRINT(INFO_DBG, "%s: Could not allocate skb\n",
ring->dev->name);
if (first_rxdp) {
wmb();
first_rxdp->Control_1 |= RXD_OWN_XENA;
}
swstats->mem_alloc_fail_cnt++;
return -ENOMEM ;
}
swstats->mem_allocated += skb->truesize;
if (ring->rxd_mode == RXD_MODE_1) {
/* 1 buffer mode - normal operation mode */
rxdp1 = (struct RxD1 *)rxdp;
memset(rxdp, 0, sizeof(struct RxD1));
skb_reserve(skb, NET_IP_ALIGN);
rxdp1->Buffer0_ptr =
pci_map_single(ring->pdev, skb->data,
size - NET_IP_ALIGN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(nic->pdev,
rxdp1->Buffer0_ptr))
goto pci_map_failed;
rxdp->Control_2 =
SET_BUFFER0_SIZE_1(size - NET_IP_ALIGN);
rxdp->Host_Control = (unsigned long)skb;
} else if (ring->rxd_mode == RXD_MODE_3B) {
/*
* 2 buffer mode -
* 2 buffer mode provides 128
* byte aligned receive buffers.
*/
rxdp3 = (struct RxD3 *)rxdp;
/* save buffer pointers to avoid frequent dma mapping */
Buffer0_ptr = rxdp3->Buffer0_ptr;
Buffer1_ptr = rxdp3->Buffer1_ptr;
memset(rxdp, 0, sizeof(struct RxD3));
/* restore the buffer pointers for dma sync*/
rxdp3->Buffer0_ptr = Buffer0_ptr;
rxdp3->Buffer1_ptr = Buffer1_ptr;
ba = &ring->ba[block_no][off];
skb_reserve(skb, BUF0_LEN);
tmp = (u64)(unsigned long)skb->data;
tmp += ALIGN_SIZE;
tmp &= ~ALIGN_SIZE;
skb->data = (void *) (unsigned long)tmp;
skb_reset_tail_pointer(skb);
if (from_card_up) {
rxdp3->Buffer0_ptr =
pci_map_single(ring->pdev, ba->ba_0,
BUF0_LEN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(nic->pdev,
rxdp3->Buffer0_ptr))
goto pci_map_failed;
} else
pci_dma_sync_single_for_device(ring->pdev,
(dma_addr_t)rxdp3->Buffer0_ptr,
BUF0_LEN,
PCI_DMA_FROMDEVICE);
rxdp->Control_2 = SET_BUFFER0_SIZE_3(BUF0_LEN);
if (ring->rxd_mode == RXD_MODE_3B) {
/* Two buffer mode */
/*
* Buffer2 will have L3/L4 header plus
* L4 payload
*/
rxdp3->Buffer2_ptr = pci_map_single(ring->pdev,
skb->data,
ring->mtu + 4,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(nic->pdev,
rxdp3->Buffer2_ptr))
goto pci_map_failed;
if (from_card_up) {
rxdp3->Buffer1_ptr =
pci_map_single(ring->pdev,
ba->ba_1,
BUF1_LEN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(nic->pdev,
rxdp3->Buffer1_ptr)) {
pci_unmap_single(ring->pdev,
(dma_addr_t)(unsigned long)
skb->data,
ring->mtu + 4,
PCI_DMA_FROMDEVICE);
goto pci_map_failed;
}
}
rxdp->Control_2 |= SET_BUFFER1_SIZE_3(1);
rxdp->Control_2 |= SET_BUFFER2_SIZE_3
(ring->mtu + 4);
}
rxdp->Control_2 |= s2BIT(0);
rxdp->Host_Control = (unsigned long) (skb);
}
if (alloc_tab & ((1 << rxsync_frequency) - 1))
rxdp->Control_1 |= RXD_OWN_XENA;
off++;
if (off == (ring->rxd_count + 1))
off = 0;
ring->rx_curr_put_info.offset = off;
rxdp->Control_2 |= SET_RXD_MARKER;
if (!(alloc_tab & ((1 << rxsync_frequency) - 1))) {
if (first_rxdp) {
wmb();
first_rxdp->Control_1 |= RXD_OWN_XENA;
}
first_rxdp = rxdp;
}
ring->rx_bufs_left += 1;
alloc_tab++;
}
end:
/* Transfer ownership of first descriptor to adapter just before
* exiting. Before that, use memory barrier so that ownership
* and other fields are seen by adapter correctly.
*/
if (first_rxdp) {
wmb();
first_rxdp->Control_1 |= RXD_OWN_XENA;
}
return SUCCESS;
pci_map_failed:
swstats->pci_map_fail_cnt++;
swstats->mem_freed += skb->truesize;
dev_kfree_skb_irq(skb);
return -ENOMEM;
}
static void free_rxd_blk(struct s2io_nic *sp, int ring_no, int blk)
{
struct net_device *dev = sp->dev;
int j;
struct sk_buff *skb;
struct RxD_t *rxdp;
struct RxD1 *rxdp1;
struct RxD3 *rxdp3;
struct mac_info *mac_control = &sp->mac_control;
struct stat_block *stats = mac_control->stats_info;
struct swStat *swstats = &stats->sw_stat;
for (j = 0 ; j < rxd_count[sp->rxd_mode]; j++) {
rxdp = mac_control->rings[ring_no].
rx_blocks[blk].rxds[j].virt_addr;
skb = (struct sk_buff *)((unsigned long)rxdp->Host_Control);
if (!skb)
continue;
if (sp->rxd_mode == RXD_MODE_1) {
rxdp1 = (struct RxD1 *)rxdp;
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp1->Buffer0_ptr,
dev->mtu +
HEADER_ETHERNET_II_802_3_SIZE +
HEADER_802_2_SIZE + HEADER_SNAP_SIZE,
PCI_DMA_FROMDEVICE);
memset(rxdp, 0, sizeof(struct RxD1));
} else if (sp->rxd_mode == RXD_MODE_3B) {
rxdp3 = (struct RxD3 *)rxdp;
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer0_ptr,
BUF0_LEN,
PCI_DMA_FROMDEVICE);
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer1_ptr,
BUF1_LEN,
PCI_DMA_FROMDEVICE);
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer2_ptr,
dev->mtu + 4,
PCI_DMA_FROMDEVICE);
memset(rxdp, 0, sizeof(struct RxD3));
}
swstats->mem_freed += skb->truesize;
dev_kfree_skb(skb);
mac_control->rings[ring_no].rx_bufs_left -= 1;
}
}
/**
* free_rx_buffers - Frees all Rx buffers
* @sp: device private variable.
* Description:
* This function will free all Rx buffers allocated by host.
* Return Value:
* NONE.
*/
static void free_rx_buffers(struct s2io_nic *sp)
{
struct net_device *dev = sp->dev;
int i, blk = 0, buf_cnt = 0;
struct config_param *config = &sp->config;
struct mac_info *mac_control = &sp->mac_control;
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
for (blk = 0; blk < rx_ring_sz[i]; blk++)
free_rxd_blk(sp, i, blk);
ring->rx_curr_put_info.block_index = 0;
ring->rx_curr_get_info.block_index = 0;
ring->rx_curr_put_info.offset = 0;
ring->rx_curr_get_info.offset = 0;
ring->rx_bufs_left = 0;
DBG_PRINT(INIT_DBG, "%s: Freed 0x%x Rx Buffers on ring%d\n",
dev->name, buf_cnt, i);
}
}
static int s2io_chk_rx_buffers(struct s2io_nic *nic, struct ring_info *ring)
{
if (fill_rx_buffers(nic, ring, 0) == -ENOMEM) {
DBG_PRINT(INFO_DBG, "%s: Out of memory in Rx Intr!!\n",
ring->dev->name);
}
return 0;
}
/**
* s2io_poll - Rx interrupt handler for NAPI support
* @napi : pointer to the napi structure.
* @budget : The number of packets that were budgeted to be processed
* during one pass through the 'Poll" function.
* Description:
* Comes into picture only if NAPI support has been incorporated. It does
* the same thing that rx_intr_handler does, but not in a interrupt context
* also It will process only a given number of packets.
* Return value:
* 0 on success and 1 if there are No Rx packets to be processed.
*/
static int s2io_poll_msix(struct napi_struct *napi, int budget)
{
struct ring_info *ring = container_of(napi, struct ring_info, napi);
struct net_device *dev = ring->dev;
int pkts_processed = 0;
u8 __iomem *addr = NULL;
u8 val8 = 0;
struct s2io_nic *nic = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = nic->bar0;
int budget_org = budget;
if (unlikely(!is_s2io_card_up(nic)))
return 0;
pkts_processed = rx_intr_handler(ring, budget);
s2io_chk_rx_buffers(nic, ring);
if (pkts_processed < budget_org) {
napi_complete(napi);
/*Re Enable MSI-Rx Vector*/
addr = (u8 __iomem *)&bar0->xmsi_mask_reg;
addr += 7 - ring->ring_no;
val8 = (ring->ring_no == 0) ? 0x3f : 0xbf;
writeb(val8, addr);
val8 = readb(addr);
}
return pkts_processed;
}
static int s2io_poll_inta(struct napi_struct *napi, int budget)
{
struct s2io_nic *nic = container_of(napi, struct s2io_nic, napi);
int pkts_processed = 0;
int ring_pkts_processed, i;
struct XENA_dev_config __iomem *bar0 = nic->bar0;
int budget_org = budget;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
if (unlikely(!is_s2io_card_up(nic)))
return 0;
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
ring_pkts_processed = rx_intr_handler(ring, budget);
s2io_chk_rx_buffers(nic, ring);
pkts_processed += ring_pkts_processed;
budget -= ring_pkts_processed;
if (budget <= 0)
break;
}
if (pkts_processed < budget_org) {
napi_complete(napi);
/* Re enable the Rx interrupts for the ring */
writeq(0, &bar0->rx_traffic_mask);
readl(&bar0->rx_traffic_mask);
}
return pkts_processed;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/**
* s2io_netpoll - netpoll event handler entry point
* @dev : pointer to the device structure.
* Description:
* This function will be called by upper layer to check for events on the
* interface in situations where interrupts are disabled. It is used for
* specific in-kernel networking tasks, such as remote consoles and kernel
* debugging over the network (example netdump in RedHat).
*/
static void s2io_netpoll(struct net_device *dev)
{
struct s2io_nic *nic = netdev_priv(dev);
const int irq = nic->pdev->irq;
struct XENA_dev_config __iomem *bar0 = nic->bar0;
u64 val64 = 0xFFFFFFFFFFFFFFFFULL;
int i;
struct config_param *config = &nic->config;
struct mac_info *mac_control = &nic->mac_control;
if (pci_channel_offline(nic->pdev))
return;
disable_irq(irq);
writeq(val64, &bar0->rx_traffic_int);
writeq(val64, &bar0->tx_traffic_int);
/* we need to free up the transmitted skbufs or else netpoll will
* run out of skbs and will fail and eventually netpoll application such
* as netdump will fail.
*/
for (i = 0; i < config->tx_fifo_num; i++)
tx_intr_handler(&mac_control->fifos[i]);
/* check for received packet and indicate up to network */
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
rx_intr_handler(ring, 0);
}
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
if (fill_rx_buffers(nic, ring, 0) == -ENOMEM) {
DBG_PRINT(INFO_DBG,
"%s: Out of memory in Rx Netpoll!!\n",
dev->name);
break;
}
}
enable_irq(irq);
}
#endif
/**
* rx_intr_handler - Rx interrupt handler
* @ring_info: per ring structure.
* @budget: budget for napi processing.
* Description:
* If the interrupt is because of a received frame or if the
* receive ring contains fresh as yet un-processed frames,this function is
* called. It picks out the RxD at which place the last Rx processing had
* stopped and sends the skb to the OSM's Rx handler and then increments
* the offset.
* Return Value:
* No. of napi packets processed.
*/
static int rx_intr_handler(struct ring_info *ring_data, int budget)
{
int get_block, put_block;
struct rx_curr_get_info get_info, put_info;
struct RxD_t *rxdp;
struct sk_buff *skb;
int pkt_cnt = 0, napi_pkts = 0;
int i;
struct RxD1 *rxdp1;
struct RxD3 *rxdp3;
get_info = ring_data->rx_curr_get_info;
get_block = get_info.block_index;
memcpy(&put_info, &ring_data->rx_curr_put_info, sizeof(put_info));
put_block = put_info.block_index;
rxdp = ring_data->rx_blocks[get_block].rxds[get_info.offset].virt_addr;
while (RXD_IS_UP2DT(rxdp)) {
/*
* If your are next to put index then it's
* FIFO full condition
*/
if ((get_block == put_block) &&
(get_info.offset + 1) == put_info.offset) {
DBG_PRINT(INTR_DBG, "%s: Ring Full\n",
ring_data->dev->name);
break;
}
skb = (struct sk_buff *)((unsigned long)rxdp->Host_Control);
if (skb == NULL) {
DBG_PRINT(ERR_DBG, "%s: NULL skb in Rx Intr\n",
ring_data->dev->name);
return 0;
}
if (ring_data->rxd_mode == RXD_MODE_1) {
rxdp1 = (struct RxD1 *)rxdp;
pci_unmap_single(ring_data->pdev, (dma_addr_t)
rxdp1->Buffer0_ptr,
ring_data->mtu +
HEADER_ETHERNET_II_802_3_SIZE +
HEADER_802_2_SIZE +
HEADER_SNAP_SIZE,
PCI_DMA_FROMDEVICE);
} else if (ring_data->rxd_mode == RXD_MODE_3B) {
rxdp3 = (struct RxD3 *)rxdp;
pci_dma_sync_single_for_cpu(ring_data->pdev,
(dma_addr_t)rxdp3->Buffer0_ptr,
BUF0_LEN,
PCI_DMA_FROMDEVICE);
pci_unmap_single(ring_data->pdev,
(dma_addr_t)rxdp3->Buffer2_ptr,
ring_data->mtu + 4,
PCI_DMA_FROMDEVICE);
}
prefetch(skb->data);
rx_osm_handler(ring_data, rxdp);
get_info.offset++;
ring_data->rx_curr_get_info.offset = get_info.offset;
rxdp = ring_data->rx_blocks[get_block].
rxds[get_info.offset].virt_addr;
if (get_info.offset == rxd_count[ring_data->rxd_mode]) {
get_info.offset = 0;
ring_data->rx_curr_get_info.offset = get_info.offset;
get_block++;
if (get_block == ring_data->block_count)
get_block = 0;
ring_data->rx_curr_get_info.block_index = get_block;
rxdp = ring_data->rx_blocks[get_block].block_virt_addr;
}
if (ring_data->nic->config.napi) {
budget--;
napi_pkts++;
if (!budget)
break;
}
pkt_cnt++;
if ((indicate_max_pkts) && (pkt_cnt > indicate_max_pkts))
break;
}
if (ring_data->lro) {
/* Clear all LRO sessions before exiting */
for (i = 0; i < MAX_LRO_SESSIONS; i++) {
struct lro *lro = &ring_data->lro0_n[i];
if (lro->in_use) {
update_L3L4_header(ring_data->nic, lro);
queue_rx_frame(lro->parent, lro->vlan_tag);
clear_lro_session(lro);
}
}
}
return napi_pkts;
}
/**
* tx_intr_handler - Transmit interrupt handler
* @nic : device private variable
* Description:
* If an interrupt was raised to indicate DMA complete of the
* Tx packet, this function is called. It identifies the last TxD
* whose buffer was freed and frees all skbs whose data have already
* DMA'ed into the NICs internal memory.
* Return Value:
* NONE
*/
static void tx_intr_handler(struct fifo_info *fifo_data)
{
struct s2io_nic *nic = fifo_data->nic;
struct tx_curr_get_info get_info, put_info;
struct sk_buff *skb = NULL;
struct TxD *txdlp;
int pkt_cnt = 0;
unsigned long flags = 0;
u8 err_mask;
struct stat_block *stats = nic->mac_control.stats_info;
struct swStat *swstats = &stats->sw_stat;
if (!spin_trylock_irqsave(&fifo_data->tx_lock, flags))
return;
get_info = fifo_data->tx_curr_get_info;
memcpy(&put_info, &fifo_data->tx_curr_put_info, sizeof(put_info));
txdlp = fifo_data->list_info[get_info.offset].list_virt_addr;
while ((!(txdlp->Control_1 & TXD_LIST_OWN_XENA)) &&
(get_info.offset != put_info.offset) &&
(txdlp->Host_Control)) {
/* Check for TxD errors */
if (txdlp->Control_1 & TXD_T_CODE) {
unsigned long long err;
err = txdlp->Control_1 & TXD_T_CODE;
if (err & 0x1) {
swstats->parity_err_cnt++;
}
/* update t_code statistics */
err_mask = err >> 48;
switch (err_mask) {
case 2:
swstats->tx_buf_abort_cnt++;
break;
case 3:
swstats->tx_desc_abort_cnt++;
break;
case 7:
swstats->tx_parity_err_cnt++;
break;
case 10:
swstats->tx_link_loss_cnt++;
break;
case 15:
swstats->tx_list_proc_err_cnt++;
break;
}
}
skb = s2io_txdl_getskb(fifo_data, txdlp, get_info.offset);
if (skb == NULL) {
spin_unlock_irqrestore(&fifo_data->tx_lock, flags);
DBG_PRINT(ERR_DBG, "%s: NULL skb in Tx Free Intr\n",
__func__);
return;
}
pkt_cnt++;
/* Updating the statistics block */
swstats->mem_freed += skb->truesize;
dev_kfree_skb_irq(skb);
get_info.offset++;
if (get_info.offset == get_info.fifo_len + 1)
get_info.offset = 0;
txdlp = fifo_data->list_info[get_info.offset].list_virt_addr;
fifo_data->tx_curr_get_info.offset = get_info.offset;
}
s2io_wake_tx_queue(fifo_data, pkt_cnt, nic->config.multiq);
spin_unlock_irqrestore(&fifo_data->tx_lock, flags);
}
/**
* s2io_mdio_write - Function to write in to MDIO registers
* @mmd_type : MMD type value (PMA/PMD/WIS/PCS/PHYXS)
* @addr : address value
* @value : data value
* @dev : pointer to net_device structure
* Description:
* This function is used to write values to the MDIO registers
* NONE
*/
static void s2io_mdio_write(u32 mmd_type, u64 addr, u16 value,
struct net_device *dev)
{
u64 val64;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
/* address transaction */
val64 = MDIO_MMD_INDX_ADDR(addr) |
MDIO_MMD_DEV_ADDR(mmd_type) |
MDIO_MMS_PRT_ADDR(0x0);
writeq(val64, &bar0->mdio_control);
val64 = val64 | MDIO_CTRL_START_TRANS(0xE);
writeq(val64, &bar0->mdio_control);
udelay(100);
/* Data transaction */
val64 = MDIO_MMD_INDX_ADDR(addr) |
MDIO_MMD_DEV_ADDR(mmd_type) |
MDIO_MMS_PRT_ADDR(0x0) |
MDIO_MDIO_DATA(value) |
MDIO_OP(MDIO_OP_WRITE_TRANS);
writeq(val64, &bar0->mdio_control);
val64 = val64 | MDIO_CTRL_START_TRANS(0xE);
writeq(val64, &bar0->mdio_control);
udelay(100);
val64 = MDIO_MMD_INDX_ADDR(addr) |
MDIO_MMD_DEV_ADDR(mmd_type) |
MDIO_MMS_PRT_ADDR(0x0) |
MDIO_OP(MDIO_OP_READ_TRANS);
writeq(val64, &bar0->mdio_control);
val64 = val64 | MDIO_CTRL_START_TRANS(0xE);
writeq(val64, &bar0->mdio_control);
udelay(100);
}
/**
* s2io_mdio_read - Function to write in to MDIO registers
* @mmd_type : MMD type value (PMA/PMD/WIS/PCS/PHYXS)
* @addr : address value
* @dev : pointer to net_device structure
* Description:
* This function is used to read values to the MDIO registers
* NONE
*/
static u64 s2io_mdio_read(u32 mmd_type, u64 addr, struct net_device *dev)
{
u64 val64 = 0x0;
u64 rval64 = 0x0;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
/* address transaction */
val64 = val64 | (MDIO_MMD_INDX_ADDR(addr)
| MDIO_MMD_DEV_ADDR(mmd_type)
| MDIO_MMS_PRT_ADDR(0x0));
writeq(val64, &bar0->mdio_control);
val64 = val64 | MDIO_CTRL_START_TRANS(0xE);
writeq(val64, &bar0->mdio_control);
udelay(100);
/* Data transaction */
val64 = MDIO_MMD_INDX_ADDR(addr) |
MDIO_MMD_DEV_ADDR(mmd_type) |
MDIO_MMS_PRT_ADDR(0x0) |
MDIO_OP(MDIO_OP_READ_TRANS);
writeq(val64, &bar0->mdio_control);
val64 = val64 | MDIO_CTRL_START_TRANS(0xE);
writeq(val64, &bar0->mdio_control);
udelay(100);
/* Read the value from regs */
rval64 = readq(&bar0->mdio_control);
rval64 = rval64 & 0xFFFF0000;
rval64 = rval64 >> 16;
return rval64;
}
/**
* s2io_chk_xpak_counter - Function to check the status of the xpak counters
* @counter : counter value to be updated
* @flag : flag to indicate the status
* @type : counter type
* Description:
* This function is to check the status of the xpak counters value
* NONE
*/
static void s2io_chk_xpak_counter(u64 *counter, u64 * regs_stat, u32 index,
u16 flag, u16 type)
{
u64 mask = 0x3;
u64 val64;
int i;
for (i = 0; i < index; i++)
mask = mask << 0x2;
if (flag > 0) {
*counter = *counter + 1;
val64 = *regs_stat & mask;
val64 = val64 >> (index * 0x2);
val64 = val64 + 1;
if (val64 == 3) {
switch (type) {
case 1:
DBG_PRINT(ERR_DBG,
"Take Xframe NIC out of service.\n");
DBG_PRINT(ERR_DBG,
"Excessive temperatures may result in premature transceiver failure.\n");
break;
case 2:
DBG_PRINT(ERR_DBG,
"Take Xframe NIC out of service.\n");
DBG_PRINT(ERR_DBG,
"Excessive bias currents may indicate imminent laser diode failure.\n");
break;
case 3:
DBG_PRINT(ERR_DBG,
"Take Xframe NIC out of service.\n");
DBG_PRINT(ERR_DBG,
"Excessive laser output power may saturate far-end receiver.\n");
break;
default:
DBG_PRINT(ERR_DBG,
"Incorrect XPAK Alarm type\n");
}
val64 = 0x0;
}
val64 = val64 << (index * 0x2);
*regs_stat = (*regs_stat & (~mask)) | (val64);
} else {
*regs_stat = *regs_stat & (~mask);
}
}
/**
* s2io_updt_xpak_counter - Function to update the xpak counters
* @dev : pointer to net_device struct
* Description:
* This function is to upate the status of the xpak counters value
* NONE
*/
static void s2io_updt_xpak_counter(struct net_device *dev)
{
u16 flag = 0x0;
u16 type = 0x0;
u16 val16 = 0x0;
u64 val64 = 0x0;
u64 addr = 0x0;
struct s2io_nic *sp = netdev_priv(dev);
struct stat_block *stats = sp->mac_control.stats_info;
struct xpakStat *xstats = &stats->xpak_stat;
/* Check the communication with the MDIO slave */
addr = MDIO_CTRL1;
val64 = 0x0;
val64 = s2io_mdio_read(MDIO_MMD_PMAPMD, addr, dev);
if ((val64 == 0xFFFF) || (val64 == 0x0000)) {
DBG_PRINT(ERR_DBG,
"ERR: MDIO slave access failed - Returned %llx\n",
(unsigned long long)val64);
return;
}
/* Check for the expected value of control reg 1 */
if (val64 != MDIO_CTRL1_SPEED10G) {
DBG_PRINT(ERR_DBG, "Incorrect value at PMA address 0x0000 - "
"Returned: %llx- Expected: 0x%x\n",
(unsigned long long)val64, MDIO_CTRL1_SPEED10G);
return;
}
/* Loading the DOM register to MDIO register */
addr = 0xA100;
s2io_mdio_write(MDIO_MMD_PMAPMD, addr, val16, dev);
val64 = s2io_mdio_read(MDIO_MMD_PMAPMD, addr, dev);
/* Reading the Alarm flags */
addr = 0xA070;
val64 = 0x0;
val64 = s2io_mdio_read(MDIO_MMD_PMAPMD, addr, dev);
flag = CHECKBIT(val64, 0x7);
type = 1;
s2io_chk_xpak_counter(&xstats->alarm_transceiver_temp_high,
&xstats->xpak_regs_stat,
0x0, flag, type);
if (CHECKBIT(val64, 0x6))
xstats->alarm_transceiver_temp_low++;
flag = CHECKBIT(val64, 0x3);
type = 2;
s2io_chk_xpak_counter(&xstats->alarm_laser_bias_current_high,
&xstats->xpak_regs_stat,
0x2, flag, type);
if (CHECKBIT(val64, 0x2))
xstats->alarm_laser_bias_current_low++;
flag = CHECKBIT(val64, 0x1);
type = 3;
s2io_chk_xpak_counter(&xstats->alarm_laser_output_power_high,
&xstats->xpak_regs_stat,
0x4, flag, type);
if (CHECKBIT(val64, 0x0))
xstats->alarm_laser_output_power_low++;
/* Reading the Warning flags */
addr = 0xA074;
val64 = 0x0;
val64 = s2io_mdio_read(MDIO_MMD_PMAPMD, addr, dev);
if (CHECKBIT(val64, 0x7))
xstats->warn_transceiver_temp_high++;
if (CHECKBIT(val64, 0x6))
xstats->warn_transceiver_temp_low++;
if (CHECKBIT(val64, 0x3))
xstats->warn_laser_bias_current_high++;
if (CHECKBIT(val64, 0x2))
xstats->warn_laser_bias_current_low++;
if (CHECKBIT(val64, 0x1))
xstats->warn_laser_output_power_high++;
if (CHECKBIT(val64, 0x0))
xstats->warn_laser_output_power_low++;
}
/**
* wait_for_cmd_complete - waits for a command to complete.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* Description: Function that waits for a command to Write into RMAC
* ADDR DATA registers to be completed and returns either success or
* error depending on whether the command was complete or not.
* Return value:
* SUCCESS on success and FAILURE on failure.
*/
static int wait_for_cmd_complete(void __iomem *addr, u64 busy_bit,
int bit_state)
{
int ret = FAILURE, cnt = 0, delay = 1;
u64 val64;
if ((bit_state != S2IO_BIT_RESET) && (bit_state != S2IO_BIT_SET))
return FAILURE;
do {
val64 = readq(addr);
if (bit_state == S2IO_BIT_RESET) {
if (!(val64 & busy_bit)) {
ret = SUCCESS;
break;
}
} else {
if (val64 & busy_bit) {
ret = SUCCESS;
break;
}
}
if (in_interrupt())
mdelay(delay);
else
msleep(delay);
if (++cnt >= 10)
delay = 50;
} while (cnt < 20);
return ret;
}
/*
* check_pci_device_id - Checks if the device id is supported
* @id : device id
* Description: Function to check if the pci device id is supported by driver.
* Return value: Actual device id if supported else PCI_ANY_ID
*/
static u16 check_pci_device_id(u16 id)
{
switch (id) {
case PCI_DEVICE_ID_HERC_WIN:
case PCI_DEVICE_ID_HERC_UNI:
return XFRAME_II_DEVICE;
case PCI_DEVICE_ID_S2IO_UNI:
case PCI_DEVICE_ID_S2IO_WIN:
return XFRAME_I_DEVICE;
default:
return PCI_ANY_ID;
}
}
/**
* s2io_reset - Resets the card.
* @sp : private member of the device structure.
* Description: Function to Reset the card. This function then also
* restores the previously saved PCI configuration space registers as
* the card reset also resets the configuration space.
* Return value:
* void.
*/
static void s2io_reset(struct s2io_nic *sp)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64;
u16 subid, pci_cmd;
int i;
u16 val16;
unsigned long long up_cnt, down_cnt, up_time, down_time, reset_cnt;
unsigned long long mem_alloc_cnt, mem_free_cnt, watchdog_cnt;
struct stat_block *stats;
struct swStat *swstats;
DBG_PRINT(INIT_DBG, "%s: Resetting XFrame card %s\n",
__func__, pci_name(sp->pdev));
/* Back up the PCI-X CMD reg, dont want to lose MMRBC, OST settings */
pci_read_config_word(sp->pdev, PCIX_COMMAND_REGISTER, &(pci_cmd));
val64 = SW_RESET_ALL;
writeq(val64, &bar0->sw_reset);
if (strstr(sp->product_name, "CX4"))
msleep(750);
msleep(250);
for (i = 0; i < S2IO_MAX_PCI_CONFIG_SPACE_REINIT; i++) {
/* Restore the PCI state saved during initialization. */
pci_restore_state(sp->pdev);
pci_save_state(sp->pdev);
pci_read_config_word(sp->pdev, 0x2, &val16);
if (check_pci_device_id(val16) != (u16)PCI_ANY_ID)
break;
msleep(200);
}
if (check_pci_device_id(val16) == (u16)PCI_ANY_ID)
DBG_PRINT(ERR_DBG, "%s SW_Reset failed!\n", __func__);
pci_write_config_word(sp->pdev, PCIX_COMMAND_REGISTER, pci_cmd);
s2io_init_pci(sp);
/* Set swapper to enable I/O register access */
s2io_set_swapper(sp);
/* restore mac_addr entries */
do_s2io_restore_unicast_mc(sp);
/* Restore the MSIX table entries from local variables */
restore_xmsi_data(sp);
/* Clear certain PCI/PCI-X fields after reset */
if (sp->device_type == XFRAME_II_DEVICE) {
/* Clear "detected parity error" bit */
pci_write_config_word(sp->pdev, PCI_STATUS, 0x8000);
/* Clearing PCIX Ecc status register */
pci_write_config_dword(sp->pdev, 0x68, 0x7C);
/* Clearing PCI_STATUS error reflected here */
writeq(s2BIT(62), &bar0->txpic_int_reg);
}
/* Reset device statistics maintained by OS */
memset(&sp->stats, 0, sizeof(struct net_device_stats));
stats = sp->mac_control.stats_info;
swstats = &stats->sw_stat;
/* save link up/down time/cnt, reset/memory/watchdog cnt */
up_cnt = swstats->link_up_cnt;
down_cnt = swstats->link_down_cnt;
up_time = swstats->link_up_time;
down_time = swstats->link_down_time;
reset_cnt = swstats->soft_reset_cnt;
mem_alloc_cnt = swstats->mem_allocated;
mem_free_cnt = swstats->mem_freed;
watchdog_cnt = swstats->watchdog_timer_cnt;
memset(stats, 0, sizeof(struct stat_block));
/* restore link up/down time/cnt, reset/memory/watchdog cnt */
swstats->link_up_cnt = up_cnt;
swstats->link_down_cnt = down_cnt;
swstats->link_up_time = up_time;
swstats->link_down_time = down_time;
swstats->soft_reset_cnt = reset_cnt;
swstats->mem_allocated = mem_alloc_cnt;
swstats->mem_freed = mem_free_cnt;
swstats->watchdog_timer_cnt = watchdog_cnt;
/* SXE-002: Configure link and activity LED to turn it off */
subid = sp->pdev->subsystem_device;
if (((subid & 0xFF) >= 0x07) &&
(sp->device_type == XFRAME_I_DEVICE)) {
val64 = readq(&bar0->gpio_control);
val64 |= 0x0000800000000000ULL;
writeq(val64, &bar0->gpio_control);
val64 = 0x0411040400000000ULL;
writeq(val64, (void __iomem *)bar0 + 0x2700);
}
/*
* Clear spurious ECC interrupts that would have occurred on
* XFRAME II cards after reset.
*/
if (sp->device_type == XFRAME_II_DEVICE) {
val64 = readq(&bar0->pcc_err_reg);
writeq(val64, &bar0->pcc_err_reg);
}
sp->device_enabled_once = false;
}
/**
* s2io_set_swapper - to set the swapper controle on the card
* @sp : private member of the device structure,
* pointer to the s2io_nic structure.
* Description: Function to set the swapper control on the card
* correctly depending on the 'endianness' of the system.
* Return value:
* SUCCESS on success and FAILURE on failure.
*/
static int s2io_set_swapper(struct s2io_nic *sp)
{
struct net_device *dev = sp->dev;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64, valt, valr;
/*
* Set proper endian settings and verify the same by reading
* the PIF Feed-back register.
*/
val64 = readq(&bar0->pif_rd_swapper_fb);
if (val64 != 0x0123456789ABCDEFULL) {
int i = 0;
static const u64 value[] = {
0xC30000C3C30000C3ULL, /* FE=1, SE=1 */
0x8100008181000081ULL, /* FE=1, SE=0 */
0x4200004242000042ULL, /* FE=0, SE=1 */
0 /* FE=0, SE=0 */
};
while (i < 4) {
writeq(value[i], &bar0->swapper_ctrl);
val64 = readq(&bar0->pif_rd_swapper_fb);
if (val64 == 0x0123456789ABCDEFULL)
break;
i++;
}
if (i == 4) {
DBG_PRINT(ERR_DBG, "%s: Endian settings are wrong, "
"feedback read %llx\n",
dev->name, (unsigned long long)val64);
return FAILURE;
}
valr = value[i];
} else {
valr = readq(&bar0->swapper_ctrl);
}
valt = 0x0123456789ABCDEFULL;
writeq(valt, &bar0->xmsi_address);
val64 = readq(&bar0->xmsi_address);
if (val64 != valt) {
int i = 0;
static const u64 value[] = {
0x00C3C30000C3C300ULL, /* FE=1, SE=1 */
0x0081810000818100ULL, /* FE=1, SE=0 */
0x0042420000424200ULL, /* FE=0, SE=1 */
0 /* FE=0, SE=0 */
};
while (i < 4) {
writeq((value[i] | valr), &bar0->swapper_ctrl);
writeq(valt, &bar0->xmsi_address);
val64 = readq(&bar0->xmsi_address);
if (val64 == valt)
break;
i++;
}
if (i == 4) {
unsigned long long x = val64;
DBG_PRINT(ERR_DBG,
"Write failed, Xmsi_addr reads:0x%llx\n", x);
return FAILURE;
}
}
val64 = readq(&bar0->swapper_ctrl);
val64 &= 0xFFFF000000000000ULL;
#ifdef __BIG_ENDIAN
/*
* The device by default set to a big endian format, so a
* big endian driver need not set anything.
*/
val64 |= (SWAPPER_CTRL_TXP_FE |
SWAPPER_CTRL_TXP_SE |
SWAPPER_CTRL_TXD_R_FE |
SWAPPER_CTRL_TXD_W_FE |
SWAPPER_CTRL_TXF_R_FE |
SWAPPER_CTRL_RXD_R_FE |
SWAPPER_CTRL_RXD_W_FE |
SWAPPER_CTRL_RXF_W_FE |
SWAPPER_CTRL_XMSI_FE |
SWAPPER_CTRL_STATS_FE |
SWAPPER_CTRL_STATS_SE);
if (sp->config.intr_type == INTA)
val64 |= SWAPPER_CTRL_XMSI_SE;
writeq(val64, &bar0->swapper_ctrl);
#else
/*
* Initially we enable all bits to make it accessible by the
* driver, then we selectively enable only those bits that
* we want to set.
*/
val64 |= (SWAPPER_CTRL_TXP_FE |
SWAPPER_CTRL_TXP_SE |
SWAPPER_CTRL_TXD_R_FE |
SWAPPER_CTRL_TXD_R_SE |
SWAPPER_CTRL_TXD_W_FE |
SWAPPER_CTRL_TXD_W_SE |
SWAPPER_CTRL_TXF_R_FE |
SWAPPER_CTRL_RXD_R_FE |
SWAPPER_CTRL_RXD_R_SE |
SWAPPER_CTRL_RXD_W_FE |
SWAPPER_CTRL_RXD_W_SE |
SWAPPER_CTRL_RXF_W_FE |
SWAPPER_CTRL_XMSI_FE |
SWAPPER_CTRL_STATS_FE |
SWAPPER_CTRL_STATS_SE);
if (sp->config.intr_type == INTA)
val64 |= SWAPPER_CTRL_XMSI_SE;
writeq(val64, &bar0->swapper_ctrl);
#endif
val64 = readq(&bar0->swapper_ctrl);
/*
* Verifying if endian settings are accurate by reading a
* feedback register.
*/
val64 = readq(&bar0->pif_rd_swapper_fb);
if (val64 != 0x0123456789ABCDEFULL) {
/* Endian settings are incorrect, calls for another dekko. */
DBG_PRINT(ERR_DBG,
"%s: Endian settings are wrong, feedback read %llx\n",
dev->name, (unsigned long long)val64);
return FAILURE;
}
return SUCCESS;
}
static int wait_for_msix_trans(struct s2io_nic *nic, int i)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
u64 val64;
int ret = 0, cnt = 0;
do {
val64 = readq(&bar0->xmsi_access);
if (!(val64 & s2BIT(15)))
break;
mdelay(1);
cnt++;
} while (cnt < 5);
if (cnt == 5) {
DBG_PRINT(ERR_DBG, "XMSI # %d Access failed\n", i);
ret = 1;
}
return ret;
}
static void restore_xmsi_data(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
u64 val64;
int i, msix_index;
if (nic->device_type == XFRAME_I_DEVICE)
return;
for (i = 0; i < MAX_REQUESTED_MSI_X; i++) {
msix_index = (i) ? ((i-1) * 8 + 1) : 0;
writeq(nic->msix_info[i].addr, &bar0->xmsi_address);
writeq(nic->msix_info[i].data, &bar0->xmsi_data);
val64 = (s2BIT(7) | s2BIT(15) | vBIT(msix_index, 26, 6));
writeq(val64, &bar0->xmsi_access);
if (wait_for_msix_trans(nic, msix_index)) {
DBG_PRINT(ERR_DBG, "%s: index: %d failed\n",
__func__, msix_index);
continue;
}
}
}
static void store_xmsi_data(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
u64 val64, addr, data;
int i, msix_index;
if (nic->device_type == XFRAME_I_DEVICE)
return;
/* Store and display */
for (i = 0; i < MAX_REQUESTED_MSI_X; i++) {
msix_index = (i) ? ((i-1) * 8 + 1) : 0;
val64 = (s2BIT(15) | vBIT(msix_index, 26, 6));
writeq(val64, &bar0->xmsi_access);
if (wait_for_msix_trans(nic, msix_index)) {
DBG_PRINT(ERR_DBG, "%s: index: %d failed\n",
__func__, msix_index);
continue;
}
addr = readq(&bar0->xmsi_address);
data = readq(&bar0->xmsi_data);
if (addr && data) {
nic->msix_info[i].addr = addr;
nic->msix_info[i].data = data;
}
}
}
static int s2io_enable_msi_x(struct s2io_nic *nic)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
u64 rx_mat;
u16 msi_control; /* Temp variable */
int ret, i, j, msix_indx = 1;
int size;
struct stat_block *stats = nic->mac_control.stats_info;
struct swStat *swstats = &stats->sw_stat;
size = nic->num_entries * sizeof(struct msix_entry);
nic->entries = kzalloc(size, GFP_KERNEL);
if (!nic->entries) {
DBG_PRINT(INFO_DBG, "%s: Memory allocation failed\n",
__func__);
swstats->mem_alloc_fail_cnt++;
return -ENOMEM;
}
swstats->mem_allocated += size;
size = nic->num_entries * sizeof(struct s2io_msix_entry);
nic->s2io_entries = kzalloc(size, GFP_KERNEL);
if (!nic->s2io_entries) {
DBG_PRINT(INFO_DBG, "%s: Memory allocation failed\n",
__func__);
swstats->mem_alloc_fail_cnt++;
kfree(nic->entries);
swstats->mem_freed
+= (nic->num_entries * sizeof(struct msix_entry));
return -ENOMEM;
}
swstats->mem_allocated += size;
nic->entries[0].entry = 0;
nic->s2io_entries[0].entry = 0;
nic->s2io_entries[0].in_use = MSIX_FLG;
nic->s2io_entries[0].type = MSIX_ALARM_TYPE;
nic->s2io_entries[0].arg = &nic->mac_control.fifos;
for (i = 1; i < nic->num_entries; i++) {
nic->entries[i].entry = ((i - 1) * 8) + 1;
nic->s2io_entries[i].entry = ((i - 1) * 8) + 1;
nic->s2io_entries[i].arg = NULL;
nic->s2io_entries[i].in_use = 0;
}
rx_mat = readq(&bar0->rx_mat);
for (j = 0; j < nic->config.rx_ring_num; j++) {
rx_mat |= RX_MAT_SET(j, msix_indx);
nic->s2io_entries[j+1].arg = &nic->mac_control.rings[j];
nic->s2io_entries[j+1].type = MSIX_RING_TYPE;
nic->s2io_entries[j+1].in_use = MSIX_FLG;
msix_indx += 8;
}
writeq(rx_mat, &bar0->rx_mat);
readq(&bar0->rx_mat);
ret = pci_enable_msix(nic->pdev, nic->entries, nic->num_entries);
/* We fail init if error or we get less vectors than min required */
if (ret) {
DBG_PRINT(ERR_DBG, "Enabling MSI-X failed\n");
kfree(nic->entries);
swstats->mem_freed += nic->num_entries *
sizeof(struct msix_entry);
kfree(nic->s2io_entries);
swstats->mem_freed += nic->num_entries *
sizeof(struct s2io_msix_entry);
nic->entries = NULL;
nic->s2io_entries = NULL;
return -ENOMEM;
}
/*
* To enable MSI-X, MSI also needs to be enabled, due to a bug
* in the herc NIC. (Temp change, needs to be removed later)
*/
pci_read_config_word(nic->pdev, 0x42, &msi_control);
msi_control |= 0x1; /* Enable MSI */
pci_write_config_word(nic->pdev, 0x42, msi_control);
return 0;
}
/* Handle software interrupt used during MSI(X) test */
static irqreturn_t s2io_test_intr(int irq, void *dev_id)
{
struct s2io_nic *sp = dev_id;
sp->msi_detected = 1;
wake_up(&sp->msi_wait);
return IRQ_HANDLED;
}
/* Test interrupt path by forcing a a software IRQ */
static int s2io_test_msi(struct s2io_nic *sp)
{
struct pci_dev *pdev = sp->pdev;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
int err;
u64 val64, saved64;
err = request_irq(sp->entries[1].vector, s2io_test_intr, 0,
sp->name, sp);
if (err) {
DBG_PRINT(ERR_DBG, "%s: PCI %s: cannot assign irq %d\n",
sp->dev->name, pci_name(pdev), pdev->irq);
return err;
}
init_waitqueue_head(&sp->msi_wait);
sp->msi_detected = 0;
saved64 = val64 = readq(&bar0->scheduled_int_ctrl);
val64 |= SCHED_INT_CTRL_ONE_SHOT;
val64 |= SCHED_INT_CTRL_TIMER_EN;
val64 |= SCHED_INT_CTRL_INT2MSI(1);
writeq(val64, &bar0->scheduled_int_ctrl);
wait_event_timeout(sp->msi_wait, sp->msi_detected, HZ/10);
if (!sp->msi_detected) {
/* MSI(X) test failed, go back to INTx mode */
DBG_PRINT(ERR_DBG, "%s: PCI %s: No interrupt was generated "
"using MSI(X) during test\n",
sp->dev->name, pci_name(pdev));
err = -EOPNOTSUPP;
}
free_irq(sp->entries[1].vector, sp);
writeq(saved64, &bar0->scheduled_int_ctrl);
return err;
}
static void remove_msix_isr(struct s2io_nic *sp)
{
int i;
u16 msi_control;
for (i = 0; i < sp->num_entries; i++) {
if (sp->s2io_entries[i].in_use == MSIX_REGISTERED_SUCCESS) {
int vector = sp->entries[i].vector;
void *arg = sp->s2io_entries[i].arg;
free_irq(vector, arg);
}
}
kfree(sp->entries);
kfree(sp->s2io_entries);
sp->entries = NULL;
sp->s2io_entries = NULL;
pci_read_config_word(sp->pdev, 0x42, &msi_control);
msi_control &= 0xFFFE; /* Disable MSI */
pci_write_config_word(sp->pdev, 0x42, msi_control);
pci_disable_msix(sp->pdev);
}
static void remove_inta_isr(struct s2io_nic *sp)
{
free_irq(sp->pdev->irq, sp->dev);
}
/* ********************************************************* *
* Functions defined below concern the OS part of the driver *
* ********************************************************* */
/**
* s2io_open - open entry point of the driver
* @dev : pointer to the device structure.
* Description:
* This function is the open entry point of the driver. It mainly calls a
* function to allocate Rx buffers and inserts them into the buffer
* descriptors and then enables the Rx part of the NIC.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int s2io_open(struct net_device *dev)
{
struct s2io_nic *sp = netdev_priv(dev);
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
int err = 0;
/*
* Make sure you have link off by default every time
* Nic is initialized
*/
netif_carrier_off(dev);
sp->last_link_state = 0;
/* Initialize H/W and enable interrupts */
err = s2io_card_up(sp);
if (err) {
DBG_PRINT(ERR_DBG, "%s: H/W initialization failed\n",
dev->name);
goto hw_init_failed;
}
if (do_s2io_prog_unicast(dev, dev->dev_addr) == FAILURE) {
DBG_PRINT(ERR_DBG, "Set Mac Address Failed\n");
s2io_card_down(sp);
err = -ENODEV;
goto hw_init_failed;
}
s2io_start_all_tx_queue(sp);
return 0;
hw_init_failed:
if (sp->config.intr_type == MSI_X) {
if (sp->entries) {
kfree(sp->entries);
swstats->mem_freed += sp->num_entries *
sizeof(struct msix_entry);
}
if (sp->s2io_entries) {
kfree(sp->s2io_entries);
swstats->mem_freed += sp->num_entries *
sizeof(struct s2io_msix_entry);
}
}
return err;
}
/**
* s2io_close -close entry point of the driver
* @dev : device pointer.
* Description:
* This is the stop entry point of the driver. It needs to undo exactly
* whatever was done by the open entry point,thus it's usually referred to
* as the close function.Among other things this function mainly stops the
* Rx side of the NIC and frees all the Rx buffers in the Rx rings.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int s2io_close(struct net_device *dev)
{
struct s2io_nic *sp = netdev_priv(dev);
struct config_param *config = &sp->config;
u64 tmp64;
int offset;
/* Return if the device is already closed *
* Can happen when s2io_card_up failed in change_mtu *
*/
if (!is_s2io_card_up(sp))
return 0;
s2io_stop_all_tx_queue(sp);
/* delete all populated mac entries */
for (offset = 1; offset < config->max_mc_addr; offset++) {
tmp64 = do_s2io_read_unicast_mc(sp, offset);
if (tmp64 != S2IO_DISABLE_MAC_ENTRY)
do_s2io_delete_unicast_mc(sp, tmp64);
}
s2io_card_down(sp);
return 0;
}
/**
* s2io_xmit - Tx entry point of te driver
* @skb : the socket buffer containing the Tx data.
* @dev : device pointer.
* Description :
* This function is the Tx entry point of the driver. S2IO NIC supports
* certain protocol assist features on Tx side, namely CSO, S/G, LSO.
* NOTE: when device can't queue the pkt,just the trans_start variable will
* not be upadted.
* Return value:
* 0 on success & 1 on failure.
*/
static netdev_tx_t s2io_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct s2io_nic *sp = netdev_priv(dev);
u16 frg_cnt, frg_len, i, queue, queue_len, put_off, get_off;
register u64 val64;
struct TxD *txdp;
struct TxFIFO_element __iomem *tx_fifo;
unsigned long flags = 0;
u16 vlan_tag = 0;
struct fifo_info *fifo = NULL;
int do_spin_lock = 1;
int offload_type;
int enable_per_list_interrupt = 0;
struct config_param *config = &sp->config;
struct mac_info *mac_control = &sp->mac_control;
struct stat_block *stats = mac_control->stats_info;
struct swStat *swstats = &stats->sw_stat;
DBG_PRINT(TX_DBG, "%s: In Neterion Tx routine\n", dev->name);
if (unlikely(skb->len <= 0)) {
DBG_PRINT(TX_DBG, "%s: Buffer has no data..\n", dev->name);
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (!is_s2io_card_up(sp)) {
DBG_PRINT(TX_DBG, "%s: Card going down for reset\n",
dev->name);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
queue = 0;
if (vlan_tx_tag_present(skb))
vlan_tag = vlan_tx_tag_get(skb);
if (sp->config.tx_steering_type == TX_DEFAULT_STEERING) {
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *ip;
struct tcphdr *th;
ip = ip_hdr(skb);
if (!ip_is_fragment(ip)) {
th = (struct tcphdr *)(((unsigned char *)ip) +
ip->ihl*4);
if (ip->protocol == IPPROTO_TCP) {
queue_len = sp->total_tcp_fifos;
queue = (ntohs(th->source) +
ntohs(th->dest)) &
sp->fifo_selector[queue_len - 1];
if (queue >= queue_len)
queue = queue_len - 1;
} else if (ip->protocol == IPPROTO_UDP) {
queue_len = sp->total_udp_fifos;
queue = (ntohs(th->source) +
ntohs(th->dest)) &
sp->fifo_selector[queue_len - 1];
if (queue >= queue_len)
queue = queue_len - 1;
queue += sp->udp_fifo_idx;
if (skb->len > 1024)
enable_per_list_interrupt = 1;
do_spin_lock = 0;
}
}
}
} else if (sp->config.tx_steering_type == TX_PRIORITY_STEERING)
/* get fifo number based on skb->priority value */
queue = config->fifo_mapping
[skb->priority & (MAX_TX_FIFOS - 1)];
fifo = &mac_control->fifos[queue];
if (do_spin_lock)
spin_lock_irqsave(&fifo->tx_lock, flags);
else {
if (unlikely(!spin_trylock_irqsave(&fifo->tx_lock, flags)))
return NETDEV_TX_LOCKED;
}
if (sp->config.multiq) {
if (__netif_subqueue_stopped(dev, fifo->fifo_no)) {
spin_unlock_irqrestore(&fifo->tx_lock, flags);
return NETDEV_TX_BUSY;
}
} else if (unlikely(fifo->queue_state == FIFO_QUEUE_STOP)) {
if (netif_queue_stopped(dev)) {
spin_unlock_irqrestore(&fifo->tx_lock, flags);
return NETDEV_TX_BUSY;
}
}
put_off = (u16)fifo->tx_curr_put_info.offset;
get_off = (u16)fifo->tx_curr_get_info.offset;
txdp = fifo->list_info[put_off].list_virt_addr;
queue_len = fifo->tx_curr_put_info.fifo_len + 1;
/* Avoid "put" pointer going beyond "get" pointer */
if (txdp->Host_Control ||
((put_off+1) == queue_len ? 0 : (put_off+1)) == get_off) {
DBG_PRINT(TX_DBG, "Error in xmit, No free TXDs.\n");
s2io_stop_tx_queue(sp, fifo->fifo_no);
dev_kfree_skb(skb);
spin_unlock_irqrestore(&fifo->tx_lock, flags);
return NETDEV_TX_OK;
}
offload_type = s2io_offload_type(skb);
if (offload_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)) {
txdp->Control_1 |= TXD_TCP_LSO_EN;
txdp->Control_1 |= TXD_TCP_LSO_MSS(s2io_tcp_mss(skb));
}
if (skb->ip_summed == CHECKSUM_PARTIAL) {
txdp->Control_2 |= (TXD_TX_CKO_IPV4_EN |
TXD_TX_CKO_TCP_EN |
TXD_TX_CKO_UDP_EN);
}
txdp->Control_1 |= TXD_GATHER_CODE_FIRST;
txdp->Control_1 |= TXD_LIST_OWN_XENA;
txdp->Control_2 |= TXD_INT_NUMBER(fifo->fifo_no);
if (enable_per_list_interrupt)
if (put_off & (queue_len >> 5))
txdp->Control_2 |= TXD_INT_TYPE_PER_LIST;
if (vlan_tag) {
txdp->Control_2 |= TXD_VLAN_ENABLE;
txdp->Control_2 |= TXD_VLAN_TAG(vlan_tag);
}
frg_len = skb_headlen(skb);
if (offload_type == SKB_GSO_UDP) {
int ufo_size;
ufo_size = s2io_udp_mss(skb);
ufo_size &= ~7;
txdp->Control_1 |= TXD_UFO_EN;
txdp->Control_1 |= TXD_UFO_MSS(ufo_size);
txdp->Control_1 |= TXD_BUFFER0_SIZE(8);
#ifdef __BIG_ENDIAN
/* both variants do cpu_to_be64(be32_to_cpu(...)) */
fifo->ufo_in_band_v[put_off] =
(__force u64)skb_shinfo(skb)->ip6_frag_id;
#else
fifo->ufo_in_band_v[put_off] =
(__force u64)skb_shinfo(skb)->ip6_frag_id << 32;
#endif
txdp->Host_Control = (unsigned long)fifo->ufo_in_band_v;
txdp->Buffer_Pointer = pci_map_single(sp->pdev,
fifo->ufo_in_band_v,
sizeof(u64),
PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(sp->pdev, txdp->Buffer_Pointer))
goto pci_map_failed;
txdp++;
}
txdp->Buffer_Pointer = pci_map_single(sp->pdev, skb->data,
frg_len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(sp->pdev, txdp->Buffer_Pointer))
goto pci_map_failed;
txdp->Host_Control = (unsigned long)skb;
txdp->Control_1 |= TXD_BUFFER0_SIZE(frg_len);
if (offload_type == SKB_GSO_UDP)
txdp->Control_1 |= TXD_UFO_EN;
frg_cnt = skb_shinfo(skb)->nr_frags;
/* For fragmented SKB. */
for (i = 0; i < frg_cnt; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
/* A '0' length fragment will be ignored */
if (!skb_frag_size(frag))
continue;
txdp++;
txdp->Buffer_Pointer = (u64)skb_frag_dma_map(&sp->pdev->dev,
frag, 0,
skb_frag_size(frag),
DMA_TO_DEVICE);
txdp->Control_1 = TXD_BUFFER0_SIZE(skb_frag_size(frag));
if (offload_type == SKB_GSO_UDP)
txdp->Control_1 |= TXD_UFO_EN;
}
txdp->Control_1 |= TXD_GATHER_CODE_LAST;
if (offload_type == SKB_GSO_UDP)
frg_cnt++; /* as Txd0 was used for inband header */
tx_fifo = mac_control->tx_FIFO_start[queue];
val64 = fifo->list_info[put_off].list_phy_addr;
writeq(val64, &tx_fifo->TxDL_Pointer);
val64 = (TX_FIFO_LAST_TXD_NUM(frg_cnt) | TX_FIFO_FIRST_LIST |
TX_FIFO_LAST_LIST);
if (offload_type)
val64 |= TX_FIFO_SPECIAL_FUNC;
writeq(val64, &tx_fifo->List_Control);
mmiowb();
put_off++;
if (put_off == fifo->tx_curr_put_info.fifo_len + 1)
put_off = 0;
fifo->tx_curr_put_info.offset = put_off;
/* Avoid "put" pointer going beyond "get" pointer */
if (((put_off+1) == queue_len ? 0 : (put_off+1)) == get_off) {
swstats->fifo_full_cnt++;
DBG_PRINT(TX_DBG,
"No free TxDs for xmit, Put: 0x%x Get:0x%x\n",
put_off, get_off);
s2io_stop_tx_queue(sp, fifo->fifo_no);
}
swstats->mem_allocated += skb->truesize;
spin_unlock_irqrestore(&fifo->tx_lock, flags);
if (sp->config.intr_type == MSI_X)
tx_intr_handler(fifo);
return NETDEV_TX_OK;
pci_map_failed:
swstats->pci_map_fail_cnt++;
s2io_stop_tx_queue(sp, fifo->fifo_no);
swstats->mem_freed += skb->truesize;
dev_kfree_skb(skb);
spin_unlock_irqrestore(&fifo->tx_lock, flags);
return NETDEV_TX_OK;
}
static void
s2io_alarm_handle(unsigned long data)
{
struct s2io_nic *sp = (struct s2io_nic *)data;
struct net_device *dev = sp->dev;
s2io_handle_errors(dev);
mod_timer(&sp->alarm_timer, jiffies + HZ / 2);
}
static irqreturn_t s2io_msix_ring_handle(int irq, void *dev_id)
{
struct ring_info *ring = (struct ring_info *)dev_id;
struct s2io_nic *sp = ring->nic;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
if (unlikely(!is_s2io_card_up(sp)))
return IRQ_HANDLED;
if (sp->config.napi) {
u8 __iomem *addr = NULL;
u8 val8 = 0;
addr = (u8 __iomem *)&bar0->xmsi_mask_reg;
addr += (7 - ring->ring_no);
val8 = (ring->ring_no == 0) ? 0x7f : 0xff;
writeb(val8, addr);
val8 = readb(addr);
napi_schedule(&ring->napi);
} else {
rx_intr_handler(ring, 0);
s2io_chk_rx_buffers(sp, ring);
}
return IRQ_HANDLED;
}
static irqreturn_t s2io_msix_fifo_handle(int irq, void *dev_id)
{
int i;
struct fifo_info *fifos = (struct fifo_info *)dev_id;
struct s2io_nic *sp = fifos->nic;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
struct config_param *config = &sp->config;
u64 reason;
if (unlikely(!is_s2io_card_up(sp)))
return IRQ_NONE;
reason = readq(&bar0->general_int_status);
if (unlikely(reason == S2IO_MINUS_ONE))
/* Nothing much can be done. Get out */
return IRQ_HANDLED;
if (reason & (GEN_INTR_TXPIC | GEN_INTR_TXTRAFFIC)) {
writeq(S2IO_MINUS_ONE, &bar0->general_int_mask);
if (reason & GEN_INTR_TXPIC)
s2io_txpic_intr_handle(sp);
if (reason & GEN_INTR_TXTRAFFIC)
writeq(S2IO_MINUS_ONE, &bar0->tx_traffic_int);
for (i = 0; i < config->tx_fifo_num; i++)
tx_intr_handler(&fifos[i]);
writeq(sp->general_int_mask, &bar0->general_int_mask);
readl(&bar0->general_int_status);
return IRQ_HANDLED;
}
/* The interrupt was not raised by us */
return IRQ_NONE;
}
static void s2io_txpic_intr_handle(struct s2io_nic *sp)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64;
val64 = readq(&bar0->pic_int_status);
if (val64 & PIC_INT_GPIO) {
val64 = readq(&bar0->gpio_int_reg);
if ((val64 & GPIO_INT_REG_LINK_DOWN) &&
(val64 & GPIO_INT_REG_LINK_UP)) {
/*
* This is unstable state so clear both up/down
* interrupt and adapter to re-evaluate the link state.
*/
val64 |= GPIO_INT_REG_LINK_DOWN;
val64 |= GPIO_INT_REG_LINK_UP;
writeq(val64, &bar0->gpio_int_reg);
val64 = readq(&bar0->gpio_int_mask);
val64 &= ~(GPIO_INT_MASK_LINK_UP |
GPIO_INT_MASK_LINK_DOWN);
writeq(val64, &bar0->gpio_int_mask);
} else if (val64 & GPIO_INT_REG_LINK_UP) {
val64 = readq(&bar0->adapter_status);
/* Enable Adapter */
val64 = readq(&bar0->adapter_control);
val64 |= ADAPTER_CNTL_EN;
writeq(val64, &bar0->adapter_control);
val64 |= ADAPTER_LED_ON;
writeq(val64, &bar0->adapter_control);
if (!sp->device_enabled_once)
sp->device_enabled_once = 1;
s2io_link(sp, LINK_UP);
/*
* unmask link down interrupt and mask link-up
* intr
*/
val64 = readq(&bar0->gpio_int_mask);
val64 &= ~GPIO_INT_MASK_LINK_DOWN;
val64 |= GPIO_INT_MASK_LINK_UP;
writeq(val64, &bar0->gpio_int_mask);
} else if (val64 & GPIO_INT_REG_LINK_DOWN) {
val64 = readq(&bar0->adapter_status);
s2io_link(sp, LINK_DOWN);
/* Link is down so unmaks link up interrupt */
val64 = readq(&bar0->gpio_int_mask);
val64 &= ~GPIO_INT_MASK_LINK_UP;
val64 |= GPIO_INT_MASK_LINK_DOWN;
writeq(val64, &bar0->gpio_int_mask);
/* turn off LED */
val64 = readq(&bar0->adapter_control);
val64 = val64 & (~ADAPTER_LED_ON);
writeq(val64, &bar0->adapter_control);
}
}
val64 = readq(&bar0->gpio_int_mask);
}
/**
* do_s2io_chk_alarm_bit - Check for alarm and incrment the counter
* @value: alarm bits
* @addr: address value
* @cnt: counter variable
* Description: Check for alarm and increment the counter
* Return Value:
* 1 - if alarm bit set
* 0 - if alarm bit is not set
*/
static int do_s2io_chk_alarm_bit(u64 value, void __iomem *addr,
unsigned long long *cnt)
{
u64 val64;
val64 = readq(addr);
if (val64 & value) {
writeq(val64, addr);
(*cnt)++;
return 1;
}
return 0;
}
/**
* s2io_handle_errors - Xframe error indication handler
* @nic: device private variable
* Description: Handle alarms such as loss of link, single or
* double ECC errors, critical and serious errors.
* Return Value:
* NONE
*/
static void s2io_handle_errors(void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 temp64 = 0, val64 = 0;
int i = 0;
struct swStat *sw_stat = &sp->mac_control.stats_info->sw_stat;
struct xpakStat *stats = &sp->mac_control.stats_info->xpak_stat;
if (!is_s2io_card_up(sp))
return;
if (pci_channel_offline(sp->pdev))
return;
memset(&sw_stat->ring_full_cnt, 0,
sizeof(sw_stat->ring_full_cnt));
/* Handling the XPAK counters update */
if (stats->xpak_timer_count < 72000) {
/* waiting for an hour */
stats->xpak_timer_count++;
} else {
s2io_updt_xpak_counter(dev);
/* reset the count to zero */
stats->xpak_timer_count = 0;
}
/* Handling link status change error Intr */
if (s2io_link_fault_indication(sp) == MAC_RMAC_ERR_TIMER) {
val64 = readq(&bar0->mac_rmac_err_reg);
writeq(val64, &bar0->mac_rmac_err_reg);
if (val64 & RMAC_LINK_STATE_CHANGE_INT)
schedule_work(&sp->set_link_task);
}
/* In case of a serious error, the device will be Reset. */
if (do_s2io_chk_alarm_bit(SERR_SOURCE_ANY, &bar0->serr_source,
&sw_stat->serious_err_cnt))
goto reset;
/* Check for data parity error */
if (do_s2io_chk_alarm_bit(GPIO_INT_REG_DP_ERR_INT, &bar0->gpio_int_reg,
&sw_stat->parity_err_cnt))
goto reset;
/* Check for ring full counter */
if (sp->device_type == XFRAME_II_DEVICE) {
val64 = readq(&bar0->ring_bump_counter1);
for (i = 0; i < 4; i++) {
temp64 = (val64 & vBIT(0xFFFF, (i*16), 16));
temp64 >>= 64 - ((i+1)*16);
sw_stat->ring_full_cnt[i] += temp64;
}
val64 = readq(&bar0->ring_bump_counter2);
for (i = 0; i < 4; i++) {
temp64 = (val64 & vBIT(0xFFFF, (i*16), 16));
temp64 >>= 64 - ((i+1)*16);
sw_stat->ring_full_cnt[i+4] += temp64;
}
}
val64 = readq(&bar0->txdma_int_status);
/*check for pfc_err*/
if (val64 & TXDMA_PFC_INT) {
if (do_s2io_chk_alarm_bit(PFC_ECC_DB_ERR | PFC_SM_ERR_ALARM |
PFC_MISC_0_ERR | PFC_MISC_1_ERR |
PFC_PCIX_ERR,
&bar0->pfc_err_reg,
&sw_stat->pfc_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(PFC_ECC_SG_ERR,
&bar0->pfc_err_reg,
&sw_stat->pfc_err_cnt);
}
/*check for tda_err*/
if (val64 & TXDMA_TDA_INT) {
if (do_s2io_chk_alarm_bit(TDA_Fn_ECC_DB_ERR |
TDA_SM0_ERR_ALARM |
TDA_SM1_ERR_ALARM,
&bar0->tda_err_reg,
&sw_stat->tda_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(TDA_Fn_ECC_SG_ERR | TDA_PCIX_ERR,
&bar0->tda_err_reg,
&sw_stat->tda_err_cnt);
}
/*check for pcc_err*/
if (val64 & TXDMA_PCC_INT) {
if (do_s2io_chk_alarm_bit(PCC_SM_ERR_ALARM | PCC_WR_ERR_ALARM |
PCC_N_SERR | PCC_6_COF_OV_ERR |
PCC_7_COF_OV_ERR | PCC_6_LSO_OV_ERR |
PCC_7_LSO_OV_ERR | PCC_FB_ECC_DB_ERR |
PCC_TXB_ECC_DB_ERR,
&bar0->pcc_err_reg,
&sw_stat->pcc_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(PCC_FB_ECC_SG_ERR | PCC_TXB_ECC_SG_ERR,
&bar0->pcc_err_reg,
&sw_stat->pcc_err_cnt);
}
/*check for tti_err*/
if (val64 & TXDMA_TTI_INT) {
if (do_s2io_chk_alarm_bit(TTI_SM_ERR_ALARM,
&bar0->tti_err_reg,
&sw_stat->tti_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(TTI_ECC_SG_ERR | TTI_ECC_DB_ERR,
&bar0->tti_err_reg,
&sw_stat->tti_err_cnt);
}
/*check for lso_err*/
if (val64 & TXDMA_LSO_INT) {
if (do_s2io_chk_alarm_bit(LSO6_ABORT | LSO7_ABORT |
LSO6_SM_ERR_ALARM | LSO7_SM_ERR_ALARM,
&bar0->lso_err_reg,
&sw_stat->lso_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(LSO6_SEND_OFLOW | LSO7_SEND_OFLOW,
&bar0->lso_err_reg,
&sw_stat->lso_err_cnt);
}
/*check for tpa_err*/
if (val64 & TXDMA_TPA_INT) {
if (do_s2io_chk_alarm_bit(TPA_SM_ERR_ALARM,
&bar0->tpa_err_reg,
&sw_stat->tpa_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(TPA_TX_FRM_DROP,
&bar0->tpa_err_reg,
&sw_stat->tpa_err_cnt);
}
/*check for sm_err*/
if (val64 & TXDMA_SM_INT) {
if (do_s2io_chk_alarm_bit(SM_SM_ERR_ALARM,
&bar0->sm_err_reg,
&sw_stat->sm_err_cnt))
goto reset;
}
val64 = readq(&bar0->mac_int_status);
if (val64 & MAC_INT_STATUS_TMAC_INT) {
if (do_s2io_chk_alarm_bit(TMAC_TX_BUF_OVRN | TMAC_TX_SM_ERR,
&bar0->mac_tmac_err_reg,
&sw_stat->mac_tmac_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(TMAC_ECC_SG_ERR | TMAC_ECC_DB_ERR |
TMAC_DESC_ECC_SG_ERR |
TMAC_DESC_ECC_DB_ERR,
&bar0->mac_tmac_err_reg,
&sw_stat->mac_tmac_err_cnt);
}
val64 = readq(&bar0->xgxs_int_status);
if (val64 & XGXS_INT_STATUS_TXGXS) {
if (do_s2io_chk_alarm_bit(TXGXS_ESTORE_UFLOW | TXGXS_TX_SM_ERR,
&bar0->xgxs_txgxs_err_reg,
&sw_stat->xgxs_txgxs_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(TXGXS_ECC_SG_ERR | TXGXS_ECC_DB_ERR,
&bar0->xgxs_txgxs_err_reg,
&sw_stat->xgxs_txgxs_err_cnt);
}
val64 = readq(&bar0->rxdma_int_status);
if (val64 & RXDMA_INT_RC_INT_M) {
if (do_s2io_chk_alarm_bit(RC_PRCn_ECC_DB_ERR |
RC_FTC_ECC_DB_ERR |
RC_PRCn_SM_ERR_ALARM |
RC_FTC_SM_ERR_ALARM,
&bar0->rc_err_reg,
&sw_stat->rc_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(RC_PRCn_ECC_SG_ERR |
RC_FTC_ECC_SG_ERR |
RC_RDA_FAIL_WR_Rn, &bar0->rc_err_reg,
&sw_stat->rc_err_cnt);
if (do_s2io_chk_alarm_bit(PRC_PCI_AB_RD_Rn |
PRC_PCI_AB_WR_Rn |
PRC_PCI_AB_F_WR_Rn,
&bar0->prc_pcix_err_reg,
&sw_stat->prc_pcix_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(PRC_PCI_DP_RD_Rn |
PRC_PCI_DP_WR_Rn |
PRC_PCI_DP_F_WR_Rn,
&bar0->prc_pcix_err_reg,
&sw_stat->prc_pcix_err_cnt);
}
if (val64 & RXDMA_INT_RPA_INT_M) {
if (do_s2io_chk_alarm_bit(RPA_SM_ERR_ALARM | RPA_CREDIT_ERR,
&bar0->rpa_err_reg,
&sw_stat->rpa_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(RPA_ECC_SG_ERR | RPA_ECC_DB_ERR,
&bar0->rpa_err_reg,
&sw_stat->rpa_err_cnt);
}
if (val64 & RXDMA_INT_RDA_INT_M) {
if (do_s2io_chk_alarm_bit(RDA_RXDn_ECC_DB_ERR |
RDA_FRM_ECC_DB_N_AERR |
RDA_SM1_ERR_ALARM |
RDA_SM0_ERR_ALARM |
RDA_RXD_ECC_DB_SERR,
&bar0->rda_err_reg,
&sw_stat->rda_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(RDA_RXDn_ECC_SG_ERR |
RDA_FRM_ECC_SG_ERR |
RDA_MISC_ERR |
RDA_PCIX_ERR,
&bar0->rda_err_reg,
&sw_stat->rda_err_cnt);
}
if (val64 & RXDMA_INT_RTI_INT_M) {
if (do_s2io_chk_alarm_bit(RTI_SM_ERR_ALARM,
&bar0->rti_err_reg,
&sw_stat->rti_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(RTI_ECC_SG_ERR | RTI_ECC_DB_ERR,
&bar0->rti_err_reg,
&sw_stat->rti_err_cnt);
}
val64 = readq(&bar0->mac_int_status);
if (val64 & MAC_INT_STATUS_RMAC_INT) {
if (do_s2io_chk_alarm_bit(RMAC_RX_BUFF_OVRN | RMAC_RX_SM_ERR,
&bar0->mac_rmac_err_reg,
&sw_stat->mac_rmac_err_cnt))
goto reset;
do_s2io_chk_alarm_bit(RMAC_UNUSED_INT |
RMAC_SINGLE_ECC_ERR |
RMAC_DOUBLE_ECC_ERR,
&bar0->mac_rmac_err_reg,
&sw_stat->mac_rmac_err_cnt);
}
val64 = readq(&bar0->xgxs_int_status);
if (val64 & XGXS_INT_STATUS_RXGXS) {
if (do_s2io_chk_alarm_bit(RXGXS_ESTORE_OFLOW | RXGXS_RX_SM_ERR,
&bar0->xgxs_rxgxs_err_reg,
&sw_stat->xgxs_rxgxs_err_cnt))
goto reset;
}
val64 = readq(&bar0->mc_int_status);
if (val64 & MC_INT_STATUS_MC_INT) {
if (do_s2io_chk_alarm_bit(MC_ERR_REG_SM_ERR,
&bar0->mc_err_reg,
&sw_stat->mc_err_cnt))
goto reset;
/* Handling Ecc errors */
if (val64 & (MC_ERR_REG_ECC_ALL_SNG | MC_ERR_REG_ECC_ALL_DBL)) {
writeq(val64, &bar0->mc_err_reg);
if (val64 & MC_ERR_REG_ECC_ALL_DBL) {
sw_stat->double_ecc_errs++;
if (sp->device_type != XFRAME_II_DEVICE) {
/*
* Reset XframeI only if critical error
*/
if (val64 &
(MC_ERR_REG_MIRI_ECC_DB_ERR_0 |
MC_ERR_REG_MIRI_ECC_DB_ERR_1))
goto reset;
}
} else
sw_stat->single_ecc_errs++;
}
}
return;
reset:
s2io_stop_all_tx_queue(sp);
schedule_work(&sp->rst_timer_task);
sw_stat->soft_reset_cnt++;
}
/**
* s2io_isr - ISR handler of the device .
* @irq: the irq of the device.
* @dev_id: a void pointer to the dev structure of the NIC.
* Description: This function is the ISR handler of the device. It
* identifies the reason for the interrupt and calls the relevant
* service routines. As a contongency measure, this ISR allocates the
* recv buffers, if their numbers are below the panic value which is
* presently set to 25% of the original number of rcv buffers allocated.
* Return value:
* IRQ_HANDLED: will be returned if IRQ was handled by this routine
* IRQ_NONE: will be returned if interrupt is not from our device
*/
static irqreturn_t s2io_isr(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
int i;
u64 reason = 0;
struct mac_info *mac_control;
struct config_param *config;
/* Pretend we handled any irq's from a disconnected card */
if (pci_channel_offline(sp->pdev))
return IRQ_NONE;
if (!is_s2io_card_up(sp))
return IRQ_NONE;
config = &sp->config;
mac_control = &sp->mac_control;
/*
* Identify the cause for interrupt and call the appropriate
* interrupt handler. Causes for the interrupt could be;
* 1. Rx of packet.
* 2. Tx complete.
* 3. Link down.
*/
reason = readq(&bar0->general_int_status);
if (unlikely(reason == S2IO_MINUS_ONE))
return IRQ_HANDLED; /* Nothing much can be done. Get out */
if (reason &
(GEN_INTR_RXTRAFFIC | GEN_INTR_TXTRAFFIC | GEN_INTR_TXPIC)) {
writeq(S2IO_MINUS_ONE, &bar0->general_int_mask);
if (config->napi) {
if (reason & GEN_INTR_RXTRAFFIC) {
napi_schedule(&sp->napi);
writeq(S2IO_MINUS_ONE, &bar0->rx_traffic_mask);
writeq(S2IO_MINUS_ONE, &bar0->rx_traffic_int);
readl(&bar0->rx_traffic_int);
}
} else {
/*
* rx_traffic_int reg is an R1 register, writing all 1's
* will ensure that the actual interrupt causing bit
* get's cleared and hence a read can be avoided.
*/
if (reason & GEN_INTR_RXTRAFFIC)
writeq(S2IO_MINUS_ONE, &bar0->rx_traffic_int);
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
rx_intr_handler(ring, 0);
}
}
/*
* tx_traffic_int reg is an R1 register, writing all 1's
* will ensure that the actual interrupt causing bit get's
* cleared and hence a read can be avoided.
*/
if (reason & GEN_INTR_TXTRAFFIC)
writeq(S2IO_MINUS_ONE, &bar0->tx_traffic_int);
for (i = 0; i < config->tx_fifo_num; i++)
tx_intr_handler(&mac_control->fifos[i]);
if (reason & GEN_INTR_TXPIC)
s2io_txpic_intr_handle(sp);
/*
* Reallocate the buffers from the interrupt handler itself.
*/
if (!config->napi) {
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
s2io_chk_rx_buffers(sp, ring);
}
}
writeq(sp->general_int_mask, &bar0->general_int_mask);
readl(&bar0->general_int_status);
return IRQ_HANDLED;
} else if (!reason) {
/* The interrupt was not raised by us */
return IRQ_NONE;
}
return IRQ_HANDLED;
}
/**
* s2io_updt_stats -
*/
static void s2io_updt_stats(struct s2io_nic *sp)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64;
int cnt = 0;
if (is_s2io_card_up(sp)) {
/* Apprx 30us on a 133 MHz bus */
val64 = SET_UPDT_CLICKS(10) |
STAT_CFG_ONE_SHOT_EN | STAT_CFG_STAT_EN;
writeq(val64, &bar0->stat_cfg);
do {
udelay(100);
val64 = readq(&bar0->stat_cfg);
if (!(val64 & s2BIT(0)))
break;
cnt++;
if (cnt == 5)
break; /* Updt failed */
} while (1);
}
}
/**
* s2io_get_stats - Updates the device statistics structure.
* @dev : pointer to the device structure.
* Description:
* This function updates the device statistics structure in the s2io_nic
* structure and returns a pointer to the same.
* Return value:
* pointer to the updated net_device_stats structure.
*/
static struct net_device_stats *s2io_get_stats(struct net_device *dev)
{
struct s2io_nic *sp = netdev_priv(dev);
struct mac_info *mac_control = &sp->mac_control;
struct stat_block *stats = mac_control->stats_info;
u64 delta;
/* Configure Stats for immediate updt */
s2io_updt_stats(sp);
/* A device reset will cause the on-adapter statistics to be zero'ed.
* This can be done while running by changing the MTU. To prevent the
* system from having the stats zero'ed, the driver keeps a copy of the
* last update to the system (which is also zero'ed on reset). This
* enables the driver to accurately know the delta between the last
* update and the current update.
*/
delta = ((u64) le32_to_cpu(stats->rmac_vld_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_vld_frms)) - sp->stats.rx_packets;
sp->stats.rx_packets += delta;
dev->stats.rx_packets += delta;
delta = ((u64) le32_to_cpu(stats->tmac_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_frms)) - sp->stats.tx_packets;
sp->stats.tx_packets += delta;
dev->stats.tx_packets += delta;
delta = ((u64) le32_to_cpu(stats->rmac_data_octets_oflow) << 32 |
le32_to_cpu(stats->rmac_data_octets)) - sp->stats.rx_bytes;
sp->stats.rx_bytes += delta;
dev->stats.rx_bytes += delta;
delta = ((u64) le32_to_cpu(stats->tmac_data_octets_oflow) << 32 |
le32_to_cpu(stats->tmac_data_octets)) - sp->stats.tx_bytes;
sp->stats.tx_bytes += delta;
dev->stats.tx_bytes += delta;
delta = le64_to_cpu(stats->rmac_drop_frms) - sp->stats.rx_errors;
sp->stats.rx_errors += delta;
dev->stats.rx_errors += delta;
delta = ((u64) le32_to_cpu(stats->tmac_any_err_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_any_err_frms)) - sp->stats.tx_errors;
sp->stats.tx_errors += delta;
dev->stats.tx_errors += delta;
delta = le64_to_cpu(stats->rmac_drop_frms) - sp->stats.rx_dropped;
sp->stats.rx_dropped += delta;
dev->stats.rx_dropped += delta;
delta = le64_to_cpu(stats->tmac_drop_frms) - sp->stats.tx_dropped;
sp->stats.tx_dropped += delta;
dev->stats.tx_dropped += delta;
/* The adapter MAC interprets pause frames as multicast packets, but
* does not pass them up. This erroneously increases the multicast
* packet count and needs to be deducted when the multicast frame count
* is queried.
*/
delta = (u64) le32_to_cpu(stats->rmac_vld_mcst_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_vld_mcst_frms);
delta -= le64_to_cpu(stats->rmac_pause_ctrl_frms);
delta -= sp->stats.multicast;
sp->stats.multicast += delta;
dev->stats.multicast += delta;
delta = ((u64) le32_to_cpu(stats->rmac_usized_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_usized_frms)) +
le64_to_cpu(stats->rmac_long_frms) - sp->stats.rx_length_errors;
sp->stats.rx_length_errors += delta;
dev->stats.rx_length_errors += delta;
delta = le64_to_cpu(stats->rmac_fcs_err_frms) - sp->stats.rx_crc_errors;
sp->stats.rx_crc_errors += delta;
dev->stats.rx_crc_errors += delta;
return &dev->stats;
}
/**
* s2io_set_multicast - entry point for multicast address enable/disable.
* @dev : pointer to the device structure
* Description:
* This function is a driver entry point which gets called by the kernel
* whenever multicast addresses must be enabled/disabled. This also gets
* called to set/reset promiscuous mode. Depending on the deivce flag, we
* determine, if multicast address must be enabled or if promiscuous mode
* is to be disabled etc.
* Return value:
* void.
*/
static void s2io_set_multicast(struct net_device *dev)
{
int i, j, prev_cnt;
struct netdev_hw_addr *ha;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64 = 0, multi_mac = 0x010203040506ULL, mask =
0xfeffffffffffULL;
u64 dis_addr = S2IO_DISABLE_MAC_ENTRY, mac_addr = 0;
void __iomem *add;
struct config_param *config = &sp->config;
if ((dev->flags & IFF_ALLMULTI) && (!sp->m_cast_flg)) {
/* Enable all Multicast addresses */
writeq(RMAC_ADDR_DATA0_MEM_ADDR(multi_mac),
&bar0->rmac_addr_data0_mem);
writeq(RMAC_ADDR_DATA1_MEM_MASK(mask),
&bar0->rmac_addr_data1_mem);
val64 = RMAC_ADDR_CMD_MEM_WE |
RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET(config->max_mc_addr - 1);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait till command completes */
wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET);
sp->m_cast_flg = 1;
sp->all_multi_pos = config->max_mc_addr - 1;
} else if ((dev->flags & IFF_ALLMULTI) && (sp->m_cast_flg)) {
/* Disable all Multicast addresses */
writeq(RMAC_ADDR_DATA0_MEM_ADDR(dis_addr),
&bar0->rmac_addr_data0_mem);
writeq(RMAC_ADDR_DATA1_MEM_MASK(0x0),
&bar0->rmac_addr_data1_mem);
val64 = RMAC_ADDR_CMD_MEM_WE |
RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET(sp->all_multi_pos);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait till command completes */
wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET);
sp->m_cast_flg = 0;
sp->all_multi_pos = 0;
}
if ((dev->flags & IFF_PROMISC) && (!sp->promisc_flg)) {
/* Put the NIC into promiscuous mode */
add = &bar0->mac_cfg;
val64 = readq(&bar0->mac_cfg);
val64 |= MAC_CFG_RMAC_PROM_ENABLE;
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32)val64, add);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64 >> 32), (add + 4));
if (vlan_tag_strip != 1) {
val64 = readq(&bar0->rx_pa_cfg);
val64 &= ~RX_PA_CFG_STRIP_VLAN_TAG;
writeq(val64, &bar0->rx_pa_cfg);
sp->vlan_strip_flag = 0;
}
val64 = readq(&bar0->mac_cfg);
sp->promisc_flg = 1;
DBG_PRINT(INFO_DBG, "%s: entered promiscuous mode\n",
dev->name);
} else if (!(dev->flags & IFF_PROMISC) && (sp->promisc_flg)) {
/* Remove the NIC from promiscuous mode */
add = &bar0->mac_cfg;
val64 = readq(&bar0->mac_cfg);
val64 &= ~MAC_CFG_RMAC_PROM_ENABLE;
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32)val64, add);
writeq(RMAC_CFG_KEY(0x4C0D), &bar0->rmac_cfg_key);
writel((u32) (val64 >> 32), (add + 4));
if (vlan_tag_strip != 0) {
val64 = readq(&bar0->rx_pa_cfg);
val64 |= RX_PA_CFG_STRIP_VLAN_TAG;
writeq(val64, &bar0->rx_pa_cfg);
sp->vlan_strip_flag = 1;
}
val64 = readq(&bar0->mac_cfg);
sp->promisc_flg = 0;
DBG_PRINT(INFO_DBG, "%s: left promiscuous mode\n", dev->name);
}
/* Update individual M_CAST address list */
if ((!sp->m_cast_flg) && netdev_mc_count(dev)) {
if (netdev_mc_count(dev) >
(config->max_mc_addr - config->max_mac_addr)) {
DBG_PRINT(ERR_DBG,
"%s: No more Rx filters can be added - "
"please enable ALL_MULTI instead\n",
dev->name);
return;
}
prev_cnt = sp->mc_addr_count;
sp->mc_addr_count = netdev_mc_count(dev);
/* Clear out the previous list of Mc in the H/W. */
for (i = 0; i < prev_cnt; i++) {
writeq(RMAC_ADDR_DATA0_MEM_ADDR(dis_addr),
&bar0->rmac_addr_data0_mem);
writeq(RMAC_ADDR_DATA1_MEM_MASK(0ULL),
&bar0->rmac_addr_data1_mem);
val64 = RMAC_ADDR_CMD_MEM_WE |
RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET
(config->mc_start_offset + i);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait for command completes */
if (wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET)) {
DBG_PRINT(ERR_DBG,
"%s: Adding Multicasts failed\n",
dev->name);
return;
}
}
/* Create the new Rx filter list and update the same in H/W. */
i = 0;
netdev_for_each_mc_addr(ha, dev) {
mac_addr = 0;
for (j = 0; j < ETH_ALEN; j++) {
mac_addr |= ha->addr[j];
mac_addr <<= 8;
}
mac_addr >>= 8;
writeq(RMAC_ADDR_DATA0_MEM_ADDR(mac_addr),
&bar0->rmac_addr_data0_mem);
writeq(RMAC_ADDR_DATA1_MEM_MASK(0ULL),
&bar0->rmac_addr_data1_mem);
val64 = RMAC_ADDR_CMD_MEM_WE |
RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET
(i + config->mc_start_offset);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait for command completes */
if (wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET)) {
DBG_PRINT(ERR_DBG,
"%s: Adding Multicasts failed\n",
dev->name);
return;
}
i++;
}
}
}
/* read from CAM unicast & multicast addresses and store it in
* def_mac_addr structure
*/
static void do_s2io_store_unicast_mc(struct s2io_nic *sp)
{
int offset;
u64 mac_addr = 0x0;
struct config_param *config = &sp->config;
/* store unicast & multicast mac addresses */
for (offset = 0; offset < config->max_mc_addr; offset++) {
mac_addr = do_s2io_read_unicast_mc(sp, offset);
/* if read fails disable the entry */
if (mac_addr == FAILURE)
mac_addr = S2IO_DISABLE_MAC_ENTRY;
do_s2io_copy_mac_addr(sp, offset, mac_addr);
}
}
/* restore unicast & multicast MAC to CAM from def_mac_addr structure */
static void do_s2io_restore_unicast_mc(struct s2io_nic *sp)
{
int offset;
struct config_param *config = &sp->config;
/* restore unicast mac address */
for (offset = 0; offset < config->max_mac_addr; offset++)
do_s2io_prog_unicast(sp->dev,
sp->def_mac_addr[offset].mac_addr);
/* restore multicast mac address */
for (offset = config->mc_start_offset;
offset < config->max_mc_addr; offset++)
do_s2io_add_mc(sp, sp->def_mac_addr[offset].mac_addr);
}
/* add a multicast MAC address to CAM */
static int do_s2io_add_mc(struct s2io_nic *sp, u8 *addr)
{
int i;
u64 mac_addr = 0;
struct config_param *config = &sp->config;
for (i = 0; i < ETH_ALEN; i++) {
mac_addr <<= 8;
mac_addr |= addr[i];
}
if ((0ULL == mac_addr) || (mac_addr == S2IO_DISABLE_MAC_ENTRY))
return SUCCESS;
/* check if the multicast mac already preset in CAM */
for (i = config->mc_start_offset; i < config->max_mc_addr; i++) {
u64 tmp64;
tmp64 = do_s2io_read_unicast_mc(sp, i);
if (tmp64 == S2IO_DISABLE_MAC_ENTRY) /* CAM entry is empty */
break;
if (tmp64 == mac_addr)
return SUCCESS;
}
if (i == config->max_mc_addr) {
DBG_PRINT(ERR_DBG,
"CAM full no space left for multicast MAC\n");
return FAILURE;
}
/* Update the internal structure with this new mac address */
do_s2io_copy_mac_addr(sp, i, mac_addr);
return do_s2io_add_mac(sp, mac_addr, i);
}
/* add MAC address to CAM */
static int do_s2io_add_mac(struct s2io_nic *sp, u64 addr, int off)
{
u64 val64;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
writeq(RMAC_ADDR_DATA0_MEM_ADDR(addr),
&bar0->rmac_addr_data0_mem);
val64 = RMAC_ADDR_CMD_MEM_WE | RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET(off);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait till command completes */
if (wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET)) {
DBG_PRINT(INFO_DBG, "do_s2io_add_mac failed\n");
return FAILURE;
}
return SUCCESS;
}
/* deletes a specified unicast/multicast mac entry from CAM */
static int do_s2io_delete_unicast_mc(struct s2io_nic *sp, u64 addr)
{
int offset;
u64 dis_addr = S2IO_DISABLE_MAC_ENTRY, tmp64;
struct config_param *config = &sp->config;
for (offset = 1;
offset < config->max_mc_addr; offset++) {
tmp64 = do_s2io_read_unicast_mc(sp, offset);
if (tmp64 == addr) {
/* disable the entry by writing 0xffffffffffffULL */
if (do_s2io_add_mac(sp, dis_addr, offset) == FAILURE)
return FAILURE;
/* store the new mac list from CAM */
do_s2io_store_unicast_mc(sp);
return SUCCESS;
}
}
DBG_PRINT(ERR_DBG, "MAC address 0x%llx not found in CAM\n",
(unsigned long long)addr);
return FAILURE;
}
/* read mac entries from CAM */
static u64 do_s2io_read_unicast_mc(struct s2io_nic *sp, int offset)
{
u64 tmp64 = 0xffffffffffff0000ULL, val64;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
/* read mac addr */
val64 = RMAC_ADDR_CMD_MEM_RD | RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET(offset);
writeq(val64, &bar0->rmac_addr_cmd_mem);
/* Wait till command completes */
if (wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET)) {
DBG_PRINT(INFO_DBG, "do_s2io_read_unicast_mc failed\n");
return FAILURE;
}
tmp64 = readq(&bar0->rmac_addr_data0_mem);
return tmp64 >> 16;
}
/**
* s2io_set_mac_addr driver entry point
*/
static int s2io_set_mac_addr(struct net_device *dev, void *p)
{
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
/* store the MAC address in CAM */
return do_s2io_prog_unicast(dev, dev->dev_addr);
}
/**
* do_s2io_prog_unicast - Programs the Xframe mac address
* @dev : pointer to the device structure.
* @addr: a uchar pointer to the new mac address which is to be set.
* Description : This procedure will program the Xframe to receive
* frames with new Mac Address
* Return value: SUCCESS on success and an appropriate (-)ve integer
* as defined in errno.h file on failure.
*/
static int do_s2io_prog_unicast(struct net_device *dev, u8 *addr)
{
struct s2io_nic *sp = netdev_priv(dev);
register u64 mac_addr = 0, perm_addr = 0;
int i;
u64 tmp64;
struct config_param *config = &sp->config;
/*
* Set the new MAC address as the new unicast filter and reflect this
* change on the device address registered with the OS. It will be
* at offset 0.
*/
for (i = 0; i < ETH_ALEN; i++) {
mac_addr <<= 8;
mac_addr |= addr[i];
perm_addr <<= 8;
perm_addr |= sp->def_mac_addr[0].mac_addr[i];
}
/* check if the dev_addr is different than perm_addr */
if (mac_addr == perm_addr)
return SUCCESS;
/* check if the mac already preset in CAM */
for (i = 1; i < config->max_mac_addr; i++) {
tmp64 = do_s2io_read_unicast_mc(sp, i);
if (tmp64 == S2IO_DISABLE_MAC_ENTRY) /* CAM entry is empty */
break;
if (tmp64 == mac_addr) {
DBG_PRINT(INFO_DBG,
"MAC addr:0x%llx already present in CAM\n",
(unsigned long long)mac_addr);
return SUCCESS;
}
}
if (i == config->max_mac_addr) {
DBG_PRINT(ERR_DBG, "CAM full no space left for Unicast MAC\n");
return FAILURE;
}
/* Update the internal structure with this new mac address */
do_s2io_copy_mac_addr(sp, i, mac_addr);
return do_s2io_add_mac(sp, mac_addr, i);
}
/**
* s2io_ethtool_sset - Sets different link parameters.
* @sp : private member of the device structure, which is a pointer to the * s2io_nic structure.
* @info: pointer to the structure with parameters given by ethtool to set
* link information.
* Description:
* The function sets different link parameters provided by the user onto
* the NIC.
* Return value:
* 0 on success.
*/
static int s2io_ethtool_sset(struct net_device *dev,
struct ethtool_cmd *info)
{
struct s2io_nic *sp = netdev_priv(dev);
if ((info->autoneg == AUTONEG_ENABLE) ||
(ethtool_cmd_speed(info) != SPEED_10000) ||
(info->duplex != DUPLEX_FULL))
return -EINVAL;
else {
s2io_close(sp->dev);
s2io_open(sp->dev);
}
return 0;
}
/**
* s2io_ethtol_gset - Return link specific information.
* @sp : private member of the device structure, pointer to the
* s2io_nic structure.
* @info : pointer to the structure with parameters given by ethtool
* to return link information.
* Description:
* Returns link specific information like speed, duplex etc.. to ethtool.
* Return value :
* return 0 on success.
*/
static int s2io_ethtool_gset(struct net_device *dev, struct ethtool_cmd *info)
{
struct s2io_nic *sp = netdev_priv(dev);
info->supported = (SUPPORTED_10000baseT_Full | SUPPORTED_FIBRE);
info->advertising = (SUPPORTED_10000baseT_Full | SUPPORTED_FIBRE);
info->port = PORT_FIBRE;
/* info->transceiver */
info->transceiver = XCVR_EXTERNAL;
if (netif_carrier_ok(sp->dev)) {
ethtool_cmd_speed_set(info, SPEED_10000);
info->duplex = DUPLEX_FULL;
} else {
ethtool_cmd_speed_set(info, -1);
info->duplex = -1;
}
info->autoneg = AUTONEG_DISABLE;
return 0;
}
/**
* s2io_ethtool_gdrvinfo - Returns driver specific information.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @info : pointer to the structure with parameters given by ethtool to
* return driver information.
* Description:
* Returns driver specefic information like name, version etc.. to ethtool.
* Return value:
* void
*/
static void s2io_ethtool_gdrvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct s2io_nic *sp = netdev_priv(dev);
strlcpy(info->driver, s2io_driver_name, sizeof(info->driver));
strlcpy(info->version, s2io_driver_version, sizeof(info->version));
strlcpy(info->bus_info, pci_name(sp->pdev), sizeof(info->bus_info));
info->regdump_len = XENA_REG_SPACE;
info->eedump_len = XENA_EEPROM_SPACE;
}
/**
* s2io_ethtool_gregs - dumps the entire space of Xfame into the buffer.
* @sp: private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @regs : pointer to the structure with parameters given by ethtool for
* dumping the registers.
* @reg_space: The input argumnet into which all the registers are dumped.
* Description:
* Dumps the entire register space of xFrame NIC into the user given
* buffer area.
* Return value :
* void .
*/
static void s2io_ethtool_gregs(struct net_device *dev,
struct ethtool_regs *regs, void *space)
{
int i;
u64 reg;
u8 *reg_space = (u8 *)space;
struct s2io_nic *sp = netdev_priv(dev);
regs->len = XENA_REG_SPACE;
regs->version = sp->pdev->subsystem_device;
for (i = 0; i < regs->len; i += 8) {
reg = readq(sp->bar0 + i);
memcpy((reg_space + i), ®, 8);
}
}
/*
* s2io_set_led - control NIC led
*/
static void s2io_set_led(struct s2io_nic *sp, bool on)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u16 subid = sp->pdev->subsystem_device;
u64 val64;
if ((sp->device_type == XFRAME_II_DEVICE) ||
((subid & 0xFF) >= 0x07)) {
val64 = readq(&bar0->gpio_control);
if (on)
val64 |= GPIO_CTRL_GPIO_0;
else
val64 &= ~GPIO_CTRL_GPIO_0;
writeq(val64, &bar0->gpio_control);
} else {
val64 = readq(&bar0->adapter_control);
if (on)
val64 |= ADAPTER_LED_ON;
else
val64 &= ~ADAPTER_LED_ON;
writeq(val64, &bar0->adapter_control);
}
}
/**
* s2io_ethtool_set_led - To physically identify the nic on the system.
* @dev : network device
* @state: led setting
*
* Description: Used to physically identify the NIC on the system.
* The Link LED will blink for a time specified by the user for
* identification.
* NOTE: The Link has to be Up to be able to blink the LED. Hence
* identification is possible only if it's link is up.
*/
static int s2io_ethtool_set_led(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u16 subid = sp->pdev->subsystem_device;
if ((sp->device_type == XFRAME_I_DEVICE) && ((subid & 0xFF) < 0x07)) {
u64 val64 = readq(&bar0->adapter_control);
if (!(val64 & ADAPTER_CNTL_EN)) {
pr_err("Adapter Link down, cannot blink LED\n");
return -EAGAIN;
}
}
switch (state) {
case ETHTOOL_ID_ACTIVE:
sp->adapt_ctrl_org = readq(&bar0->gpio_control);
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_ON:
s2io_set_led(sp, true);
break;
case ETHTOOL_ID_OFF:
s2io_set_led(sp, false);
break;
case ETHTOOL_ID_INACTIVE:
if (CARDS_WITH_FAULTY_LINK_INDICATORS(sp->device_type, subid))
writeq(sp->adapt_ctrl_org, &bar0->gpio_control);
}
return 0;
}
static void s2io_ethtool_gringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct s2io_nic *sp = netdev_priv(dev);
int i, tx_desc_count = 0, rx_desc_count = 0;
if (sp->rxd_mode == RXD_MODE_1) {
ering->rx_max_pending = MAX_RX_DESC_1;
ering->rx_jumbo_max_pending = MAX_RX_DESC_1;
} else {
ering->rx_max_pending = MAX_RX_DESC_2;
ering->rx_jumbo_max_pending = MAX_RX_DESC_2;
}
ering->tx_max_pending = MAX_TX_DESC;
for (i = 0; i < sp->config.rx_ring_num; i++)
rx_desc_count += sp->config.rx_cfg[i].num_rxd;
ering->rx_pending = rx_desc_count;
ering->rx_jumbo_pending = rx_desc_count;
for (i = 0; i < sp->config.tx_fifo_num; i++)
tx_desc_count += sp->config.tx_cfg[i].fifo_len;
ering->tx_pending = tx_desc_count;
DBG_PRINT(INFO_DBG, "max txds: %d\n", sp->config.max_txds);
}
/**
* s2io_ethtool_getpause_data -Pause frame frame generation and reception.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @ep : pointer to the structure with pause parameters given by ethtool.
* Description:
* Returns the Pause frame generation and reception capability of the NIC.
* Return value:
* void
*/
static void s2io_ethtool_getpause_data(struct net_device *dev,
struct ethtool_pauseparam *ep)
{
u64 val64;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
val64 = readq(&bar0->rmac_pause_cfg);
if (val64 & RMAC_PAUSE_GEN_ENABLE)
ep->tx_pause = true;
if (val64 & RMAC_PAUSE_RX_ENABLE)
ep->rx_pause = true;
ep->autoneg = false;
}
/**
* s2io_ethtool_setpause_data - set/reset pause frame generation.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @ep : pointer to the structure with pause parameters given by ethtool.
* Description:
* It can be used to set or reset Pause frame generation or reception
* support of the NIC.
* Return value:
* int, returns 0 on Success
*/
static int s2io_ethtool_setpause_data(struct net_device *dev,
struct ethtool_pauseparam *ep)
{
u64 val64;
struct s2io_nic *sp = netdev_priv(dev);
struct XENA_dev_config __iomem *bar0 = sp->bar0;
val64 = readq(&bar0->rmac_pause_cfg);
if (ep->tx_pause)
val64 |= RMAC_PAUSE_GEN_ENABLE;
else
val64 &= ~RMAC_PAUSE_GEN_ENABLE;
if (ep->rx_pause)
val64 |= RMAC_PAUSE_RX_ENABLE;
else
val64 &= ~RMAC_PAUSE_RX_ENABLE;
writeq(val64, &bar0->rmac_pause_cfg);
return 0;
}
/**
* read_eeprom - reads 4 bytes of data from user given offset.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @off : offset at which the data must be written
* @data : Its an output parameter where the data read at the given
* offset is stored.
* Description:
* Will read 4 bytes of data from the user given offset and return the
* read data.
* NOTE: Will allow to read only part of the EEPROM visible through the
* I2C bus.
* Return value:
* -1 on failure and 0 on success.
*/
#define S2IO_DEV_ID 5
static int read_eeprom(struct s2io_nic *sp, int off, u64 *data)
{
int ret = -1;
u32 exit_cnt = 0;
u64 val64;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
if (sp->device_type == XFRAME_I_DEVICE) {
val64 = I2C_CONTROL_DEV_ID(S2IO_DEV_ID) |
I2C_CONTROL_ADDR(off) |
I2C_CONTROL_BYTE_CNT(0x3) |
I2C_CONTROL_READ |
I2C_CONTROL_CNTL_START;
SPECIAL_REG_WRITE(val64, &bar0->i2c_control, LF);
while (exit_cnt < 5) {
val64 = readq(&bar0->i2c_control);
if (I2C_CONTROL_CNTL_END(val64)) {
*data = I2C_CONTROL_GET_DATA(val64);
ret = 0;
break;
}
msleep(50);
exit_cnt++;
}
}
if (sp->device_type == XFRAME_II_DEVICE) {
val64 = SPI_CONTROL_KEY(0x9) | SPI_CONTROL_SEL1 |
SPI_CONTROL_BYTECNT(0x3) |
SPI_CONTROL_CMD(0x3) | SPI_CONTROL_ADDR(off);
SPECIAL_REG_WRITE(val64, &bar0->spi_control, LF);
val64 |= SPI_CONTROL_REQ;
SPECIAL_REG_WRITE(val64, &bar0->spi_control, LF);
while (exit_cnt < 5) {
val64 = readq(&bar0->spi_control);
if (val64 & SPI_CONTROL_NACK) {
ret = 1;
break;
} else if (val64 & SPI_CONTROL_DONE) {
*data = readq(&bar0->spi_data);
*data &= 0xffffff;
ret = 0;
break;
}
msleep(50);
exit_cnt++;
}
}
return ret;
}
/**
* write_eeprom - actually writes the relevant part of the data value.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @off : offset at which the data must be written
* @data : The data that is to be written
* @cnt : Number of bytes of the data that are actually to be written into
* the Eeprom. (max of 3)
* Description:
* Actually writes the relevant part of the data value into the Eeprom
* through the I2C bus.
* Return value:
* 0 on success, -1 on failure.
*/
static int write_eeprom(struct s2io_nic *sp, int off, u64 data, int cnt)
{
int exit_cnt = 0, ret = -1;
u64 val64;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
if (sp->device_type == XFRAME_I_DEVICE) {
val64 = I2C_CONTROL_DEV_ID(S2IO_DEV_ID) |
I2C_CONTROL_ADDR(off) |
I2C_CONTROL_BYTE_CNT(cnt) |
I2C_CONTROL_SET_DATA((u32)data) |
I2C_CONTROL_CNTL_START;
SPECIAL_REG_WRITE(val64, &bar0->i2c_control, LF);
while (exit_cnt < 5) {
val64 = readq(&bar0->i2c_control);
if (I2C_CONTROL_CNTL_END(val64)) {
if (!(val64 & I2C_CONTROL_NACK))
ret = 0;
break;
}
msleep(50);
exit_cnt++;
}
}
if (sp->device_type == XFRAME_II_DEVICE) {
int write_cnt = (cnt == 8) ? 0 : cnt;
writeq(SPI_DATA_WRITE(data, (cnt << 3)), &bar0->spi_data);
val64 = SPI_CONTROL_KEY(0x9) | SPI_CONTROL_SEL1 |
SPI_CONTROL_BYTECNT(write_cnt) |
SPI_CONTROL_CMD(0x2) | SPI_CONTROL_ADDR(off);
SPECIAL_REG_WRITE(val64, &bar0->spi_control, LF);
val64 |= SPI_CONTROL_REQ;
SPECIAL_REG_WRITE(val64, &bar0->spi_control, LF);
while (exit_cnt < 5) {
val64 = readq(&bar0->spi_control);
if (val64 & SPI_CONTROL_NACK) {
ret = 1;
break;
} else if (val64 & SPI_CONTROL_DONE) {
ret = 0;
break;
}
msleep(50);
exit_cnt++;
}
}
return ret;
}
static void s2io_vpd_read(struct s2io_nic *nic)
{
u8 *vpd_data;
u8 data;
int i = 0, cnt, len, fail = 0;
int vpd_addr = 0x80;
struct swStat *swstats = &nic->mac_control.stats_info->sw_stat;
if (nic->device_type == XFRAME_II_DEVICE) {
strcpy(nic->product_name, "Xframe II 10GbE network adapter");
vpd_addr = 0x80;
} else {
strcpy(nic->product_name, "Xframe I 10GbE network adapter");
vpd_addr = 0x50;
}
strcpy(nic->serial_num, "NOT AVAILABLE");
vpd_data = kmalloc(256, GFP_KERNEL);
if (!vpd_data) {
swstats->mem_alloc_fail_cnt++;
return;
}
swstats->mem_allocated += 256;
for (i = 0; i < 256; i += 4) {
pci_write_config_byte(nic->pdev, (vpd_addr + 2), i);
pci_read_config_byte(nic->pdev, (vpd_addr + 2), &data);
pci_write_config_byte(nic->pdev, (vpd_addr + 3), 0);
for (cnt = 0; cnt < 5; cnt++) {
msleep(2);
pci_read_config_byte(nic->pdev, (vpd_addr + 3), &data);
if (data == 0x80)
break;
}
if (cnt >= 5) {
DBG_PRINT(ERR_DBG, "Read of VPD data failed\n");
fail = 1;
break;
}
pci_read_config_dword(nic->pdev, (vpd_addr + 4),
(u32 *)&vpd_data[i]);
}
if (!fail) {
/* read serial number of adapter */
for (cnt = 0; cnt < 252; cnt++) {
if ((vpd_data[cnt] == 'S') &&
(vpd_data[cnt+1] == 'N')) {
len = vpd_data[cnt+2];
if (len < min(VPD_STRING_LEN, 256-cnt-2)) {
memcpy(nic->serial_num,
&vpd_data[cnt + 3],
len);
memset(nic->serial_num+len,
0,
VPD_STRING_LEN-len);
break;
}
}
}
}
if ((!fail) && (vpd_data[1] < VPD_STRING_LEN)) {
len = vpd_data[1];
memcpy(nic->product_name, &vpd_data[3], len);
nic->product_name[len] = 0;
}
kfree(vpd_data);
swstats->mem_freed += 256;
}
/**
* s2io_ethtool_geeprom - reads the value stored in the Eeprom.
* @sp : private member of the device structure, which is a pointer to the * s2io_nic structure.
* @eeprom : pointer to the user level structure provided by ethtool,
* containing all relevant information.
* @data_buf : user defined value to be written into Eeprom.
* Description: Reads the values stored in the Eeprom at given offset
* for a given length. Stores these values int the input argument data
* buffer 'data_buf' and returns these to the caller (ethtool.)
* Return value:
* int 0 on success
*/
static int s2io_ethtool_geeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 * data_buf)
{
u32 i, valid;
u64 data;
struct s2io_nic *sp = netdev_priv(dev);
eeprom->magic = sp->pdev->vendor | (sp->pdev->device << 16);
if ((eeprom->offset + eeprom->len) > (XENA_EEPROM_SPACE))
eeprom->len = XENA_EEPROM_SPACE - eeprom->offset;
for (i = 0; i < eeprom->len; i += 4) {
if (read_eeprom(sp, (eeprom->offset + i), &data)) {
DBG_PRINT(ERR_DBG, "Read of EEPROM failed\n");
return -EFAULT;
}
valid = INV(data);
memcpy((data_buf + i), &valid, 4);
}
return 0;
}
/**
* s2io_ethtool_seeprom - tries to write the user provided value in Eeprom
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @eeprom : pointer to the user level structure provided by ethtool,
* containing all relevant information.
* @data_buf ; user defined value to be written into Eeprom.
* Description:
* Tries to write the user provided value in the Eeprom, at the offset
* given by the user.
* Return value:
* 0 on success, -EFAULT on failure.
*/
static int s2io_ethtool_seeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom,
u8 *data_buf)
{
int len = eeprom->len, cnt = 0;
u64 valid = 0, data;
struct s2io_nic *sp = netdev_priv(dev);
if (eeprom->magic != (sp->pdev->vendor | (sp->pdev->device << 16))) {
DBG_PRINT(ERR_DBG,
"ETHTOOL_WRITE_EEPROM Err: "
"Magic value is wrong, it is 0x%x should be 0x%x\n",
(sp->pdev->vendor | (sp->pdev->device << 16)),
eeprom->magic);
return -EFAULT;
}
while (len) {
data = (u32)data_buf[cnt] & 0x000000FF;
if (data)
valid = (u32)(data << 24);
else
valid = data;
if (write_eeprom(sp, (eeprom->offset + cnt), valid, 0)) {
DBG_PRINT(ERR_DBG,
"ETHTOOL_WRITE_EEPROM Err: "
"Cannot write into the specified offset\n");
return -EFAULT;
}
cnt++;
len--;
}
return 0;
}
/**
* s2io_register_test - reads and writes into all clock domains.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @data : variable that returns the result of each of the test conducted b
* by the driver.
* Description:
* Read and write into all clock domains. The NIC has 3 clock domains,
* see that registers in all the three regions are accessible.
* Return value:
* 0 on success.
*/
static int s2io_register_test(struct s2io_nic *sp, uint64_t *data)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64 = 0, exp_val;
int fail = 0;
val64 = readq(&bar0->pif_rd_swapper_fb);
if (val64 != 0x123456789abcdefULL) {
fail = 1;
DBG_PRINT(INFO_DBG, "Read Test level %d fails\n", 1);
}
val64 = readq(&bar0->rmac_pause_cfg);
if (val64 != 0xc000ffff00000000ULL) {
fail = 1;
DBG_PRINT(INFO_DBG, "Read Test level %d fails\n", 2);
}
val64 = readq(&bar0->rx_queue_cfg);
if (sp->device_type == XFRAME_II_DEVICE)
exp_val = 0x0404040404040404ULL;
else
exp_val = 0x0808080808080808ULL;
if (val64 != exp_val) {
fail = 1;
DBG_PRINT(INFO_DBG, "Read Test level %d fails\n", 3);
}
val64 = readq(&bar0->xgxs_efifo_cfg);
if (val64 != 0x000000001923141EULL) {
fail = 1;
DBG_PRINT(INFO_DBG, "Read Test level %d fails\n", 4);
}
val64 = 0x5A5A5A5A5A5A5A5AULL;
writeq(val64, &bar0->xmsi_data);
val64 = readq(&bar0->xmsi_data);
if (val64 != 0x5A5A5A5A5A5A5A5AULL) {
fail = 1;
DBG_PRINT(ERR_DBG, "Write Test level %d fails\n", 1);
}
val64 = 0xA5A5A5A5A5A5A5A5ULL;
writeq(val64, &bar0->xmsi_data);
val64 = readq(&bar0->xmsi_data);
if (val64 != 0xA5A5A5A5A5A5A5A5ULL) {
fail = 1;
DBG_PRINT(ERR_DBG, "Write Test level %d fails\n", 2);
}
*data = fail;
return fail;
}
/**
* s2io_eeprom_test - to verify that EEprom in the xena can be programmed.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @data:variable that returns the result of each of the test conducted by
* the driver.
* Description:
* Verify that EEPROM in the xena can be programmed using I2C_CONTROL
* register.
* Return value:
* 0 on success.
*/
static int s2io_eeprom_test(struct s2io_nic *sp, uint64_t *data)
{
int fail = 0;
u64 ret_data, org_4F0, org_7F0;
u8 saved_4F0 = 0, saved_7F0 = 0;
struct net_device *dev = sp->dev;
/* Test Write Error at offset 0 */
/* Note that SPI interface allows write access to all areas
* of EEPROM. Hence doing all negative testing only for Xframe I.
*/
if (sp->device_type == XFRAME_I_DEVICE)
if (!write_eeprom(sp, 0, 0, 3))
fail = 1;
/* Save current values at offsets 0x4F0 and 0x7F0 */
if (!read_eeprom(sp, 0x4F0, &org_4F0))
saved_4F0 = 1;
if (!read_eeprom(sp, 0x7F0, &org_7F0))
saved_7F0 = 1;
/* Test Write at offset 4f0 */
if (write_eeprom(sp, 0x4F0, 0x012345, 3))
fail = 1;
if (read_eeprom(sp, 0x4F0, &ret_data))
fail = 1;
if (ret_data != 0x012345) {
DBG_PRINT(ERR_DBG, "%s: eeprom test error at offset 0x4F0. "
"Data written %llx Data read %llx\n",
dev->name, (unsigned long long)0x12345,
(unsigned long long)ret_data);
fail = 1;
}
/* Reset the EEPROM data go FFFF */
write_eeprom(sp, 0x4F0, 0xFFFFFF, 3);
/* Test Write Request Error at offset 0x7c */
if (sp->device_type == XFRAME_I_DEVICE)
if (!write_eeprom(sp, 0x07C, 0, 3))
fail = 1;
/* Test Write Request at offset 0x7f0 */
if (write_eeprom(sp, 0x7F0, 0x012345, 3))
fail = 1;
if (read_eeprom(sp, 0x7F0, &ret_data))
fail = 1;
if (ret_data != 0x012345) {
DBG_PRINT(ERR_DBG, "%s: eeprom test error at offset 0x7F0. "
"Data written %llx Data read %llx\n",
dev->name, (unsigned long long)0x12345,
(unsigned long long)ret_data);
fail = 1;
}
/* Reset the EEPROM data go FFFF */
write_eeprom(sp, 0x7F0, 0xFFFFFF, 3);
if (sp->device_type == XFRAME_I_DEVICE) {
/* Test Write Error at offset 0x80 */
if (!write_eeprom(sp, 0x080, 0, 3))
fail = 1;
/* Test Write Error at offset 0xfc */
if (!write_eeprom(sp, 0x0FC, 0, 3))
fail = 1;
/* Test Write Error at offset 0x100 */
if (!write_eeprom(sp, 0x100, 0, 3))
fail = 1;
/* Test Write Error at offset 4ec */
if (!write_eeprom(sp, 0x4EC, 0, 3))
fail = 1;
}
/* Restore values at offsets 0x4F0 and 0x7F0 */
if (saved_4F0)
write_eeprom(sp, 0x4F0, org_4F0, 3);
if (saved_7F0)
write_eeprom(sp, 0x7F0, org_7F0, 3);
*data = fail;
return fail;
}
/**
* s2io_bist_test - invokes the MemBist test of the card .
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @data:variable that returns the result of each of the test conducted by
* the driver.
* Description:
* This invokes the MemBist test of the card. We give around
* 2 secs time for the Test to complete. If it's still not complete
* within this peiod, we consider that the test failed.
* Return value:
* 0 on success and -1 on failure.
*/
static int s2io_bist_test(struct s2io_nic *sp, uint64_t *data)
{
u8 bist = 0;
int cnt = 0, ret = -1;
pci_read_config_byte(sp->pdev, PCI_BIST, &bist);
bist |= PCI_BIST_START;
pci_write_config_word(sp->pdev, PCI_BIST, bist);
while (cnt < 20) {
pci_read_config_byte(sp->pdev, PCI_BIST, &bist);
if (!(bist & PCI_BIST_START)) {
*data = (bist & PCI_BIST_CODE_MASK);
ret = 0;
break;
}
msleep(100);
cnt++;
}
return ret;
}
/**
* s2io-link_test - verifies the link state of the nic
* @sp ; private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @data: variable that returns the result of each of the test conducted by
* the driver.
* Description:
* The function verifies the link state of the NIC and updates the input
* argument 'data' appropriately.
* Return value:
* 0 on success.
*/
static int s2io_link_test(struct s2io_nic *sp, uint64_t *data)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64;
val64 = readq(&bar0->adapter_status);
if (!(LINK_IS_UP(val64)))
*data = 1;
else
*data = 0;
return *data;
}
/**
* s2io_rldram_test - offline test for access to the RldRam chip on the NIC
* @sp - private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @data - variable that returns the result of each of the test
* conducted by the driver.
* Description:
* This is one of the offline test that tests the read and write
* access to the RldRam chip on the NIC.
* Return value:
* 0 on success.
*/
static int s2io_rldram_test(struct s2io_nic *sp, uint64_t *data)
{
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64;
int cnt, iteration = 0, test_fail = 0;
val64 = readq(&bar0->adapter_control);
val64 &= ~ADAPTER_ECC_EN;
writeq(val64, &bar0->adapter_control);
val64 = readq(&bar0->mc_rldram_test_ctrl);
val64 |= MC_RLDRAM_TEST_MODE;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_test_ctrl, LF);
val64 = readq(&bar0->mc_rldram_mrs);
val64 |= MC_RLDRAM_QUEUE_SIZE_ENABLE;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_mrs, UF);
val64 |= MC_RLDRAM_MRS_ENABLE;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_mrs, UF);
while (iteration < 2) {
val64 = 0x55555555aaaa0000ULL;
if (iteration == 1)
val64 ^= 0xFFFFFFFFFFFF0000ULL;
writeq(val64, &bar0->mc_rldram_test_d0);
val64 = 0xaaaa5a5555550000ULL;
if (iteration == 1)
val64 ^= 0xFFFFFFFFFFFF0000ULL;
writeq(val64, &bar0->mc_rldram_test_d1);
val64 = 0x55aaaaaaaa5a0000ULL;
if (iteration == 1)
val64 ^= 0xFFFFFFFFFFFF0000ULL;
writeq(val64, &bar0->mc_rldram_test_d2);
val64 = (u64) (0x0000003ffffe0100ULL);
writeq(val64, &bar0->mc_rldram_test_add);
val64 = MC_RLDRAM_TEST_MODE |
MC_RLDRAM_TEST_WRITE |
MC_RLDRAM_TEST_GO;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_test_ctrl, LF);
for (cnt = 0; cnt < 5; cnt++) {
val64 = readq(&bar0->mc_rldram_test_ctrl);
if (val64 & MC_RLDRAM_TEST_DONE)
break;
msleep(200);
}
if (cnt == 5)
break;
val64 = MC_RLDRAM_TEST_MODE | MC_RLDRAM_TEST_GO;
SPECIAL_REG_WRITE(val64, &bar0->mc_rldram_test_ctrl, LF);
for (cnt = 0; cnt < 5; cnt++) {
val64 = readq(&bar0->mc_rldram_test_ctrl);
if (val64 & MC_RLDRAM_TEST_DONE)
break;
msleep(500);
}
if (cnt == 5)
break;
val64 = readq(&bar0->mc_rldram_test_ctrl);
if (!(val64 & MC_RLDRAM_TEST_PASS))
test_fail = 1;
iteration++;
}
*data = test_fail;
/* Bring the adapter out of test mode */
SPECIAL_REG_WRITE(0, &bar0->mc_rldram_test_ctrl, LF);
return test_fail;
}
/**
* s2io_ethtool_test - conducts 6 tsets to determine the health of card.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @ethtest : pointer to a ethtool command specific structure that will be
* returned to the user.
* @data : variable that returns the result of each of the test
* conducted by the driver.
* Description:
* This function conducts 6 tests ( 4 offline and 2 online) to determine
* the health of the card.
* Return value:
* void
*/
static void s2io_ethtool_test(struct net_device *dev,
struct ethtool_test *ethtest,
uint64_t *data)
{
struct s2io_nic *sp = netdev_priv(dev);
int orig_state = netif_running(sp->dev);
if (ethtest->flags == ETH_TEST_FL_OFFLINE) {
/* Offline Tests. */
if (orig_state)
s2io_close(sp->dev);
if (s2io_register_test(sp, &data[0]))
ethtest->flags |= ETH_TEST_FL_FAILED;
s2io_reset(sp);
if (s2io_rldram_test(sp, &data[3]))
ethtest->flags |= ETH_TEST_FL_FAILED;
s2io_reset(sp);
if (s2io_eeprom_test(sp, &data[1]))
ethtest->flags |= ETH_TEST_FL_FAILED;
if (s2io_bist_test(sp, &data[4]))
ethtest->flags |= ETH_TEST_FL_FAILED;
if (orig_state)
s2io_open(sp->dev);
data[2] = 0;
} else {
/* Online Tests. */
if (!orig_state) {
DBG_PRINT(ERR_DBG, "%s: is not up, cannot run test\n",
dev->name);
data[0] = -1;
data[1] = -1;
data[2] = -1;
data[3] = -1;
data[4] = -1;
}
if (s2io_link_test(sp, &data[2]))
ethtest->flags |= ETH_TEST_FL_FAILED;
data[0] = 0;
data[1] = 0;
data[3] = 0;
data[4] = 0;
}
}
static void s2io_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *estats,
u64 *tmp_stats)
{
int i = 0, k;
struct s2io_nic *sp = netdev_priv(dev);
struct stat_block *stats = sp->mac_control.stats_info;
struct swStat *swstats = &stats->sw_stat;
struct xpakStat *xstats = &stats->xpak_stat;
s2io_updt_stats(sp);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_data_octets_oflow) << 32 |
le32_to_cpu(stats->tmac_data_octets);
tmp_stats[i++] = le64_to_cpu(stats->tmac_drop_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_mcst_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_mcst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_bcst_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_bcst_frms);
tmp_stats[i++] = le64_to_cpu(stats->tmac_pause_ctrl_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_ttl_octets_oflow) << 32 |
le32_to_cpu(stats->tmac_ttl_octets);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_ucst_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_ucst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_nucst_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_nucst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_any_err_frms_oflow) << 32 |
le32_to_cpu(stats->tmac_any_err_frms);
tmp_stats[i++] = le64_to_cpu(stats->tmac_ttl_less_fb_octets);
tmp_stats[i++] = le64_to_cpu(stats->tmac_vld_ip_octets);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_vld_ip_oflow) << 32 |
le32_to_cpu(stats->tmac_vld_ip);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_drop_ip_oflow) << 32 |
le32_to_cpu(stats->tmac_drop_ip);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_icmp_oflow) << 32 |
le32_to_cpu(stats->tmac_icmp);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->tmac_rst_tcp_oflow) << 32 |
le32_to_cpu(stats->tmac_rst_tcp);
tmp_stats[i++] = le64_to_cpu(stats->tmac_tcp);
tmp_stats[i++] = (u64)le32_to_cpu(stats->tmac_udp_oflow) << 32 |
le32_to_cpu(stats->tmac_udp);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_vld_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_vld_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_data_octets_oflow) << 32 |
le32_to_cpu(stats->rmac_data_octets);
tmp_stats[i++] = le64_to_cpu(stats->rmac_fcs_err_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_drop_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_vld_mcst_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_vld_mcst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_vld_bcst_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_vld_bcst_frms);
tmp_stats[i++] = le32_to_cpu(stats->rmac_in_rng_len_err_frms);
tmp_stats[i++] = le32_to_cpu(stats->rmac_out_rng_len_err_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_long_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_pause_ctrl_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_unsup_ctrl_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_ttl_octets_oflow) << 32 |
le32_to_cpu(stats->rmac_ttl_octets);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_accepted_ucst_frms_oflow) << 32
| le32_to_cpu(stats->rmac_accepted_ucst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_accepted_nucst_frms_oflow)
<< 32 | le32_to_cpu(stats->rmac_accepted_nucst_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_discarded_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_discarded_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_drop_events_oflow)
<< 32 | le32_to_cpu(stats->rmac_drop_events);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_less_fb_octets);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_usized_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_usized_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_osized_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_osized_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_frag_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_frag_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_jabber_frms_oflow) << 32 |
le32_to_cpu(stats->rmac_jabber_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_64_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_65_127_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_128_255_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_256_511_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_512_1023_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_1024_1518_frms);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_ip_oflow) << 32 |
le32_to_cpu(stats->rmac_ip);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ip_octets);
tmp_stats[i++] = le32_to_cpu(stats->rmac_hdr_err_ip);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_drop_ip_oflow) << 32 |
le32_to_cpu(stats->rmac_drop_ip);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_icmp_oflow) << 32 |
le32_to_cpu(stats->rmac_icmp);
tmp_stats[i++] = le64_to_cpu(stats->rmac_tcp);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_udp_oflow) << 32 |
le32_to_cpu(stats->rmac_udp);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_err_drp_udp_oflow) << 32 |
le32_to_cpu(stats->rmac_err_drp_udp);
tmp_stats[i++] = le64_to_cpu(stats->rmac_xgmii_err_sym);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q0);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q1);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q2);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q3);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q4);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q5);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q6);
tmp_stats[i++] = le64_to_cpu(stats->rmac_frms_q7);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q0);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q1);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q2);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q3);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q4);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q5);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q6);
tmp_stats[i++] = le16_to_cpu(stats->rmac_full_q7);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_pause_cnt_oflow) << 32 |
le32_to_cpu(stats->rmac_pause_cnt);
tmp_stats[i++] = le64_to_cpu(stats->rmac_xgmii_data_err_cnt);
tmp_stats[i++] = le64_to_cpu(stats->rmac_xgmii_ctrl_err_cnt);
tmp_stats[i++] =
(u64)le32_to_cpu(stats->rmac_accepted_ip_oflow) << 32 |
le32_to_cpu(stats->rmac_accepted_ip);
tmp_stats[i++] = le32_to_cpu(stats->rmac_err_tcp);
tmp_stats[i++] = le32_to_cpu(stats->rd_req_cnt);
tmp_stats[i++] = le32_to_cpu(stats->new_rd_req_cnt);
tmp_stats[i++] = le32_to_cpu(stats->new_rd_req_rtry_cnt);
tmp_stats[i++] = le32_to_cpu(stats->rd_rtry_cnt);
tmp_stats[i++] = le32_to_cpu(stats->wr_rtry_rd_ack_cnt);
tmp_stats[i++] = le32_to_cpu(stats->wr_req_cnt);
tmp_stats[i++] = le32_to_cpu(stats->new_wr_req_cnt);
tmp_stats[i++] = le32_to_cpu(stats->new_wr_req_rtry_cnt);
tmp_stats[i++] = le32_to_cpu(stats->wr_rtry_cnt);
tmp_stats[i++] = le32_to_cpu(stats->wr_disc_cnt);
tmp_stats[i++] = le32_to_cpu(stats->rd_rtry_wr_ack_cnt);
tmp_stats[i++] = le32_to_cpu(stats->txp_wr_cnt);
tmp_stats[i++] = le32_to_cpu(stats->txd_rd_cnt);
tmp_stats[i++] = le32_to_cpu(stats->txd_wr_cnt);
tmp_stats[i++] = le32_to_cpu(stats->rxd_rd_cnt);
tmp_stats[i++] = le32_to_cpu(stats->rxd_wr_cnt);
tmp_stats[i++] = le32_to_cpu(stats->txf_rd_cnt);
tmp_stats[i++] = le32_to_cpu(stats->rxf_wr_cnt);
/* Enhanced statistics exist only for Hercules */
if (sp->device_type == XFRAME_II_DEVICE) {
tmp_stats[i++] =
le64_to_cpu(stats->rmac_ttl_1519_4095_frms);
tmp_stats[i++] =
le64_to_cpu(stats->rmac_ttl_4096_8191_frms);
tmp_stats[i++] =
le64_to_cpu(stats->rmac_ttl_8192_max_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_ttl_gt_max_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_osized_alt_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_jabber_alt_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_gt_max_alt_frms);
tmp_stats[i++] = le64_to_cpu(stats->rmac_vlan_frms);
tmp_stats[i++] = le32_to_cpu(stats->rmac_len_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_fcs_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_pf_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_da_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_red_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_rts_discard);
tmp_stats[i++] = le32_to_cpu(stats->rmac_ingm_full_discard);
tmp_stats[i++] = le32_to_cpu(stats->link_fault_cnt);
}
tmp_stats[i++] = 0;
tmp_stats[i++] = swstats->single_ecc_errs;
tmp_stats[i++] = swstats->double_ecc_errs;
tmp_stats[i++] = swstats->parity_err_cnt;
tmp_stats[i++] = swstats->serious_err_cnt;
tmp_stats[i++] = swstats->soft_reset_cnt;
tmp_stats[i++] = swstats->fifo_full_cnt;
for (k = 0; k < MAX_RX_RINGS; k++)
tmp_stats[i++] = swstats->ring_full_cnt[k];
tmp_stats[i++] = xstats->alarm_transceiver_temp_high;
tmp_stats[i++] = xstats->alarm_transceiver_temp_low;
tmp_stats[i++] = xstats->alarm_laser_bias_current_high;
tmp_stats[i++] = xstats->alarm_laser_bias_current_low;
tmp_stats[i++] = xstats->alarm_laser_output_power_high;
tmp_stats[i++] = xstats->alarm_laser_output_power_low;
tmp_stats[i++] = xstats->warn_transceiver_temp_high;
tmp_stats[i++] = xstats->warn_transceiver_temp_low;
tmp_stats[i++] = xstats->warn_laser_bias_current_high;
tmp_stats[i++] = xstats->warn_laser_bias_current_low;
tmp_stats[i++] = xstats->warn_laser_output_power_high;
tmp_stats[i++] = xstats->warn_laser_output_power_low;
tmp_stats[i++] = swstats->clubbed_frms_cnt;
tmp_stats[i++] = swstats->sending_both;
tmp_stats[i++] = swstats->outof_sequence_pkts;
tmp_stats[i++] = swstats->flush_max_pkts;
if (swstats->num_aggregations) {
u64 tmp = swstats->sum_avg_pkts_aggregated;
int count = 0;
/*
* Since 64-bit divide does not work on all platforms,
* do repeated subtraction.
*/
while (tmp >= swstats->num_aggregations) {
tmp -= swstats->num_aggregations;
count++;
}
tmp_stats[i++] = count;
} else
tmp_stats[i++] = 0;
tmp_stats[i++] = swstats->mem_alloc_fail_cnt;
tmp_stats[i++] = swstats->pci_map_fail_cnt;
tmp_stats[i++] = swstats->watchdog_timer_cnt;
tmp_stats[i++] = swstats->mem_allocated;
tmp_stats[i++] = swstats->mem_freed;
tmp_stats[i++] = swstats->link_up_cnt;
tmp_stats[i++] = swstats->link_down_cnt;
tmp_stats[i++] = swstats->link_up_time;
tmp_stats[i++] = swstats->link_down_time;
tmp_stats[i++] = swstats->tx_buf_abort_cnt;
tmp_stats[i++] = swstats->tx_desc_abort_cnt;
tmp_stats[i++] = swstats->tx_parity_err_cnt;
tmp_stats[i++] = swstats->tx_link_loss_cnt;
tmp_stats[i++] = swstats->tx_list_proc_err_cnt;
tmp_stats[i++] = swstats->rx_parity_err_cnt;
tmp_stats[i++] = swstats->rx_abort_cnt;
tmp_stats[i++] = swstats->rx_parity_abort_cnt;
tmp_stats[i++] = swstats->rx_rda_fail_cnt;
tmp_stats[i++] = swstats->rx_unkn_prot_cnt;
tmp_stats[i++] = swstats->rx_fcs_err_cnt;
tmp_stats[i++] = swstats->rx_buf_size_err_cnt;
tmp_stats[i++] = swstats->rx_rxd_corrupt_cnt;
tmp_stats[i++] = swstats->rx_unkn_err_cnt;
tmp_stats[i++] = swstats->tda_err_cnt;
tmp_stats[i++] = swstats->pfc_err_cnt;
tmp_stats[i++] = swstats->pcc_err_cnt;
tmp_stats[i++] = swstats->tti_err_cnt;
tmp_stats[i++] = swstats->tpa_err_cnt;
tmp_stats[i++] = swstats->sm_err_cnt;
tmp_stats[i++] = swstats->lso_err_cnt;
tmp_stats[i++] = swstats->mac_tmac_err_cnt;
tmp_stats[i++] = swstats->mac_rmac_err_cnt;
tmp_stats[i++] = swstats->xgxs_txgxs_err_cnt;
tmp_stats[i++] = swstats->xgxs_rxgxs_err_cnt;
tmp_stats[i++] = swstats->rc_err_cnt;
tmp_stats[i++] = swstats->prc_pcix_err_cnt;
tmp_stats[i++] = swstats->rpa_err_cnt;
tmp_stats[i++] = swstats->rda_err_cnt;
tmp_stats[i++] = swstats->rti_err_cnt;
tmp_stats[i++] = swstats->mc_err_cnt;
}
static int s2io_ethtool_get_regs_len(struct net_device *dev)
{
return XENA_REG_SPACE;
}
static int s2io_get_eeprom_len(struct net_device *dev)
{
return XENA_EEPROM_SPACE;
}
static int s2io_get_sset_count(struct net_device *dev, int sset)
{
struct s2io_nic *sp = netdev_priv(dev);
switch (sset) {
case ETH_SS_TEST:
return S2IO_TEST_LEN;
case ETH_SS_STATS:
switch (sp->device_type) {
case XFRAME_I_DEVICE:
return XFRAME_I_STAT_LEN;
case XFRAME_II_DEVICE:
return XFRAME_II_STAT_LEN;
default:
return 0;
}
default:
return -EOPNOTSUPP;
}
}
static void s2io_ethtool_get_strings(struct net_device *dev,
u32 stringset, u8 *data)
{
int stat_size = 0;
struct s2io_nic *sp = netdev_priv(dev);
switch (stringset) {
case ETH_SS_TEST:
memcpy(data, s2io_gstrings, S2IO_STRINGS_LEN);
break;
case ETH_SS_STATS:
stat_size = sizeof(ethtool_xena_stats_keys);
memcpy(data, ðtool_xena_stats_keys, stat_size);
if (sp->device_type == XFRAME_II_DEVICE) {
memcpy(data + stat_size,
ðtool_enhanced_stats_keys,
sizeof(ethtool_enhanced_stats_keys));
stat_size += sizeof(ethtool_enhanced_stats_keys);
}
memcpy(data + stat_size, ðtool_driver_stats_keys,
sizeof(ethtool_driver_stats_keys));
}
}
static int s2io_set_features(struct net_device *dev, netdev_features_t features)
{
struct s2io_nic *sp = netdev_priv(dev);
netdev_features_t changed = (features ^ dev->features) & NETIF_F_LRO;
if (changed && netif_running(dev)) {
int rc;
s2io_stop_all_tx_queue(sp);
s2io_card_down(sp);
dev->features = features;
rc = s2io_card_up(sp);
if (rc)
s2io_reset(sp);
else
s2io_start_all_tx_queue(sp);
return rc ? rc : 1;
}
return 0;
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_settings = s2io_ethtool_gset,
.set_settings = s2io_ethtool_sset,
.get_drvinfo = s2io_ethtool_gdrvinfo,
.get_regs_len = s2io_ethtool_get_regs_len,
.get_regs = s2io_ethtool_gregs,
.get_link = ethtool_op_get_link,
.get_eeprom_len = s2io_get_eeprom_len,
.get_eeprom = s2io_ethtool_geeprom,
.set_eeprom = s2io_ethtool_seeprom,
.get_ringparam = s2io_ethtool_gringparam,
.get_pauseparam = s2io_ethtool_getpause_data,
.set_pauseparam = s2io_ethtool_setpause_data,
.self_test = s2io_ethtool_test,
.get_strings = s2io_ethtool_get_strings,
.set_phys_id = s2io_ethtool_set_led,
.get_ethtool_stats = s2io_get_ethtool_stats,
.get_sset_count = s2io_get_sset_count,
};
/**
* s2io_ioctl - Entry point for the Ioctl
* @dev : Device pointer.
* @ifr : An IOCTL specefic structure, that can contain a pointer to
* a proprietary structure used to pass information to the driver.
* @cmd : This is used to distinguish between the different commands that
* can be passed to the IOCTL functions.
* Description:
* Currently there are no special functionality supported in IOCTL, hence
* function always return EOPNOTSUPPORTED
*/
static int s2io_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
return -EOPNOTSUPP;
}
/**
* s2io_change_mtu - entry point to change MTU size for the device.
* @dev : device pointer.
* @new_mtu : the new MTU size for the device.
* Description: A driver entry point to change MTU size for the device.
* Before changing the MTU the device must be stopped.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int s2io_change_mtu(struct net_device *dev, int new_mtu)
{
struct s2io_nic *sp = netdev_priv(dev);
int ret = 0;
if ((new_mtu < MIN_MTU) || (new_mtu > S2IO_JUMBO_SIZE)) {
DBG_PRINT(ERR_DBG, "%s: MTU size is invalid.\n", dev->name);
return -EPERM;
}
dev->mtu = new_mtu;
if (netif_running(dev)) {
s2io_stop_all_tx_queue(sp);
s2io_card_down(sp);
ret = s2io_card_up(sp);
if (ret) {
DBG_PRINT(ERR_DBG, "%s: Device bring up failed\n",
__func__);
return ret;
}
s2io_wake_all_tx_queue(sp);
} else { /* Device is down */
struct XENA_dev_config __iomem *bar0 = sp->bar0;
u64 val64 = new_mtu;
writeq(vBIT(val64, 2, 14), &bar0->rmac_max_pyld_len);
}
return ret;
}
/**
* s2io_set_link - Set the LInk status
* @data: long pointer to device private structue
* Description: Sets the link status for the adapter
*/
static void s2io_set_link(struct work_struct *work)
{
struct s2io_nic *nic = container_of(work, struct s2io_nic,
set_link_task);
struct net_device *dev = nic->dev;
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64;
u16 subid;
rtnl_lock();
if (!netif_running(dev))
goto out_unlock;
if (test_and_set_bit(__S2IO_STATE_LINK_TASK, &(nic->state))) {
/* The card is being reset, no point doing anything */
goto out_unlock;
}
subid = nic->pdev->subsystem_device;
if (s2io_link_fault_indication(nic) == MAC_RMAC_ERR_TIMER) {
/*
* Allow a small delay for the NICs self initiated
* cleanup to complete.
*/
msleep(100);
}
val64 = readq(&bar0->adapter_status);
if (LINK_IS_UP(val64)) {
if (!(readq(&bar0->adapter_control) & ADAPTER_CNTL_EN)) {
if (verify_xena_quiescence(nic)) {
val64 = readq(&bar0->adapter_control);
val64 |= ADAPTER_CNTL_EN;
writeq(val64, &bar0->adapter_control);
if (CARDS_WITH_FAULTY_LINK_INDICATORS(
nic->device_type, subid)) {
val64 = readq(&bar0->gpio_control);
val64 |= GPIO_CTRL_GPIO_0;
writeq(val64, &bar0->gpio_control);
val64 = readq(&bar0->gpio_control);
} else {
val64 |= ADAPTER_LED_ON;
writeq(val64, &bar0->adapter_control);
}
nic->device_enabled_once = true;
} else {
DBG_PRINT(ERR_DBG,
"%s: Error: device is not Quiescent\n",
dev->name);
s2io_stop_all_tx_queue(nic);
}
}
val64 = readq(&bar0->adapter_control);
val64 |= ADAPTER_LED_ON;
writeq(val64, &bar0->adapter_control);
s2io_link(nic, LINK_UP);
} else {
if (CARDS_WITH_FAULTY_LINK_INDICATORS(nic->device_type,
subid)) {
val64 = readq(&bar0->gpio_control);
val64 &= ~GPIO_CTRL_GPIO_0;
writeq(val64, &bar0->gpio_control);
val64 = readq(&bar0->gpio_control);
}
/* turn off LED */
val64 = readq(&bar0->adapter_control);
val64 = val64 & (~ADAPTER_LED_ON);
writeq(val64, &bar0->adapter_control);
s2io_link(nic, LINK_DOWN);
}
clear_bit(__S2IO_STATE_LINK_TASK, &(nic->state));
out_unlock:
rtnl_unlock();
}
static int set_rxd_buffer_pointer(struct s2io_nic *sp, struct RxD_t *rxdp,
struct buffAdd *ba,
struct sk_buff **skb, u64 *temp0, u64 *temp1,
u64 *temp2, int size)
{
struct net_device *dev = sp->dev;
struct swStat *stats = &sp->mac_control.stats_info->sw_stat;
if ((sp->rxd_mode == RXD_MODE_1) && (rxdp->Host_Control == 0)) {
struct RxD1 *rxdp1 = (struct RxD1 *)rxdp;
/* allocate skb */
if (*skb) {
DBG_PRINT(INFO_DBG, "SKB is not NULL\n");
/*
* As Rx frame are not going to be processed,
* using same mapped address for the Rxd
* buffer pointer
*/
rxdp1->Buffer0_ptr = *temp0;
} else {
*skb = netdev_alloc_skb(dev, size);
if (!(*skb)) {
DBG_PRINT(INFO_DBG,
"%s: Out of memory to allocate %s\n",
dev->name, "1 buf mode SKBs");
stats->mem_alloc_fail_cnt++;
return -ENOMEM ;
}
stats->mem_allocated += (*skb)->truesize;
/* storing the mapped addr in a temp variable
* such it will be used for next rxd whose
* Host Control is NULL
*/
rxdp1->Buffer0_ptr = *temp0 =
pci_map_single(sp->pdev, (*skb)->data,
size - NET_IP_ALIGN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(sp->pdev, rxdp1->Buffer0_ptr))
goto memalloc_failed;
rxdp->Host_Control = (unsigned long) (*skb);
}
} else if ((sp->rxd_mode == RXD_MODE_3B) && (rxdp->Host_Control == 0)) {
struct RxD3 *rxdp3 = (struct RxD3 *)rxdp;
/* Two buffer Mode */
if (*skb) {
rxdp3->Buffer2_ptr = *temp2;
rxdp3->Buffer0_ptr = *temp0;
rxdp3->Buffer1_ptr = *temp1;
} else {
*skb = netdev_alloc_skb(dev, size);
if (!(*skb)) {
DBG_PRINT(INFO_DBG,
"%s: Out of memory to allocate %s\n",
dev->name,
"2 buf mode SKBs");
stats->mem_alloc_fail_cnt++;
return -ENOMEM;
}
stats->mem_allocated += (*skb)->truesize;
rxdp3->Buffer2_ptr = *temp2 =
pci_map_single(sp->pdev, (*skb)->data,
dev->mtu + 4,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(sp->pdev, rxdp3->Buffer2_ptr))
goto memalloc_failed;
rxdp3->Buffer0_ptr = *temp0 =
pci_map_single(sp->pdev, ba->ba_0, BUF0_LEN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(sp->pdev,
rxdp3->Buffer0_ptr)) {
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer2_ptr,
dev->mtu + 4,
PCI_DMA_FROMDEVICE);
goto memalloc_failed;
}
rxdp->Host_Control = (unsigned long) (*skb);
/* Buffer-1 will be dummy buffer not used */
rxdp3->Buffer1_ptr = *temp1 =
pci_map_single(sp->pdev, ba->ba_1, BUF1_LEN,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(sp->pdev,
rxdp3->Buffer1_ptr)) {
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer0_ptr,
BUF0_LEN, PCI_DMA_FROMDEVICE);
pci_unmap_single(sp->pdev,
(dma_addr_t)rxdp3->Buffer2_ptr,
dev->mtu + 4,
PCI_DMA_FROMDEVICE);
goto memalloc_failed;
}
}
}
return 0;
memalloc_failed:
stats->pci_map_fail_cnt++;
stats->mem_freed += (*skb)->truesize;
dev_kfree_skb(*skb);
return -ENOMEM;
}
static void set_rxd_buffer_size(struct s2io_nic *sp, struct RxD_t *rxdp,
int size)
{
struct net_device *dev = sp->dev;
if (sp->rxd_mode == RXD_MODE_1) {
rxdp->Control_2 = SET_BUFFER0_SIZE_1(size - NET_IP_ALIGN);
} else if (sp->rxd_mode == RXD_MODE_3B) {
rxdp->Control_2 = SET_BUFFER0_SIZE_3(BUF0_LEN);
rxdp->Control_2 |= SET_BUFFER1_SIZE_3(1);
rxdp->Control_2 |= SET_BUFFER2_SIZE_3(dev->mtu + 4);
}
}
static int rxd_owner_bit_reset(struct s2io_nic *sp)
{
int i, j, k, blk_cnt = 0, size;
struct config_param *config = &sp->config;
struct mac_info *mac_control = &sp->mac_control;
struct net_device *dev = sp->dev;
struct RxD_t *rxdp = NULL;
struct sk_buff *skb = NULL;
struct buffAdd *ba = NULL;
u64 temp0_64 = 0, temp1_64 = 0, temp2_64 = 0;
/* Calculate the size based on ring mode */
size = dev->mtu + HEADER_ETHERNET_II_802_3_SIZE +
HEADER_802_2_SIZE + HEADER_SNAP_SIZE;
if (sp->rxd_mode == RXD_MODE_1)
size += NET_IP_ALIGN;
else if (sp->rxd_mode == RXD_MODE_3B)
size = dev->mtu + ALIGN_SIZE + BUF0_LEN + 4;
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
blk_cnt = rx_cfg->num_rxd / (rxd_count[sp->rxd_mode] + 1);
for (j = 0; j < blk_cnt; j++) {
for (k = 0; k < rxd_count[sp->rxd_mode]; k++) {
rxdp = ring->rx_blocks[j].rxds[k].virt_addr;
if (sp->rxd_mode == RXD_MODE_3B)
ba = &ring->ba[j][k];
if (set_rxd_buffer_pointer(sp, rxdp, ba, &skb,
(u64 *)&temp0_64,
(u64 *)&temp1_64,
(u64 *)&temp2_64,
size) == -ENOMEM) {
return 0;
}
set_rxd_buffer_size(sp, rxdp, size);
wmb();
/* flip the Ownership bit to Hardware */
rxdp->Control_1 |= RXD_OWN_XENA;
}
}
}
return 0;
}
static int s2io_add_isr(struct s2io_nic *sp)
{
int ret = 0;
struct net_device *dev = sp->dev;
int err = 0;
if (sp->config.intr_type == MSI_X)
ret = s2io_enable_msi_x(sp);
if (ret) {
DBG_PRINT(ERR_DBG, "%s: Defaulting to INTA\n", dev->name);
sp->config.intr_type = INTA;
}
/*
* Store the values of the MSIX table in
* the struct s2io_nic structure
*/
store_xmsi_data(sp);
/* After proper initialization of H/W, register ISR */
if (sp->config.intr_type == MSI_X) {
int i, msix_rx_cnt = 0;
for (i = 0; i < sp->num_entries; i++) {
if (sp->s2io_entries[i].in_use == MSIX_FLG) {
if (sp->s2io_entries[i].type ==
MSIX_RING_TYPE) {
sprintf(sp->desc[i], "%s:MSI-X-%d-RX",
dev->name, i);
err = request_irq(sp->entries[i].vector,
s2io_msix_ring_handle,
0,
sp->desc[i],
sp->s2io_entries[i].arg);
} else if (sp->s2io_entries[i].type ==
MSIX_ALARM_TYPE) {
sprintf(sp->desc[i], "%s:MSI-X-%d-TX",
dev->name, i);
err = request_irq(sp->entries[i].vector,
s2io_msix_fifo_handle,
0,
sp->desc[i],
sp->s2io_entries[i].arg);
}
/* if either data or addr is zero print it. */
if (!(sp->msix_info[i].addr &&
sp->msix_info[i].data)) {
DBG_PRINT(ERR_DBG,
"%s @Addr:0x%llx Data:0x%llx\n",
sp->desc[i],
(unsigned long long)
sp->msix_info[i].addr,
(unsigned long long)
ntohl(sp->msix_info[i].data));
} else
msix_rx_cnt++;
if (err) {
remove_msix_isr(sp);
DBG_PRINT(ERR_DBG,
"%s:MSI-X-%d registration "
"failed\n", dev->name, i);
DBG_PRINT(ERR_DBG,
"%s: Defaulting to INTA\n",
dev->name);
sp->config.intr_type = INTA;
break;
}
sp->s2io_entries[i].in_use =
MSIX_REGISTERED_SUCCESS;
}
}
if (!err) {
pr_info("MSI-X-RX %d entries enabled\n", --msix_rx_cnt);
DBG_PRINT(INFO_DBG,
"MSI-X-TX entries enabled through alarm vector\n");
}
}
if (sp->config.intr_type == INTA) {
err = request_irq(sp->pdev->irq, s2io_isr, IRQF_SHARED,
sp->name, dev);
if (err) {
DBG_PRINT(ERR_DBG, "%s: ISR registration failed\n",
dev->name);
return -1;
}
}
return 0;
}
static void s2io_rem_isr(struct s2io_nic *sp)
{
if (sp->config.intr_type == MSI_X)
remove_msix_isr(sp);
else
remove_inta_isr(sp);
}
static void do_s2io_card_down(struct s2io_nic *sp, int do_io)
{
int cnt = 0;
struct XENA_dev_config __iomem *bar0 = sp->bar0;
register u64 val64 = 0;
struct config_param *config;
config = &sp->config;
if (!is_s2io_card_up(sp))
return;
del_timer_sync(&sp->alarm_timer);
/* If s2io_set_link task is executing, wait till it completes. */
while (test_and_set_bit(__S2IO_STATE_LINK_TASK, &(sp->state)))
msleep(50);
clear_bit(__S2IO_STATE_CARD_UP, &sp->state);
/* Disable napi */
if (sp->config.napi) {
int off = 0;
if (config->intr_type == MSI_X) {
for (; off < sp->config.rx_ring_num; off++)
napi_disable(&sp->mac_control.rings[off].napi);
}
else
napi_disable(&sp->napi);
}
/* disable Tx and Rx traffic on the NIC */
if (do_io)
stop_nic(sp);
s2io_rem_isr(sp);
/* stop the tx queue, indicate link down */
s2io_link(sp, LINK_DOWN);
/* Check if the device is Quiescent and then Reset the NIC */
while (do_io) {
/* As per the HW requirement we need to replenish the
* receive buffer to avoid the ring bump. Since there is
* no intention of processing the Rx frame at this pointwe are
* just setting the ownership bit of rxd in Each Rx
* ring to HW and set the appropriate buffer size
* based on the ring mode
*/
rxd_owner_bit_reset(sp);
val64 = readq(&bar0->adapter_status);
if (verify_xena_quiescence(sp)) {
if (verify_pcc_quiescent(sp, sp->device_enabled_once))
break;
}
msleep(50);
cnt++;
if (cnt == 10) {
DBG_PRINT(ERR_DBG, "Device not Quiescent - "
"adapter status reads 0x%llx\n",
(unsigned long long)val64);
break;
}
}
if (do_io)
s2io_reset(sp);
/* Free all Tx buffers */
free_tx_buffers(sp);
/* Free all Rx buffers */
free_rx_buffers(sp);
clear_bit(__S2IO_STATE_LINK_TASK, &(sp->state));
}
static void s2io_card_down(struct s2io_nic *sp)
{
do_s2io_card_down(sp, 1);
}
static int s2io_card_up(struct s2io_nic *sp)
{
int i, ret = 0;
struct config_param *config;
struct mac_info *mac_control;
struct net_device *dev = (struct net_device *)sp->dev;
u16 interruptible;
/* Initialize the H/W I/O registers */
ret = init_nic(sp);
if (ret != 0) {
DBG_PRINT(ERR_DBG, "%s: H/W initialization failed\n",
dev->name);
if (ret != -EIO)
s2io_reset(sp);
return ret;
}
/*
* Initializing the Rx buffers. For now we are considering only 1
* Rx ring and initializing buffers into 30 Rx blocks
*/
config = &sp->config;
mac_control = &sp->mac_control;
for (i = 0; i < config->rx_ring_num; i++) {
struct ring_info *ring = &mac_control->rings[i];
ring->mtu = dev->mtu;
ring->lro = !!(dev->features & NETIF_F_LRO);
ret = fill_rx_buffers(sp, ring, 1);
if (ret) {
DBG_PRINT(ERR_DBG, "%s: Out of memory in Open\n",
dev->name);
s2io_reset(sp);
free_rx_buffers(sp);
return -ENOMEM;
}
DBG_PRINT(INFO_DBG, "Buf in ring:%d is %d:\n", i,
ring->rx_bufs_left);
}
/* Initialise napi */
if (config->napi) {
if (config->intr_type == MSI_X) {
for (i = 0; i < sp->config.rx_ring_num; i++)
napi_enable(&sp->mac_control.rings[i].napi);
} else {
napi_enable(&sp->napi);
}
}
/* Maintain the state prior to the open */
if (sp->promisc_flg)
sp->promisc_flg = 0;
if (sp->m_cast_flg) {
sp->m_cast_flg = 0;
sp->all_multi_pos = 0;
}
/* Setting its receive mode */
s2io_set_multicast(dev);
if (dev->features & NETIF_F_LRO) {
/* Initialize max aggregatable pkts per session based on MTU */
sp->lro_max_aggr_per_sess = ((1<<16) - 1) / dev->mtu;
/* Check if we can use (if specified) user provided value */
if (lro_max_pkts < sp->lro_max_aggr_per_sess)
sp->lro_max_aggr_per_sess = lro_max_pkts;
}
/* Enable Rx Traffic and interrupts on the NIC */
if (start_nic(sp)) {
DBG_PRINT(ERR_DBG, "%s: Starting NIC failed\n", dev->name);
s2io_reset(sp);
free_rx_buffers(sp);
return -ENODEV;
}
/* Add interrupt service routine */
if (s2io_add_isr(sp) != 0) {
if (sp->config.intr_type == MSI_X)
s2io_rem_isr(sp);
s2io_reset(sp);
free_rx_buffers(sp);
return -ENODEV;
}
S2IO_TIMER_CONF(sp->alarm_timer, s2io_alarm_handle, sp, (HZ/2));
set_bit(__S2IO_STATE_CARD_UP, &sp->state);
/* Enable select interrupts */
en_dis_err_alarms(sp, ENA_ALL_INTRS, ENABLE_INTRS);
if (sp->config.intr_type != INTA) {
interruptible = TX_TRAFFIC_INTR | TX_PIC_INTR;
en_dis_able_nic_intrs(sp, interruptible, ENABLE_INTRS);
} else {
interruptible = TX_TRAFFIC_INTR | RX_TRAFFIC_INTR;
interruptible |= TX_PIC_INTR;
en_dis_able_nic_intrs(sp, interruptible, ENABLE_INTRS);
}
return 0;
}
/**
* s2io_restart_nic - Resets the NIC.
* @data : long pointer to the device private structure
* Description:
* This function is scheduled to be run by the s2io_tx_watchdog
* function after 0.5 secs to reset the NIC. The idea is to reduce
* the run time of the watch dog routine which is run holding a
* spin lock.
*/
static void s2io_restart_nic(struct work_struct *work)
{
struct s2io_nic *sp = container_of(work, struct s2io_nic, rst_timer_task);
struct net_device *dev = sp->dev;
rtnl_lock();
if (!netif_running(dev))
goto out_unlock;
s2io_card_down(sp);
if (s2io_card_up(sp)) {
DBG_PRINT(ERR_DBG, "%s: Device bring up failed\n", dev->name);
}
s2io_wake_all_tx_queue(sp);
DBG_PRINT(ERR_DBG, "%s: was reset by Tx watchdog timer\n", dev->name);
out_unlock:
rtnl_unlock();
}
/**
* s2io_tx_watchdog - Watchdog for transmit side.
* @dev : Pointer to net device structure
* Description:
* This function is triggered if the Tx Queue is stopped
* for a pre-defined amount of time when the Interface is still up.
* If the Interface is jammed in such a situation, the hardware is
* reset (by s2io_close) and restarted again (by s2io_open) to
* overcome any problem that might have been caused in the hardware.
* Return value:
* void
*/
static void s2io_tx_watchdog(struct net_device *dev)
{
struct s2io_nic *sp = netdev_priv(dev);
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
if (netif_carrier_ok(dev)) {
swstats->watchdog_timer_cnt++;
schedule_work(&sp->rst_timer_task);
swstats->soft_reset_cnt++;
}
}
/**
* rx_osm_handler - To perform some OS related operations on SKB.
* @sp: private member of the device structure,pointer to s2io_nic structure.
* @skb : the socket buffer pointer.
* @len : length of the packet
* @cksum : FCS checksum of the frame.
* @ring_no : the ring from which this RxD was extracted.
* Description:
* This function is called by the Rx interrupt serivce routine to perform
* some OS related operations on the SKB before passing it to the upper
* layers. It mainly checks if the checksum is OK, if so adds it to the
* SKBs cksum variable, increments the Rx packet count and passes the SKB
* to the upper layer. If the checksum is wrong, it increments the Rx
* packet error count, frees the SKB and returns error.
* Return value:
* SUCCESS on success and -1 on failure.
*/
static int rx_osm_handler(struct ring_info *ring_data, struct RxD_t * rxdp)
{
struct s2io_nic *sp = ring_data->nic;
struct net_device *dev = (struct net_device *)ring_data->dev;
struct sk_buff *skb = (struct sk_buff *)
((unsigned long)rxdp->Host_Control);
int ring_no = ring_data->ring_no;
u16 l3_csum, l4_csum;
unsigned long long err = rxdp->Control_1 & RXD_T_CODE;
struct lro *uninitialized_var(lro);
u8 err_mask;
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
skb->dev = dev;
if (err) {
/* Check for parity error */
if (err & 0x1)
swstats->parity_err_cnt++;
err_mask = err >> 48;
switch (err_mask) {
case 1:
swstats->rx_parity_err_cnt++;
break;
case 2:
swstats->rx_abort_cnt++;
break;
case 3:
swstats->rx_parity_abort_cnt++;
break;
case 4:
swstats->rx_rda_fail_cnt++;
break;
case 5:
swstats->rx_unkn_prot_cnt++;
break;
case 6:
swstats->rx_fcs_err_cnt++;
break;
case 7:
swstats->rx_buf_size_err_cnt++;
break;
case 8:
swstats->rx_rxd_corrupt_cnt++;
break;
case 15:
swstats->rx_unkn_err_cnt++;
break;
}
/*
* Drop the packet if bad transfer code. Exception being
* 0x5, which could be due to unsupported IPv6 extension header.
* In this case, we let stack handle the packet.
* Note that in this case, since checksum will be incorrect,
* stack will validate the same.
*/
if (err_mask != 0x5) {
DBG_PRINT(ERR_DBG, "%s: Rx error Value: 0x%x\n",
dev->name, err_mask);
dev->stats.rx_crc_errors++;
swstats->mem_freed
+= skb->truesize;
dev_kfree_skb(skb);
ring_data->rx_bufs_left -= 1;
rxdp->Host_Control = 0;
return 0;
}
}
rxdp->Host_Control = 0;
if (sp->rxd_mode == RXD_MODE_1) {
int len = RXD_GET_BUFFER0_SIZE_1(rxdp->Control_2);
skb_put(skb, len);
} else if (sp->rxd_mode == RXD_MODE_3B) {
int get_block = ring_data->rx_curr_get_info.block_index;
int get_off = ring_data->rx_curr_get_info.offset;
int buf0_len = RXD_GET_BUFFER0_SIZE_3(rxdp->Control_2);
int buf2_len = RXD_GET_BUFFER2_SIZE_3(rxdp->Control_2);
unsigned char *buff = skb_push(skb, buf0_len);
struct buffAdd *ba = &ring_data->ba[get_block][get_off];
memcpy(buff, ba->ba_0, buf0_len);
skb_put(skb, buf2_len);
}
if ((rxdp->Control_1 & TCP_OR_UDP_FRAME) &&
((!ring_data->lro) ||
(ring_data->lro && (!(rxdp->Control_1 & RXD_FRAME_IP_FRAG)))) &&
(dev->features & NETIF_F_RXCSUM)) {
l3_csum = RXD_GET_L3_CKSUM(rxdp->Control_1);
l4_csum = RXD_GET_L4_CKSUM(rxdp->Control_1);
if ((l3_csum == L3_CKSUM_OK) && (l4_csum == L4_CKSUM_OK)) {
/*
* NIC verifies if the Checksum of the received
* frame is Ok or not and accordingly returns
* a flag in the RxD.
*/
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (ring_data->lro) {
u32 tcp_len = 0;
u8 *tcp;
int ret = 0;
ret = s2io_club_tcp_session(ring_data,
skb->data, &tcp,
&tcp_len, &lro,
rxdp, sp);
switch (ret) {
case 3: /* Begin anew */
lro->parent = skb;
goto aggregate;
case 1: /* Aggregate */
lro_append_pkt(sp, lro, skb, tcp_len);
goto aggregate;
case 4: /* Flush session */
lro_append_pkt(sp, lro, skb, tcp_len);
queue_rx_frame(lro->parent,
lro->vlan_tag);
clear_lro_session(lro);
swstats->flush_max_pkts++;
goto aggregate;
case 2: /* Flush both */
lro->parent->data_len = lro->frags_len;
swstats->sending_both++;
queue_rx_frame(lro->parent,
lro->vlan_tag);
clear_lro_session(lro);
goto send_up;
case 0: /* sessions exceeded */
case -1: /* non-TCP or not L2 aggregatable */
case 5: /*
* First pkt in session not
* L3/L4 aggregatable
*/
break;
default:
DBG_PRINT(ERR_DBG,
"%s: Samadhana!!\n",
__func__);
BUG();
}
}
} else {
/*
* Packet with erroneous checksum, let the
* upper layers deal with it.
*/
skb_checksum_none_assert(skb);
}
} else
skb_checksum_none_assert(skb);
swstats->mem_freed += skb->truesize;
send_up:
skb_record_rx_queue(skb, ring_no);
queue_rx_frame(skb, RXD_GET_VLAN_TAG(rxdp->Control_2));
aggregate:
sp->mac_control.rings[ring_no].rx_bufs_left -= 1;
return SUCCESS;
}
/**
* s2io_link - stops/starts the Tx queue.
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* @link : inidicates whether link is UP/DOWN.
* Description:
* This function stops/starts the Tx queue depending on whether the link
* status of the NIC is is down or up. This is called by the Alarm
* interrupt handler whenever a link change interrupt comes up.
* Return value:
* void.
*/
static void s2io_link(struct s2io_nic *sp, int link)
{
struct net_device *dev = (struct net_device *)sp->dev;
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
if (link != sp->last_link_state) {
init_tti(sp, link);
if (link == LINK_DOWN) {
DBG_PRINT(ERR_DBG, "%s: Link down\n", dev->name);
s2io_stop_all_tx_queue(sp);
netif_carrier_off(dev);
if (swstats->link_up_cnt)
swstats->link_up_time =
jiffies - sp->start_time;
swstats->link_down_cnt++;
} else {
DBG_PRINT(ERR_DBG, "%s: Link Up\n", dev->name);
if (swstats->link_down_cnt)
swstats->link_down_time =
jiffies - sp->start_time;
swstats->link_up_cnt++;
netif_carrier_on(dev);
s2io_wake_all_tx_queue(sp);
}
}
sp->last_link_state = link;
sp->start_time = jiffies;
}
/**
* s2io_init_pci -Initialization of PCI and PCI-X configuration registers .
* @sp : private member of the device structure, which is a pointer to the
* s2io_nic structure.
* Description:
* This function initializes a few of the PCI and PCI-X configuration registers
* with recommended values.
* Return value:
* void
*/
static void s2io_init_pci(struct s2io_nic *sp)
{
u16 pci_cmd = 0, pcix_cmd = 0;
/* Enable Data Parity Error Recovery in PCI-X command register. */
pci_read_config_word(sp->pdev, PCIX_COMMAND_REGISTER,
&(pcix_cmd));
pci_write_config_word(sp->pdev, PCIX_COMMAND_REGISTER,
(pcix_cmd | 1));
pci_read_config_word(sp->pdev, PCIX_COMMAND_REGISTER,
&(pcix_cmd));
/* Set the PErr Response bit in PCI command register. */
pci_read_config_word(sp->pdev, PCI_COMMAND, &pci_cmd);
pci_write_config_word(sp->pdev, PCI_COMMAND,
(pci_cmd | PCI_COMMAND_PARITY));
pci_read_config_word(sp->pdev, PCI_COMMAND, &pci_cmd);
}
static int s2io_verify_parm(struct pci_dev *pdev, u8 *dev_intr_type,
u8 *dev_multiq)
{
int i;
if ((tx_fifo_num > MAX_TX_FIFOS) || (tx_fifo_num < 1)) {
DBG_PRINT(ERR_DBG, "Requested number of tx fifos "
"(%d) not supported\n", tx_fifo_num);
if (tx_fifo_num < 1)
tx_fifo_num = 1;
else
tx_fifo_num = MAX_TX_FIFOS;
DBG_PRINT(ERR_DBG, "Default to %d tx fifos\n", tx_fifo_num);
}
if (multiq)
*dev_multiq = multiq;
if (tx_steering_type && (1 == tx_fifo_num)) {
if (tx_steering_type != TX_DEFAULT_STEERING)
DBG_PRINT(ERR_DBG,
"Tx steering is not supported with "
"one fifo. Disabling Tx steering.\n");
tx_steering_type = NO_STEERING;
}
if ((tx_steering_type < NO_STEERING) ||
(tx_steering_type > TX_DEFAULT_STEERING)) {
DBG_PRINT(ERR_DBG,
"Requested transmit steering not supported\n");
DBG_PRINT(ERR_DBG, "Disabling transmit steering\n");
tx_steering_type = NO_STEERING;
}
if (rx_ring_num > MAX_RX_RINGS) {
DBG_PRINT(ERR_DBG,
"Requested number of rx rings not supported\n");
DBG_PRINT(ERR_DBG, "Default to %d rx rings\n",
MAX_RX_RINGS);
rx_ring_num = MAX_RX_RINGS;
}
if ((*dev_intr_type != INTA) && (*dev_intr_type != MSI_X)) {
DBG_PRINT(ERR_DBG, "Wrong intr_type requested. "
"Defaulting to INTA\n");
*dev_intr_type = INTA;
}
if ((*dev_intr_type == MSI_X) &&
((pdev->device != PCI_DEVICE_ID_HERC_WIN) &&
(pdev->device != PCI_DEVICE_ID_HERC_UNI))) {
DBG_PRINT(ERR_DBG, "Xframe I does not support MSI_X. "
"Defaulting to INTA\n");
*dev_intr_type = INTA;
}
if ((rx_ring_mode != 1) && (rx_ring_mode != 2)) {
DBG_PRINT(ERR_DBG, "Requested ring mode not supported\n");
DBG_PRINT(ERR_DBG, "Defaulting to 1-buffer mode\n");
rx_ring_mode = 1;
}
for (i = 0; i < MAX_RX_RINGS; i++)
if (rx_ring_sz[i] > MAX_RX_BLOCKS_PER_RING) {
DBG_PRINT(ERR_DBG, "Requested rx ring size not "
"supported\nDefaulting to %d\n",
MAX_RX_BLOCKS_PER_RING);
rx_ring_sz[i] = MAX_RX_BLOCKS_PER_RING;
}
return SUCCESS;
}
/**
* rts_ds_steer - Receive traffic steering based on IPv4 or IPv6 TOS
* or Traffic class respectively.
* @nic: device private variable
* Description: The function configures the receive steering to
* desired receive ring.
* Return Value: SUCCESS on success and
* '-1' on failure (endian settings incorrect).
*/
static int rts_ds_steer(struct s2io_nic *nic, u8 ds_codepoint, u8 ring)
{
struct XENA_dev_config __iomem *bar0 = nic->bar0;
register u64 val64 = 0;
if (ds_codepoint > 63)
return FAILURE;
val64 = RTS_DS_MEM_DATA(ring);
writeq(val64, &bar0->rts_ds_mem_data);
val64 = RTS_DS_MEM_CTRL_WE |
RTS_DS_MEM_CTRL_STROBE_NEW_CMD |
RTS_DS_MEM_CTRL_OFFSET(ds_codepoint);
writeq(val64, &bar0->rts_ds_mem_ctrl);
return wait_for_cmd_complete(&bar0->rts_ds_mem_ctrl,
RTS_DS_MEM_CTRL_STROBE_CMD_BEING_EXECUTED,
S2IO_BIT_RESET);
}
static const struct net_device_ops s2io_netdev_ops = {
.ndo_open = s2io_open,
.ndo_stop = s2io_close,
.ndo_get_stats = s2io_get_stats,
.ndo_start_xmit = s2io_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = s2io_set_multicast,
.ndo_do_ioctl = s2io_ioctl,
.ndo_set_mac_address = s2io_set_mac_addr,
.ndo_change_mtu = s2io_change_mtu,
.ndo_set_features = s2io_set_features,
.ndo_tx_timeout = s2io_tx_watchdog,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = s2io_netpoll,
#endif
};
/**
* s2io_init_nic - Initialization of the adapter .
* @pdev : structure containing the PCI related information of the device.
* @pre: List of PCI devices supported by the driver listed in s2io_tbl.
* Description:
* The function initializes an adapter identified by the pci_dec structure.
* All OS related initialization including memory and device structure and
* initlaization of the device private variable is done. Also the swapper
* control register is initialized to enable read and write into the I/O
* registers of the device.
* Return value:
* returns 0 on success and negative on failure.
*/
static int __devinit
s2io_init_nic(struct pci_dev *pdev, const struct pci_device_id *pre)
{
struct s2io_nic *sp;
struct net_device *dev;
int i, j, ret;
int dma_flag = false;
u32 mac_up, mac_down;
u64 val64 = 0, tmp64 = 0;
struct XENA_dev_config __iomem *bar0 = NULL;
u16 subid;
struct config_param *config;
struct mac_info *mac_control;
int mode;
u8 dev_intr_type = intr_type;
u8 dev_multiq = 0;
ret = s2io_verify_parm(pdev, &dev_intr_type, &dev_multiq);
if (ret)
return ret;
ret = pci_enable_device(pdev);
if (ret) {
DBG_PRINT(ERR_DBG,
"%s: pci_enable_device failed\n", __func__);
return ret;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
DBG_PRINT(INIT_DBG, "%s: Using 64bit DMA\n", __func__);
dma_flag = true;
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
DBG_PRINT(ERR_DBG,
"Unable to obtain 64bit DMA "
"for consistent allocations\n");
pci_disable_device(pdev);
return -ENOMEM;
}
} else if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) {
DBG_PRINT(INIT_DBG, "%s: Using 32bit DMA\n", __func__);
} else {
pci_disable_device(pdev);
return -ENOMEM;
}
ret = pci_request_regions(pdev, s2io_driver_name);
if (ret) {
DBG_PRINT(ERR_DBG, "%s: Request Regions failed - %x\n",
__func__, ret);
pci_disable_device(pdev);
return -ENODEV;
}
if (dev_multiq)
dev = alloc_etherdev_mq(sizeof(struct s2io_nic), tx_fifo_num);
else
dev = alloc_etherdev(sizeof(struct s2io_nic));
if (dev == NULL) {
pci_disable_device(pdev);
pci_release_regions(pdev);
return -ENODEV;
}
pci_set_master(pdev);
pci_set_drvdata(pdev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
/* Private member variable initialized to s2io NIC structure */
sp = netdev_priv(dev);
sp->dev = dev;
sp->pdev = pdev;
sp->high_dma_flag = dma_flag;
sp->device_enabled_once = false;
if (rx_ring_mode == 1)
sp->rxd_mode = RXD_MODE_1;
if (rx_ring_mode == 2)
sp->rxd_mode = RXD_MODE_3B;
sp->config.intr_type = dev_intr_type;
if ((pdev->device == PCI_DEVICE_ID_HERC_WIN) ||
(pdev->device == PCI_DEVICE_ID_HERC_UNI))
sp->device_type = XFRAME_II_DEVICE;
else
sp->device_type = XFRAME_I_DEVICE;
/* Initialize some PCI/PCI-X fields of the NIC. */
s2io_init_pci(sp);
/*
* Setting the device configuration parameters.
* Most of these parameters can be specified by the user during
* module insertion as they are module loadable parameters. If
* these parameters are not not specified during load time, they
* are initialized with default values.
*/
config = &sp->config;
mac_control = &sp->mac_control;
config->napi = napi;
config->tx_steering_type = tx_steering_type;
/* Tx side parameters. */
if (config->tx_steering_type == TX_PRIORITY_STEERING)
config->tx_fifo_num = MAX_TX_FIFOS;
else
config->tx_fifo_num = tx_fifo_num;
/* Initialize the fifos used for tx steering */
if (config->tx_fifo_num < 5) {
if (config->tx_fifo_num == 1)
sp->total_tcp_fifos = 1;
else
sp->total_tcp_fifos = config->tx_fifo_num - 1;
sp->udp_fifo_idx = config->tx_fifo_num - 1;
sp->total_udp_fifos = 1;
sp->other_fifo_idx = sp->total_tcp_fifos - 1;
} else {
sp->total_tcp_fifos = (tx_fifo_num - FIFO_UDP_MAX_NUM -
FIFO_OTHER_MAX_NUM);
sp->udp_fifo_idx = sp->total_tcp_fifos;
sp->total_udp_fifos = FIFO_UDP_MAX_NUM;
sp->other_fifo_idx = sp->udp_fifo_idx + FIFO_UDP_MAX_NUM;
}
config->multiq = dev_multiq;
for (i = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
tx_cfg->fifo_len = tx_fifo_len[i];
tx_cfg->fifo_priority = i;
}
/* mapping the QoS priority to the configured fifos */
for (i = 0; i < MAX_TX_FIFOS; i++)
config->fifo_mapping[i] = fifo_map[config->tx_fifo_num - 1][i];
/* map the hashing selector table to the configured fifos */
for (i = 0; i < config->tx_fifo_num; i++)
sp->fifo_selector[i] = fifo_selector[i];
config->tx_intr_type = TXD_INT_TYPE_UTILZ;
for (i = 0; i < config->tx_fifo_num; i++) {
struct tx_fifo_config *tx_cfg = &config->tx_cfg[i];
tx_cfg->f_no_snoop = (NO_SNOOP_TXD | NO_SNOOP_TXD_BUFFER);
if (tx_cfg->fifo_len < 65) {
config->tx_intr_type = TXD_INT_TYPE_PER_LIST;
break;
}
}
/* + 2 because one Txd for skb->data and one Txd for UFO */
config->max_txds = MAX_SKB_FRAGS + 2;
/* Rx side parameters. */
config->rx_ring_num = rx_ring_num;
for (i = 0; i < config->rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
struct ring_info *ring = &mac_control->rings[i];
rx_cfg->num_rxd = rx_ring_sz[i] * (rxd_count[sp->rxd_mode] + 1);
rx_cfg->ring_priority = i;
ring->rx_bufs_left = 0;
ring->rxd_mode = sp->rxd_mode;
ring->rxd_count = rxd_count[sp->rxd_mode];
ring->pdev = sp->pdev;
ring->dev = sp->dev;
}
for (i = 0; i < rx_ring_num; i++) {
struct rx_ring_config *rx_cfg = &config->rx_cfg[i];
rx_cfg->ring_org = RING_ORG_BUFF1;
rx_cfg->f_no_snoop = (NO_SNOOP_RXD | NO_SNOOP_RXD_BUFFER);
}
/* Setting Mac Control parameters */
mac_control->rmac_pause_time = rmac_pause_time;
mac_control->mc_pause_threshold_q0q3 = mc_pause_threshold_q0q3;
mac_control->mc_pause_threshold_q4q7 = mc_pause_threshold_q4q7;
/* initialize the shared memory used by the NIC and the host */
if (init_shared_mem(sp)) {
DBG_PRINT(ERR_DBG, "%s: Memory allocation failed\n", dev->name);
ret = -ENOMEM;
goto mem_alloc_failed;
}
sp->bar0 = pci_ioremap_bar(pdev, 0);
if (!sp->bar0) {
DBG_PRINT(ERR_DBG, "%s: Neterion: cannot remap io mem1\n",
dev->name);
ret = -ENOMEM;
goto bar0_remap_failed;
}
sp->bar1 = pci_ioremap_bar(pdev, 2);
if (!sp->bar1) {
DBG_PRINT(ERR_DBG, "%s: Neterion: cannot remap io mem2\n",
dev->name);
ret = -ENOMEM;
goto bar1_remap_failed;
}
/* Initializing the BAR1 address as the start of the FIFO pointer. */
for (j = 0; j < MAX_TX_FIFOS; j++) {
mac_control->tx_FIFO_start[j] = sp->bar1 + (j * 0x00020000);
}
/* Driver entry points */
dev->netdev_ops = &s2io_netdev_ops;
SET_ETHTOOL_OPS(dev, &netdev_ethtool_ops);
dev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_TSO | NETIF_F_TSO6 |
NETIF_F_RXCSUM | NETIF_F_LRO;
dev->features |= dev->hw_features |
NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX;
if (sp->device_type & XFRAME_II_DEVICE) {
dev->hw_features |= NETIF_F_UFO;
if (ufo)
dev->features |= NETIF_F_UFO;
}
if (sp->high_dma_flag == true)
dev->features |= NETIF_F_HIGHDMA;
dev->watchdog_timeo = WATCH_DOG_TIMEOUT;
INIT_WORK(&sp->rst_timer_task, s2io_restart_nic);
INIT_WORK(&sp->set_link_task, s2io_set_link);
pci_save_state(sp->pdev);
/* Setting swapper control on the NIC, for proper reset operation */
if (s2io_set_swapper(sp)) {
DBG_PRINT(ERR_DBG, "%s: swapper settings are wrong\n",
dev->name);
ret = -EAGAIN;
goto set_swap_failed;
}
/* Verify if the Herc works on the slot its placed into */
if (sp->device_type & XFRAME_II_DEVICE) {
mode = s2io_verify_pci_mode(sp);
if (mode < 0) {
DBG_PRINT(ERR_DBG, "%s: Unsupported PCI bus mode\n",
__func__);
ret = -EBADSLT;
goto set_swap_failed;
}
}
if (sp->config.intr_type == MSI_X) {
sp->num_entries = config->rx_ring_num + 1;
ret = s2io_enable_msi_x(sp);
if (!ret) {
ret = s2io_test_msi(sp);
/* rollback MSI-X, will re-enable during add_isr() */
remove_msix_isr(sp);
}
if (ret) {
DBG_PRINT(ERR_DBG,
"MSI-X requested but failed to enable\n");
sp->config.intr_type = INTA;
}
}
if (config->intr_type == MSI_X) {
for (i = 0; i < config->rx_ring_num ; i++) {
struct ring_info *ring = &mac_control->rings[i];
netif_napi_add(dev, &ring->napi, s2io_poll_msix, 64);
}
} else {
netif_napi_add(dev, &sp->napi, s2io_poll_inta, 64);
}
/* Not needed for Herc */
if (sp->device_type & XFRAME_I_DEVICE) {
/*
* Fix for all "FFs" MAC address problems observed on
* Alpha platforms
*/
fix_mac_address(sp);
s2io_reset(sp);
}
/*
* MAC address initialization.
* For now only one mac address will be read and used.
*/
bar0 = sp->bar0;
val64 = RMAC_ADDR_CMD_MEM_RD | RMAC_ADDR_CMD_MEM_STROBE_NEW_CMD |
RMAC_ADDR_CMD_MEM_OFFSET(0 + S2IO_MAC_ADDR_START_OFFSET);
writeq(val64, &bar0->rmac_addr_cmd_mem);
wait_for_cmd_complete(&bar0->rmac_addr_cmd_mem,
RMAC_ADDR_CMD_MEM_STROBE_CMD_EXECUTING,
S2IO_BIT_RESET);
tmp64 = readq(&bar0->rmac_addr_data0_mem);
mac_down = (u32)tmp64;
mac_up = (u32) (tmp64 >> 32);
sp->def_mac_addr[0].mac_addr[3] = (u8) (mac_up);
sp->def_mac_addr[0].mac_addr[2] = (u8) (mac_up >> 8);
sp->def_mac_addr[0].mac_addr[1] = (u8) (mac_up >> 16);
sp->def_mac_addr[0].mac_addr[0] = (u8) (mac_up >> 24);
sp->def_mac_addr[0].mac_addr[5] = (u8) (mac_down >> 16);
sp->def_mac_addr[0].mac_addr[4] = (u8) (mac_down >> 24);
/* Set the factory defined MAC address initially */
dev->addr_len = ETH_ALEN;
memcpy(dev->dev_addr, sp->def_mac_addr, ETH_ALEN);
memcpy(dev->perm_addr, dev->dev_addr, ETH_ALEN);
/* initialize number of multicast & unicast MAC entries variables */
if (sp->device_type == XFRAME_I_DEVICE) {
config->max_mc_addr = S2IO_XENA_MAX_MC_ADDRESSES;
config->max_mac_addr = S2IO_XENA_MAX_MAC_ADDRESSES;
config->mc_start_offset = S2IO_XENA_MC_ADDR_START_OFFSET;
} else if (sp->device_type == XFRAME_II_DEVICE) {
config->max_mc_addr = S2IO_HERC_MAX_MC_ADDRESSES;
config->max_mac_addr = S2IO_HERC_MAX_MAC_ADDRESSES;
config->mc_start_offset = S2IO_HERC_MC_ADDR_START_OFFSET;
}
/* store mac addresses from CAM to s2io_nic structure */
do_s2io_store_unicast_mc(sp);
/* Configure MSIX vector for number of rings configured plus one */
if ((sp->device_type == XFRAME_II_DEVICE) &&
(config->intr_type == MSI_X))
sp->num_entries = config->rx_ring_num + 1;
/* Store the values of the MSIX table in the s2io_nic structure */
store_xmsi_data(sp);
/* reset Nic and bring it to known state */
s2io_reset(sp);
/*
* Initialize link state flags
* and the card state parameter
*/
sp->state = 0;
/* Initialize spinlocks */
for (i = 0; i < sp->config.tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
spin_lock_init(&fifo->tx_lock);
}
/*
* SXE-002: Configure link and activity LED to init state
* on driver load.
*/
subid = sp->pdev->subsystem_device;
if ((subid & 0xFF) >= 0x07) {
val64 = readq(&bar0->gpio_control);
val64 |= 0x0000800000000000ULL;
writeq(val64, &bar0->gpio_control);
val64 = 0x0411040400000000ULL;
writeq(val64, (void __iomem *)bar0 + 0x2700);
val64 = readq(&bar0->gpio_control);
}
sp->rx_csum = 1; /* Rx chksum verify enabled by default */
if (register_netdev(dev)) {
DBG_PRINT(ERR_DBG, "Device registration failed\n");
ret = -ENODEV;
goto register_failed;
}
s2io_vpd_read(sp);
DBG_PRINT(ERR_DBG, "Copyright(c) 2002-2010 Exar Corp.\n");
DBG_PRINT(ERR_DBG, "%s: Neterion %s (rev %d)\n", dev->name,
sp->product_name, pdev->revision);
DBG_PRINT(ERR_DBG, "%s: Driver version %s\n", dev->name,
s2io_driver_version);
DBG_PRINT(ERR_DBG, "%s: MAC Address: %pM\n", dev->name, dev->dev_addr);
DBG_PRINT(ERR_DBG, "Serial number: %s\n", sp->serial_num);
if (sp->device_type & XFRAME_II_DEVICE) {
mode = s2io_print_pci_mode(sp);
if (mode < 0) {
ret = -EBADSLT;
unregister_netdev(dev);
goto set_swap_failed;
}
}
switch (sp->rxd_mode) {
case RXD_MODE_1:
DBG_PRINT(ERR_DBG, "%s: 1-Buffer receive mode enabled\n",
dev->name);
break;
case RXD_MODE_3B:
DBG_PRINT(ERR_DBG, "%s: 2-Buffer receive mode enabled\n",
dev->name);
break;
}
switch (sp->config.napi) {
case 0:
DBG_PRINT(ERR_DBG, "%s: NAPI disabled\n", dev->name);
break;
case 1:
DBG_PRINT(ERR_DBG, "%s: NAPI enabled\n", dev->name);
break;
}
DBG_PRINT(ERR_DBG, "%s: Using %d Tx fifo(s)\n", dev->name,
sp->config.tx_fifo_num);
DBG_PRINT(ERR_DBG, "%s: Using %d Rx ring(s)\n", dev->name,
sp->config.rx_ring_num);
switch (sp->config.intr_type) {
case INTA:
DBG_PRINT(ERR_DBG, "%s: Interrupt type INTA\n", dev->name);
break;
case MSI_X:
DBG_PRINT(ERR_DBG, "%s: Interrupt type MSI-X\n", dev->name);
break;
}
if (sp->config.multiq) {
for (i = 0; i < sp->config.tx_fifo_num; i++) {
struct fifo_info *fifo = &mac_control->fifos[i];
fifo->multiq = config->multiq;
}
DBG_PRINT(ERR_DBG, "%s: Multiqueue support enabled\n",
dev->name);
} else
DBG_PRINT(ERR_DBG, "%s: Multiqueue support disabled\n",
dev->name);
switch (sp->config.tx_steering_type) {
case NO_STEERING:
DBG_PRINT(ERR_DBG, "%s: No steering enabled for transmit\n",
dev->name);
break;
case TX_PRIORITY_STEERING:
DBG_PRINT(ERR_DBG,
"%s: Priority steering enabled for transmit\n",
dev->name);
break;
case TX_DEFAULT_STEERING:
DBG_PRINT(ERR_DBG,
"%s: Default steering enabled for transmit\n",
dev->name);
}
DBG_PRINT(ERR_DBG, "%s: Large receive offload enabled\n",
dev->name);
if (ufo)
DBG_PRINT(ERR_DBG,
"%s: UDP Fragmentation Offload(UFO) enabled\n",
dev->name);
/* Initialize device name */
sprintf(sp->name, "%s Neterion %s", dev->name, sp->product_name);
if (vlan_tag_strip)
sp->vlan_strip_flag = 1;
else
sp->vlan_strip_flag = 0;
/*
* Make Link state as off at this point, when the Link change
* interrupt comes the state will be automatically changed to
* the right state.
*/
netif_carrier_off(dev);
return 0;
register_failed:
set_swap_failed:
iounmap(sp->bar1);
bar1_remap_failed:
iounmap(sp->bar0);
bar0_remap_failed:
mem_alloc_failed:
free_shared_mem(sp);
pci_disable_device(pdev);
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
free_netdev(dev);
return ret;
}
/**
* s2io_rem_nic - Free the PCI device
* @pdev: structure containing the PCI related information of the device.
* Description: This function is called by the Pci subsystem to release a
* PCI device and free up all resource held up by the device. This could
* be in response to a Hot plug event or when the driver is to be removed
* from memory.
*/
static void __devexit s2io_rem_nic(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct s2io_nic *sp;
if (dev == NULL) {
DBG_PRINT(ERR_DBG, "Driver Data is NULL!!\n");
return;
}
sp = netdev_priv(dev);
cancel_work_sync(&sp->rst_timer_task);
cancel_work_sync(&sp->set_link_task);
unregister_netdev(dev);
free_shared_mem(sp);
iounmap(sp->bar0);
iounmap(sp->bar1);
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
free_netdev(dev);
pci_disable_device(pdev);
}
/**
* s2io_starter - Entry point for the driver
* Description: This function is the entry point for the driver. It verifies
* the module loadable parameters and initializes PCI configuration space.
*/
static int __init s2io_starter(void)
{
return pci_register_driver(&s2io_driver);
}
/**
* s2io_closer - Cleanup routine for the driver
* Description: This function is the cleanup routine for the driver. It unregist * ers the driver.
*/
static __exit void s2io_closer(void)
{
pci_unregister_driver(&s2io_driver);
DBG_PRINT(INIT_DBG, "cleanup done\n");
}
module_init(s2io_starter);
module_exit(s2io_closer);
static int check_L2_lro_capable(u8 *buffer, struct iphdr **ip,
struct tcphdr **tcp, struct RxD_t *rxdp,
struct s2io_nic *sp)
{
int ip_off;
u8 l2_type = (u8)((rxdp->Control_1 >> 37) & 0x7), ip_len;
if (!(rxdp->Control_1 & RXD_FRAME_PROTO_TCP)) {
DBG_PRINT(INIT_DBG,
"%s: Non-TCP frames not supported for LRO\n",
__func__);
return -1;
}
/* Checking for DIX type or DIX type with VLAN */
if ((l2_type == 0) || (l2_type == 4)) {
ip_off = HEADER_ETHERNET_II_802_3_SIZE;
/*
* If vlan stripping is disabled and the frame is VLAN tagged,
* shift the offset by the VLAN header size bytes.
*/
if ((!sp->vlan_strip_flag) &&
(rxdp->Control_1 & RXD_FRAME_VLAN_TAG))
ip_off += HEADER_VLAN_SIZE;
} else {
/* LLC, SNAP etc are considered non-mergeable */
return -1;
}
*ip = (struct iphdr *)((u8 *)buffer + ip_off);
ip_len = (u8)((*ip)->ihl);
ip_len <<= 2;
*tcp = (struct tcphdr *)((unsigned long)*ip + ip_len);
return 0;
}
static int check_for_socket_match(struct lro *lro, struct iphdr *ip,
struct tcphdr *tcp)
{
DBG_PRINT(INFO_DBG, "%s: Been here...\n", __func__);
if ((lro->iph->saddr != ip->saddr) ||
(lro->iph->daddr != ip->daddr) ||
(lro->tcph->source != tcp->source) ||
(lro->tcph->dest != tcp->dest))
return -1;
return 0;
}
static inline int get_l4_pyld_length(struct iphdr *ip, struct tcphdr *tcp)
{
return ntohs(ip->tot_len) - (ip->ihl << 2) - (tcp->doff << 2);
}
static void initiate_new_session(struct lro *lro, u8 *l2h,
struct iphdr *ip, struct tcphdr *tcp,
u32 tcp_pyld_len, u16 vlan_tag)
{
DBG_PRINT(INFO_DBG, "%s: Been here...\n", __func__);
lro->l2h = l2h;
lro->iph = ip;
lro->tcph = tcp;
lro->tcp_next_seq = tcp_pyld_len + ntohl(tcp->seq);
lro->tcp_ack = tcp->ack_seq;
lro->sg_num = 1;
lro->total_len = ntohs(ip->tot_len);
lro->frags_len = 0;
lro->vlan_tag = vlan_tag;
/*
* Check if we saw TCP timestamp.
* Other consistency checks have already been done.
*/
if (tcp->doff == 8) {
__be32 *ptr;
ptr = (__be32 *)(tcp+1);
lro->saw_ts = 1;
lro->cur_tsval = ntohl(*(ptr+1));
lro->cur_tsecr = *(ptr+2);
}
lro->in_use = 1;
}
static void update_L3L4_header(struct s2io_nic *sp, struct lro *lro)
{
struct iphdr *ip = lro->iph;
struct tcphdr *tcp = lro->tcph;
__sum16 nchk;
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
DBG_PRINT(INFO_DBG, "%s: Been here...\n", __func__);
/* Update L3 header */
ip->tot_len = htons(lro->total_len);
ip->check = 0;
nchk = ip_fast_csum((u8 *)lro->iph, ip->ihl);
ip->check = nchk;
/* Update L4 header */
tcp->ack_seq = lro->tcp_ack;
tcp->window = lro->window;
/* Update tsecr field if this session has timestamps enabled */
if (lro->saw_ts) {
__be32 *ptr = (__be32 *)(tcp + 1);
*(ptr+2) = lro->cur_tsecr;
}
/* Update counters required for calculation of
* average no. of packets aggregated.
*/
swstats->sum_avg_pkts_aggregated += lro->sg_num;
swstats->num_aggregations++;
}
static void aggregate_new_rx(struct lro *lro, struct iphdr *ip,
struct tcphdr *tcp, u32 l4_pyld)
{
DBG_PRINT(INFO_DBG, "%s: Been here...\n", __func__);
lro->total_len += l4_pyld;
lro->frags_len += l4_pyld;
lro->tcp_next_seq += l4_pyld;
lro->sg_num++;
/* Update ack seq no. and window ad(from this pkt) in LRO object */
lro->tcp_ack = tcp->ack_seq;
lro->window = tcp->window;
if (lro->saw_ts) {
__be32 *ptr;
/* Update tsecr and tsval from this packet */
ptr = (__be32 *)(tcp+1);
lro->cur_tsval = ntohl(*(ptr+1));
lro->cur_tsecr = *(ptr + 2);
}
}
static int verify_l3_l4_lro_capable(struct lro *l_lro, struct iphdr *ip,
struct tcphdr *tcp, u32 tcp_pyld_len)
{
u8 *ptr;
DBG_PRINT(INFO_DBG, "%s: Been here...\n", __func__);
if (!tcp_pyld_len) {
/* Runt frame or a pure ack */
return -1;
}
if (ip->ihl != 5) /* IP has options */
return -1;
/* If we see CE codepoint in IP header, packet is not mergeable */
if (INET_ECN_is_ce(ipv4_get_dsfield(ip)))
return -1;
/* If we see ECE or CWR flags in TCP header, packet is not mergeable */
if (tcp->urg || tcp->psh || tcp->rst ||
tcp->syn || tcp->fin ||
tcp->ece || tcp->cwr || !tcp->ack) {
/*
* Currently recognize only the ack control word and
* any other control field being set would result in
* flushing the LRO session
*/
return -1;
}
/*
* Allow only one TCP timestamp option. Don't aggregate if
* any other options are detected.
*/
if (tcp->doff != 5 && tcp->doff != 8)
return -1;
if (tcp->doff == 8) {
ptr = (u8 *)(tcp + 1);
while (*ptr == TCPOPT_NOP)
ptr++;
if (*ptr != TCPOPT_TIMESTAMP || *(ptr+1) != TCPOLEN_TIMESTAMP)
return -1;
/* Ensure timestamp value increases monotonically */
if (l_lro)
if (l_lro->cur_tsval > ntohl(*((__be32 *)(ptr+2))))
return -1;
/* timestamp echo reply should be non-zero */
if (*((__be32 *)(ptr+6)) == 0)
return -1;
}
return 0;
}
static int s2io_club_tcp_session(struct ring_info *ring_data, u8 *buffer,
u8 **tcp, u32 *tcp_len, struct lro **lro,
struct RxD_t *rxdp, struct s2io_nic *sp)
{
struct iphdr *ip;
struct tcphdr *tcph;
int ret = 0, i;
u16 vlan_tag = 0;
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
ret = check_L2_lro_capable(buffer, &ip, (struct tcphdr **)tcp,
rxdp, sp);
if (ret)
return ret;
DBG_PRINT(INFO_DBG, "IP Saddr: %x Daddr: %x\n", ip->saddr, ip->daddr);
vlan_tag = RXD_GET_VLAN_TAG(rxdp->Control_2);
tcph = (struct tcphdr *)*tcp;
*tcp_len = get_l4_pyld_length(ip, tcph);
for (i = 0; i < MAX_LRO_SESSIONS; i++) {
struct lro *l_lro = &ring_data->lro0_n[i];
if (l_lro->in_use) {
if (check_for_socket_match(l_lro, ip, tcph))
continue;
/* Sock pair matched */
*lro = l_lro;
if ((*lro)->tcp_next_seq != ntohl(tcph->seq)) {
DBG_PRINT(INFO_DBG, "%s: Out of sequence. "
"expected 0x%x, actual 0x%x\n",
__func__,
(*lro)->tcp_next_seq,
ntohl(tcph->seq));
swstats->outof_sequence_pkts++;
ret = 2;
break;
}
if (!verify_l3_l4_lro_capable(l_lro, ip, tcph,
*tcp_len))
ret = 1; /* Aggregate */
else
ret = 2; /* Flush both */
break;
}
}
if (ret == 0) {
/* Before searching for available LRO objects,
* check if the pkt is L3/L4 aggregatable. If not
* don't create new LRO session. Just send this
* packet up.
*/
if (verify_l3_l4_lro_capable(NULL, ip, tcph, *tcp_len))
return 5;
for (i = 0; i < MAX_LRO_SESSIONS; i++) {
struct lro *l_lro = &ring_data->lro0_n[i];
if (!(l_lro->in_use)) {
*lro = l_lro;
ret = 3; /* Begin anew */
break;
}
}
}
if (ret == 0) { /* sessions exceeded */
DBG_PRINT(INFO_DBG, "%s: All LRO sessions already in use\n",
__func__);
*lro = NULL;
return ret;
}
switch (ret) {
case 3:
initiate_new_session(*lro, buffer, ip, tcph, *tcp_len,
vlan_tag);
break;
case 2:
update_L3L4_header(sp, *lro);
break;
case 1:
aggregate_new_rx(*lro, ip, tcph, *tcp_len);
if ((*lro)->sg_num == sp->lro_max_aggr_per_sess) {
update_L3L4_header(sp, *lro);
ret = 4; /* Flush the LRO */
}
break;
default:
DBG_PRINT(ERR_DBG, "%s: Don't know, can't say!!\n", __func__);
break;
}
return ret;
}
static void clear_lro_session(struct lro *lro)
{
static u16 lro_struct_size = sizeof(struct lro);
memset(lro, 0, lro_struct_size);
}
static void queue_rx_frame(struct sk_buff *skb, u16 vlan_tag)
{
struct net_device *dev = skb->dev;
struct s2io_nic *sp = netdev_priv(dev);
skb->protocol = eth_type_trans(skb, dev);
if (vlan_tag && sp->vlan_strip_flag)
__vlan_hwaccel_put_tag(skb, vlan_tag);
if (sp->config.napi)
netif_receive_skb(skb);
else
netif_rx(skb);
}
static void lro_append_pkt(struct s2io_nic *sp, struct lro *lro,
struct sk_buff *skb, u32 tcp_len)
{
struct sk_buff *first = lro->parent;
struct swStat *swstats = &sp->mac_control.stats_info->sw_stat;
first->len += tcp_len;
first->data_len = lro->frags_len;
skb_pull(skb, (skb->len - tcp_len));
if (skb_shinfo(first)->frag_list)
lro->last_frag->next = skb;
else
skb_shinfo(first)->frag_list = skb;
first->truesize += skb->truesize;
lro->last_frag = skb;
swstats->clubbed_frms_cnt++;
}
/**
* s2io_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t s2io_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct s2io_nic *sp = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev)) {
/* Bring down the card, while avoiding PCI I/O */
do_s2io_card_down(sp, 0);
}
pci_disable_device(pdev);
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* s2io_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
* At this point, the card has exprienced a hard reset,
* followed by fixups by BIOS, and has its config space
* set up identically to what it was at cold boot.
*/
static pci_ers_result_t s2io_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct s2io_nic *sp = netdev_priv(netdev);
if (pci_enable_device(pdev)) {
pr_err("Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
s2io_reset(sp);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* s2io_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells
* us that its OK to resume normal operation.
*/
static void s2io_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct s2io_nic *sp = netdev_priv(netdev);
if (netif_running(netdev)) {
if (s2io_card_up(sp)) {
pr_err("Can't bring device back up after reset.\n");
return;
}
if (s2io_set_mac_addr(netdev, netdev->dev_addr) == FAILURE) {
s2io_card_down(sp);
pr_err("Can't restore mac addr after reset.\n");
return;
}
}
netif_device_attach(netdev);
netif_tx_wake_all_queues(netdev);
}
| gpl-2.0 |
smarkwell/asuswrt-merlin | release/src-rt/linux/linux-2.6/drivers/media/video/bt8xx/bttv-input.c | 50 | 8923 | /*
*
* Copyright (c) 2003 Gerd Knorr
* Copyright (c) 2003 Pavel Machek
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include "bttv.h"
#include "bttvp.h"
static int debug;
module_param(debug, int, 0644); /* debug level (0,1,2) */
static int repeat_delay = 500;
module_param(repeat_delay, int, 0644);
static int repeat_period = 33;
module_param(repeat_period, int, 0644);
static int ir_rc5_remote_gap = 885;
module_param(ir_rc5_remote_gap, int, 0644);
static int ir_rc5_key_timeout = 200;
module_param(ir_rc5_key_timeout, int, 0644);
#define DEVNAME "bttv-input"
/* ---------------------------------------------------------------------- */
static void ir_handle_key(struct bttv *btv)
{
struct card_ir *ir = btv->remote;
u32 gpio,data;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
if (ir->polling) {
if (ir->last_gpio == gpio)
return;
ir->last_gpio = gpio;
}
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk(KERN_INFO DEVNAME ": irq gpio=0x%x code=%d | %s%s%s\n",
gpio, data,
ir->polling ? "poll" : "irq",
(gpio & ir->mask_keydown) ? " down" : "",
(gpio & ir->mask_keyup) ? " up" : "");
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
ir_input_keydown(ir->dev,&ir->ir,data,data);
} else {
ir_input_nokey(ir->dev,&ir->ir);
}
}
void bttv_input_irq(struct bttv *btv)
{
struct card_ir *ir = btv->remote;
if (!ir->polling)
ir_handle_key(btv);
}
static void bttv_input_timer(unsigned long data)
{
struct bttv *btv = (struct bttv*)data;
struct card_ir *ir = btv->remote;
ir_handle_key(btv);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
/* ---------------------------------------------------------------*/
static int bttv_rc5_irq(struct bttv *btv)
{
struct card_ir *ir = btv->remote;
struct timeval tv;
u32 gpio;
u32 gap;
unsigned long current_jiffies;
/* read gpio port */
gpio = bttv_gpio_read(&btv->c);
/* remote IRQ? */
if (!(gpio & 0x20))
return 0;
/* get time of bit */
current_jiffies = jiffies;
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
/* active code => add bit */
if (ir->active) {
/* only if in the code (otherwise spurious IRQ or timer
late) */
if (ir->last_bit < 28) {
ir->last_bit = (gap - ir_rc5_remote_gap / 2) /
ir_rc5_remote_gap;
ir->code |= 1 << ir->last_bit;
}
/* starting new code */
} else {
ir->active = 1;
ir->code = 0;
ir->base_time = tv;
ir->last_bit = 0;
mod_timer(&ir->timer_end,
current_jiffies + msecs_to_jiffies(30));
}
/* toggle GPIO pin 4 to reset the irq */
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
return 1;
}
/* ---------------------------------------------------------------------- */
static void bttv_ir_start(struct bttv *btv, struct card_ir *ir)
{
if (ir->polling) {
setup_timer(&ir->timer, bttv_input_timer, (unsigned long)btv);
ir->timer.expires = jiffies + HZ;
add_timer(&ir->timer);
} else if (ir->rc5_gpio) {
/* set timer_end for code completion */
init_timer(&ir->timer_end);
ir->timer_end.function = ir_rc5_timer_end;
ir->timer_end.data = (unsigned long)ir;
init_timer(&ir->timer_keyup);
ir->timer_keyup.function = ir_rc5_timer_keyup;
ir->timer_keyup.data = (unsigned long)ir;
ir->shift_by = 1;
ir->start = 3;
ir->addr = 0x0;
ir->rc5_key_timeout = ir_rc5_key_timeout;
ir->rc5_remote_gap = ir_rc5_remote_gap;
}
}
static void bttv_ir_stop(struct bttv *btv)
{
if (btv->remote->polling) {
del_timer_sync(&btv->remote->timer);
flush_scheduled_work();
}
if (btv->remote->rc5_gpio) {
u32 gpio;
del_timer_sync(&btv->remote->timer_end);
flush_scheduled_work();
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
}
}
int bttv_input_init(struct bttv *btv)
{
struct card_ir *ir;
IR_KEYTAB_TYPE *ir_codes = NULL;
struct input_dev *input_dev;
int ir_type = IR_TYPE_OTHER;
int err = -ENOMEM;
if (!btv->has_remote)
return -ENODEV;
ir = kzalloc(sizeof(*ir),GFP_KERNEL);
input_dev = input_allocate_device();
if (!ir || !input_dev)
goto err_out_free;
/* detect & configure */
switch (btv->c.type) {
case BTTV_BOARD_AVERMEDIA:
case BTTV_BOARD_AVPHONE98:
case BTTV_BOARD_AVERMEDIA98:
ir_codes = ir_codes_avermedia;
ir->mask_keycode = 0xf88000;
ir->mask_keydown = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_AVDVBT_761:
case BTTV_BOARD_AVDVBT_771:
ir_codes = ir_codes_avermedia_dvbt;
ir->mask_keycode = 0x0f00c0;
ir->mask_keydown = 0x000020;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PXELVWPLTVPAK:
ir_codes = ir_codes_pixelview;
ir->mask_keycode = 0x003e00;
ir->mask_keyup = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PV_M4900:
case BTTV_BOARD_PV_BT878P_9B:
case BTTV_BOARD_PV_BT878P_PLUS:
ir_codes = ir_codes_pixelview;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_WINFAST2000:
ir_codes = ir_codes_winfast;
ir->mask_keycode = 0x1f8;
break;
case BTTV_BOARD_MAGICTVIEW061:
case BTTV_BOARD_MAGICTVIEW063:
ir_codes = ir_codes_winfast;
ir->mask_keycode = 0x0008e000;
ir->mask_keydown = 0x00200000;
break;
case BTTV_BOARD_APAC_VIEWCOMP:
ir_codes = ir_codes_apac_viewcomp;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_CONCEPTRONIC_CTVFMI2:
case BTTV_BOARD_CONTVFMI:
ir_codes = ir_codes_pixelview;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x006000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_NEBULA_DIGITV:
ir_codes = ir_codes_nebula;
btv->custom_irq = bttv_rc5_irq;
ir->rc5_gpio = 1;
break;
case BTTV_BOARD_MACHTV_MAGICTV:
ir_codes = ir_codes_apac_viewcomp;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x004000;
ir->polling = 50; /* ms */
break;
}
if (NULL == ir_codes) {
dprintk(KERN_INFO "Ooops: IR config error [card=%d]\n", btv->c.type);
err = -ENODEV;
goto err_out_free;
}
if (ir->rc5_gpio) {
u32 gpio;
/* enable remote irq */
bttv_gpio_inout(&btv->c, (1 << 4), 1 << 4);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
} else {
/* init hardware-specific stuff */
bttv_gpio_inout(&btv->c, ir->mask_keycode | ir->mask_keydown, 0);
}
/* init input device */
ir->dev = input_dev;
snprintf(ir->name, sizeof(ir->name), "bttv IR (card=%d)",
btv->c.type);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(btv->c.pci));
ir_input_init(input_dev, &ir->ir, ir_type, ir_codes);
input_dev->name = ir->name;
input_dev->phys = ir->phys;
input_dev->id.bustype = BUS_PCI;
input_dev->id.version = 1;
if (btv->c.pci->subsystem_vendor) {
input_dev->id.vendor = btv->c.pci->subsystem_vendor;
input_dev->id.product = btv->c.pci->subsystem_device;
} else {
input_dev->id.vendor = btv->c.pci->vendor;
input_dev->id.product = btv->c.pci->device;
}
input_dev->cdev.dev = &btv->c.pci->dev;
btv->remote = ir;
bttv_ir_start(btv, ir);
/* all done */
err = input_register_device(btv->remote->dev);
if (err)
goto err_out_stop;
/* the remote isn't as bouncy as a keyboard */
ir->dev->rep[REP_DELAY] = repeat_delay;
ir->dev->rep[REP_PERIOD] = repeat_period;
return 0;
err_out_stop:
bttv_ir_stop(btv);
btv->remote = NULL;
err_out_free:
input_free_device(input_dev);
kfree(ir);
return err;
}
void bttv_input_fini(struct bttv *btv)
{
if (btv->remote == NULL)
return;
bttv_ir_stop(btv);
input_unregister_device(btv->remote->dev);
kfree(btv->remote);
btv->remote = NULL;
}
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
Krabappel2548/kernel_msm8x60 | drivers/usb/gadget/f_gg.c | 50 | 7834 | /*
* f_gg.c -- USB gadget gordons gate driver for ETS
*
* Copyright (C) 2010-2012 by Sony Ericsson Mobile Communications AB
* Copyright (C) 2012 Sony Mobile Communications AB.
*
* This software is distributed under the terms of the GNU General
* Public License ("GPL") as published by the Free Software Foundation,
* either version 2 of that License or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/usb/android.h>
#include "u_serial.h"
struct gg_gser_descs {
struct usb_endpoint_descriptor *in;
struct usb_endpoint_descriptor *out;
};
struct f_gg {
struct gserial port;
u8 data_id;
u8 port_num;
struct gg_gser_descs fs;
struct gg_gser_descs hs;
};
/*-------------------------------------------------------------------------*/
static inline struct f_gg *gg_func_to_gser(struct usb_function *f)
{
return container_of(f, struct f_gg, port.func);
}
/*-------------------------------------------------------------------------*/
/* interface descriptor: */
static struct usb_interface_descriptor gg_gser_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor gg_gser_fs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor gg_gser_fs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *gg_gser_fs_function[] = {
(struct usb_descriptor_header *) &gg_gser_interface_desc,
(struct usb_descriptor_header *) &gg_gser_fs_in_desc,
(struct usb_descriptor_header *) &gg_gser_fs_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor gg_gser_hs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor gg_gser_hs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_descriptor_header *gg_gser_hs_function[] = {
(struct usb_descriptor_header *) &gg_gser_interface_desc,
(struct usb_descriptor_header *) &gg_gser_hs_in_desc,
(struct usb_descriptor_header *) &gg_gser_hs_out_desc,
NULL,
};
/* string descriptors: */
static struct usb_string gg_gser_string_defs[] = {
[0].s = "Generic Serial",
{ } /* end of list */
};
static struct usb_gadget_strings gg_gser_string_table = {
.language = 0x0409, /* en-us */
.strings = gg_gser_string_defs,
};
static struct usb_gadget_strings *gg_gser_strings[] = {
&gg_gser_string_table,
NULL,
};
/*-------------------------------------------------------------------------*/
static int gg_gser_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_gg *gser = gg_func_to_gser(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* we know alt == 0, so this is an activation or a reset */
if (gser->port.in->driver_data) {
DBG(cdev, "reset generic ttyGS%d\n", gser->port_num);
gserial_disconnect(&gser->port);
} else
DBG(cdev, "activate generic ttyGS%d\n", gser->port_num);
gser->port.in_desc = ep_choose(cdev->gadget,
gser->hs.in, gser->fs.in);
gser->port.out_desc = ep_choose(cdev->gadget,
gser->hs.out, gser->fs.out);
gserial_connect(&gser->port, gser->port_num);
printk(KERN_INFO "GG: gg_gser_set_alt: ttyGS%d\n", gser->port_num);
return 0;
}
static void gg_gser_disable(struct usb_function *f)
{
struct f_gg *gser = gg_func_to_gser(f);
DBG(f->config->cdev, "generic ttyGS%d deactivated\n", gser->port_num);
gserial_disconnect(&gser->port);
}
/*-------------------------------------------------------------------------*/
/* serial function driver setup/binding */
static int gg_gser_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_gg *gser = gg_func_to_gser(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
gser->data_id = status;
gg_gser_interface_desc.bInterfaceNumber = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &gg_gser_fs_in_desc);
if (!ep)
goto fail;
gser->port.in = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &gg_gser_fs_out_desc);
if (!ep)
goto fail;
gser->port.out = ep;
ep->driver_data = cdev; /* claim */
/* copy descriptors, and track endpoint copies */
f->descriptors = usb_copy_descriptors(gg_gser_fs_function);
gser->fs.in = usb_find_endpoint(gg_gser_fs_function,
f->descriptors, &gg_gser_fs_in_desc);
gser->fs.out = usb_find_endpoint(gg_gser_fs_function,
f->descriptors, &gg_gser_fs_out_desc);
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
gg_gser_hs_in_desc.bEndpointAddress =
gg_gser_fs_in_desc.bEndpointAddress;
gg_gser_hs_out_desc.bEndpointAddress =
gg_gser_fs_out_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->hs_descriptors = usb_copy_descriptors(gg_gser_hs_function);
gser->hs.in = usb_find_endpoint(gg_gser_hs_function,
f->hs_descriptors, &gg_gser_hs_in_desc);
gser->hs.out = usb_find_endpoint(gg_gser_hs_function,
f->hs_descriptors, &gg_gser_hs_out_desc);
}
DBG(cdev, "generic ttyGS%d: %s speed IN/%s OUT/%s\n",
gser->port_num,
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
gser->port.in->name, gser->port.out->name);
return 0;
fail:
/* we might as well release our claims on endpoints */
if (gser->port.out)
gser->port.out->driver_data = NULL;
if (gser->port.in)
gser->port.in->driver_data = NULL;
printk(KERN_ERR "can't bind, err %s %d\n", f->name, status);
return status;
}
static void gg_gser_unbind(struct usb_configuration *c, struct usb_function *f)
{
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
usb_free_descriptors(f->descriptors);
kfree(gg_func_to_gser(f));
}
static int gordonsg_bind_config(struct usb_configuration *c, u8 port_num)
{
struct f_gg *gser;
int status;
/* maybe allocate device-global string ID */
if (gg_gser_string_defs[0].id == 0) {
status = usb_string_id(c->cdev);
if (status < 0)
return status;
gg_gser_string_defs[0].id = status;
}
/* allocate and initialize one new instance */
gser = kzalloc(sizeof *gser, GFP_KERNEL);
if (!gser)
return -ENOMEM;
gser->port_num = port_num;
gser->port.func.name = "gg";
gser->port.func.strings = gg_gser_strings;
gser->port.func.bind = gg_gser_bind;
gser->port.func.unbind = gg_gser_unbind;
gser->port.func.set_alt = gg_gser_set_alt;
gser->port.func.disable = gg_gser_disable;
status = usb_add_function(c, &gser->port.func);
if (status)
kfree(gser);
return status;
}
static int gg_bind_config(struct usb_configuration *c)
{
int status = 0;
/* See if composite driver can allocate
* serial ports. But for now allocate
* two ports one for acm and another for gg.
*/
status = gserial_setup(c->cdev->gadget, 2);
if (status)
return status;
status = gordonsg_bind_config(c, 1);
return status;
}
| gpl-2.0 |
PenguPilot/overo-kernel | net/netfilter/nf_conntrack_helper.c | 50 | 11415 | /* Helper handling for netfilter. */
/* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
* (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <linux/stddef.h>
#include <linux/random.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/rculist.h>
#include <linux/rtnetlink.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_extend.h>
static DEFINE_MUTEX(nf_ct_helper_mutex);
static struct hlist_head *nf_ct_helper_hash __read_mostly;
static unsigned int nf_ct_helper_hsize __read_mostly;
static unsigned int nf_ct_helper_count __read_mostly;
static bool nf_ct_auto_assign_helper __read_mostly = true;
module_param_named(nf_conntrack_helper, nf_ct_auto_assign_helper, bool, 0644);
MODULE_PARM_DESC(nf_conntrack_helper,
"Enable automatic conntrack helper assignment (default 1)");
#ifdef CONFIG_SYSCTL
static struct ctl_table helper_sysctl_table[] = {
{
.procname = "nf_conntrack_helper",
.data = &init_net.ct.sysctl_auto_assign_helper,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{}
};
static int nf_conntrack_helper_init_sysctl(struct net *net)
{
struct ctl_table *table;
table = kmemdup(helper_sysctl_table, sizeof(helper_sysctl_table),
GFP_KERNEL);
if (!table)
goto out;
table[0].data = &net->ct.sysctl_auto_assign_helper;
net->ct.helper_sysctl_header =
register_net_sysctl(net, "net/netfilter", table);
if (!net->ct.helper_sysctl_header) {
pr_err("nf_conntrack_helper: can't register to sysctl.\n");
goto out_register;
}
return 0;
out_register:
kfree(table);
out:
return -ENOMEM;
}
static void nf_conntrack_helper_fini_sysctl(struct net *net)
{
struct ctl_table *table;
table = net->ct.helper_sysctl_header->ctl_table_arg;
unregister_net_sysctl_table(net->ct.helper_sysctl_header);
kfree(table);
}
#else
static int nf_conntrack_helper_init_sysctl(struct net *net)
{
return 0;
}
static void nf_conntrack_helper_fini_sysctl(struct net *net)
{
}
#endif /* CONFIG_SYSCTL */
/* Stupid hash, but collision free for the default registrations of the
* helpers currently in the kernel. */
static unsigned int helper_hash(const struct nf_conntrack_tuple *tuple)
{
return (((tuple->src.l3num << 8) | tuple->dst.protonum) ^
(__force __u16)tuple->src.u.all) % nf_ct_helper_hsize;
}
static struct nf_conntrack_helper *
__nf_ct_helper_find(const struct nf_conntrack_tuple *tuple)
{
struct nf_conntrack_helper *helper;
struct nf_conntrack_tuple_mask mask = { .src.u.all = htons(0xFFFF) };
struct hlist_node *n;
unsigned int h;
if (!nf_ct_helper_count)
return NULL;
h = helper_hash(tuple);
hlist_for_each_entry_rcu(helper, n, &nf_ct_helper_hash[h], hnode) {
if (nf_ct_tuple_src_mask_cmp(tuple, &helper->tuple, &mask))
return helper;
}
return NULL;
}
struct nf_conntrack_helper *
__nf_conntrack_helper_find(const char *name, u16 l3num, u8 protonum)
{
struct nf_conntrack_helper *h;
struct hlist_node *n;
unsigned int i;
for (i = 0; i < nf_ct_helper_hsize; i++) {
hlist_for_each_entry_rcu(h, n, &nf_ct_helper_hash[i], hnode) {
if (!strcmp(h->name, name) &&
h->tuple.src.l3num == l3num &&
h->tuple.dst.protonum == protonum)
return h;
}
}
return NULL;
}
EXPORT_SYMBOL_GPL(__nf_conntrack_helper_find);
struct nf_conntrack_helper *
nf_conntrack_helper_try_module_get(const char *name, u16 l3num, u8 protonum)
{
struct nf_conntrack_helper *h;
h = __nf_conntrack_helper_find(name, l3num, protonum);
#ifdef CONFIG_MODULES
if (h == NULL) {
if (request_module("nfct-helper-%s", name) == 0)
h = __nf_conntrack_helper_find(name, l3num, protonum);
}
#endif
if (h != NULL && !try_module_get(h->me))
h = NULL;
return h;
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_try_module_get);
struct nf_conn_help *nf_ct_helper_ext_add(struct nf_conn *ct, gfp_t gfp)
{
struct nf_conn_help *help;
help = nf_ct_ext_add(ct, NF_CT_EXT_HELPER, gfp);
if (help)
INIT_HLIST_HEAD(&help->expectations);
else
pr_debug("failed to add helper extension area");
return help;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_ext_add);
int __nf_ct_try_assign_helper(struct nf_conn *ct, struct nf_conn *tmpl,
gfp_t flags)
{
struct nf_conntrack_helper *helper = NULL;
struct nf_conn_help *help;
struct net *net = nf_ct_net(ct);
int ret = 0;
/* We already got a helper explicitly attached. The function
* nf_conntrack_alter_reply - in case NAT is in use - asks for looking
* the helper up again. Since now the user is in full control of
* making consistent helper configurations, skip this automatic
* re-lookup, otherwise we'll lose the helper.
*/
if (test_bit(IPS_HELPER_BIT, &ct->status))
return 0;
if (tmpl != NULL) {
help = nfct_help(tmpl);
if (help != NULL) {
helper = help->helper;
set_bit(IPS_HELPER_BIT, &ct->status);
}
}
help = nfct_help(ct);
if (net->ct.sysctl_auto_assign_helper && helper == NULL) {
helper = __nf_ct_helper_find(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
if (unlikely(!net->ct.auto_assign_helper_warned && helper)) {
pr_info("nf_conntrack: automatic helper "
"assignment is deprecated and it will "
"be removed soon. Use the iptables CT target "
"to attach helpers instead.\n");
net->ct.auto_assign_helper_warned = true;
}
}
if (helper == NULL) {
if (help)
RCU_INIT_POINTER(help->helper, NULL);
goto out;
}
if (help == NULL) {
help = nf_ct_helper_ext_add(ct, flags);
if (help == NULL) {
ret = -ENOMEM;
goto out;
}
} else {
memset(&help->help, 0, sizeof(help->help));
}
rcu_assign_pointer(help->helper, helper);
out:
return ret;
}
EXPORT_SYMBOL_GPL(__nf_ct_try_assign_helper);
static inline int unhelp(struct nf_conntrack_tuple_hash *i,
const struct nf_conntrack_helper *me)
{
struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(i);
struct nf_conn_help *help = nfct_help(ct);
if (help && rcu_dereference_protected(
help->helper,
lockdep_is_held(&nf_conntrack_lock)
) == me) {
nf_conntrack_event(IPCT_HELPER, ct);
RCU_INIT_POINTER(help->helper, NULL);
}
return 0;
}
void nf_ct_helper_destroy(struct nf_conn *ct)
{
struct nf_conn_help *help = nfct_help(ct);
struct nf_conntrack_helper *helper;
if (help) {
rcu_read_lock();
helper = rcu_dereference(help->helper);
if (helper && helper->destroy)
helper->destroy(ct);
rcu_read_unlock();
}
}
static LIST_HEAD(nf_ct_helper_expectfn_list);
void nf_ct_helper_expectfn_register(struct nf_ct_helper_expectfn *n)
{
spin_lock_bh(&nf_conntrack_lock);
list_add_rcu(&n->head, &nf_ct_helper_expectfn_list);
spin_unlock_bh(&nf_conntrack_lock);
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_register);
void nf_ct_helper_expectfn_unregister(struct nf_ct_helper_expectfn *n)
{
spin_lock_bh(&nf_conntrack_lock);
list_del_rcu(&n->head);
spin_unlock_bh(&nf_conntrack_lock);
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_unregister);
struct nf_ct_helper_expectfn *
nf_ct_helper_expectfn_find_by_name(const char *name)
{
struct nf_ct_helper_expectfn *cur;
bool found = false;
rcu_read_lock();
list_for_each_entry_rcu(cur, &nf_ct_helper_expectfn_list, head) {
if (!strcmp(cur->name, name)) {
found = true;
break;
}
}
rcu_read_unlock();
return found ? cur : NULL;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_find_by_name);
struct nf_ct_helper_expectfn *
nf_ct_helper_expectfn_find_by_symbol(const void *symbol)
{
struct nf_ct_helper_expectfn *cur;
bool found = false;
rcu_read_lock();
list_for_each_entry_rcu(cur, &nf_ct_helper_expectfn_list, head) {
if (cur->expectfn == symbol) {
found = true;
break;
}
}
rcu_read_unlock();
return found ? cur : NULL;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_find_by_symbol);
int nf_conntrack_helper_register(struct nf_conntrack_helper *me)
{
unsigned int h = helper_hash(&me->tuple);
BUG_ON(me->expect_policy == NULL);
BUG_ON(me->expect_class_max >= NF_CT_MAX_EXPECT_CLASSES);
BUG_ON(strlen(me->name) > NF_CT_HELPER_NAME_LEN - 1);
mutex_lock(&nf_ct_helper_mutex);
hlist_add_head_rcu(&me->hnode, &nf_ct_helper_hash[h]);
nf_ct_helper_count++;
mutex_unlock(&nf_ct_helper_mutex);
return 0;
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_register);
static void __nf_conntrack_helper_unregister(struct nf_conntrack_helper *me,
struct net *net)
{
struct nf_conntrack_tuple_hash *h;
struct nf_conntrack_expect *exp;
const struct hlist_node *n, *next;
const struct hlist_nulls_node *nn;
unsigned int i;
/* Get rid of expectations */
for (i = 0; i < nf_ct_expect_hsize; i++) {
hlist_for_each_entry_safe(exp, n, next,
&net->ct.expect_hash[i], hnode) {
struct nf_conn_help *help = nfct_help(exp->master);
if ((rcu_dereference_protected(
help->helper,
lockdep_is_held(&nf_conntrack_lock)
) == me || exp->helper == me) &&
del_timer(&exp->timeout)) {
nf_ct_unlink_expect(exp);
nf_ct_expect_put(exp);
}
}
}
/* Get rid of expecteds, set helpers to NULL. */
hlist_nulls_for_each_entry(h, nn, &net->ct.unconfirmed, hnnode)
unhelp(h, me);
for (i = 0; i < net->ct.htable_size; i++) {
hlist_nulls_for_each_entry(h, nn, &net->ct.hash[i], hnnode)
unhelp(h, me);
}
}
void nf_conntrack_helper_unregister(struct nf_conntrack_helper *me)
{
struct net *net;
mutex_lock(&nf_ct_helper_mutex);
hlist_del_rcu(&me->hnode);
nf_ct_helper_count--;
mutex_unlock(&nf_ct_helper_mutex);
/* Make sure every nothing is still using the helper unless its a
* connection in the hash.
*/
synchronize_rcu();
rtnl_lock();
spin_lock_bh(&nf_conntrack_lock);
for_each_net(net)
__nf_conntrack_helper_unregister(me, net);
spin_unlock_bh(&nf_conntrack_lock);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_unregister);
static struct nf_ct_ext_type helper_extend __read_mostly = {
.len = sizeof(struct nf_conn_help),
.align = __alignof__(struct nf_conn_help),
.id = NF_CT_EXT_HELPER,
};
int nf_conntrack_helper_init(struct net *net)
{
int err;
net->ct.auto_assign_helper_warned = false;
net->ct.sysctl_auto_assign_helper = nf_ct_auto_assign_helper;
if (net_eq(net, &init_net)) {
nf_ct_helper_hsize = 1; /* gets rounded up to use one page */
nf_ct_helper_hash =
nf_ct_alloc_hashtable(&nf_ct_helper_hsize, 0);
if (!nf_ct_helper_hash)
return -ENOMEM;
err = nf_ct_extend_register(&helper_extend);
if (err < 0)
goto err1;
}
err = nf_conntrack_helper_init_sysctl(net);
if (err < 0)
goto out_sysctl;
return 0;
out_sysctl:
if (net_eq(net, &init_net))
nf_ct_extend_unregister(&helper_extend);
err1:
nf_ct_free_hashtable(nf_ct_helper_hash, nf_ct_helper_hsize);
return err;
}
void nf_conntrack_helper_fini(struct net *net)
{
nf_conntrack_helper_fini_sysctl(net);
if (net_eq(net, &init_net)) {
nf_ct_extend_unregister(&helper_extend);
nf_ct_free_hashtable(nf_ct_helper_hash, nf_ct_helper_hsize);
}
}
| gpl-2.0 |
EnJens/kernel_tf201_stock | fs/ext3/inode.c | 306 | 108078 | /*
* linux/fs/ext3/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie
* (sct@redhat.com), 1993, 1998
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* (jj@sunsite.ms.mff.cuni.cz)
*
* Assorted race fixes, rewrite of ext3_get_block() by Al Viro, 2000
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/ext3_jbd.h>
#include <linux/jbd.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include <linux/mpage.h>
#include <linux/uio.h>
#include <linux/bio.h>
#include <linux/fiemap.h>
#include <linux/namei.h>
#include <trace/events/ext3.h>
#include "xattr.h"
#include "acl.h"
static int ext3_writepage_trans_blocks(struct inode *inode);
static int ext3_block_truncate_page(struct inode *inode, loff_t from);
/*
* Test whether an inode is a fast symlink.
*/
static int ext3_inode_is_fast_symlink(struct inode *inode)
{
int ea_blocks = EXT3_I(inode)->i_file_acl ?
(inode->i_sb->s_blocksize >> 9) : 0;
return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
}
/*
* The ext3 forget function must perform a revoke if we are freeing data
* which has been journaled. Metadata (eg. indirect blocks) must be
* revoked in all cases.
*
* "bh" may be NULL: a metadata block may have been freed from memory
* but there may still be a record of it in the journal, and that record
* still needs to be revoked.
*/
int ext3_forget(handle_t *handle, int is_metadata, struct inode *inode,
struct buffer_head *bh, ext3_fsblk_t blocknr)
{
int err;
might_sleep();
trace_ext3_forget(inode, is_metadata, blocknr);
BUFFER_TRACE(bh, "enter");
jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
"data mode %lx\n",
bh, is_metadata, inode->i_mode,
test_opt(inode->i_sb, DATA_FLAGS));
/* Never use the revoke function if we are doing full data
* journaling: there is no need to, and a V1 superblock won't
* support it. Otherwise, only skip the revoke on un-journaled
* data blocks. */
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT3_MOUNT_JOURNAL_DATA ||
(!is_metadata && !ext3_should_journal_data(inode))) {
if (bh) {
BUFFER_TRACE(bh, "call journal_forget");
return ext3_journal_forget(handle, bh);
}
return 0;
}
/*
* data!=journal && (is_metadata || should_journal_data(inode))
*/
BUFFER_TRACE(bh, "call ext3_journal_revoke");
err = ext3_journal_revoke(handle, blocknr, bh);
if (err)
ext3_abort(inode->i_sb, __func__,
"error %d when attempting revoke", err);
BUFFER_TRACE(bh, "exit");
return err;
}
/*
* Work out how many blocks we need to proceed with the next chunk of a
* truncate transaction.
*/
static unsigned long blocks_for_truncate(struct inode *inode)
{
unsigned long needed;
needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
/* Give ourselves just enough room to cope with inodes in which
* i_blocks is corrupt: we've seen disk corruptions in the past
* which resulted in random data in an inode which looked enough
* like a regular file for ext3 to try to delete it. Things
* will go a bit crazy if that happens, but at least we should
* try not to panic the whole kernel. */
if (needed < 2)
needed = 2;
/* But we need to bound the transaction so we don't overflow the
* journal. */
if (needed > EXT3_MAX_TRANS_DATA)
needed = EXT3_MAX_TRANS_DATA;
return EXT3_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
}
/*
* Truncate transactions can be complex and absolutely huge. So we need to
* be able to restart the transaction at a conventient checkpoint to make
* sure we don't overflow the journal.
*
* start_transaction gets us a new handle for a truncate transaction,
* and extend_transaction tries to extend the existing one a bit. If
* extend fails, we need to propagate the failure up and restart the
* transaction in the top-level truncate loop. --sct
*/
static handle_t *start_transaction(struct inode *inode)
{
handle_t *result;
result = ext3_journal_start(inode, blocks_for_truncate(inode));
if (!IS_ERR(result))
return result;
ext3_std_error(inode->i_sb, PTR_ERR(result));
return result;
}
/*
* Try to extend this transaction for the purposes of truncation.
*
* Returns 0 if we managed to create more room. If we can't create more
* room, and the transaction must be restarted we return 1.
*/
static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
{
if (handle->h_buffer_credits > EXT3_RESERVE_TRANS_BLOCKS)
return 0;
if (!ext3_journal_extend(handle, blocks_for_truncate(inode)))
return 0;
return 1;
}
/*
* Restart the transaction associated with *handle. This does a commit,
* so before we call here everything must be consistently dirtied against
* this transaction.
*/
static int truncate_restart_transaction(handle_t *handle, struct inode *inode)
{
int ret;
jbd_debug(2, "restarting handle %p\n", handle);
/*
* Drop truncate_mutex to avoid deadlock with ext3_get_blocks_handle
* At this moment, get_block can be called only for blocks inside
* i_size since page cache has been already dropped and writes are
* blocked by i_mutex. So we can safely drop the truncate_mutex.
*/
mutex_unlock(&EXT3_I(inode)->truncate_mutex);
ret = ext3_journal_restart(handle, blocks_for_truncate(inode));
mutex_lock(&EXT3_I(inode)->truncate_mutex);
return ret;
}
/*
* Called at inode eviction from icache
*/
void ext3_evict_inode (struct inode *inode)
{
struct ext3_inode_info *ei = EXT3_I(inode);
struct ext3_block_alloc_info *rsv;
handle_t *handle;
int want_delete = 0;
trace_ext3_evict_inode(inode);
if (!inode->i_nlink && !is_bad_inode(inode)) {
dquot_initialize(inode);
want_delete = 1;
}
/*
* When journalling data dirty buffers are tracked only in the journal.
* So although mm thinks everything is clean and ready for reaping the
* inode might still have some pages to write in the running
* transaction or waiting to be checkpointed. Thus calling
* journal_invalidatepage() (via truncate_inode_pages()) to discard
* these buffers can cause data loss. Also even if we did not discard
* these buffers, we would have no way to find them after the inode
* is reaped and thus user could see stale data if he tries to read
* them before the transaction is checkpointed. So be careful and
* force everything to disk here... We use ei->i_datasync_tid to
* store the newest transaction containing inode's data.
*
* Note that directories do not have this problem because they don't
* use page cache.
*/
if (inode->i_nlink && ext3_should_journal_data(inode) &&
(S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
tid_t commit_tid = atomic_read(&ei->i_datasync_tid);
journal_t *journal = EXT3_SB(inode->i_sb)->s_journal;
log_start_commit(journal, commit_tid);
log_wait_commit(journal, commit_tid);
filemap_write_and_wait(&inode->i_data);
}
truncate_inode_pages(&inode->i_data, 0);
ext3_discard_reservation(inode);
rsv = ei->i_block_alloc_info;
ei->i_block_alloc_info = NULL;
if (unlikely(rsv))
kfree(rsv);
if (!want_delete)
goto no_delete;
handle = start_transaction(inode);
if (IS_ERR(handle)) {
/*
* If we're going to skip the normal cleanup, we still need to
* make sure that the in-core orphan linked list is properly
* cleaned up.
*/
ext3_orphan_del(NULL, inode);
goto no_delete;
}
if (IS_SYNC(inode))
handle->h_sync = 1;
inode->i_size = 0;
if (inode->i_blocks)
ext3_truncate(inode);
/*
* Kill off the orphan record created when the inode lost the last
* link. Note that ext3_orphan_del() has to be able to cope with the
* deletion of a non-existent orphan - ext3_truncate() could
* have removed the record.
*/
ext3_orphan_del(handle, inode);
ei->i_dtime = get_seconds();
/*
* One subtle ordering requirement: if anything has gone wrong
* (transaction abort, IO errors, whatever), then we can still
* do these next steps (the fs will already have been marked as
* having errors), but we can't free the inode if the mark_dirty
* fails.
*/
if (ext3_mark_inode_dirty(handle, inode)) {
/* If that failed, just dquot_drop() and be done with that */
dquot_drop(inode);
end_writeback(inode);
} else {
ext3_xattr_delete_inode(handle, inode);
dquot_free_inode(inode);
dquot_drop(inode);
end_writeback(inode);
ext3_free_inode(handle, inode);
}
ext3_journal_stop(handle);
return;
no_delete:
end_writeback(inode);
dquot_drop(inode);
}
typedef struct {
__le32 *p;
__le32 key;
struct buffer_head *bh;
} Indirect;
static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
{
p->key = *(p->p = v);
p->bh = bh;
}
static int verify_chain(Indirect *from, Indirect *to)
{
while (from <= to && from->key == *from->p)
from++;
return (from > to);
}
/**
* ext3_block_to_path - parse the block number into array of offsets
* @inode: inode in question (we are only interested in its superblock)
* @i_block: block number to be parsed
* @offsets: array to store the offsets in
* @boundary: set this non-zero if the referred-to block is likely to be
* followed (on disk) by an indirect block.
*
* To store the locations of file's data ext3 uses a data structure common
* for UNIX filesystems - tree of pointers anchored in the inode, with
* data blocks at leaves and indirect blocks in intermediate nodes.
* This function translates the block number into path in that tree -
* return value is the path length and @offsets[n] is the offset of
* pointer to (n+1)th node in the nth one. If @block is out of range
* (negative or too large) warning is printed and zero returned.
*
* Note: function doesn't find node addresses, so no IO is needed. All
* we need to know is the capacity of indirect blocks (taken from the
* inode->i_sb).
*/
/*
* Portability note: the last comparison (check that we fit into triple
* indirect block) is spelled differently, because otherwise on an
* architecture with 32-bit longs and 8Kb pages we might get into trouble
* if our filesystem had 8Kb blocks. We might use long long, but that would
* kill us on x86. Oh, well, at least the sign propagation does not matter -
* i_block would have to be negative in the very beginning, so we would not
* get there at all.
*/
static int ext3_block_to_path(struct inode *inode,
long i_block, int offsets[4], int *boundary)
{
int ptrs = EXT3_ADDR_PER_BLOCK(inode->i_sb);
int ptrs_bits = EXT3_ADDR_PER_BLOCK_BITS(inode->i_sb);
const long direct_blocks = EXT3_NDIR_BLOCKS,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
int final = 0;
if (i_block < 0) {
ext3_warning (inode->i_sb, "ext3_block_to_path", "block < 0");
} else if (i_block < direct_blocks) {
offsets[n++] = i_block;
final = direct_blocks;
} else if ( (i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = EXT3_IND_BLOCK;
offsets[n++] = i_block;
final = ptrs;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = EXT3_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = EXT3_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else {
ext3_warning(inode->i_sb, "ext3_block_to_path", "block > big");
}
if (boundary)
*boundary = final - 1 - (i_block & (ptrs - 1));
return n;
}
/**
* ext3_get_branch - read the chain of indirect blocks leading to data
* @inode: inode in question
* @depth: depth of the chain (1 - direct pointer, etc.)
* @offsets: offsets of pointers in inode/indirect blocks
* @chain: place to store the result
* @err: here we store the error value
*
* Function fills the array of triples <key, p, bh> and returns %NULL
* if everything went OK or the pointer to the last filled triple
* (incomplete one) otherwise. Upon the return chain[i].key contains
* the number of (i+1)-th block in the chain (as it is stored in memory,
* i.e. little-endian 32-bit), chain[i].p contains the address of that
* number (it points into struct inode for i==0 and into the bh->b_data
* for i>0) and chain[i].bh points to the buffer_head of i-th indirect
* block for i>0 and NULL for i==0. In other words, it holds the block
* numbers of the chain, addresses they were taken from (and where we can
* verify that chain did not change) and buffer_heads hosting these
* numbers.
*
* Function stops when it stumbles upon zero pointer (absent block)
* (pointer to last triple returned, *@err == 0)
* or when it gets an IO error reading an indirect block
* (ditto, *@err == -EIO)
* or when it notices that chain had been changed while it was reading
* (ditto, *@err == -EAGAIN)
* or when it reads all @depth-1 indirect blocks successfully and finds
* the whole chain, all way to the data (returns %NULL, *err == 0).
*/
static Indirect *ext3_get_branch(struct inode *inode, int depth, int *offsets,
Indirect chain[4], int *err)
{
struct super_block *sb = inode->i_sb;
Indirect *p = chain;
struct buffer_head *bh;
*err = 0;
/* i_data is not going away, no lock needed */
add_chain (chain, NULL, EXT3_I(inode)->i_data + *offsets);
if (!p->key)
goto no_block;
while (--depth) {
bh = sb_bread(sb, le32_to_cpu(p->key));
if (!bh)
goto failure;
/* Reader: pointers */
if (!verify_chain(chain, p))
goto changed;
add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
/* Reader: end */
if (!p->key)
goto no_block;
}
return NULL;
changed:
brelse(bh);
*err = -EAGAIN;
goto no_block;
failure:
*err = -EIO;
no_block:
return p;
}
/**
* ext3_find_near - find a place for allocation with sufficient locality
* @inode: owner
* @ind: descriptor of indirect block.
*
* This function returns the preferred place for block allocation.
* It is used when heuristic for sequential allocation fails.
* Rules are:
* + if there is a block to the left of our position - allocate near it.
* + if pointer will live in indirect block - allocate near that block.
* + if pointer will live in inode - allocate in the same
* cylinder group.
*
* In the latter case we colour the starting block by the callers PID to
* prevent it from clashing with concurrent allocations for a different inode
* in the same block group. The PID is used here so that functionally related
* files will be close-by on-disk.
*
* Caller must make sure that @ind is valid and will stay that way.
*/
static ext3_fsblk_t ext3_find_near(struct inode *inode, Indirect *ind)
{
struct ext3_inode_info *ei = EXT3_I(inode);
__le32 *start = ind->bh ? (__le32*) ind->bh->b_data : ei->i_data;
__le32 *p;
ext3_fsblk_t bg_start;
ext3_grpblk_t colour;
/* Try to find previous block */
for (p = ind->p - 1; p >= start; p--) {
if (*p)
return le32_to_cpu(*p);
}
/* No such thing, so let's try location of indirect block */
if (ind->bh)
return ind->bh->b_blocknr;
/*
* It is going to be referred to from the inode itself? OK, just put it
* into the same cylinder group then.
*/
bg_start = ext3_group_first_block_no(inode->i_sb, ei->i_block_group);
colour = (current->pid % 16) *
(EXT3_BLOCKS_PER_GROUP(inode->i_sb) / 16);
return bg_start + colour;
}
/**
* ext3_find_goal - find a preferred place for allocation.
* @inode: owner
* @block: block we want
* @partial: pointer to the last triple within a chain
*
* Normally this function find the preferred place for block allocation,
* returns it.
*/
static ext3_fsblk_t ext3_find_goal(struct inode *inode, long block,
Indirect *partial)
{
struct ext3_block_alloc_info *block_i;
block_i = EXT3_I(inode)->i_block_alloc_info;
/*
* try the heuristic for sequential allocation,
* failing that at least try to get decent locality.
*/
if (block_i && (block == block_i->last_alloc_logical_block + 1)
&& (block_i->last_alloc_physical_block != 0)) {
return block_i->last_alloc_physical_block + 1;
}
return ext3_find_near(inode, partial);
}
/**
* ext3_blks_to_allocate - Look up the block map and count the number
* of direct blocks need to be allocated for the given branch.
*
* @branch: chain of indirect blocks
* @k: number of blocks need for indirect blocks
* @blks: number of data blocks to be mapped.
* @blocks_to_boundary: the offset in the indirect block
*
* return the total number of blocks to be allocate, including the
* direct and indirect blocks.
*/
static int ext3_blks_to_allocate(Indirect *branch, int k, unsigned long blks,
int blocks_to_boundary)
{
unsigned long count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now we don't handle cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary &&
le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
/**
* ext3_alloc_blocks - multiple allocate blocks needed for a branch
* @handle: handle for this transaction
* @inode: owner
* @goal: preferred place for allocation
* @indirect_blks: the number of blocks need to allocate for indirect
* blocks
* @blks: number of blocks need to allocated for direct blocks
* @new_blocks: on return it will store the new block numbers for
* the indirect blocks(if needed) and the first direct block,
* @err: here we store the error value
*
* return the number of direct blocks allocated
*/
static int ext3_alloc_blocks(handle_t *handle, struct inode *inode,
ext3_fsblk_t goal, int indirect_blks, int blks,
ext3_fsblk_t new_blocks[4], int *err)
{
int target, i;
unsigned long count = 0;
int index = 0;
ext3_fsblk_t current_block = 0;
int ret = 0;
/*
* Here we try to allocate the requested multiple blocks at once,
* on a best-effort basis.
* To build a branch, we should allocate blocks for
* the indirect blocks(if not allocated yet), and at least
* the first direct block of this branch. That's the
* minimum number of blocks need to allocate(required)
*/
target = blks + indirect_blks;
while (1) {
count = target;
/* allocating blocks for indirect blocks and direct blocks */
current_block = ext3_new_blocks(handle,inode,goal,&count,err);
if (*err)
goto failed_out;
target -= count;
/* allocate blocks for indirect blocks */
while (index < indirect_blks && count) {
new_blocks[index++] = current_block++;
count--;
}
if (count > 0)
break;
}
/* save the new block number for the first direct block */
new_blocks[index] = current_block;
/* total number of blocks allocated for direct blocks */
ret = count;
*err = 0;
return ret;
failed_out:
for (i = 0; i <index; i++)
ext3_free_blocks(handle, inode, new_blocks[i], 1);
return ret;
}
/**
* ext3_alloc_branch - allocate and set up a chain of blocks.
* @handle: handle for this transaction
* @inode: owner
* @indirect_blks: number of allocated indirect blocks
* @blks: number of allocated direct blocks
* @goal: preferred place for allocation
* @offsets: offsets (in the blocks) to store the pointers to next.
* @branch: place to store the chain in.
*
* This function allocates blocks, zeroes out all but the last one,
* links them into chain and (if we are synchronous) writes them to disk.
* In other words, it prepares a branch that can be spliced onto the
* inode. It stores the information about that chain in the branch[], in
* the same format as ext3_get_branch() would do. We are calling it after
* we had read the existing part of chain and partial points to the last
* triple of that (one with zero ->key). Upon the exit we have the same
* picture as after the successful ext3_get_block(), except that in one
* place chain is disconnected - *branch->p is still zero (we did not
* set the last link), but branch->key contains the number that should
* be placed into *branch->p to fill that gap.
*
* If allocation fails we free all blocks we've allocated (and forget
* their buffer_heads) and return the error value the from failed
* ext3_alloc_block() (normally -ENOSPC). Otherwise we set the chain
* as described above and return 0.
*/
static int ext3_alloc_branch(handle_t *handle, struct inode *inode,
int indirect_blks, int *blks, ext3_fsblk_t goal,
int *offsets, Indirect *branch)
{
int blocksize = inode->i_sb->s_blocksize;
int i, n = 0;
int err = 0;
struct buffer_head *bh;
int num;
ext3_fsblk_t new_blocks[4];
ext3_fsblk_t current_block;
num = ext3_alloc_blocks(handle, inode, goal, indirect_blks,
*blks, new_blocks, &err);
if (err)
return err;
branch[0].key = cpu_to_le32(new_blocks[0]);
/*
* metadata blocks and data blocks are allocated.
*/
for (n = 1; n <= indirect_blks; n++) {
/*
* Get buffer_head for parent block, zero it out
* and set the pointer to new one, then send
* parent to disk.
*/
bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
branch[n].bh = bh;
lock_buffer(bh);
BUFFER_TRACE(bh, "call get_create_access");
err = ext3_journal_get_create_access(handle, bh);
if (err) {
unlock_buffer(bh);
brelse(bh);
goto failed;
}
memset(bh->b_data, 0, blocksize);
branch[n].p = (__le32 *) bh->b_data + offsets[n];
branch[n].key = cpu_to_le32(new_blocks[n]);
*branch[n].p = branch[n].key;
if ( n == indirect_blks) {
current_block = new_blocks[n];
/*
* End of chain, update the last new metablock of
* the chain to point to the new allocated
* data blocks numbers
*/
for (i=1; i < num; i++)
*(branch[n].p + i) = cpu_to_le32(++current_block);
}
BUFFER_TRACE(bh, "marking uptodate");
set_buffer_uptodate(bh);
unlock_buffer(bh);
BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
err = ext3_journal_dirty_metadata(handle, bh);
if (err)
goto failed;
}
*blks = num;
return err;
failed:
/* Allocation failed, free what we already allocated */
for (i = 1; i <= n ; i++) {
BUFFER_TRACE(branch[i].bh, "call journal_forget");
ext3_journal_forget(handle, branch[i].bh);
}
for (i = 0; i <indirect_blks; i++)
ext3_free_blocks(handle, inode, new_blocks[i], 1);
ext3_free_blocks(handle, inode, new_blocks[i], num);
return err;
}
/**
* ext3_splice_branch - splice the allocated branch onto inode.
* @handle: handle for this transaction
* @inode: owner
* @block: (logical) number of block we are adding
* @where: location of missing link
* @num: number of indirect blocks we are adding
* @blks: number of direct blocks we are adding
*
* This function fills the missing link and does all housekeeping needed in
* inode (->i_blocks, etc.). In case of success we end up with the full
* chain to new block and return 0.
*/
static int ext3_splice_branch(handle_t *handle, struct inode *inode,
long block, Indirect *where, int num, int blks)
{
int i;
int err = 0;
struct ext3_block_alloc_info *block_i;
ext3_fsblk_t current_block;
struct ext3_inode_info *ei = EXT3_I(inode);
block_i = ei->i_block_alloc_info;
/*
* If we're splicing into a [td]indirect block (as opposed to the
* inode) then we need to get write access to the [td]indirect block
* before the splice.
*/
if (where->bh) {
BUFFER_TRACE(where->bh, "get_write_access");
err = ext3_journal_get_write_access(handle, where->bh);
if (err)
goto err_out;
}
/* That's it */
*where->p = where->key;
/*
* Update the host buffer_head or inode to point to more just allocated
* direct blocks blocks
*/
if (num == 0 && blks > 1) {
current_block = le32_to_cpu(where->key) + 1;
for (i = 1; i < blks; i++)
*(where->p + i ) = cpu_to_le32(current_block++);
}
/*
* update the most recently allocated logical & physical block
* in i_block_alloc_info, to assist find the proper goal block for next
* allocation
*/
if (block_i) {
block_i->last_alloc_logical_block = block + blks - 1;
block_i->last_alloc_physical_block =
le32_to_cpu(where[num].key) + blks - 1;
}
/* We are done with atomic stuff, now do the rest of housekeeping */
inode->i_ctime = CURRENT_TIME_SEC;
ext3_mark_inode_dirty(handle, inode);
/* ext3_mark_inode_dirty already updated i_sync_tid */
atomic_set(&ei->i_datasync_tid, handle->h_transaction->t_tid);
/* had we spliced it onto indirect block? */
if (where->bh) {
/*
* If we spliced it onto an indirect block, we haven't
* altered the inode. Note however that if it is being spliced
* onto an indirect block at the very end of the file (the
* file is growing) then we *will* alter the inode to reflect
* the new i_size. But that is not done here - it is done in
* generic_commit_write->__mark_inode_dirty->ext3_dirty_inode.
*/
jbd_debug(5, "splicing indirect only\n");
BUFFER_TRACE(where->bh, "call ext3_journal_dirty_metadata");
err = ext3_journal_dirty_metadata(handle, where->bh);
if (err)
goto err_out;
} else {
/*
* OK, we spliced it into the inode itself on a direct block.
* Inode was dirtied above.
*/
jbd_debug(5, "splicing direct\n");
}
return err;
err_out:
for (i = 1; i <= num; i++) {
BUFFER_TRACE(where[i].bh, "call journal_forget");
ext3_journal_forget(handle, where[i].bh);
ext3_free_blocks(handle,inode,le32_to_cpu(where[i-1].key),1);
}
ext3_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks);
return err;
}
/*
* Allocation strategy is simple: if we have to allocate something, we will
* have to go the whole way to leaf. So let's do it before attaching anything
* to tree, set linkage between the newborn blocks, write them if sync is
* required, recheck the path, free and repeat if check fails, otherwise
* set the last missing link (that will protect us from any truncate-generated
* removals - all blocks on the path are immune now) and possibly force the
* write on the parent block.
* That has a nice additional property: no special recovery from the failed
* allocations is needed - we simply release blocks and do not touch anything
* reachable from inode.
*
* `handle' can be NULL if create == 0.
*
* The BKL may not be held on entry here. Be sure to take it early.
* return > 0, # of blocks mapped or allocated.
* return = 0, if plain lookup failed.
* return < 0, error case.
*/
int ext3_get_blocks_handle(handle_t *handle, struct inode *inode,
sector_t iblock, unsigned long maxblocks,
struct buffer_head *bh_result,
int create)
{
int err = -EIO;
int offsets[4];
Indirect chain[4];
Indirect *partial;
ext3_fsblk_t goal;
int indirect_blks;
int blocks_to_boundary = 0;
int depth;
struct ext3_inode_info *ei = EXT3_I(inode);
int count = 0;
ext3_fsblk_t first_block = 0;
trace_ext3_get_blocks_enter(inode, iblock, maxblocks, create);
J_ASSERT(handle != NULL || create == 0);
depth = ext3_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
if (depth == 0)
goto out;
partial = ext3_get_branch(inode, depth, offsets, chain, &err);
/* Simplest case - block found, no allocation needed */
if (!partial) {
first_block = le32_to_cpu(chain[depth - 1].key);
clear_buffer_new(bh_result);
count++;
/*map more blocks*/
while (count < maxblocks && count <= blocks_to_boundary) {
ext3_fsblk_t blk;
if (!verify_chain(chain, chain + depth - 1)) {
/*
* Indirect block might be removed by
* truncate while we were reading it.
* Handling of that case: forget what we've
* got now. Flag the err as EAGAIN, so it
* will reread.
*/
err = -EAGAIN;
count = 0;
break;
}
blk = le32_to_cpu(*(chain[depth-1].p + count));
if (blk == first_block + count)
count++;
else
break;
}
if (err != -EAGAIN)
goto got_it;
}
/* Next simple case - plain lookup or failed read of indirect block */
if (!create || err == -EIO)
goto cleanup;
/*
* Block out ext3_truncate while we alter the tree
*/
mutex_lock(&ei->truncate_mutex);
/*
* If the indirect block is missing while we are reading
* the chain(ext3_get_branch() returns -EAGAIN err), or
* if the chain has been changed after we grab the semaphore,
* (either because another process truncated this branch, or
* another get_block allocated this branch) re-grab the chain to see if
* the request block has been allocated or not.
*
* Since we already block the truncate/other get_block
* at this point, we will have the current copy of the chain when we
* splice the branch into the tree.
*/
if (err == -EAGAIN || !verify_chain(chain, partial)) {
while (partial > chain) {
brelse(partial->bh);
partial--;
}
partial = ext3_get_branch(inode, depth, offsets, chain, &err);
if (!partial) {
count++;
mutex_unlock(&ei->truncate_mutex);
if (err)
goto cleanup;
clear_buffer_new(bh_result);
goto got_it;
}
}
/*
* Okay, we need to do block allocation. Lazily initialize the block
* allocation info here if necessary
*/
if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
ext3_init_block_alloc_info(inode);
goal = ext3_find_goal(inode, iblock, partial);
/* the number of blocks need to allocate for [d,t]indirect blocks */
indirect_blks = (chain + depth) - partial - 1;
/*
* Next look up the indirect map to count the totoal number of
* direct blocks to allocate for this branch.
*/
count = ext3_blks_to_allocate(partial, indirect_blks,
maxblocks, blocks_to_boundary);
err = ext3_alloc_branch(handle, inode, indirect_blks, &count, goal,
offsets + (partial - chain), partial);
/*
* The ext3_splice_branch call will free and forget any buffers
* on the new chain if there is a failure, but that risks using
* up transaction credits, especially for bitmaps where the
* credits cannot be returned. Can we handle this somehow? We
* may need to return -EAGAIN upwards in the worst case. --sct
*/
if (!err)
err = ext3_splice_branch(handle, inode, iblock,
partial, indirect_blks, count);
mutex_unlock(&ei->truncate_mutex);
if (err)
goto cleanup;
set_buffer_new(bh_result);
got_it:
map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
if (count > blocks_to_boundary)
set_buffer_boundary(bh_result);
err = count;
/* Clean up and exit */
partial = chain + depth - 1; /* the whole chain */
cleanup:
while (partial > chain) {
BUFFER_TRACE(partial->bh, "call brelse");
brelse(partial->bh);
partial--;
}
BUFFER_TRACE(bh_result, "returned");
out:
trace_ext3_get_blocks_exit(inode, iblock,
depth ? le32_to_cpu(chain[depth-1].key) : 0,
count, err);
return err;
}
/* Maximum number of blocks we map for direct IO at once. */
#define DIO_MAX_BLOCKS 4096
/*
* Number of credits we need for writing DIO_MAX_BLOCKS:
* We need sb + group descriptor + bitmap + inode -> 4
* For B blocks with A block pointers per block we need:
* 1 (triple ind.) + (B/A/A + 2) (doubly ind.) + (B/A + 2) (indirect).
* If we plug in 4096 for B and 256 for A (for 1KB block size), we get 25.
*/
#define DIO_CREDITS 25
static int ext3_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
handle_t *handle = ext3_journal_current_handle();
int ret = 0, started = 0;
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
if (create && !handle) { /* Direct IO write... */
if (max_blocks > DIO_MAX_BLOCKS)
max_blocks = DIO_MAX_BLOCKS;
handle = ext3_journal_start(inode, DIO_CREDITS +
EXT3_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
started = 1;
}
ret = ext3_get_blocks_handle(handle, inode, iblock,
max_blocks, bh_result, create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
if (started)
ext3_journal_stop(handle);
out:
return ret;
}
int ext3_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
return generic_block_fiemap(inode, fieinfo, start, len,
ext3_get_block);
}
/*
* `handle' can be NULL if create is zero
*/
struct buffer_head *ext3_getblk(handle_t *handle, struct inode *inode,
long block, int create, int *errp)
{
struct buffer_head dummy;
int fatal = 0, err;
J_ASSERT(handle != NULL || create == 0);
dummy.b_state = 0;
dummy.b_blocknr = -1000;
buffer_trace_init(&dummy.b_history);
err = ext3_get_blocks_handle(handle, inode, block, 1,
&dummy, create);
/*
* ext3_get_blocks_handle() returns number of blocks
* mapped. 0 in case of a HOLE.
*/
if (err > 0) {
if (err > 1)
WARN_ON(1);
err = 0;
}
*errp = err;
if (!err && buffer_mapped(&dummy)) {
struct buffer_head *bh;
bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
if (!bh) {
*errp = -EIO;
goto err;
}
if (buffer_new(&dummy)) {
J_ASSERT(create != 0);
J_ASSERT(handle != NULL);
/*
* Now that we do not always journal data, we should
* keep in mind whether this should always journal the
* new buffer as metadata. For now, regular file
* writes use ext3_get_block instead, so it's not a
* problem.
*/
lock_buffer(bh);
BUFFER_TRACE(bh, "call get_create_access");
fatal = ext3_journal_get_create_access(handle, bh);
if (!fatal && !buffer_uptodate(bh)) {
memset(bh->b_data,0,inode->i_sb->s_blocksize);
set_buffer_uptodate(bh);
}
unlock_buffer(bh);
BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
err = ext3_journal_dirty_metadata(handle, bh);
if (!fatal)
fatal = err;
} else {
BUFFER_TRACE(bh, "not a new buffer");
}
if (fatal) {
*errp = fatal;
brelse(bh);
bh = NULL;
}
return bh;
}
err:
return NULL;
}
struct buffer_head *ext3_bread(handle_t *handle, struct inode *inode,
int block, int create, int *err)
{
struct buffer_head * bh;
bh = ext3_getblk(handle, inode, block, create, err);
if (!bh)
return bh;
if (buffer_uptodate(bh))
return bh;
ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
wait_on_buffer(bh);
if (buffer_uptodate(bh))
return bh;
put_bh(bh);
*err = -EIO;
return NULL;
}
static int walk_page_buffers( handle_t *handle,
struct buffer_head *head,
unsigned from,
unsigned to,
int *partial,
int (*fn)( handle_t *handle,
struct buffer_head *bh))
{
struct buffer_head *bh;
unsigned block_start, block_end;
unsigned blocksize = head->b_size;
int err, ret = 0;
struct buffer_head *next;
for ( bh = head, block_start = 0;
ret == 0 && (bh != head || !block_start);
block_start = block_end, bh = next)
{
next = bh->b_this_page;
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (partial && !buffer_uptodate(bh))
*partial = 1;
continue;
}
err = (*fn)(handle, bh);
if (!ret)
ret = err;
}
return ret;
}
/*
* To preserve ordering, it is essential that the hole instantiation and
* the data write be encapsulated in a single transaction. We cannot
* close off a transaction and start a new one between the ext3_get_block()
* and the commit_write(). So doing the journal_start at the start of
* prepare_write() is the right place.
*
* Also, this function can nest inside ext3_writepage() ->
* block_write_full_page(). In that case, we *know* that ext3_writepage()
* has generated enough buffer credits to do the whole page. So we won't
* block on the journal in that case, which is good, because the caller may
* be PF_MEMALLOC.
*
* By accident, ext3 can be reentered when a transaction is open via
* quota file writes. If we were to commit the transaction while thus
* reentered, there can be a deadlock - we would be holding a quota
* lock, and the commit would never complete if another thread had a
* transaction open and was blocking on the quota lock - a ranking
* violation.
*
* So what we do is to rely on the fact that journal_stop/journal_start
* will _not_ run commit under these circumstances because handle->h_ref
* is elevated. We'll still have enough credits for the tiny quotafile
* write.
*/
static int do_journal_get_write_access(handle_t *handle,
struct buffer_head *bh)
{
int dirty = buffer_dirty(bh);
int ret;
if (!buffer_mapped(bh) || buffer_freed(bh))
return 0;
/*
* __block_prepare_write() could have dirtied some buffers. Clean
* the dirty bit as jbd2_journal_get_write_access() could complain
* otherwise about fs integrity issues. Setting of the dirty bit
* by __block_prepare_write() isn't a real problem here as we clear
* the bit before releasing a page lock and thus writeback cannot
* ever write the buffer.
*/
if (dirty)
clear_buffer_dirty(bh);
ret = ext3_journal_get_write_access(handle, bh);
if (!ret && dirty)
ret = ext3_journal_dirty_metadata(handle, bh);
return ret;
}
/*
* Truncate blocks that were not used by write. We have to truncate the
* pagecache as well so that corresponding buffers get properly unmapped.
*/
static void ext3_truncate_failed_write(struct inode *inode)
{
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext3_truncate(inode);
}
/*
* Truncate blocks that were not used by direct IO write. We have to zero out
* the last file block as well because direct IO might have written to it.
*/
static void ext3_truncate_failed_direct_write(struct inode *inode)
{
ext3_block_truncate_page(inode, inode->i_size);
ext3_truncate(inode);
}
static int ext3_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
int ret;
handle_t *handle;
int retries = 0;
struct page *page;
pgoff_t index;
unsigned from, to;
/* Reserve one block more for addition to orphan list in case
* we allocate blocks but write fails for some reason */
int needed_blocks = ext3_writepage_trans_blocks(inode) + 1;
trace_ext3_write_begin(inode, pos, len, flags);
index = pos >> PAGE_CACHE_SHIFT;
from = pos & (PAGE_CACHE_SIZE - 1);
to = from + len;
retry:
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page)
return -ENOMEM;
*pagep = page;
handle = ext3_journal_start(inode, needed_blocks);
if (IS_ERR(handle)) {
unlock_page(page);
page_cache_release(page);
ret = PTR_ERR(handle);
goto out;
}
ret = __block_write_begin(page, pos, len, ext3_get_block);
if (ret)
goto write_begin_failed;
if (ext3_should_journal_data(inode)) {
ret = walk_page_buffers(handle, page_buffers(page),
from, to, NULL, do_journal_get_write_access);
}
write_begin_failed:
if (ret) {
/*
* block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_mutex.
*
* Add inode to orphan list in case we crash before truncate
* finishes. Do this only if ext3_can_truncate() agrees so
* that orphan processing code is happy.
*/
if (pos + len > inode->i_size && ext3_can_truncate(inode))
ext3_orphan_add(handle, inode);
ext3_journal_stop(handle);
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
ext3_truncate_failed_write(inode);
}
if (ret == -ENOSPC && ext3_should_retry_alloc(inode->i_sb, &retries))
goto retry;
out:
return ret;
}
int ext3_journal_dirty_data(handle_t *handle, struct buffer_head *bh)
{
int err = journal_dirty_data(handle, bh);
if (err)
ext3_journal_abort_handle(__func__, __func__,
bh, handle, err);
return err;
}
/* For ordered writepage and write_end functions */
static int journal_dirty_data_fn(handle_t *handle, struct buffer_head *bh)
{
/*
* Write could have mapped the buffer but it didn't copy the data in
* yet. So avoid filing such buffer into a transaction.
*/
if (buffer_mapped(bh) && buffer_uptodate(bh))
return ext3_journal_dirty_data(handle, bh);
return 0;
}
/* For write_end() in data=journal mode */
static int write_end_fn(handle_t *handle, struct buffer_head *bh)
{
if (!buffer_mapped(bh) || buffer_freed(bh))
return 0;
set_buffer_uptodate(bh);
return ext3_journal_dirty_metadata(handle, bh);
}
/*
* This is nasty and subtle: ext3_write_begin() could have allocated blocks
* for the whole page but later we failed to copy the data in. Update inode
* size according to what we managed to copy. The rest is going to be
* truncated in write_end function.
*/
static void update_file_sizes(struct inode *inode, loff_t pos, unsigned copied)
{
/* What matters to us is i_disksize. We don't write i_size anywhere */
if (pos + copied > inode->i_size)
i_size_write(inode, pos + copied);
if (pos + copied > EXT3_I(inode)->i_disksize) {
EXT3_I(inode)->i_disksize = pos + copied;
mark_inode_dirty(inode);
}
}
/*
* We need to pick up the new inode size which generic_commit_write gave us
* `file' can be NULL - eg, when called from page_symlink().
*
* ext3 never places buffers on inode->i_mapping->private_list. metadata
* buffers are managed internally.
*/
static int ext3_ordered_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
handle_t *handle = ext3_journal_current_handle();
struct inode *inode = file->f_mapping->host;
unsigned from, to;
int ret = 0, ret2;
trace_ext3_ordered_write_end(inode, pos, len, copied);
copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
from = pos & (PAGE_CACHE_SIZE - 1);
to = from + copied;
ret = walk_page_buffers(handle, page_buffers(page),
from, to, NULL, journal_dirty_data_fn);
if (ret == 0)
update_file_sizes(inode, pos, copied);
/*
* There may be allocated blocks outside of i_size because
* we failed to copy some data. Prepare for truncate.
*/
if (pos + len > inode->i_size && ext3_can_truncate(inode))
ext3_orphan_add(handle, inode);
ret2 = ext3_journal_stop(handle);
if (!ret)
ret = ret2;
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
ext3_truncate_failed_write(inode);
return ret ? ret : copied;
}
static int ext3_writeback_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
handle_t *handle = ext3_journal_current_handle();
struct inode *inode = file->f_mapping->host;
int ret;
trace_ext3_writeback_write_end(inode, pos, len, copied);
copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
update_file_sizes(inode, pos, copied);
/*
* There may be allocated blocks outside of i_size because
* we failed to copy some data. Prepare for truncate.
*/
if (pos + len > inode->i_size && ext3_can_truncate(inode))
ext3_orphan_add(handle, inode);
ret = ext3_journal_stop(handle);
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
ext3_truncate_failed_write(inode);
return ret ? ret : copied;
}
static int ext3_journalled_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
handle_t *handle = ext3_journal_current_handle();
struct inode *inode = mapping->host;
struct ext3_inode_info *ei = EXT3_I(inode);
int ret = 0, ret2;
int partial = 0;
unsigned from, to;
trace_ext3_journalled_write_end(inode, pos, len, copied);
from = pos & (PAGE_CACHE_SIZE - 1);
to = from + len;
if (copied < len) {
if (!PageUptodate(page))
copied = 0;
page_zero_new_buffers(page, from + copied, to);
to = from + copied;
}
ret = walk_page_buffers(handle, page_buffers(page), from,
to, &partial, write_end_fn);
if (!partial)
SetPageUptodate(page);
if (pos + copied > inode->i_size)
i_size_write(inode, pos + copied);
/*
* There may be allocated blocks outside of i_size because
* we failed to copy some data. Prepare for truncate.
*/
if (pos + len > inode->i_size && ext3_can_truncate(inode))
ext3_orphan_add(handle, inode);
ext3_set_inode_state(inode, EXT3_STATE_JDATA);
atomic_set(&ei->i_datasync_tid, handle->h_transaction->t_tid);
if (inode->i_size > ei->i_disksize) {
ei->i_disksize = inode->i_size;
ret2 = ext3_mark_inode_dirty(handle, inode);
if (!ret)
ret = ret2;
}
ret2 = ext3_journal_stop(handle);
if (!ret)
ret = ret2;
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
ext3_truncate_failed_write(inode);
return ret ? ret : copied;
}
/*
* bmap() is special. It gets used by applications such as lilo and by
* the swapper to find the on-disk block of a specific piece of data.
*
* Naturally, this is dangerous if the block concerned is still in the
* journal. If somebody makes a swapfile on an ext3 data-journaling
* filesystem and enables swap, then they may get a nasty shock when the
* data getting swapped to that swapfile suddenly gets overwritten by
* the original zero's written out previously to the journal and
* awaiting writeback in the kernel's buffer cache.
*
* So, if we see any bmap calls here on a modified, data-journaled file,
* take extra steps to flush any blocks which might be in the cache.
*/
static sector_t ext3_bmap(struct address_space *mapping, sector_t block)
{
struct inode *inode = mapping->host;
journal_t *journal;
int err;
if (ext3_test_inode_state(inode, EXT3_STATE_JDATA)) {
/*
* This is a REALLY heavyweight approach, but the use of
* bmap on dirty files is expected to be extremely rare:
* only if we run lilo or swapon on a freshly made file
* do we expect this to happen.
*
* (bmap requires CAP_SYS_RAWIO so this does not
* represent an unprivileged user DOS attack --- we'd be
* in trouble if mortal users could trigger this path at
* will.)
*
* NB. EXT3_STATE_JDATA is not set on files other than
* regular files. If somebody wants to bmap a directory
* or symlink and gets confused because the buffer
* hasn't yet been flushed to disk, they deserve
* everything they get.
*/
ext3_clear_inode_state(inode, EXT3_STATE_JDATA);
journal = EXT3_JOURNAL(inode);
journal_lock_updates(journal);
err = journal_flush(journal);
journal_unlock_updates(journal);
if (err)
return 0;
}
return generic_block_bmap(mapping,block,ext3_get_block);
}
static int bget_one(handle_t *handle, struct buffer_head *bh)
{
get_bh(bh);
return 0;
}
static int bput_one(handle_t *handle, struct buffer_head *bh)
{
put_bh(bh);
return 0;
}
static int buffer_unmapped(handle_t *handle, struct buffer_head *bh)
{
return !buffer_mapped(bh);
}
/*
* Note that we always start a transaction even if we're not journalling
* data. This is to preserve ordering: any hole instantiation within
* __block_write_full_page -> ext3_get_block() should be journalled
* along with the data so we don't crash and then get metadata which
* refers to old data.
*
* In all journalling modes block_write_full_page() will start the I/O.
*
* Problem:
*
* ext3_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
* ext3_writepage()
*
* Similar for:
*
* ext3_file_write() -> generic_file_write() -> __alloc_pages() -> ...
*
* Same applies to ext3_get_block(). We will deadlock on various things like
* lock_journal and i_truncate_mutex.
*
* Setting PF_MEMALLOC here doesn't work - too many internal memory
* allocations fail.
*
* 16May01: If we're reentered then journal_current_handle() will be
* non-zero. We simply *return*.
*
* 1 July 2001: @@@ FIXME:
* In journalled data mode, a data buffer may be metadata against the
* current transaction. But the same file is part of a shared mapping
* and someone does a writepage() on it.
*
* We will move the buffer onto the async_data list, but *after* it has
* been dirtied. So there's a small window where we have dirty data on
* BJ_Metadata.
*
* Note that this only applies to the last partial page in the file. The
* bit which block_write_full_page() uses prepare/commit for. (That's
* broken code anyway: it's wrong for msync()).
*
* It's a rare case: affects the final partial page, for journalled data
* where the file is subject to bith write() and writepage() in the same
* transction. To fix it we'll need a custom block_write_full_page().
* We'll probably need that anyway for journalling writepage() output.
*
* We don't honour synchronous mounts for writepage(). That would be
* disastrous. Any write() or metadata operation will sync the fs for
* us.
*
* AKPM2: if all the page's buffers are mapped to disk and !data=journal,
* we don't need to open a transaction here.
*/
static int ext3_ordered_writepage(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct buffer_head *page_bufs;
handle_t *handle = NULL;
int ret = 0;
int err;
J_ASSERT(PageLocked(page));
/*
* We don't want to warn for emergency remount. The condition is
* ordered to avoid dereferencing inode->i_sb in non-error case to
* avoid slow-downs.
*/
WARN_ON_ONCE(IS_RDONLY(inode) &&
!(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ERROR_FS));
/*
* We give up here if we're reentered, because it might be for a
* different filesystem.
*/
if (ext3_journal_current_handle())
goto out_fail;
trace_ext3_ordered_writepage(page);
if (!page_has_buffers(page)) {
create_empty_buffers(page, inode->i_sb->s_blocksize,
(1 << BH_Dirty)|(1 << BH_Uptodate));
page_bufs = page_buffers(page);
} else {
page_bufs = page_buffers(page);
if (!walk_page_buffers(NULL, page_bufs, 0, PAGE_CACHE_SIZE,
NULL, buffer_unmapped)) {
/* Provide NULL get_block() to catch bugs if buffers
* weren't really mapped */
return block_write_full_page(page, NULL, wbc);
}
}
handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_fail;
}
walk_page_buffers(handle, page_bufs, 0,
PAGE_CACHE_SIZE, NULL, bget_one);
ret = block_write_full_page(page, ext3_get_block, wbc);
/*
* The page can become unlocked at any point now, and
* truncate can then come in and change things. So we
* can't touch *page from now on. But *page_bufs is
* safe due to elevated refcount.
*/
/*
* And attach them to the current transaction. But only if
* block_write_full_page() succeeded. Otherwise they are unmapped,
* and generally junk.
*/
if (ret == 0) {
err = walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE,
NULL, journal_dirty_data_fn);
if (!ret)
ret = err;
}
walk_page_buffers(handle, page_bufs, 0,
PAGE_CACHE_SIZE, NULL, bput_one);
err = ext3_journal_stop(handle);
if (!ret)
ret = err;
return ret;
out_fail:
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return ret;
}
static int ext3_writeback_writepage(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
handle_t *handle = NULL;
int ret = 0;
int err;
J_ASSERT(PageLocked(page));
/*
* We don't want to warn for emergency remount. The condition is
* ordered to avoid dereferencing inode->i_sb in non-error case to
* avoid slow-downs.
*/
WARN_ON_ONCE(IS_RDONLY(inode) &&
!(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ERROR_FS));
if (ext3_journal_current_handle())
goto out_fail;
trace_ext3_writeback_writepage(page);
if (page_has_buffers(page)) {
if (!walk_page_buffers(NULL, page_buffers(page), 0,
PAGE_CACHE_SIZE, NULL, buffer_unmapped)) {
/* Provide NULL get_block() to catch bugs if buffers
* weren't really mapped */
return block_write_full_page(page, NULL, wbc);
}
}
handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_fail;
}
ret = block_write_full_page(page, ext3_get_block, wbc);
err = ext3_journal_stop(handle);
if (!ret)
ret = err;
return ret;
out_fail:
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return ret;
}
static int ext3_journalled_writepage(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
handle_t *handle = NULL;
int ret = 0;
int err;
J_ASSERT(PageLocked(page));
/*
* We don't want to warn for emergency remount. The condition is
* ordered to avoid dereferencing inode->i_sb in non-error case to
* avoid slow-downs.
*/
WARN_ON_ONCE(IS_RDONLY(inode) &&
!(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ERROR_FS));
if (ext3_journal_current_handle())
goto no_write;
trace_ext3_journalled_writepage(page);
handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto no_write;
}
if (!page_has_buffers(page) || PageChecked(page)) {
/*
* It's mmapped pagecache. Add buffers and journal it. There
* doesn't seem much point in redirtying the page here.
*/
ClearPageChecked(page);
ret = __block_write_begin(page, 0, PAGE_CACHE_SIZE,
ext3_get_block);
if (ret != 0) {
ext3_journal_stop(handle);
goto out_unlock;
}
ret = walk_page_buffers(handle, page_buffers(page), 0,
PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
err = walk_page_buffers(handle, page_buffers(page), 0,
PAGE_CACHE_SIZE, NULL, write_end_fn);
if (ret == 0)
ret = err;
ext3_set_inode_state(inode, EXT3_STATE_JDATA);
atomic_set(&EXT3_I(inode)->i_datasync_tid,
handle->h_transaction->t_tid);
unlock_page(page);
} else {
/*
* It may be a page full of checkpoint-mode buffers. We don't
* really know unless we go poke around in the buffer_heads.
* But block_write_full_page will do the right thing.
*/
ret = block_write_full_page(page, ext3_get_block, wbc);
}
err = ext3_journal_stop(handle);
if (!ret)
ret = err;
out:
return ret;
no_write:
redirty_page_for_writepage(wbc, page);
out_unlock:
unlock_page(page);
goto out;
}
static int ext3_readpage(struct file *file, struct page *page)
{
trace_ext3_readpage(page);
return mpage_readpage(page, ext3_get_block);
}
static int
ext3_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, ext3_get_block);
}
static void ext3_invalidatepage(struct page *page, unsigned long offset)
{
journal_t *journal = EXT3_JOURNAL(page->mapping->host);
trace_ext3_invalidatepage(page, offset);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0)
ClearPageChecked(page);
journal_invalidatepage(journal, page, offset);
}
static int ext3_releasepage(struct page *page, gfp_t wait)
{
journal_t *journal = EXT3_JOURNAL(page->mapping->host);
trace_ext3_releasepage(page);
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
return journal_try_to_free_buffers(journal, page, wait);
}
/*
* If the O_DIRECT write will extend the file then add this inode to the
* orphan list. So recovery will truncate it back to the original size
* if the machine crashes during the write.
*
* If the O_DIRECT write is intantiating holes inside i_size and the machine
* crashes then stale disk data _may_ be exposed inside the file. But current
* VFS code falls back into buffered path in that case so we are safe.
*/
static ssize_t ext3_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct ext3_inode_info *ei = EXT3_I(inode);
handle_t *handle;
ssize_t ret;
int orphan = 0;
size_t count = iov_length(iov, nr_segs);
int retries = 0;
trace_ext3_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
if (rw == WRITE) {
loff_t final_size = offset + count;
if (final_size > inode->i_size) {
/* Credits for sb + inode write */
handle = ext3_journal_start(inode, 2);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext3_orphan_add(handle, inode);
if (ret) {
ext3_journal_stop(handle);
goto out;
}
orphan = 1;
ei->i_disksize = inode->i_size;
ext3_journal_stop(handle);
}
}
retry:
ret = blockdev_direct_IO(rw, iocb, inode, iov, offset, nr_segs,
ext3_get_block);
/*
* In case of error extending write may have instantiated a few
* blocks outside i_size. Trim these off again.
*/
if (unlikely((rw & WRITE) && ret < 0)) {
loff_t isize = i_size_read(inode);
loff_t end = offset + iov_length(iov, nr_segs);
if (end > isize)
ext3_truncate_failed_direct_write(inode);
}
if (ret == -ENOSPC && ext3_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (orphan) {
int err;
/* Credits for sb + inode write */
handle = ext3_journal_start(inode, 2);
if (IS_ERR(handle)) {
/* This is really bad luck. We've written the data
* but cannot extend i_size. Truncate allocated blocks
* and pretend the write failed... */
ext3_truncate_failed_direct_write(inode);
ret = PTR_ERR(handle);
goto out;
}
if (inode->i_nlink)
ext3_orphan_del(handle, inode);
if (ret > 0) {
loff_t end = offset + ret;
if (end > inode->i_size) {
ei->i_disksize = end;
i_size_write(inode, end);
/*
* We're going to return a positive `ret'
* here due to non-zero-length I/O, so there's
* no way of reporting error returns from
* ext3_mark_inode_dirty() to userspace. So
* ignore it.
*/
ext3_mark_inode_dirty(handle, inode);
}
}
err = ext3_journal_stop(handle);
if (ret == 0)
ret = err;
}
out:
trace_ext3_direct_IO_exit(inode, offset,
iov_length(iov, nr_segs), rw, ret);
return ret;
}
/*
* Pages can be marked dirty completely asynchronously from ext3's journalling
* activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
* much here because ->set_page_dirty is called under VFS locks. The page is
* not necessarily locked.
*
* We cannot just dirty the page and leave attached buffers clean, because the
* buffers' dirty state is "definitive". We cannot just set the buffers dirty
* or jbddirty because all the journalling code will explode.
*
* So what we do is to mark the page "pending dirty" and next time writepage
* is called, propagate that into the buffers appropriately.
*/
static int ext3_journalled_set_page_dirty(struct page *page)
{
SetPageChecked(page);
return __set_page_dirty_nobuffers(page);
}
static const struct address_space_operations ext3_ordered_aops = {
.readpage = ext3_readpage,
.readpages = ext3_readpages,
.writepage = ext3_ordered_writepage,
.write_begin = ext3_write_begin,
.write_end = ext3_ordered_write_end,
.bmap = ext3_bmap,
.invalidatepage = ext3_invalidatepage,
.releasepage = ext3_releasepage,
.direct_IO = ext3_direct_IO,
.migratepage = buffer_migrate_page,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations ext3_writeback_aops = {
.readpage = ext3_readpage,
.readpages = ext3_readpages,
.writepage = ext3_writeback_writepage,
.write_begin = ext3_write_begin,
.write_end = ext3_writeback_write_end,
.bmap = ext3_bmap,
.invalidatepage = ext3_invalidatepage,
.releasepage = ext3_releasepage,
.direct_IO = ext3_direct_IO,
.migratepage = buffer_migrate_page,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations ext3_journalled_aops = {
.readpage = ext3_readpage,
.readpages = ext3_readpages,
.writepage = ext3_journalled_writepage,
.write_begin = ext3_write_begin,
.write_end = ext3_journalled_write_end,
.set_page_dirty = ext3_journalled_set_page_dirty,
.bmap = ext3_bmap,
.invalidatepage = ext3_invalidatepage,
.releasepage = ext3_releasepage,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
void ext3_set_aops(struct inode *inode)
{
if (ext3_should_order_data(inode))
inode->i_mapping->a_ops = &ext3_ordered_aops;
else if (ext3_should_writeback_data(inode))
inode->i_mapping->a_ops = &ext3_writeback_aops;
else
inode->i_mapping->a_ops = &ext3_journalled_aops;
}
/*
* ext3_block_truncate_page() zeroes out a mapping from file offset `from'
* up to the end of the block which corresponds to `from'.
* This required during truncate. We need to physically zero the tail end
* of that block so it doesn't yield old data if the file is later grown.
*/
static int ext3_block_truncate_page(struct inode *inode, loff_t from)
{
ext3_fsblk_t index = from >> PAGE_CACHE_SHIFT;
unsigned offset = from & (PAGE_CACHE_SIZE - 1);
unsigned blocksize, iblock, length, pos;
struct page *page;
handle_t *handle = NULL;
struct buffer_head *bh;
int err = 0;
/* Truncated on block boundary - nothing to do */
blocksize = inode->i_sb->s_blocksize;
if ((from & (blocksize - 1)) == 0)
return 0;
page = grab_cache_page(inode->i_mapping, index);
if (!page)
return -ENOMEM;
length = blocksize - (offset & (blocksize - 1));
iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
if (!page_has_buffers(page))
create_empty_buffers(page, blocksize, 0);
/* Find the buffer that contains "offset" */
bh = page_buffers(page);
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
err = 0;
if (buffer_freed(bh)) {
BUFFER_TRACE(bh, "freed: skip");
goto unlock;
}
if (!buffer_mapped(bh)) {
BUFFER_TRACE(bh, "unmapped");
ext3_get_block(inode, iblock, bh, 0);
/* unmapped? It's a hole - nothing to do */
if (!buffer_mapped(bh)) {
BUFFER_TRACE(bh, "still unmapped");
goto unlock;
}
}
/* Ok, it's mapped. Make sure it's up-to-date */
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
err = -EIO;
ll_rw_block(READ, 1, &bh);
wait_on_buffer(bh);
/* Uhhuh. Read error. Complain and punt. */
if (!buffer_uptodate(bh))
goto unlock;
}
/* data=writeback mode doesn't need transaction to zero-out data */
if (!ext3_should_writeback_data(inode)) {
/* We journal at most one block */
handle = ext3_journal_start(inode, 1);
if (IS_ERR(handle)) {
clear_highpage(page);
flush_dcache_page(page);
err = PTR_ERR(handle);
goto unlock;
}
}
if (ext3_should_journal_data(inode)) {
BUFFER_TRACE(bh, "get write access");
err = ext3_journal_get_write_access(handle, bh);
if (err)
goto stop;
}
zero_user(page, offset, length);
BUFFER_TRACE(bh, "zeroed end of block");
err = 0;
if (ext3_should_journal_data(inode)) {
err = ext3_journal_dirty_metadata(handle, bh);
} else {
if (ext3_should_order_data(inode))
err = ext3_journal_dirty_data(handle, bh);
mark_buffer_dirty(bh);
}
stop:
if (handle)
ext3_journal_stop(handle);
unlock:
unlock_page(page);
page_cache_release(page);
return err;
}
/*
* Probably it should be a library function... search for first non-zero word
* or memcmp with zero_page, whatever is better for particular architecture.
* Linus?
*/
static inline int all_zeroes(__le32 *p, __le32 *q)
{
while (p < q)
if (*p++)
return 0;
return 1;
}
/**
* ext3_find_shared - find the indirect blocks for partial truncation.
* @inode: inode in question
* @depth: depth of the affected branch
* @offsets: offsets of pointers in that branch (see ext3_block_to_path)
* @chain: place to store the pointers to partial indirect blocks
* @top: place to the (detached) top of branch
*
* This is a helper function used by ext3_truncate().
*
* When we do truncate() we may have to clean the ends of several
* indirect blocks but leave the blocks themselves alive. Block is
* partially truncated if some data below the new i_size is referred
* from it (and it is on the path to the first completely truncated
* data block, indeed). We have to free the top of that path along
* with everything to the right of the path. Since no allocation
* past the truncation point is possible until ext3_truncate()
* finishes, we may safely do the latter, but top of branch may
* require special attention - pageout below the truncation point
* might try to populate it.
*
* We atomically detach the top of branch from the tree, store the
* block number of its root in *@top, pointers to buffer_heads of
* partially truncated blocks - in @chain[].bh and pointers to
* their last elements that should not be removed - in
* @chain[].p. Return value is the pointer to last filled element
* of @chain.
*
* The work left to caller to do the actual freeing of subtrees:
* a) free the subtree starting from *@top
* b) free the subtrees whose roots are stored in
* (@chain[i].p+1 .. end of @chain[i].bh->b_data)
* c) free the subtrees growing from the inode past the @chain[0].
* (no partially truncated stuff there). */
static Indirect *ext3_find_shared(struct inode *inode, int depth,
int offsets[4], Indirect chain[4], __le32 *top)
{
Indirect *partial, *p;
int k, err;
*top = 0;
/* Make k index the deepest non-null offset + 1 */
for (k = depth; k > 1 && !offsets[k-1]; k--)
;
partial = ext3_get_branch(inode, k, offsets, chain, &err);
/* Writer: pointers */
if (!partial)
partial = chain + k-1;
/*
* If the branch acquired continuation since we've looked at it -
* fine, it should all survive and (new) top doesn't belong to us.
*/
if (!partial->key && *partial->p)
/* Writer: end */
goto no_top;
for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
;
/*
* OK, we've found the last block that must survive. The rest of our
* branch should be detached before unlocking. However, if that rest
* of branch is all ours and does not grow immediately from the inode
* it's easier to cheat and just decrement partial->p.
*/
if (p == chain + k - 1 && p > chain) {
p->p--;
} else {
*top = *p->p;
/* Nope, don't do this in ext3. Must leave the tree intact */
#if 0
*p->p = 0;
#endif
}
/* Writer: end */
while(partial > p) {
brelse(partial->bh);
partial--;
}
no_top:
return partial;
}
/*
* Zero a number of block pointers in either an inode or an indirect block.
* If we restart the transaction we must again get write access to the
* indirect block for further modification.
*
* We release `count' blocks on disk, but (last - first) may be greater
* than `count' because there can be holes in there.
*/
static void ext3_clear_blocks(handle_t *handle, struct inode *inode,
struct buffer_head *bh, ext3_fsblk_t block_to_free,
unsigned long count, __le32 *first, __le32 *last)
{
__le32 *p;
if (try_to_extend_transaction(handle, inode)) {
if (bh) {
BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
if (ext3_journal_dirty_metadata(handle, bh))
return;
}
ext3_mark_inode_dirty(handle, inode);
truncate_restart_transaction(handle, inode);
if (bh) {
BUFFER_TRACE(bh, "retaking write access");
if (ext3_journal_get_write_access(handle, bh))
return;
}
}
/*
* Any buffers which are on the journal will be in memory. We find
* them on the hash table so journal_revoke() will run journal_forget()
* on them. We've already detached each block from the file, so
* bforget() in journal_forget() should be safe.
*
* AKPM: turn on bforget in journal_forget()!!!
*/
for (p = first; p < last; p++) {
u32 nr = le32_to_cpu(*p);
if (nr) {
struct buffer_head *bh;
*p = 0;
bh = sb_find_get_block(inode->i_sb, nr);
ext3_forget(handle, 0, inode, bh, nr);
}
}
ext3_free_blocks(handle, inode, block_to_free, count);
}
/**
* ext3_free_data - free a list of data blocks
* @handle: handle for this transaction
* @inode: inode we are dealing with
* @this_bh: indirect buffer_head which contains *@first and *@last
* @first: array of block numbers
* @last: points immediately past the end of array
*
* We are freeing all blocks referred from that array (numbers are stored as
* little-endian 32-bit) and updating @inode->i_blocks appropriately.
*
* We accumulate contiguous runs of blocks to free. Conveniently, if these
* blocks are contiguous then releasing them at one time will only affect one
* or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
* actually use a lot of journal space.
*
* @this_bh will be %NULL if @first and @last point into the inode's direct
* block pointers.
*/
static void ext3_free_data(handle_t *handle, struct inode *inode,
struct buffer_head *this_bh,
__le32 *first, __le32 *last)
{
ext3_fsblk_t block_to_free = 0; /* Starting block # of a run */
unsigned long count = 0; /* Number of blocks in the run */
__le32 *block_to_free_p = NULL; /* Pointer into inode/ind
corresponding to
block_to_free */
ext3_fsblk_t nr; /* Current block # */
__le32 *p; /* Pointer into inode/ind
for current block */
int err;
if (this_bh) { /* For indirect block */
BUFFER_TRACE(this_bh, "get_write_access");
err = ext3_journal_get_write_access(handle, this_bh);
/* Important: if we can't update the indirect pointers
* to the blocks, we can't free them. */
if (err)
return;
}
for (p = first; p < last; p++) {
nr = le32_to_cpu(*p);
if (nr) {
/* accumulate blocks to free if they're contiguous */
if (count == 0) {
block_to_free = nr;
block_to_free_p = p;
count = 1;
} else if (nr == block_to_free + count) {
count++;
} else {
ext3_clear_blocks(handle, inode, this_bh,
block_to_free,
count, block_to_free_p, p);
block_to_free = nr;
block_to_free_p = p;
count = 1;
}
}
}
if (count > 0)
ext3_clear_blocks(handle, inode, this_bh, block_to_free,
count, block_to_free_p, p);
if (this_bh) {
BUFFER_TRACE(this_bh, "call ext3_journal_dirty_metadata");
/*
* The buffer head should have an attached journal head at this
* point. However, if the data is corrupted and an indirect
* block pointed to itself, it would have been detached when
* the block was cleared. Check for this instead of OOPSing.
*/
if (bh2jh(this_bh))
ext3_journal_dirty_metadata(handle, this_bh);
else
ext3_error(inode->i_sb, "ext3_free_data",
"circular indirect block detected, "
"inode=%lu, block=%llu",
inode->i_ino,
(unsigned long long)this_bh->b_blocknr);
}
}
/**
* ext3_free_branches - free an array of branches
* @handle: JBD handle for this transaction
* @inode: inode we are dealing with
* @parent_bh: the buffer_head which contains *@first and *@last
* @first: array of block numbers
* @last: pointer immediately past the end of array
* @depth: depth of the branches to free
*
* We are freeing all blocks referred from these branches (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static void ext3_free_branches(handle_t *handle, struct inode *inode,
struct buffer_head *parent_bh,
__le32 *first, __le32 *last, int depth)
{
ext3_fsblk_t nr;
__le32 *p;
if (is_handle_aborted(handle))
return;
if (depth--) {
struct buffer_head *bh;
int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
p = last;
while (--p >= first) {
nr = le32_to_cpu(*p);
if (!nr)
continue; /* A hole */
/* Go read the buffer for the next level down */
bh = sb_bread(inode->i_sb, nr);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (!bh) {
ext3_error(inode->i_sb, "ext3_free_branches",
"Read failure, inode=%lu, block="E3FSBLK,
inode->i_ino, nr);
continue;
}
/* This zaps the entire block. Bottom up. */
BUFFER_TRACE(bh, "free child branches");
ext3_free_branches(handle, inode, bh,
(__le32*)bh->b_data,
(__le32*)bh->b_data + addr_per_block,
depth);
/*
* Everything below this this pointer has been
* released. Now let this top-of-subtree go.
*
* We want the freeing of this indirect block to be
* atomic in the journal with the updating of the
* bitmap block which owns it. So make some room in
* the journal.
*
* We zero the parent pointer *after* freeing its
* pointee in the bitmaps, so if extend_transaction()
* for some reason fails to put the bitmap changes and
* the release into the same transaction, recovery
* will merely complain about releasing a free block,
* rather than leaking blocks.
*/
if (is_handle_aborted(handle))
return;
if (try_to_extend_transaction(handle, inode)) {
ext3_mark_inode_dirty(handle, inode);
truncate_restart_transaction(handle, inode);
}
/*
* We've probably journalled the indirect block several
* times during the truncate. But it's no longer
* needed and we now drop it from the transaction via
* journal_revoke().
*
* That's easy if it's exclusively part of this
* transaction. But if it's part of the committing
* transaction then journal_forget() will simply
* brelse() it. That means that if the underlying
* block is reallocated in ext3_get_block(),
* unmap_underlying_metadata() will find this block
* and will try to get rid of it. damn, damn. Thus
* we don't allow a block to be reallocated until
* a transaction freeing it has fully committed.
*
* We also have to make sure journal replay after a
* crash does not overwrite non-journaled data blocks
* with old metadata when the block got reallocated for
* data. Thus we have to store a revoke record for a
* block in the same transaction in which we free the
* block.
*/
ext3_forget(handle, 1, inode, bh, bh->b_blocknr);
ext3_free_blocks(handle, inode, nr, 1);
if (parent_bh) {
/*
* The block which we have just freed is
* pointed to by an indirect block: journal it
*/
BUFFER_TRACE(parent_bh, "get_write_access");
if (!ext3_journal_get_write_access(handle,
parent_bh)){
*p = 0;
BUFFER_TRACE(parent_bh,
"call ext3_journal_dirty_metadata");
ext3_journal_dirty_metadata(handle,
parent_bh);
}
}
}
} else {
/* We have reached the bottom of the tree. */
BUFFER_TRACE(parent_bh, "free data blocks");
ext3_free_data(handle, inode, parent_bh, first, last);
}
}
int ext3_can_truncate(struct inode *inode)
{
if (S_ISREG(inode->i_mode))
return 1;
if (S_ISDIR(inode->i_mode))
return 1;
if (S_ISLNK(inode->i_mode))
return !ext3_inode_is_fast_symlink(inode);
return 0;
}
/*
* ext3_truncate()
*
* We block out ext3_get_block() block instantiations across the entire
* transaction, and VFS/VM ensures that ext3_truncate() cannot run
* simultaneously on behalf of the same inode.
*
* As we work through the truncate and commmit bits of it to the journal there
* is one core, guiding principle: the file's tree must always be consistent on
* disk. We must be able to restart the truncate after a crash.
*
* The file's tree may be transiently inconsistent in memory (although it
* probably isn't), but whenever we close off and commit a journal transaction,
* the contents of (the filesystem + the journal) must be consistent and
* restartable. It's pretty simple, really: bottom up, right to left (although
* left-to-right works OK too).
*
* Note that at recovery time, journal replay occurs *before* the restart of
* truncate against the orphan inode list.
*
* The committed inode has the new, desired i_size (which is the same as
* i_disksize in this case). After a crash, ext3_orphan_cleanup() will see
* that this inode's truncate did not complete and it will again call
* ext3_truncate() to have another go. So there will be instantiated blocks
* to the right of the truncation point in a crashed ext3 filesystem. But
* that's fine - as long as they are linked from the inode, the post-crash
* ext3_truncate() run will find them and release them.
*/
void ext3_truncate(struct inode *inode)
{
handle_t *handle;
struct ext3_inode_info *ei = EXT3_I(inode);
__le32 *i_data = ei->i_data;
int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
int offsets[4];
Indirect chain[4];
Indirect *partial;
__le32 nr = 0;
int n;
long last_block;
unsigned blocksize = inode->i_sb->s_blocksize;
trace_ext3_truncate_enter(inode);
if (!ext3_can_truncate(inode))
goto out_notrans;
if (inode->i_size == 0 && ext3_should_writeback_data(inode))
ext3_set_inode_state(inode, EXT3_STATE_FLUSH_ON_CLOSE);
handle = start_transaction(inode);
if (IS_ERR(handle))
goto out_notrans;
last_block = (inode->i_size + blocksize-1)
>> EXT3_BLOCK_SIZE_BITS(inode->i_sb);
n = ext3_block_to_path(inode, last_block, offsets, NULL);
if (n == 0)
goto out_stop; /* error */
/*
* OK. This truncate is going to happen. We add the inode to the
* orphan list, so that if this truncate spans multiple transactions,
* and we crash, we will resume the truncate when the filesystem
* recovers. It also marks the inode dirty, to catch the new size.
*
* Implication: the file must always be in a sane, consistent
* truncatable state while each transaction commits.
*/
if (ext3_orphan_add(handle, inode))
goto out_stop;
/*
* The orphan list entry will now protect us from any crash which
* occurs before the truncate completes, so it is now safe to propagate
* the new, shorter inode size (held for now in i_size) into the
* on-disk inode. We do this via i_disksize, which is the value which
* ext3 *really* writes onto the disk inode.
*/
ei->i_disksize = inode->i_size;
/*
* From here we block out all ext3_get_block() callers who want to
* modify the block allocation tree.
*/
mutex_lock(&ei->truncate_mutex);
if (n == 1) { /* direct blocks */
ext3_free_data(handle, inode, NULL, i_data+offsets[0],
i_data + EXT3_NDIR_BLOCKS);
goto do_indirects;
}
partial = ext3_find_shared(inode, n, offsets, chain, &nr);
/* Kill the top of shared branch (not detached) */
if (nr) {
if (partial == chain) {
/* Shared branch grows from the inode */
ext3_free_branches(handle, inode, NULL,
&nr, &nr+1, (chain+n-1) - partial);
*partial->p = 0;
/*
* We mark the inode dirty prior to restart,
* and prior to stop. No need for it here.
*/
} else {
/* Shared branch grows from an indirect block */
ext3_free_branches(handle, inode, partial->bh,
partial->p,
partial->p+1, (chain+n-1) - partial);
}
}
/* Clear the ends of indirect blocks on the shared branch */
while (partial > chain) {
ext3_free_branches(handle, inode, partial->bh, partial->p + 1,
(__le32*)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
BUFFER_TRACE(partial->bh, "call brelse");
brelse (partial->bh);
partial--;
}
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
nr = i_data[EXT3_IND_BLOCK];
if (nr) {
ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
i_data[EXT3_IND_BLOCK] = 0;
}
case EXT3_IND_BLOCK:
nr = i_data[EXT3_DIND_BLOCK];
if (nr) {
ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
i_data[EXT3_DIND_BLOCK] = 0;
}
case EXT3_DIND_BLOCK:
nr = i_data[EXT3_TIND_BLOCK];
if (nr) {
ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
i_data[EXT3_TIND_BLOCK] = 0;
}
case EXT3_TIND_BLOCK:
;
}
ext3_discard_reservation(inode);
mutex_unlock(&ei->truncate_mutex);
inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
ext3_mark_inode_dirty(handle, inode);
/*
* In a multi-transaction truncate, we only make the final transaction
* synchronous
*/
if (IS_SYNC(inode))
handle->h_sync = 1;
out_stop:
/*
* If this was a simple ftruncate(), and the file will remain alive
* then we need to clear up the orphan record which we created above.
* However, if this was a real unlink then we were called by
* ext3_evict_inode(), and we allow that function to clean up the
* orphan info for us.
*/
if (inode->i_nlink)
ext3_orphan_del(handle, inode);
ext3_journal_stop(handle);
trace_ext3_truncate_exit(inode);
return;
out_notrans:
/*
* Delete the inode from orphan list so that it doesn't stay there
* forever and trigger assertion on umount.
*/
if (inode->i_nlink)
ext3_orphan_del(NULL, inode);
trace_ext3_truncate_exit(inode);
}
static ext3_fsblk_t ext3_get_inode_block(struct super_block *sb,
unsigned long ino, struct ext3_iloc *iloc)
{
unsigned long block_group;
unsigned long offset;
ext3_fsblk_t block;
struct ext3_group_desc *gdp;
if (!ext3_valid_inum(sb, ino)) {
/*
* This error is already checked for in namei.c unless we are
* looking at an NFS filehandle, in which case no error
* report is needed
*/
return 0;
}
block_group = (ino - 1) / EXT3_INODES_PER_GROUP(sb);
gdp = ext3_get_group_desc(sb, block_group, NULL);
if (!gdp)
return 0;
/*
* Figure out the offset within the block group inode table
*/
offset = ((ino - 1) % EXT3_INODES_PER_GROUP(sb)) *
EXT3_INODE_SIZE(sb);
block = le32_to_cpu(gdp->bg_inode_table) +
(offset >> EXT3_BLOCK_SIZE_BITS(sb));
iloc->block_group = block_group;
iloc->offset = offset & (EXT3_BLOCK_SIZE(sb) - 1);
return block;
}
/*
* ext3_get_inode_loc returns with an extra refcount against the inode's
* underlying buffer_head on success. If 'in_mem' is true, we have all
* data in memory that is needed to recreate the on-disk version of this
* inode.
*/
static int __ext3_get_inode_loc(struct inode *inode,
struct ext3_iloc *iloc, int in_mem)
{
ext3_fsblk_t block;
struct buffer_head *bh;
block = ext3_get_inode_block(inode->i_sb, inode->i_ino, iloc);
if (!block)
return -EIO;
bh = sb_getblk(inode->i_sb, block);
if (!bh) {
ext3_error (inode->i_sb, "ext3_get_inode_loc",
"unable to read inode block - "
"inode=%lu, block="E3FSBLK,
inode->i_ino, block);
return -EIO;
}
if (!buffer_uptodate(bh)) {
lock_buffer(bh);
/*
* If the buffer has the write error flag, we have failed
* to write out another inode in the same block. In this
* case, we don't have to read the block because we may
* read the old inode data successfully.
*/
if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
set_buffer_uptodate(bh);
if (buffer_uptodate(bh)) {
/* someone brought it uptodate while we waited */
unlock_buffer(bh);
goto has_buffer;
}
/*
* If we have all information of the inode in memory and this
* is the only valid inode in the block, we need not read the
* block.
*/
if (in_mem) {
struct buffer_head *bitmap_bh;
struct ext3_group_desc *desc;
int inodes_per_buffer;
int inode_offset, i;
int block_group;
int start;
block_group = (inode->i_ino - 1) /
EXT3_INODES_PER_GROUP(inode->i_sb);
inodes_per_buffer = bh->b_size /
EXT3_INODE_SIZE(inode->i_sb);
inode_offset = ((inode->i_ino - 1) %
EXT3_INODES_PER_GROUP(inode->i_sb));
start = inode_offset & ~(inodes_per_buffer - 1);
/* Is the inode bitmap in cache? */
desc = ext3_get_group_desc(inode->i_sb,
block_group, NULL);
if (!desc)
goto make_io;
bitmap_bh = sb_getblk(inode->i_sb,
le32_to_cpu(desc->bg_inode_bitmap));
if (!bitmap_bh)
goto make_io;
/*
* If the inode bitmap isn't in cache then the
* optimisation may end up performing two reads instead
* of one, so skip it.
*/
if (!buffer_uptodate(bitmap_bh)) {
brelse(bitmap_bh);
goto make_io;
}
for (i = start; i < start + inodes_per_buffer; i++) {
if (i == inode_offset)
continue;
if (ext3_test_bit(i, bitmap_bh->b_data))
break;
}
brelse(bitmap_bh);
if (i == start + inodes_per_buffer) {
/* all other inodes are free, so skip I/O */
memset(bh->b_data, 0, bh->b_size);
set_buffer_uptodate(bh);
unlock_buffer(bh);
goto has_buffer;
}
}
make_io:
/*
* There are other valid inodes in the buffer, this inode
* has in-inode xattrs, or we don't have this inode in memory.
* Read the block from disk.
*/
trace_ext3_load_inode(inode);
get_bh(bh);
bh->b_end_io = end_buffer_read_sync;
submit_bh(READ | REQ_META | REQ_PRIO, bh);
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
ext3_error(inode->i_sb, "ext3_get_inode_loc",
"unable to read inode block - "
"inode=%lu, block="E3FSBLK,
inode->i_ino, block);
brelse(bh);
return -EIO;
}
}
has_buffer:
iloc->bh = bh;
return 0;
}
int ext3_get_inode_loc(struct inode *inode, struct ext3_iloc *iloc)
{
/* We have all inode data except xattrs in memory here. */
return __ext3_get_inode_loc(inode, iloc,
!ext3_test_inode_state(inode, EXT3_STATE_XATTR));
}
void ext3_set_inode_flags(struct inode *inode)
{
unsigned int flags = EXT3_I(inode)->i_flags;
inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
if (flags & EXT3_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & EXT3_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & EXT3_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & EXT3_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & EXT3_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
}
/* Propagate flags from i_flags to EXT3_I(inode)->i_flags */
void ext3_get_inode_flags(struct ext3_inode_info *ei)
{
unsigned int flags = ei->vfs_inode.i_flags;
ei->i_flags &= ~(EXT3_SYNC_FL|EXT3_APPEND_FL|
EXT3_IMMUTABLE_FL|EXT3_NOATIME_FL|EXT3_DIRSYNC_FL);
if (flags & S_SYNC)
ei->i_flags |= EXT3_SYNC_FL;
if (flags & S_APPEND)
ei->i_flags |= EXT3_APPEND_FL;
if (flags & S_IMMUTABLE)
ei->i_flags |= EXT3_IMMUTABLE_FL;
if (flags & S_NOATIME)
ei->i_flags |= EXT3_NOATIME_FL;
if (flags & S_DIRSYNC)
ei->i_flags |= EXT3_DIRSYNC_FL;
}
struct inode *ext3_iget(struct super_block *sb, unsigned long ino)
{
struct ext3_iloc iloc;
struct ext3_inode *raw_inode;
struct ext3_inode_info *ei;
struct buffer_head *bh;
struct inode *inode;
journal_t *journal = EXT3_SB(sb)->s_journal;
transaction_t *transaction;
long ret;
int block;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
ei = EXT3_I(inode);
ei->i_block_alloc_info = NULL;
ret = __ext3_get_inode_loc(inode, &iloc, 0);
if (ret < 0)
goto bad_inode;
bh = iloc.bh;
raw_inode = ext3_raw_inode(&iloc);
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if(!(test_opt (inode->i_sb, NO_UID32))) {
inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
inode->i_size = le32_to_cpu(raw_inode->i_size);
inode->i_atime.tv_sec = (signed)le32_to_cpu(raw_inode->i_atime);
inode->i_ctime.tv_sec = (signed)le32_to_cpu(raw_inode->i_ctime);
inode->i_mtime.tv_sec = (signed)le32_to_cpu(raw_inode->i_mtime);
inode->i_atime.tv_nsec = inode->i_ctime.tv_nsec = inode->i_mtime.tv_nsec = 0;
ei->i_state_flags = 0;
ei->i_dir_start_lookup = 0;
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0) {
if (inode->i_mode == 0 ||
!(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ORPHAN_FS)) {
/* this inode is deleted */
brelse (bh);
ret = -ESTALE;
goto bad_inode;
}
/* The only unlinked inodes we let through here have
* valid i_mode and are being read by the orphan
* recovery code: that's fine, we're about to complete
* the process of deleting those. */
}
inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
#ifdef EXT3_FRAGMENTS
ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
ei->i_frag_no = raw_inode->i_frag;
ei->i_frag_size = raw_inode->i_fsize;
#endif
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
if (!S_ISREG(inode->i_mode)) {
ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
} else {
inode->i_size |=
((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
}
ei->i_disksize = inode->i_size;
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_block_group = iloc.block_group;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (block = 0; block < EXT3_N_BLOCKS; block++)
ei->i_data[block] = raw_inode->i_block[block];
INIT_LIST_HEAD(&ei->i_orphan);
/*
* Set transaction id's of transactions that have to be committed
* to finish f[data]sync. We set them to currently running transaction
* as we cannot be sure that the inode or some of its metadata isn't
* part of the transaction - the inode could have been reclaimed and
* now it is reread from disk.
*/
if (journal) {
tid_t tid;
spin_lock(&journal->j_state_lock);
if (journal->j_running_transaction)
transaction = journal->j_running_transaction;
else
transaction = journal->j_committing_transaction;
if (transaction)
tid = transaction->t_tid;
else
tid = journal->j_commit_sequence;
spin_unlock(&journal->j_state_lock);
atomic_set(&ei->i_sync_tid, tid);
atomic_set(&ei->i_datasync_tid, tid);
}
if (inode->i_ino >= EXT3_FIRST_INO(inode->i_sb) + 1 &&
EXT3_INODE_SIZE(inode->i_sb) > EXT3_GOOD_OLD_INODE_SIZE) {
/*
* When mke2fs creates big inodes it does not zero out
* the unused bytes above EXT3_GOOD_OLD_INODE_SIZE,
* so ignore those first few inodes.
*/
ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
if (EXT3_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
EXT3_INODE_SIZE(inode->i_sb)) {
brelse (bh);
ret = -EIO;
goto bad_inode;
}
if (ei->i_extra_isize == 0) {
/* The extra space is currently unused. Use it. */
ei->i_extra_isize = sizeof(struct ext3_inode) -
EXT3_GOOD_OLD_INODE_SIZE;
} else {
__le32 *magic = (void *)raw_inode +
EXT3_GOOD_OLD_INODE_SIZE +
ei->i_extra_isize;
if (*magic == cpu_to_le32(EXT3_XATTR_MAGIC))
ext3_set_inode_state(inode, EXT3_STATE_XATTR);
}
} else
ei->i_extra_isize = 0;
if (S_ISREG(inode->i_mode)) {
inode->i_op = &ext3_file_inode_operations;
inode->i_fop = &ext3_file_operations;
ext3_set_aops(inode);
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext3_dir_inode_operations;
inode->i_fop = &ext3_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
if (ext3_inode_is_fast_symlink(inode)) {
inode->i_op = &ext3_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext3_symlink_inode_operations;
ext3_set_aops(inode);
}
} else {
inode->i_op = &ext3_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
}
brelse (iloc.bh);
ext3_set_inode_flags(inode);
unlock_new_inode(inode);
return inode;
bad_inode:
iget_failed(inode);
return ERR_PTR(ret);
}
/*
* Post the struct inode info into an on-disk inode location in the
* buffer-cache. This gobbles the caller's reference to the
* buffer_head in the inode location struct.
*
* The caller must have write access to iloc->bh.
*/
static int ext3_do_update_inode(handle_t *handle,
struct inode *inode,
struct ext3_iloc *iloc)
{
struct ext3_inode *raw_inode = ext3_raw_inode(iloc);
struct ext3_inode_info *ei = EXT3_I(inode);
struct buffer_head *bh = iloc->bh;
int err = 0, rc, block;
again:
/* we can't allow multiple procs in here at once, its a bit racey */
lock_buffer(bh);
/* For fields not not tracking in the in-memory inode,
* initialise them to zero for new inodes. */
if (ext3_test_inode_state(inode, EXT3_STATE_NEW))
memset(raw_inode, 0, EXT3_SB(inode->i_sb)->s_inode_size);
ext3_get_inode_flags(ei);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
if(!(test_opt(inode->i_sb, NO_UID32))) {
raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
/*
* Fix up interoperability with old kernels. Otherwise, old inodes get
* re-used with the upper 16 bits of the uid/gid intact
*/
if(!ei->i_dtime) {
raw_inode->i_uid_high =
cpu_to_le16(high_16_bits(inode->i_uid));
raw_inode->i_gid_high =
cpu_to_le16(high_16_bits(inode->i_gid));
} else {
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
} else {
raw_inode->i_uid_low =
cpu_to_le16(fs_high2lowuid(inode->i_uid));
raw_inode->i_gid_low =
cpu_to_le16(fs_high2lowgid(inode->i_gid));
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
raw_inode->i_size = cpu_to_le32(ei->i_disksize);
raw_inode->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
raw_inode->i_ctime = cpu_to_le32(inode->i_ctime.tv_sec);
raw_inode->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
raw_inode->i_flags = cpu_to_le32(ei->i_flags);
#ifdef EXT3_FRAGMENTS
raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
raw_inode->i_frag = ei->i_frag_no;
raw_inode->i_fsize = ei->i_frag_size;
#endif
raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
if (!S_ISREG(inode->i_mode)) {
raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
} else {
raw_inode->i_size_high =
cpu_to_le32(ei->i_disksize >> 32);
if (ei->i_disksize > 0x7fffffffULL) {
struct super_block *sb = inode->i_sb;
if (!EXT3_HAS_RO_COMPAT_FEATURE(sb,
EXT3_FEATURE_RO_COMPAT_LARGE_FILE) ||
EXT3_SB(sb)->s_es->s_rev_level ==
cpu_to_le32(EXT3_GOOD_OLD_REV)) {
/* If this is the first large file
* created, add a flag to the superblock.
*/
unlock_buffer(bh);
err = ext3_journal_get_write_access(handle,
EXT3_SB(sb)->s_sbh);
if (err)
goto out_brelse;
ext3_update_dynamic_rev(sb);
EXT3_SET_RO_COMPAT_FEATURE(sb,
EXT3_FEATURE_RO_COMPAT_LARGE_FILE);
handle->h_sync = 1;
err = ext3_journal_dirty_metadata(handle,
EXT3_SB(sb)->s_sbh);
/* get our lock and start over */
goto again;
}
}
}
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
raw_inode->i_block[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
raw_inode->i_block[1] = 0;
} else {
raw_inode->i_block[0] = 0;
raw_inode->i_block[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
raw_inode->i_block[2] = 0;
}
} else for (block = 0; block < EXT3_N_BLOCKS; block++)
raw_inode->i_block[block] = ei->i_data[block];
if (ei->i_extra_isize)
raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
unlock_buffer(bh);
rc = ext3_journal_dirty_metadata(handle, bh);
if (!err)
err = rc;
ext3_clear_inode_state(inode, EXT3_STATE_NEW);
atomic_set(&ei->i_sync_tid, handle->h_transaction->t_tid);
out_brelse:
brelse (bh);
ext3_std_error(inode->i_sb, err);
return err;
}
/*
* ext3_write_inode()
*
* We are called from a few places:
*
* - Within generic_file_write() for O_SYNC files.
* Here, there will be no transaction running. We wait for any running
* trasnaction to commit.
*
* - Within sys_sync(), kupdate and such.
* We wait on commit, if tol to.
*
* - Within prune_icache() (PF_MEMALLOC == true)
* Here we simply return. We can't afford to block kswapd on the
* journal commit.
*
* In all cases it is actually safe for us to return without doing anything,
* because the inode has been copied into a raw inode buffer in
* ext3_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
* knfsd.
*
* Note that we are absolutely dependent upon all inode dirtiers doing the
* right thing: they *must* call mark_inode_dirty() after dirtying info in
* which we are interested.
*
* It would be a bug for them to not do this. The code:
*
* mark_inode_dirty(inode)
* stuff();
* inode->i_size = expr;
*
* is in error because a kswapd-driven write_inode() could occur while
* `stuff()' is running, and the new i_size will be lost. Plus the inode
* will no longer be on the superblock's dirty inode list.
*/
int ext3_write_inode(struct inode *inode, struct writeback_control *wbc)
{
if (current->flags & PF_MEMALLOC)
return 0;
if (ext3_journal_current_handle()) {
jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
dump_stack();
return -EIO;
}
if (wbc->sync_mode != WB_SYNC_ALL)
return 0;
return ext3_force_commit(inode->i_sb);
}
/*
* ext3_setattr()
*
* Called from notify_change.
*
* We want to trap VFS attempts to truncate the file as soon as
* possible. In particular, we want to make sure that when the VFS
* shrinks i_size, we put the inode on the orphan list and modify
* i_disksize immediately, so that during the subsequent flushing of
* dirty pages and freeing of disk blocks, we can guarantee that any
* commit will leave the blocks being flushed in an unused state on
* disk. (On recovery, the inode will get truncated and the blocks will
* be freed, so we have a strong guarantee that no future commit will
* leave these blocks visible to the user.)
*
* Called with inode->sem down.
*/
int ext3_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
int error, rc = 0;
const unsigned int ia_valid = attr->ia_valid;
error = inode_change_ok(inode, attr);
if (error)
return error;
if (is_quota_modification(inode, attr))
dquot_initialize(inode);
if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
(ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
handle_t *handle;
/* (user+group)*(old+new) structure, inode write (sb,
* inode block, ? - but truncate inode update has it) */
handle = ext3_journal_start(inode, EXT3_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
EXT3_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)+3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto err_out;
}
error = dquot_transfer(inode, attr);
if (error) {
ext3_journal_stop(handle);
return error;
}
/* Update corresponding info in inode so that everything is in
* one transaction */
if (attr->ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (attr->ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
error = ext3_mark_inode_dirty(handle, inode);
ext3_journal_stop(handle);
}
if (attr->ia_valid & ATTR_SIZE)
inode_dio_wait(inode);
if (S_ISREG(inode->i_mode) &&
attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
handle_t *handle;
handle = ext3_journal_start(inode, 3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto err_out;
}
error = ext3_orphan_add(handle, inode);
if (error) {
ext3_journal_stop(handle);
goto err_out;
}
EXT3_I(inode)->i_disksize = attr->ia_size;
error = ext3_mark_inode_dirty(handle, inode);
ext3_journal_stop(handle);
if (error) {
/* Some hard fs error must have happened. Bail out. */
ext3_orphan_del(NULL, inode);
goto err_out;
}
rc = ext3_block_truncate_page(inode, attr->ia_size);
if (rc) {
/* Cleanup orphan list and exit */
handle = ext3_journal_start(inode, 3);
if (IS_ERR(handle)) {
ext3_orphan_del(NULL, inode);
goto err_out;
}
ext3_orphan_del(handle, inode);
ext3_journal_stop(handle);
goto err_out;
}
}
if ((attr->ia_valid & ATTR_SIZE) &&
attr->ia_size != i_size_read(inode)) {
truncate_setsize(inode, attr->ia_size);
ext3_truncate(inode);
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
if (ia_valid & ATTR_MODE)
rc = ext3_acl_chmod(inode);
err_out:
ext3_std_error(inode->i_sb, error);
if (!error)
error = rc;
return error;
}
/*
* How many blocks doth make a writepage()?
*
* With N blocks per page, it may be:
* N data blocks
* 2 indirect block
* 2 dindirect
* 1 tindirect
* N+5 bitmap blocks (from the above)
* N+5 group descriptor summary blocks
* 1 inode block
* 1 superblock.
* 2 * EXT3_SINGLEDATA_TRANS_BLOCKS for the quote files
*
* 3 * (N + 5) + 2 + 2 * EXT3_SINGLEDATA_TRANS_BLOCKS
*
* With ordered or writeback data it's the same, less the N data blocks.
*
* If the inode's direct blocks can hold an integral number of pages then a
* page cannot straddle two indirect blocks, and we can only touch one indirect
* and dindirect block, and the "5" above becomes "3".
*
* This still overestimates under most circumstances. If we were to pass the
* start and end offsets in here as well we could do block_to_path() on each
* block and work out the exact number of indirects which are touched. Pah.
*/
static int ext3_writepage_trans_blocks(struct inode *inode)
{
int bpp = ext3_journal_blocks_per_page(inode);
int indirects = (EXT3_NDIR_BLOCKS % bpp) ? 5 : 3;
int ret;
if (ext3_should_journal_data(inode))
ret = 3 * (bpp + indirects) + 2;
else
ret = 2 * (bpp + indirects) + indirects + 2;
#ifdef CONFIG_QUOTA
/* We know that structure was already allocated during dquot_initialize so
* we will be updating only the data blocks + inodes */
ret += EXT3_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
#endif
return ret;
}
/*
* The caller must have previously called ext3_reserve_inode_write().
* Give this, we know that the caller already has write access to iloc->bh.
*/
int ext3_mark_iloc_dirty(handle_t *handle,
struct inode *inode, struct ext3_iloc *iloc)
{
int err = 0;
/* the do_update_inode consumes one bh->b_count */
get_bh(iloc->bh);
/* ext3_do_update_inode() does journal_dirty_metadata */
err = ext3_do_update_inode(handle, inode, iloc);
put_bh(iloc->bh);
return err;
}
/*
* On success, We end up with an outstanding reference count against
* iloc->bh. This _must_ be cleaned up later.
*/
int
ext3_reserve_inode_write(handle_t *handle, struct inode *inode,
struct ext3_iloc *iloc)
{
int err = 0;
if (handle) {
err = ext3_get_inode_loc(inode, iloc);
if (!err) {
BUFFER_TRACE(iloc->bh, "get_write_access");
err = ext3_journal_get_write_access(handle, iloc->bh);
if (err) {
brelse(iloc->bh);
iloc->bh = NULL;
}
}
}
ext3_std_error(inode->i_sb, err);
return err;
}
/*
* What we do here is to mark the in-core inode as clean with respect to inode
* dirtiness (it may still be data-dirty).
* This means that the in-core inode may be reaped by prune_icache
* without having to perform any I/O. This is a very good thing,
* because *any* task may call prune_icache - even ones which
* have a transaction open against a different journal.
*
* Is this cheating? Not really. Sure, we haven't written the
* inode out, but prune_icache isn't a user-visible syncing function.
* Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
* we start and wait on commits.
*
* Is this efficient/effective? Well, we're being nice to the system
* by cleaning up our inodes proactively so they can be reaped
* without I/O. But we are potentially leaving up to five seconds'
* worth of inodes floating about which prune_icache wants us to
* write out. One way to fix that would be to get prune_icache()
* to do a write_super() to free up some memory. It has the desired
* effect.
*/
int ext3_mark_inode_dirty(handle_t *handle, struct inode *inode)
{
struct ext3_iloc iloc;
int err;
might_sleep();
trace_ext3_mark_inode_dirty(inode, _RET_IP_);
err = ext3_reserve_inode_write(handle, inode, &iloc);
if (!err)
err = ext3_mark_iloc_dirty(handle, inode, &iloc);
return err;
}
/*
* ext3_dirty_inode() is called from __mark_inode_dirty()
*
* We're really interested in the case where a file is being extended.
* i_size has been changed by generic_commit_write() and we thus need
* to include the updated inode in the current transaction.
*
* Also, dquot_alloc_space() will always dirty the inode when blocks
* are allocated to the file.
*
* If the inode is marked synchronous, we don't honour that here - doing
* so would cause a commit on atime updates, which we don't bother doing.
* We handle synchronous inodes at the highest possible level.
*/
void ext3_dirty_inode(struct inode *inode, int flags)
{
handle_t *current_handle = ext3_journal_current_handle();
handle_t *handle;
handle = ext3_journal_start(inode, 2);
if (IS_ERR(handle))
goto out;
if (current_handle &&
current_handle->h_transaction != handle->h_transaction) {
/* This task has a transaction open against a different fs */
printk(KERN_EMERG "%s: transactions do not match!\n",
__func__);
} else {
jbd_debug(5, "marking dirty. outer handle=%p\n",
current_handle);
ext3_mark_inode_dirty(handle, inode);
}
ext3_journal_stop(handle);
out:
return;
}
#if 0
/*
* Bind an inode's backing buffer_head into this transaction, to prevent
* it from being flushed to disk early. Unlike
* ext3_reserve_inode_write, this leaves behind no bh reference and
* returns no iloc structure, so the caller needs to repeat the iloc
* lookup to mark the inode dirty later.
*/
static int ext3_pin_inode(handle_t *handle, struct inode *inode)
{
struct ext3_iloc iloc;
int err = 0;
if (handle) {
err = ext3_get_inode_loc(inode, &iloc);
if (!err) {
BUFFER_TRACE(iloc.bh, "get_write_access");
err = journal_get_write_access(handle, iloc.bh);
if (!err)
err = ext3_journal_dirty_metadata(handle,
iloc.bh);
brelse(iloc.bh);
}
}
ext3_std_error(inode->i_sb, err);
return err;
}
#endif
int ext3_change_inode_journal_flag(struct inode *inode, int val)
{
journal_t *journal;
handle_t *handle;
int err;
/*
* We have to be very careful here: changing a data block's
* journaling status dynamically is dangerous. If we write a
* data block to the journal, change the status and then delete
* that block, we risk forgetting to revoke the old log record
* from the journal and so a subsequent replay can corrupt data.
* So, first we make sure that the journal is empty and that
* nobody is changing anything.
*/
journal = EXT3_JOURNAL(inode);
if (is_journal_aborted(journal))
return -EROFS;
journal_lock_updates(journal);
journal_flush(journal);
/*
* OK, there are no updates running now, and all cached data is
* synced to disk. We are now in a completely consistent state
* which doesn't have anything in the journal, and we know that
* no filesystem updates are running, so it is safe to modify
* the inode's in-core data-journaling state flag now.
*/
if (val)
EXT3_I(inode)->i_flags |= EXT3_JOURNAL_DATA_FL;
else
EXT3_I(inode)->i_flags &= ~EXT3_JOURNAL_DATA_FL;
ext3_set_aops(inode);
journal_unlock_updates(journal);
/* Finally we can mark the inode as dirty. */
handle = ext3_journal_start(inode, 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
err = ext3_mark_inode_dirty(handle, inode);
handle->h_sync = 1;
ext3_journal_stop(handle);
ext3_std_error(inode->i_sb, err);
return err;
}
| gpl-2.0 |
jserve2014/OPENWRT_r48629 | target/linux/ar71xx/files/arch/mips/ath79/mach-onion-omega.c | 306 | 2045 | /*
* Onion Omega board support
*
* Copyright (C) 2015 Boken Lin <bl@onion.io>
*
* 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 <asm/mach-ath79/ath79.h>
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-usb.h"
#include "dev-wmac.h"
#include "machtypes.h"
#define OMEGA_GPIO_LED_SYSTEM 27
#define OMEGA_GPIO_BTN_RESET 11
#define OMEGA_GPIO_USB_POWER 8
#define OMEGA_KEYS_POLL_INTERVAL 20 /* msecs */
#define OMEGA_KEYS_DEBOUNCE_INTERVAL (3 * OMEGA_KEYS_POLL_INTERVAL)
static const char *omega_part_probes[] = {
"tp-link",
NULL,
};
static struct flash_platform_data omega_flash_data = {
.part_probes = omega_part_probes,
};
static struct gpio_led omega_leds_gpio[] __initdata = {
{
.name = "onion:amber:system",
.gpio = OMEGA_GPIO_LED_SYSTEM,
.active_low = 1,
},
};
static struct gpio_keys_button omega_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = OMEGA_KEYS_DEBOUNCE_INTERVAL,
.gpio = OMEGA_GPIO_BTN_RESET,
.active_low = 0,
}
};
static void __init onion_omega_setup(void)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00);
u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000);
ath79_register_m25p80(&omega_flash_data);
ath79_register_leds_gpio(-1, ARRAY_SIZE(omega_leds_gpio),
omega_leds_gpio);
ath79_register_gpio_keys_polled(-1, OMEGA_KEYS_POLL_INTERVAL,
ARRAY_SIZE(omega_gpio_keys),
omega_gpio_keys);
gpio_request_one(OMEGA_GPIO_USB_POWER,
GPIOF_OUT_INIT_HIGH | GPIOF_EXPORT_DIR_FIXED,
"USB power");
ath79_register_usb();
ath79_init_mac(ath79_eth0_data.mac_addr, mac, -1);
ath79_register_mdio(0, 0x0);
ath79_register_eth(0);
ath79_register_wmac(ee, mac);
}
MIPS_MACHINE(ATH79_MACH_ONION_OMEGA, "ONION-OMEGA", "Onion Omega", onion_omega_setup);
| gpl-2.0 |
janarthananfit/android_kernel_msm_beni | net/dccp/input.c | 562 | 22232 | /*
* net/dccp/input.c
*
* An implementation of the DCCP protocol
* Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* 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/dccp.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include "ackvec.h"
#include "ccid.h"
#include "dccp.h"
/* rate-limit for syncs in reply to sequence-invalid packets; RFC 4340, 7.5.4 */
int sysctl_dccp_sync_ratelimit __read_mostly = HZ / 8;
static void dccp_enqueue_skb(struct sock *sk, struct sk_buff *skb)
{
__skb_pull(skb, dccp_hdr(skb)->dccph_doff * 4);
__skb_queue_tail(&sk->sk_receive_queue, skb);
skb_set_owner_r(skb, sk);
sk->sk_data_ready(sk, 0);
}
static void dccp_fin(struct sock *sk, struct sk_buff *skb)
{
/*
* On receiving Close/CloseReq, both RD/WR shutdown are performed.
* RFC 4340, 8.3 says that we MAY send further Data/DataAcks after
* receiving the closing segment, but there is no guarantee that such
* data will be processed at all.
*/
sk->sk_shutdown = SHUTDOWN_MASK;
sock_set_flag(sk, SOCK_DONE);
dccp_enqueue_skb(sk, skb);
}
static int dccp_rcv_close(struct sock *sk, struct sk_buff *skb)
{
int queued = 0;
switch (sk->sk_state) {
/*
* We ignore Close when received in one of the following states:
* - CLOSED (may be a late or duplicate packet)
* - PASSIVE_CLOSEREQ (the peer has sent a CloseReq earlier)
* - RESPOND (already handled by dccp_check_req)
*/
case DCCP_CLOSING:
/*
* Simultaneous-close: receiving a Close after sending one. This
* can happen if both client and server perform active-close and
* will result in an endless ping-pong of crossing and retrans-
* mitted Close packets, which only terminates when one of the
* nodes times out (min. 64 seconds). Quicker convergence can be
* achieved when one of the nodes acts as tie-breaker.
* This is ok as both ends are done with data transfer and each
* end is just waiting for the other to acknowledge termination.
*/
if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT)
break;
/* fall through */
case DCCP_REQUESTING:
case DCCP_ACTIVE_CLOSEREQ:
dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED);
dccp_done(sk);
break;
case DCCP_OPEN:
case DCCP_PARTOPEN:
/* Give waiting application a chance to read pending data */
queued = 1;
dccp_fin(sk, skb);
dccp_set_state(sk, DCCP_PASSIVE_CLOSE);
/* fall through */
case DCCP_PASSIVE_CLOSE:
/*
* Retransmitted Close: we have already enqueued the first one.
*/
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
}
return queued;
}
static int dccp_rcv_closereq(struct sock *sk, struct sk_buff *skb)
{
int queued = 0;
/*
* Step 7: Check for unexpected packet types
* If (S.is_server and P.type == CloseReq)
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) {
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC);
return queued;
}
/* Step 13: process relevant Client states < CLOSEREQ */
switch (sk->sk_state) {
case DCCP_REQUESTING:
dccp_send_close(sk, 0);
dccp_set_state(sk, DCCP_CLOSING);
break;
case DCCP_OPEN:
case DCCP_PARTOPEN:
/* Give waiting application a chance to read pending data */
queued = 1;
dccp_fin(sk, skb);
dccp_set_state(sk, DCCP_PASSIVE_CLOSEREQ);
/* fall through */
case DCCP_PASSIVE_CLOSEREQ:
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
}
return queued;
}
static u16 dccp_reset_code_convert(const u8 code)
{
const u16 error_code[] = {
[DCCP_RESET_CODE_CLOSED] = 0, /* normal termination */
[DCCP_RESET_CODE_UNSPECIFIED] = 0, /* nothing known */
[DCCP_RESET_CODE_ABORTED] = ECONNRESET,
[DCCP_RESET_CODE_NO_CONNECTION] = ECONNREFUSED,
[DCCP_RESET_CODE_CONNECTION_REFUSED] = ECONNREFUSED,
[DCCP_RESET_CODE_TOO_BUSY] = EUSERS,
[DCCP_RESET_CODE_AGGRESSION_PENALTY] = EDQUOT,
[DCCP_RESET_CODE_PACKET_ERROR] = ENOMSG,
[DCCP_RESET_CODE_BAD_INIT_COOKIE] = EBADR,
[DCCP_RESET_CODE_BAD_SERVICE_CODE] = EBADRQC,
[DCCP_RESET_CODE_OPTION_ERROR] = EILSEQ,
[DCCP_RESET_CODE_MANDATORY_ERROR] = EOPNOTSUPP,
};
return code >= DCCP_MAX_RESET_CODES ? 0 : error_code[code];
}
static void dccp_rcv_reset(struct sock *sk, struct sk_buff *skb)
{
u16 err = dccp_reset_code_convert(dccp_hdr_reset(skb)->dccph_reset_code);
sk->sk_err = err;
/* Queue the equivalent of TCP fin so that dccp_recvmsg exits the loop */
dccp_fin(sk, skb);
if (err && !sock_flag(sk, SOCK_DEAD))
sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
dccp_time_wait(sk, DCCP_TIME_WAIT, 0);
}
static void dccp_event_ack_recv(struct sock *sk, struct sk_buff *skb)
{
struct dccp_sock *dp = dccp_sk(sk);
if (dp->dccps_hc_rx_ackvec != NULL)
dccp_ackvec_check_rcv_ackno(dp->dccps_hc_rx_ackvec, sk,
DCCP_SKB_CB(skb)->dccpd_ack_seq);
}
static void dccp_deliver_input_to_ccids(struct sock *sk, struct sk_buff *skb)
{
const struct dccp_sock *dp = dccp_sk(sk);
/* Don't deliver to RX CCID when node has shut down read end. */
if (!(sk->sk_shutdown & RCV_SHUTDOWN))
ccid_hc_rx_packet_recv(dp->dccps_hc_rx_ccid, sk, skb);
/*
* Until the TX queue has been drained, we can not honour SHUT_WR, since
* we need received feedback as input to adjust congestion control.
*/
if (sk->sk_write_queue.qlen > 0 || !(sk->sk_shutdown & SEND_SHUTDOWN))
ccid_hc_tx_packet_recv(dp->dccps_hc_tx_ccid, sk, skb);
}
static int dccp_check_seqno(struct sock *sk, struct sk_buff *skb)
{
const struct dccp_hdr *dh = dccp_hdr(skb);
struct dccp_sock *dp = dccp_sk(sk);
u64 lswl, lawl, seqno = DCCP_SKB_CB(skb)->dccpd_seq,
ackno = DCCP_SKB_CB(skb)->dccpd_ack_seq;
/*
* Step 5: Prepare sequence numbers for Sync
* If P.type == Sync or P.type == SyncAck,
* If S.AWL <= P.ackno <= S.AWH and P.seqno >= S.SWL,
* / * P is valid, so update sequence number variables
* accordingly. After this update, P will pass the tests
* in Step 6. A SyncAck is generated if necessary in
* Step 15 * /
* Update S.GSR, S.SWL, S.SWH
* Otherwise,
* Drop packet and return
*/
if (dh->dccph_type == DCCP_PKT_SYNC ||
dh->dccph_type == DCCP_PKT_SYNCACK) {
if (between48(ackno, dp->dccps_awl, dp->dccps_awh) &&
dccp_delta_seqno(dp->dccps_swl, seqno) >= 0)
dccp_update_gsr(sk, seqno);
else
return -1;
}
/*
* Step 6: Check sequence numbers
* Let LSWL = S.SWL and LAWL = S.AWL
* If P.type == CloseReq or P.type == Close or P.type == Reset,
* LSWL := S.GSR + 1, LAWL := S.GAR
* If LSWL <= P.seqno <= S.SWH
* and (P.ackno does not exist or LAWL <= P.ackno <= S.AWH),
* Update S.GSR, S.SWL, S.SWH
* If P.type != Sync,
* Update S.GAR
*/
lswl = dp->dccps_swl;
lawl = dp->dccps_awl;
if (dh->dccph_type == DCCP_PKT_CLOSEREQ ||
dh->dccph_type == DCCP_PKT_CLOSE ||
dh->dccph_type == DCCP_PKT_RESET) {
lswl = ADD48(dp->dccps_gsr, 1);
lawl = dp->dccps_gar;
}
if (between48(seqno, lswl, dp->dccps_swh) &&
(ackno == DCCP_PKT_WITHOUT_ACK_SEQ ||
between48(ackno, lawl, dp->dccps_awh))) {
dccp_update_gsr(sk, seqno);
if (dh->dccph_type != DCCP_PKT_SYNC &&
(ackno != DCCP_PKT_WITHOUT_ACK_SEQ))
dp->dccps_gar = ackno;
} else {
unsigned long now = jiffies;
/*
* Step 6: Check sequence numbers
* Otherwise,
* If P.type == Reset,
* Send Sync packet acknowledging S.GSR
* Otherwise,
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*
* These Syncs are rate-limited as per RFC 4340, 7.5.4:
* at most 1 / (dccp_sync_rate_limit * HZ) Syncs per second.
*/
if (time_before(now, (dp->dccps_rate_last +
sysctl_dccp_sync_ratelimit)))
return 0;
DCCP_WARN("DCCP: Step 6 failed for %s packet, "
"(LSWL(%llu) <= P.seqno(%llu) <= S.SWH(%llu)) and "
"(P.ackno %s or LAWL(%llu) <= P.ackno(%llu) <= S.AWH(%llu), "
"sending SYNC...\n", dccp_packet_name(dh->dccph_type),
(unsigned long long) lswl, (unsigned long long) seqno,
(unsigned long long) dp->dccps_swh,
(ackno == DCCP_PKT_WITHOUT_ACK_SEQ) ? "doesn't exist"
: "exists",
(unsigned long long) lawl, (unsigned long long) ackno,
(unsigned long long) dp->dccps_awh);
dp->dccps_rate_last = now;
if (dh->dccph_type == DCCP_PKT_RESET)
seqno = dp->dccps_gsr;
dccp_send_sync(sk, seqno, DCCP_PKT_SYNC);
return -1;
}
return 0;
}
static int __dccp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct dccp_hdr *dh, const unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
switch (dccp_hdr(skb)->dccph_type) {
case DCCP_PKT_DATAACK:
case DCCP_PKT_DATA:
/*
* FIXME: schedule DATA_DROPPED (RFC 4340, 11.7.2) if and when
* - sk_shutdown == RCV_SHUTDOWN, use Code 1, "Not Listening"
* - sk_receive_queue is full, use Code 2, "Receive Buffer"
*/
dccp_enqueue_skb(sk, skb);
return 0;
case DCCP_PKT_ACK:
goto discard;
case DCCP_PKT_RESET:
/*
* Step 9: Process Reset
* If P.type == Reset,
* Tear down connection
* S.state := TIMEWAIT
* Set TIMEWAIT timer
* Drop packet and return
*/
dccp_rcv_reset(sk, skb);
return 0;
case DCCP_PKT_CLOSEREQ:
if (dccp_rcv_closereq(sk, skb))
return 0;
goto discard;
case DCCP_PKT_CLOSE:
if (dccp_rcv_close(sk, skb))
return 0;
goto discard;
case DCCP_PKT_REQUEST:
/* Step 7
* or (S.is_server and P.type == Response)
* or (S.is_client and P.type == Request)
* or (S.state >= OPEN and P.type == Request
* and P.seqno >= S.OSR)
* or (S.state >= OPEN and P.type == Response
* and P.seqno >= S.OSR)
* or (S.state == RESPOND and P.type == Data),
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
if (dp->dccps_role != DCCP_ROLE_LISTEN)
goto send_sync;
goto check_seq;
case DCCP_PKT_RESPONSE:
if (dp->dccps_role != DCCP_ROLE_CLIENT)
goto send_sync;
check_seq:
if (dccp_delta_seqno(dp->dccps_osr,
DCCP_SKB_CB(skb)->dccpd_seq) >= 0) {
send_sync:
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_PKT_SYNC);
}
break;
case DCCP_PKT_SYNC:
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_PKT_SYNCACK);
/*
* From RFC 4340, sec. 5.7
*
* As with DCCP-Ack packets, DCCP-Sync and DCCP-SyncAck packets
* MAY have non-zero-length application data areas, whose
* contents receivers MUST ignore.
*/
goto discard;
}
DCCP_INC_STATS_BH(DCCP_MIB_INERRS);
discard:
__kfree_skb(skb);
return 0;
}
int dccp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct dccp_hdr *dh, const unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
if (dccp_check_seqno(sk, skb))
goto discard;
if (dccp_parse_options(sk, NULL, skb))
return 1;
if (DCCP_SKB_CB(skb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ)
dccp_event_ack_recv(sk, skb);
if (dp->dccps_hc_rx_ackvec != NULL &&
dccp_ackvec_add(dp->dccps_hc_rx_ackvec, sk,
DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_ACKVEC_STATE_RECEIVED))
goto discard;
dccp_deliver_input_to_ccids(sk, skb);
return __dccp_rcv_established(sk, skb, dh, len);
discard:
__kfree_skb(skb);
return 0;
}
EXPORT_SYMBOL_GPL(dccp_rcv_established);
static int dccp_rcv_request_sent_state_process(struct sock *sk,
struct sk_buff *skb,
const struct dccp_hdr *dh,
const unsigned len)
{
/*
* Step 4: Prepare sequence numbers in REQUEST
* If S.state == REQUEST,
* If (P.type == Response or P.type == Reset)
* and S.AWL <= P.ackno <= S.AWH,
* / * Set sequence number variables corresponding to the
* other endpoint, so P will pass the tests in Step 6 * /
* Set S.GSR, S.ISR, S.SWL, S.SWH
* / * Response processing continues in Step 10; Reset
* processing continues in Step 9 * /
*/
if (dh->dccph_type == DCCP_PKT_RESPONSE) {
const struct inet_connection_sock *icsk = inet_csk(sk);
struct dccp_sock *dp = dccp_sk(sk);
long tstamp = dccp_timestamp();
if (!between48(DCCP_SKB_CB(skb)->dccpd_ack_seq,
dp->dccps_awl, dp->dccps_awh)) {
dccp_pr_debug("invalid ackno: S.AWL=%llu, "
"P.ackno=%llu, S.AWH=%llu\n",
(unsigned long long)dp->dccps_awl,
(unsigned long long)DCCP_SKB_CB(skb)->dccpd_ack_seq,
(unsigned long long)dp->dccps_awh);
goto out_invalid_packet;
}
/*
* If option processing (Step 8) failed, return 1 here so that
* dccp_v4_do_rcv() sends a Reset. The Reset code depends on
* the option type and is set in dccp_parse_options().
*/
if (dccp_parse_options(sk, NULL, skb))
return 1;
/* Obtain usec RTT sample from SYN exchange (used by CCID 3) */
if (likely(dp->dccps_options_received.dccpor_timestamp_echo))
dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * (tstamp -
dp->dccps_options_received.dccpor_timestamp_echo));
/* Stop the REQUEST timer */
inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
WARN_ON(sk->sk_send_head == NULL);
kfree_skb(sk->sk_send_head);
sk->sk_send_head = NULL;
dp->dccps_isr = DCCP_SKB_CB(skb)->dccpd_seq;
dccp_update_gsr(sk, dp->dccps_isr);
/*
* SWL and AWL are initially adjusted so that they are not less than
* the initial Sequence Numbers received and sent, respectively:
* SWL := max(GSR + 1 - floor(W/4), ISR),
* AWL := max(GSS - W' + 1, ISS).
* These adjustments MUST be applied only at the beginning of the
* connection.
*
* AWL was adjusted in dccp_v4_connect -acme
*/
dccp_set_seqno(&dp->dccps_swl,
max48(dp->dccps_swl, dp->dccps_isr));
dccp_sync_mss(sk, icsk->icsk_pmtu_cookie);
/*
* Step 10: Process REQUEST state (second part)
* If S.state == REQUEST,
* / * If we get here, P is a valid Response from the
* server (see Step 4), and we should move to
* PARTOPEN state. PARTOPEN means send an Ack,
* don't send Data packets, retransmit Acks
* periodically, and always include any Init Cookie
* from the Response * /
* S.state := PARTOPEN
* Set PARTOPEN timer
* Continue with S.state == PARTOPEN
* / * Step 12 will send the Ack completing the
* three-way handshake * /
*/
dccp_set_state(sk, DCCP_PARTOPEN);
/*
* If feature negotiation was successful, activate features now;
* an activation failure means that this host could not activate
* one ore more features (e.g. insufficient memory), which would
* leave at least one feature in an undefined state.
*/
if (dccp_feat_activate_values(sk, &dp->dccps_featneg))
goto unable_to_proceed;
/* Make sure socket is routed, for correct metrics. */
icsk->icsk_af_ops->rebuild_header(sk);
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
}
if (sk->sk_write_pending || icsk->icsk_ack.pingpong ||
icsk->icsk_accept_queue.rskq_defer_accept) {
/* Save one ACK. Data will be ready after
* several ticks, if write_pending is set.
*
* It may be deleted, but with this feature tcpdumps
* look so _wonderfully_ clever, that I was not able
* to stand against the temptation 8) --ANK
*/
/*
* OK, in DCCP we can as well do a similar trick, its
* even in the draft, but there is no need for us to
* schedule an ack here, as dccp_sendmsg does this for
* us, also stated in the draft. -acme
*/
__kfree_skb(skb);
return 0;
}
dccp_send_ack(sk);
return -1;
}
out_invalid_packet:
/* dccp_v4_do_rcv will send a reset */
DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_PACKET_ERROR;
return 1;
unable_to_proceed:
DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_ABORTED;
/*
* We mark this socket as no longer usable, so that the loop in
* dccp_sendmsg() terminates and the application gets notified.
*/
dccp_set_state(sk, DCCP_CLOSED);
sk->sk_err = ECOMM;
return 1;
}
static int dccp_rcv_respond_partopen_state_process(struct sock *sk,
struct sk_buff *skb,
const struct dccp_hdr *dh,
const unsigned len)
{
int queued = 0;
switch (dh->dccph_type) {
case DCCP_PKT_RESET:
inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
break;
case DCCP_PKT_DATA:
if (sk->sk_state == DCCP_RESPOND)
break;
case DCCP_PKT_DATAACK:
case DCCP_PKT_ACK:
/*
* FIXME: we should be reseting the PARTOPEN (DELACK) timer
* here but only if we haven't used the DELACK timer for
* something else, like sending a delayed ack for a TIMESTAMP
* echo, etc, for now were not clearing it, sending an extra
* ACK when there is nothing else to do in DELACK is not a big
* deal after all.
*/
/* Stop the PARTOPEN timer */
if (sk->sk_state == DCCP_PARTOPEN)
inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
dccp_sk(sk)->dccps_osr = DCCP_SKB_CB(skb)->dccpd_seq;
dccp_set_state(sk, DCCP_OPEN);
if (dh->dccph_type == DCCP_PKT_DATAACK ||
dh->dccph_type == DCCP_PKT_DATA) {
__dccp_rcv_established(sk, skb, dh, len);
queued = 1; /* packet was queued
(by __dccp_rcv_established) */
}
break;
}
return queued;
}
int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
struct dccp_hdr *dh, unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb);
const int old_state = sk->sk_state;
int queued = 0;
/*
* Step 3: Process LISTEN state
*
* If S.state == LISTEN,
* If P.type == Request or P contains a valid Init Cookie option,
* (* Must scan the packet's options to check for Init
* Cookies. Only Init Cookies are processed here,
* however; other options are processed in Step 8. This
* scan need only be performed if the endpoint uses Init
* Cookies *)
* (* Generate a new socket and switch to that socket *)
* Set S := new socket for this port pair
* S.state = RESPOND
* Choose S.ISS (initial seqno) or set from Init Cookies
* Initialize S.GAR := S.ISS
* Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init
* Cookies Continue with S.state == RESPOND
* (* A Response packet will be generated in Step 11 *)
* Otherwise,
* Generate Reset(No Connection) unless P.type == Reset
* Drop packet and return
*/
if (sk->sk_state == DCCP_LISTEN) {
if (dh->dccph_type == DCCP_PKT_REQUEST) {
if (inet_csk(sk)->icsk_af_ops->conn_request(sk,
skb) < 0)
return 1;
goto discard;
}
if (dh->dccph_type == DCCP_PKT_RESET)
goto discard;
/* Caller (dccp_v4_do_rcv) will send Reset */
dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION;
return 1;
}
if (sk->sk_state != DCCP_REQUESTING && sk->sk_state != DCCP_RESPOND) {
if (dccp_check_seqno(sk, skb))
goto discard;
/*
* Step 8: Process options and mark acknowledgeable
*/
if (dccp_parse_options(sk, NULL, skb))
return 1;
if (dcb->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ)
dccp_event_ack_recv(sk, skb);
if (dp->dccps_hc_rx_ackvec != NULL &&
dccp_ackvec_add(dp->dccps_hc_rx_ackvec, sk,
DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_ACKVEC_STATE_RECEIVED))
goto discard;
dccp_deliver_input_to_ccids(sk, skb);
}
/*
* Step 9: Process Reset
* If P.type == Reset,
* Tear down connection
* S.state := TIMEWAIT
* Set TIMEWAIT timer
* Drop packet and return
*/
if (dh->dccph_type == DCCP_PKT_RESET) {
dccp_rcv_reset(sk, skb);
return 0;
/*
* Step 7: Check for unexpected packet types
* If (S.is_server and P.type == Response)
* or (S.is_client and P.type == Request)
* or (S.state == RESPOND and P.type == Data),
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
} else if ((dp->dccps_role != DCCP_ROLE_CLIENT &&
dh->dccph_type == DCCP_PKT_RESPONSE) ||
(dp->dccps_role == DCCP_ROLE_CLIENT &&
dh->dccph_type == DCCP_PKT_REQUEST) ||
(sk->sk_state == DCCP_RESPOND &&
dh->dccph_type == DCCP_PKT_DATA)) {
dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC);
goto discard;
} else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) {
if (dccp_rcv_closereq(sk, skb))
return 0;
goto discard;
} else if (dh->dccph_type == DCCP_PKT_CLOSE) {
if (dccp_rcv_close(sk, skb))
return 0;
goto discard;
}
switch (sk->sk_state) {
case DCCP_CLOSED:
dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION;
return 1;
case DCCP_REQUESTING:
queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len);
if (queued >= 0)
return queued;
__kfree_skb(skb);
return 0;
case DCCP_RESPOND:
case DCCP_PARTOPEN:
queued = dccp_rcv_respond_partopen_state_process(sk, skb,
dh, len);
break;
}
if (dh->dccph_type == DCCP_PKT_ACK ||
dh->dccph_type == DCCP_PKT_DATAACK) {
switch (old_state) {
case DCCP_PARTOPEN:
sk->sk_state_change(sk);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
break;
}
} else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) {
dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK);
goto discard;
}
if (!queued) {
discard:
__kfree_skb(skb);
}
return 0;
}
EXPORT_SYMBOL_GPL(dccp_rcv_state_process);
/**
* dccp_sample_rtt - Validate and finalise computation of RTT sample
* @delta: number of microseconds between packet and acknowledgment
* The routine is kept generic to work in different contexts. It should be
* called immediately when the ACK used for the RTT sample arrives.
*/
u32 dccp_sample_rtt(struct sock *sk, long delta)
{
/* dccpor_elapsed_time is either zeroed out or set and > 0 */
delta -= dccp_sk(sk)->dccps_options_received.dccpor_elapsed_time * 10;
if (unlikely(delta <= 0)) {
DCCP_WARN("unusable RTT sample %ld, using min\n", delta);
return DCCP_SANE_RTT_MIN;
}
if (unlikely(delta > DCCP_SANE_RTT_MAX)) {
DCCP_WARN("RTT sample %ld too large, using max\n", delta);
return DCCP_SANE_RTT_MAX;
}
return delta;
}
| gpl-2.0 |
TenchiMasaki/android-tegra-nv-3.1.10-rel-15r7 | drivers/media/video/em28xx/em28xx-audio.c | 562 | 19472 | /*
* Empiatech em28x1 audio extension
*
* Copyright (C) 2006 Markus Rechberger <mrechberger@gmail.com>
*
* Copyright (C) 2007-2011 Mauro Carvalho Chehab <mchehab@redhat.com>
* - Port to work with the in-kernel driver
* - Cleanups, fixes, alsa-controls, etc.
*
* This driver is based on my previous au600 usb pstn audio driver
* and inherits all the copyrights
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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/usb.h>
#include <linux/init.h>
#include <linux/sound.h>
#include <linux/spinlock.h>
#include <linux/soundcard.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include <media/v4l2-common.h>
#include "em28xx.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "activates debug info");
#define dprintk(fmt, arg...) do { \
if (debug) \
printk(KERN_INFO "em28xx-audio %s: " fmt, \
__func__, ##arg); \
} while (0)
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static int em28xx_deinit_isoc_audio(struct em28xx *dev)
{
int i;
dprintk("Stopping isoc\n");
for (i = 0; i < EM28XX_AUDIO_BUFS; i++) {
if (!irqs_disabled())
usb_kill_urb(dev->adev.urb[i]);
else
usb_unlink_urb(dev->adev.urb[i]);
usb_free_urb(dev->adev.urb[i]);
dev->adev.urb[i] = NULL;
kfree(dev->adev.transfer_buffer[i]);
dev->adev.transfer_buffer[i] = NULL;
}
return 0;
}
static void em28xx_audio_isocirq(struct urb *urb)
{
struct em28xx *dev = urb->context;
int i;
unsigned int oldptr;
int period_elapsed = 0;
int status;
unsigned char *cp;
unsigned int stride;
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dprintk("urb completition error %d.\n", urb->status);
break;
}
if (atomic_read(&dev->stream_started) == 0)
return;
if (dev->adev.capture_pcm_substream) {
substream = dev->adev.capture_pcm_substream;
runtime = substream->runtime;
stride = runtime->frame_bits >> 3;
for (i = 0; i < urb->number_of_packets; i++) {
int length =
urb->iso_frame_desc[i].actual_length / stride;
cp = (unsigned char *)urb->transfer_buffer +
urb->iso_frame_desc[i].offset;
if (!length)
continue;
oldptr = dev->adev.hwptr_done_capture;
if (oldptr + length >= runtime->buffer_size) {
unsigned int cnt =
runtime->buffer_size - oldptr;
memcpy(runtime->dma_area + oldptr * stride, cp,
cnt * stride);
memcpy(runtime->dma_area, cp + cnt * stride,
length * stride - cnt * stride);
} else {
memcpy(runtime->dma_area + oldptr * stride, cp,
length * stride);
}
snd_pcm_stream_lock(substream);
dev->adev.hwptr_done_capture += length;
if (dev->adev.hwptr_done_capture >=
runtime->buffer_size)
dev->adev.hwptr_done_capture -=
runtime->buffer_size;
dev->adev.capture_transfer_done += length;
if (dev->adev.capture_transfer_done >=
runtime->period_size) {
dev->adev.capture_transfer_done -=
runtime->period_size;
period_elapsed = 1;
}
snd_pcm_stream_unlock(substream);
}
if (period_elapsed)
snd_pcm_period_elapsed(substream);
}
urb->status = 0;
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status < 0) {
em28xx_errdev("resubmit of audio urb failed (error=%i)\n",
status);
}
return;
}
static int em28xx_init_audio_isoc(struct em28xx *dev)
{
int i, errCode;
const int sb_size = EM28XX_NUM_AUDIO_PACKETS *
EM28XX_AUDIO_MAX_PACKET_SIZE;
dprintk("Starting isoc transfers\n");
for (i = 0; i < EM28XX_AUDIO_BUFS; i++) {
struct urb *urb;
int j, k;
dev->adev.transfer_buffer[i] = kmalloc(sb_size, GFP_ATOMIC);
if (!dev->adev.transfer_buffer[i])
return -ENOMEM;
memset(dev->adev.transfer_buffer[i], 0x80, sb_size);
urb = usb_alloc_urb(EM28XX_NUM_AUDIO_PACKETS, GFP_ATOMIC);
if (!urb) {
em28xx_errdev("usb_alloc_urb failed!\n");
for (j = 0; j < i; j++) {
usb_free_urb(dev->adev.urb[j]);
kfree(dev->adev.transfer_buffer[j]);
}
return -ENOMEM;
}
urb->dev = dev->udev;
urb->context = dev;
urb->pipe = usb_rcvisocpipe(dev->udev, 0x83);
urb->transfer_flags = URB_ISO_ASAP;
urb->transfer_buffer = dev->adev.transfer_buffer[i];
urb->interval = 1;
urb->complete = em28xx_audio_isocirq;
urb->number_of_packets = EM28XX_NUM_AUDIO_PACKETS;
urb->transfer_buffer_length = sb_size;
for (j = k = 0; j < EM28XX_NUM_AUDIO_PACKETS;
j++, k += EM28XX_AUDIO_MAX_PACKET_SIZE) {
urb->iso_frame_desc[j].offset = k;
urb->iso_frame_desc[j].length =
EM28XX_AUDIO_MAX_PACKET_SIZE;
}
dev->adev.urb[i] = urb;
}
for (i = 0; i < EM28XX_AUDIO_BUFS; i++) {
errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC);
if (errCode) {
em28xx_errdev("submit of audio urb failed\n");
em28xx_deinit_isoc_audio(dev);
atomic_set(&dev->stream_started, 0);
return errCode;
}
}
return 0;
}
static int snd_pcm_alloc_vmalloc_buffer(struct snd_pcm_substream *subs,
size_t size)
{
struct snd_pcm_runtime *runtime = subs->runtime;
dprintk("Allocating vbuffer\n");
if (runtime->dma_area) {
if (runtime->dma_bytes > size)
return 0;
vfree(runtime->dma_area);
}
runtime->dma_area = vmalloc(size);
if (!runtime->dma_area)
return -ENOMEM;
runtime->dma_bytes = size;
return 0;
}
static struct snd_pcm_hardware snd_em28xx_hw_capture = {
.info = SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BATCH |
SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_KNOT,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 62720 * 8, /* just about the value in usbaudio.c */
.period_bytes_min = 64, /* 12544/2, */
.period_bytes_max = 12544,
.periods_min = 2,
.periods_max = 98, /* 12544, */
};
static int snd_em28xx_capture_open(struct snd_pcm_substream *substream)
{
struct em28xx *dev = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int ret = 0;
dprintk("opening device and trying to acquire exclusive lock\n");
if (!dev) {
em28xx_err("BUG: em28xx can't find device struct."
" Can't proceed with open\n");
return -ENODEV;
}
runtime->hw = snd_em28xx_hw_capture;
if ((dev->alt == 0 || dev->audio_ifnum) && dev->adev.users == 0) {
if (dev->audio_ifnum)
dev->alt = 1;
else
dev->alt = 7;
dprintk("changing alternate number on interface %d to %d\n",
dev->audio_ifnum, dev->alt);
usb_set_interface(dev->udev, dev->audio_ifnum, dev->alt);
/* Sets volume, mute, etc */
dev->mute = 0;
mutex_lock(&dev->lock);
ret = em28xx_audio_analog_set(dev);
if (ret < 0)
goto err;
dev->adev.users++;
mutex_unlock(&dev->lock);
}
snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
dev->adev.capture_pcm_substream = substream;
runtime->private_data = dev;
return 0;
err:
mutex_unlock(&dev->lock);
em28xx_err("Error while configuring em28xx mixer\n");
return ret;
}
static int snd_em28xx_pcm_close(struct snd_pcm_substream *substream)
{
struct em28xx *dev = snd_pcm_substream_chip(substream);
dprintk("closing device\n");
dev->mute = 1;
mutex_lock(&dev->lock);
dev->adev.users--;
if (atomic_read(&dev->stream_started) > 0) {
atomic_set(&dev->stream_started, 0);
schedule_work(&dev->wq_trigger);
}
em28xx_audio_analog_set(dev);
if (substream->runtime->dma_area) {
dprintk("freeing\n");
vfree(substream->runtime->dma_area);
substream->runtime->dma_area = NULL;
}
mutex_unlock(&dev->lock);
return 0;
}
static int snd_em28xx_hw_capture_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
unsigned int channels, rate, format;
int ret;
dprintk("Setting capture parameters\n");
ret = snd_pcm_alloc_vmalloc_buffer(substream,
params_buffer_bytes(hw_params));
if (ret < 0)
return ret;
format = params_format(hw_params);
rate = params_rate(hw_params);
channels = params_channels(hw_params);
/* TODO: set up em28xx audio chip to deliver the correct audio format,
current default is 48000hz multiplexed => 96000hz mono
which shouldn't matter since analogue TV only supports mono */
return 0;
}
static int snd_em28xx_hw_capture_free(struct snd_pcm_substream *substream)
{
struct em28xx *dev = snd_pcm_substream_chip(substream);
dprintk("Stop capture, if needed\n");
if (atomic_read(&dev->stream_started) > 0) {
atomic_set(&dev->stream_started, 0);
schedule_work(&dev->wq_trigger);
}
return 0;
}
static int snd_em28xx_prepare(struct snd_pcm_substream *substream)
{
struct em28xx *dev = snd_pcm_substream_chip(substream);
dev->adev.hwptr_done_capture = 0;
dev->adev.capture_transfer_done = 0;
return 0;
}
static void audio_trigger(struct work_struct *work)
{
struct em28xx *dev = container_of(work, struct em28xx, wq_trigger);
if (atomic_read(&dev->stream_started)) {
dprintk("starting capture");
em28xx_init_audio_isoc(dev);
} else {
dprintk("stopping capture");
em28xx_deinit_isoc_audio(dev);
}
}
static int snd_em28xx_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct em28xx *dev = snd_pcm_substream_chip(substream);
int retval = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: /* fall through */
case SNDRV_PCM_TRIGGER_RESUME: /* fall through */
case SNDRV_PCM_TRIGGER_START:
atomic_set(&dev->stream_started, 1);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH: /* fall through */
case SNDRV_PCM_TRIGGER_SUSPEND: /* fall through */
case SNDRV_PCM_TRIGGER_STOP:
atomic_set(&dev->stream_started, 0);
break;
default:
retval = -EINVAL;
}
schedule_work(&dev->wq_trigger);
return retval;
}
static snd_pcm_uframes_t snd_em28xx_capture_pointer(struct snd_pcm_substream
*substream)
{
unsigned long flags;
struct em28xx *dev;
snd_pcm_uframes_t hwptr_done;
dev = snd_pcm_substream_chip(substream);
spin_lock_irqsave(&dev->adev.slock, flags);
hwptr_done = dev->adev.hwptr_done_capture;
spin_unlock_irqrestore(&dev->adev.slock, flags);
return hwptr_done;
}
static struct page *snd_pcm_get_vmalloc_page(struct snd_pcm_substream *subs,
unsigned long offset)
{
void *pageptr = subs->runtime->dma_area + offset;
return vmalloc_to_page(pageptr);
}
/*
* AC97 volume control support
*/
static int em28xx_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *info)
{
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = 2;
info->value.integer.min = 0;
info->value.integer.max = 0x1f;
return 0;
}
static int em28xx_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
struct em28xx *dev = snd_kcontrol_chip(kcontrol);
u16 val = (0x1f - (value->value.integer.value[0] & 0x1f)) |
(0x1f - (value->value.integer.value[1] & 0x1f)) << 8;
int rc;
mutex_lock(&dev->lock);
rc = em28xx_read_ac97(dev, kcontrol->private_value);
if (rc < 0)
goto err;
val |= rc & 0x8000; /* Preserve the mute flag */
rc = em28xx_write_ac97(dev, kcontrol->private_value, val);
if (rc < 0)
goto err;
dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
(val & 0x8000) ? "muted " : "",
0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
val, (int)kcontrol->private_value);
err:
mutex_unlock(&dev->lock);
return rc;
}
static int em28xx_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
struct em28xx *dev = snd_kcontrol_chip(kcontrol);
int val;
mutex_lock(&dev->lock);
val = em28xx_read_ac97(dev, kcontrol->private_value);
mutex_unlock(&dev->lock);
if (val < 0)
return val;
dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
(val & 0x8000) ? "muted " : "",
0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
val, (int)kcontrol->private_value);
value->value.integer.value[0] = 0x1f - (val & 0x1f);
value->value.integer.value[1] = 0x1f - ((val << 8) & 0x1f);
return 0;
}
static int em28xx_vol_put_mute(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
struct em28xx *dev = snd_kcontrol_chip(kcontrol);
u16 val = value->value.integer.value[0];
int rc;
mutex_lock(&dev->lock);
rc = em28xx_read_ac97(dev, kcontrol->private_value);
if (rc < 0)
goto err;
if (val)
rc &= 0x1f1f;
else
rc |= 0x8000;
rc = em28xx_write_ac97(dev, kcontrol->private_value, rc);
if (rc < 0)
goto err;
dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
(val & 0x8000) ? "muted " : "",
0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
val, (int)kcontrol->private_value);
err:
mutex_unlock(&dev->lock);
return rc;
}
static int em28xx_vol_get_mute(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
struct em28xx *dev = snd_kcontrol_chip(kcontrol);
int val;
mutex_lock(&dev->lock);
val = em28xx_read_ac97(dev, kcontrol->private_value);
mutex_unlock(&dev->lock);
if (val < 0)
return val;
if (val & 0x8000)
value->value.integer.value[0] = 0;
else
value->value.integer.value[0] = 1;
dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
(val & 0x8000) ? "muted " : "",
0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
val, (int)kcontrol->private_value);
return 0;
}
static const DECLARE_TLV_DB_SCALE(em28xx_db_scale, -3450, 150, 0);
static int em28xx_cvol_new(struct snd_card *card, struct em28xx *dev,
char *name, int id)
{
int err;
char ctl_name[44];
struct snd_kcontrol *kctl;
struct snd_kcontrol_new tmp;
memset (&tmp, 0, sizeof(tmp));
tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
tmp.private_value = id,
tmp.name = ctl_name,
/* Add Mute Control */
sprintf(ctl_name, "%s Switch", name);
tmp.get = em28xx_vol_get_mute;
tmp.put = em28xx_vol_put_mute;
tmp.info = snd_ctl_boolean_mono_info;
kctl = snd_ctl_new1(&tmp, dev);
err = snd_ctl_add(card, kctl);
if (err < 0)
return err;
dprintk("Added control %s for ac97 volume control 0x%04x\n",
ctl_name, id);
memset (&tmp, 0, sizeof(tmp));
tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
tmp.private_value = id,
tmp.name = ctl_name,
/* Add Volume Control */
sprintf(ctl_name, "%s Volume", name);
tmp.get = em28xx_vol_get;
tmp.put = em28xx_vol_put;
tmp.info = em28xx_vol_info;
tmp.tlv.p = em28xx_db_scale,
kctl = snd_ctl_new1(&tmp, dev);
err = snd_ctl_add(card, kctl);
if (err < 0)
return err;
dprintk("Added control %s for ac97 volume control 0x%04x\n",
ctl_name, id);
return 0;
}
/*
* register/unregister code and data
*/
static struct snd_pcm_ops snd_em28xx_pcm_capture = {
.open = snd_em28xx_capture_open,
.close = snd_em28xx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_em28xx_hw_capture_params,
.hw_free = snd_em28xx_hw_capture_free,
.prepare = snd_em28xx_prepare,
.trigger = snd_em28xx_capture_trigger,
.pointer = snd_em28xx_capture_pointer,
.page = snd_pcm_get_vmalloc_page,
};
static int em28xx_audio_init(struct em28xx *dev)
{
struct em28xx_audio *adev = &dev->adev;
struct snd_pcm *pcm;
struct snd_card *card;
static int devnr;
int err;
if (!dev->has_alsa_audio || dev->audio_ifnum < 0) {
/* This device does not support the extension (in this case
the device is expecting the snd-usb-audio module or
doesn't have analog audio support at all) */
return 0;
}
printk(KERN_INFO "em28xx-audio.c: probing for em28xx Audio Vendor Class\n");
printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2006 Markus "
"Rechberger\n");
printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2007-2011 Mauro Carvalho Chehab\n");
err = snd_card_create(index[devnr], "Em28xx Audio", THIS_MODULE, 0,
&card);
if (err < 0)
return err;
spin_lock_init(&adev->slock);
err = snd_pcm_new(card, "Em28xx Audio", 0, 0, 1, &pcm);
if (err < 0) {
snd_card_free(card);
return err;
}
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_em28xx_pcm_capture);
pcm->info_flags = 0;
pcm->private_data = dev;
strcpy(pcm->name, "Empia 28xx Capture");
snd_card_set_dev(card, &dev->udev->dev);
strcpy(card->driver, "Em28xx-Audio");
strcpy(card->shortname, "Em28xx Audio");
strcpy(card->longname, "Empia Em28xx Audio");
INIT_WORK(&dev->wq_trigger, audio_trigger);
if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
em28xx_cvol_new(card, dev, "Video", AC97_VIDEO_VOL);
em28xx_cvol_new(card, dev, "Line In", AC97_LINEIN_VOL);
em28xx_cvol_new(card, dev, "Phone", AC97_PHONE_VOL);
em28xx_cvol_new(card, dev, "Microphone", AC97_PHONE_VOL);
em28xx_cvol_new(card, dev, "CD", AC97_CD_VOL);
em28xx_cvol_new(card, dev, "AUX", AC97_AUX_VOL);
em28xx_cvol_new(card, dev, "PCM", AC97_PCM_OUT_VOL);
em28xx_cvol_new(card, dev, "Master", AC97_MASTER_VOL);
em28xx_cvol_new(card, dev, "Line", AC97_LINE_LEVEL_VOL);
em28xx_cvol_new(card, dev, "Mono", AC97_MASTER_MONO_VOL);
em28xx_cvol_new(card, dev, "LFE", AC97_LFE_MASTER_VOL);
em28xx_cvol_new(card, dev, "Surround", AC97_SURR_MASTER_VOL);
}
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
return err;
}
adev->sndcard = card;
adev->udev = dev->udev;
return 0;
}
static int em28xx_audio_fini(struct em28xx *dev)
{
if (dev == NULL)
return 0;
if (dev->has_alsa_audio != 1) {
/* This device does not support the extension (in this case
the device is expecting the snd-usb-audio module or
doesn't have analog audio support at all) */
return 0;
}
if (dev->adev.sndcard) {
snd_card_free(dev->adev.sndcard);
dev->adev.sndcard = NULL;
}
return 0;
}
static struct em28xx_ops audio_ops = {
.id = EM28XX_AUDIO,
.name = "Em28xx Audio Extension",
.init = em28xx_audio_init,
.fini = em28xx_audio_fini,
};
static int __init em28xx_alsa_register(void)
{
return em28xx_register_extension(&audio_ops);
}
static void __exit em28xx_alsa_unregister(void)
{
em28xx_unregister_extension(&audio_ops);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Markus Rechberger <mrechberger@gmail.com>");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_DESCRIPTION("Em28xx Audio driver");
module_init(em28xx_alsa_register);
module_exit(em28xx_alsa_unregister);
| gpl-2.0 |
deepongi/android_kernel_sony_msm | drivers/infiniband/hw/mthca/mthca_qp.c | 2610 | 62454 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2004 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 <linux/string.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <asm/io.h>
#include <rdma/ib_verbs.h>
#include <rdma/ib_cache.h>
#include <rdma/ib_pack.h>
#include "mthca_dev.h"
#include "mthca_cmd.h"
#include "mthca_memfree.h"
#include "mthca_wqe.h"
enum {
MTHCA_MAX_DIRECT_QP_SIZE = 4 * PAGE_SIZE,
MTHCA_ACK_REQ_FREQ = 10,
MTHCA_FLIGHT_LIMIT = 9,
MTHCA_UD_HEADER_SIZE = 72, /* largest UD header possible */
MTHCA_INLINE_HEADER_SIZE = 4, /* data segment overhead for inline */
MTHCA_INLINE_CHUNK_SIZE = 16 /* inline data segment chunk */
};
enum {
MTHCA_QP_STATE_RST = 0,
MTHCA_QP_STATE_INIT = 1,
MTHCA_QP_STATE_RTR = 2,
MTHCA_QP_STATE_RTS = 3,
MTHCA_QP_STATE_SQE = 4,
MTHCA_QP_STATE_SQD = 5,
MTHCA_QP_STATE_ERR = 6,
MTHCA_QP_STATE_DRAINING = 7
};
enum {
MTHCA_QP_ST_RC = 0x0,
MTHCA_QP_ST_UC = 0x1,
MTHCA_QP_ST_RD = 0x2,
MTHCA_QP_ST_UD = 0x3,
MTHCA_QP_ST_MLX = 0x7
};
enum {
MTHCA_QP_PM_MIGRATED = 0x3,
MTHCA_QP_PM_ARMED = 0x0,
MTHCA_QP_PM_REARM = 0x1
};
enum {
/* qp_context flags */
MTHCA_QP_BIT_DE = 1 << 8,
/* params1 */
MTHCA_QP_BIT_SRE = 1 << 15,
MTHCA_QP_BIT_SWE = 1 << 14,
MTHCA_QP_BIT_SAE = 1 << 13,
MTHCA_QP_BIT_SIC = 1 << 4,
MTHCA_QP_BIT_SSC = 1 << 3,
/* params2 */
MTHCA_QP_BIT_RRE = 1 << 15,
MTHCA_QP_BIT_RWE = 1 << 14,
MTHCA_QP_BIT_RAE = 1 << 13,
MTHCA_QP_BIT_RIC = 1 << 4,
MTHCA_QP_BIT_RSC = 1 << 3
};
enum {
MTHCA_SEND_DOORBELL_FENCE = 1 << 5
};
struct mthca_qp_path {
__be32 port_pkey;
u8 rnr_retry;
u8 g_mylmc;
__be16 rlid;
u8 ackto;
u8 mgid_index;
u8 static_rate;
u8 hop_limit;
__be32 sl_tclass_flowlabel;
u8 rgid[16];
} __attribute__((packed));
struct mthca_qp_context {
__be32 flags;
__be32 tavor_sched_queue; /* Reserved on Arbel */
u8 mtu_msgmax;
u8 rq_size_stride; /* Reserved on Tavor */
u8 sq_size_stride; /* Reserved on Tavor */
u8 rlkey_arbel_sched_queue; /* Reserved on Tavor */
__be32 usr_page;
__be32 local_qpn;
__be32 remote_qpn;
u32 reserved1[2];
struct mthca_qp_path pri_path;
struct mthca_qp_path alt_path;
__be32 rdd;
__be32 pd;
__be32 wqe_base;
__be32 wqe_lkey;
__be32 params1;
__be32 reserved2;
__be32 next_send_psn;
__be32 cqn_snd;
__be32 snd_wqe_base_l; /* Next send WQE on Tavor */
__be32 snd_db_index; /* (debugging only entries) */
__be32 last_acked_psn;
__be32 ssn;
__be32 params2;
__be32 rnr_nextrecvpsn;
__be32 ra_buff_indx;
__be32 cqn_rcv;
__be32 rcv_wqe_base_l; /* Next recv WQE on Tavor */
__be32 rcv_db_index; /* (debugging only entries) */
__be32 qkey;
__be32 srqn;
__be32 rmsn;
__be16 rq_wqe_counter; /* reserved on Tavor */
__be16 sq_wqe_counter; /* reserved on Tavor */
u32 reserved3[18];
} __attribute__((packed));
struct mthca_qp_param {
__be32 opt_param_mask;
u32 reserved1;
struct mthca_qp_context context;
u32 reserved2[62];
} __attribute__((packed));
enum {
MTHCA_QP_OPTPAR_ALT_ADDR_PATH = 1 << 0,
MTHCA_QP_OPTPAR_RRE = 1 << 1,
MTHCA_QP_OPTPAR_RAE = 1 << 2,
MTHCA_QP_OPTPAR_RWE = 1 << 3,
MTHCA_QP_OPTPAR_PKEY_INDEX = 1 << 4,
MTHCA_QP_OPTPAR_Q_KEY = 1 << 5,
MTHCA_QP_OPTPAR_RNR_TIMEOUT = 1 << 6,
MTHCA_QP_OPTPAR_PRIMARY_ADDR_PATH = 1 << 7,
MTHCA_QP_OPTPAR_SRA_MAX = 1 << 8,
MTHCA_QP_OPTPAR_RRA_MAX = 1 << 9,
MTHCA_QP_OPTPAR_PM_STATE = 1 << 10,
MTHCA_QP_OPTPAR_PORT_NUM = 1 << 11,
MTHCA_QP_OPTPAR_RETRY_COUNT = 1 << 12,
MTHCA_QP_OPTPAR_ALT_RNR_RETRY = 1 << 13,
MTHCA_QP_OPTPAR_ACK_TIMEOUT = 1 << 14,
MTHCA_QP_OPTPAR_RNR_RETRY = 1 << 15,
MTHCA_QP_OPTPAR_SCHED_QUEUE = 1 << 16
};
static const u8 mthca_opcode[] = {
[IB_WR_SEND] = MTHCA_OPCODE_SEND,
[IB_WR_SEND_WITH_IMM] = MTHCA_OPCODE_SEND_IMM,
[IB_WR_RDMA_WRITE] = MTHCA_OPCODE_RDMA_WRITE,
[IB_WR_RDMA_WRITE_WITH_IMM] = MTHCA_OPCODE_RDMA_WRITE_IMM,
[IB_WR_RDMA_READ] = MTHCA_OPCODE_RDMA_READ,
[IB_WR_ATOMIC_CMP_AND_SWP] = MTHCA_OPCODE_ATOMIC_CS,
[IB_WR_ATOMIC_FETCH_AND_ADD] = MTHCA_OPCODE_ATOMIC_FA,
};
static int is_sqp(struct mthca_dev *dev, struct mthca_qp *qp)
{
return qp->qpn >= dev->qp_table.sqp_start &&
qp->qpn <= dev->qp_table.sqp_start + 3;
}
static int is_qp0(struct mthca_dev *dev, struct mthca_qp *qp)
{
return qp->qpn >= dev->qp_table.sqp_start &&
qp->qpn <= dev->qp_table.sqp_start + 1;
}
static void *get_recv_wqe(struct mthca_qp *qp, int n)
{
if (qp->is_direct)
return qp->queue.direct.buf + (n << qp->rq.wqe_shift);
else
return qp->queue.page_list[(n << qp->rq.wqe_shift) >> PAGE_SHIFT].buf +
((n << qp->rq.wqe_shift) & (PAGE_SIZE - 1));
}
static void *get_send_wqe(struct mthca_qp *qp, int n)
{
if (qp->is_direct)
return qp->queue.direct.buf + qp->send_wqe_offset +
(n << qp->sq.wqe_shift);
else
return qp->queue.page_list[(qp->send_wqe_offset +
(n << qp->sq.wqe_shift)) >>
PAGE_SHIFT].buf +
((qp->send_wqe_offset + (n << qp->sq.wqe_shift)) &
(PAGE_SIZE - 1));
}
static void mthca_wq_reset(struct mthca_wq *wq)
{
wq->next_ind = 0;
wq->last_comp = wq->max - 1;
wq->head = 0;
wq->tail = 0;
}
void mthca_qp_event(struct mthca_dev *dev, u32 qpn,
enum ib_event_type event_type)
{
struct mthca_qp *qp;
struct ib_event event;
spin_lock(&dev->qp_table.lock);
qp = mthca_array_get(&dev->qp_table.qp, qpn & (dev->limits.num_qps - 1));
if (qp)
++qp->refcount;
spin_unlock(&dev->qp_table.lock);
if (!qp) {
mthca_warn(dev, "Async event %d for bogus QP %08x\n",
event_type, qpn);
return;
}
if (event_type == IB_EVENT_PATH_MIG)
qp->port = qp->alt_port;
event.device = &dev->ib_dev;
event.event = event_type;
event.element.qp = &qp->ibqp;
if (qp->ibqp.event_handler)
qp->ibqp.event_handler(&event, qp->ibqp.qp_context);
spin_lock(&dev->qp_table.lock);
if (!--qp->refcount)
wake_up(&qp->wait);
spin_unlock(&dev->qp_table.lock);
}
static int to_mthca_state(enum ib_qp_state ib_state)
{
switch (ib_state) {
case IB_QPS_RESET: return MTHCA_QP_STATE_RST;
case IB_QPS_INIT: return MTHCA_QP_STATE_INIT;
case IB_QPS_RTR: return MTHCA_QP_STATE_RTR;
case IB_QPS_RTS: return MTHCA_QP_STATE_RTS;
case IB_QPS_SQD: return MTHCA_QP_STATE_SQD;
case IB_QPS_SQE: return MTHCA_QP_STATE_SQE;
case IB_QPS_ERR: return MTHCA_QP_STATE_ERR;
default: return -1;
}
}
enum { RC, UC, UD, RD, RDEE, MLX, NUM_TRANS };
static int to_mthca_st(int transport)
{
switch (transport) {
case RC: return MTHCA_QP_ST_RC;
case UC: return MTHCA_QP_ST_UC;
case UD: return MTHCA_QP_ST_UD;
case RD: return MTHCA_QP_ST_RD;
case MLX: return MTHCA_QP_ST_MLX;
default: return -1;
}
}
static void store_attrs(struct mthca_sqp *sqp, const struct ib_qp_attr *attr,
int attr_mask)
{
if (attr_mask & IB_QP_PKEY_INDEX)
sqp->pkey_index = attr->pkey_index;
if (attr_mask & IB_QP_QKEY)
sqp->qkey = attr->qkey;
if (attr_mask & IB_QP_SQ_PSN)
sqp->send_psn = attr->sq_psn;
}
static void init_port(struct mthca_dev *dev, int port)
{
int err;
struct mthca_init_ib_param param;
memset(¶m, 0, sizeof param);
param.port_width = dev->limits.port_width_cap;
param.vl_cap = dev->limits.vl_cap;
param.mtu_cap = dev->limits.mtu_cap;
param.gid_cap = dev->limits.gid_table_len;
param.pkey_cap = dev->limits.pkey_table_len;
err = mthca_INIT_IB(dev, ¶m, port);
if (err)
mthca_warn(dev, "INIT_IB failed, return code %d.\n", err);
}
static __be32 get_hw_access_flags(struct mthca_qp *qp, const struct ib_qp_attr *attr,
int attr_mask)
{
u8 dest_rd_atomic;
u32 access_flags;
u32 hw_access_flags = 0;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
dest_rd_atomic = attr->max_dest_rd_atomic;
else
dest_rd_atomic = qp->resp_depth;
if (attr_mask & IB_QP_ACCESS_FLAGS)
access_flags = attr->qp_access_flags;
else
access_flags = qp->atomic_rd_en;
if (!dest_rd_atomic)
access_flags &= IB_ACCESS_REMOTE_WRITE;
if (access_flags & IB_ACCESS_REMOTE_READ)
hw_access_flags |= MTHCA_QP_BIT_RRE;
if (access_flags & IB_ACCESS_REMOTE_ATOMIC)
hw_access_flags |= MTHCA_QP_BIT_RAE;
if (access_flags & IB_ACCESS_REMOTE_WRITE)
hw_access_flags |= MTHCA_QP_BIT_RWE;
return cpu_to_be32(hw_access_flags);
}
static inline enum ib_qp_state to_ib_qp_state(int mthca_state)
{
switch (mthca_state) {
case MTHCA_QP_STATE_RST: return IB_QPS_RESET;
case MTHCA_QP_STATE_INIT: return IB_QPS_INIT;
case MTHCA_QP_STATE_RTR: return IB_QPS_RTR;
case MTHCA_QP_STATE_RTS: return IB_QPS_RTS;
case MTHCA_QP_STATE_DRAINING:
case MTHCA_QP_STATE_SQD: return IB_QPS_SQD;
case MTHCA_QP_STATE_SQE: return IB_QPS_SQE;
case MTHCA_QP_STATE_ERR: return IB_QPS_ERR;
default: return -1;
}
}
static inline enum ib_mig_state to_ib_mig_state(int mthca_mig_state)
{
switch (mthca_mig_state) {
case 0: return IB_MIG_ARMED;
case 1: return IB_MIG_REARM;
case 3: return IB_MIG_MIGRATED;
default: return -1;
}
}
static int to_ib_qp_access_flags(int mthca_flags)
{
int ib_flags = 0;
if (mthca_flags & MTHCA_QP_BIT_RRE)
ib_flags |= IB_ACCESS_REMOTE_READ;
if (mthca_flags & MTHCA_QP_BIT_RWE)
ib_flags |= IB_ACCESS_REMOTE_WRITE;
if (mthca_flags & MTHCA_QP_BIT_RAE)
ib_flags |= IB_ACCESS_REMOTE_ATOMIC;
return ib_flags;
}
static void to_ib_ah_attr(struct mthca_dev *dev, struct ib_ah_attr *ib_ah_attr,
struct mthca_qp_path *path)
{
memset(ib_ah_attr, 0, sizeof *ib_ah_attr);
ib_ah_attr->port_num = (be32_to_cpu(path->port_pkey) >> 24) & 0x3;
if (ib_ah_attr->port_num == 0 || ib_ah_attr->port_num > dev->limits.num_ports)
return;
ib_ah_attr->dlid = be16_to_cpu(path->rlid);
ib_ah_attr->sl = be32_to_cpu(path->sl_tclass_flowlabel) >> 28;
ib_ah_attr->src_path_bits = path->g_mylmc & 0x7f;
ib_ah_attr->static_rate = mthca_rate_to_ib(dev,
path->static_rate & 0xf,
ib_ah_attr->port_num);
ib_ah_attr->ah_flags = (path->g_mylmc & (1 << 7)) ? IB_AH_GRH : 0;
if (ib_ah_attr->ah_flags) {
ib_ah_attr->grh.sgid_index = path->mgid_index & (dev->limits.gid_table_len - 1);
ib_ah_attr->grh.hop_limit = path->hop_limit;
ib_ah_attr->grh.traffic_class =
(be32_to_cpu(path->sl_tclass_flowlabel) >> 20) & 0xff;
ib_ah_attr->grh.flow_label =
be32_to_cpu(path->sl_tclass_flowlabel) & 0xfffff;
memcpy(ib_ah_attr->grh.dgid.raw,
path->rgid, sizeof ib_ah_attr->grh.dgid.raw);
}
}
int mthca_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask,
struct ib_qp_init_attr *qp_init_attr)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
int err = 0;
struct mthca_mailbox *mailbox = NULL;
struct mthca_qp_param *qp_param;
struct mthca_qp_context *context;
int mthca_state;
mutex_lock(&qp->mutex);
if (qp->state == IB_QPS_RESET) {
qp_attr->qp_state = IB_QPS_RESET;
goto done;
}
mailbox = mthca_alloc_mailbox(dev, GFP_KERNEL);
if (IS_ERR(mailbox)) {
err = PTR_ERR(mailbox);
goto out;
}
err = mthca_QUERY_QP(dev, qp->qpn, 0, mailbox);
if (err) {
mthca_warn(dev, "QUERY_QP failed (%d)\n", err);
goto out_mailbox;
}
qp_param = mailbox->buf;
context = &qp_param->context;
mthca_state = be32_to_cpu(context->flags) >> 28;
qp->state = to_ib_qp_state(mthca_state);
qp_attr->qp_state = qp->state;
qp_attr->path_mtu = context->mtu_msgmax >> 5;
qp_attr->path_mig_state =
to_ib_mig_state((be32_to_cpu(context->flags) >> 11) & 0x3);
qp_attr->qkey = be32_to_cpu(context->qkey);
qp_attr->rq_psn = be32_to_cpu(context->rnr_nextrecvpsn) & 0xffffff;
qp_attr->sq_psn = be32_to_cpu(context->next_send_psn) & 0xffffff;
qp_attr->dest_qp_num = be32_to_cpu(context->remote_qpn) & 0xffffff;
qp_attr->qp_access_flags =
to_ib_qp_access_flags(be32_to_cpu(context->params2));
if (qp->transport == RC || qp->transport == UC) {
to_ib_ah_attr(dev, &qp_attr->ah_attr, &context->pri_path);
to_ib_ah_attr(dev, &qp_attr->alt_ah_attr, &context->alt_path);
qp_attr->alt_pkey_index =
be32_to_cpu(context->alt_path.port_pkey) & 0x7f;
qp_attr->alt_port_num = qp_attr->alt_ah_attr.port_num;
}
qp_attr->pkey_index = be32_to_cpu(context->pri_path.port_pkey) & 0x7f;
qp_attr->port_num =
(be32_to_cpu(context->pri_path.port_pkey) >> 24) & 0x3;
/* qp_attr->en_sqd_async_notify is only applicable in modify qp */
qp_attr->sq_draining = mthca_state == MTHCA_QP_STATE_DRAINING;
qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context->params1) >> 21) & 0x7);
qp_attr->max_dest_rd_atomic =
1 << ((be32_to_cpu(context->params2) >> 21) & 0x7);
qp_attr->min_rnr_timer =
(be32_to_cpu(context->rnr_nextrecvpsn) >> 24) & 0x1f;
qp_attr->timeout = context->pri_path.ackto >> 3;
qp_attr->retry_cnt = (be32_to_cpu(context->params1) >> 16) & 0x7;
qp_attr->rnr_retry = context->pri_path.rnr_retry >> 5;
qp_attr->alt_timeout = context->alt_path.ackto >> 3;
done:
qp_attr->cur_qp_state = qp_attr->qp_state;
qp_attr->cap.max_send_wr = qp->sq.max;
qp_attr->cap.max_recv_wr = qp->rq.max;
qp_attr->cap.max_send_sge = qp->sq.max_gs;
qp_attr->cap.max_recv_sge = qp->rq.max_gs;
qp_attr->cap.max_inline_data = qp->max_inline_data;
qp_init_attr->cap = qp_attr->cap;
qp_init_attr->sq_sig_type = qp->sq_policy;
out_mailbox:
mthca_free_mailbox(dev, mailbox);
out:
mutex_unlock(&qp->mutex);
return err;
}
static int mthca_path_set(struct mthca_dev *dev, const struct ib_ah_attr *ah,
struct mthca_qp_path *path, u8 port)
{
path->g_mylmc = ah->src_path_bits & 0x7f;
path->rlid = cpu_to_be16(ah->dlid);
path->static_rate = mthca_get_rate(dev, ah->static_rate, port);
if (ah->ah_flags & IB_AH_GRH) {
if (ah->grh.sgid_index >= dev->limits.gid_table_len) {
mthca_dbg(dev, "sgid_index (%u) too large. max is %d\n",
ah->grh.sgid_index, dev->limits.gid_table_len-1);
return -1;
}
path->g_mylmc |= 1 << 7;
path->mgid_index = ah->grh.sgid_index;
path->hop_limit = ah->grh.hop_limit;
path->sl_tclass_flowlabel =
cpu_to_be32((ah->sl << 28) |
(ah->grh.traffic_class << 20) |
(ah->grh.flow_label));
memcpy(path->rgid, ah->grh.dgid.raw, 16);
} else
path->sl_tclass_flowlabel = cpu_to_be32(ah->sl << 28);
return 0;
}
static int __mthca_modify_qp(struct ib_qp *ibqp,
const struct ib_qp_attr *attr, int attr_mask,
enum ib_qp_state cur_state, enum ib_qp_state new_state)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
struct mthca_mailbox *mailbox;
struct mthca_qp_param *qp_param;
struct mthca_qp_context *qp_context;
u32 sqd_event = 0;
int err = -EINVAL;
mailbox = mthca_alloc_mailbox(dev, GFP_KERNEL);
if (IS_ERR(mailbox)) {
err = PTR_ERR(mailbox);
goto out;
}
qp_param = mailbox->buf;
qp_context = &qp_param->context;
memset(qp_param, 0, sizeof *qp_param);
qp_context->flags = cpu_to_be32((to_mthca_state(new_state) << 28) |
(to_mthca_st(qp->transport) << 16));
qp_context->flags |= cpu_to_be32(MTHCA_QP_BIT_DE);
if (!(attr_mask & IB_QP_PATH_MIG_STATE))
qp_context->flags |= cpu_to_be32(MTHCA_QP_PM_MIGRATED << 11);
else {
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_PM_STATE);
switch (attr->path_mig_state) {
case IB_MIG_MIGRATED:
qp_context->flags |= cpu_to_be32(MTHCA_QP_PM_MIGRATED << 11);
break;
case IB_MIG_REARM:
qp_context->flags |= cpu_to_be32(MTHCA_QP_PM_REARM << 11);
break;
case IB_MIG_ARMED:
qp_context->flags |= cpu_to_be32(MTHCA_QP_PM_ARMED << 11);
break;
}
}
/* leave tavor_sched_queue as 0 */
if (qp->transport == MLX || qp->transport == UD)
qp_context->mtu_msgmax = (IB_MTU_2048 << 5) | 11;
else if (attr_mask & IB_QP_PATH_MTU) {
if (attr->path_mtu < IB_MTU_256 || attr->path_mtu > IB_MTU_2048) {
mthca_dbg(dev, "path MTU (%u) is invalid\n",
attr->path_mtu);
goto out_mailbox;
}
qp_context->mtu_msgmax = (attr->path_mtu << 5) | 31;
}
if (mthca_is_memfree(dev)) {
if (qp->rq.max)
qp_context->rq_size_stride = ilog2(qp->rq.max) << 3;
qp_context->rq_size_stride |= qp->rq.wqe_shift - 4;
if (qp->sq.max)
qp_context->sq_size_stride = ilog2(qp->sq.max) << 3;
qp_context->sq_size_stride |= qp->sq.wqe_shift - 4;
}
/* leave arbel_sched_queue as 0 */
if (qp->ibqp.uobject)
qp_context->usr_page =
cpu_to_be32(to_mucontext(qp->ibqp.uobject->context)->uar.index);
else
qp_context->usr_page = cpu_to_be32(dev->driver_uar.index);
qp_context->local_qpn = cpu_to_be32(qp->qpn);
if (attr_mask & IB_QP_DEST_QPN) {
qp_context->remote_qpn = cpu_to_be32(attr->dest_qp_num);
}
if (qp->transport == MLX)
qp_context->pri_path.port_pkey |=
cpu_to_be32(qp->port << 24);
else {
if (attr_mask & IB_QP_PORT) {
qp_context->pri_path.port_pkey |=
cpu_to_be32(attr->port_num << 24);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_PORT_NUM);
}
}
if (attr_mask & IB_QP_PKEY_INDEX) {
qp_context->pri_path.port_pkey |=
cpu_to_be32(attr->pkey_index);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_PKEY_INDEX);
}
if (attr_mask & IB_QP_RNR_RETRY) {
qp_context->alt_path.rnr_retry = qp_context->pri_path.rnr_retry =
attr->rnr_retry << 5;
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_RNR_RETRY |
MTHCA_QP_OPTPAR_ALT_RNR_RETRY);
}
if (attr_mask & IB_QP_AV) {
if (mthca_path_set(dev, &attr->ah_attr, &qp_context->pri_path,
attr_mask & IB_QP_PORT ? attr->port_num : qp->port))
goto out_mailbox;
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_PRIMARY_ADDR_PATH);
}
if (ibqp->qp_type == IB_QPT_RC &&
cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) {
u8 sched_queue = ibqp->uobject ? 0x2 : 0x1;
if (mthca_is_memfree(dev))
qp_context->rlkey_arbel_sched_queue |= sched_queue;
else
qp_context->tavor_sched_queue |= cpu_to_be32(sched_queue);
qp_param->opt_param_mask |=
cpu_to_be32(MTHCA_QP_OPTPAR_SCHED_QUEUE);
}
if (attr_mask & IB_QP_TIMEOUT) {
qp_context->pri_path.ackto = attr->timeout << 3;
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_ACK_TIMEOUT);
}
if (attr_mask & IB_QP_ALT_PATH) {
if (attr->alt_pkey_index >= dev->limits.pkey_table_len) {
mthca_dbg(dev, "Alternate P_Key index (%u) too large. max is %d\n",
attr->alt_pkey_index, dev->limits.pkey_table_len-1);
goto out_mailbox;
}
if (attr->alt_port_num == 0 || attr->alt_port_num > dev->limits.num_ports) {
mthca_dbg(dev, "Alternate port number (%u) is invalid\n",
attr->alt_port_num);
goto out_mailbox;
}
if (mthca_path_set(dev, &attr->alt_ah_attr, &qp_context->alt_path,
attr->alt_ah_attr.port_num))
goto out_mailbox;
qp_context->alt_path.port_pkey |= cpu_to_be32(attr->alt_pkey_index |
attr->alt_port_num << 24);
qp_context->alt_path.ackto = attr->alt_timeout << 3;
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_ALT_ADDR_PATH);
}
/* leave rdd as 0 */
qp_context->pd = cpu_to_be32(to_mpd(ibqp->pd)->pd_num);
/* leave wqe_base as 0 (we always create an MR based at 0 for WQs) */
qp_context->wqe_lkey = cpu_to_be32(qp->mr.ibmr.lkey);
qp_context->params1 = cpu_to_be32((MTHCA_ACK_REQ_FREQ << 28) |
(MTHCA_FLIGHT_LIMIT << 24) |
MTHCA_QP_BIT_SWE);
if (qp->sq_policy == IB_SIGNAL_ALL_WR)
qp_context->params1 |= cpu_to_be32(MTHCA_QP_BIT_SSC);
if (attr_mask & IB_QP_RETRY_CNT) {
qp_context->params1 |= cpu_to_be32(attr->retry_cnt << 16);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_RETRY_COUNT);
}
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) {
if (attr->max_rd_atomic) {
qp_context->params1 |=
cpu_to_be32(MTHCA_QP_BIT_SRE |
MTHCA_QP_BIT_SAE);
qp_context->params1 |=
cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21);
}
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_SRA_MAX);
}
if (attr_mask & IB_QP_SQ_PSN)
qp_context->next_send_psn = cpu_to_be32(attr->sq_psn);
qp_context->cqn_snd = cpu_to_be32(to_mcq(ibqp->send_cq)->cqn);
if (mthca_is_memfree(dev)) {
qp_context->snd_wqe_base_l = cpu_to_be32(qp->send_wqe_offset);
qp_context->snd_db_index = cpu_to_be32(qp->sq.db_index);
}
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) {
if (attr->max_dest_rd_atomic)
qp_context->params2 |=
cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_RRA_MAX);
}
if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC)) {
qp_context->params2 |= get_hw_access_flags(qp, attr, attr_mask);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_RWE |
MTHCA_QP_OPTPAR_RRE |
MTHCA_QP_OPTPAR_RAE);
}
qp_context->params2 |= cpu_to_be32(MTHCA_QP_BIT_RSC);
if (ibqp->srq)
qp_context->params2 |= cpu_to_be32(MTHCA_QP_BIT_RIC);
if (attr_mask & IB_QP_MIN_RNR_TIMER) {
qp_context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_RNR_TIMEOUT);
}
if (attr_mask & IB_QP_RQ_PSN)
qp_context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn);
qp_context->ra_buff_indx =
cpu_to_be32(dev->qp_table.rdb_base +
((qp->qpn & (dev->limits.num_qps - 1)) * MTHCA_RDB_ENTRY_SIZE <<
dev->qp_table.rdb_shift));
qp_context->cqn_rcv = cpu_to_be32(to_mcq(ibqp->recv_cq)->cqn);
if (mthca_is_memfree(dev))
qp_context->rcv_db_index = cpu_to_be32(qp->rq.db_index);
if (attr_mask & IB_QP_QKEY) {
qp_context->qkey = cpu_to_be32(attr->qkey);
qp_param->opt_param_mask |= cpu_to_be32(MTHCA_QP_OPTPAR_Q_KEY);
}
if (ibqp->srq)
qp_context->srqn = cpu_to_be32(1 << 24 |
to_msrq(ibqp->srq)->srqn);
if (cur_state == IB_QPS_RTS && new_state == IB_QPS_SQD &&
attr_mask & IB_QP_EN_SQD_ASYNC_NOTIFY &&
attr->en_sqd_async_notify)
sqd_event = 1 << 31;
err = mthca_MODIFY_QP(dev, cur_state, new_state, qp->qpn, 0,
mailbox, sqd_event);
if (err) {
mthca_warn(dev, "modify QP %d->%d returned %d.\n",
cur_state, new_state, err);
goto out_mailbox;
}
qp->state = new_state;
if (attr_mask & IB_QP_ACCESS_FLAGS)
qp->atomic_rd_en = attr->qp_access_flags;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
qp->resp_depth = attr->max_dest_rd_atomic;
if (attr_mask & IB_QP_PORT)
qp->port = attr->port_num;
if (attr_mask & IB_QP_ALT_PATH)
qp->alt_port = attr->alt_port_num;
if (is_sqp(dev, qp))
store_attrs(to_msqp(qp), attr, attr_mask);
/*
* If we moved QP0 to RTR, bring the IB link up; if we moved
* QP0 to RESET or ERROR, bring the link back down.
*/
if (is_qp0(dev, qp)) {
if (cur_state != IB_QPS_RTR &&
new_state == IB_QPS_RTR)
init_port(dev, qp->port);
if (cur_state != IB_QPS_RESET &&
cur_state != IB_QPS_ERR &&
(new_state == IB_QPS_RESET ||
new_state == IB_QPS_ERR))
mthca_CLOSE_IB(dev, qp->port);
}
/*
* If we moved a kernel QP to RESET, clean up all old CQ
* entries and reinitialize the QP.
*/
if (new_state == IB_QPS_RESET && !qp->ibqp.uobject) {
mthca_cq_clean(dev, to_mcq(qp->ibqp.recv_cq), qp->qpn,
qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL);
if (qp->ibqp.send_cq != qp->ibqp.recv_cq)
mthca_cq_clean(dev, to_mcq(qp->ibqp.send_cq), qp->qpn, NULL);
mthca_wq_reset(&qp->sq);
qp->sq.last = get_send_wqe(qp, qp->sq.max - 1);
mthca_wq_reset(&qp->rq);
qp->rq.last = get_recv_wqe(qp, qp->rq.max - 1);
if (mthca_is_memfree(dev)) {
*qp->sq.db = 0;
*qp->rq.db = 0;
}
}
out_mailbox:
mthca_free_mailbox(dev, mailbox);
out:
return err;
}
int mthca_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask,
struct ib_udata *udata)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
enum ib_qp_state cur_state, new_state;
int err = -EINVAL;
mutex_lock(&qp->mutex);
if (attr_mask & IB_QP_CUR_STATE) {
cur_state = attr->cur_qp_state;
} else {
spin_lock_irq(&qp->sq.lock);
spin_lock(&qp->rq.lock);
cur_state = qp->state;
spin_unlock(&qp->rq.lock);
spin_unlock_irq(&qp->sq.lock);
}
new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state;
if (!ib_modify_qp_is_ok(cur_state, new_state, ibqp->qp_type, attr_mask)) {
mthca_dbg(dev, "Bad QP transition (transport %d) "
"%d->%d with attr 0x%08x\n",
qp->transport, cur_state, new_state,
attr_mask);
goto out;
}
if ((attr_mask & IB_QP_PKEY_INDEX) &&
attr->pkey_index >= dev->limits.pkey_table_len) {
mthca_dbg(dev, "P_Key index (%u) too large. max is %d\n",
attr->pkey_index, dev->limits.pkey_table_len-1);
goto out;
}
if ((attr_mask & IB_QP_PORT) &&
(attr->port_num == 0 || attr->port_num > dev->limits.num_ports)) {
mthca_dbg(dev, "Port number (%u) is invalid\n", attr->port_num);
goto out;
}
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC &&
attr->max_rd_atomic > dev->limits.max_qp_init_rdma) {
mthca_dbg(dev, "Max rdma_atomic as initiator %u too large (max is %d)\n",
attr->max_rd_atomic, dev->limits.max_qp_init_rdma);
goto out;
}
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC &&
attr->max_dest_rd_atomic > 1 << dev->qp_table.rdb_shift) {
mthca_dbg(dev, "Max rdma_atomic as responder %u too large (max %d)\n",
attr->max_dest_rd_atomic, 1 << dev->qp_table.rdb_shift);
goto out;
}
if (cur_state == new_state && cur_state == IB_QPS_RESET) {
err = 0;
goto out;
}
err = __mthca_modify_qp(ibqp, attr, attr_mask, cur_state, new_state);
out:
mutex_unlock(&qp->mutex);
return err;
}
static int mthca_max_data_size(struct mthca_dev *dev, struct mthca_qp *qp, int desc_sz)
{
/*
* Calculate the maximum size of WQE s/g segments, excluding
* the next segment and other non-data segments.
*/
int max_data_size = desc_sz - sizeof (struct mthca_next_seg);
switch (qp->transport) {
case MLX:
max_data_size -= 2 * sizeof (struct mthca_data_seg);
break;
case UD:
if (mthca_is_memfree(dev))
max_data_size -= sizeof (struct mthca_arbel_ud_seg);
else
max_data_size -= sizeof (struct mthca_tavor_ud_seg);
break;
default:
max_data_size -= sizeof (struct mthca_raddr_seg);
break;
}
return max_data_size;
}
static inline int mthca_max_inline_data(struct mthca_pd *pd, int max_data_size)
{
/* We don't support inline data for kernel QPs (yet). */
return pd->ibpd.uobject ? max_data_size - MTHCA_INLINE_HEADER_SIZE : 0;
}
static void mthca_adjust_qp_caps(struct mthca_dev *dev,
struct mthca_pd *pd,
struct mthca_qp *qp)
{
int max_data_size = mthca_max_data_size(dev, qp,
min(dev->limits.max_desc_sz,
1 << qp->sq.wqe_shift));
qp->max_inline_data = mthca_max_inline_data(pd, max_data_size);
qp->sq.max_gs = min_t(int, dev->limits.max_sg,
max_data_size / sizeof (struct mthca_data_seg));
qp->rq.max_gs = min_t(int, dev->limits.max_sg,
(min(dev->limits.max_desc_sz, 1 << qp->rq.wqe_shift) -
sizeof (struct mthca_next_seg)) /
sizeof (struct mthca_data_seg));
}
/*
* Allocate and register buffer for WQEs. qp->rq.max, sq.max,
* rq.max_gs and sq.max_gs must all be assigned.
* mthca_alloc_wqe_buf will calculate rq.wqe_shift and
* sq.wqe_shift (as well as send_wqe_offset, is_direct, and
* queue)
*/
static int mthca_alloc_wqe_buf(struct mthca_dev *dev,
struct mthca_pd *pd,
struct mthca_qp *qp)
{
int size;
int err = -ENOMEM;
size = sizeof (struct mthca_next_seg) +
qp->rq.max_gs * sizeof (struct mthca_data_seg);
if (size > dev->limits.max_desc_sz)
return -EINVAL;
for (qp->rq.wqe_shift = 6; 1 << qp->rq.wqe_shift < size;
qp->rq.wqe_shift++)
; /* nothing */
size = qp->sq.max_gs * sizeof (struct mthca_data_seg);
switch (qp->transport) {
case MLX:
size += 2 * sizeof (struct mthca_data_seg);
break;
case UD:
size += mthca_is_memfree(dev) ?
sizeof (struct mthca_arbel_ud_seg) :
sizeof (struct mthca_tavor_ud_seg);
break;
case UC:
size += sizeof (struct mthca_raddr_seg);
break;
case RC:
size += sizeof (struct mthca_raddr_seg);
/*
* An atomic op will require an atomic segment, a
* remote address segment and one scatter entry.
*/
size = max_t(int, size,
sizeof (struct mthca_atomic_seg) +
sizeof (struct mthca_raddr_seg) +
sizeof (struct mthca_data_seg));
break;
default:
break;
}
/* Make sure that we have enough space for a bind request */
size = max_t(int, size, sizeof (struct mthca_bind_seg));
size += sizeof (struct mthca_next_seg);
if (size > dev->limits.max_desc_sz)
return -EINVAL;
for (qp->sq.wqe_shift = 6; 1 << qp->sq.wqe_shift < size;
qp->sq.wqe_shift++)
; /* nothing */
qp->send_wqe_offset = ALIGN(qp->rq.max << qp->rq.wqe_shift,
1 << qp->sq.wqe_shift);
/*
* If this is a userspace QP, we don't actually have to
* allocate anything. All we need is to calculate the WQE
* sizes and the send_wqe_offset, so we're done now.
*/
if (pd->ibpd.uobject)
return 0;
size = PAGE_ALIGN(qp->send_wqe_offset +
(qp->sq.max << qp->sq.wqe_shift));
qp->wrid = kmalloc((qp->rq.max + qp->sq.max) * sizeof (u64),
GFP_KERNEL);
if (!qp->wrid)
goto err_out;
err = mthca_buf_alloc(dev, size, MTHCA_MAX_DIRECT_QP_SIZE,
&qp->queue, &qp->is_direct, pd, 0, &qp->mr);
if (err)
goto err_out;
return 0;
err_out:
kfree(qp->wrid);
return err;
}
static void mthca_free_wqe_buf(struct mthca_dev *dev,
struct mthca_qp *qp)
{
mthca_buf_free(dev, PAGE_ALIGN(qp->send_wqe_offset +
(qp->sq.max << qp->sq.wqe_shift)),
&qp->queue, qp->is_direct, &qp->mr);
kfree(qp->wrid);
}
static int mthca_map_memfree(struct mthca_dev *dev,
struct mthca_qp *qp)
{
int ret;
if (mthca_is_memfree(dev)) {
ret = mthca_table_get(dev, dev->qp_table.qp_table, qp->qpn);
if (ret)
return ret;
ret = mthca_table_get(dev, dev->qp_table.eqp_table, qp->qpn);
if (ret)
goto err_qpc;
ret = mthca_table_get(dev, dev->qp_table.rdb_table,
qp->qpn << dev->qp_table.rdb_shift);
if (ret)
goto err_eqpc;
}
return 0;
err_eqpc:
mthca_table_put(dev, dev->qp_table.eqp_table, qp->qpn);
err_qpc:
mthca_table_put(dev, dev->qp_table.qp_table, qp->qpn);
return ret;
}
static void mthca_unmap_memfree(struct mthca_dev *dev,
struct mthca_qp *qp)
{
mthca_table_put(dev, dev->qp_table.rdb_table,
qp->qpn << dev->qp_table.rdb_shift);
mthca_table_put(dev, dev->qp_table.eqp_table, qp->qpn);
mthca_table_put(dev, dev->qp_table.qp_table, qp->qpn);
}
static int mthca_alloc_memfree(struct mthca_dev *dev,
struct mthca_qp *qp)
{
if (mthca_is_memfree(dev)) {
qp->rq.db_index = mthca_alloc_db(dev, MTHCA_DB_TYPE_RQ,
qp->qpn, &qp->rq.db);
if (qp->rq.db_index < 0)
return -ENOMEM;
qp->sq.db_index = mthca_alloc_db(dev, MTHCA_DB_TYPE_SQ,
qp->qpn, &qp->sq.db);
if (qp->sq.db_index < 0) {
mthca_free_db(dev, MTHCA_DB_TYPE_RQ, qp->rq.db_index);
return -ENOMEM;
}
}
return 0;
}
static void mthca_free_memfree(struct mthca_dev *dev,
struct mthca_qp *qp)
{
if (mthca_is_memfree(dev)) {
mthca_free_db(dev, MTHCA_DB_TYPE_SQ, qp->sq.db_index);
mthca_free_db(dev, MTHCA_DB_TYPE_RQ, qp->rq.db_index);
}
}
static int mthca_alloc_qp_common(struct mthca_dev *dev,
struct mthca_pd *pd,
struct mthca_cq *send_cq,
struct mthca_cq *recv_cq,
enum ib_sig_type send_policy,
struct mthca_qp *qp)
{
int ret;
int i;
struct mthca_next_seg *next;
qp->refcount = 1;
init_waitqueue_head(&qp->wait);
mutex_init(&qp->mutex);
qp->state = IB_QPS_RESET;
qp->atomic_rd_en = 0;
qp->resp_depth = 0;
qp->sq_policy = send_policy;
mthca_wq_reset(&qp->sq);
mthca_wq_reset(&qp->rq);
spin_lock_init(&qp->sq.lock);
spin_lock_init(&qp->rq.lock);
ret = mthca_map_memfree(dev, qp);
if (ret)
return ret;
ret = mthca_alloc_wqe_buf(dev, pd, qp);
if (ret) {
mthca_unmap_memfree(dev, qp);
return ret;
}
mthca_adjust_qp_caps(dev, pd, qp);
/*
* If this is a userspace QP, we're done now. The doorbells
* will be allocated and buffers will be initialized in
* userspace.
*/
if (pd->ibpd.uobject)
return 0;
ret = mthca_alloc_memfree(dev, qp);
if (ret) {
mthca_free_wqe_buf(dev, qp);
mthca_unmap_memfree(dev, qp);
return ret;
}
if (mthca_is_memfree(dev)) {
struct mthca_data_seg *scatter;
int size = (sizeof (struct mthca_next_seg) +
qp->rq.max_gs * sizeof (struct mthca_data_seg)) / 16;
for (i = 0; i < qp->rq.max; ++i) {
next = get_recv_wqe(qp, i);
next->nda_op = cpu_to_be32(((i + 1) & (qp->rq.max - 1)) <<
qp->rq.wqe_shift);
next->ee_nds = cpu_to_be32(size);
for (scatter = (void *) (next + 1);
(void *) scatter < (void *) next + (1 << qp->rq.wqe_shift);
++scatter)
scatter->lkey = cpu_to_be32(MTHCA_INVAL_LKEY);
}
for (i = 0; i < qp->sq.max; ++i) {
next = get_send_wqe(qp, i);
next->nda_op = cpu_to_be32((((i + 1) & (qp->sq.max - 1)) <<
qp->sq.wqe_shift) +
qp->send_wqe_offset);
}
} else {
for (i = 0; i < qp->rq.max; ++i) {
next = get_recv_wqe(qp, i);
next->nda_op = htonl((((i + 1) % qp->rq.max) <<
qp->rq.wqe_shift) | 1);
}
}
qp->sq.last = get_send_wqe(qp, qp->sq.max - 1);
qp->rq.last = get_recv_wqe(qp, qp->rq.max - 1);
return 0;
}
static int mthca_set_qp_size(struct mthca_dev *dev, struct ib_qp_cap *cap,
struct mthca_pd *pd, struct mthca_qp *qp)
{
int max_data_size = mthca_max_data_size(dev, qp, dev->limits.max_desc_sz);
/* Sanity check QP size before proceeding */
if (cap->max_send_wr > dev->limits.max_wqes ||
cap->max_recv_wr > dev->limits.max_wqes ||
cap->max_send_sge > dev->limits.max_sg ||
cap->max_recv_sge > dev->limits.max_sg ||
cap->max_inline_data > mthca_max_inline_data(pd, max_data_size))
return -EINVAL;
/*
* For MLX transport we need 2 extra send gather entries:
* one for the header and one for the checksum at the end
*/
if (qp->transport == MLX && cap->max_send_sge + 2 > dev->limits.max_sg)
return -EINVAL;
if (mthca_is_memfree(dev)) {
qp->rq.max = cap->max_recv_wr ?
roundup_pow_of_two(cap->max_recv_wr) : 0;
qp->sq.max = cap->max_send_wr ?
roundup_pow_of_two(cap->max_send_wr) : 0;
} else {
qp->rq.max = cap->max_recv_wr;
qp->sq.max = cap->max_send_wr;
}
qp->rq.max_gs = cap->max_recv_sge;
qp->sq.max_gs = max_t(int, cap->max_send_sge,
ALIGN(cap->max_inline_data + MTHCA_INLINE_HEADER_SIZE,
MTHCA_INLINE_CHUNK_SIZE) /
sizeof (struct mthca_data_seg));
return 0;
}
int mthca_alloc_qp(struct mthca_dev *dev,
struct mthca_pd *pd,
struct mthca_cq *send_cq,
struct mthca_cq *recv_cq,
enum ib_qp_type type,
enum ib_sig_type send_policy,
struct ib_qp_cap *cap,
struct mthca_qp *qp)
{
int err;
switch (type) {
case IB_QPT_RC: qp->transport = RC; break;
case IB_QPT_UC: qp->transport = UC; break;
case IB_QPT_UD: qp->transport = UD; break;
default: return -EINVAL;
}
err = mthca_set_qp_size(dev, cap, pd, qp);
if (err)
return err;
qp->qpn = mthca_alloc(&dev->qp_table.alloc);
if (qp->qpn == -1)
return -ENOMEM;
/* initialize port to zero for error-catching. */
qp->port = 0;
err = mthca_alloc_qp_common(dev, pd, send_cq, recv_cq,
send_policy, qp);
if (err) {
mthca_free(&dev->qp_table.alloc, qp->qpn);
return err;
}
spin_lock_irq(&dev->qp_table.lock);
mthca_array_set(&dev->qp_table.qp,
qp->qpn & (dev->limits.num_qps - 1), qp);
spin_unlock_irq(&dev->qp_table.lock);
return 0;
}
static void mthca_lock_cqs(struct mthca_cq *send_cq, struct mthca_cq *recv_cq)
__acquires(&send_cq->lock) __acquires(&recv_cq->lock)
{
if (send_cq == recv_cq) {
spin_lock_irq(&send_cq->lock);
__acquire(&recv_cq->lock);
} else if (send_cq->cqn < recv_cq->cqn) {
spin_lock_irq(&send_cq->lock);
spin_lock_nested(&recv_cq->lock, SINGLE_DEPTH_NESTING);
} else {
spin_lock_irq(&recv_cq->lock);
spin_lock_nested(&send_cq->lock, SINGLE_DEPTH_NESTING);
}
}
static void mthca_unlock_cqs(struct mthca_cq *send_cq, struct mthca_cq *recv_cq)
__releases(&send_cq->lock) __releases(&recv_cq->lock)
{
if (send_cq == recv_cq) {
__release(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
} else if (send_cq->cqn < recv_cq->cqn) {
spin_unlock(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
} else {
spin_unlock(&send_cq->lock);
spin_unlock_irq(&recv_cq->lock);
}
}
int mthca_alloc_sqp(struct mthca_dev *dev,
struct mthca_pd *pd,
struct mthca_cq *send_cq,
struct mthca_cq *recv_cq,
enum ib_sig_type send_policy,
struct ib_qp_cap *cap,
int qpn,
int port,
struct mthca_sqp *sqp)
{
u32 mqpn = qpn * 2 + dev->qp_table.sqp_start + port - 1;
int err;
sqp->qp.transport = MLX;
err = mthca_set_qp_size(dev, cap, pd, &sqp->qp);
if (err)
return err;
sqp->header_buf_size = sqp->qp.sq.max * MTHCA_UD_HEADER_SIZE;
sqp->header_buf = dma_alloc_coherent(&dev->pdev->dev, sqp->header_buf_size,
&sqp->header_dma, GFP_KERNEL);
if (!sqp->header_buf)
return -ENOMEM;
spin_lock_irq(&dev->qp_table.lock);
if (mthca_array_get(&dev->qp_table.qp, mqpn))
err = -EBUSY;
else
mthca_array_set(&dev->qp_table.qp, mqpn, sqp);
spin_unlock_irq(&dev->qp_table.lock);
if (err)
goto err_out;
sqp->qp.port = port;
sqp->qp.qpn = mqpn;
sqp->qp.transport = MLX;
err = mthca_alloc_qp_common(dev, pd, send_cq, recv_cq,
send_policy, &sqp->qp);
if (err)
goto err_out_free;
atomic_inc(&pd->sqp_count);
return 0;
err_out_free:
/*
* Lock CQs here, so that CQ polling code can do QP lookup
* without taking a lock.
*/
mthca_lock_cqs(send_cq, recv_cq);
spin_lock(&dev->qp_table.lock);
mthca_array_clear(&dev->qp_table.qp, mqpn);
spin_unlock(&dev->qp_table.lock);
mthca_unlock_cqs(send_cq, recv_cq);
err_out:
dma_free_coherent(&dev->pdev->dev, sqp->header_buf_size,
sqp->header_buf, sqp->header_dma);
return err;
}
static inline int get_qp_refcount(struct mthca_dev *dev, struct mthca_qp *qp)
{
int c;
spin_lock_irq(&dev->qp_table.lock);
c = qp->refcount;
spin_unlock_irq(&dev->qp_table.lock);
return c;
}
void mthca_free_qp(struct mthca_dev *dev,
struct mthca_qp *qp)
{
struct mthca_cq *send_cq;
struct mthca_cq *recv_cq;
send_cq = to_mcq(qp->ibqp.send_cq);
recv_cq = to_mcq(qp->ibqp.recv_cq);
/*
* Lock CQs here, so that CQ polling code can do QP lookup
* without taking a lock.
*/
mthca_lock_cqs(send_cq, recv_cq);
spin_lock(&dev->qp_table.lock);
mthca_array_clear(&dev->qp_table.qp,
qp->qpn & (dev->limits.num_qps - 1));
--qp->refcount;
spin_unlock(&dev->qp_table.lock);
mthca_unlock_cqs(send_cq, recv_cq);
wait_event(qp->wait, !get_qp_refcount(dev, qp));
if (qp->state != IB_QPS_RESET)
mthca_MODIFY_QP(dev, qp->state, IB_QPS_RESET, qp->qpn, 0,
NULL, 0);
/*
* If this is a userspace QP, the buffers, MR, CQs and so on
* will be cleaned up in userspace, so all we have to do is
* unref the mem-free tables and free the QPN in our table.
*/
if (!qp->ibqp.uobject) {
mthca_cq_clean(dev, recv_cq, qp->qpn,
qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL);
if (send_cq != recv_cq)
mthca_cq_clean(dev, send_cq, qp->qpn, NULL);
mthca_free_memfree(dev, qp);
mthca_free_wqe_buf(dev, qp);
}
mthca_unmap_memfree(dev, qp);
if (is_sqp(dev, qp)) {
atomic_dec(&(to_mpd(qp->ibqp.pd)->sqp_count));
dma_free_coherent(&dev->pdev->dev,
to_msqp(qp)->header_buf_size,
to_msqp(qp)->header_buf,
to_msqp(qp)->header_dma);
} else
mthca_free(&dev->qp_table.alloc, qp->qpn);
}
/* Create UD header for an MLX send and build a data segment for it */
static int build_mlx_header(struct mthca_dev *dev, struct mthca_sqp *sqp,
int ind, struct ib_send_wr *wr,
struct mthca_mlx_seg *mlx,
struct mthca_data_seg *data)
{
int header_size;
int err;
u16 pkey;
ib_ud_header_init(256, /* assume a MAD */ 1, 0, 0,
mthca_ah_grh_present(to_mah(wr->wr.ud.ah)), 0,
&sqp->ud_header);
err = mthca_read_ah(dev, to_mah(wr->wr.ud.ah), &sqp->ud_header);
if (err)
return err;
mlx->flags &= ~cpu_to_be32(MTHCA_NEXT_SOLICIT | 1);
mlx->flags |= cpu_to_be32((!sqp->qp.ibqp.qp_num ? MTHCA_MLX_VL15 : 0) |
(sqp->ud_header.lrh.destination_lid ==
IB_LID_PERMISSIVE ? MTHCA_MLX_SLR : 0) |
(sqp->ud_header.lrh.service_level << 8));
mlx->rlid = sqp->ud_header.lrh.destination_lid;
mlx->vcrc = 0;
switch (wr->opcode) {
case IB_WR_SEND:
sqp->ud_header.bth.opcode = IB_OPCODE_UD_SEND_ONLY;
sqp->ud_header.immediate_present = 0;
break;
case IB_WR_SEND_WITH_IMM:
sqp->ud_header.bth.opcode = IB_OPCODE_UD_SEND_ONLY_WITH_IMMEDIATE;
sqp->ud_header.immediate_present = 1;
sqp->ud_header.immediate_data = wr->ex.imm_data;
break;
default:
return -EINVAL;
}
sqp->ud_header.lrh.virtual_lane = !sqp->qp.ibqp.qp_num ? 15 : 0;
if (sqp->ud_header.lrh.destination_lid == IB_LID_PERMISSIVE)
sqp->ud_header.lrh.source_lid = IB_LID_PERMISSIVE;
sqp->ud_header.bth.solicited_event = !!(wr->send_flags & IB_SEND_SOLICITED);
if (!sqp->qp.ibqp.qp_num)
ib_get_cached_pkey(&dev->ib_dev, sqp->qp.port,
sqp->pkey_index, &pkey);
else
ib_get_cached_pkey(&dev->ib_dev, sqp->qp.port,
wr->wr.ud.pkey_index, &pkey);
sqp->ud_header.bth.pkey = cpu_to_be16(pkey);
sqp->ud_header.bth.destination_qpn = cpu_to_be32(wr->wr.ud.remote_qpn);
sqp->ud_header.bth.psn = cpu_to_be32((sqp->send_psn++) & ((1 << 24) - 1));
sqp->ud_header.deth.qkey = cpu_to_be32(wr->wr.ud.remote_qkey & 0x80000000 ?
sqp->qkey : wr->wr.ud.remote_qkey);
sqp->ud_header.deth.source_qpn = cpu_to_be32(sqp->qp.ibqp.qp_num);
header_size = ib_ud_header_pack(&sqp->ud_header,
sqp->header_buf +
ind * MTHCA_UD_HEADER_SIZE);
data->byte_count = cpu_to_be32(header_size);
data->lkey = cpu_to_be32(to_mpd(sqp->qp.ibqp.pd)->ntmr.ibmr.lkey);
data->addr = cpu_to_be64(sqp->header_dma +
ind * MTHCA_UD_HEADER_SIZE);
return 0;
}
static inline int mthca_wq_overflow(struct mthca_wq *wq, int nreq,
struct ib_cq *ib_cq)
{
unsigned cur;
struct mthca_cq *cq;
cur = wq->head - wq->tail;
if (likely(cur + nreq < wq->max))
return 0;
cq = to_mcq(ib_cq);
spin_lock(&cq->lock);
cur = wq->head - wq->tail;
spin_unlock(&cq->lock);
return cur + nreq >= wq->max;
}
static __always_inline void set_raddr_seg(struct mthca_raddr_seg *rseg,
u64 remote_addr, u32 rkey)
{
rseg->raddr = cpu_to_be64(remote_addr);
rseg->rkey = cpu_to_be32(rkey);
rseg->reserved = 0;
}
static __always_inline void set_atomic_seg(struct mthca_atomic_seg *aseg,
struct ib_send_wr *wr)
{
if (wr->opcode == IB_WR_ATOMIC_CMP_AND_SWP) {
aseg->swap_add = cpu_to_be64(wr->wr.atomic.swap);
aseg->compare = cpu_to_be64(wr->wr.atomic.compare_add);
} else {
aseg->swap_add = cpu_to_be64(wr->wr.atomic.compare_add);
aseg->compare = 0;
}
}
static void set_tavor_ud_seg(struct mthca_tavor_ud_seg *useg,
struct ib_send_wr *wr)
{
useg->lkey = cpu_to_be32(to_mah(wr->wr.ud.ah)->key);
useg->av_addr = cpu_to_be64(to_mah(wr->wr.ud.ah)->avdma);
useg->dqpn = cpu_to_be32(wr->wr.ud.remote_qpn);
useg->qkey = cpu_to_be32(wr->wr.ud.remote_qkey);
}
static void set_arbel_ud_seg(struct mthca_arbel_ud_seg *useg,
struct ib_send_wr *wr)
{
memcpy(useg->av, to_mah(wr->wr.ud.ah)->av, MTHCA_AV_SIZE);
useg->dqpn = cpu_to_be32(wr->wr.ud.remote_qpn);
useg->qkey = cpu_to_be32(wr->wr.ud.remote_qkey);
}
int mthca_tavor_post_send(struct ib_qp *ibqp, struct ib_send_wr *wr,
struct ib_send_wr **bad_wr)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
void *wqe;
void *prev_wqe;
unsigned long flags;
int err = 0;
int nreq;
int i;
int size;
/*
* f0 and size0 are only used if nreq != 0, and they will
* always be initialized the first time through the main loop
* before nreq is incremented. So nreq cannot become non-zero
* without initializing f0 and size0, and they are in fact
* never used uninitialized.
*/
int uninitialized_var(size0);
u32 uninitialized_var(f0);
int ind;
u8 op0 = 0;
spin_lock_irqsave(&qp->sq.lock, flags);
/* XXX check that state is OK to post send */
ind = qp->sq.next_ind;
for (nreq = 0; wr; ++nreq, wr = wr->next) {
if (mthca_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq)) {
mthca_err(dev, "SQ %06x full (%u head, %u tail,"
" %d max, %d nreq)\n", qp->qpn,
qp->sq.head, qp->sq.tail,
qp->sq.max, nreq);
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
wqe = get_send_wqe(qp, ind);
prev_wqe = qp->sq.last;
qp->sq.last = wqe;
((struct mthca_next_seg *) wqe)->nda_op = 0;
((struct mthca_next_seg *) wqe)->ee_nds = 0;
((struct mthca_next_seg *) wqe)->flags =
((wr->send_flags & IB_SEND_SIGNALED) ?
cpu_to_be32(MTHCA_NEXT_CQ_UPDATE) : 0) |
((wr->send_flags & IB_SEND_SOLICITED) ?
cpu_to_be32(MTHCA_NEXT_SOLICIT) : 0) |
cpu_to_be32(1);
if (wr->opcode == IB_WR_SEND_WITH_IMM ||
wr->opcode == IB_WR_RDMA_WRITE_WITH_IMM)
((struct mthca_next_seg *) wqe)->imm = wr->ex.imm_data;
wqe += sizeof (struct mthca_next_seg);
size = sizeof (struct mthca_next_seg) / 16;
switch (qp->transport) {
case RC:
switch (wr->opcode) {
case IB_WR_ATOMIC_CMP_AND_SWP:
case IB_WR_ATOMIC_FETCH_AND_ADD:
set_raddr_seg(wqe, wr->wr.atomic.remote_addr,
wr->wr.atomic.rkey);
wqe += sizeof (struct mthca_raddr_seg);
set_atomic_seg(wqe, wr);
wqe += sizeof (struct mthca_atomic_seg);
size += (sizeof (struct mthca_raddr_seg) +
sizeof (struct mthca_atomic_seg)) / 16;
break;
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
case IB_WR_RDMA_READ:
set_raddr_seg(wqe, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
wqe += sizeof (struct mthca_raddr_seg);
size += sizeof (struct mthca_raddr_seg) / 16;
break;
default:
/* No extra segments required for sends */
break;
}
break;
case UC:
switch (wr->opcode) {
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
set_raddr_seg(wqe, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
wqe += sizeof (struct mthca_raddr_seg);
size += sizeof (struct mthca_raddr_seg) / 16;
break;
default:
/* No extra segments required for sends */
break;
}
break;
case UD:
set_tavor_ud_seg(wqe, wr);
wqe += sizeof (struct mthca_tavor_ud_seg);
size += sizeof (struct mthca_tavor_ud_seg) / 16;
break;
case MLX:
err = build_mlx_header(dev, to_msqp(qp), ind, wr,
wqe - sizeof (struct mthca_next_seg),
wqe);
if (err) {
*bad_wr = wr;
goto out;
}
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
break;
}
if (wr->num_sge > qp->sq.max_gs) {
mthca_err(dev, "too many gathers\n");
err = -EINVAL;
*bad_wr = wr;
goto out;
}
for (i = 0; i < wr->num_sge; ++i) {
mthca_set_data_seg(wqe, wr->sg_list + i);
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
}
/* Add one more inline data segment for ICRC */
if (qp->transport == MLX) {
((struct mthca_data_seg *) wqe)->byte_count =
cpu_to_be32((1 << 31) | 4);
((u32 *) wqe)[1] = 0;
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
}
qp->wrid[ind + qp->rq.max] = wr->wr_id;
if (wr->opcode >= ARRAY_SIZE(mthca_opcode)) {
mthca_err(dev, "opcode invalid\n");
err = -EINVAL;
*bad_wr = wr;
goto out;
}
((struct mthca_next_seg *) prev_wqe)->nda_op =
cpu_to_be32(((ind << qp->sq.wqe_shift) +
qp->send_wqe_offset) |
mthca_opcode[wr->opcode]);
wmb();
((struct mthca_next_seg *) prev_wqe)->ee_nds =
cpu_to_be32((nreq ? 0 : MTHCA_NEXT_DBD) | size |
((wr->send_flags & IB_SEND_FENCE) ?
MTHCA_NEXT_FENCE : 0));
if (!nreq) {
size0 = size;
op0 = mthca_opcode[wr->opcode];
f0 = wr->send_flags & IB_SEND_FENCE ?
MTHCA_SEND_DOORBELL_FENCE : 0;
}
++ind;
if (unlikely(ind >= qp->sq.max))
ind -= qp->sq.max;
}
out:
if (likely(nreq)) {
wmb();
mthca_write64(((qp->sq.next_ind << qp->sq.wqe_shift) +
qp->send_wqe_offset) | f0 | op0,
(qp->qpn << 8) | size0,
dev->kar + MTHCA_SEND_DOORBELL,
MTHCA_GET_DOORBELL_LOCK(&dev->doorbell_lock));
/*
* Make sure doorbells don't leak out of SQ spinlock
* and reach the HCA out of order:
*/
mmiowb();
}
qp->sq.next_ind = ind;
qp->sq.head += nreq;
spin_unlock_irqrestore(&qp->sq.lock, flags);
return err;
}
int mthca_tavor_post_receive(struct ib_qp *ibqp, struct ib_recv_wr *wr,
struct ib_recv_wr **bad_wr)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
unsigned long flags;
int err = 0;
int nreq;
int i;
int size;
/*
* size0 is only used if nreq != 0, and it will always be
* initialized the first time through the main loop before
* nreq is incremented. So nreq cannot become non-zero
* without initializing size0, and it is in fact never used
* uninitialized.
*/
int uninitialized_var(size0);
int ind;
void *wqe;
void *prev_wqe;
spin_lock_irqsave(&qp->rq.lock, flags);
/* XXX check that state is OK to post receive */
ind = qp->rq.next_ind;
for (nreq = 0; wr; wr = wr->next) {
if (mthca_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) {
mthca_err(dev, "RQ %06x full (%u head, %u tail,"
" %d max, %d nreq)\n", qp->qpn,
qp->rq.head, qp->rq.tail,
qp->rq.max, nreq);
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
wqe = get_recv_wqe(qp, ind);
prev_wqe = qp->rq.last;
qp->rq.last = wqe;
((struct mthca_next_seg *) wqe)->ee_nds =
cpu_to_be32(MTHCA_NEXT_DBD);
((struct mthca_next_seg *) wqe)->flags = 0;
wqe += sizeof (struct mthca_next_seg);
size = sizeof (struct mthca_next_seg) / 16;
if (unlikely(wr->num_sge > qp->rq.max_gs)) {
err = -EINVAL;
*bad_wr = wr;
goto out;
}
for (i = 0; i < wr->num_sge; ++i) {
mthca_set_data_seg(wqe, wr->sg_list + i);
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
}
qp->wrid[ind] = wr->wr_id;
((struct mthca_next_seg *) prev_wqe)->ee_nds =
cpu_to_be32(MTHCA_NEXT_DBD | size);
if (!nreq)
size0 = size;
++ind;
if (unlikely(ind >= qp->rq.max))
ind -= qp->rq.max;
++nreq;
if (unlikely(nreq == MTHCA_TAVOR_MAX_WQES_PER_RECV_DB)) {
nreq = 0;
wmb();
mthca_write64((qp->rq.next_ind << qp->rq.wqe_shift) | size0,
qp->qpn << 8, dev->kar + MTHCA_RECEIVE_DOORBELL,
MTHCA_GET_DOORBELL_LOCK(&dev->doorbell_lock));
qp->rq.next_ind = ind;
qp->rq.head += MTHCA_TAVOR_MAX_WQES_PER_RECV_DB;
}
}
out:
if (likely(nreq)) {
wmb();
mthca_write64((qp->rq.next_ind << qp->rq.wqe_shift) | size0,
qp->qpn << 8 | nreq, dev->kar + MTHCA_RECEIVE_DOORBELL,
MTHCA_GET_DOORBELL_LOCK(&dev->doorbell_lock));
}
qp->rq.next_ind = ind;
qp->rq.head += nreq;
/*
* Make sure doorbells don't leak out of RQ spinlock and reach
* the HCA out of order:
*/
mmiowb();
spin_unlock_irqrestore(&qp->rq.lock, flags);
return err;
}
int mthca_arbel_post_send(struct ib_qp *ibqp, struct ib_send_wr *wr,
struct ib_send_wr **bad_wr)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
u32 dbhi;
void *wqe;
void *prev_wqe;
unsigned long flags;
int err = 0;
int nreq;
int i;
int size;
/*
* f0 and size0 are only used if nreq != 0, and they will
* always be initialized the first time through the main loop
* before nreq is incremented. So nreq cannot become non-zero
* without initializing f0 and size0, and they are in fact
* never used uninitialized.
*/
int uninitialized_var(size0);
u32 uninitialized_var(f0);
int ind;
u8 op0 = 0;
spin_lock_irqsave(&qp->sq.lock, flags);
/* XXX check that state is OK to post send */
ind = qp->sq.head & (qp->sq.max - 1);
for (nreq = 0; wr; ++nreq, wr = wr->next) {
if (unlikely(nreq == MTHCA_ARBEL_MAX_WQES_PER_SEND_DB)) {
nreq = 0;
dbhi = (MTHCA_ARBEL_MAX_WQES_PER_SEND_DB << 24) |
((qp->sq.head & 0xffff) << 8) | f0 | op0;
qp->sq.head += MTHCA_ARBEL_MAX_WQES_PER_SEND_DB;
/*
* Make sure that descriptors are written before
* doorbell record.
*/
wmb();
*qp->sq.db = cpu_to_be32(qp->sq.head & 0xffff);
/*
* Make sure doorbell record is written before we
* write MMIO send doorbell.
*/
wmb();
mthca_write64(dbhi, (qp->qpn << 8) | size0,
dev->kar + MTHCA_SEND_DOORBELL,
MTHCA_GET_DOORBELL_LOCK(&dev->doorbell_lock));
}
if (mthca_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq)) {
mthca_err(dev, "SQ %06x full (%u head, %u tail,"
" %d max, %d nreq)\n", qp->qpn,
qp->sq.head, qp->sq.tail,
qp->sq.max, nreq);
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
wqe = get_send_wqe(qp, ind);
prev_wqe = qp->sq.last;
qp->sq.last = wqe;
((struct mthca_next_seg *) wqe)->flags =
((wr->send_flags & IB_SEND_SIGNALED) ?
cpu_to_be32(MTHCA_NEXT_CQ_UPDATE) : 0) |
((wr->send_flags & IB_SEND_SOLICITED) ?
cpu_to_be32(MTHCA_NEXT_SOLICIT) : 0) |
((wr->send_flags & IB_SEND_IP_CSUM) ?
cpu_to_be32(MTHCA_NEXT_IP_CSUM | MTHCA_NEXT_TCP_UDP_CSUM) : 0) |
cpu_to_be32(1);
if (wr->opcode == IB_WR_SEND_WITH_IMM ||
wr->opcode == IB_WR_RDMA_WRITE_WITH_IMM)
((struct mthca_next_seg *) wqe)->imm = wr->ex.imm_data;
wqe += sizeof (struct mthca_next_seg);
size = sizeof (struct mthca_next_seg) / 16;
switch (qp->transport) {
case RC:
switch (wr->opcode) {
case IB_WR_ATOMIC_CMP_AND_SWP:
case IB_WR_ATOMIC_FETCH_AND_ADD:
set_raddr_seg(wqe, wr->wr.atomic.remote_addr,
wr->wr.atomic.rkey);
wqe += sizeof (struct mthca_raddr_seg);
set_atomic_seg(wqe, wr);
wqe += sizeof (struct mthca_atomic_seg);
size += (sizeof (struct mthca_raddr_seg) +
sizeof (struct mthca_atomic_seg)) / 16;
break;
case IB_WR_RDMA_READ:
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
set_raddr_seg(wqe, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
wqe += sizeof (struct mthca_raddr_seg);
size += sizeof (struct mthca_raddr_seg) / 16;
break;
default:
/* No extra segments required for sends */
break;
}
break;
case UC:
switch (wr->opcode) {
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
set_raddr_seg(wqe, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
wqe += sizeof (struct mthca_raddr_seg);
size += sizeof (struct mthca_raddr_seg) / 16;
break;
default:
/* No extra segments required for sends */
break;
}
break;
case UD:
set_arbel_ud_seg(wqe, wr);
wqe += sizeof (struct mthca_arbel_ud_seg);
size += sizeof (struct mthca_arbel_ud_seg) / 16;
break;
case MLX:
err = build_mlx_header(dev, to_msqp(qp), ind, wr,
wqe - sizeof (struct mthca_next_seg),
wqe);
if (err) {
*bad_wr = wr;
goto out;
}
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
break;
}
if (wr->num_sge > qp->sq.max_gs) {
mthca_err(dev, "too many gathers\n");
err = -EINVAL;
*bad_wr = wr;
goto out;
}
for (i = 0; i < wr->num_sge; ++i) {
mthca_set_data_seg(wqe, wr->sg_list + i);
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
}
/* Add one more inline data segment for ICRC */
if (qp->transport == MLX) {
((struct mthca_data_seg *) wqe)->byte_count =
cpu_to_be32((1 << 31) | 4);
((u32 *) wqe)[1] = 0;
wqe += sizeof (struct mthca_data_seg);
size += sizeof (struct mthca_data_seg) / 16;
}
qp->wrid[ind + qp->rq.max] = wr->wr_id;
if (wr->opcode >= ARRAY_SIZE(mthca_opcode)) {
mthca_err(dev, "opcode invalid\n");
err = -EINVAL;
*bad_wr = wr;
goto out;
}
((struct mthca_next_seg *) prev_wqe)->nda_op =
cpu_to_be32(((ind << qp->sq.wqe_shift) +
qp->send_wqe_offset) |
mthca_opcode[wr->opcode]);
wmb();
((struct mthca_next_seg *) prev_wqe)->ee_nds =
cpu_to_be32(MTHCA_NEXT_DBD | size |
((wr->send_flags & IB_SEND_FENCE) ?
MTHCA_NEXT_FENCE : 0));
if (!nreq) {
size0 = size;
op0 = mthca_opcode[wr->opcode];
f0 = wr->send_flags & IB_SEND_FENCE ?
MTHCA_SEND_DOORBELL_FENCE : 0;
}
++ind;
if (unlikely(ind >= qp->sq.max))
ind -= qp->sq.max;
}
out:
if (likely(nreq)) {
dbhi = (nreq << 24) | ((qp->sq.head & 0xffff) << 8) | f0 | op0;
qp->sq.head += nreq;
/*
* Make sure that descriptors are written before
* doorbell record.
*/
wmb();
*qp->sq.db = cpu_to_be32(qp->sq.head & 0xffff);
/*
* Make sure doorbell record is written before we
* write MMIO send doorbell.
*/
wmb();
mthca_write64(dbhi, (qp->qpn << 8) | size0, dev->kar + MTHCA_SEND_DOORBELL,
MTHCA_GET_DOORBELL_LOCK(&dev->doorbell_lock));
}
/*
* Make sure doorbells don't leak out of SQ spinlock and reach
* the HCA out of order:
*/
mmiowb();
spin_unlock_irqrestore(&qp->sq.lock, flags);
return err;
}
int mthca_arbel_post_receive(struct ib_qp *ibqp, struct ib_recv_wr *wr,
struct ib_recv_wr **bad_wr)
{
struct mthca_dev *dev = to_mdev(ibqp->device);
struct mthca_qp *qp = to_mqp(ibqp);
unsigned long flags;
int err = 0;
int nreq;
int ind;
int i;
void *wqe;
spin_lock_irqsave(&qp->rq.lock, flags);
/* XXX check that state is OK to post receive */
ind = qp->rq.head & (qp->rq.max - 1);
for (nreq = 0; wr; ++nreq, wr = wr->next) {
if (mthca_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) {
mthca_err(dev, "RQ %06x full (%u head, %u tail,"
" %d max, %d nreq)\n", qp->qpn,
qp->rq.head, qp->rq.tail,
qp->rq.max, nreq);
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
wqe = get_recv_wqe(qp, ind);
((struct mthca_next_seg *) wqe)->flags = 0;
wqe += sizeof (struct mthca_next_seg);
if (unlikely(wr->num_sge > qp->rq.max_gs)) {
err = -EINVAL;
*bad_wr = wr;
goto out;
}
for (i = 0; i < wr->num_sge; ++i) {
mthca_set_data_seg(wqe, wr->sg_list + i);
wqe += sizeof (struct mthca_data_seg);
}
if (i < qp->rq.max_gs)
mthca_set_data_seg_inval(wqe);
qp->wrid[ind] = wr->wr_id;
++ind;
if (unlikely(ind >= qp->rq.max))
ind -= qp->rq.max;
}
out:
if (likely(nreq)) {
qp->rq.head += nreq;
/*
* Make sure that descriptors are written before
* doorbell record.
*/
wmb();
*qp->rq.db = cpu_to_be32(qp->rq.head & 0xffff);
}
spin_unlock_irqrestore(&qp->rq.lock, flags);
return err;
}
void mthca_free_err_wqe(struct mthca_dev *dev, struct mthca_qp *qp, int is_send,
int index, int *dbd, __be32 *new_wqe)
{
struct mthca_next_seg *next;
/*
* For SRQs, all receive WQEs generate a CQE, so we're always
* at the end of the doorbell chain.
*/
if (qp->ibqp.srq && !is_send) {
*new_wqe = 0;
return;
}
if (is_send)
next = get_send_wqe(qp, index);
else
next = get_recv_wqe(qp, index);
*dbd = !!(next->ee_nds & cpu_to_be32(MTHCA_NEXT_DBD));
if (next->ee_nds & cpu_to_be32(0x3f))
*new_wqe = (next->nda_op & cpu_to_be32(~0x3f)) |
(next->ee_nds & cpu_to_be32(0x3f));
else
*new_wqe = 0;
}
int mthca_init_qp_table(struct mthca_dev *dev)
{
int err;
int i;
spin_lock_init(&dev->qp_table.lock);
/*
* We reserve 2 extra QPs per port for the special QPs. The
* special QP for port 1 has to be even, so round up.
*/
dev->qp_table.sqp_start = (dev->limits.reserved_qps + 1) & ~1UL;
err = mthca_alloc_init(&dev->qp_table.alloc,
dev->limits.num_qps,
(1 << 24) - 1,
dev->qp_table.sqp_start +
MTHCA_MAX_PORTS * 2);
if (err)
return err;
err = mthca_array_init(&dev->qp_table.qp,
dev->limits.num_qps);
if (err) {
mthca_alloc_cleanup(&dev->qp_table.alloc);
return err;
}
for (i = 0; i < 2; ++i) {
err = mthca_CONF_SPECIAL_QP(dev, i ? IB_QPT_GSI : IB_QPT_SMI,
dev->qp_table.sqp_start + i * 2);
if (err) {
mthca_warn(dev, "CONF_SPECIAL_QP returned "
"%d, aborting.\n", err);
goto err_out;
}
}
return 0;
err_out:
for (i = 0; i < 2; ++i)
mthca_CONF_SPECIAL_QP(dev, i, 0);
mthca_array_cleanup(&dev->qp_table.qp, dev->limits.num_qps);
mthca_alloc_cleanup(&dev->qp_table.alloc);
return err;
}
void mthca_cleanup_qp_table(struct mthca_dev *dev)
{
int i;
for (i = 0; i < 2; ++i)
mthca_CONF_SPECIAL_QP(dev, i, 0);
mthca_array_cleanup(&dev->qp_table.qp, dev->limits.num_qps);
mthca_alloc_cleanup(&dev->qp_table.alloc);
}
| gpl-2.0 |
umiddelb/linux-fslc | drivers/net/phy/ste10Xp.c | 3378 | 3479 | /*
* drivers/net/phy/ste10Xp.c
*
* Driver for STMicroelectronics STe10Xp PHYs
*
* Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*
* Copyright (c) 2008 STMicroelectronics Limited
*
* 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/init.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/phy.h>
#define MII_XCIIS 0x11 /* Configuration Info IRQ & Status Reg */
#define MII_XIE 0x12 /* Interrupt Enable Register */
#define MII_XIE_DEFAULT_MASK 0x0070 /* ANE complete, Remote Fault, Link Down */
#define STE101P_PHY_ID 0x00061c50
#define STE100P_PHY_ID 0x1c040011
static int ste10Xp_config_init(struct phy_device *phydev)
{
int value, err;
/* Software Reset PHY */
value = phy_read(phydev, MII_BMCR);
if (value < 0)
return value;
value |= BMCR_RESET;
err = phy_write(phydev, MII_BMCR, value);
if (err < 0)
return err;
do {
value = phy_read(phydev, MII_BMCR);
} while (value & BMCR_RESET);
return 0;
}
static int ste10Xp_config_intr(struct phy_device *phydev)
{
int err, value;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED) {
/* Enable all STe101P interrupts (PR12) */
err = phy_write(phydev, MII_XIE, MII_XIE_DEFAULT_MASK);
/* clear any pending interrupts */
if (err == 0) {
value = phy_read(phydev, MII_XCIIS);
if (value < 0)
err = value;
}
} else
err = phy_write(phydev, MII_XIE, 0);
return err;
}
static int ste10Xp_ack_interrupt(struct phy_device *phydev)
{
int err = phy_read(phydev, MII_XCIIS);
if (err < 0)
return err;
return 0;
}
static struct phy_driver ste10xp_pdriver[] = {
{
.phy_id = STE101P_PHY_ID,
.phy_id_mask = 0xfffffff0,
.name = "STe101p",
.features = PHY_BASIC_FEATURES | SUPPORTED_Pause,
.flags = PHY_HAS_INTERRUPT,
.config_init = ste10Xp_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = ste10Xp_ack_interrupt,
.config_intr = ste10Xp_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = {.owner = THIS_MODULE,}
}, {
.phy_id = STE100P_PHY_ID,
.phy_id_mask = 0xffffffff,
.name = "STe100p",
.features = PHY_BASIC_FEATURES | SUPPORTED_Pause,
.flags = PHY_HAS_INTERRUPT,
.config_init = ste10Xp_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = ste10Xp_ack_interrupt,
.config_intr = ste10Xp_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = {.owner = THIS_MODULE,}
} };
static int __init ste10Xp_init(void)
{
return phy_drivers_register(ste10xp_pdriver,
ARRAY_SIZE(ste10xp_pdriver));
}
static void __exit ste10Xp_exit(void)
{
phy_drivers_unregister(ste10xp_pdriver,
ARRAY_SIZE(ste10xp_pdriver));
}
module_init(ste10Xp_init);
module_exit(ste10Xp_exit);
static struct mdio_device_id __maybe_unused ste10Xp_tbl[] = {
{ STE101P_PHY_ID, 0xfffffff0 },
{ STE100P_PHY_ID, 0xffffffff },
{ }
};
MODULE_DEVICE_TABLE(mdio, ste10Xp_tbl);
MODULE_DESCRIPTION("STMicroelectronics STe10Xp PHY driver");
MODULE_AUTHOR("Giuseppe Cavallaro <peppe.cavallaro@st.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DooMLoRD/android_kernel_htc_tegra3 | drivers/ata/pata_ns87410.c | 3634 | 5057 | /*
* pata_ns87410.c - National Semiconductor 87410 PATA for new ATA layer
* (C) 2006 Red Hat Inc
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_ns87410"
#define DRV_VERSION "0.4.6"
/**
* ns87410_pre_reset - probe begin
* @link: ATA link
* @deadline: deadline jiffies for the operation
*
* Check enabled ports
*/
static int ns87410_pre_reset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static const struct pci_bits ns87410_enable_bits[] = {
{ 0x43, 1, 0x08, 0x08 },
{ 0x47, 1, 0x08, 0x08 }
};
if (!pci_test_config_bits(pdev, &ns87410_enable_bits[ap->port_no]))
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
/**
* ns87410_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Program timing data. This is kept per channel not per device,
* and only affects the data port.
*/
static void ns87410_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int port = 0x40 + 4 * ap->port_no;
u8 idetcr, idefr;
struct ata_timing at;
static const u8 activebits[15] = {
0, 1, 2, 3, 4,
5, 5, 6, 6, 6,
6, 7, 7, 7, 7
};
static const u8 recoverbits[12] = {
0, 1, 2, 3, 4, 5, 6, 6, 7, 7, 7, 7
};
pci_read_config_byte(pdev, port + 3, &idefr);
if (ata_pio_need_iordy(adev))
idefr |= 0x04; /* IORDY enable */
else
idefr &= ~0x04;
if (ata_timing_compute(adev, adev->pio_mode, &at, 30303, 1) < 0) {
dev_printk(KERN_ERR, &pdev->dev, "unknown mode %d.\n", adev->pio_mode);
return;
}
at.active = clamp_val(at.active, 2, 16) - 2;
at.setup = clamp_val(at.setup, 1, 4) - 1;
at.recover = clamp_val(at.recover, 1, 12) - 1;
idetcr = (at.setup << 6) | (recoverbits[at.recover] << 3) | activebits[at.active];
pci_write_config_byte(pdev, port, idetcr);
pci_write_config_byte(pdev, port + 3, idefr);
/* We use ap->private_data as a pointer to the device currently
loaded for timing */
ap->private_data = adev;
}
/**
* ns87410_qc_issue - command issue
* @qc: command pending
*
* Called when the libata layer is about to issue a command. We wrap
* this interface so that we can load the correct ATA timings if
* necessary.
*/
static unsigned int ns87410_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *adev = qc->dev;
/* If modes have been configured and the channel data is not loaded
then load it. We have to check if pio_mode is set as the core code
does not set adev->pio_mode to XFER_PIO_0 while probing as would be
logical */
if (adev->pio_mode && adev != ap->private_data)
ns87410_set_piomode(ap, adev);
return ata_sff_qc_issue(qc);
}
static struct scsi_host_template ns87410_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations ns87410_port_ops = {
.inherits = &ata_sff_port_ops,
.qc_issue = ns87410_qc_issue,
.cable_detect = ata_cable_40wire,
.set_piomode = ns87410_set_piomode,
.prereset = ns87410_pre_reset,
};
static int ns87410_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO3,
.port_ops = &ns87410_port_ops
};
const struct ata_port_info *ppi[] = { &info, NULL };
return ata_pci_sff_init_one(dev, ppi, &ns87410_sht, NULL, 0);
}
static const struct pci_device_id ns87410[] = {
{ PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_87410), },
{ },
};
static struct pci_driver ns87410_pci_driver = {
.name = DRV_NAME,
.id_table = ns87410,
.probe = ns87410_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init ns87410_init(void)
{
return pci_register_driver(&ns87410_pci_driver);
}
static void __exit ns87410_exit(void)
{
pci_unregister_driver(&ns87410_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for Nat Semi 87410");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, ns87410);
MODULE_VERSION(DRV_VERSION);
module_init(ns87410_init);
module_exit(ns87410_exit);
| gpl-2.0 |
WhiteDawn/Whatever-Flo-Android-Kernel | sound/soc/codecs/stac9766.c | 4914 | 12581 | /*
* stac9766.c -- ALSA SoC STAC9766 codec support
*
* Copyright 2009 Jon Smirl, Digispeaker
* Author: Jon Smirl <jonsmirl@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.
*
* Features:-
*
* o Support for AC97 Codec, S/PDIF
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include "stac9766.h"
#define STAC9766_VERSION "0.10"
/*
* STAC9766 register cache
*/
static const u16 stac9766_reg[] = {
0x6A90, 0x8000, 0x8000, 0x8000, /* 6 */
0x0000, 0x0000, 0x8008, 0x8008, /* e */
0x8808, 0x8808, 0x8808, 0x8808, /* 16 */
0x8808, 0x0000, 0x8000, 0x0000, /* 1e */
0x0000, 0x0000, 0x0000, 0x000f, /* 26 */
0x0a05, 0x0400, 0xbb80, 0x0000, /* 2e */
0x0000, 0xbb80, 0x0000, 0x0000, /* 36 */
0x0000, 0x2000, 0x0000, 0x0100, /* 3e */
0x0000, 0x0000, 0x0080, 0x0000, /* 46 */
0x0000, 0x0000, 0x0003, 0xffff, /* 4e */
0x0000, 0x0000, 0x0000, 0x0000, /* 56 */
0x4000, 0x0000, 0x0000, 0x0000, /* 5e */
0x1201, 0xFFFF, 0xFFFF, 0x0000, /* 66 */
0x0000, 0x0000, 0x0000, 0x0000, /* 6e */
0x0000, 0x0000, 0x0000, 0x0006, /* 76 */
0x0000, 0x0000, 0x0000, 0x0000, /* 7e */
};
static const char *stac9766_record_mux[] = {"Mic", "CD", "Video", "AUX",
"Line", "Stereo Mix", "Mono Mix", "Phone"};
static const char *stac9766_mono_mux[] = {"Mix", "Mic"};
static const char *stac9766_mic_mux[] = {"Mic1", "Mic2"};
static const char *stac9766_SPDIF_mux[] = {"PCM", "ADC Record"};
static const char *stac9766_popbypass_mux[] = {"Normal", "Bypass Mixer"};
static const char *stac9766_record_all_mux[] = {"All analog",
"Analog plus DAC"};
static const char *stac9766_boost1[] = {"0dB", "10dB"};
static const char *stac9766_boost2[] = {"0dB", "20dB"};
static const char *stac9766_stereo_mic[] = {"Off", "On"};
static const struct soc_enum stac9766_record_enum =
SOC_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 8, stac9766_record_mux);
static const struct soc_enum stac9766_mono_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 9, 2, stac9766_mono_mux);
static const struct soc_enum stac9766_mic_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 8, 2, stac9766_mic_mux);
static const struct soc_enum stac9766_SPDIF_enum =
SOC_ENUM_SINGLE(AC97_STAC_DA_CONTROL, 1, 2, stac9766_SPDIF_mux);
static const struct soc_enum stac9766_popbypass_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, stac9766_popbypass_mux);
static const struct soc_enum stac9766_record_all_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 12, 2,
stac9766_record_all_mux);
static const struct soc_enum stac9766_boost1_enum =
SOC_ENUM_SINGLE(AC97_MIC, 6, 2, stac9766_boost1); /* 0/10dB */
static const struct soc_enum stac9766_boost2_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 2, 2, stac9766_boost2); /* 0/20dB */
static const struct soc_enum stac9766_stereo_mic_enum =
SOC_ENUM_SINGLE(AC97_STAC_STEREO_MIC, 2, 1, stac9766_stereo_mic);
static const DECLARE_TLV_DB_LINEAR(master_tlv, -4600, 0);
static const DECLARE_TLV_DB_LINEAR(record_tlv, 0, 2250);
static const DECLARE_TLV_DB_LINEAR(beep_tlv, -4500, 0);
static const DECLARE_TLV_DB_LINEAR(mix_tlv, -3450, 1200);
static const struct snd_kcontrol_new stac9766_snd_ac97_controls[] = {
SOC_DOUBLE_TLV("Speaker Volume", AC97_MASTER, 8, 0, 31, 1, master_tlv),
SOC_SINGLE("Speaker Switch", AC97_MASTER, 15, 1, 1),
SOC_DOUBLE_TLV("Headphone Volume", AC97_HEADPHONE, 8, 0, 31, 1,
master_tlv),
SOC_SINGLE("Headphone Switch", AC97_HEADPHONE, 15, 1, 1),
SOC_SINGLE_TLV("Mono Out Volume", AC97_MASTER_MONO, 0, 31, 1,
master_tlv),
SOC_SINGLE("Mono Out Switch", AC97_MASTER_MONO, 15, 1, 1),
SOC_DOUBLE_TLV("Record Volume", AC97_REC_GAIN, 8, 0, 15, 0, record_tlv),
SOC_SINGLE("Record Switch", AC97_REC_GAIN, 15, 1, 1),
SOC_SINGLE_TLV("Beep Volume", AC97_PC_BEEP, 1, 15, 1, beep_tlv),
SOC_SINGLE("Beep Switch", AC97_PC_BEEP, 15, 1, 1),
SOC_SINGLE("Beep Frequency", AC97_PC_BEEP, 5, 127, 1),
SOC_SINGLE_TLV("Phone Volume", AC97_PHONE, 0, 31, 1, mix_tlv),
SOC_SINGLE("Phone Switch", AC97_PHONE, 15, 1, 1),
SOC_ENUM("Mic Boost1", stac9766_boost1_enum),
SOC_ENUM("Mic Boost2", stac9766_boost2_enum),
SOC_SINGLE_TLV("Mic Volume", AC97_MIC, 0, 31, 1, mix_tlv),
SOC_SINGLE("Mic Switch", AC97_MIC, 15, 1, 1),
SOC_ENUM("Stereo Mic", stac9766_stereo_mic_enum),
SOC_DOUBLE_TLV("Line Volume", AC97_LINE, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Line Switch", AC97_LINE, 15, 1, 1),
SOC_DOUBLE_TLV("CD Volume", AC97_CD, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("CD Switch", AC97_CD, 15, 1, 1),
SOC_DOUBLE_TLV("AUX Volume", AC97_AUX, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("AUX Switch", AC97_AUX, 15, 1, 1),
SOC_DOUBLE_TLV("Video Volume", AC97_VIDEO, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Video Switch", AC97_VIDEO, 15, 1, 1),
SOC_DOUBLE_TLV("DAC Volume", AC97_PCM, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("DAC Switch", AC97_PCM, 15, 1, 1),
SOC_SINGLE("Loopback Test Switch", AC97_GENERAL_PURPOSE, 7, 1, 0),
SOC_SINGLE("3D Volume", AC97_3D_CONTROL, 3, 2, 1),
SOC_SINGLE("3D Switch", AC97_GENERAL_PURPOSE, 13, 1, 0),
SOC_ENUM("SPDIF Mux", stac9766_SPDIF_enum),
SOC_ENUM("Mic1/2 Mux", stac9766_mic_enum),
SOC_ENUM("Record All Mux", stac9766_record_all_enum),
SOC_ENUM("Record Mux", stac9766_record_enum),
SOC_ENUM("Mono Mux", stac9766_mono_enum),
SOC_ENUM("Pop Bypass Mux", stac9766_popbypass_enum),
};
static int stac9766_ac97_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int val)
{
u16 *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
soc_ac97_ops.write(codec->ac97, reg, val);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return 0;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
soc_ac97_ops.write(codec->ac97, reg, val);
cache[reg / 2] = val;
return 0;
}
static unsigned int stac9766_ac97_read(struct snd_soc_codec *codec,
unsigned int reg)
{
u16 val = 0, *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
val = soc_ac97_ops.read(codec->ac97, reg - AC97_STAC_PAGE0);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return val;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
if (reg == AC97_RESET || reg == AC97_GPIO_STATUS ||
reg == AC97_INT_PAGING || reg == AC97_VENDOR_ID1 ||
reg == AC97_VENDOR_ID2) {
val = soc_ac97_ops.read(codec->ac97, reg);
return val;
}
return cache[reg / 2];
}
static int ac97_analog_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x1; /* enable variable rate audio */
vra &= ~0x4; /* disable SPDIF output */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
reg = AC97_PCM_FRONT_DAC_RATE;
else
reg = AC97_PCM_LR_ADC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int ac97_digital_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
stac9766_ac97_write(codec, AC97_SPDIF, 0x2002);
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x5; /* Enable VRA and SPDIF out */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
reg = AC97_PCM_FRONT_DAC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int stac9766_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON: /* full On */
case SND_SOC_BIAS_PREPARE: /* partial On */
case SND_SOC_BIAS_STANDBY: /* Off, with power */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0x0000);
break;
case SND_SOC_BIAS_OFF: /* Off, without power */
/* disable everything including AC link */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0xffff);
break;
}
codec->dapm.bias_level = level;
return 0;
}
static int stac9766_reset(struct snd_soc_codec *codec, int try_warm)
{
if (try_warm && soc_ac97_ops.warm_reset) {
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) == stac9766_reg[0])
return 1;
}
soc_ac97_ops.reset(codec->ac97);
if (soc_ac97_ops.warm_reset)
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) != stac9766_reg[0])
return -EIO;
return 0;
}
static int stac9766_codec_suspend(struct snd_soc_codec *codec)
{
stac9766_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int stac9766_codec_resume(struct snd_soc_codec *codec)
{
u16 id, reset;
reset = 0;
/* give the codec an AC97 warm reset to start the link */
reset:
if (reset > 5) {
printk(KERN_ERR "stac9766 failed to resume");
return -EIO;
}
codec->ac97->bus->ops->warm_reset(codec->ac97);
id = soc_ac97_ops.read(codec->ac97, AC97_VENDOR_ID2);
if (id != 0x4c13) {
stac9766_reset(codec, 0);
reset++;
goto reset;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static const struct snd_soc_dai_ops stac9766_dai_ops_analog = {
.prepare = ac97_analog_prepare,
};
static const struct snd_soc_dai_ops stac9766_dai_ops_digital = {
.prepare = ac97_digital_prepare,
};
static struct snd_soc_dai_driver stac9766_dai[] = {
{
.name = "stac9766-hifi-analog",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
.capture = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
/* alsa ops */
.ops = &stac9766_dai_ops_analog,
},
{
.name = "stac9766-hifi-IEC958",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 IEC958",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_32000 | \
SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE,
},
/* alsa ops */
.ops = &stac9766_dai_ops_digital,
}
};
static int stac9766_codec_probe(struct snd_soc_codec *codec)
{
int ret = 0;
printk(KERN_INFO "STAC9766 SoC Audio Codec %s\n", STAC9766_VERSION);
ret = snd_soc_new_ac97_codec(codec, &soc_ac97_ops, 0);
if (ret < 0)
goto codec_err;
/* do a cold reset for the controller and then try
* a warm reset followed by an optional cold reset for codec */
stac9766_reset(codec, 0);
ret = stac9766_reset(codec, 1);
if (ret < 0) {
printk(KERN_ERR "Failed to reset STAC9766: AC97 link error\n");
goto codec_err;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_add_codec_controls(codec, stac9766_snd_ac97_controls,
ARRAY_SIZE(stac9766_snd_ac97_controls));
return 0;
codec_err:
snd_soc_free_ac97_codec(codec);
return ret;
}
static int stac9766_codec_remove(struct snd_soc_codec *codec)
{
snd_soc_free_ac97_codec(codec);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_stac9766 = {
.write = stac9766_ac97_write,
.read = stac9766_ac97_read,
.set_bias_level = stac9766_set_bias_level,
.probe = stac9766_codec_probe,
.remove = stac9766_codec_remove,
.suspend = stac9766_codec_suspend,
.resume = stac9766_codec_resume,
.reg_cache_size = ARRAY_SIZE(stac9766_reg),
.reg_word_size = sizeof(u16),
.reg_cache_step = 2,
.reg_cache_default = stac9766_reg,
};
static __devinit int stac9766_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_stac9766, stac9766_dai, ARRAY_SIZE(stac9766_dai));
}
static int __devexit stac9766_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver stac9766_codec_driver = {
.driver = {
.name = "stac9766-codec",
.owner = THIS_MODULE,
},
.probe = stac9766_probe,
.remove = __devexit_p(stac9766_remove),
};
module_platform_driver(stac9766_codec_driver);
MODULE_DESCRIPTION("ASoC stac9766 driver");
MODULE_AUTHOR("Jon Smirl <jonsmirl@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wimpknocker/lge-kernel-lproj | arch/arm/plat-mxc/devices/platform-mx2-camera.c | 4914 | 2340 | /*
* Copyright (C) 2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include <mach/hardware.h>
#include <mach/devices-common.h>
#define imx_mx2_camera_data_entry_single(soc) \
{ \
.iobasecsi = soc ## _CSI_BASE_ADDR, \
.iosizecsi = SZ_4K, \
.irqcsi = soc ## _INT_CSI, \
}
#define imx_mx2_camera_data_entry_single_emma(soc) \
{ \
.iobasecsi = soc ## _CSI_BASE_ADDR, \
.iosizecsi = SZ_32, \
.irqcsi = soc ## _INT_CSI, \
.iobaseemmaprp = soc ## _EMMAPRP_BASE_ADDR, \
.iosizeemmaprp = SZ_32, \
.irqemmaprp = soc ## _INT_EMMAPRP, \
}
#ifdef CONFIG_SOC_IMX25
const struct imx_mx2_camera_data imx25_mx2_camera_data __initconst =
imx_mx2_camera_data_entry_single(MX25);
#endif /* ifdef CONFIG_SOC_IMX25 */
#ifdef CONFIG_SOC_IMX27
const struct imx_mx2_camera_data imx27_mx2_camera_data __initconst =
imx_mx2_camera_data_entry_single_emma(MX27);
#endif /* ifdef CONFIG_SOC_IMX27 */
struct platform_device *__init imx_add_mx2_camera(
const struct imx_mx2_camera_data *data,
const struct mx2_camera_platform_data *pdata)
{
struct resource res[] = {
{
.start = data->iobasecsi,
.end = data->iobasecsi + data->iosizecsi - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irqcsi,
.end = data->irqcsi,
.flags = IORESOURCE_IRQ,
}, {
.start = data->iobaseemmaprp,
.end = data->iobaseemmaprp + data->iosizeemmaprp - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irqemmaprp,
.end = data->irqemmaprp,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device_dmamask("mx2-camera", 0,
res, data->iobaseemmaprp ? 4 : 2,
pdata, sizeof(*pdata), DMA_BIT_MASK(32));
}
struct platform_device *__init imx_add_mx2_emmaprp(
const struct imx_mx2_camera_data *data)
{
struct resource res[] = {
{
.start = data->iobaseemmaprp,
.end = data->iobaseemmaprp + data->iosizeemmaprp - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irqemmaprp,
.end = data->irqemmaprp,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device_dmamask("m2m-emmaprp", 0,
res, 2, NULL, 0, DMA_BIT_MASK(32));
}
| gpl-2.0 |
sleekmason/LG-V510-Kitkat | arch/arm/mach-imx/mm-imx1.c | 5426 | 1723 | /*
* author: Sascha Hauer
* Created: april 20th, 2004
* Copyright: Synertronixx GmbH
*
* Common code for i.MX1 machines
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <asm/mach/map.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/irqs.h>
#include <mach/iomux-v1.h>
static struct map_desc imx_io_desc[] __initdata = {
imx_map_entry(MX1, IO, MT_DEVICE),
};
void __init mx1_map_io(void)
{
iotable_init(imx_io_desc, ARRAY_SIZE(imx_io_desc));
}
void __init imx1_init_early(void)
{
mxc_set_cpu_type(MXC_CPU_MX1);
mxc_arch_reset_init(MX1_IO_ADDRESS(MX1_WDT_BASE_ADDR));
imx_iomuxv1_init(MX1_IO_ADDRESS(MX1_GPIO_BASE_ADDR),
MX1_NUM_GPIO_PORT);
}
void __init mx1_init_irq(void)
{
mxc_init_irq(MX1_IO_ADDRESS(MX1_AVIC_BASE_ADDR));
}
void __init imx1_soc_init(void)
{
mxc_register_gpio("imx1-gpio", 0, MX1_GPIO1_BASE_ADDR, SZ_256,
MX1_GPIO_INT_PORTA, 0);
mxc_register_gpio("imx1-gpio", 1, MX1_GPIO2_BASE_ADDR, SZ_256,
MX1_GPIO_INT_PORTB, 0);
mxc_register_gpio("imx1-gpio", 2, MX1_GPIO3_BASE_ADDR, SZ_256,
MX1_GPIO_INT_PORTC, 0);
mxc_register_gpio("imx1-gpio", 3, MX1_GPIO4_BASE_ADDR, SZ_256,
MX1_GPIO_INT_PORTD, 0);
}
| gpl-2.0 |
LIFECorp/kernel | arch/arm/mach-nomadik/clock.c | 7986 | 1437 | /*
* linux/arch/arm/mach-nomadik/clock.c
*
* Copyright (C) 2009 Alessandro Rubini
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/clkdev.h>
#include "clock.h"
/*
* The nomadik board uses generic clocks, but the serial pl011 file
* calls clk_enable(), clk_disable(), clk_get_rate(), so we provide them
*/
unsigned long clk_get_rate(struct clk *clk)
{
return clk->rate;
}
EXPORT_SYMBOL(clk_get_rate);
/* enable and disable do nothing */
int clk_enable(struct clk *clk)
{
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_disable);
static struct clk clk_24 = {
.rate = 2400000,
};
static struct clk clk_48 = {
.rate = 48 * 1000 * 1000,
};
/*
* Catch-all default clock to satisfy drivers using the clk API. We don't
* model the actual hardware clocks yet.
*/
static struct clk clk_default;
#define CLK(_clk, dev) \
{ \
.clk = _clk, \
.dev_id = dev, \
}
static struct clk_lookup lookups[] = {
{
.con_id = "apb_pclk",
.clk = &clk_default,
},
CLK(&clk_24, "mtu0"),
CLK(&clk_24, "mtu1"),
CLK(&clk_48, "uart0"),
CLK(&clk_48, "uart1"),
CLK(&clk_default, "gpio.0"),
CLK(&clk_default, "gpio.1"),
CLK(&clk_default, "gpio.2"),
CLK(&clk_default, "gpio.3"),
CLK(&clk_default, "rng"),
};
int __init clk_init(void)
{
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
return 0;
}
| gpl-2.0 |
high1/android_kernel_htc_golfu_wifi | drivers/staging/comedi/drivers/gsc_hpdi.c | 7986 | 30722 | /*
comedi/drivers/gsc_hpdi.c
This is a driver for the General Standards Corporation High
Speed Parallel Digital Interface rs485 boards.
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Copyright (C) 2003 Coherent Imaging Systems
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-8 David A. Schleef <ds@schleef.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.
************************************************************************/
/*
Driver: gsc_hpdi
Description: General Standards Corporation High
Speed Parallel Digital Interface rs485 boards
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Status: only receive mode works, transmit not supported
Updated: 2003-02-20
Devices: [General Standards Corporation] PCI-HPDI32 (gsc_hpdi),
PMC-HPDI32
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
There are some additional hpdi models available from GSC for which
support could be added to this driver.
*/
#include <linux/interrupt.h>
#include "../comedidev.h"
#include <linux/delay.h>
#include "comedi_pci.h"
#include "plx9080.h"
#include "comedi_fc.h"
static int hpdi_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int hpdi_detach(struct comedi_device *dev);
static void abort_dma(struct comedi_device *dev, unsigned int channel);
static int hpdi_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int hpdi_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_cmd *cmd);
static int hpdi_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static irqreturn_t handle_interrupt(int irq, void *d);
static int dio_config_block_size(struct comedi_device *dev, unsigned int *data);
#undef HPDI_DEBUG /* disable debugging messages */
/* #define HPDI_DEBUG enable debugging code */
#ifdef HPDI_DEBUG
#define DEBUG_PRINT(format, args...) printk(format , ## args)
#else
#define DEBUG_PRINT(format, args...)
#endif
#define TIMER_BASE 50 /* 20MHz master clock */
#define DMA_BUFFER_SIZE 0x10000
#define NUM_DMA_BUFFERS 4
#define NUM_DMA_DESCRIPTORS 256
/* indices of base address regions */
enum base_address_regions {
PLX9080_BADDRINDEX = 0,
HPDI_BADDRINDEX = 2,
};
enum hpdi_registers {
FIRMWARE_REV_REG = 0x0,
BOARD_CONTROL_REG = 0x4,
BOARD_STATUS_REG = 0x8,
TX_PROG_ALMOST_REG = 0xc,
RX_PROG_ALMOST_REG = 0x10,
FEATURES_REG = 0x14,
FIFO_REG = 0x18,
TX_STATUS_COUNT_REG = 0x1c,
TX_LINE_VALID_COUNT_REG = 0x20,
TX_LINE_INVALID_COUNT_REG = 0x24,
RX_STATUS_COUNT_REG = 0x28,
RX_LINE_COUNT_REG = 0x2c,
INTERRUPT_CONTROL_REG = 0x30,
INTERRUPT_STATUS_REG = 0x34,
TX_CLOCK_DIVIDER_REG = 0x38,
TX_FIFO_SIZE_REG = 0x40,
RX_FIFO_SIZE_REG = 0x44,
TX_FIFO_WORDS_REG = 0x48,
RX_FIFO_WORDS_REG = 0x4c,
INTERRUPT_EDGE_LEVEL_REG = 0x50,
INTERRUPT_POLARITY_REG = 0x54,
};
int command_channel_valid(unsigned int channel)
{
if (channel == 0 || channel > 6) {
printk(KERN_WARNING
"gsc_hpdi: bug! invalid cable command channel\n");
return 0;
}
return 1;
}
/* bit definitions */
enum firmware_revision_bits {
FEATURES_REG_PRESENT_BIT = 0x8000,
};
int firmware_revision(uint32_t fwr_bits)
{
return fwr_bits & 0xff;
}
int pcb_revision(uint32_t fwr_bits)
{
return (fwr_bits >> 8) & 0xff;
}
int hpdi_subid(uint32_t fwr_bits)
{
return (fwr_bits >> 16) & 0xff;
}
enum board_control_bits {
BOARD_RESET_BIT = 0x1, /* wait 10usec before accessing fifos */
TX_FIFO_RESET_BIT = 0x2,
RX_FIFO_RESET_BIT = 0x4,
TX_ENABLE_BIT = 0x10,
RX_ENABLE_BIT = 0x20,
DEMAND_DMA_DIRECTION_TX_BIT = 0x40,
/* for ch 0, ch 1 can only transmit (when present) */
LINE_VALID_ON_STATUS_VALID_BIT = 0x80,
START_TX_BIT = 0x10,
CABLE_THROTTLE_ENABLE_BIT = 0x20,
TEST_MODE_ENABLE_BIT = 0x80000000,
};
uint32_t command_discrete_output_bits(unsigned int channel, int output,
int output_value)
{
uint32_t bits = 0;
if (command_channel_valid(channel) == 0)
return 0;
if (output) {
bits |= 0x1 << (16 + channel);
if (output_value)
bits |= 0x1 << (24 + channel);
} else
bits |= 0x1 << (24 + channel);
return bits;
}
enum board_status_bits {
COMMAND_LINE_STATUS_MASK = 0x7f,
TX_IN_PROGRESS_BIT = 0x80,
TX_NOT_EMPTY_BIT = 0x100,
TX_NOT_ALMOST_EMPTY_BIT = 0x200,
TX_NOT_ALMOST_FULL_BIT = 0x400,
TX_NOT_FULL_BIT = 0x800,
RX_NOT_EMPTY_BIT = 0x1000,
RX_NOT_ALMOST_EMPTY_BIT = 0x2000,
RX_NOT_ALMOST_FULL_BIT = 0x4000,
RX_NOT_FULL_BIT = 0x8000,
BOARD_JUMPER0_INSTALLED_BIT = 0x10000,
BOARD_JUMPER1_INSTALLED_BIT = 0x20000,
TX_OVERRUN_BIT = 0x200000,
RX_UNDERRUN_BIT = 0x400000,
RX_OVERRUN_BIT = 0x800000,
};
uint32_t almost_full_bits(unsigned int num_words)
{
/* XXX need to add or subtract one? */
return (num_words << 16) & 0xff0000;
}
uint32_t almost_empty_bits(unsigned int num_words)
{
return num_words & 0xffff;
}
unsigned int almost_full_num_words(uint32_t bits)
{
/* XXX need to add or subtract one? */
return (bits >> 16) & 0xffff;
}
unsigned int almost_empty_num_words(uint32_t bits)
{
return bits & 0xffff;
}
enum features_bits {
FIFO_SIZE_PRESENT_BIT = 0x1,
FIFO_WORDS_PRESENT_BIT = 0x2,
LEVEL_EDGE_INTERRUPTS_PRESENT_BIT = 0x4,
GPIO_SUPPORTED_BIT = 0x8,
PLX_DMA_CH1_SUPPORTED_BIT = 0x10,
OVERRUN_UNDERRUN_SUPPORTED_BIT = 0x20,
};
enum interrupt_sources {
FRAME_VALID_START_INTR = 0,
FRAME_VALID_END_INTR = 1,
TX_FIFO_EMPTY_INTR = 8,
TX_FIFO_ALMOST_EMPTY_INTR = 9,
TX_FIFO_ALMOST_FULL_INTR = 10,
TX_FIFO_FULL_INTR = 11,
RX_EMPTY_INTR = 12,
RX_ALMOST_EMPTY_INTR = 13,
RX_ALMOST_FULL_INTR = 14,
RX_FULL_INTR = 15,
};
int command_intr_source(unsigned int channel)
{
if (command_channel_valid(channel) == 0)
channel = 1;
return channel + 1;
}
uint32_t intr_bit(int interrupt_source)
{
return 0x1 << interrupt_source;
}
uint32_t tx_clock_divisor_bits(unsigned int divisor)
{
return divisor & 0xff;
}
unsigned int fifo_size(uint32_t fifo_size_bits)
{
return fifo_size_bits & 0xfffff;
}
unsigned int fifo_words(uint32_t fifo_words_bits)
{
return fifo_words_bits & 0xfffff;
}
uint32_t intr_edge_bit(int interrupt_source)
{
return 0x1 << interrupt_source;
}
uint32_t intr_active_high_bit(int interrupt_source)
{
return 0x1 << interrupt_source;
}
struct hpdi_board {
char *name;
int device_id; /* pci device id */
int subdevice_id; /* pci subdevice id */
};
static const struct hpdi_board hpdi_boards[] = {
{
.name = "pci-hpdi32",
.device_id = PCI_DEVICE_ID_PLX_9080,
.subdevice_id = 0x2400,
},
#if 0
{
.name = "pxi-hpdi32",
.device_id = 0x9656,
.subdevice_id = 0x2705,
},
#endif
};
static DEFINE_PCI_DEVICE_TABLE(hpdi_pci_table) = {
{
PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9080, PCI_VENDOR_ID_PLX,
0x2400, 0, 0, 0}, {
0}
};
MODULE_DEVICE_TABLE(pci, hpdi_pci_table);
static inline struct hpdi_board *board(const struct comedi_device *dev)
{
return (struct hpdi_board *)dev->board_ptr;
}
struct hpdi_private {
struct pci_dev *hw_dev; /* pointer to board's pci_dev struct */
/* base addresses (physical) */
resource_size_t plx9080_phys_iobase;
resource_size_t hpdi_phys_iobase;
/* base addresses (ioremapped) */
void *plx9080_iobase;
void *hpdi_iobase;
uint32_t *dio_buffer[NUM_DMA_BUFFERS]; /* dma buffers */
/* physical addresses of dma buffers */
dma_addr_t dio_buffer_phys_addr[NUM_DMA_BUFFERS];
/* array of dma descriptors read by plx9080, allocated to get proper
* alignment */
struct plx_dma_desc *dma_desc;
/* physical address of dma descriptor array */
dma_addr_t dma_desc_phys_addr;
unsigned int num_dma_descriptors;
/* pointer to start of buffers indexed by descriptor */
uint32_t *desc_dio_buffer[NUM_DMA_DESCRIPTORS];
/* index of the dma descriptor that is currently being used */
volatile unsigned int dma_desc_index;
unsigned int tx_fifo_size;
unsigned int rx_fifo_size;
volatile unsigned long dio_count;
/* software copies of values written to hpdi registers */
volatile uint32_t bits[24];
/* number of bytes at which to generate COMEDI_CB_BLOCK events */
volatile unsigned int block_size;
unsigned dio_config_output:1;
};
static inline struct hpdi_private *priv(struct comedi_device *dev)
{
return dev->private;
}
static struct comedi_driver driver_hpdi = {
.driver_name = "gsc_hpdi",
.module = THIS_MODULE,
.attach = hpdi_attach,
.detach = hpdi_detach,
};
static int __devinit driver_hpdi_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_hpdi.driver_name);
}
static void __devexit driver_hpdi_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_hpdi_pci_driver = {
.id_table = hpdi_pci_table,
.probe = &driver_hpdi_pci_probe,
.remove = __devexit_p(&driver_hpdi_pci_remove)
};
static int __init driver_hpdi_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_hpdi);
if (retval < 0)
return retval;
driver_hpdi_pci_driver.name = (char *)driver_hpdi.driver_name;
return pci_register_driver(&driver_hpdi_pci_driver);
}
static void __exit driver_hpdi_cleanup_module(void)
{
pci_unregister_driver(&driver_hpdi_pci_driver);
comedi_driver_unregister(&driver_hpdi);
}
module_init(driver_hpdi_init_module);
module_exit(driver_hpdi_cleanup_module);
static int dio_config_insn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
priv(dev)->dio_config_output = 1;
return insn->n;
break;
case INSN_CONFIG_DIO_INPUT:
priv(dev)->dio_config_output = 0;
return insn->n;
break;
case INSN_CONFIG_DIO_QUERY:
data[1] =
priv(dev)->dio_config_output ? COMEDI_OUTPUT : COMEDI_INPUT;
return insn->n;
break;
case INSN_CONFIG_BLOCK_SIZE:
return dio_config_block_size(dev, data);
break;
default:
break;
}
return -EINVAL;
}
static void disable_plx_interrupts(struct comedi_device *dev)
{
writel(0, priv(dev)->plx9080_iobase + PLX_INTRCS_REG);
}
/* initialize plx9080 chip */
static void init_plx9080(struct comedi_device *dev)
{
uint32_t bits;
void *plx_iobase = priv(dev)->plx9080_iobase;
/* plx9080 dump */
DEBUG_PRINT(" plx interrupt status 0x%x\n",
readl(plx_iobase + PLX_INTRCS_REG));
DEBUG_PRINT(" plx id bits 0x%x\n", readl(plx_iobase + PLX_ID_REG));
DEBUG_PRINT(" plx control reg 0x%x\n",
readl(priv(dev)->plx9080_iobase + PLX_CONTROL_REG));
DEBUG_PRINT(" plx revision 0x%x\n",
readl(plx_iobase + PLX_REVISION_REG));
DEBUG_PRINT(" plx dma channel 0 mode 0x%x\n",
readl(plx_iobase + PLX_DMA0_MODE_REG));
DEBUG_PRINT(" plx dma channel 1 mode 0x%x\n",
readl(plx_iobase + PLX_DMA1_MODE_REG));
DEBUG_PRINT(" plx dma channel 0 pci address 0x%x\n",
readl(plx_iobase + PLX_DMA0_PCI_ADDRESS_REG));
DEBUG_PRINT(" plx dma channel 0 local address 0x%x\n",
readl(plx_iobase + PLX_DMA0_LOCAL_ADDRESS_REG));
DEBUG_PRINT(" plx dma channel 0 transfer size 0x%x\n",
readl(plx_iobase + PLX_DMA0_TRANSFER_SIZE_REG));
DEBUG_PRINT(" plx dma channel 0 descriptor 0x%x\n",
readl(plx_iobase + PLX_DMA0_DESCRIPTOR_REG));
DEBUG_PRINT(" plx dma channel 0 command status 0x%x\n",
readb(plx_iobase + PLX_DMA0_CS_REG));
DEBUG_PRINT(" plx dma channel 0 threshold 0x%x\n",
readl(plx_iobase + PLX_DMA0_THRESHOLD_REG));
DEBUG_PRINT(" plx bigend 0x%x\n", readl(plx_iobase + PLX_BIGEND_REG));
#ifdef __BIG_ENDIAN
bits = BIGEND_DMA0 | BIGEND_DMA1;
#else
bits = 0;
#endif
writel(bits, priv(dev)->plx9080_iobase + PLX_BIGEND_REG);
disable_plx_interrupts(dev);
abort_dma(dev, 0);
abort_dma(dev, 1);
/* configure dma0 mode */
bits = 0;
/* enable ready input */
bits |= PLX_DMA_EN_READYIN_BIT;
/* enable dma chaining */
bits |= PLX_EN_CHAIN_BIT;
/* enable interrupt on dma done
* (probably don't need this, since chain never finishes) */
bits |= PLX_EN_DMA_DONE_INTR_BIT;
/* don't increment local address during transfers
* (we are transferring from a fixed fifo register) */
bits |= PLX_LOCAL_ADDR_CONST_BIT;
/* route dma interrupt to pci bus */
bits |= PLX_DMA_INTR_PCI_BIT;
/* enable demand mode */
bits |= PLX_DEMAND_MODE_BIT;
/* enable local burst mode */
bits |= PLX_DMA_LOCAL_BURST_EN_BIT;
bits |= PLX_LOCAL_BUS_32_WIDE_BITS;
writel(bits, plx_iobase + PLX_DMA0_MODE_REG);
}
/* Allocate and initialize the subdevice structures.
*/
static int setup_subdevices(struct comedi_device *dev)
{
struct comedi_subdevice *s;
if (alloc_subdevices(dev, 1) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog input subdevice */
dev->read_subdev = s;
/* dev->write_subdev = s; */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags =
SDF_READABLE | SDF_WRITEABLE | SDF_LSAMPL | SDF_CMD_READ;
s->n_chan = 32;
s->len_chanlist = 32;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_config = dio_config_insn;
s->do_cmd = hpdi_cmd;
s->do_cmdtest = hpdi_cmd_test;
s->cancel = hpdi_cancel;
return 0;
}
static int init_hpdi(struct comedi_device *dev)
{
uint32_t plx_intcsr_bits;
writel(BOARD_RESET_BIT, priv(dev)->hpdi_iobase + BOARD_CONTROL_REG);
udelay(10);
writel(almost_empty_bits(32) | almost_full_bits(32),
priv(dev)->hpdi_iobase + RX_PROG_ALMOST_REG);
writel(almost_empty_bits(32) | almost_full_bits(32),
priv(dev)->hpdi_iobase + TX_PROG_ALMOST_REG);
priv(dev)->tx_fifo_size = fifo_size(readl(priv(dev)->hpdi_iobase +
TX_FIFO_SIZE_REG));
priv(dev)->rx_fifo_size = fifo_size(readl(priv(dev)->hpdi_iobase +
RX_FIFO_SIZE_REG));
writel(0, priv(dev)->hpdi_iobase + INTERRUPT_CONTROL_REG);
/* enable interrupts */
plx_intcsr_bits =
ICS_AERR | ICS_PERR | ICS_PIE | ICS_PLIE | ICS_PAIE | ICS_LIE |
ICS_DMA0_E;
writel(plx_intcsr_bits, priv(dev)->plx9080_iobase + PLX_INTRCS_REG);
return 0;
}
/* setup dma descriptors so a link completes every 'transfer_size' bytes */
static int setup_dma_descriptors(struct comedi_device *dev,
unsigned int transfer_size)
{
unsigned int buffer_index, buffer_offset;
uint32_t next_bits = PLX_DESC_IN_PCI_BIT | PLX_INTR_TERM_COUNT |
PLX_XFER_LOCAL_TO_PCI;
unsigned int i;
if (transfer_size > DMA_BUFFER_SIZE)
transfer_size = DMA_BUFFER_SIZE;
transfer_size -= transfer_size % sizeof(uint32_t);
if (transfer_size == 0)
return -1;
DEBUG_PRINT(" transfer_size %i\n", transfer_size);
DEBUG_PRINT(" descriptors at 0x%lx\n",
(unsigned long)priv(dev)->dma_desc_phys_addr);
buffer_offset = 0;
buffer_index = 0;
for (i = 0; i < NUM_DMA_DESCRIPTORS &&
buffer_index < NUM_DMA_BUFFERS; i++) {
priv(dev)->dma_desc[i].pci_start_addr =
cpu_to_le32(priv(dev)->dio_buffer_phys_addr[buffer_index] +
buffer_offset);
priv(dev)->dma_desc[i].local_start_addr = cpu_to_le32(FIFO_REG);
priv(dev)->dma_desc[i].transfer_size =
cpu_to_le32(transfer_size);
priv(dev)->dma_desc[i].next =
cpu_to_le32((priv(dev)->dma_desc_phys_addr + (i +
1) *
sizeof(priv(dev)->dma_desc[0])) | next_bits);
priv(dev)->desc_dio_buffer[i] =
priv(dev)->dio_buffer[buffer_index] +
(buffer_offset / sizeof(uint32_t));
buffer_offset += transfer_size;
if (transfer_size + buffer_offset > DMA_BUFFER_SIZE) {
buffer_offset = 0;
buffer_index++;
}
DEBUG_PRINT(" desc %i\n", i);
DEBUG_PRINT(" start addr virt 0x%p, phys 0x%lx\n",
priv(dev)->desc_dio_buffer[i],
(unsigned long)priv(dev)->dma_desc[i].
pci_start_addr);
DEBUG_PRINT(" next 0x%lx\n",
(unsigned long)priv(dev)->dma_desc[i].next);
}
priv(dev)->num_dma_descriptors = i;
/* fix last descriptor to point back to first */
priv(dev)->dma_desc[i - 1].next =
cpu_to_le32(priv(dev)->dma_desc_phys_addr | next_bits);
DEBUG_PRINT(" desc %i next fixup 0x%lx\n", i - 1,
(unsigned long)priv(dev)->dma_desc[i - 1].next);
priv(dev)->block_size = transfer_size;
return transfer_size;
}
static int hpdi_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct pci_dev *pcidev;
int i;
int retval;
printk(KERN_WARNING "comedi%d: gsc_hpdi\n", dev->minor);
if (alloc_private(dev, sizeof(struct hpdi_private)) < 0)
return -ENOMEM;
pcidev = NULL;
for (i = 0; i < ARRAY_SIZE(hpdi_boards) &&
dev->board_ptr == NULL; i++) {
do {
pcidev = pci_get_subsys(PCI_VENDOR_ID_PLX,
hpdi_boards[i].device_id,
PCI_VENDOR_ID_PLX,
hpdi_boards[i].subdevice_id,
pcidev);
/* was a particular bus/slot requested? */
if (it->options[0] || it->options[1]) {
/* are we on the wrong bus/slot? */
if (pcidev->bus->number != it->options[0] ||
PCI_SLOT(pcidev->devfn) != it->options[1])
continue;
}
if (pcidev) {
priv(dev)->hw_dev = pcidev;
dev->board_ptr = hpdi_boards + i;
break;
}
} while (pcidev != NULL);
}
if (dev->board_ptr == NULL) {
printk(KERN_WARNING "gsc_hpdi: no hpdi card found\n");
return -EIO;
}
printk(KERN_WARNING
"gsc_hpdi: found %s on bus %i, slot %i\n", board(dev)->name,
pcidev->bus->number, PCI_SLOT(pcidev->devfn));
if (comedi_pci_enable(pcidev, driver_hpdi.driver_name)) {
printk(KERN_WARNING
" failed enable PCI device and request regions\n");
return -EIO;
}
pci_set_master(pcidev);
/* Initialize dev->board_name */
dev->board_name = board(dev)->name;
priv(dev)->plx9080_phys_iobase =
pci_resource_start(pcidev, PLX9080_BADDRINDEX);
priv(dev)->hpdi_phys_iobase =
pci_resource_start(pcidev, HPDI_BADDRINDEX);
/* remap, won't work with 2.0 kernels but who cares */
priv(dev)->plx9080_iobase = ioremap(priv(dev)->plx9080_phys_iobase,
pci_resource_len(pcidev,
PLX9080_BADDRINDEX));
priv(dev)->hpdi_iobase =
ioremap(priv(dev)->hpdi_phys_iobase,
pci_resource_len(pcidev, HPDI_BADDRINDEX));
if (!priv(dev)->plx9080_iobase || !priv(dev)->hpdi_iobase) {
printk(KERN_WARNING " failed to remap io memory\n");
return -ENOMEM;
}
DEBUG_PRINT(" plx9080 remapped to 0x%p\n", priv(dev)->plx9080_iobase);
DEBUG_PRINT(" hpdi remapped to 0x%p\n", priv(dev)->hpdi_iobase);
init_plx9080(dev);
/* get irq */
if (request_irq(pcidev->irq, handle_interrupt, IRQF_SHARED,
driver_hpdi.driver_name, dev)) {
printk(KERN_WARNING
" unable to allocate irq %u\n", pcidev->irq);
return -EINVAL;
}
dev->irq = pcidev->irq;
printk(KERN_WARNING " irq %u\n", dev->irq);
/* alocate pci dma buffers */
for (i = 0; i < NUM_DMA_BUFFERS; i++) {
priv(dev)->dio_buffer[i] =
pci_alloc_consistent(priv(dev)->hw_dev, DMA_BUFFER_SIZE,
&priv(dev)->dio_buffer_phys_addr[i]);
DEBUG_PRINT("dio_buffer at virt 0x%p, phys 0x%lx\n",
priv(dev)->dio_buffer[i],
(unsigned long)priv(dev)->dio_buffer_phys_addr[i]);
}
/* allocate dma descriptors */
priv(dev)->dma_desc = pci_alloc_consistent(priv(dev)->hw_dev,
sizeof(struct plx_dma_desc) *
NUM_DMA_DESCRIPTORS,
&priv(dev)->
dma_desc_phys_addr);
if (priv(dev)->dma_desc_phys_addr & 0xf) {
printk(KERN_WARNING
" dma descriptors not quad-word aligned (bug)\n");
return -EIO;
}
retval = setup_dma_descriptors(dev, 0x1000);
if (retval < 0)
return retval;
retval = setup_subdevices(dev);
if (retval < 0)
return retval;
return init_hpdi(dev);
}
static int hpdi_detach(struct comedi_device *dev)
{
unsigned int i;
printk(KERN_WARNING "comedi%d: gsc_hpdi: remove\n", dev->minor);
if (dev->irq)
free_irq(dev->irq, dev);
if ((priv(dev)) && (priv(dev)->hw_dev)) {
if (priv(dev)->plx9080_iobase) {
disable_plx_interrupts(dev);
iounmap((void *)priv(dev)->plx9080_iobase);
}
if (priv(dev)->hpdi_iobase)
iounmap((void *)priv(dev)->hpdi_iobase);
/* free pci dma buffers */
for (i = 0; i < NUM_DMA_BUFFERS; i++) {
if (priv(dev)->dio_buffer[i])
pci_free_consistent(priv(dev)->hw_dev,
DMA_BUFFER_SIZE,
priv(dev)->
dio_buffer[i],
priv
(dev)->dio_buffer_phys_addr
[i]);
}
/* free dma descriptors */
if (priv(dev)->dma_desc)
pci_free_consistent(priv(dev)->hw_dev,
sizeof(struct plx_dma_desc)
* NUM_DMA_DESCRIPTORS,
priv(dev)->dma_desc,
priv(dev)->
dma_desc_phys_addr);
if (priv(dev)->hpdi_phys_iobase)
comedi_pci_disable(priv(dev)->hw_dev);
pci_dev_put(priv(dev)->hw_dev);
}
return 0;
}
static int dio_config_block_size(struct comedi_device *dev, unsigned int *data)
{
unsigned int requested_block_size;
int retval;
requested_block_size = data[1];
retval = setup_dma_descriptors(dev, requested_block_size);
if (retval < 0)
return retval;
data[1] = retval;
return 2;
}
static int di_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
int i;
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_NOW;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually
* compatible */
/* uniqueness check */
if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (!cmd->chanlist_len) {
cmd->chanlist_len = 32;
err++;
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
switch (cmd->stop_src) {
case TRIG_COUNT:
if (!cmd->stop_arg) {
cmd->stop_arg = 1;
err++;
}
break;
case TRIG_NONE:
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
break;
default:
break;
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (err)
return 4;
if (!cmd->chanlist)
return 0;
for (i = 1; i < cmd->chanlist_len; i++) {
if (CR_CHAN(cmd->chanlist[i]) != i) {
/* XXX could support 8 or 16 channels */
comedi_error(dev,
"chanlist must be ch 0 to 31 in order");
err++;
break;
}
}
if (err)
return 5;
return 0;
}
static int hpdi_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
if (priv(dev)->dio_config_output)
return -EINVAL;
else
return di_cmd_test(dev, s, cmd);
}
static inline void hpdi_writel(struct comedi_device *dev, uint32_t bits,
unsigned int offset)
{
writel(bits | priv(dev)->bits[offset / sizeof(uint32_t)],
priv(dev)->hpdi_iobase + offset);
}
static int di_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
uint32_t bits;
unsigned long flags;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
hpdi_writel(dev, RX_FIFO_RESET_BIT, BOARD_CONTROL_REG);
DEBUG_PRINT("hpdi: in di_cmd\n");
abort_dma(dev, 0);
priv(dev)->dma_desc_index = 0;
/* These register are supposedly unused during chained dma,
* but I have found that left over values from last operation
* occasionally cause problems with transfer of first dma
* block. Initializing them to zero seems to fix the problem. */
writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_TRANSFER_SIZE_REG);
writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_PCI_ADDRESS_REG);
writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_LOCAL_ADDRESS_REG);
/* give location of first dma descriptor */
bits =
priv(dev)->dma_desc_phys_addr | PLX_DESC_IN_PCI_BIT |
PLX_INTR_TERM_COUNT | PLX_XFER_LOCAL_TO_PCI;
writel(bits, priv(dev)->plx9080_iobase + PLX_DMA0_DESCRIPTOR_REG);
/* spinlock for plx dma control/status reg */
spin_lock_irqsave(&dev->spinlock, flags);
/* enable dma transfer */
writeb(PLX_DMA_EN_BIT | PLX_DMA_START_BIT | PLX_CLEAR_DMA_INTR_BIT,
priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
if (cmd->stop_src == TRIG_COUNT)
priv(dev)->dio_count = cmd->stop_arg;
else
priv(dev)->dio_count = 1;
/* clear over/under run status flags */
writel(RX_UNDERRUN_BIT | RX_OVERRUN_BIT,
priv(dev)->hpdi_iobase + BOARD_STATUS_REG);
/* enable interrupts */
writel(intr_bit(RX_FULL_INTR),
priv(dev)->hpdi_iobase + INTERRUPT_CONTROL_REG);
DEBUG_PRINT("hpdi: starting rx\n");
hpdi_writel(dev, RX_ENABLE_BIT, BOARD_CONTROL_REG);
return 0;
}
static int hpdi_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
if (priv(dev)->dio_config_output)
return -EINVAL;
else
return di_cmd(dev, s);
}
static void drain_dma_buffers(struct comedi_device *dev, unsigned int channel)
{
struct comedi_async *async = dev->read_subdev->async;
uint32_t next_transfer_addr;
int j;
int num_samples = 0;
void *pci_addr_reg;
if (channel)
pci_addr_reg =
priv(dev)->plx9080_iobase + PLX_DMA1_PCI_ADDRESS_REG;
else
pci_addr_reg =
priv(dev)->plx9080_iobase + PLX_DMA0_PCI_ADDRESS_REG;
/* loop until we have read all the full buffers */
j = 0;
for (next_transfer_addr = readl(pci_addr_reg);
(next_transfer_addr <
le32_to_cpu(priv(dev)->dma_desc[priv(dev)->dma_desc_index].
pci_start_addr)
|| next_transfer_addr >=
le32_to_cpu(priv(dev)->dma_desc[priv(dev)->dma_desc_index].
pci_start_addr) + priv(dev)->block_size)
&& j < priv(dev)->num_dma_descriptors; j++) {
/* transfer data from dma buffer to comedi buffer */
num_samples = priv(dev)->block_size / sizeof(uint32_t);
if (async->cmd.stop_src == TRIG_COUNT) {
if (num_samples > priv(dev)->dio_count)
num_samples = priv(dev)->dio_count;
priv(dev)->dio_count -= num_samples;
}
cfc_write_array_to_buffer(dev->read_subdev,
priv(dev)->desc_dio_buffer[priv(dev)->
dma_desc_index],
num_samples * sizeof(uint32_t));
priv(dev)->dma_desc_index++;
priv(dev)->dma_desc_index %= priv(dev)->num_dma_descriptors;
DEBUG_PRINT("next desc addr 0x%lx\n", (unsigned long)
priv(dev)->dma_desc[priv(dev)->dma_desc_index].
next);
DEBUG_PRINT("pci addr reg 0x%x\n", next_transfer_addr);
}
/* XXX check for buffer overrun somehow */
}
static irqreturn_t handle_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async = s->async;
uint32_t hpdi_intr_status, hpdi_board_status;
uint32_t plx_status;
uint32_t plx_bits;
uint8_t dma0_status, dma1_status;
unsigned long flags;
if (!dev->attached)
return IRQ_NONE;
plx_status = readl(priv(dev)->plx9080_iobase + PLX_INTRCS_REG);
if ((plx_status & (ICS_DMA0_A | ICS_DMA1_A | ICS_LIA)) == 0)
return IRQ_NONE;
hpdi_intr_status = readl(priv(dev)->hpdi_iobase + INTERRUPT_STATUS_REG);
hpdi_board_status = readl(priv(dev)->hpdi_iobase + BOARD_STATUS_REG);
async->events = 0;
if (hpdi_intr_status) {
DEBUG_PRINT("hpdi: intr status 0x%x, ", hpdi_intr_status);
writel(hpdi_intr_status,
priv(dev)->hpdi_iobase + INTERRUPT_STATUS_REG);
}
/* spin lock makes sure no one else changes plx dma control reg */
spin_lock_irqsave(&dev->spinlock, flags);
dma0_status = readb(priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
if (plx_status & ICS_DMA0_A) { /* dma chan 0 interrupt */
writeb((dma0_status & PLX_DMA_EN_BIT) | PLX_CLEAR_DMA_INTR_BIT,
priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
DEBUG_PRINT("dma0 status 0x%x\n", dma0_status);
if (dma0_status & PLX_DMA_EN_BIT)
drain_dma_buffers(dev, 0);
DEBUG_PRINT(" cleared dma ch0 interrupt\n");
}
spin_unlock_irqrestore(&dev->spinlock, flags);
/* spin lock makes sure no one else changes plx dma control reg */
spin_lock_irqsave(&dev->spinlock, flags);
dma1_status = readb(priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
if (plx_status & ICS_DMA1_A) { /* XXX *//* dma chan 1 interrupt */
writeb((dma1_status & PLX_DMA_EN_BIT) | PLX_CLEAR_DMA_INTR_BIT,
priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
DEBUG_PRINT("dma1 status 0x%x\n", dma1_status);
DEBUG_PRINT(" cleared dma ch1 interrupt\n");
}
spin_unlock_irqrestore(&dev->spinlock, flags);
/* clear possible plx9080 interrupt sources */
if (plx_status & ICS_LDIA) { /* clear local doorbell interrupt */
plx_bits = readl(priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
writel(plx_bits, priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
DEBUG_PRINT(" cleared local doorbell bits 0x%x\n", plx_bits);
}
if (hpdi_board_status & RX_OVERRUN_BIT) {
comedi_error(dev, "rx fifo overrun");
async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
DEBUG_PRINT("dma0_status 0x%x\n",
(int)readb(priv(dev)->plx9080_iobase +
PLX_DMA0_CS_REG));
}
if (hpdi_board_status & RX_UNDERRUN_BIT) {
comedi_error(dev, "rx fifo underrun");
async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
}
if (priv(dev)->dio_count == 0)
async->events |= COMEDI_CB_EOA;
DEBUG_PRINT("board status 0x%x, ", hpdi_board_status);
DEBUG_PRINT("plx status 0x%x\n", plx_status);
if (async->events)
DEBUG_PRINT(" events 0x%x\n", async->events);
cfc_handle_events(dev, s);
return IRQ_HANDLED;
}
static void abort_dma(struct comedi_device *dev, unsigned int channel)
{
unsigned long flags;
/* spinlock for plx dma control/status reg */
spin_lock_irqsave(&dev->spinlock, flags);
plx9080_abort_dma(priv(dev)->plx9080_iobase, channel);
spin_unlock_irqrestore(&dev->spinlock, flags);
}
static int hpdi_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
hpdi_writel(dev, 0, BOARD_CONTROL_REG);
writel(0, priv(dev)->hpdi_iobase + INTERRUPT_CONTROL_REG);
abort_dma(dev, 0);
return 0;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
dohclude/android_kernel_htc_msm8960 | drivers/staging/cxt1e1/pmcc4_drv.c | 51 | 57708 | /*
* $Id: pmcc4_drv.c,v 3.1 2007/08/15 23:32:17 rickd PMCC4_3_1B $
*/
/*-----------------------------------------------------------------------------
* pmcc4_drv.c -
*
* Copyright (C) 2007 One Stop Systems, Inc.
* Copyright (C) 2002-2006 SBE, 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.
*
* For further information, contact via email: support@onestopsystems.com
* One Stop Systems, Inc. Escondido, California U.S.A.
*-----------------------------------------------------------------------------
* RCS info:
* RCS revision: $Revision: 3.1 $
* Last changed on $Date: 2007/08/15 23:32:17 $
* Changed by $Author: rickd $
*-----------------------------------------------------------------------------
* $Log: pmcc4_drv.c,v $
* Revision 3.1 2007/08/15 23:32:17 rickd
* Use 'if 0' instead of GNU comment delimeter to avoid line wrap induced compiler errors.
*
* Revision 3.0 2007/08/15 22:19:55 rickd
* Correct sizeof() castings and pi->regram to support 64bit compatibility.
*
* Revision 2.10 2006/04/21 00:56:40 rickd
* workqueue files now prefixed with <sbecom> prefix.
*
* Revision 2.9 2005/11/01 19:22:49 rickd
* Add sanity checks against max_port for ioctl functions.
*
* Revision 2.8 2005/10/27 18:59:25 rickd
* Code cleanup. Default channel config to HDLC_FCS16.
*
* Revision 2.7 2005/10/18 18:16:30 rickd
* Further NCOMM code repairs - (1) interrupt matrix usage inconsistant
* for indexing into nciInterrupt[][], code missing double parameters.
* (2) check input of ncomm interrupt registration cardID for correct
* boundary values.
*
* Revision 2.6 2005/10/17 23:55:28 rickd
* Initial port of NCOMM support patches from original work found
* in pmc_c4t1e1 as updated by NCOMM. Ref: CONFIG_SBE_PMCC4_NCOMM.
* Corrected NCOMMs wanpmcC4T1E1_getBaseAddress() to correctly handle
* multiple boards.
*
* Revision 2.5 2005/10/13 23:01:28 rickd
* Correct panic for illegal address reference w/in get_brdinfo on
* first_if/last_if name acquistion under Linux 2.6
*
* Revision 2.4 2005/10/13 21:20:19 rickd
* Correction of c4_cleanup() wherein next should be acquired before
* ci_t structure is free'd.
*
* Revision 2.3 2005/10/13 19:20:10 rickd
* Correct driver removal cleanup code for multiple boards.
*
* Revision 2.2 2005/10/11 18:34:04 rickd
* New routine added to determine number of ports (comets) on board.
*
* Revision 2.1 2005/10/05 00:48:13 rickd
* Add some RX activation trace code.
*
* Revision 2.0 2005/09/28 00:10:06 rickd
* Implement 2.6 workqueue for TX/RX restart. Correction to
* hardware register boundary checks allows expanded access of MUSYCC.
* Implement new musycc reg&bits namings.
*
*-----------------------------------------------------------------------------
*/
char OSSIid_pmcc4_drvc[] =
"@(#)pmcc4_drv.c - $Revision: 3.1 $ (c) Copyright 2002-2007 One Stop Systems, Inc.";
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#if defined (__FreeBSD__) || defined (__NetBSD__)
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/errno.h>
#else
#include <linux/types.h>
#include "pmcc4_sysdep.h"
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/sched.h> /* include for timer */
#include <linux/timer.h> /* include for timer */
#include <linux/hdlc.h>
#include <asm/io.h>
#endif
#include "sbecom_inline_linux.h"
#include "libsbew.h"
#include "pmcc4_private.h"
#include "pmcc4.h"
#include "pmcc4_ioctls.h"
#include "musycc.h"
#include "comet.h"
#include "sbe_bid.h"
#ifdef SBE_INCLUDE_SYMBOLS
#define STATIC
#else
#define STATIC static
#endif
#define KERN_WARN KERN_WARNING
/* forward references */
status_t c4_wk_chan_init (mpi_t *, mch_t *);
void c4_wq_port_cleanup (mpi_t *);
status_t c4_wq_port_init (mpi_t *);
int c4_loop_port (ci_t *, int, u_int8_t);
status_t c4_set_port (ci_t *, int);
status_t musycc_chan_down (ci_t *, int);
u_int32_t musycc_chan_proto (int);
status_t musycc_dump_ring (ci_t *, unsigned int);
status_t __init musycc_init (ci_t *);
void musycc_init_mdt (mpi_t *);
void musycc_serv_req (mpi_t *, u_int32_t);
void musycc_update_timeslots (mpi_t *);
extern void musycc_update_tx_thp (mch_t *);
extern int log_level;
extern int cxt1e1_max_mru;
extern int cxt1e1_max_mtu;
extern int max_rxdesc_used, max_rxdesc_default;
extern int max_txdesc_used, max_txdesc_default;
#if defined (__powerpc__)
extern void *memset (void *s, int c, size_t n);
#endif
int drvr_state = SBE_DRVR_INIT;
ci_t *c4_list = 0;
ci_t *CI; /* dummy pointer to board ZEROE's data -
* DEBUG USAGE */
void
sbecom_set_loglevel (int d)
{
/*
* The code within the following -if- clause is a backdoor debug facility
* which can be used to display the state of a board's channel.
*/
if (d > LOG_DEBUG)
{
unsigned int channum = d - (LOG_DEBUG + 1); /* convert to ZERO
* relativity */
(void) musycc_dump_ring ((ci_t *) CI, channum); /* CI implies support
* for card 0 only */
} else
{
if (log_level != d)
{
pr_info("log level changed from %d to %d\n", log_level, d);
log_level = d; /* set new */
} else
pr_info("log level is %d\n", log_level);
}
}
mch_t *
c4_find_chan (int channum)
{
ci_t *ci;
mch_t *ch;
int portnum, gchan;
for (ci = c4_list; ci; ci = ci->next)
for (portnum = 0; portnum < ci->max_port; portnum++)
for (gchan = 0; gchan < MUSYCC_NCHANS; gchan++)
{
if ((ch = ci->port[portnum].chan[gchan]))
{
if ((ch->state != UNASSIGNED) &&
(ch->channum == channum))
return (ch);
}
}
return 0;
}
ci_t *__init
c4_new (void *hi)
{
ci_t *ci;
#ifdef SBE_MAP_DEBUG
pr_warning("c4_new() entered, ci needs %u.\n",
(unsigned int) sizeof (ci_t));
#endif
ci = (ci_t *) OS_kmalloc (sizeof (ci_t));
if (ci)
{
ci->hdw_info = hi;
ci->state = C_INIT; /* mark as hardware not available */
ci->next = c4_list;
c4_list = ci;
ci->brdno = ci->next ? ci->next->brdno + 1 : 0;
} else
pr_warning("failed CI malloc, size %u.\n",
(unsigned int) sizeof (ci_t));
if (CI == 0)
CI = ci; /* DEBUG, only board 0 usage */
return ci;
}
/***
* Check port state and set LED states using watchdog or ioctl...
* also check for in-band SF loopback commands (& cause results if they are there)
*
* Alarm function depends on comet bits indicating change in
* link status (linkMask) to keep the link status indication straight.
*
* Indications are only LED and system log -- except when ioctl is invoked.
*
* "alarmed" record (a.k.a. copyVal, in some cases below) decodes as:
*
* RMAI (E1 only) 0x100
* alarm LED on 0x80
* link LED on 0x40
* link returned 0x20 (link was down, now it's back and 'port get' hasn't run)
* change in LED 0x10 (update LED register because value has changed)
* link is down 0x08
* YelAlm(RAI) 0x04
* RedAlm 0x02
* AIS(blue)Alm 0x01
*
* note "link has returned" indication is reset on read
* (e.g. by use of the c4_control port get command)
*/
#define sbeLinkMask 0x41 /* change in signal status (lost/recovered) +
* state */
#define sbeLinkChange 0x40
#define sbeLinkDown 0x01
#define sbeAlarmsMask 0x07 /* red / yellow / blue alarm conditions */
#define sbeE1AlarmsMask 0x107 /* alarm conditions */
#define COMET_LBCMD_READ 0x80 /* read only (do not set, return read value) */
void
checkPorts (ci_t * ci)
{
#ifndef CONFIG_SBE_PMCC4_NCOMM
/*
* PORT POINT - NCOMM needs to avoid this code since the polling of
* alarms conflicts with NCOMM's interrupt servicing implementation.
*/
comet_t *comet;
volatile u_int32_t value;
u_int32_t copyVal, LEDval;
u_int8_t portnum;
LEDval = 0;
for (portnum = 0; portnum < ci->max_port; portnum++)
{
copyVal = 0x12f & (ci->alarmed[portnum]); /* port's alarm record */
comet = ci->port[portnum].cometbase;
value = pci_read_32 ((u_int32_t *) &comet->cdrc_ists) & sbeLinkMask; /* link loss reg */
if (value & sbeLinkChange) /* is there a change in the link stuff */
{
/* if there's been a change (above) and yet it's the same (below) */
if (!(((copyVal >> 3) & sbeLinkDown) ^ (value & sbeLinkDown)))
{
if (value & sbeLinkDown)
pr_warning("%s: Port %d momentarily recovered.\n",
ci->devname, portnum);
else
pr_warning("%s: Warning: Port %d link was briefly down.\n",
ci->devname, portnum);
} else if (value & sbeLinkDown)
pr_warning("%s: Warning: Port %d link is down.\n",
ci->devname, portnum);
else
{
pr_warning("%s: Port %d link has recovered.\n",
ci->devname, portnum);
copyVal |= 0x20; /* record link transition to up */
}
copyVal |= 0x10; /* change (link) --> update LEDs */
}
copyVal &= 0x137; /* clear LED & link old history bits &
* save others */
if (value & sbeLinkDown)
copyVal |= 0x08; /* record link status (now) */
else
{ /* if link is up, do this */
copyVal |= 0x40; /* LED indicate link is up */
/* Alarm things & the like ... first if E1, then if T1 */
if (IS_FRAME_ANY_E1 (ci->port[portnum].p.port_mode))
{
/*
* first check Codeword (SaX) changes & CRC and
* sub-multi-frame errors
*/
/*
* note these errors are printed every time they are detected
* vs. alarms
*/
value = pci_read_32 ((u_int32_t *) &comet->e1_frmr_nat_ists); /* codeword */
if (value & 0x1f)
{ /* if errors (crc or smf only) */
if (value & 0x10)
pr_warning("%s: E1 Port %d Codeword Sa4 change detected.\n",
ci->devname, portnum);
if (value & 0x08)
pr_warning("%s: E1 Port %d Codeword Sa5 change detected.\n",
ci->devname, portnum);
if (value & 0x04)
pr_warning("%s: E1 Port %d Codeword Sa6 change detected.\n",
ci->devname, portnum);
if (value & 0x02)
pr_warning("%s: E1 Port %d Codeword Sa7 change detected.\n",
ci->devname, portnum);
if (value & 0x01)
pr_warning("%s: E1 Port %d Codeword Sa8 change detected.\n",
ci->devname, portnum);
}
value = pci_read_32 ((u_int32_t *) &comet->e1_frmr_mists); /* crc & smf */
if (value & 0x3)
{ /* if errors (crc or smf only) */
if (value & sbeE1CRC)
pr_warning("%s: E1 Port %d CRC-4 error(s) detected.\n",
ci->devname, portnum);
if (value & sbeE1errSMF) /* error in sub-multiframe */
pr_warning("%s: E1 Port %d received errored SMF.\n",
ci->devname, portnum);
}
value = pci_read_32 ((u_int32_t *) &comet->e1_frmr_masts) & 0xcc; /* alarms */
/*
* pack alarms together (bitmiser), and construct similar to
* T1
*/
/* RAI,RMAI,.,.,LOF,AIS,.,. ==> RMAI,.,.,.,.,.,RAI,LOF,AIS */
/* see 0x97 */
value = (value >> 2);
if (value & 0x30)
{
if (value & 0x20)
value |= 0x40; /* RAI */
if (value & 0x10)
value |= 0x100; /* RMAI */
value &= ~0x30;
} /* finished packing alarm in handy order */
if (value != (copyVal & sbeE1AlarmsMask))
{ /* if alarms changed */
copyVal |= 0x10;/* change LED status */
if ((copyVal & sbeRedAlm) && !(value & sbeRedAlm))
{
copyVal &= ~sbeRedAlm;
pr_warning("%s: E1 Port %d LOF alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeRedAlm) && (value & sbeRedAlm))
{
copyVal |= sbeRedAlm;
pr_warning("%s: E1 Warning: Port %d LOF alarm.\n",
ci->devname, portnum);
} else if ((copyVal & sbeYelAlm) && !(value & sbeYelAlm))
{
copyVal &= ~sbeYelAlm;
pr_warning("%s: E1 Port %d RAI alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeYelAlm) && (value & sbeYelAlm))
{
copyVal |= sbeYelAlm;
pr_warning("%s: E1 Warning: Port %d RAI alarm.\n",
ci->devname, portnum);
} else if ((copyVal & sbeE1RMAI) && !(value & sbeE1RMAI))
{
copyVal &= ~sbeE1RMAI;
pr_warning("%s: E1 Port %d RMAI alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeE1RMAI) && (value & sbeE1RMAI))
{
copyVal |= sbeE1RMAI;
pr_warning("%s: E1 Warning: Port %d RMAI alarm.\n",
ci->devname, portnum);
} else if ((copyVal & sbeAISAlm) && !(value & sbeAISAlm))
{
copyVal &= ~sbeAISAlm;
pr_warning("%s: E1 Port %d AIS alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeAISAlm) && (value & sbeAISAlm))
{
copyVal |= sbeAISAlm;
pr_warning("%s: E1 Warning: Port %d AIS alarm.\n",
ci->devname, portnum);
}
}
/* end of E1 alarm code */
} else
{ /* if a T1 mode */
value = pci_read_32 ((u_int32_t *) &comet->t1_almi_ists); /* alarms */
value &= sbeAlarmsMask;
if (value != (copyVal & sbeAlarmsMask))
{ /* if alarms changed */
copyVal |= 0x10;/* change LED status */
if ((copyVal & sbeRedAlm) && !(value & sbeRedAlm))
{
copyVal &= ~sbeRedAlm;
pr_warning("%s: Port %d red alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeRedAlm) && (value & sbeRedAlm))
{
copyVal |= sbeRedAlm;
pr_warning("%s: Warning: Port %d red alarm.\n",
ci->devname, portnum);
} else if ((copyVal & sbeYelAlm) && !(value & sbeYelAlm))
{
copyVal &= ~sbeYelAlm;
pr_warning("%s: Port %d yellow (RAI) alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeYelAlm) && (value & sbeYelAlm))
{
copyVal |= sbeYelAlm;
pr_warning("%s: Warning: Port %d yellow (RAI) alarm.\n",
ci->devname, portnum);
} else if ((copyVal & sbeAISAlm) && !(value & sbeAISAlm))
{
copyVal &= ~sbeAISAlm;
pr_warning("%s: Port %d blue (AIS) alarm ended.\n",
ci->devname, portnum);
} else if (!(copyVal & sbeAISAlm) && (value & sbeAISAlm))
{
copyVal |= sbeAISAlm;
pr_warning("%s: Warning: Port %d blue (AIS) alarm.\n",
ci->devname, portnum);
}
}
} /* end T1 mode alarm checks */
}
if (copyVal & sbeAlarmsMask)
copyVal |= 0x80; /* if alarm turn yel LED on */
if (copyVal & 0x10)
LEDval |= 0x100; /* tag if LED values have changed */
LEDval |= ((copyVal & 0xc0) >> (6 - (portnum * 2)));
ci->alarmed[portnum] &= 0xfffff000; /* out with the old (it's fff
* ... foo) */
ci->alarmed[portnum] |= (copyVal); /* in with the new */
/*
* enough with the alarms and LED's, now let's check for loopback
* requests
*/
if (IS_FRAME_ANY_T1 (ci->port[portnum].p.port_mode))
{ /* if a T1 mode */
/*
* begin in-band (SF) loopback code detection -- start by reading
* command
*/
value = pci_read_32 ((u_int32_t *) &comet->ibcd_ies); /* detect reg. */
value &= 0x3; /* trim to handy bits */
if (value & 0x2)
{ /* activate loopback (sets for deactivate
* code length) */
copyVal = c4_loop_port (ci, portnum, COMET_LBCMD_READ); /* read line loopback
* mode */
if (copyVal != COMET_MDIAG_LINELB) /* don't do it again if
* already in that mode */
c4_loop_port (ci, portnum, COMET_MDIAG_LINELB); /* put port in line
* loopback mode */
}
if (value & 0x1)
{ /* deactivate loopback (sets for activate
* code length) */
copyVal = c4_loop_port (ci, portnum, COMET_LBCMD_READ); /* read line loopback
* mode */
if (copyVal != COMET_MDIAG_LBOFF) /* don't do it again if
* already in that mode */
c4_loop_port (ci, portnum, COMET_MDIAG_LBOFF); /* take port out of any
* loopback mode */
}
}
if (IS_FRAME_ANY_T1ESF (ci->port[portnum].p.port_mode))
{ /* if a T1 ESF mode */
/* begin ESF loopback code */
value = pci_read_32 ((u_int32_t *) &comet->t1_rboc_sts) & 0x3f; /* read command */
if (value == 0x07)
c4_loop_port (ci, portnum, COMET_MDIAG_LINELB); /* put port in line
* loopback mode */
if (value == 0x0a)
c4_loop_port (ci, portnum, COMET_MDIAG_PAYLB); /* put port in payload
* loopbk mode */
if ((value == 0x1c) || (value == 0x19) || (value == 0x12))
c4_loop_port (ci, portnum, COMET_MDIAG_LBOFF); /* take port out of any
* loopbk mode */
if (log_level >= LOG_DEBUG)
if (value != 0x3f)
pr_warning("%s: BOC value = %x on Port %d\n",
ci->devname, value, portnum);
/* end ESF loopback code */
}
}
/* if something is new, update LED's */
if (LEDval & 0x100)
pci_write_32 ((u_int32_t *) &ci->cpldbase->leds, LEDval & 0xff);
#endif /*** CONFIG_SBE_PMCC4_NCOMM ***/
}
STATIC void
c4_watchdog (ci_t * ci)
{
if (drvr_state != SBE_DRVR_AVAILABLE)
{
if (log_level >= LOG_MONITOR)
pr_info("drvr not available (%x)\n", drvr_state);
return;
}
ci->wdcount++;
checkPorts (ci);
ci->wd_notify = 0;
}
void
c4_cleanup (void)
{
ci_t *ci, *next;
mpi_t *pi;
int portnum, j;
ci = c4_list;
while (ci)
{
next = ci->next; /* protect <next> from upcoming <free> */
pci_write_32 ((u_int32_t *) &ci->cpldbase->leds, PMCC4_CPLD_LED_OFF);
for (portnum = 0; portnum < ci->max_port; portnum++)
{
pi = &ci->port[portnum];
c4_wq_port_cleanup (pi);
for (j = 0; j < MUSYCC_NCHANS; j++)
{
if (pi->chan[j])
OS_kfree (pi->chan[j]); /* free mch_t struct */
}
OS_kfree (pi->regram_saved);
}
OS_kfree (ci->iqd_p_saved);
OS_kfree (ci);
ci = next; /* cleanup next board, if any */
}
}
/*
* This function issues a write to all comet chips and expects the same data
* to be returned from the subsequent read. This determines the board build
* to be a 1-port, 2-port, or 4-port build. The value returned represents a
* bit-mask of the found ports. Only certain configurations are considered
* VALID or LEGAL builds.
*/
int
c4_get_portcfg (ci_t * ci)
{
comet_t *comet;
int portnum, mask;
u_int32_t wdata, rdata;
wdata = COMET_MDIAG_LBOFF; /* take port out of any loopback mode */
mask = 0;
for (portnum = 0; portnum < MUSYCC_NPORTS; portnum++)
{
comet = ci->port[portnum].cometbase;
pci_write_32 ((u_int32_t *) &comet->mdiag, wdata);
rdata = pci_read_32 ((u_int32_t *) &comet->mdiag) & COMET_MDIAG_LBMASK;
if (wdata == rdata)
mask |= 1 << portnum;
}
return mask;
}
/* nothing herein should generate interrupts */
status_t __init
c4_init (ci_t * ci, u_char *func0, u_char *func1)
{
mpi_t *pi;
mch_t *ch;
static u_int32_t count = 0;
int portnum, j;
ci->state = C_INIT;
ci->brdno = count++;
ci->intlog.this_status_new = 0;
atomic_set (&ci->bh_pending, 0);
ci->reg = (struct musycc_globalr *) func0;
ci->eeprombase = (u_int32_t *) (func1 + EEPROM_OFFSET);
ci->cpldbase = (c4cpld_t *) ((u_int32_t *) (func1 + ISPLD_OFFSET));
/*** PORT POINT - the following is the first access of any type to the hardware ***/
#ifdef CONFIG_SBE_PMCC4_NCOMM
/* NCOMM driver uses INTB interrupt to monitor CPLD register */
pci_write_32 ((u_int32_t *) &ci->reg->glcd, GCD_MAGIC);
#else
/* standard driver POLLS for INTB via CPLD register */
pci_write_32 ((u_int32_t *) &ci->reg->glcd, GCD_MAGIC | MUSYCC_GCD_INTB_DISABLE);
#endif
{
int pmsk;
/* need comet addresses available for determination of hardware build */
for (portnum = 0; portnum < MUSYCC_NPORTS; portnum++)
{
pi = &ci->port[portnum];
pi->cometbase = (comet_t *) ((u_int32_t *) (func1 + COMET_OFFSET (portnum)));
pi->reg = (struct musycc_globalr *) ((u_char *) ci->reg + (portnum * 0x800));
pi->portnum = portnum;
pi->p.portnum = portnum;
pi->openchans = 0;
#ifdef SBE_MAP_DEBUG
pr_info("Comet-%d: addr = %p\n", portnum, pi->cometbase);
#endif
}
pmsk = c4_get_portcfg (ci);
switch (pmsk)
{
case 0x1:
ci->max_port = 1;
break;
case 0x3:
ci->max_port = 2;
break;
#if 0
case 0x7: /* not built, but could be... */
ci->max_port = 3;
break;
#endif
case 0xf:
ci->max_port = 4;
break;
default:
ci->max_port = 0;
pr_warning("%s: illegal port configuration (%x)\n",
ci->devname, pmsk);
return SBE_DRVR_FAIL;
}
#ifdef SBE_MAP_DEBUG
pr_info(">> %s: c4_get_build - pmsk %x max_port %x\n",
ci->devname, pmsk, ci->max_port);
#endif
}
for (portnum = 0; portnum < ci->max_port; portnum++)
{
pi = &ci->port[portnum];
pi->up = ci;
pi->sr_last = 0xffffffff;
pi->p.port_mode = CFG_FRAME_SF; /* T1 B8ZS, the default */
pi->p.portP = (CFG_CLK_PORT_EXTERNAL | CFG_LBO_LH0); /* T1 defaults */
OS_sem_init (&pi->sr_sem_busy, SEM_AVAILABLE);
OS_sem_init (&pi->sr_sem_wait, SEM_TAKEN);
for (j = 0; j < 32; j++)
{
pi->fifomap[j] = -1;
pi->tsm[j] = 0; /* no assignments, all available */
}
/* allocate channel structures for this port */
for (j = 0; j < MUSYCC_NCHANS; j++)
{
ch = OS_kmalloc (sizeof (mch_t));
if (ch)
{
pi->chan[j] = ch;
ch->state = UNASSIGNED;
ch->up = pi;
ch->gchan = (-1); /* channel assignment not yet known */
ch->channum = (-1); /* channel assignment not yet known */
ch->p.card = ci->brdno;
ch->p.port = portnum;
ch->p.channum = (-1); /* channel assignment not yet known */
ch->p.mode_56k = 0; /* default is 64kbps mode */
} else
{
pr_warning("failed mch_t malloc, port %d channel %d size %u.\n",
portnum, j, (unsigned int) sizeof (mch_t));
break;
}
}
}
{
/*
* Set LEDs through their paces to supply visual proof that LEDs are
* functional and not burnt out nor broken.
*
* YELLOW + GREEN -> OFF.
*/
pci_write_32 ((u_int32_t *) &ci->cpldbase->leds,
PMCC4_CPLD_LED_GREEN | PMCC4_CPLD_LED_YELLOW);
OS_uwait (750000, "leds");
pci_write_32 ((u_int32_t *) &ci->cpldbase->leds, PMCC4_CPLD_LED_OFF);
}
OS_init_watchdog (&ci->wd, (void (*) (void *)) c4_watchdog, ci, WATCHDOG_TIMEOUT);
return SBE_DRVR_SUCCESS;
}
/* better be fully setup to handle interrupts when you call this */
status_t __init
c4_init2 (ci_t * ci)
{
status_t ret;
/* PORT POINT: this routine generates first interrupt */
if ((ret = musycc_init (ci)) != SBE_DRVR_SUCCESS)
return ret;
#if 0
ci->p.framing_type = FRAMING_CBP;
ci->p.h110enable = 1;
#if 0
ci->p.hypersize = 0;
#else
hyperdummy = 0;
#endif
ci->p.clock = 0; /* Use internal clocking until set to
* external */
c4_card_set_params (ci, &ci->p);
#endif
OS_start_watchdog (&ci->wd);
return SBE_DRVR_SUCCESS;
}
/* This function sets the loopback mode (or clears it, as the case may be). */
int
c4_loop_port (ci_t * ci, int portnum, u_int8_t cmd)
{
comet_t *comet;
volatile u_int32_t loopValue;
comet = ci->port[portnum].cometbase;
loopValue = pci_read_32 ((u_int32_t *) &comet->mdiag) & COMET_MDIAG_LBMASK;
if (cmd & COMET_LBCMD_READ)
return loopValue; /* return the read value */
if (loopValue != cmd)
{
switch (cmd)
{
case COMET_MDIAG_LINELB:
/* set(SF)loopback down (turn off) code length to 6 bits */
pci_write_32 ((u_int32_t *) &comet->ibcd_cfg, 0x05);
break;
case COMET_MDIAG_LBOFF:
/* set (SF) loopback up (turn on) code length to 5 bits */
pci_write_32 ((u_int32_t *) &comet->ibcd_cfg, 0x00);
break;
}
pci_write_32 ((u_int32_t *) &comet->mdiag, cmd);
if (log_level >= LOG_WARN)
pr_info("%s: loopback mode changed to %2x from %2x on Port %d\n",
ci->devname, cmd, loopValue, portnum);
loopValue = pci_read_32 ((u_int32_t *) &comet->mdiag) & COMET_MDIAG_LBMASK;
if (loopValue != cmd)
{
if (log_level >= LOG_ERROR)
pr_info("%s: write to loop register failed, unknown state for Port %d\n",
ci->devname, portnum);
}
} else
{
if (log_level >= LOG_WARN)
pr_info("%s: loopback already in that mode (%2x)\n",
ci->devname, loopValue);
}
return 0;
}
/* c4_frame_rw: read or write the comet register specified
* (modifies use of port_param to non-standard use of struct)
* Specifically:
* pp.portnum (one guess)
* pp.port_mode offset of register
* pp.portP write (or not, i.e. read)
* pp.portStatus write value
* BTW:
* pp.portStatus also used to return read value
* pp.portP also used during write, to return old reg value
*/
status_t
c4_frame_rw (ci_t * ci, struct sbecom_port_param * pp)
{
comet_t *comet;
volatile u_int32_t data;
if (pp->portnum >= ci->max_port)/* sanity check */
return ENXIO;
comet = ci->port[pp->portnum].cometbase;
data = pci_read_32 ((u_int32_t *) comet + pp->port_mode) & 0xff;
if (pp->portP)
{ /* control says this is a register
* _write_ */
if (pp->portStatus == data)
pr_info("%s: Port %d already that value! Writing again anyhow.\n",
ci->devname, pp->portnum);
pp->portP = (u_int8_t) data;
pci_write_32 ((u_int32_t *) comet + pp->port_mode,
pp->portStatus);
data = pci_read_32 ((u_int32_t *) comet + pp->port_mode) & 0xff;
}
pp->portStatus = (u_int8_t) data;
return 0;
}
/* c4_pld_rw: read or write the pld register specified
* (modifies use of port_param to non-standard use of struct)
* Specifically:
* pp.port_mode offset of register
* pp.portP write (or not, i.e. read)
* pp.portStatus write value
* BTW:
* pp.portStatus also used to return read value
* pp.portP also used during write, to return old reg value
*/
status_t
c4_pld_rw (ci_t * ci, struct sbecom_port_param * pp)
{
volatile u_int32_t *regaddr;
volatile u_int32_t data;
int regnum = pp->port_mode;
regaddr = (u_int32_t *) ci->cpldbase + regnum;
data = pci_read_32 ((u_int32_t *) regaddr) & 0xff;
if (pp->portP)
{ /* control says this is a register
* _write_ */
pp->portP = (u_int8_t) data;
pci_write_32 ((u_int32_t *) regaddr, pp->portStatus);
data = pci_read_32 ((u_int32_t *) regaddr) & 0xff;
}
pp->portStatus = (u_int8_t) data;
return 0;
}
/* c4_musycc_rw: read or write the musycc register specified
* (modifies use of port_param to non-standard use of struct)
* Specifically:
* mcp.RWportnum port number and write indication bit (0x80)
* mcp.offset offset of register
* mcp.value write value going in and read value returning
*/
/* PORT POINT: TX Subchannel Map registers are write-only
* areas within the MUSYCC and always return FF */
/* PORT POINT: regram and reg structures are minorly different and <offset> ioctl
* settings are aligned with the <reg> struct musycc_globalr{} usage.
* Also, regram is separately allocated shared memory, allocated for each port.
* PORT POINT: access offsets of 0x6000 for Msg Cfg Desc Tbl are for 4-port MUSYCC
* only. (An 8-port MUSYCC has 0x16000 offsets for accessing its upper 4 tables.)
*/
status_t
c4_musycc_rw (ci_t * ci, struct c4_musycc_param * mcp)
{
mpi_t *pi;
volatile u_int32_t *dph; /* hardware implemented register */
u_int32_t *dpr = 0; /* RAM image of registers for group command
* usage */
int offset = mcp->offset % 0x800; /* group relative address
* offset, mcp->portnum is
* not used */
int portnum, ramread = 0;
volatile u_int32_t data;
/*
* Sanity check hardware accessibility. The 0x6000 portion handles port
* numbers associated with Msg Descr Tbl decoding.
*/
portnum = (mcp->offset % 0x6000) / 0x800;
if (portnum >= ci->max_port)
return ENXIO;
pi = &ci->port[portnum];
if (mcp->offset >= 0x6000)
offset += 0x6000; /* put back in MsgCfgDesc address offset */
dph = (u_int32_t *) ((u_long) pi->reg + offset);
/* read of TX are from RAM image, since hardware returns FF */
dpr = (u_int32_t *) ((u_long) pi->regram + offset);
if (mcp->offset < 0x6000) /* non MsgDesc Tbl accesses might require
* RAM access */
{
if (offset >= 0x200 && offset < 0x380)
ramread = 1;
if (offset >= 0x10 && offset < 0x200)
ramread = 1;
}
/* read register from RAM or hardware, depending... */
if (ramread)
{
data = *dpr;
//pr_info("c4_musycc_rw: RAM addr %p read data %x (portno %x offset %x RAM ramread %x)\n", dpr, data, portnum, offset, ramread); /* RLD DEBUG */
} else
{
data = pci_read_32 ((u_int32_t *) dph);
//pr_info("c4_musycc_rw: REG addr %p read data %x (portno %x offset %x RAM ramread %x)\n", dph, data, portnum, offset, ramread); /* RLD DEBUG */
}
if (mcp->RWportnum & 0x80)
{ /* control says this is a register
* _write_ */
if (mcp->value == data)
pr_info("%s: musycc grp%d already that value! writing again anyhow.\n",
ci->devname, (mcp->RWportnum & 0x7));
/* write register RAM */
if (ramread)
*dpr = mcp->value;
/* write hardware register */
pci_write_32 ((u_int32_t *) dph, mcp->value);
}
mcp->value = data; /* return the read value (or the 'old
* value', if is write) */
return 0;
}
status_t
c4_get_port (ci_t * ci, int portnum)
{
if (portnum >= ci->max_port) /* sanity check */
return ENXIO;
SD_SEM_TAKE (&ci->sem_wdbusy, "_wd_"); /* only 1 thru here, per
* board */
checkPorts (ci);
ci->port[portnum].p.portStatus = (u_int8_t) ci->alarmed[portnum];
ci->alarmed[portnum] &= 0xdf;
SD_SEM_GIVE (&ci->sem_wdbusy); /* release per-board hold */
return 0;
}
status_t
c4_set_port (ci_t * ci, int portnum)
{
mpi_t *pi;
struct sbecom_port_param *pp;
int e1mode;
u_int8_t clck;
int i;
if (portnum >= ci->max_port) /* sanity check */
return ENXIO;
pi = &ci->port[portnum];
pp = &ci->port[portnum].p;
e1mode = IS_FRAME_ANY_E1 (pp->port_mode);
if (log_level >= LOG_MONITOR2)
{
pr_info("%s: c4_set_port[%d]: entered, e1mode = %x, openchans %d.\n",
ci->devname,
portnum, e1mode, pi->openchans);
}
if (pi->openchans)
return EBUSY; /* group needs initialization only for
* first channel of a group */
{
status_t ret;
if ((ret = c4_wq_port_init (pi))) /* create/init
* workqueue_struct */
return (ret);
}
init_comet (ci, pi->cometbase, pp->port_mode, 1 /* clockmaster == true */ , pp->portP);
clck = pci_read_32 ((u_int32_t *) &ci->cpldbase->mclk) & PMCC4_CPLD_MCLK_MASK;
if (e1mode)
clck |= 1 << portnum;
else
clck &= 0xf ^ (1 << portnum);
pci_write_32 ((u_int32_t *) &ci->cpldbase->mclk, clck);
pci_write_32 ((u_int32_t *) &ci->cpldbase->mcsr, PMCC4_CPLD_MCSR_IND);
pci_write_32 ((u_int32_t *) &pi->reg->gbp, OS_vtophys (pi->regram));
/*********************************************************************/
/* ERRATA: If transparent mode is used, do not set OOFMP_DISABLE bit */
/*********************************************************************/
pi->regram->grcd =
__constant_cpu_to_le32 (MUSYCC_GRCD_RX_ENABLE |
MUSYCC_GRCD_TX_ENABLE |
MUSYCC_GRCD_OOFMP_DISABLE |
MUSYCC_GRCD_SF_ALIGN | /* per MUSYCC ERRATA,
* for T1 * fix */
MUSYCC_GRCD_COFAIRQ_DISABLE |
MUSYCC_GRCD_MC_ENABLE |
(MUSYCC_GRCD_POLLTH_32 << MUSYCC_GRCD_POLLTH_SHIFT));
pi->regram->pcd =
__constant_cpu_to_le32 ((e1mode ? 1 : 0) |
MUSYCC_PCD_TXSYNC_RISING |
MUSYCC_PCD_RXSYNC_RISING |
MUSYCC_PCD_RXDATA_RISING);
/* Message length descriptor */
pi->regram->mld = __constant_cpu_to_le32 (cxt1e1_max_mru | (cxt1e1_max_mru << 16));
/* tsm algorithm */
for (i = 0; i < 32; i++)
{
/*** ASSIGNMENT NOTES: ***/
/*** Group's channel ZERO unavailable if E1. ***/
/*** Group's channel 16 unavailable if E1 CAS. ***/
/*** Group's channels 24-31 unavailable if T1. ***/
if (((i == 0) && e1mode) ||
((i == 16) && ((pp->port_mode == CFG_FRAME_E1CRC_CAS) || (pp->port_mode == CFG_FRAME_E1CRC_CAS_AMI)))
|| ((i > 23) && (!e1mode)))
{
pi->tsm[i] = 0xff; /* make tslot unavailable for this mode */
} else
{
pi->tsm[i] = 0x00; /* make tslot available for assignment */
}
}
for (i = 0; i < MUSYCC_NCHANS; i++)
{
pi->regram->ttsm[i] = 0;
pi->regram->rtsm[i] = 0;
}
FLUSH_MEM_WRITE ();
musycc_serv_req (pi, SR_GROUP_INIT | SR_RX_DIRECTION);
musycc_serv_req (pi, SR_GROUP_INIT | SR_TX_DIRECTION);
musycc_init_mdt (pi);
pi->group_is_set = 1;
pi->p = *pp;
return 0;
}
unsigned int max_int = 0;
status_t
c4_new_chan (ci_t * ci, int portnum, int channum, void *user)
{
mpi_t *pi;
mch_t *ch;
int gchan;
if (c4_find_chan (channum)) /* a new channel shouldn't already exist */
return EEXIST;
if (portnum >= ci->max_port) /* sanity check */
return ENXIO;
pi = &(ci->port[portnum]);
/* find any available channel within this port */
for (gchan = 0; gchan < MUSYCC_NCHANS; gchan++)
{
ch = pi->chan[gchan];
if (ch && ch->state == UNASSIGNED) /* no assignment is good! */
break;
}
if (gchan == MUSYCC_NCHANS) /* exhausted table, all were assigned */
return ENFILE;
ch->up = pi;
/* NOTE: mch_t already cleared during OS_kmalloc() */
ch->state = DOWN;
ch->user = user;
ch->gchan = gchan;
ch->channum = channum; /* mark our channel assignment */
ch->p.channum = channum;
#if 1
ch->p.card = ci->brdno;
ch->p.port = portnum;
#endif
ch->p.chan_mode = CFG_CH_PROTO_HDLC_FCS16;
ch->p.idlecode = CFG_CH_FLAG_7E;
ch->p.pad_fill_count = 2;
spin_lock_init (&ch->ch_rxlock);
spin_lock_init (&ch->ch_txlock);
{
status_t ret;
if ((ret = c4_wk_chan_init (pi, ch)))
return ret;
}
/* save off interface assignments which bound a board */
if (ci->first_if == 0) /* first channel registered is assumed to
* be the lowest channel */
{
ci->first_if = ci->last_if = user;
ci->first_channum = ci->last_channum = channum;
} else
{
ci->last_if = user;
if (ci->last_channum < channum) /* higher number channel found */
ci->last_channum = channum;
}
return 0;
}
status_t
c4_del_chan (int channum)
{
mch_t *ch;
if (!(ch = c4_find_chan (channum)))
return ENOENT;
if (ch->state == UP)
musycc_chan_down ((ci_t *) 0, channum);
ch->state = UNASSIGNED;
ch->gchan = (-1);
ch->channum = (-1);
ch->p.channum = (-1);
return 0;
}
status_t
c4_del_chan_stats (int channum)
{
mch_t *ch;
if (!(ch = c4_find_chan (channum)))
return ENOENT;
memset (&ch->s, 0, sizeof (struct sbecom_chan_stats));
return 0;
}
status_t
c4_set_chan (int channum, struct sbecom_chan_param * p)
{
mch_t *ch;
int i, x = 0;
if (!(ch = c4_find_chan (channum)))
return ENOENT;
#if 1
if (ch->p.card != p->card ||
ch->p.port != p->port ||
ch->p.channum != p->channum)
return EINVAL;
#endif
if (!(ch->up->group_is_set))
{
return EIO; /* out of order, SET_PORT command
* required prior to first group's
* SET_CHAN command */
}
/*
* Check for change of parameter settings in order to invoke closing of
* channel prior to hardware poking.
*/
if (ch->p.status != p->status || ch->p.chan_mode != p->chan_mode ||
ch->p.data_inv != p->data_inv || ch->p.intr_mask != p->intr_mask ||
ch->txd_free < ch->txd_num) /* to clear out queued messages */
x = 1; /* we have a change requested */
for (i = 0; i < 32; i++) /* check for timeslot mapping changes */
if (ch->p.bitmask[i] != p->bitmask[i])
x = 1; /* we have a change requested */
ch->p = *p;
if (x && (ch->state == UP)) /* if change request and channel is
* open... */
{
status_t ret;
if ((ret = musycc_chan_down ((ci_t *) 0, channum)))
return ret;
if ((ret = c4_chan_up (ch->up->up, channum)))
return ret;
sd_enable_xmit (ch->user); /* re-enable to catch flow controlled
* channel */
}
return 0;
}
status_t
c4_get_chan (int channum, struct sbecom_chan_param * p)
{
mch_t *ch;
if (!(ch = c4_find_chan (channum)))
return ENOENT;
*p = ch->p;
return 0;
}
status_t
c4_get_chan_stats (int channum, struct sbecom_chan_stats * p)
{
mch_t *ch;
if (!(ch = c4_find_chan (channum)))
return ENOENT;
*p = ch->s;
p->tx_pending = atomic_read (&ch->tx_pending);
return 0;
}
STATIC int
c4_fifo_alloc (mpi_t * pi, int chan, int *len)
{
int i, l = 0, start = 0, max = 0, maxstart = 0;
for (i = 0; i < 32; i++)
{
if (pi->fifomap[i] != -1)
{
l = 0;
start = i + 1;
continue;
}
++l;
if (l > max)
{
max = l;
maxstart = start;
}
if (max == *len)
break;
}
if (max != *len)
{
if (log_level >= LOG_WARN)
pr_info("%s: wanted to allocate %d fifo space, but got only %d\n",
pi->up->devname, *len, max);
*len = max;
}
if (log_level >= LOG_DEBUG)
pr_info("%s: allocated %d fifo at %d for channel %d/%d\n",
pi->up->devname, max, start, chan, pi->p.portnum);
for (i = maxstart; i < (maxstart + max); i++)
pi->fifomap[i] = chan;
return start;
}
void
c4_fifo_free (mpi_t * pi, int chan)
{
int i;
if (log_level >= LOG_DEBUG)
pr_info("%s: deallocated fifo for channel %d/%d\n",
pi->up->devname, chan, pi->p.portnum);
for (i = 0; i < 32; i++)
if (pi->fifomap[i] == chan)
pi->fifomap[i] = -1;
}
status_t
c4_chan_up (ci_t * ci, int channum)
{
mpi_t *pi;
mch_t *ch;
struct mbuf *m;
struct mdesc *md;
int nts, nbuf, txnum, rxnum;
int addr, i, j, gchan;
u_int32_t tmp; /* for optimizing conversion across BE
* platform */
if (!(ch = c4_find_chan (channum)))
return ENOENT;
if (ch->state == UP)
{
if (log_level >= LOG_MONITOR)
pr_info("%s: channel already UP, graceful early exit\n",
ci->devname);
return 0;
}
pi = ch->up;
gchan = ch->gchan;
/* find nts ('number of timeslots') */
nts = 0;
for (i = 0; i < 32; i++)
{
if (ch->p.bitmask[i] & pi->tsm[i])
{
if (1 || log_level >= LOG_WARN)
{
pr_info("%s: c4_chan_up[%d] EINVAL (attempt to cfg in-use or unavailable TimeSlot[%d])\n",
ci->devname, channum, i);
pr_info("+ ask4 %x, currently %x\n",
ch->p.bitmask[i], pi->tsm[i]);
}
return EINVAL;
}
for (j = 0; j < 8; j++)
if (ch->p.bitmask[i] & (1 << j))
nts++;
}
nbuf = nts / 8 ? nts / 8 : 1;
if (!nbuf)
{
/* if( log_level >= LOG_WARN) */
pr_info("%s: c4_chan_up[%d] ENOBUFS (no TimeSlots assigned)\n",
ci->devname, channum);
return ENOBUFS; /* this should not happen */
}
addr = c4_fifo_alloc (pi, gchan, &nbuf);
ch->state = UP;
/* Setup the Time Slot Map */
musycc_update_timeslots (pi);
/* ch->tx_limit = nts; */
ch->s.tx_pending = 0;
/* Set Channel Configuration Descriptors */
{
u_int32_t ccd;
ccd = musycc_chan_proto (ch->p.chan_mode) << MUSYCC_CCD_PROTO_SHIFT;
if ((ch->p.chan_mode == CFG_CH_PROTO_ISLP_MODE) ||
(ch->p.chan_mode == CFG_CH_PROTO_TRANS))
{
ccd |= MUSYCC_CCD_FCS_XFER; /* Non FSC Mode */
}
ccd |= 2 << MUSYCC_CCD_MAX_LENGTH; /* Select second MTU */
ccd |= ch->p.intr_mask;
ccd |= addr << MUSYCC_CCD_BUFFER_LOC;
if (ch->p.chan_mode == CFG_CH_PROTO_TRANS)
ccd |= (nbuf) << MUSYCC_CCD_BUFFER_LENGTH;
else
ccd |= (nbuf - 1) << MUSYCC_CCD_BUFFER_LENGTH;
if (ch->p.data_inv & CFG_CH_DINV_TX)
ccd |= MUSYCC_CCD_INVERT_DATA; /* Invert data */
pi->regram->tcct[gchan] = cpu_to_le32 (ccd);
if (ch->p.data_inv & CFG_CH_DINV_RX)
ccd |= MUSYCC_CCD_INVERT_DATA; /* Invert data */
else
ccd &= ~MUSYCC_CCD_INVERT_DATA; /* take away data inversion */
pi->regram->rcct[gchan] = cpu_to_le32 (ccd);
FLUSH_MEM_WRITE ();
}
/* Reread the Channel Configuration Descriptor for this channel */
musycc_serv_req (pi, SR_CHANNEL_CONFIG | SR_RX_DIRECTION | gchan);
musycc_serv_req (pi, SR_CHANNEL_CONFIG | SR_TX_DIRECTION | gchan);
/*
* Figure out how many buffers we want. If the customer has changed from
* the defaults, then use the changed values. Otherwise, use Transparent
* mode's specific minimum default settings.
*/
if (ch->p.chan_mode == CFG_CH_PROTO_TRANS)
{
if (max_rxdesc_used == max_rxdesc_default) /* use default setting */
max_rxdesc_used = MUSYCC_RXDESC_TRANS;
if (max_txdesc_used == max_txdesc_default) /* use default setting */
max_txdesc_used = MUSYCC_TXDESC_TRANS;
}
/*
* Increase counts when hyperchanneling, since this implies an increase
* in throughput per channel
*/
rxnum = max_rxdesc_used + (nts / 4);
txnum = max_txdesc_used + (nts / 4);
#if 0
/* DEBUG INFO */
if (log_level >= LOG_MONITOR)
pr_info("%s: mode %x rxnum %d (rxused %d def %d) txnum %d (txused %d def %d)\n",
ci->devname, ch->p.chan_mode,
rxnum, max_rxdesc_used, max_rxdesc_default,
txnum, max_txdesc_used, max_txdesc_default);
#endif
ch->rxd_num = rxnum;
ch->txd_num = txnum;
ch->rxix_irq_srv = 0;
ch->mdr = OS_kmalloc (sizeof (struct mdesc) * rxnum);
ch->mdt = OS_kmalloc (sizeof (struct mdesc) * txnum);
if (ch->p.chan_mode == CFG_CH_PROTO_TRANS)
tmp = __constant_cpu_to_le32 (cxt1e1_max_mru | EOBIRQ_ENABLE);
else
tmp = __constant_cpu_to_le32 (cxt1e1_max_mru);
for (i = 0, md = ch->mdr; i < rxnum; i++, md++)
{
if (i == (rxnum - 1))
{
md->snext = &ch->mdr[0];/* wrapness */
} else
{
md->snext = &ch->mdr[i + 1];
}
md->next = cpu_to_le32 (OS_vtophys (md->snext));
if (!(m = OS_mem_token_alloc (cxt1e1_max_mru)))
{
if (log_level >= LOG_MONITOR)
pr_info("%s: c4_chan_up[%d] - token alloc failure, size = %d.\n",
ci->devname, channum, cxt1e1_max_mru);
goto errfree;
}
md->mem_token = m;
md->data = cpu_to_le32 (OS_vtophys (OS_mem_token_data (m)));
md->status = tmp | MUSYCC_RX_OWNED; /* MUSYCC owns RX descriptor **
* CODING NOTE:
* MUSYCC_RX_OWNED = 0 so no
* need to byteSwap */
}
for (i = 0, md = ch->mdt; i < txnum; i++, md++)
{
md->status = HOST_TX_OWNED; /* Host owns TX descriptor ** CODING
* NOTE: HOST_TX_OWNED = 0 so no need to
* byteSwap */
md->mem_token = 0;
md->data = 0;
if (i == (txnum - 1))
{
md->snext = &ch->mdt[0];/* wrapness */
} else
{
md->snext = &ch->mdt[i + 1];
}
md->next = cpu_to_le32 (OS_vtophys (md->snext));
}
ch->txd_irq_srv = ch->txd_usr_add = &ch->mdt[0];
ch->txd_free = txnum;
ch->tx_full = 0;
ch->txd_required = 0;
/* Configure it into the chip */
tmp = cpu_to_le32 (OS_vtophys (&ch->mdt[0]));
pi->regram->thp[gchan] = tmp;
pi->regram->tmp[gchan] = tmp;
tmp = cpu_to_le32 (OS_vtophys (&ch->mdr[0]));
pi->regram->rhp[gchan] = tmp;
pi->regram->rmp[gchan] = tmp;
/* Activate the Channel */
FLUSH_MEM_WRITE ();
if (ch->p.status & RX_ENABLED)
{
#ifdef RLD_TRANS_DEBUG
pr_info("++ c4_chan_up() CHAN RX ACTIVATE: chan %d\n", ch->channum);
#endif
ch->ch_start_rx = 0; /* we are restarting RX... */
musycc_serv_req (pi, SR_CHANNEL_ACTIVATE | SR_RX_DIRECTION | gchan);
}
if (ch->p.status & TX_ENABLED)
{
#ifdef RLD_TRANS_DEBUG
pr_info("++ c4_chan_up() CHAN TX ACTIVATE: chan %d <delayed>\n", ch->channum);
#endif
ch->ch_start_tx = CH_START_TX_1ST; /* we are delaying start
* until receipt from user of
* first packet to transmit. */
}
ch->status = ch->p.status;
pi->openchans++;
return 0;
errfree:
while (i > 0)
{
/* Don't leak all the previously allocated mbufs in this loop */
i--;
OS_mem_token_free (ch->mdr[i].mem_token);
}
OS_kfree (ch->mdt);
ch->mdt = 0;
ch->txd_num = 0;
OS_kfree (ch->mdr);
ch->mdr = 0;
ch->rxd_num = 0;
ch->state = DOWN;
return ENOBUFS;
}
/* stop the hardware from servicing & interrupting */
void
c4_stopwd (ci_t * ci)
{
OS_stop_watchdog (&ci->wd);
SD_SEM_TAKE (&ci->sem_wdbusy, "_stop_"); /* ensure WD not running */
SD_SEM_GIVE (&ci->sem_wdbusy);
}
void
sbecom_get_brdinfo (ci_t * ci, struct sbe_brd_info * bip, u_int8_t *bsn)
{
char *np;
u_int32_t sn = 0;
int i;
bip->brdno = ci->brdno; /* our board number */
bip->brd_id = ci->brd_id;
bip->brd_hdw_id = ci->hdw_bid;
bip->brd_chan_cnt = MUSYCC_NCHANS * ci->max_port; /* number of channels
* being used */
bip->brd_port_cnt = ci->max_port; /* number of ports being used */
bip->brd_pci_speed = BINFO_PCI_SPEED_unk; /* PCI speed not yet
* determinable */
if (ci->first_if)
{
{
struct net_device *dev;
dev = (struct net_device *) ci->first_if;
np = (char *) dev->name;
}
strncpy (bip->first_iname, np, CHNM_STRLEN - 1);
} else
strcpy (bip->first_iname, "<NULL>");
if (ci->last_if)
{
{
struct net_device *dev;
dev = (struct net_device *) ci->last_if;
np = (char *) dev->name;
}
strncpy (bip->last_iname, np, CHNM_STRLEN - 1);
} else
strcpy (bip->last_iname, "<NULL>");
if (bsn)
{
for (i = 0; i < 3; i++)
{
bip->brd_mac_addr[i] = *bsn++;
}
for (; i < 6; i++)
{
bip->brd_mac_addr[i] = *bsn;
sn = (sn << 8) | *bsn++;
}
} else
{
for (i = 0; i < 6; i++)
bip->brd_mac_addr[i] = 0;
}
bip->brd_sn = sn;
}
status_t
c4_get_iidinfo (ci_t * ci, struct sbe_iid_info * iip)
{
struct net_device *dev;
char *np;
if (!(dev = getuserbychan (iip->channum)))
return ENOENT;
np = dev->name;
strncpy (iip->iname, np, CHNM_STRLEN - 1);
return 0;
}
#ifdef CONFIG_SBE_PMCC4_NCOMM
void (*nciInterrupt[MAX_BOARDS][4]) (void);
extern void wanpmcC4T1E1_hookInterrupt (int cardID, int deviceID, void *handler);
void
wanpmcC4T1E1_hookInterrupt (int cardID, int deviceID, void *handler)
{
if (cardID < MAX_BOARDS) /* sanity check */
nciInterrupt[cardID][deviceID] = handler;
}
irqreturn_t
c4_ebus_intr_th_handler (void *devp)
{
ci_t *ci = (ci_t *) devp;
volatile u_int32_t ists;
int handled = 0;
int brdno;
/* which COMET caused the interrupt */
brdno = ci->brdno;
ists = pci_read_32 ((u_int32_t *) &ci->cpldbase->intr);
if (ists & PMCC4_CPLD_INTR_CMT_1)
{
handled = 0x1;
if (nciInterrupt[brdno][0] != NULL)
(*nciInterrupt[brdno][0]) ();
}
if (ists & PMCC4_CPLD_INTR_CMT_2)
{
handled |= 0x2;
if (nciInterrupt[brdno][1] != NULL)
(*nciInterrupt[brdno][1]) ();
}
if (ists & PMCC4_CPLD_INTR_CMT_3)
{
handled |= 0x4;
if (nciInterrupt[brdno][2] != NULL)
(*nciInterrupt[brdno][2]) ();
}
if (ists & PMCC4_CPLD_INTR_CMT_4)
{
handled |= 0x8;
if (nciInterrupt[brdno][3] != NULL)
(*nciInterrupt[brdno][3]) ();
}
#if 0
/*** Test code just de-implements the asserted interrupt. Alternate
vendor will supply COMET interrupt handling code herein or such.
***/
pci_write_32 ((u_int32_t *) &ci->reg->glcd, GCD_MAGIC | MUSYCC_GCD_INTB_DISABLE);
#endif
return IRQ_RETVAL (handled);
}
unsigned long
wanpmcC4T1E1_getBaseAddress (int cardID, int deviceID)
{
ci_t *ci;
unsigned long base = 0;
ci = c4_list;
while (ci)
{
if (ci->brdno == cardID) /* found valid device */
{
if (deviceID < ci->max_port) /* comet is supported */
base = ((unsigned long) ci->port[deviceID].cometbase);
break;
}
ci = ci->next; /* next board, if any */
}
return (base);
}
#endif /*** CONFIG_SBE_PMCC4_NCOMM ***/
/*** End-of-File ***/
| gpl-2.0 |
sabyasachi/ctags-exuberant | get.c | 51 | 15984 | /*
* $Id: get.c 559 2007-06-17 03:30:09Z elliotth $
*
* Copyright (c) 1996-2002, Darren Hiebert
*
* This source code is released for free distribution under the terms of the
* GNU General Public License.
*
* This module contains the high level source read functions (preprocessor
* directives are handled within this level).
*/
/*
* INCLUDE FILES
*/
#include "general.h" /* must always come first */
#include <string.h>
#include "debug.h"
#include "entry.h"
#include "get.h"
#include "options.h"
#include "read.h"
#include "vstring.h"
/*
* MACROS
*/
#define stringMatch(s1,s2) (strcmp (s1,s2) == 0)
#define isspacetab(c) ((c) == SPACE || (c) == TAB)
/*
* DATA DECLARATIONS
*/
typedef enum { COMMENT_NONE, COMMENT_C, COMMENT_CPLUS } Comment;
enum eCppLimits {
MaxCppNestingLevel = 20,
MaxDirectiveName = 10
};
/* Defines the one nesting level of a preprocessor conditional.
*/
typedef struct sConditionalInfo {
boolean ignoreAllBranches; /* ignoring parent conditional branch */
boolean singleBranch; /* choose only one branch */
boolean branchChosen; /* branch already selected */
boolean ignoring; /* current ignore state */
} conditionalInfo;
enum eState {
DRCTV_NONE, /* no known directive - ignore to end of line */
DRCTV_DEFINE, /* "#define" encountered */
DRCTV_HASH, /* initial '#' read; determine directive */
DRCTV_IF, /* "#if" or "#ifdef" encountered */
DRCTV_PRAGMA, /* #pragma encountered */
DRCTV_UNDEF /* "#undef" encountered */
};
/* Defines the current state of the pre-processor.
*/
typedef struct sCppState {
int ungetch, ungetch2; /* ungotten characters, if any */
boolean resolveRequired; /* must resolve if/else/elif/endif branch */
boolean hasAtLiteralStrings; /* supports @"c:\" strings */
struct sDirective {
enum eState state; /* current directive being processed */
boolean accept; /* is a directive syntactically permitted? */
vString * name; /* macro name */
unsigned int nestLevel; /* level 0 is not used */
conditionalInfo ifdef [MaxCppNestingLevel];
} directive;
} cppState;
/*
* DATA DEFINITIONS
*/
/* Use brace formatting to detect end of block.
*/
static boolean BraceFormat = FALSE;
static cppState Cpp = {
'\0', '\0', /* ungetch characters */
FALSE, /* resolveRequired */
FALSE, /* hasAtLiteralStrings */
{
DRCTV_NONE, /* state */
FALSE, /* accept */
NULL, /* tag name */
0, /* nestLevel */
{ {FALSE,FALSE,FALSE,FALSE} } /* ifdef array */
} /* directive */
};
/*
* FUNCTION DEFINITIONS
*/
extern boolean isBraceFormat (void)
{
return BraceFormat;
}
extern unsigned int getDirectiveNestLevel (void)
{
return Cpp.directive.nestLevel;
}
extern void cppInit (const boolean state, const boolean hasAtLiteralStrings)
{
BraceFormat = state;
Cpp.ungetch = '\0';
Cpp.ungetch2 = '\0';
Cpp.resolveRequired = FALSE;
Cpp.hasAtLiteralStrings = hasAtLiteralStrings;
Cpp.directive.state = DRCTV_NONE;
Cpp.directive.accept = TRUE;
Cpp.directive.nestLevel = 0;
Cpp.directive.ifdef [0].ignoreAllBranches = FALSE;
Cpp.directive.ifdef [0].singleBranch = FALSE;
Cpp.directive.ifdef [0].branchChosen = FALSE;
Cpp.directive.ifdef [0].ignoring = FALSE;
if (Cpp.directive.name == NULL)
Cpp.directive.name = vStringNew ();
else
vStringClear (Cpp.directive.name);
}
extern void cppTerminate (void)
{
if (Cpp.directive.name != NULL)
{
vStringDelete (Cpp.directive.name);
Cpp.directive.name = NULL;
}
}
extern void cppBeginStatement (void)
{
Cpp.resolveRequired = TRUE;
}
extern void cppEndStatement (void)
{
Cpp.resolveRequired = FALSE;
}
/*
* Scanning functions
*
* This section handles preprocessor directives. It strips out all
* directives and may emit a tag for #define directives.
*/
/* This puts a character back into the input queue for the source File.
* Up to two characters may be ungotten.
*/
extern void cppUngetc (const int c)
{
Assert (Cpp.ungetch2 == '\0');
Cpp.ungetch2 = Cpp.ungetch;
Cpp.ungetch = c;
}
/* Reads a directive, whose first character is given by "c", into "name".
*/
static boolean readDirective (int c, char *const name, unsigned int maxLength)
{
unsigned int i;
for (i = 0 ; i < maxLength - 1 ; ++i)
{
if (i > 0)
{
c = fileGetc ();
if (c == EOF || ! isalpha (c))
{
fileUngetc (c);
break;
}
}
name [i] = c;
}
name [i] = '\0'; /* null terminate */
return (boolean) isspacetab (c);
}
/* Reads an identifier, whose first character is given by "c", into "tag",
* together with the file location and corresponding line number.
*/
static void readIdentifier (int c, vString *const name)
{
vStringClear (name);
do
{
vStringPut (name, c);
} while (c = fileGetc (), (c != EOF && isident (c)));
fileUngetc (c);
vStringTerminate (name);
}
static conditionalInfo *currentConditional (void)
{
return &Cpp.directive.ifdef [Cpp.directive.nestLevel];
}
static boolean isIgnore (void)
{
return Cpp.directive.ifdef [Cpp.directive.nestLevel].ignoring;
}
static boolean setIgnore (const boolean ignore)
{
return Cpp.directive.ifdef [Cpp.directive.nestLevel].ignoring = ignore;
}
static boolean isIgnoreBranch (void)
{
conditionalInfo *const ifdef = currentConditional ();
/* Force a single branch if an incomplete statement is discovered
* en route. This may have allowed earlier branches containing complete
* statements to be followed, but we must follow no further branches.
*/
if (Cpp.resolveRequired && ! BraceFormat)
ifdef->singleBranch = TRUE;
/* We will ignore this branch in the following cases:
*
* 1. We are ignoring all branches (conditional was within an ignored
* branch of the parent conditional)
* 2. A branch has already been chosen and either of:
* a. A statement was incomplete upon entering the conditional
* b. A statement is incomplete upon encountering a branch
*/
return (boolean) (ifdef->ignoreAllBranches ||
(ifdef->branchChosen && ifdef->singleBranch));
}
static void chooseBranch (void)
{
if (! BraceFormat)
{
conditionalInfo *const ifdef = currentConditional ();
ifdef->branchChosen = (boolean) (ifdef->singleBranch ||
Cpp.resolveRequired);
}
}
/* Pushes one nesting level for an #if directive, indicating whether or not
* the branch should be ignored and whether a branch has already been chosen.
*/
static boolean pushConditional (const boolean firstBranchChosen)
{
const boolean ignoreAllBranches = isIgnore (); /* current ignore */
boolean ignoreBranch = FALSE;
if (Cpp.directive.nestLevel < (unsigned int) MaxCppNestingLevel - 1)
{
conditionalInfo *ifdef;
++Cpp.directive.nestLevel;
ifdef = currentConditional ();
/* We take a snapshot of whether there is an incomplete statement in
* progress upon encountering the preprocessor conditional. If so,
* then we will flag that only a single branch of the conditional
* should be followed.
*/
ifdef->ignoreAllBranches = ignoreAllBranches;
ifdef->singleBranch = Cpp.resolveRequired;
ifdef->branchChosen = firstBranchChosen;
ifdef->ignoring = (boolean) (ignoreAllBranches || (
! firstBranchChosen && ! BraceFormat &&
(ifdef->singleBranch || !Option.if0)));
ignoreBranch = ifdef->ignoring;
}
return ignoreBranch;
}
/* Pops one nesting level for an #endif directive.
*/
static boolean popConditional (void)
{
if (Cpp.directive.nestLevel > 0)
--Cpp.directive.nestLevel;
return isIgnore ();
}
static void makeDefineTag (const char *const name)
{
const boolean isFileScope = (boolean) (! isHeaderFile ());
if (includingDefineTags () &&
(! isFileScope || Option.include.fileScope))
{
tagEntryInfo e;
initTagEntry (&e, name);
e.lineNumberEntry = (boolean) (Option.locate != EX_PATTERN);
e.isFileScope = isFileScope;
e.truncateLine = TRUE;
e.kindName = "macro";
e.kind = 'd';
makeTagEntry (&e);
}
}
static void directiveDefine (const int c)
{
if (isident1 (c))
{
readIdentifier (c, Cpp.directive.name);
if (! isIgnore ())
makeDefineTag (vStringValue (Cpp.directive.name));
}
Cpp.directive.state = DRCTV_NONE;
}
static void directivePragma (int c)
{
if (isident1 (c))
{
readIdentifier (c, Cpp.directive.name);
if (stringMatch (vStringValue (Cpp.directive.name), "weak"))
{
/* generate macro tag for weak name */
do
{
c = fileGetc ();
} while (c == SPACE);
if (isident1 (c))
{
readIdentifier (c, Cpp.directive.name);
makeDefineTag (vStringValue (Cpp.directive.name));
}
}
}
Cpp.directive.state = DRCTV_NONE;
}
static boolean directiveIf (const int c)
{
DebugStatement ( const boolean ignore0 = isIgnore (); )
const boolean ignore = pushConditional ((boolean) (c != '0'));
Cpp.directive.state = DRCTV_NONE;
DebugStatement ( debugCppNest (TRUE, Cpp.directive.nestLevel);
if (ignore != ignore0) debugCppIgnore (ignore); )
return ignore;
}
static boolean directiveHash (const int c)
{
boolean ignore = FALSE;
char directive [MaxDirectiveName];
DebugStatement ( const boolean ignore0 = isIgnore (); )
readDirective (c, directive, MaxDirectiveName);
if (stringMatch (directive, "define"))
Cpp.directive.state = DRCTV_DEFINE;
else if (stringMatch (directive, "undef"))
Cpp.directive.state = DRCTV_UNDEF;
else if (strncmp (directive, "if", (size_t) 2) == 0)
Cpp.directive.state = DRCTV_IF;
else if (stringMatch (directive, "elif") ||
stringMatch (directive, "else"))
{
ignore = setIgnore (isIgnoreBranch ());
if (! ignore && stringMatch (directive, "else"))
chooseBranch ();
Cpp.directive.state = DRCTV_NONE;
DebugStatement ( if (ignore != ignore0) debugCppIgnore (ignore); )
}
else if (stringMatch (directive, "endif"))
{
DebugStatement ( debugCppNest (FALSE, Cpp.directive.nestLevel); )
ignore = popConditional ();
Cpp.directive.state = DRCTV_NONE;
DebugStatement ( if (ignore != ignore0) debugCppIgnore (ignore); )
}
else if (stringMatch (directive, "pragma"))
Cpp.directive.state = DRCTV_PRAGMA;
else
Cpp.directive.state = DRCTV_NONE;
return ignore;
}
/* Handles a pre-processor directive whose first character is given by "c".
*/
static boolean handleDirective (const int c)
{
boolean ignore = isIgnore ();
switch (Cpp.directive.state)
{
case DRCTV_NONE: ignore = isIgnore (); break;
case DRCTV_DEFINE: directiveDefine (c); break;
case DRCTV_HASH: ignore = directiveHash (c); break;
case DRCTV_IF: ignore = directiveIf (c); break;
case DRCTV_PRAGMA: directivePragma (c); break;
case DRCTV_UNDEF: directiveDefine (c); break;
}
return ignore;
}
/* Called upon reading of a slash ('/') characters, determines whether a
* comment is encountered, and its type.
*/
static Comment isComment (void)
{
Comment comment;
const int next = fileGetc ();
if (next == '*')
comment = COMMENT_C;
else if (next == '/')
comment = COMMENT_CPLUS;
else
{
fileUngetc (next);
comment = COMMENT_NONE;
}
return comment;
}
/* Skips over a C style comment. According to ANSI specification a comment
* is treated as white space, so we perform this substitution.
*/
int skipOverCComment (void)
{
int c = fileGetc ();
while (c != EOF)
{
if (c != '*')
c = fileGetc ();
else
{
const int next = fileGetc ();
if (next != '/')
c = next;
else
{
c = SPACE; /* replace comment with space */
break;
}
}
}
return c;
}
/* Skips over a C++ style comment.
*/
static int skipOverCplusComment (void)
{
int c;
while ((c = fileGetc ()) != EOF)
{
if (c == BACKSLASH)
fileGetc (); /* throw away next character, too */
else if (c == NEWLINE)
break;
}
return c;
}
/* Skips to the end of a string, returning a special character to
* symbolically represent a generic string.
*/
static int skipToEndOfString (boolean ignoreBackslash)
{
int c;
while ((c = fileGetc ()) != EOF)
{
if (c == BACKSLASH && ! ignoreBackslash)
fileGetc (); /* throw away next character, too */
else if (c == DOUBLE_QUOTE)
break;
}
return STRING_SYMBOL; /* symbolic representation of string */
}
/* Skips to the end of the three (possibly four) 'c' sequence, returning a
* special character to symbolically represent a generic character.
* Also detects Vera numbers that include a base specifier (ie. 'b1010).
*/
static int skipToEndOfChar (void)
{
int c;
int count = 0, veraBase = '\0';
while ((c = fileGetc ()) != EOF)
{
++count;
if (c == BACKSLASH)
fileGetc (); /* throw away next character, too */
else if (c == SINGLE_QUOTE)
break;
else if (c == NEWLINE)
{
fileUngetc (c);
break;
}
else if (count == 1 && strchr ("DHOB", toupper (c)) != NULL)
veraBase = c;
else if (veraBase != '\0' && ! isalnum (c))
{
fileUngetc (c);
break;
}
}
return CHAR_SYMBOL; /* symbolic representation of character */
}
/* This function returns the next character, stripping out comments,
* C pre-processor directives, and the contents of single and double
* quoted strings. In short, strip anything which places a burden upon
* the tokenizer.
*/
extern int cppGetc (void)
{
boolean directive = FALSE;
boolean ignore = FALSE;
int c;
if (Cpp.ungetch != '\0')
{
c = Cpp.ungetch;
Cpp.ungetch = Cpp.ungetch2;
Cpp.ungetch2 = '\0';
return c; /* return here to avoid re-calling debugPutc () */
}
else do
{
c = fileGetc ();
process:
switch (c)
{
case EOF:
ignore = FALSE;
directive = FALSE;
break;
case TAB:
case SPACE:
break; /* ignore most white space */
case NEWLINE:
if (directive && ! ignore)
directive = FALSE;
Cpp.directive.accept = TRUE;
break;
case DOUBLE_QUOTE:
Cpp.directive.accept = FALSE;
c = skipToEndOfString (FALSE);
break;
case '#':
if (Cpp.directive.accept)
{
directive = TRUE;
Cpp.directive.state = DRCTV_HASH;
Cpp.directive.accept = FALSE;
}
break;
case SINGLE_QUOTE:
Cpp.directive.accept = FALSE;
c = skipToEndOfChar ();
break;
case '/':
{
const Comment comment = isComment ();
if (comment == COMMENT_C)
c = skipOverCComment ();
else if (comment == COMMENT_CPLUS)
{
c = skipOverCplusComment ();
if (c == NEWLINE)
fileUngetc (c);
}
else
Cpp.directive.accept = FALSE;
break;
}
case BACKSLASH:
{
int next = fileGetc ();
if (next == NEWLINE)
continue;
else if (next == '?')
cppUngetc (next);
else
fileUngetc (next);
break;
}
case '?':
{
int next = fileGetc ();
if (next != '?')
fileUngetc (next);
else
{
next = fileGetc ();
switch (next)
{
case '(': c = '['; break;
case ')': c = ']'; break;
case '<': c = '{'; break;
case '>': c = '}'; break;
case '/': c = BACKSLASH; goto process;
case '!': c = '|'; break;
case SINGLE_QUOTE: c = '^'; break;
case '-': c = '~'; break;
case '=': c = '#'; goto process;
default:
fileUngetc (next);
cppUngetc ('?');
break;
}
}
} break;
default:
if (c == '@' && Cpp.hasAtLiteralStrings)
{
int next = fileGetc ();
if (next == DOUBLE_QUOTE)
{
Cpp.directive.accept = FALSE;
c = skipToEndOfString (TRUE);
break;
}
}
Cpp.directive.accept = FALSE;
if (directive)
ignore = handleDirective (c);
break;
}
} while (directive || ignore);
DebugStatement ( debugPutc (DEBUG_CPP, c); )
DebugStatement ( if (c == NEWLINE)
debugPrintf (DEBUG_CPP, "%6ld: ", getInputLineNumber () + 1); )
return c;
}
/* vi:set tabstop=4 shiftwidth=4: */
| gpl-2.0 |
twobob/buildroot-kindle | output/build/host-ncurses-5.9/ncurses/base/lib_addch.c | 51 | 15644 | /****************************************************************************
* Copyright (c) 1998-2009,2010 Free Software Foundation, Inc. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/*
** lib_addch.c
**
** The routine waddch().
**
*/
#include <curses.priv.h>
#include <ctype.h>
MODULE_ID("$Id: lib_addch.c,v 1.124 2010/04/24 22:41:05 tom Exp $")
static const NCURSES_CH_T blankchar = NewChar(BLANK_TEXT);
/*
* Ugly microtweaking alert. Everything from here to end of module is
* likely to be speed-critical -- profiling data sure says it is!
* Most of the important screen-painting functions are shells around
* waddch(). So we make every effort to reduce function-call overhead
* by inlining stuff, even at the cost of making wrapped copies for
* export. Also we supply some internal versions that don't call the
* window sync hook, for use by string-put functions.
*/
/* Return bit mask for clearing color pair number if given ch has color */
#define COLOR_MASK(ch) (~(attr_t)((ch) & A_COLOR ? A_COLOR : 0))
static NCURSES_INLINE NCURSES_CH_T
render_char(WINDOW *win, NCURSES_CH_T ch)
/* compute a rendition of the given char correct for the current context */
{
attr_t a = WINDOW_ATTRS(win);
int pair = GetPair(ch);
if (ISBLANK(ch)
&& AttrOf(ch) == A_NORMAL
&& pair == 0) {
/* color/pair in attrs has precedence over bkgrnd */
ch = win->_nc_bkgd;
SetAttr(ch, a | AttrOf(win->_nc_bkgd));
if ((pair = GET_WINDOW_PAIR(win)) == 0)
pair = GetPair(win->_nc_bkgd);
SetPair(ch, pair);
} else {
/* color in attrs has precedence over bkgrnd */
a |= AttrOf(win->_nc_bkgd) & COLOR_MASK(a);
/* color in ch has precedence */
if (pair == 0) {
if ((pair = GET_WINDOW_PAIR(win)) == 0)
pair = GetPair(win->_nc_bkgd);
}
AddAttr(ch, (a & COLOR_MASK(AttrOf(ch))));
SetPair(ch, pair);
}
TR(TRACE_VIRTPUT,
("render_char bkg %s (%d), attrs %s (%d) -> ch %s (%d)",
_tracech_t2(1, CHREF(win->_nc_bkgd)),
GetPair(win->_nc_bkgd),
_traceattr(WINDOW_ATTRS(win)),
GET_WINDOW_PAIR(win),
_tracech_t2(3, CHREF(ch)),
GetPair(ch)));
return (ch);
}
NCURSES_EXPORT(NCURSES_CH_T)
_nc_render(WINDOW *win, NCURSES_CH_T ch)
/* make render_char() visible while still allowing us to inline it below */
{
return render_char(win, ch);
}
/* check if position is legal; if not, return error */
#ifndef NDEBUG /* treat this like an assertion */
#define CHECK_POSITION(win, x, y) \
if (y > win->_maxy \
|| x > win->_maxx \
|| y < 0 \
|| x < 0) { \
TR(TRACE_VIRTPUT, ("Alert! Win=%p _curx = %d, _cury = %d " \
"(_maxx = %d, _maxy = %d)", win, x, y, \
win->_maxx, win->_maxy)); \
return(ERR); \
}
#else
#define CHECK_POSITION(win, x, y) /* nothing */
#endif
static bool
newline_forces_scroll(WINDOW *win, NCURSES_SIZE_T * ypos)
{
bool result = FALSE;
if (*ypos >= win->_regtop && *ypos == win->_regbottom) {
*ypos = win->_regbottom;
result = TRUE;
} else {
*ypos = (NCURSES_SIZE_T) (*ypos + 1);
}
return result;
}
/*
* The _WRAPPED flag is useful only for telling an application that we've just
* wrapped the cursor. We don't do anything with this flag except set it when
* wrapping, and clear it whenever we move the cursor. If we try to wrap at
* the lower-right corner of a window, we cannot move the cursor (since that
* wouldn't be legal). So we return an error (which is what SVr4 does).
* Unlike SVr4, we can successfully add a character to the lower-right corner
* (Solaris 2.6 does this also, however).
*/
static int
wrap_to_next_line(WINDOW *win)
{
win->_flags |= _WRAPPED;
if (newline_forces_scroll(win, &(win->_cury))) {
win->_curx = win->_maxx;
if (!win->_scroll)
return (ERR);
scroll(win);
}
win->_curx = 0;
return (OK);
}
#if USE_WIDEC_SUPPORT
static int waddch_literal(WINDOW *, NCURSES_CH_T);
/*
* Fill the given number of cells with blanks using the current background
* rendition. This saves/restores the current x-position.
*/
static void
fill_cells(WINDOW *win, int count)
{
NCURSES_CH_T blank = blankchar;
int save_x = win->_curx;
int save_y = win->_cury;
while (count-- > 0) {
if (waddch_literal(win, blank) == ERR)
break;
}
win->_curx = (NCURSES_SIZE_T) save_x;
win->_cury = (NCURSES_SIZE_T) save_y;
}
#endif
/*
* Build up the bytes for a multibyte character, returning the length when
* complete (a positive number), -1 for error and -2 for incomplete.
*/
#if USE_WIDEC_SUPPORT
NCURSES_EXPORT(int)
_nc_build_wch(WINDOW *win, ARG_CH_T ch)
{
char *buffer = WINDOW_EXT(win, addch_work);
int len;
int x = win->_curx;
int y = win->_cury;
mbstate_t state;
wchar_t result;
if ((WINDOW_EXT(win, addch_used) != 0) &&
(WINDOW_EXT(win, addch_x) != x ||
WINDOW_EXT(win, addch_y) != y)) {
/* discard the incomplete multibyte character */
WINDOW_EXT(win, addch_used) = 0;
TR(TRACE_VIRTPUT,
("Alert discarded multibyte on move (%d,%d) -> (%d,%d)",
WINDOW_EXT(win, addch_y), WINDOW_EXT(win, addch_x),
y, x));
}
WINDOW_EXT(win, addch_x) = x;
WINDOW_EXT(win, addch_y) = y;
init_mb(state);
buffer[WINDOW_EXT(win, addch_used)] = (char) CharOf(CHDEREF(ch));
WINDOW_EXT(win, addch_used) += 1;
buffer[WINDOW_EXT(win, addch_used)] = '\0';
if ((len = (int) mbrtowc(&result,
buffer,
WINDOW_EXT(win, addch_used), &state)) > 0) {
attr_t attrs = AttrOf(CHDEREF(ch));
if_EXT_COLORS(int pair = GetPair(CHDEREF(ch)));
SetChar(CHDEREF(ch), result, attrs);
if_EXT_COLORS(SetPair(CHDEREF(ch), pair));
WINDOW_EXT(win, addch_used) = 0;
} else if (len == -1) {
/*
* An error occurred. We could either discard everything,
* or assume that the error was in the previous input.
* Try the latter.
*/
TR(TRACE_VIRTPUT, ("Alert! mbrtowc returns error"));
/* handle this with unctrl() */
WINDOW_EXT(win, addch_used) = 0;
}
return len;
}
#endif /* USE_WIDEC_SUPPORT */
static
#if !USE_WIDEC_SUPPORT /* cannot be inline if it is recursive */
NCURSES_INLINE
#endif
int
waddch_literal(WINDOW *win, NCURSES_CH_T ch)
{
int x;
int y;
struct ldat *line;
x = win->_curx;
y = win->_cury;
CHECK_POSITION(win, x, y);
ch = render_char(win, ch);
line = win->_line + y;
CHANGED_CELL(line, x);
/*
* Build up multibyte characters until we have a wide-character.
*/
#if NCURSES_SP_FUNCS
#define DeriveSP() SCREEN *sp = _nc_screen_of(win);
#else
#define DeriveSP() /*nothing */
#endif
if_WIDEC({
DeriveSP();
if (WINDOW_EXT(win, addch_used) != 0 || !Charable(ch)) {
int len = _nc_build_wch(win, CHREF(ch));
if (len >= -1) {
attr_t attr = AttrOf(ch);
/* handle EILSEQ (i.e., when len >= -1) */
if (len == -1 && is8bits(CharOf(ch))) {
int rc = OK;
const char *s = NCURSES_SP_NAME(unctrl)
(NCURSES_SP_ARGx (chtype) CharOf(ch));
if (s[1] != '\0') {
while (*s != '\0') {
rc = waddch(win, UChar(*s) | attr);
if (rc != OK)
break;
++s;
}
return rc;
}
}
if (len == -1)
return waddch(win, ' ' | attr);
} else {
return OK;
}
}
});
/*
* Non-spacing characters are added to the current cell.
*
* Spacing characters that are wider than one column require some display
* adjustments.
*/
if_WIDEC({
int len = wcwidth(CharOf(ch));
int i;
int j;
wchar_t *chars;
if (len == 0) { /* non-spacing */
if ((x > 0 && y >= 0)
|| (win->_maxx >= 0 && win->_cury >= 1)) {
if (x > 0 && y >= 0)
chars = (win->_line[y].text[x - 1].chars);
else
chars = (win->_line[y - 1].text[win->_maxx].chars);
for (i = 0; i < CCHARW_MAX; ++i) {
if (chars[i] == 0) {
TR(TRACE_VIRTPUT,
("added non-spacing %d: %x",
x, (int) CharOf(ch)));
chars[i] = CharOf(ch);
break;
}
}
}
goto testwrapping;
} else if (len > 1) { /* multi-column characters */
/*
* Check if the character will fit on the current line. If it does
* not fit, fill in the remainder of the line with blanks. and
* move to the next line.
*/
if (len > win->_maxx + 1) {
TR(TRACE_VIRTPUT, ("character will not fit"));
return ERR;
} else if (x + len > win->_maxx + 1) {
int count = win->_maxx + 1 - x;
TR(TRACE_VIRTPUT, ("fill %d remaining cells", count));
fill_cells(win, count);
if (wrap_to_next_line(win) == ERR)
return ERR;
x = win->_curx;
y = win->_cury;
line = win->_line + y;
}
/*
* Check for cells which are orphaned by adding this character, set
* those to blanks.
*
* FIXME: this actually could fill j-i cells, more complicated to
* setup though.
*/
for (i = 0; i < len; ++i) {
if (isWidecBase(win->_line[y].text[x + i])) {
break;
} else if (isWidecExt(win->_line[y].text[x + i])) {
for (j = i; x + j <= win->_maxx; ++j) {
if (!isWidecExt(win->_line[y].text[x + j])) {
TR(TRACE_VIRTPUT, ("fill %d orphan cells", j));
fill_cells(win, j);
break;
}
}
break;
}
}
/*
* Finally, add the cells for this character.
*/
for (i = 0; i < len; ++i) {
NCURSES_CH_T value = ch;
SetWidecExt(value, i);
TR(TRACE_VIRTPUT, ("multicolumn %d:%d (%d,%d)",
i + 1, len,
win->_begy + y, win->_begx + x));
line->text[x] = value;
CHANGED_CELL(line, x);
++x;
}
goto testwrapping;
}
});
/*
* Single-column characters.
*/
line->text[x++] = ch;
/*
* This label is used only for wide-characters.
*/
if_WIDEC(
testwrapping:
);
TR(TRACE_VIRTPUT, ("cell (%ld, %ld..%d) = %s",
(long) win->_cury, (long) win->_curx, x - 1,
_tracech_t(CHREF(ch))));
if (x > win->_maxx) {
return wrap_to_next_line(win);
}
win->_curx = (NCURSES_SIZE_T) x;
return OK;
}
static NCURSES_INLINE int
waddch_nosync(WINDOW *win, const NCURSES_CH_T ch)
/* the workhorse function -- add a character to the given window */
{
NCURSES_SIZE_T x, y;
chtype t = (chtype) CharOf(ch);
#if USE_WIDEC_SUPPORT || NCURSES_SP_FUNCS || USE_REENTRANT
SCREEN *sp = _nc_screen_of(win);
#endif
const char *s = NCURSES_SP_NAME(unctrl) (NCURSES_SP_ARGx t);
int tabsize = 8;
/*
* If we are using the alternate character set, forget about locale.
* Otherwise, if unctrl() returns a single-character or the locale
* claims the code is printable, treat it that way.
*/
if ((AttrOf(ch) & A_ALTCHARSET)
|| (
#if USE_WIDEC_SUPPORT
(sp != 0 && sp->_legacy_coding) &&
#endif
s[1] == 0
)
|| (
isprint(t)
#if USE_WIDEC_SUPPORT
|| ((sp == 0 || !sp->_legacy_coding) &&
(WINDOW_EXT(win, addch_used)
|| !_nc_is_charable(CharOf(ch))))
#endif
))
return waddch_literal(win, ch);
/*
* Handle carriage control and other codes that are not printable, or are
* known to expand to more than one character according to unctrl().
*/
x = win->_curx;
y = win->_cury;
switch (t) {
case '\t':
#if USE_REENTRANT
tabsize = *ptrTabsize(sp);
#else
tabsize = TABSIZE;
#endif
x = (NCURSES_SIZE_T) (x + (tabsize - (x % tabsize)));
/*
* Space-fill the tab on the bottom line so that we'll get the
* "correct" cursor position.
*/
if ((!win->_scroll && (y == win->_regbottom))
|| (x <= win->_maxx)) {
NCURSES_CH_T blank = blankchar;
AddAttr(blank, AttrOf(ch));
while (win->_curx < x) {
if (waddch_literal(win, blank) == ERR)
return (ERR);
}
break;
} else {
wclrtoeol(win);
win->_flags |= _WRAPPED;
if (newline_forces_scroll(win, &y)) {
x = win->_maxx;
if (win->_scroll) {
scroll(win);
x = 0;
}
} else {
x = 0;
}
}
break;
case '\n':
wclrtoeol(win);
if (newline_forces_scroll(win, &y)) {
if (win->_scroll)
scroll(win);
else
return (ERR);
}
/* FALLTHRU */
case '\r':
x = 0;
win->_flags &= ~_WRAPPED;
break;
case '\b':
if (x == 0)
return (OK);
x--;
win->_flags &= ~_WRAPPED;
break;
default:
while (*s) {
NCURSES_CH_T sch;
SetChar(sch, *s++, AttrOf(ch));
if_EXT_COLORS(SetPair(sch, GetPair(ch)));
if (waddch_literal(win, sch) == ERR)
return ERR;
}
return (OK);
}
win->_curx = x;
win->_cury = y;
return (OK);
}
NCURSES_EXPORT(int)
_nc_waddch_nosync(WINDOW *win, const NCURSES_CH_T c)
/* export copy of waddch_nosync() so the string-put functions can use it */
{
return (waddch_nosync(win, c));
}
/*
* The versions below call _nc_synchook(). We wanted to avoid this in the
* version exported for string puts; they'll call _nc_synchook once at end
* of run.
*/
/* These are actual entry points */
NCURSES_EXPORT(int)
waddch(WINDOW *win, const chtype ch)
{
int code = ERR;
NCURSES_CH_T wch;
SetChar2(wch, ch);
TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("waddch(%p, %s)"), (void *) win,
_tracechtype(ch)));
if (win && (waddch_nosync(win, wch) != ERR)) {
_nc_synchook(win);
code = OK;
}
TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
return (code);
}
NCURSES_EXPORT(int)
wechochar(WINDOW *win, const chtype ch)
{
int code = ERR;
NCURSES_CH_T wch;
SetChar2(wch, ch);
TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wechochar(%p, %s)"),
(void *) win,
_tracechtype(ch)));
if (win && (waddch_nosync(win, wch) != ERR)) {
bool save_immed = win->_immed;
win->_immed = TRUE;
_nc_synchook(win);
win->_immed = save_immed;
code = OK;
}
TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
return (code);
}
| gpl-2.0 |
ktraghavendra/linux | drivers/gpu/drm/msm/mdp/mdp5/mdp5_kms.c | 51 | 19450 | /*
* Copyright (c) 2014, The Linux Foundation. All rights reserved.
* Copyright (C) 2013 Red Hat
* Author: Rob Clark <robdclark@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "msm_drv.h"
#include "msm_mmu.h"
#include "mdp5_kms.h"
static const char *iommu_ports[] = {
"mdp_0",
};
static int mdp5_hw_init(struct msm_kms *kms)
{
struct mdp5_kms *mdp5_kms = to_mdp5_kms(to_mdp_kms(kms));
struct drm_device *dev = mdp5_kms->dev;
unsigned long flags;
pm_runtime_get_sync(dev->dev);
/* Magic unknown register writes:
*
* W VBIF:0x004 00000001 (mdss_mdp.c:839)
* W MDP5:0x2e0 0xe9 (mdss_mdp.c:839)
* W MDP5:0x2e4 0x55 (mdss_mdp.c:839)
* W MDP5:0x3ac 0xc0000ccc (mdss_mdp.c:839)
* W MDP5:0x3b4 0xc0000ccc (mdss_mdp.c:839)
* W MDP5:0x3bc 0xcccccc (mdss_mdp.c:839)
* W MDP5:0x4a8 0xcccc0c0 (mdss_mdp.c:839)
* W MDP5:0x4b0 0xccccc0c0 (mdss_mdp.c:839)
* W MDP5:0x4b8 0xccccc000 (mdss_mdp.c:839)
*
* Downstream fbdev driver gets these register offsets/values
* from DT.. not really sure what these registers are or if
* different values for different boards/SoC's, etc. I guess
* they are the golden registers.
*
* Not setting these does not seem to cause any problem. But
* we may be getting lucky with the bootloader initializing
* them for us. OTOH, if we can always count on the bootloader
* setting the golden registers, then perhaps we don't need to
* care.
*/
spin_lock_irqsave(&mdp5_kms->resource_lock, flags);
mdp5_write(mdp5_kms, REG_MDP5_MDP_DISP_INTF_SEL(0), 0);
spin_unlock_irqrestore(&mdp5_kms->resource_lock, flags);
mdp5_ctlm_hw_reset(mdp5_kms->ctlm);
pm_runtime_put_sync(dev->dev);
return 0;
}
static void mdp5_prepare_commit(struct msm_kms *kms, struct drm_atomic_state *state)
{
struct mdp5_kms *mdp5_kms = to_mdp5_kms(to_mdp_kms(kms));
mdp5_enable(mdp5_kms);
}
static void mdp5_complete_commit(struct msm_kms *kms, struct drm_atomic_state *state)
{
int i;
struct mdp5_kms *mdp5_kms = to_mdp5_kms(to_mdp_kms(kms));
int nplanes = mdp5_kms->dev->mode_config.num_total_plane;
for (i = 0; i < nplanes; i++) {
struct drm_plane *plane = state->planes[i];
struct drm_plane_state *plane_state = state->plane_states[i];
if (!plane)
continue;
mdp5_plane_complete_commit(plane, plane_state);
}
mdp5_disable(mdp5_kms);
}
static void mdp5_wait_for_crtc_commit_done(struct msm_kms *kms,
struct drm_crtc *crtc)
{
mdp5_crtc_wait_for_commit_done(crtc);
}
static long mdp5_round_pixclk(struct msm_kms *kms, unsigned long rate,
struct drm_encoder *encoder)
{
return rate;
}
static int mdp5_set_split_display(struct msm_kms *kms,
struct drm_encoder *encoder,
struct drm_encoder *slave_encoder,
bool is_cmd_mode)
{
if (is_cmd_mode)
return mdp5_cmd_encoder_set_split_display(encoder,
slave_encoder);
else
return mdp5_encoder_set_split_display(encoder, slave_encoder);
}
static void mdp5_preclose(struct msm_kms *kms, struct drm_file *file)
{
struct mdp5_kms *mdp5_kms = to_mdp5_kms(to_mdp_kms(kms));
struct msm_drm_private *priv = mdp5_kms->dev->dev_private;
unsigned i;
for (i = 0; i < priv->num_crtcs; i++)
mdp5_crtc_cancel_pending_flip(priv->crtcs[i], file);
}
static void mdp5_destroy(struct msm_kms *kms)
{
struct mdp5_kms *mdp5_kms = to_mdp5_kms(to_mdp_kms(kms));
struct msm_mmu *mmu = mdp5_kms->mmu;
mdp5_irq_domain_fini(mdp5_kms);
if (mmu) {
mmu->funcs->detach(mmu, iommu_ports, ARRAY_SIZE(iommu_ports));
mmu->funcs->destroy(mmu);
}
if (mdp5_kms->ctlm)
mdp5_ctlm_destroy(mdp5_kms->ctlm);
if (mdp5_kms->smp)
mdp5_smp_destroy(mdp5_kms->smp);
if (mdp5_kms->cfg)
mdp5_cfg_destroy(mdp5_kms->cfg);
kfree(mdp5_kms);
}
static const struct mdp_kms_funcs kms_funcs = {
.base = {
.hw_init = mdp5_hw_init,
.irq_preinstall = mdp5_irq_preinstall,
.irq_postinstall = mdp5_irq_postinstall,
.irq_uninstall = mdp5_irq_uninstall,
.irq = mdp5_irq,
.enable_vblank = mdp5_enable_vblank,
.disable_vblank = mdp5_disable_vblank,
.prepare_commit = mdp5_prepare_commit,
.complete_commit = mdp5_complete_commit,
.wait_for_crtc_commit_done = mdp5_wait_for_crtc_commit_done,
.get_format = mdp_get_format,
.round_pixclk = mdp5_round_pixclk,
.set_split_display = mdp5_set_split_display,
.preclose = mdp5_preclose,
.destroy = mdp5_destroy,
},
.set_irqmask = mdp5_set_irqmask,
};
int mdp5_disable(struct mdp5_kms *mdp5_kms)
{
DBG("");
clk_disable_unprepare(mdp5_kms->ahb_clk);
clk_disable_unprepare(mdp5_kms->axi_clk);
clk_disable_unprepare(mdp5_kms->core_clk);
if (mdp5_kms->lut_clk)
clk_disable_unprepare(mdp5_kms->lut_clk);
return 0;
}
int mdp5_enable(struct mdp5_kms *mdp5_kms)
{
DBG("");
clk_prepare_enable(mdp5_kms->ahb_clk);
clk_prepare_enable(mdp5_kms->axi_clk);
clk_prepare_enable(mdp5_kms->core_clk);
if (mdp5_kms->lut_clk)
clk_prepare_enable(mdp5_kms->lut_clk);
return 0;
}
static struct drm_encoder *construct_encoder(struct mdp5_kms *mdp5_kms,
enum mdp5_intf_type intf_type, int intf_num,
enum mdp5_intf_mode intf_mode, struct mdp5_ctl *ctl)
{
struct drm_device *dev = mdp5_kms->dev;
struct msm_drm_private *priv = dev->dev_private;
struct drm_encoder *encoder;
struct mdp5_interface intf = {
.num = intf_num,
.type = intf_type,
.mode = intf_mode,
};
if ((intf_type == INTF_DSI) &&
(intf_mode == MDP5_INTF_DSI_MODE_COMMAND))
encoder = mdp5_cmd_encoder_init(dev, &intf, ctl);
else
encoder = mdp5_encoder_init(dev, &intf, ctl);
if (IS_ERR(encoder)) {
dev_err(dev->dev, "failed to construct encoder\n");
return encoder;
}
encoder->possible_crtcs = (1 << priv->num_crtcs) - 1;
priv->encoders[priv->num_encoders++] = encoder;
return encoder;
}
static int get_dsi_id_from_intf(const struct mdp5_cfg_hw *hw_cfg, int intf_num)
{
const enum mdp5_intf_type *intfs = hw_cfg->intf.connect;
const int intf_cnt = ARRAY_SIZE(hw_cfg->intf.connect);
int id = 0, i;
for (i = 0; i < intf_cnt; i++) {
if (intfs[i] == INTF_DSI) {
if (intf_num == i)
return id;
id++;
}
}
return -EINVAL;
}
static int modeset_init_intf(struct mdp5_kms *mdp5_kms, int intf_num)
{
struct drm_device *dev = mdp5_kms->dev;
struct msm_drm_private *priv = dev->dev_private;
const struct mdp5_cfg_hw *hw_cfg =
mdp5_cfg_get_hw_config(mdp5_kms->cfg);
enum mdp5_intf_type intf_type = hw_cfg->intf.connect[intf_num];
struct mdp5_ctl_manager *ctlm = mdp5_kms->ctlm;
struct mdp5_ctl *ctl;
struct drm_encoder *encoder;
int ret = 0;
switch (intf_type) {
case INTF_DISABLED:
break;
case INTF_eDP:
if (!priv->edp)
break;
ctl = mdp5_ctlm_request(ctlm, intf_num);
if (!ctl) {
ret = -EINVAL;
break;
}
encoder = construct_encoder(mdp5_kms, INTF_eDP, intf_num,
MDP5_INTF_MODE_NONE, ctl);
if (IS_ERR(encoder)) {
ret = PTR_ERR(encoder);
break;
}
ret = msm_edp_modeset_init(priv->edp, dev, encoder);
break;
case INTF_HDMI:
if (!priv->hdmi)
break;
ctl = mdp5_ctlm_request(ctlm, intf_num);
if (!ctl) {
ret = -EINVAL;
break;
}
encoder = construct_encoder(mdp5_kms, INTF_HDMI, intf_num,
MDP5_INTF_MODE_NONE, ctl);
if (IS_ERR(encoder)) {
ret = PTR_ERR(encoder);
break;
}
ret = hdmi_modeset_init(priv->hdmi, dev, encoder);
break;
case INTF_DSI:
{
int dsi_id = get_dsi_id_from_intf(hw_cfg, intf_num);
struct drm_encoder *dsi_encs[MSM_DSI_ENCODER_NUM];
enum mdp5_intf_mode mode;
int i;
if ((dsi_id >= ARRAY_SIZE(priv->dsi)) || (dsi_id < 0)) {
dev_err(dev->dev, "failed to find dsi from intf %d\n",
intf_num);
ret = -EINVAL;
break;
}
if (!priv->dsi[dsi_id])
break;
ctl = mdp5_ctlm_request(ctlm, intf_num);
if (!ctl) {
ret = -EINVAL;
break;
}
for (i = 0; i < MSM_DSI_ENCODER_NUM; i++) {
mode = (i == MSM_DSI_CMD_ENCODER_ID) ?
MDP5_INTF_DSI_MODE_COMMAND :
MDP5_INTF_DSI_MODE_VIDEO;
dsi_encs[i] = construct_encoder(mdp5_kms, INTF_DSI,
intf_num, mode, ctl);
if (IS_ERR(dsi_encs[i])) {
ret = PTR_ERR(dsi_encs[i]);
break;
}
}
ret = msm_dsi_modeset_init(priv->dsi[dsi_id], dev, dsi_encs);
break;
}
default:
dev_err(dev->dev, "unknown intf: %d\n", intf_type);
ret = -EINVAL;
break;
}
return ret;
}
static int modeset_init(struct mdp5_kms *mdp5_kms)
{
static const enum mdp5_pipe crtcs[] = {
SSPP_RGB0, SSPP_RGB1, SSPP_RGB2, SSPP_RGB3,
};
static const enum mdp5_pipe vig_planes[] = {
SSPP_VIG0, SSPP_VIG1, SSPP_VIG2, SSPP_VIG3,
};
static const enum mdp5_pipe dma_planes[] = {
SSPP_DMA0, SSPP_DMA1,
};
struct drm_device *dev = mdp5_kms->dev;
struct msm_drm_private *priv = dev->dev_private;
const struct mdp5_cfg_hw *hw_cfg;
int i, ret;
hw_cfg = mdp5_cfg_get_hw_config(mdp5_kms->cfg);
/* register our interrupt-controller for hdmi/eDP/dsi/etc
* to use for irqs routed through mdp:
*/
ret = mdp5_irq_domain_init(mdp5_kms);
if (ret)
goto fail;
/* construct CRTCs and their private planes: */
for (i = 0; i < hw_cfg->pipe_rgb.count; i++) {
struct drm_plane *plane;
struct drm_crtc *crtc;
plane = mdp5_plane_init(dev, crtcs[i], true,
hw_cfg->pipe_rgb.base[i], hw_cfg->pipe_rgb.caps);
if (IS_ERR(plane)) {
ret = PTR_ERR(plane);
dev_err(dev->dev, "failed to construct plane for %s (%d)\n",
pipe2name(crtcs[i]), ret);
goto fail;
}
crtc = mdp5_crtc_init(dev, plane, i);
if (IS_ERR(crtc)) {
ret = PTR_ERR(crtc);
dev_err(dev->dev, "failed to construct crtc for %s (%d)\n",
pipe2name(crtcs[i]), ret);
goto fail;
}
priv->crtcs[priv->num_crtcs++] = crtc;
}
/* Construct video planes: */
for (i = 0; i < hw_cfg->pipe_vig.count; i++) {
struct drm_plane *plane;
plane = mdp5_plane_init(dev, vig_planes[i], false,
hw_cfg->pipe_vig.base[i], hw_cfg->pipe_vig.caps);
if (IS_ERR(plane)) {
ret = PTR_ERR(plane);
dev_err(dev->dev, "failed to construct %s plane: %d\n",
pipe2name(vig_planes[i]), ret);
goto fail;
}
}
/* DMA planes */
for (i = 0; i < hw_cfg->pipe_dma.count; i++) {
struct drm_plane *plane;
plane = mdp5_plane_init(dev, dma_planes[i], false,
hw_cfg->pipe_dma.base[i], hw_cfg->pipe_dma.caps);
if (IS_ERR(plane)) {
ret = PTR_ERR(plane);
dev_err(dev->dev, "failed to construct %s plane: %d\n",
pipe2name(dma_planes[i]), ret);
goto fail;
}
}
/* Construct encoders and modeset initialize connector devices
* for each external display interface.
*/
for (i = 0; i < ARRAY_SIZE(hw_cfg->intf.connect); i++) {
ret = modeset_init_intf(mdp5_kms, i);
if (ret)
goto fail;
}
return 0;
fail:
return ret;
}
static void read_hw_revision(struct mdp5_kms *mdp5_kms,
uint32_t *major, uint32_t *minor)
{
uint32_t version;
mdp5_enable(mdp5_kms);
version = mdp5_read(mdp5_kms, REG_MDSS_HW_VERSION);
mdp5_disable(mdp5_kms);
*major = FIELD(version, MDSS_HW_VERSION_MAJOR);
*minor = FIELD(version, MDSS_HW_VERSION_MINOR);
DBG("MDP5 version v%d.%d", *major, *minor);
}
static int get_clk(struct platform_device *pdev, struct clk **clkp,
const char *name, bool mandatory)
{
struct device *dev = &pdev->dev;
struct clk *clk = devm_clk_get(dev, name);
if (IS_ERR(clk) && mandatory) {
dev_err(dev, "failed to get %s (%ld)\n", name, PTR_ERR(clk));
return PTR_ERR(clk);
}
if (IS_ERR(clk))
DBG("skipping %s", name);
else
*clkp = clk;
return 0;
}
static struct drm_encoder *get_encoder_from_crtc(struct drm_crtc *crtc)
{
struct drm_device *dev = crtc->dev;
struct drm_encoder *encoder;
drm_for_each_encoder(encoder, dev)
if (encoder->crtc == crtc)
return encoder;
return NULL;
}
static int mdp5_get_scanoutpos(struct drm_device *dev, unsigned int pipe,
unsigned int flags, int *vpos, int *hpos,
ktime_t *stime, ktime_t *etime,
const struct drm_display_mode *mode)
{
struct msm_drm_private *priv = dev->dev_private;
struct drm_crtc *crtc;
struct drm_encoder *encoder;
int line, vsw, vbp, vactive_start, vactive_end, vfp_end;
int ret = 0;
crtc = priv->crtcs[pipe];
if (!crtc) {
DRM_ERROR("Invalid crtc %d\n", pipe);
return 0;
}
encoder = get_encoder_from_crtc(crtc);
if (!encoder) {
DRM_ERROR("no encoder found for crtc %d\n", pipe);
return 0;
}
ret |= DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_ACCURATE;
vsw = mode->crtc_vsync_end - mode->crtc_vsync_start;
vbp = mode->crtc_vtotal - mode->crtc_vsync_end;
/*
* the line counter is 1 at the start of the VSYNC pulse and VTOTAL at
* the end of VFP. Translate the porch values relative to the line
* counter positions.
*/
vactive_start = vsw + vbp + 1;
vactive_end = vactive_start + mode->crtc_vdisplay;
/* last scan line before VSYNC */
vfp_end = mode->crtc_vtotal;
if (stime)
*stime = ktime_get();
line = mdp5_encoder_get_linecount(encoder);
if (line < vactive_start) {
line -= vactive_start;
ret |= DRM_SCANOUTPOS_IN_VBLANK;
} else if (line > vactive_end) {
line = line - vfp_end - vactive_start;
ret |= DRM_SCANOUTPOS_IN_VBLANK;
} else {
line -= vactive_start;
}
*vpos = line;
*hpos = 0;
if (etime)
*etime = ktime_get();
return ret;
}
static int mdp5_get_vblank_timestamp(struct drm_device *dev, unsigned int pipe,
int *max_error,
struct timeval *vblank_time,
unsigned flags)
{
struct msm_drm_private *priv = dev->dev_private;
struct drm_crtc *crtc;
if (pipe < 0 || pipe >= priv->num_crtcs) {
DRM_ERROR("Invalid crtc %d\n", pipe);
return -EINVAL;
}
crtc = priv->crtcs[pipe];
if (!crtc) {
DRM_ERROR("Invalid crtc %d\n", pipe);
return -EINVAL;
}
return drm_calc_vbltimestamp_from_scanoutpos(dev, pipe, max_error,
vblank_time, flags,
&crtc->mode);
}
static u32 mdp5_get_vblank_counter(struct drm_device *dev, unsigned int pipe)
{
struct msm_drm_private *priv = dev->dev_private;
struct drm_crtc *crtc;
struct drm_encoder *encoder;
if (pipe < 0 || pipe >= priv->num_crtcs)
return 0;
crtc = priv->crtcs[pipe];
if (!crtc)
return 0;
encoder = get_encoder_from_crtc(crtc);
if (!encoder)
return 0;
return mdp5_encoder_get_framecount(encoder);
}
struct msm_kms *mdp5_kms_init(struct drm_device *dev)
{
struct platform_device *pdev = dev->platformdev;
struct mdp5_cfg *config;
struct mdp5_kms *mdp5_kms;
struct msm_kms *kms = NULL;
struct msm_mmu *mmu;
uint32_t major, minor;
int i, ret;
mdp5_kms = kzalloc(sizeof(*mdp5_kms), GFP_KERNEL);
if (!mdp5_kms) {
dev_err(dev->dev, "failed to allocate kms\n");
ret = -ENOMEM;
goto fail;
}
spin_lock_init(&mdp5_kms->resource_lock);
mdp_kms_init(&mdp5_kms->base, &kms_funcs);
kms = &mdp5_kms->base.base;
mdp5_kms->dev = dev;
/* mdp5_kms->mmio actually represents the MDSS base address */
mdp5_kms->mmio = msm_ioremap(pdev, "mdp_phys", "MDP5");
if (IS_ERR(mdp5_kms->mmio)) {
ret = PTR_ERR(mdp5_kms->mmio);
goto fail;
}
mdp5_kms->vbif = msm_ioremap(pdev, "vbif_phys", "VBIF");
if (IS_ERR(mdp5_kms->vbif)) {
ret = PTR_ERR(mdp5_kms->vbif);
goto fail;
}
mdp5_kms->vdd = devm_regulator_get(&pdev->dev, "vdd");
if (IS_ERR(mdp5_kms->vdd)) {
ret = PTR_ERR(mdp5_kms->vdd);
goto fail;
}
ret = regulator_enable(mdp5_kms->vdd);
if (ret) {
dev_err(dev->dev, "failed to enable regulator vdd: %d\n", ret);
goto fail;
}
/* mandatory clocks: */
ret = get_clk(pdev, &mdp5_kms->axi_clk, "bus_clk", true);
if (ret)
goto fail;
ret = get_clk(pdev, &mdp5_kms->ahb_clk, "iface_clk", true);
if (ret)
goto fail;
ret = get_clk(pdev, &mdp5_kms->src_clk, "core_clk_src", true);
if (ret)
goto fail;
ret = get_clk(pdev, &mdp5_kms->core_clk, "core_clk", true);
if (ret)
goto fail;
ret = get_clk(pdev, &mdp5_kms->vsync_clk, "vsync_clk", true);
if (ret)
goto fail;
/* optional clocks: */
get_clk(pdev, &mdp5_kms->lut_clk, "lut_clk", false);
/* we need to set a default rate before enabling. Set a safe
* rate first, then figure out hw revision, and then set a
* more optimal rate:
*/
clk_set_rate(mdp5_kms->src_clk, 200000000);
read_hw_revision(mdp5_kms, &major, &minor);
mdp5_kms->cfg = mdp5_cfg_init(mdp5_kms, major, minor);
if (IS_ERR(mdp5_kms->cfg)) {
ret = PTR_ERR(mdp5_kms->cfg);
mdp5_kms->cfg = NULL;
goto fail;
}
config = mdp5_cfg_get_config(mdp5_kms->cfg);
mdp5_kms->caps = config->hw->mdp.caps;
/* TODO: compute core clock rate at runtime */
clk_set_rate(mdp5_kms->src_clk, config->hw->max_clk);
/*
* Some chipsets have a Shared Memory Pool (SMP), while others
* have dedicated latency buffering per source pipe instead;
* this section initializes the SMP:
*/
if (mdp5_kms->caps & MDP_CAP_SMP) {
mdp5_kms->smp = mdp5_smp_init(mdp5_kms->dev, &config->hw->smp);
if (IS_ERR(mdp5_kms->smp)) {
ret = PTR_ERR(mdp5_kms->smp);
mdp5_kms->smp = NULL;
goto fail;
}
}
mdp5_kms->ctlm = mdp5_ctlm_init(dev, mdp5_kms->mmio, mdp5_kms->cfg);
if (IS_ERR(mdp5_kms->ctlm)) {
ret = PTR_ERR(mdp5_kms->ctlm);
mdp5_kms->ctlm = NULL;
goto fail;
}
/* make sure things are off before attaching iommu (bootloader could
* have left things on, in which case we'll start getting faults if
* we don't disable):
*/
mdp5_enable(mdp5_kms);
for (i = 0; i < MDP5_INTF_NUM_MAX; i++) {
if (mdp5_cfg_intf_is_virtual(config->hw->intf.connect[i]) ||
!config->hw->intf.base[i])
continue;
mdp5_write(mdp5_kms, REG_MDP5_INTF_TIMING_ENGINE_EN(i), 0);
mdp5_write(mdp5_kms, REG_MDP5_INTF_FRAME_LINE_COUNT_EN(i), 0x3);
}
mdp5_disable(mdp5_kms);
mdelay(16);
if (config->platform.iommu) {
mmu = msm_iommu_new(&pdev->dev, config->platform.iommu);
if (IS_ERR(mmu)) {
ret = PTR_ERR(mmu);
dev_err(dev->dev, "failed to init iommu: %d\n", ret);
iommu_domain_free(config->platform.iommu);
goto fail;
}
ret = mmu->funcs->attach(mmu, iommu_ports,
ARRAY_SIZE(iommu_ports));
if (ret) {
dev_err(dev->dev, "failed to attach iommu: %d\n", ret);
mmu->funcs->destroy(mmu);
goto fail;
}
} else {
dev_info(dev->dev, "no iommu, fallback to phys "
"contig buffers for scanout\n");
mmu = NULL;
}
mdp5_kms->mmu = mmu;
mdp5_kms->id = msm_register_mmu(dev, mmu);
if (mdp5_kms->id < 0) {
ret = mdp5_kms->id;
dev_err(dev->dev, "failed to register mdp5 iommu: %d\n", ret);
goto fail;
}
ret = modeset_init(mdp5_kms);
if (ret) {
dev_err(dev->dev, "modeset_init failed: %d\n", ret);
goto fail;
}
dev->mode_config.min_width = 0;
dev->mode_config.min_height = 0;
dev->mode_config.max_width = config->hw->lm.max_width;
dev->mode_config.max_height = config->hw->lm.max_height;
dev->driver->get_vblank_timestamp = mdp5_get_vblank_timestamp;
dev->driver->get_scanout_position = mdp5_get_scanoutpos;
dev->driver->get_vblank_counter = mdp5_get_vblank_counter;
dev->max_vblank_count = 0xffffffff;
dev->vblank_disable_immediate = true;
return kms;
fail:
if (kms)
mdp5_destroy(kms);
return ERR_PTR(ret);
}
| gpl-2.0 |
sloshedpuppie/LetsGoRetro | xbmc/filesystem/udf25.cpp | 51 | 31038 | /*
* Copyright (C) 2010 Team Boxee
* http://www.boxee.tv
*
* Copyright (C) 2010-2013 Team XBMC
* http://xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Note: parts of this code comes from libdvdread.
* Jorgen Lundman and team boxee did the necessary modifications to support udf 2.5
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "system.h"
#include "utils/log.h"
#include "udf25.h"
#include "File.h"
/* For direct data access, LSB first */
#define GETN1(p) ((uint8_t)data[p])
#define GETN2(p) ((uint16_t)data[p] | ((uint16_t)data[(p) + 1] << 8))
#define GETN3(p) ((uint32_t)data[p] | ((uint32_t)data[(p) + 1] << 8) \
| ((uint32_t)data[(p) + 2] << 16))
#define GETN4(p) ((uint32_t)data[p] \
| ((uint32_t)data[(p) + 1] << 8) \
| ((uint32_t)data[(p) + 2] << 16) \
| ((uint32_t)data[(p) + 3] << 24))
#define GETN8(p) ((uint64_t)data[p] \
| ((uint64_t)data[(p) + 1] << 8) \
| ((uint64_t)data[(p) + 2] << 16) \
| ((uint64_t)data[(p) + 3] << 24) \
| ((uint64_t)data[(p) + 4] << 32) \
| ((uint64_t)data[(p) + 5] << 40) \
| ((uint64_t)data[(p) + 6] << 48) \
| ((uint64_t)data[(p) + 7] << 56))
/* This is wrong with regard to endianess */
#define GETN(p, n, target) memcpy(target, &data[p], n)
using namespace XFILE;
static int Unicodedecode( uint8_t *data, int len, char *target )
{
int p = 1, i = 0;
if( ( data[ 0 ] == 8 ) || ( data[ 0 ] == 16 ) ) do {
if( data[ 0 ] == 16 ) p++; /* Ignore MSB of unicode16 */
if( p < len ) {
target[ i++ ] = data[ p++ ];
}
} while( p < len );
target[ i ] = '\0';
return 0;
}
static int UDFExtentAD( uint8_t *data, uint32_t *Length, uint32_t *Location )
{
*Length = GETN4(0);
*Location = GETN4(4);
return 0;
}
static int UDFShortAD( uint8_t *data, struct AD *ad )
{
ad->Length = GETN4(0);
ad->Flags = ad->Length >> 30;
ad->Length &= 0x3FFFFFFF;
ad->Location = GETN4(4);
return 0;
}
static int UDFLongAD( uint8_t *data, struct AD *ad )
{
ad->Length = GETN4(0);
ad->Flags = ad->Length >> 30;
ad->Length &= 0x3FFFFFFF;
ad->Location = GETN4(4);
ad->Partition = GETN2(8);
/* GETN(10, 6, Use); */
return 0;
}
static int UDFExtAD( uint8_t *data, struct AD *ad )
{
ad->Length = GETN4(0);
ad->Flags = ad->Length >> 30;
ad->Length &= 0x3FFFFFFF;
ad->Location = GETN4(12);
ad->Partition = GETN2(16);
/* GETN(10, 6, Use); */
return 0;
}
static int UDFAD( uint8_t *ptr, uint32_t len, struct FileAD *fad)
{
struct AD *ad;
if (fad->num_AD >= UDF_MAX_AD_CHAINS)
return len;
ad = &fad->AD_chain[fad->num_AD];
ad->Partition = fad->Partition;
ad->Flags = 0;
fad->num_AD++;
switch( fad->Flags & 0x0007 ) {
case 0:
UDFShortAD( ptr, ad );
return 8;
case 1:
UDFLongAD( ptr, ad );
return 16;
case 2:
UDFExtAD( ptr, ad );
return 20;
case 3:
switch( len ) {
case 8:
UDFShortAD( ptr, ad );
break;
case 16:
UDFLongAD( ptr, ad );
break;
case 20:
UDFExtAD( ptr, ad );
break;
}
break;
default:
break;
}
return len;
}
static int UDFICB( uint8_t *data, uint8_t *FileType, uint16_t *Flags )
{
*FileType = GETN1(11);
*Flags = GETN2(18);
return 0;
}
static int UDFPartition( uint8_t *data, uint16_t *Flags, uint16_t *Number,
char *Contents, uint32_t *Start, uint32_t *Length )
{
*Flags = GETN2(20);
*Number = GETN2(22);
GETN(24, 32, Contents);
*Start = GETN4(188);
*Length = GETN4(192);
return 0;
}
static int UDFLogVolume( uint8_t *data, char *VolumeDescriptor )
{
uint32_t lbsize;
Unicodedecode(&data[84], 128, VolumeDescriptor);
lbsize = GETN4(212); /* should be 2048 */
if (lbsize != DVD_VIDEO_LB_LEN) return 1;
return 0;
}
static int UDFAdEntry( uint8_t *data, struct FileAD *fad )
{
uint32_t L_AD;
unsigned int p;
L_AD = GETN4(20);
p = 24;
while( p < 24 + L_AD ) {
p += UDFAD( &data[ p ], L_AD, fad );
}
return 0;
}
static int UDFExtFileEntry( uint8_t *data, struct FileAD *fad )
{
uint32_t L_EA, L_AD;
unsigned int p;
UDFICB( &data[ 16 ], &fad->Type, &fad->Flags );
/* Init ad for an empty file (i.e. there isn't a AD, L_AD == 0 ) */
fad->Length = GETN8(56); // 64-bit.
L_EA = GETN4( 208);
L_AD = GETN4( 212);
p = 216 + L_EA;
fad->num_AD = 0;
while( p < 216 + L_EA + L_AD ) {
p += UDFAD( &data[ p ], L_AD, fad );
}
return 0;
}
/* TagID 266
* The differences in ExtFile are indicated below:
* struct extfile_entry {
* struct desc_tag tag;
* struct icb_tag icbtag;
* uint32_t uid;
* uint32_t gid;
* uint32_t perm;
* uint16_t link_cnt;
* uint8_t rec_format;
* uint8_t rec_disp_attr;
* uint32_t rec_len;
* uint64_t inf_len;
* uint64_t obj_size; // NEW
* uint64_t logblks_rec;
* struct timestamp atime;
* struct timestamp mtime;
* struct timestamp ctime; // NEW
* struct timestamp attrtime;
* uint32_t ckpoint;
* uint32_t reserved1; // NEW
* struct long_ad ex_attr_icb;
* struct long_ad streamdir_icb; // NEW
* struct regid imp_id;
* uint64_t unique_id;
* uint32_t l_ea;
* uint32_t l_ad;
* uint8_t data[1];
* } __packed;
*
* So old "l_ea" is now +216
*
* Lund
*/
static int UDFFileEntry( uint8_t *data, struct FileAD *fad )
{
uint32_t L_EA, L_AD;
unsigned int p;
UDFICB( &data[ 16 ], &fad->Type, &fad->Flags );
fad->Length = GETN8( 56 ); /* Was 4 bytes at 60, changed for 64bit. */
L_EA = GETN4( 168 );
L_AD = GETN4( 172 );
if (176 + L_EA + L_AD > DVD_VIDEO_LB_LEN)
return 0;
p = 176 + L_EA;
fad->num_AD = 0;
while( p < 176 + L_EA + L_AD ) {
p += UDFAD( &data[ p ], L_AD, fad );
}
return 0;
}
uint32_t UDFFilePos(struct FileAD *File, uint64_t pos, uint64_t *res)
{
uint32_t i;
for (i = 0; i < File->num_AD; i++) {
if (pos < File->AD_chain[i].Length)
break;
pos -= File->AD_chain[i].Length;
}
if (i == File->num_AD)
return 0;
*res = (uint64_t)(File->Partition_Start + File->AD_chain[i].Location) * DVD_VIDEO_LB_LEN + pos;
return File->AD_chain[i].Length - (uint32_t)pos;
}
uint32_t UDFFileBlockPos(struct FileAD *File, uint32_t lb)
{
uint64_t res;
uint32_t rem;
rem = UDFFilePos(File, lb * DVD_VIDEO_LB_LEN, &res);
if(rem > 0)
return (uint32_t)(res / DVD_VIDEO_LB_LEN);
else
return 0;
}
static int UDFFileIdentifier( uint8_t *data, uint8_t *FileCharacteristics,
char *FileName, struct AD *FileICB )
{
uint8_t L_FI;
uint16_t L_IU;
*FileCharacteristics = GETN1(18);
L_FI = GETN1(19);
UDFLongAD(&data[20], FileICB);
L_IU = GETN2(36);
if (L_FI) Unicodedecode(&data[38 + L_IU], L_FI, FileName);
else FileName[0] = '\0';
return 4 * ((38 + L_FI + L_IU + 3) / 4);
}
static int UDFDescriptor( uint8_t *data, uint16_t *TagID )
{
*TagID = GETN2(0);
/* TODO: check CRC 'n stuff */
return 0;
}
int udf25::UDFScanDirX( udf_dir_t *dirp )
{
char filename[ MAX_UDF_FILE_NAME_LEN ];
uint8_t directory_base[ 2 * DVD_VIDEO_LB_LEN + 2048];
uint8_t *directory = (uint8_t *)(((uintptr_t)directory_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum;
uint16_t TagID;
uint8_t filechar;
unsigned int p;
struct AD FileICB;
struct FileAD File;
struct Partition partition;
if(!(GetUDFCache(PartitionCache, 0, &partition))) {
if(!UDFFindPartition(0, &partition))
return 0;
}
/* Scan dir for ICB of file */
lbnum = dirp->dir_current;
// I have cut out the caching part of the original UDFScanDir() function
// one day we should probably bring it back.
memset(&File, 0, sizeof(File));
if( DVDReadLBUDF( lbnum, 2, directory, 0 ) <= 0 ) {
return 0;
}
p = dirp->current_p;
while( p < dirp->dir_length ) {
if( p > DVD_VIDEO_LB_LEN ) {
++lbnum;
p -= DVD_VIDEO_LB_LEN;
//Dir.Length -= DVD_VIDEO_LB_LEN;
if (dirp->dir_length >= DVD_VIDEO_LB_LEN)
dirp->dir_length -= DVD_VIDEO_LB_LEN;
else
dirp->dir_length = 0;
if( DVDReadLBUDF( lbnum, 2, directory, 0 ) <= 0 ) {
return 0;
}
}
UDFDescriptor( &directory[ p ], &TagID );
if( TagID == 257 ) {
p += UDFFileIdentifier( &directory[ p ], &filechar,
filename, &FileICB );
dirp->current_p = p;
dirp->dir_current = lbnum;
if (!*filename) // No filename, simulate "." dirname
strcpy((char *)dirp->entry.d_name, ".");
else {
// Bah, MSVC don't have strlcpy()
strncpy((char *)dirp->entry.d_name, filename,
sizeof(dirp->entry.d_name)-1);
dirp->entry.d_name[ sizeof(dirp->entry.d_name) - 1 ] = 0;
}
// Look up the Filedata
if( !UDFMapICB( FileICB, &partition, &File))
return 0;
if (File.Type == 4)
dirp->entry.d_type = DVD_DT_DIR;
else
dirp->entry.d_type = DVD_DT_REG; // Add more types?
dirp->entry.d_filesize = File.Length;
return 1;
} else {
// Not TagID 257
return 0;
}
}
// End of DIR
return 0;
}
int udf25::SetUDFCache(UDFCacheType type, uint32_t nr, void *data)
{
int n;
struct udf_cache *c;
void *tmp;
if(DVDUDFCacheLevel(-1) <= 0)
return 0;
c = (struct udf_cache *)GetUDFCacheHandle();
if(c == NULL) {
c = (struct udf_cache *)calloc(1, sizeof(struct udf_cache));
/* fprintf(stderr, "calloc: %d\n", sizeof(struct udf_cache)); */
if(c == NULL)
return 0;
SetUDFCacheHandle(c);
}
switch(type) {
case AVDPCache:
c->avdp = *(struct avdp_t *)data;
c->avdp_valid = 1;
break;
case PVDCache:
c->pvd = *(struct pvd_t *)data;
c->pvd_valid = 1;
break;
case PartitionCache:
c->partition = *(struct Partition *)data;
c->partition_valid = 1;
break;
case RootICBCache:
c->rooticb = *(struct AD *)data;
c->rooticb_valid = 1;
break;
case LBUDFCache:
for(n = 0; n < c->lb_num; n++) {
if(c->lbs[n].lb == nr) {
/* replace with new data */
c->lbs[n].data_base = ((uint8_t **)data)[0];
c->lbs[n].data = ((uint8_t **)data)[1];
c->lbs[n].lb = nr;
return 1;
}
}
c->lb_num++;
tmp = realloc(c->lbs, c->lb_num * sizeof(struct lbudf));
/*
fprintf(stderr, "realloc lb: %d * %d = %d\n",
c->lb_num, sizeof(struct lbudf),
c->lb_num * sizeof(struct lbudf));
*/
if(tmp == NULL) {
if(c->lbs) free(c->lbs);
c->lb_num = 0;
return 0;
}
c->lbs = (struct lbudf *)tmp;
c->lbs[n].data_base = ((uint8_t **)data)[0];
c->lbs[n].data = ((uint8_t **)data)[1];
c->lbs[n].lb = nr;
break;
case MapCache:
for(n = 0; n < c->map_num; n++) {
if(c->maps[n].lbn == nr) {
/* replace with new data */
c->maps[n] = *(struct icbmap *)data;
c->maps[n].lbn = nr;
return 1;
}
}
c->map_num++;
tmp = realloc(c->maps, c->map_num * sizeof(struct icbmap));
/*
fprintf(stderr, "realloc maps: %d * %d = %d\n",
c->map_num, sizeof(struct icbmap),
c->map_num * sizeof(struct icbmap));
*/
if(tmp == NULL) {
if(c->maps) free(c->maps);
c->map_num = 0;
return 0;
}
c->maps = (struct icbmap *)tmp;
c->maps[n] = *(struct icbmap *)data;
c->maps[n].lbn = nr;
break;
default:
return 0;
}
return 1;
}
int udf25::DVDUDFCacheLevel(int level)
{
if(level > 0) {
level = 1;
} else if(level < 0) {
return m_udfcache_level;
}
m_udfcache_level = level;
return level;
}
void *udf25::GetUDFCacheHandle()
{
return m_udfcache;
}
void udf25::SetUDFCacheHandle(void *cache)
{
m_udfcache = cache;
}
int udf25::GetUDFCache(UDFCacheType type, uint32_t nr, void *data)
{
int n;
struct udf_cache *c;
if(DVDUDFCacheLevel(-1) <= 0)
return 0;
c = (struct udf_cache *)GetUDFCacheHandle();
if(c == NULL)
return 0;
switch(type) {
case AVDPCache:
if(c->avdp_valid) {
*(struct avdp_t *)data = c->avdp;
return 1;
}
break;
case PVDCache:
if(c->pvd_valid) {
*(struct pvd_t *)data = c->pvd;
return 1;
}
break;
case PartitionCache:
if(c->partition_valid) {
*(struct Partition *)data = c->partition;
return 1;
}
break;
case RootICBCache:
if(c->rooticb_valid) {
*(struct AD *)data = c->rooticb;
return 1;
}
break;
case LBUDFCache:
for(n = 0; n < c->lb_num; n++) {
if(c->lbs[n].lb == nr) {
*(uint8_t **)data = c->lbs[n].data;
return 1;
}
}
break;
case MapCache:
for(n = 0; n < c->map_num; n++) {
if(c->maps[n].lbn == nr) {
*(struct icbmap *)data = c->maps[n];
return 1;
}
}
break;
default:
break;
}
return 0;
}
int udf25::ReadAt( int64_t pos, size_t len, unsigned char *data )
{
if (m_fp->Seek(pos, SEEK_SET) != pos)
return -1;
ssize_t ret = m_fp->Read(data, len);
if ( ret > 0 && static_cast<size_t>(ret) < len)
{
CLog::Log(LOGERROR, "udf25::ReadFile - less data than requested available!" );
return (int)ret;
}
return (int)ret;
}
int udf25::DVDReadLBUDF( uint32_t lb_number, size_t block_count, unsigned char *data, int encrypted )
{
int ret;
size_t len = block_count * DVD_VIDEO_LB_LEN;
int64_t pos = lb_number * (int64_t)DVD_VIDEO_LB_LEN;
ret = ReadAt(pos, len, data);
if(ret < 0)
return ret;
if((unsigned int)ret < len)
{
CLog::Log(LOGERROR, "udf25::DVDReadLBUDF - Block was not complete, setting to wanted %u (got %u)", (unsigned int)len, (unsigned int)ret);
memset(&data[ret], 0, len - ret);
}
return len / DVD_VIDEO_LB_LEN;
}
int udf25::UDFGetAVDP( struct avdp_t *avdp)
{
uint8_t Anchor_base[ DVD_VIDEO_LB_LEN + 2048 ];
uint8_t *Anchor = (uint8_t *)(((uintptr_t)Anchor_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum, MVDS_location, MVDS_length;
uint16_t TagID;
uint32_t lastsector;
int terminate;
struct avdp_t;
if(GetUDFCache(AVDPCache, 0, avdp))
return 1;
/* Find Anchor */
lastsector = 0;
lbnum = 256; /* Try #1, prime anchor */
terminate = 0;
for(;;) {
if( DVDReadLBUDF( lbnum, 1, Anchor, 0 ) > 0 ) {
UDFDescriptor( Anchor, &TagID );
} else {
TagID = 0;
}
if (TagID != 2) {
/* Not an anchor */
if( terminate ) return 0; /* Final try failed */
if( lastsector ) {
/* We already found the last sector. Try #3, alternative
* backup anchor. If that fails, don't try again.
*/
lbnum = lastsector;
terminate = 1;
} else {
/* TODO: Find last sector of the disc (this is optional). */
if( lastsector )
/* Try #2, backup anchor */
lbnum = lastsector - 256;
else
/* Unable to find last sector */
return 0;
}
} else
/* It's an anchor! We can leave */
break;
}
/* Main volume descriptor */
UDFExtentAD( &Anchor[ 16 ], &MVDS_length, &MVDS_location );
avdp->mvds.location = MVDS_location;
avdp->mvds.length = MVDS_length;
/* Backup volume descriptor */
UDFExtentAD( &Anchor[ 24 ], &MVDS_length, &MVDS_location );
avdp->rvds.location = MVDS_location;
avdp->rvds.length = MVDS_length;
SetUDFCache(AVDPCache, 0, avdp);
return 1;
}
int udf25::UDFFindPartition( int partnum, struct Partition *part )
{
uint8_t LogBlock_base[ DVD_VIDEO_LB_LEN + 2048 ];
uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum, MVDS_location, MVDS_length;
uint16_t TagID;
int i, volvalid;
struct avdp_t avdp;
if(!UDFGetAVDP(&avdp))
return 0;
/* Main volume descriptor */
MVDS_location = avdp.mvds.location;
MVDS_length = avdp.mvds.length;
part->valid = 0;
volvalid = 0;
part->VolumeDesc[ 0 ] = '\0';
i = 1;
do {
/* Find Volume Descriptor */
lbnum = MVDS_location;
do {
if( DVDReadLBUDF( lbnum++, 1, LogBlock, 0 ) <= 0 )
TagID = 0;
else
UDFDescriptor( LogBlock, &TagID );
if( ( TagID == 5 ) && ( !part->valid ) ) {
/* Partition Descriptor */
UDFPartition( LogBlock, &part->Flags, &part->Number,
part->Contents, &part->Start, &part->Length );
part->Start_Correction = 0;
part->valid = ( partnum == part->Number );
} else if( ( TagID == 6 ) && ( !volvalid ) ) {
/* Logical Volume Descriptor */
if( UDFLogVolume( LogBlock, part->VolumeDesc ) ) {
/* TODO: sector size wrong! */
} else
volvalid = 1;
}
} while( ( lbnum <= MVDS_location + ( MVDS_length - 1 )
/ DVD_VIDEO_LB_LEN ) && ( TagID != 8 )
&& ( ( !part->valid ) || ( !volvalid ) ) );
if( ( !part->valid) || ( !volvalid ) ) {
/* Backup volume descriptor */
MVDS_location = avdp.mvds.location;
MVDS_length = avdp.mvds.length;
}
} while( i-- && ( ( !part->valid ) || ( !volvalid ) ) );
/* Look for a metadata partition */
lbnum = part->Start;
do {
if( DVDReadLBUDF( lbnum++, 1, LogBlock, 0 ) <= 0 )
TagID = 0;
else
UDFDescriptor( LogBlock, &TagID );
/*
* It seems that someone added a FileType of 250, which seems to be
* a "redirect" style file entry. If we discover such an entry, we
* add on the "location" to partition->Start, and try again.
* Who added this? Is there any official guide somewhere?
* 2008/09/17 lundman
* Should we handle 261(250) as well? FileEntry+redirect
*/
if( TagID == 266 ) {
struct FileAD File;
File.Partition = part->Number;
File.Partition_Start = part->Start;
UDFExtFileEntry( LogBlock, &File );
if (File.Type == 250) {
part->Start += File.AD_chain[0].Location;
// we need to remember this correction because read positions are relative to the non-indirected partition start
part->Start_Correction = File.AD_chain[0].Location;
part->Length = File.AD_chain[0].Length;
break;
}
}
} while( ( lbnum < part->Start + part->Length )
&& ( TagID != 8 ) && ( TagID != 256 ) );
/* We only care for the partition, not the volume */
return part->valid;
}
int udf25::UDFMapICB( struct AD ICB, struct Partition *partition, struct FileAD *File )
{
uint8_t LogBlock_base[DVD_VIDEO_LB_LEN + 2048];
uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum;
uint16_t TagID;
struct icbmap tmpmap;
lbnum = partition->Start + ICB.Location;
tmpmap.lbn = lbnum;
if(GetUDFCache(MapCache, lbnum, &tmpmap)) {
memcpy(File, &tmpmap.file, sizeof(tmpmap.file));
return 1;
}
memset(File, 0, sizeof(*File));
File->Partition = partition->Number;
File->Partition_Start = partition->Start;
File->Partition_Start_Correction = partition->Start_Correction;
do {
if( DVDReadLBUDF( lbnum++, 1, LogBlock, 0 ) <= 0 )
TagID = 0;
else
UDFDescriptor( LogBlock, &TagID );
if( TagID == 261 ) {
UDFFileEntry( LogBlock, File );
break;
};
/* ExtendedFileInfo */
if( TagID == 266 ) {
UDFExtFileEntry( LogBlock, File );
break;
}
} while( lbnum <= partition->Start + ICB.Location + ( ICB.Length - 1 )
/ DVD_VIDEO_LB_LEN );
if(File->Type) {
/* check if ad chain continues elsewhere */
while(File->num_AD && File->AD_chain[File->num_AD-1].Flags == 3) {
struct AD* ad = &File->AD_chain[File->num_AD-1];
/* remove the forward pointer from the list */
File->num_AD--;
if( DVDReadLBUDF( File->Partition_Start + ad->Location, 1, LogBlock, 0 ) <= 0 )
TagID = 0;
else
UDFDescriptor( LogBlock, &TagID );
if( TagID == 258 ) {
/* add all additional entries */
UDFAdEntry( LogBlock, File );
} else {
return 0;
}
}
memcpy(&tmpmap.file, File, sizeof(tmpmap.file));
SetUDFCache(MapCache, tmpmap.lbn, &tmpmap);
return 1;
}
return 0;
}
int udf25::UDFScanDir(const struct FileAD& Dir, char *FileName, struct Partition *partition, struct AD *FileICB, int cache_file_info)
{
char filename[ MAX_UDF_FILE_NAME_LEN ];
uint8_t directory_base[ 2 * DVD_VIDEO_LB_LEN + 2048];
uint8_t *directory = (uint8_t *)(((uintptr_t)directory_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum;
uint16_t TagID;
uint8_t filechar;
unsigned int p;
uint8_t *cached_dir_base = NULL, *cached_dir;
uint32_t dir_lba;
struct AD tmpICB;
int found = 0;
int in_cache = 0;
/* Scan dir for ICB of file */
lbnum = partition->Start + Dir.AD_chain[0].Location;
if(DVDUDFCacheLevel(-1) > 0) {
/* caching */
if(!GetUDFCache(LBUDFCache, lbnum, &cached_dir)) {
dir_lba = (Dir.AD_chain[0].Length + DVD_VIDEO_LB_LEN) / DVD_VIDEO_LB_LEN;
if((cached_dir_base = (uint8_t *)malloc(dir_lba * DVD_VIDEO_LB_LEN + 2048)) == NULL)
return 0;
cached_dir = (uint8_t *)(((uintptr_t)cached_dir_base & ~((uintptr_t)2047)) + 2048);
if( DVDReadLBUDF( lbnum, dir_lba, cached_dir, 0) <= 0 ) {
free(cached_dir_base);
cached_dir_base = NULL;
cached_dir = NULL;
}
/*
if(cached_dir) {
fprintf(stderr, "malloc dir: %d\n", dir_lba * DVD_VIDEO_LB_LEN);
}
*/
{
uint8_t *data[2];
data[0] = cached_dir_base;
data[1] = cached_dir;
SetUDFCache(LBUDFCache, lbnum, data);
}
} else
in_cache = 1;
if(cached_dir == NULL)
return 0;
p = 0;
while( p < Dir.AD_chain[0].Length ) { /* Assuming dirs don't use chains? */
UDFDescriptor( &cached_dir[ p ], &TagID );
if( TagID == 257 ) {
p += UDFFileIdentifier( &cached_dir[ p ], &filechar,
filename, &tmpICB );
if(cache_file_info && !in_cache) {
struct FileAD tmpFile;
memset(&tmpFile, 0, sizeof(tmpFile));
if( !strcasecmp( FileName, filename ) ) {
memcpy(FileICB, &tmpICB, sizeof(tmpICB));
found = 1;
}
UDFMapICB(tmpICB, partition, &tmpFile);
} else {
if( !strcasecmp( FileName, filename ) ) {
memcpy(FileICB, &tmpICB, sizeof(tmpICB));
return 1;
}
}
} else {
if(cache_file_info && (!in_cache) && found)
return 1;
return 0;
}
}
if(cache_file_info && (!in_cache) && found)
return 1;
return 0;
}
if( DVDReadLBUDF( lbnum, 2, directory, 0 ) <= 0 )
return 0;
p = 0;
uint32_t l = Dir.AD_chain[0].Length;
while (p < l) {
if( p > DVD_VIDEO_LB_LEN ) {
++lbnum;
p -= DVD_VIDEO_LB_LEN;
l -= DVD_VIDEO_LB_LEN;
if( DVDReadLBUDF( lbnum, 2, directory, 0 ) <= 0 ) {
return 0;
}
}
UDFDescriptor( &directory[ p ], &TagID );
if( TagID == 257 ) {
p += UDFFileIdentifier( &directory[ p ], &filechar,
filename, FileICB );
if( !strcasecmp( FileName, filename ) ) {
return 1;
}
} else
return 0;
}
return 0;
}
udf25::udf25( )
{
m_fp = NULL;
m_udfcache_level = 1;
m_udfcache = NULL;
}
udf25::~udf25( )
{
delete m_fp;
struct udf_cache * cache = (struct udf_cache *) m_udfcache;
if (!cache)
return;
if (cache->lbs)
{
for (int n = 0; n < cache->lb_num; n++)
{
free(cache->lbs[n].data_base);
}
free(cache->lbs);
}
free(cache->maps);
free(cache);
}
UDF_FILE udf25::UDFFindFile( const char* filename, uint64_t *filesize )
{
uint8_t LogBlock_base[ DVD_VIDEO_LB_LEN + 2048 ];
uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
uint32_t lbnum;
uint16_t TagID;
struct Partition partition;
struct AD RootICB, ICB;
struct FileAD File;
char tokenline[ MAX_UDF_FILE_NAME_LEN ];
char *token;
struct FileAD *result;
*filesize = 0;
tokenline[0] = '\0';
strncat(tokenline, filename, MAX_UDF_FILE_NAME_LEN - 1);
memset(&ICB, 0, sizeof(ICB));
memset(&File, 0, sizeof(File));
if(!(GetUDFCache(PartitionCache, 0, &partition) &&
GetUDFCache(RootICBCache, 0, &RootICB))) {
/* Find partition, 0 is the standard location for DVD Video.*/
if( !UDFFindPartition(0, &partition ) ) return 0;
SetUDFCache(PartitionCache, 0, &partition);
/* Find root dir ICB */
lbnum = partition.Start;
do {
if( DVDReadLBUDF( lbnum++, 1, LogBlock, 0 ) <= 0 )
TagID = 0;
else
UDFDescriptor( LogBlock, &TagID );
/* File Set Descriptor */
if( TagID == 256 ) /* File Set Descriptor */
UDFLongAD( &LogBlock[ 400 ], &RootICB );
} while( ( lbnum < partition.Start + partition.Length )
&& ( TagID != 8 ) && ( TagID != 256 ) );
/* Sanity checks. */
if( TagID != 256 )
return NULL;
/* This following test will fail under UDF2.50 images, as it is no longer
* valid */
/*if( RootICB.Partition != 0 )
return 0;*/
SetUDFCache(RootICBCache, 0, &RootICB);
}
/* Find root dir */
if( !UDFMapICB( RootICB, &partition, &File ) )
return NULL;
if( File.Type != 4 )
return NULL; /* Root dir should be dir */
{
int cache_file_info = 0;
/* Tokenize filepath */
token = strtok(tokenline, "/");
while( token != NULL ) {
if( !UDFScanDir( File, token, &partition, &ICB,
cache_file_info))
return NULL;
if( !UDFMapICB( ICB, &partition, &File ) )
return NULL;
if(!strcmp(token, "index.bdmv"))
cache_file_info = 1;
token = strtok( NULL, "/" );
}
}
/* Sanity check. */
if( File.AD_chain[0].Partition != 0 )
return 0;
*filesize = File.Length;
/* Hack to not return partition.Start for empty files. */
if( !File.AD_chain[0].Location )
return NULL;
/* Allocate a new UDF_FILE and return it. */
result = (struct FileAD *) malloc(sizeof(*result));
if (!result) return NULL;
memcpy(result, &File, sizeof(*result));
return result;
}
bool udf25::Open(const char *isofile)
{
m_fp = new CFile();
if(!m_fp->Open(isofile))
{
CLog::Log(LOGERROR,"file_open - Could not open input");
delete m_fp;
m_fp = NULL;
return false;
}
return true;
}
HANDLE udf25::OpenFile( const char* filename )
{
uint64_t filesize;
UDF_FILE file = NULL;
BD_FILE bdfile = NULL;
if(!m_fp)
return INVALID_HANDLE_VALUE;
file = UDFFindFile(filename, &filesize);
if(!file)
return INVALID_HANDLE_VALUE;
bdfile = (BD_FILE)calloc(1, sizeof(*bdfile));
bdfile->file = file;
bdfile->filesize = filesize;
return (HANDLE)bdfile;
}
long udf25::ReadFile(HANDLE hFile, unsigned char *pBuffer, long lSize)
{
BD_FILE bdfile = (BD_FILE)hFile;
long len_origin;
uint64_t pos;
uint32_t len;
int ret;
/* Check arguments. */
if( bdfile == NULL || pBuffer == NULL )
return -1;
len_origin = lSize;
while(lSize > 0)
{
len = UDFFilePos(bdfile->file, bdfile->seek_pos, &pos);
if(len == 0)
break;
// correct for partition indirection if applicable
pos -= bdfile->file->Partition_Start_Correction * DVD_VIDEO_LB_LEN;
if((uint32_t)lSize < len)
len = lSize;
ret = ReadAt(pos, len, pBuffer);
if(ret < 0)
{
CLog::Log(LOGERROR, "udf25::ReadFile - error during read" );
return ret;
}
if(ret == 0)
break;
bdfile->seek_pos += ret;
pBuffer += ret;
lSize -= ret;
}
return len_origin - lSize;
}
void udf25::CloseFile(HANDLE hFile)
{
if(hFile == INVALID_HANDLE_VALUE)
return;
BD_FILE bdfile = (BD_FILE)hFile;
if(bdfile)
{
free(bdfile->file);
free(bdfile);
}
}
int64_t udf25::Seek(HANDLE hFile, int64_t lOffset, int whence)
{
BD_FILE bdfile = (BD_FILE)hFile;
if(bdfile == NULL)
return -1;
int64_t seek_pos = bdfile->seek_pos;
switch (whence)
{
case SEEK_SET:
// cur = pos
bdfile->seek_pos = lOffset;
break;
case SEEK_CUR:
// cur += pos
bdfile->seek_pos += lOffset;
break;
case SEEK_END:
// end += pos
bdfile->seek_pos = bdfile->filesize + lOffset;
break;
}
if (bdfile->seek_pos > bdfile->filesize)
{
bdfile->seek_pos = seek_pos;
return bdfile->seek_pos;
}
return bdfile->seek_pos;
}
int64_t udf25::GetFileSize(HANDLE hFile)
{
BD_FILE bdfile = (BD_FILE)hFile;
if(bdfile == NULL)
return -1;
return bdfile->filesize;
}
int64_t udf25::GetFilePosition(HANDLE hFile)
{
BD_FILE bdfile = (BD_FILE)hFile;
if(bdfile == NULL)
return -1;
return bdfile->seek_pos;
}
udf_dir_t *udf25::OpenDir( const char *subdir )
{
udf_dir_t *result;
BD_FILE bd_file;
bd_file = (BD_FILE)OpenFile(subdir);
if (bd_file == (BD_FILE)INVALID_HANDLE_VALUE)
return NULL;
result = (udf_dir_t *)calloc(1, sizeof(udf_dir_t));
if (!result) {
CloseFile((HANDLE)bd_file);
return NULL;
}
result->dir_location = UDFFileBlockPos(bd_file->file, 0);
result->dir_current = UDFFileBlockPos(bd_file->file, 0);
result->dir_length = (uint32_t) bd_file->filesize;
CloseFile((HANDLE)bd_file);
return result;
}
udf_dirent_t *udf25::ReadDir( udf_dir_t *dirp )
{
if (!UDFScanDirX(dirp)) {
dirp->current_p = 0;
dirp->dir_current = dirp->dir_location; // this is a rewind, wanted?
return NULL;
}
return &dirp->entry;
}
int udf25::CloseDir( udf_dir_t *dirp )
{
if (!dirp) return 0;
free(dirp);
CloseFile(NULL);
return 0;
}
| gpl-2.0 |
drod2169/Linux-3.14.x | arch/tile/gxio/iorpc_usb_host.c | 2355 | 2738 | /*
* Copyright 2012 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
/* This file is machine-generated; DO NOT EDIT! */
#include "gxio/iorpc_usb_host.h"
struct cfg_interrupt_param {
union iorpc_interrupt interrupt;
};
int gxio_usb_host_cfg_interrupt(gxio_usb_host_context_t *context, int inter_x,
int inter_y, int inter_ipi, int inter_event)
{
struct cfg_interrupt_param temp;
struct cfg_interrupt_param *params = &temp;
params->interrupt.kernel.x = inter_x;
params->interrupt.kernel.y = inter_y;
params->interrupt.kernel.ipi = inter_ipi;
params->interrupt.kernel.event = inter_event;
return hv_dev_pwrite(context->fd, 0, (HV_VirtAddr) params,
sizeof(*params), GXIO_USB_HOST_OP_CFG_INTERRUPT);
}
EXPORT_SYMBOL(gxio_usb_host_cfg_interrupt);
struct register_client_memory_param {
HV_PTE pte;
unsigned int flags;
};
int gxio_usb_host_register_client_memory(gxio_usb_host_context_t *context,
HV_PTE pte, unsigned int flags)
{
struct register_client_memory_param temp;
struct register_client_memory_param *params = &temp;
params->pte = pte;
params->flags = flags;
return hv_dev_pwrite(context->fd, 0, (HV_VirtAddr) params,
sizeof(*params),
GXIO_USB_HOST_OP_REGISTER_CLIENT_MEMORY);
}
EXPORT_SYMBOL(gxio_usb_host_register_client_memory);
struct get_mmio_base_param {
HV_PTE base;
};
int gxio_usb_host_get_mmio_base(gxio_usb_host_context_t *context, HV_PTE *base)
{
int __result;
struct get_mmio_base_param temp;
struct get_mmio_base_param *params = &temp;
__result =
hv_dev_pread(context->fd, 0, (HV_VirtAddr) params, sizeof(*params),
GXIO_USB_HOST_OP_GET_MMIO_BASE);
*base = params->base;
return __result;
}
EXPORT_SYMBOL(gxio_usb_host_get_mmio_base);
struct check_mmio_offset_param {
unsigned long offset;
unsigned long size;
};
int gxio_usb_host_check_mmio_offset(gxio_usb_host_context_t *context,
unsigned long offset, unsigned long size)
{
struct check_mmio_offset_param temp;
struct check_mmio_offset_param *params = &temp;
params->offset = offset;
params->size = size;
return hv_dev_pwrite(context->fd, 0, (HV_VirtAddr) params,
sizeof(*params),
GXIO_USB_HOST_OP_CHECK_MMIO_OFFSET);
}
EXPORT_SYMBOL(gxio_usb_host_check_mmio_offset);
| gpl-2.0 |
tommytarts/QuantumKernelM8-GPe2 | arch/arm/mach-shmobile/pfc-sh7372.c | 4915 | 59494 | /*
* sh7372 processor support - PFC hardware block
*
* Copyright (C) 2010 Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on
* sh7367 processor support - PFC hardware block
* Copyright (C) 2010 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <mach/irqs.h>
#include <mach/sh7372.h>
#define CPU_ALL_PORT(fn, pfx, sfx) \
PORT_10(fn, pfx, sfx), PORT_90(fn, pfx, sfx), \
PORT_10(fn, pfx##10, sfx), PORT_10(fn, pfx##11, sfx), \
PORT_10(fn, pfx##12, sfx), PORT_10(fn, pfx##13, sfx), \
PORT_10(fn, pfx##14, sfx), PORT_10(fn, pfx##15, sfx), \
PORT_10(fn, pfx##16, sfx), PORT_10(fn, pfx##17, sfx), \
PORT_10(fn, pfx##18, sfx), PORT_1(fn, pfx##190, sfx)
enum {
PINMUX_RESERVED = 0,
/* PORT0_DATA -> PORT190_DATA */
PINMUX_DATA_BEGIN,
PORT_ALL(DATA),
PINMUX_DATA_END,
/* PORT0_IN -> PORT190_IN */
PINMUX_INPUT_BEGIN,
PORT_ALL(IN),
PINMUX_INPUT_END,
/* PORT0_IN_PU -> PORT190_IN_PU */
PINMUX_INPUT_PULLUP_BEGIN,
PORT_ALL(IN_PU),
PINMUX_INPUT_PULLUP_END,
/* PORT0_IN_PD -> PORT190_IN_PD */
PINMUX_INPUT_PULLDOWN_BEGIN,
PORT_ALL(IN_PD),
PINMUX_INPUT_PULLDOWN_END,
/* PORT0_OUT -> PORT190_OUT */
PINMUX_OUTPUT_BEGIN,
PORT_ALL(OUT),
PINMUX_OUTPUT_END,
PINMUX_FUNCTION_BEGIN,
PORT_ALL(FN_IN), /* PORT0_FN_IN -> PORT190_FN_IN */
PORT_ALL(FN_OUT), /* PORT0_FN_OUT -> PORT190_FN_OUT */
PORT_ALL(FN0), /* PORT0_FN0 -> PORT190_FN0 */
PORT_ALL(FN1), /* PORT0_FN1 -> PORT190_FN1 */
PORT_ALL(FN2), /* PORT0_FN2 -> PORT190_FN2 */
PORT_ALL(FN3), /* PORT0_FN3 -> PORT190_FN3 */
PORT_ALL(FN4), /* PORT0_FN4 -> PORT190_FN4 */
PORT_ALL(FN5), /* PORT0_FN5 -> PORT190_FN5 */
PORT_ALL(FN6), /* PORT0_FN6 -> PORT190_FN6 */
PORT_ALL(FN7), /* PORT0_FN7 -> PORT190_FN7 */
MSEL1CR_31_0, MSEL1CR_31_1,
MSEL1CR_30_0, MSEL1CR_30_1,
MSEL1CR_29_0, MSEL1CR_29_1,
MSEL1CR_28_0, MSEL1CR_28_1,
MSEL1CR_27_0, MSEL1CR_27_1,
MSEL1CR_26_0, MSEL1CR_26_1,
MSEL1CR_16_0, MSEL1CR_16_1,
MSEL1CR_15_0, MSEL1CR_15_1,
MSEL1CR_14_0, MSEL1CR_14_1,
MSEL1CR_13_0, MSEL1CR_13_1,
MSEL1CR_12_0, MSEL1CR_12_1,
MSEL1CR_9_0, MSEL1CR_9_1,
MSEL1CR_8_0, MSEL1CR_8_1,
MSEL1CR_7_0, MSEL1CR_7_1,
MSEL1CR_6_0, MSEL1CR_6_1,
MSEL1CR_4_0, MSEL1CR_4_1,
MSEL1CR_3_0, MSEL1CR_3_1,
MSEL1CR_2_0, MSEL1CR_2_1,
MSEL1CR_0_0, MSEL1CR_0_1,
MSEL3CR_27_0, MSEL3CR_27_1,
MSEL3CR_26_0, MSEL3CR_26_1,
MSEL3CR_21_0, MSEL3CR_21_1,
MSEL3CR_20_0, MSEL3CR_20_1,
MSEL3CR_15_0, MSEL3CR_15_1,
MSEL3CR_9_0, MSEL3CR_9_1,
MSEL3CR_6_0, MSEL3CR_6_1,
MSEL4CR_19_0, MSEL4CR_19_1,
MSEL4CR_18_0, MSEL4CR_18_1,
MSEL4CR_17_0, MSEL4CR_17_1,
MSEL4CR_16_0, MSEL4CR_16_1,
MSEL4CR_15_0, MSEL4CR_15_1,
MSEL4CR_14_0, MSEL4CR_14_1,
MSEL4CR_10_0, MSEL4CR_10_1,
MSEL4CR_6_0, MSEL4CR_6_1,
MSEL4CR_4_0, MSEL4CR_4_1,
MSEL4CR_1_0, MSEL4CR_1_1,
PINMUX_FUNCTION_END,
PINMUX_MARK_BEGIN,
/* IRQ */
IRQ0_6_MARK, IRQ0_162_MARK, IRQ1_MARK, IRQ2_4_MARK,
IRQ2_5_MARK, IRQ3_8_MARK, IRQ3_16_MARK, IRQ4_17_MARK,
IRQ4_163_MARK, IRQ5_MARK, IRQ6_39_MARK, IRQ6_164_MARK,
IRQ7_40_MARK, IRQ7_167_MARK, IRQ8_41_MARK, IRQ8_168_MARK,
IRQ9_42_MARK, IRQ9_169_MARK, IRQ10_MARK, IRQ11_MARK,
IRQ12_80_MARK, IRQ12_137_MARK, IRQ13_81_MARK, IRQ13_145_MARK,
IRQ14_82_MARK, IRQ14_146_MARK, IRQ15_83_MARK, IRQ15_147_MARK,
IRQ16_84_MARK, IRQ16_170_MARK, IRQ17_MARK, IRQ18_MARK,
IRQ19_MARK, IRQ20_MARK, IRQ21_MARK, IRQ22_MARK,
IRQ23_MARK, IRQ24_MARK, IRQ25_MARK, IRQ26_121_MARK,
IRQ26_172_MARK, IRQ27_122_MARK, IRQ27_180_MARK, IRQ28_123_MARK,
IRQ28_181_MARK, IRQ29_129_MARK, IRQ29_182_MARK, IRQ30_130_MARK,
IRQ30_183_MARK, IRQ31_138_MARK, IRQ31_184_MARK,
/* MSIOF0 */
MSIOF0_TSYNC_MARK, MSIOF0_TSCK_MARK, MSIOF0_RXD_MARK,
MSIOF0_RSCK_MARK, MSIOF0_RSYNC_MARK, MSIOF0_MCK0_MARK,
MSIOF0_MCK1_MARK, MSIOF0_SS1_MARK, MSIOF0_SS2_MARK,
MSIOF0_TXD_MARK,
/* MSIOF1 */
MSIOF1_TSCK_39_MARK, MSIOF1_TSYNC_40_MARK,
MSIOF1_TSCK_88_MARK, MSIOF1_TSYNC_89_MARK,
MSIOF1_TXD_41_MARK, MSIOF1_RXD_42_MARK,
MSIOF1_TXD_90_MARK, MSIOF1_RXD_91_MARK,
MSIOF1_SS1_43_MARK, MSIOF1_SS2_44_MARK,
MSIOF1_SS1_92_MARK, MSIOF1_SS2_93_MARK,
MSIOF1_RSCK_MARK, MSIOF1_RSYNC_MARK,
MSIOF1_MCK0_MARK, MSIOF1_MCK1_MARK,
/* MSIOF2 */
MSIOF2_RSCK_MARK, MSIOF2_RSYNC_MARK, MSIOF2_MCK0_MARK,
MSIOF2_MCK1_MARK, MSIOF2_SS1_MARK, MSIOF2_SS2_MARK,
MSIOF2_TSYNC_MARK, MSIOF2_TSCK_MARK, MSIOF2_RXD_MARK,
MSIOF2_TXD_MARK,
/* BBIF1 */
BBIF1_RXD_MARK, BBIF1_TSYNC_MARK, BBIF1_TSCK_MARK,
BBIF1_TXD_MARK, BBIF1_RSCK_MARK, BBIF1_RSYNC_MARK,
BBIF1_FLOW_MARK, BB_RX_FLOW_N_MARK,
/* BBIF2 */
BBIF2_TSCK1_MARK, BBIF2_TSYNC1_MARK,
BBIF2_TXD1_MARK, BBIF2_RXD_MARK,
/* FSI */
FSIACK_MARK, FSIBCK_MARK, FSIAILR_MARK, FSIAIBT_MARK,
FSIAISLD_MARK, FSIAOMC_MARK, FSIAOLR_MARK, FSIAOBT_MARK,
FSIAOSLD_MARK, FSIASPDIF_11_MARK, FSIASPDIF_15_MARK,
/* FMSI */
FMSOCK_MARK, FMSOOLR_MARK, FMSIOLR_MARK, FMSOOBT_MARK,
FMSIOBT_MARK, FMSOSLD_MARK, FMSOILR_MARK, FMSIILR_MARK,
FMSOIBT_MARK, FMSIIBT_MARK, FMSISLD_MARK, FMSICK_MARK,
/* SCIFA0 */
SCIFA0_TXD_MARK, SCIFA0_RXD_MARK, SCIFA0_SCK_MARK,
SCIFA0_RTS_MARK, SCIFA0_CTS_MARK,
/* SCIFA1 */
SCIFA1_TXD_MARK, SCIFA1_RXD_MARK, SCIFA1_SCK_MARK,
SCIFA1_RTS_MARK, SCIFA1_CTS_MARK,
/* SCIFA2 */
SCIFA2_CTS1_MARK, SCIFA2_RTS1_MARK, SCIFA2_TXD1_MARK,
SCIFA2_RXD1_MARK, SCIFA2_SCK1_MARK,
/* SCIFA3 */
SCIFA3_CTS_43_MARK, SCIFA3_CTS_140_MARK, SCIFA3_RTS_44_MARK,
SCIFA3_RTS_141_MARK, SCIFA3_SCK_MARK, SCIFA3_TXD_MARK,
SCIFA3_RXD_MARK,
/* SCIFA4 */
SCIFA4_RXD_MARK, SCIFA4_TXD_MARK,
/* SCIFA5 */
SCIFA5_RXD_MARK, SCIFA5_TXD_MARK,
/* SCIFB */
SCIFB_SCK_MARK, SCIFB_RTS_MARK, SCIFB_CTS_MARK,
SCIFB_TXD_MARK, SCIFB_RXD_MARK,
/* CEU */
VIO_HD_MARK, VIO_CKO1_MARK, VIO_CKO2_MARK, VIO_VD_MARK,
VIO_CLK_MARK, VIO_FIELD_MARK, VIO_CKO_MARK,
VIO_D0_MARK, VIO_D1_MARK, VIO_D2_MARK, VIO_D3_MARK,
VIO_D4_MARK, VIO_D5_MARK, VIO_D6_MARK, VIO_D7_MARK,
VIO_D8_MARK, VIO_D9_MARK, VIO_D10_MARK, VIO_D11_MARK,
VIO_D12_MARK, VIO_D13_MARK, VIO_D14_MARK, VIO_D15_MARK,
/* USB0 */
IDIN_0_MARK, EXTLP_0_MARK, OVCN2_0_MARK, PWEN_0_MARK,
OVCN_0_MARK, VBUS0_0_MARK,
/* USB1 */
IDIN_1_18_MARK, IDIN_1_113_MARK,
PWEN_1_115_MARK, PWEN_1_138_MARK,
OVCN_1_114_MARK, OVCN_1_162_MARK,
EXTLP_1_MARK, OVCN2_1_MARK,
VBUS0_1_MARK,
/* GPIO */
GPI0_MARK, GPI1_MARK, GPO0_MARK, GPO1_MARK,
/* BSC */
BS_MARK, WE1_MARK,
CKO_MARK, WAIT_MARK, RDWR_MARK,
A0_MARK, A1_MARK, A2_MARK, A3_MARK,
A6_MARK, A7_MARK, A8_MARK, A9_MARK,
A10_MARK, A11_MARK, A12_MARK, A13_MARK,
A14_MARK, A15_MARK, A16_MARK, A17_MARK,
A18_MARK, A19_MARK, A20_MARK, A21_MARK,
A22_MARK, A23_MARK, A24_MARK, A25_MARK,
A26_MARK,
CS0_MARK, CS2_MARK, CS4_MARK,
CS5A_MARK, CS5B_MARK, CS6A_MARK,
/* BSC/FLCTL */
RD_FSC_MARK, WE0_FWE_MARK, A4_FOE_MARK, A5_FCDE_MARK,
D0_NAF0_MARK, D1_NAF1_MARK, D2_NAF2_MARK, D3_NAF3_MARK,
D4_NAF4_MARK, D5_NAF5_MARK, D6_NAF6_MARK, D7_NAF7_MARK,
D8_NAF8_MARK, D9_NAF9_MARK, D10_NAF10_MARK, D11_NAF11_MARK,
D12_NAF12_MARK, D13_NAF13_MARK, D14_NAF14_MARK, D15_NAF15_MARK,
/* MMCIF(1) */
MMCD0_0_MARK, MMCD0_1_MARK, MMCD0_2_MARK, MMCD0_3_MARK,
MMCD0_4_MARK, MMCD0_5_MARK, MMCD0_6_MARK, MMCD0_7_MARK,
MMCCMD0_MARK, MMCCLK0_MARK,
/* MMCIF(2) */
MMCD1_0_MARK, MMCD1_1_MARK, MMCD1_2_MARK, MMCD1_3_MARK,
MMCD1_4_MARK, MMCD1_5_MARK, MMCD1_6_MARK, MMCD1_7_MARK,
MMCCLK1_MARK, MMCCMD1_MARK,
/* SPU2 */
VINT_I_MARK,
/* FLCTL */
FCE1_MARK, FCE0_MARK, FRB_MARK,
/* HSI */
GP_RX_FLAG_MARK, GP_RX_DATA_MARK, GP_TX_READY_MARK,
GP_RX_WAKE_MARK, MP_TX_FLAG_MARK, MP_TX_DATA_MARK,
MP_RX_READY_MARK, MP_TX_WAKE_MARK,
/* MFI */
MFIv6_MARK,
MFIv4_MARK,
MEMC_CS0_MARK, MEMC_BUSCLK_MEMC_A0_MARK,
MEMC_CS1_MEMC_A1_MARK, MEMC_ADV_MEMC_DREQ0_MARK,
MEMC_WAIT_MEMC_DREQ1_MARK, MEMC_NOE_MARK,
MEMC_NWE_MARK, MEMC_INT_MARK,
MEMC_AD0_MARK, MEMC_AD1_MARK, MEMC_AD2_MARK,
MEMC_AD3_MARK, MEMC_AD4_MARK, MEMC_AD5_MARK,
MEMC_AD6_MARK, MEMC_AD7_MARK, MEMC_AD8_MARK,
MEMC_AD9_MARK, MEMC_AD10_MARK, MEMC_AD11_MARK,
MEMC_AD12_MARK, MEMC_AD13_MARK, MEMC_AD14_MARK,
MEMC_AD15_MARK,
/* SIM */
SIM_RST_MARK, SIM_CLK_MARK, SIM_D_MARK,
/* TPU */
TPU0TO0_MARK, TPU0TO1_MARK,
TPU0TO2_93_MARK, TPU0TO2_99_MARK,
TPU0TO3_MARK,
/* I2C2 */
I2C_SCL2_MARK, I2C_SDA2_MARK,
/* I2C3(1) */
I2C_SCL3_MARK, I2C_SDA3_MARK,
/* I2C3(2) */
I2C_SCL3S_MARK, I2C_SDA3S_MARK,
/* I2C4(2) */
I2C_SCL4_MARK, I2C_SDA4_MARK,
/* I2C4(2) */
I2C_SCL4S_MARK, I2C_SDA4S_MARK,
/* KEYSC */
KEYOUT0_MARK, KEYIN0_121_MARK, KEYIN0_136_MARK,
KEYOUT1_MARK, KEYIN1_122_MARK, KEYIN1_135_MARK,
KEYOUT2_MARK, KEYIN2_123_MARK, KEYIN2_134_MARK,
KEYOUT3_MARK, KEYIN3_124_MARK, KEYIN3_133_MARK,
KEYOUT4_MARK, KEYIN4_MARK,
KEYOUT5_MARK, KEYIN5_MARK,
KEYOUT6_MARK, KEYIN6_MARK,
KEYOUT7_MARK, KEYIN7_MARK,
/* LCDC */
LCDC0_SELECT_MARK,
LCDC1_SELECT_MARK,
LCDHSYN_MARK, LCDCS_MARK, LCDVSYN_MARK, LCDDCK_MARK,
LCDWR_MARK, LCDRD_MARK, LCDDISP_MARK, LCDRS_MARK,
LCDLCLK_MARK, LCDDON_MARK,
LCDD0_MARK, LCDD1_MARK, LCDD2_MARK, LCDD3_MARK,
LCDD4_MARK, LCDD5_MARK, LCDD6_MARK, LCDD7_MARK,
LCDD8_MARK, LCDD9_MARK, LCDD10_MARK, LCDD11_MARK,
LCDD12_MARK, LCDD13_MARK, LCDD14_MARK, LCDD15_MARK,
LCDD16_MARK, LCDD17_MARK, LCDD18_MARK, LCDD19_MARK,
LCDD20_MARK, LCDD21_MARK, LCDD22_MARK, LCDD23_MARK,
/* IRDA */
IRDA_OUT_MARK, IRDA_IN_MARK, IRDA_FIRSEL_MARK,
IROUT_139_MARK, IROUT_140_MARK,
/* TSIF1 */
TS0_1SELECT_MARK,
TS0_2SELECT_MARK,
TS1_1SELECT_MARK,
TS1_2SELECT_MARK,
TS_SPSYNC1_MARK, TS_SDAT1_MARK,
TS_SDEN1_MARK, TS_SCK1_MARK,
/* TSIF2 */
TS_SPSYNC2_MARK, TS_SDAT2_MARK,
TS_SDEN2_MARK, TS_SCK2_MARK,
/* HDMI */
HDMI_HPD_MARK, HDMI_CEC_MARK,
/* SDHI0 */
SDHICLK0_MARK, SDHICD0_MARK,
SDHICMD0_MARK, SDHIWP0_MARK,
SDHID0_0_MARK, SDHID0_1_MARK,
SDHID0_2_MARK, SDHID0_3_MARK,
/* SDHI1 */
SDHICLK1_MARK, SDHICMD1_MARK, SDHID1_0_MARK,
SDHID1_1_MARK, SDHID1_2_MARK, SDHID1_3_MARK,
/* SDHI2 */
SDHICLK2_MARK, SDHICMD2_MARK, SDHID2_0_MARK,
SDHID2_1_MARK, SDHID2_2_MARK, SDHID2_3_MARK,
/* SDENC */
SDENC_CPG_MARK,
SDENC_DV_CLKI_MARK,
PINMUX_MARK_END,
};
static pinmux_enum_t pinmux_data[] = {
/* specify valid pin states for each pin in GPIO mode */
PORT_DATA_IO_PD(0), PORT_DATA_IO_PD(1),
PORT_DATA_O(2), PORT_DATA_I_PD(3),
PORT_DATA_I_PD(4), PORT_DATA_I_PD(5),
PORT_DATA_IO_PU_PD(6), PORT_DATA_I_PD(7),
PORT_DATA_IO_PD(8), PORT_DATA_O(9),
PORT_DATA_O(10), PORT_DATA_O(11),
PORT_DATA_IO_PU_PD(12), PORT_DATA_IO_PD(13),
PORT_DATA_IO_PD(14), PORT_DATA_O(15),
PORT_DATA_IO_PD(16), PORT_DATA_IO_PD(17),
PORT_DATA_I_PD(18), PORT_DATA_IO(19),
PORT_DATA_IO(20), PORT_DATA_IO(21),
PORT_DATA_IO(22), PORT_DATA_IO(23),
PORT_DATA_IO(24), PORT_DATA_IO(25),
PORT_DATA_IO(26), PORT_DATA_IO(27),
PORT_DATA_IO(28), PORT_DATA_IO(29),
PORT_DATA_IO(30), PORT_DATA_IO(31),
PORT_DATA_IO(32), PORT_DATA_IO(33),
PORT_DATA_IO(34), PORT_DATA_IO(35),
PORT_DATA_IO(36), PORT_DATA_IO(37),
PORT_DATA_IO(38), PORT_DATA_IO(39),
PORT_DATA_IO(40), PORT_DATA_IO(41),
PORT_DATA_IO(42), PORT_DATA_IO(43),
PORT_DATA_IO(44), PORT_DATA_IO(45),
PORT_DATA_IO_PU(46), PORT_DATA_IO_PU(47),
PORT_DATA_IO_PU(48), PORT_DATA_IO_PU(49),
PORT_DATA_IO_PU(50), PORT_DATA_IO_PU(51),
PORT_DATA_IO_PU(52), PORT_DATA_IO_PU(53),
PORT_DATA_IO_PU(54), PORT_DATA_IO_PU(55),
PORT_DATA_IO_PU(56), PORT_DATA_IO_PU(57),
PORT_DATA_IO_PU(58), PORT_DATA_IO_PU(59),
PORT_DATA_IO_PU(60), PORT_DATA_IO_PU(61),
PORT_DATA_IO(62), PORT_DATA_O(63),
PORT_DATA_O(64), PORT_DATA_IO_PU(65),
PORT_DATA_O(66), PORT_DATA_IO_PU(67), /*66?*/
PORT_DATA_O(68), PORT_DATA_IO(69),
PORT_DATA_IO(70), PORT_DATA_IO(71),
PORT_DATA_O(72), PORT_DATA_I_PU(73),
PORT_DATA_I_PU_PD(74), PORT_DATA_IO_PU_PD(75),
PORT_DATA_IO_PU_PD(76), PORT_DATA_IO_PU_PD(77),
PORT_DATA_IO_PU_PD(78), PORT_DATA_IO_PU_PD(79),
PORT_DATA_IO_PU_PD(80), PORT_DATA_IO_PU_PD(81),
PORT_DATA_IO_PU_PD(82), PORT_DATA_IO_PU_PD(83),
PORT_DATA_IO_PU_PD(84), PORT_DATA_IO_PU_PD(85),
PORT_DATA_IO_PU_PD(86), PORT_DATA_IO_PU_PD(87),
PORT_DATA_IO_PU_PD(88), PORT_DATA_IO_PU_PD(89),
PORT_DATA_IO_PU_PD(90), PORT_DATA_IO_PU_PD(91),
PORT_DATA_IO_PU_PD(92), PORT_DATA_IO_PU_PD(93),
PORT_DATA_IO_PU_PD(94), PORT_DATA_IO_PU_PD(95),
PORT_DATA_IO_PU(96), PORT_DATA_IO_PU_PD(97),
PORT_DATA_IO_PU_PD(98), PORT_DATA_O(99), /*99?*/
PORT_DATA_IO_PD(100), PORT_DATA_IO_PD(101),
PORT_DATA_IO_PD(102), PORT_DATA_IO_PD(103),
PORT_DATA_IO_PD(104), PORT_DATA_IO_PD(105),
PORT_DATA_IO_PU(106), PORT_DATA_IO_PU(107),
PORT_DATA_IO_PU(108), PORT_DATA_IO_PU(109),
PORT_DATA_IO_PU(110), PORT_DATA_IO_PU(111),
PORT_DATA_IO_PD(112), PORT_DATA_IO_PD(113),
PORT_DATA_IO_PU(114), PORT_DATA_IO_PU(115),
PORT_DATA_IO_PU(116), PORT_DATA_IO_PU(117),
PORT_DATA_IO_PU(118), PORT_DATA_IO_PU(119),
PORT_DATA_IO_PU(120), PORT_DATA_IO_PD(121),
PORT_DATA_IO_PD(122), PORT_DATA_IO_PD(123),
PORT_DATA_IO_PD(124), PORT_DATA_IO_PD(125),
PORT_DATA_IO_PD(126), PORT_DATA_IO_PD(127),
PORT_DATA_IO_PD(128), PORT_DATA_IO_PU_PD(129),
PORT_DATA_IO_PU_PD(130), PORT_DATA_IO_PU_PD(131),
PORT_DATA_IO_PU_PD(132), PORT_DATA_IO_PU_PD(133),
PORT_DATA_IO_PU_PD(134), PORT_DATA_IO_PU_PD(135),
PORT_DATA_IO_PD(136), PORT_DATA_IO_PD(137),
PORT_DATA_IO_PD(138), PORT_DATA_IO_PD(139),
PORT_DATA_IO_PD(140), PORT_DATA_IO_PD(141),
PORT_DATA_IO_PD(142), PORT_DATA_IO_PU_PD(143),
PORT_DATA_IO_PD(144), PORT_DATA_IO_PD(145),
PORT_DATA_IO_PD(146), PORT_DATA_IO_PD(147),
PORT_DATA_IO_PD(148), PORT_DATA_IO_PD(149),
PORT_DATA_IO_PD(150), PORT_DATA_IO_PD(151),
PORT_DATA_IO_PU_PD(152), PORT_DATA_I_PD(153),
PORT_DATA_IO_PU_PD(154), PORT_DATA_I_PD(155),
PORT_DATA_IO_PD(156), PORT_DATA_IO_PD(157),
PORT_DATA_I_PD(158), PORT_DATA_IO_PD(159),
PORT_DATA_O(160), PORT_DATA_IO_PD(161),
PORT_DATA_IO_PD(162), PORT_DATA_IO_PD(163),
PORT_DATA_I_PD(164), PORT_DATA_IO_PD(165),
PORT_DATA_I_PD(166), PORT_DATA_I_PD(167),
PORT_DATA_I_PD(168), PORT_DATA_I_PD(169),
PORT_DATA_I_PD(170), PORT_DATA_O(171),
PORT_DATA_IO_PU_PD(172), PORT_DATA_IO_PU_PD(173),
PORT_DATA_IO_PU_PD(174), PORT_DATA_IO_PU_PD(175),
PORT_DATA_IO_PU_PD(176), PORT_DATA_IO_PU_PD(177),
PORT_DATA_IO_PU_PD(178), PORT_DATA_O(179),
PORT_DATA_IO_PU_PD(180), PORT_DATA_IO_PU_PD(181),
PORT_DATA_IO_PU_PD(182), PORT_DATA_IO_PU_PD(183),
PORT_DATA_IO_PU_PD(184), PORT_DATA_O(185),
PORT_DATA_IO_PU_PD(186), PORT_DATA_IO_PU_PD(187),
PORT_DATA_IO_PU_PD(188), PORT_DATA_IO_PU_PD(189),
PORT_DATA_IO_PU_PD(190),
/* IRQ */
PINMUX_DATA(IRQ0_6_MARK, PORT6_FN0, MSEL1CR_0_0),
PINMUX_DATA(IRQ0_162_MARK, PORT162_FN0, MSEL1CR_0_1),
PINMUX_DATA(IRQ1_MARK, PORT12_FN0),
PINMUX_DATA(IRQ2_4_MARK, PORT4_FN0, MSEL1CR_2_0),
PINMUX_DATA(IRQ2_5_MARK, PORT5_FN0, MSEL1CR_2_1),
PINMUX_DATA(IRQ3_8_MARK, PORT8_FN0, MSEL1CR_3_0),
PINMUX_DATA(IRQ3_16_MARK, PORT16_FN0, MSEL1CR_3_1),
PINMUX_DATA(IRQ4_17_MARK, PORT17_FN0, MSEL1CR_4_0),
PINMUX_DATA(IRQ4_163_MARK, PORT163_FN0, MSEL1CR_4_1),
PINMUX_DATA(IRQ5_MARK, PORT18_FN0),
PINMUX_DATA(IRQ6_39_MARK, PORT39_FN0, MSEL1CR_6_0),
PINMUX_DATA(IRQ6_164_MARK, PORT164_FN0, MSEL1CR_6_1),
PINMUX_DATA(IRQ7_40_MARK, PORT40_FN0, MSEL1CR_7_1),
PINMUX_DATA(IRQ7_167_MARK, PORT167_FN0, MSEL1CR_7_0),
PINMUX_DATA(IRQ8_41_MARK, PORT41_FN0, MSEL1CR_8_1),
PINMUX_DATA(IRQ8_168_MARK, PORT168_FN0, MSEL1CR_8_0),
PINMUX_DATA(IRQ9_42_MARK, PORT42_FN0, MSEL1CR_9_0),
PINMUX_DATA(IRQ9_169_MARK, PORT169_FN0, MSEL1CR_9_1),
PINMUX_DATA(IRQ10_MARK, PORT65_FN0, MSEL1CR_9_1),
PINMUX_DATA(IRQ11_MARK, PORT67_FN0),
PINMUX_DATA(IRQ12_80_MARK, PORT80_FN0, MSEL1CR_12_0),
PINMUX_DATA(IRQ12_137_MARK, PORT137_FN0, MSEL1CR_12_1),
PINMUX_DATA(IRQ13_81_MARK, PORT81_FN0, MSEL1CR_13_0),
PINMUX_DATA(IRQ13_145_MARK, PORT145_FN0, MSEL1CR_13_1),
PINMUX_DATA(IRQ14_82_MARK, PORT82_FN0, MSEL1CR_14_0),
PINMUX_DATA(IRQ14_146_MARK, PORT146_FN0, MSEL1CR_14_1),
PINMUX_DATA(IRQ15_83_MARK, PORT83_FN0, MSEL1CR_15_0),
PINMUX_DATA(IRQ15_147_MARK, PORT147_FN0, MSEL1CR_15_1),
PINMUX_DATA(IRQ16_84_MARK, PORT84_FN0, MSEL1CR_16_0),
PINMUX_DATA(IRQ16_170_MARK, PORT170_FN0, MSEL1CR_16_1),
PINMUX_DATA(IRQ17_MARK, PORT85_FN0),
PINMUX_DATA(IRQ18_MARK, PORT86_FN0),
PINMUX_DATA(IRQ19_MARK, PORT87_FN0),
PINMUX_DATA(IRQ20_MARK, PORT92_FN0),
PINMUX_DATA(IRQ21_MARK, PORT93_FN0),
PINMUX_DATA(IRQ22_MARK, PORT94_FN0),
PINMUX_DATA(IRQ23_MARK, PORT95_FN0),
PINMUX_DATA(IRQ24_MARK, PORT112_FN0),
PINMUX_DATA(IRQ25_MARK, PORT119_FN0),
PINMUX_DATA(IRQ26_121_MARK, PORT121_FN0, MSEL1CR_26_1),
PINMUX_DATA(IRQ26_172_MARK, PORT172_FN0, MSEL1CR_26_0),
PINMUX_DATA(IRQ27_122_MARK, PORT122_FN0, MSEL1CR_27_1),
PINMUX_DATA(IRQ27_180_MARK, PORT180_FN0, MSEL1CR_27_0),
PINMUX_DATA(IRQ28_123_MARK, PORT123_FN0, MSEL1CR_28_1),
PINMUX_DATA(IRQ28_181_MARK, PORT181_FN0, MSEL1CR_28_0),
PINMUX_DATA(IRQ29_129_MARK, PORT129_FN0, MSEL1CR_29_1),
PINMUX_DATA(IRQ29_182_MARK, PORT182_FN0, MSEL1CR_29_0),
PINMUX_DATA(IRQ30_130_MARK, PORT130_FN0, MSEL1CR_30_1),
PINMUX_DATA(IRQ30_183_MARK, PORT183_FN0, MSEL1CR_30_0),
PINMUX_DATA(IRQ31_138_MARK, PORT138_FN0, MSEL1CR_31_1),
PINMUX_DATA(IRQ31_184_MARK, PORT184_FN0, MSEL1CR_31_0),
/* Function 1 */
PINMUX_DATA(BBIF2_TSCK1_MARK, PORT0_FN1),
PINMUX_DATA(BBIF2_TSYNC1_MARK, PORT1_FN1),
PINMUX_DATA(BBIF2_TXD1_MARK, PORT2_FN1),
PINMUX_DATA(BBIF2_RXD_MARK, PORT3_FN1),
PINMUX_DATA(FSIACK_MARK, PORT4_FN1),
PINMUX_DATA(FSIAILR_MARK, PORT5_FN1),
PINMUX_DATA(FSIAIBT_MARK, PORT6_FN1),
PINMUX_DATA(FSIAISLD_MARK, PORT7_FN1),
PINMUX_DATA(FSIAOMC_MARK, PORT8_FN1),
PINMUX_DATA(FSIAOLR_MARK, PORT9_FN1),
PINMUX_DATA(FSIAOBT_MARK, PORT10_FN1),
PINMUX_DATA(FSIAOSLD_MARK, PORT11_FN1),
PINMUX_DATA(FMSOCK_MARK, PORT12_FN1),
PINMUX_DATA(FMSOOLR_MARK, PORT13_FN1),
PINMUX_DATA(FMSOOBT_MARK, PORT14_FN1),
PINMUX_DATA(FMSOSLD_MARK, PORT15_FN1),
PINMUX_DATA(FMSOILR_MARK, PORT16_FN1),
PINMUX_DATA(FMSOIBT_MARK, PORT17_FN1),
PINMUX_DATA(FMSISLD_MARK, PORT18_FN1),
PINMUX_DATA(A0_MARK, PORT19_FN1),
PINMUX_DATA(A1_MARK, PORT20_FN1),
PINMUX_DATA(A2_MARK, PORT21_FN1),
PINMUX_DATA(A3_MARK, PORT22_FN1),
PINMUX_DATA(A4_FOE_MARK, PORT23_FN1),
PINMUX_DATA(A5_FCDE_MARK, PORT24_FN1),
PINMUX_DATA(A6_MARK, PORT25_FN1),
PINMUX_DATA(A7_MARK, PORT26_FN1),
PINMUX_DATA(A8_MARK, PORT27_FN1),
PINMUX_DATA(A9_MARK, PORT28_FN1),
PINMUX_DATA(A10_MARK, PORT29_FN1),
PINMUX_DATA(A11_MARK, PORT30_FN1),
PINMUX_DATA(A12_MARK, PORT31_FN1),
PINMUX_DATA(A13_MARK, PORT32_FN1),
PINMUX_DATA(A14_MARK, PORT33_FN1),
PINMUX_DATA(A15_MARK, PORT34_FN1),
PINMUX_DATA(A16_MARK, PORT35_FN1),
PINMUX_DATA(A17_MARK, PORT36_FN1),
PINMUX_DATA(A18_MARK, PORT37_FN1),
PINMUX_DATA(A19_MARK, PORT38_FN1),
PINMUX_DATA(A20_MARK, PORT39_FN1),
PINMUX_DATA(A21_MARK, PORT40_FN1),
PINMUX_DATA(A22_MARK, PORT41_FN1),
PINMUX_DATA(A23_MARK, PORT42_FN1),
PINMUX_DATA(A24_MARK, PORT43_FN1),
PINMUX_DATA(A25_MARK, PORT44_FN1),
PINMUX_DATA(A26_MARK, PORT45_FN1),
PINMUX_DATA(D0_NAF0_MARK, PORT46_FN1),
PINMUX_DATA(D1_NAF1_MARK, PORT47_FN1),
PINMUX_DATA(D2_NAF2_MARK, PORT48_FN1),
PINMUX_DATA(D3_NAF3_MARK, PORT49_FN1),
PINMUX_DATA(D4_NAF4_MARK, PORT50_FN1),
PINMUX_DATA(D5_NAF5_MARK, PORT51_FN1),
PINMUX_DATA(D6_NAF6_MARK, PORT52_FN1),
PINMUX_DATA(D7_NAF7_MARK, PORT53_FN1),
PINMUX_DATA(D8_NAF8_MARK, PORT54_FN1),
PINMUX_DATA(D9_NAF9_MARK, PORT55_FN1),
PINMUX_DATA(D10_NAF10_MARK, PORT56_FN1),
PINMUX_DATA(D11_NAF11_MARK, PORT57_FN1),
PINMUX_DATA(D12_NAF12_MARK, PORT58_FN1),
PINMUX_DATA(D13_NAF13_MARK, PORT59_FN1),
PINMUX_DATA(D14_NAF14_MARK, PORT60_FN1),
PINMUX_DATA(D15_NAF15_MARK, PORT61_FN1),
PINMUX_DATA(CS0_MARK, PORT62_FN1),
PINMUX_DATA(CS2_MARK, PORT63_FN1),
PINMUX_DATA(CS4_MARK, PORT64_FN1),
PINMUX_DATA(CS5A_MARK, PORT65_FN1),
PINMUX_DATA(CS5B_MARK, PORT66_FN1),
PINMUX_DATA(CS6A_MARK, PORT67_FN1),
PINMUX_DATA(FCE0_MARK, PORT68_FN1),
PINMUX_DATA(RD_FSC_MARK, PORT69_FN1),
PINMUX_DATA(WE0_FWE_MARK, PORT70_FN1),
PINMUX_DATA(WE1_MARK, PORT71_FN1),
PINMUX_DATA(CKO_MARK, PORT72_FN1),
PINMUX_DATA(FRB_MARK, PORT73_FN1),
PINMUX_DATA(WAIT_MARK, PORT74_FN1),
PINMUX_DATA(RDWR_MARK, PORT75_FN1),
PINMUX_DATA(MEMC_AD0_MARK, PORT76_FN1),
PINMUX_DATA(MEMC_AD1_MARK, PORT77_FN1),
PINMUX_DATA(MEMC_AD2_MARK, PORT78_FN1),
PINMUX_DATA(MEMC_AD3_MARK, PORT79_FN1),
PINMUX_DATA(MEMC_AD4_MARK, PORT80_FN1),
PINMUX_DATA(MEMC_AD5_MARK, PORT81_FN1),
PINMUX_DATA(MEMC_AD6_MARK, PORT82_FN1),
PINMUX_DATA(MEMC_AD7_MARK, PORT83_FN1),
PINMUX_DATA(MEMC_AD8_MARK, PORT84_FN1),
PINMUX_DATA(MEMC_AD9_MARK, PORT85_FN1),
PINMUX_DATA(MEMC_AD10_MARK, PORT86_FN1),
PINMUX_DATA(MEMC_AD11_MARK, PORT87_FN1),
PINMUX_DATA(MEMC_AD12_MARK, PORT88_FN1),
PINMUX_DATA(MEMC_AD13_MARK, PORT89_FN1),
PINMUX_DATA(MEMC_AD14_MARK, PORT90_FN1),
PINMUX_DATA(MEMC_AD15_MARK, PORT91_FN1),
PINMUX_DATA(MEMC_CS0_MARK, PORT92_FN1),
PINMUX_DATA(MEMC_BUSCLK_MEMC_A0_MARK, PORT93_FN1),
PINMUX_DATA(MEMC_CS1_MEMC_A1_MARK, PORT94_FN1),
PINMUX_DATA(MEMC_ADV_MEMC_DREQ0_MARK, PORT95_FN1),
PINMUX_DATA(MEMC_WAIT_MEMC_DREQ1_MARK, PORT96_FN1),
PINMUX_DATA(MEMC_NOE_MARK, PORT97_FN1),
PINMUX_DATA(MEMC_NWE_MARK, PORT98_FN1),
PINMUX_DATA(MEMC_INT_MARK, PORT99_FN1),
PINMUX_DATA(VIO_VD_MARK, PORT100_FN1),
PINMUX_DATA(VIO_HD_MARK, PORT101_FN1),
PINMUX_DATA(VIO_D0_MARK, PORT102_FN1),
PINMUX_DATA(VIO_D1_MARK, PORT103_FN1),
PINMUX_DATA(VIO_D2_MARK, PORT104_FN1),
PINMUX_DATA(VIO_D3_MARK, PORT105_FN1),
PINMUX_DATA(VIO_D4_MARK, PORT106_FN1),
PINMUX_DATA(VIO_D5_MARK, PORT107_FN1),
PINMUX_DATA(VIO_D6_MARK, PORT108_FN1),
PINMUX_DATA(VIO_D7_MARK, PORT109_FN1),
PINMUX_DATA(VIO_D8_MARK, PORT110_FN1),
PINMUX_DATA(VIO_D9_MARK, PORT111_FN1),
PINMUX_DATA(VIO_D10_MARK, PORT112_FN1),
PINMUX_DATA(VIO_D11_MARK, PORT113_FN1),
PINMUX_DATA(VIO_D12_MARK, PORT114_FN1),
PINMUX_DATA(VIO_D13_MARK, PORT115_FN1),
PINMUX_DATA(VIO_D14_MARK, PORT116_FN1),
PINMUX_DATA(VIO_D15_MARK, PORT117_FN1),
PINMUX_DATA(VIO_CLK_MARK, PORT118_FN1),
PINMUX_DATA(VIO_FIELD_MARK, PORT119_FN1),
PINMUX_DATA(VIO_CKO_MARK, PORT120_FN1),
PINMUX_DATA(LCDD0_MARK, PORT121_FN1),
PINMUX_DATA(LCDD1_MARK, PORT122_FN1),
PINMUX_DATA(LCDD2_MARK, PORT123_FN1),
PINMUX_DATA(LCDD3_MARK, PORT124_FN1),
PINMUX_DATA(LCDD4_MARK, PORT125_FN1),
PINMUX_DATA(LCDD5_MARK, PORT126_FN1),
PINMUX_DATA(LCDD6_MARK, PORT127_FN1),
PINMUX_DATA(LCDD7_MARK, PORT128_FN1),
PINMUX_DATA(LCDD8_MARK, PORT129_FN1),
PINMUX_DATA(LCDD9_MARK, PORT130_FN1),
PINMUX_DATA(LCDD10_MARK, PORT131_FN1),
PINMUX_DATA(LCDD11_MARK, PORT132_FN1),
PINMUX_DATA(LCDD12_MARK, PORT133_FN1),
PINMUX_DATA(LCDD13_MARK, PORT134_FN1),
PINMUX_DATA(LCDD14_MARK, PORT135_FN1),
PINMUX_DATA(LCDD15_MARK, PORT136_FN1),
PINMUX_DATA(LCDD16_MARK, PORT137_FN1),
PINMUX_DATA(LCDD17_MARK, PORT138_FN1),
PINMUX_DATA(LCDD18_MARK, PORT139_FN1),
PINMUX_DATA(LCDD19_MARK, PORT140_FN1),
PINMUX_DATA(LCDD20_MARK, PORT141_FN1),
PINMUX_DATA(LCDD21_MARK, PORT142_FN1),
PINMUX_DATA(LCDD22_MARK, PORT143_FN1),
PINMUX_DATA(LCDD23_MARK, PORT144_FN1),
PINMUX_DATA(LCDHSYN_MARK, PORT145_FN1),
PINMUX_DATA(LCDVSYN_MARK, PORT146_FN1),
PINMUX_DATA(LCDDCK_MARK, PORT147_FN1),
PINMUX_DATA(LCDRD_MARK, PORT148_FN1),
PINMUX_DATA(LCDDISP_MARK, PORT149_FN1),
PINMUX_DATA(LCDLCLK_MARK, PORT150_FN1),
PINMUX_DATA(LCDDON_MARK, PORT151_FN1),
PINMUX_DATA(SCIFA0_TXD_MARK, PORT152_FN1),
PINMUX_DATA(SCIFA0_RXD_MARK, PORT153_FN1),
PINMUX_DATA(SCIFA1_TXD_MARK, PORT154_FN1),
PINMUX_DATA(SCIFA1_RXD_MARK, PORT155_FN1),
PINMUX_DATA(TS_SPSYNC1_MARK, PORT156_FN1),
PINMUX_DATA(TS_SDAT1_MARK, PORT157_FN1),
PINMUX_DATA(TS_SDEN1_MARK, PORT158_FN1),
PINMUX_DATA(TS_SCK1_MARK, PORT159_FN1),
PINMUX_DATA(TPU0TO0_MARK, PORT160_FN1),
PINMUX_DATA(TPU0TO1_MARK, PORT161_FN1),
PINMUX_DATA(SCIFB_SCK_MARK, PORT162_FN1),
PINMUX_DATA(SCIFB_RTS_MARK, PORT163_FN1),
PINMUX_DATA(SCIFB_CTS_MARK, PORT164_FN1),
PINMUX_DATA(SCIFB_TXD_MARK, PORT165_FN1),
PINMUX_DATA(SCIFB_RXD_MARK, PORT166_FN1),
PINMUX_DATA(VBUS0_0_MARK, PORT167_FN1),
PINMUX_DATA(VBUS0_1_MARK, PORT168_FN1),
PINMUX_DATA(HDMI_HPD_MARK, PORT169_FN1),
PINMUX_DATA(HDMI_CEC_MARK, PORT170_FN1),
PINMUX_DATA(SDHICLK0_MARK, PORT171_FN1),
PINMUX_DATA(SDHICD0_MARK, PORT172_FN1),
PINMUX_DATA(SDHID0_0_MARK, PORT173_FN1),
PINMUX_DATA(SDHID0_1_MARK, PORT174_FN1),
PINMUX_DATA(SDHID0_2_MARK, PORT175_FN1),
PINMUX_DATA(SDHID0_3_MARK, PORT176_FN1),
PINMUX_DATA(SDHICMD0_MARK, PORT177_FN1),
PINMUX_DATA(SDHIWP0_MARK, PORT178_FN1),
PINMUX_DATA(SDHICLK1_MARK, PORT179_FN1),
PINMUX_DATA(SDHID1_0_MARK, PORT180_FN1),
PINMUX_DATA(SDHID1_1_MARK, PORT181_FN1),
PINMUX_DATA(SDHID1_2_MARK, PORT182_FN1),
PINMUX_DATA(SDHID1_3_MARK, PORT183_FN1),
PINMUX_DATA(SDHICMD1_MARK, PORT184_FN1),
PINMUX_DATA(SDHICLK2_MARK, PORT185_FN1),
PINMUX_DATA(SDHID2_0_MARK, PORT186_FN1),
PINMUX_DATA(SDHID2_1_MARK, PORT187_FN1),
PINMUX_DATA(SDHID2_2_MARK, PORT188_FN1),
PINMUX_DATA(SDHID2_3_MARK, PORT189_FN1),
PINMUX_DATA(SDHICMD2_MARK, PORT190_FN1),
/* Function 2 */
PINMUX_DATA(FSIBCK_MARK, PORT4_FN2),
PINMUX_DATA(SCIFA4_RXD_MARK, PORT5_FN2),
PINMUX_DATA(SCIFA4_TXD_MARK, PORT6_FN2),
PINMUX_DATA(SCIFA5_RXD_MARK, PORT8_FN2),
PINMUX_DATA(FSIASPDIF_11_MARK, PORT11_FN2),
PINMUX_DATA(SCIFA5_TXD_MARK, PORT12_FN2),
PINMUX_DATA(FMSIOLR_MARK, PORT13_FN2),
PINMUX_DATA(FMSIOBT_MARK, PORT14_FN2),
PINMUX_DATA(FSIASPDIF_15_MARK, PORT15_FN2),
PINMUX_DATA(FMSIILR_MARK, PORT16_FN2),
PINMUX_DATA(FMSIIBT_MARK, PORT17_FN2),
PINMUX_DATA(BS_MARK, PORT19_FN2),
PINMUX_DATA(MSIOF0_TSYNC_MARK, PORT36_FN2),
PINMUX_DATA(MSIOF0_TSCK_MARK, PORT37_FN2),
PINMUX_DATA(MSIOF0_RXD_MARK, PORT38_FN2),
PINMUX_DATA(MSIOF0_RSCK_MARK, PORT39_FN2),
PINMUX_DATA(MSIOF0_RSYNC_MARK, PORT40_FN2),
PINMUX_DATA(MSIOF0_MCK0_MARK, PORT41_FN2),
PINMUX_DATA(MSIOF0_MCK1_MARK, PORT42_FN2),
PINMUX_DATA(MSIOF0_SS1_MARK, PORT43_FN2),
PINMUX_DATA(MSIOF0_SS2_MARK, PORT44_FN2),
PINMUX_DATA(MSIOF0_TXD_MARK, PORT45_FN2),
PINMUX_DATA(FMSICK_MARK, PORT65_FN2),
PINMUX_DATA(FCE1_MARK, PORT66_FN2),
PINMUX_DATA(BBIF1_RXD_MARK, PORT76_FN2),
PINMUX_DATA(BBIF1_TSYNC_MARK, PORT77_FN2),
PINMUX_DATA(BBIF1_TSCK_MARK, PORT78_FN2),
PINMUX_DATA(BBIF1_TXD_MARK, PORT79_FN2),
PINMUX_DATA(BBIF1_RSCK_MARK, PORT80_FN2),
PINMUX_DATA(BBIF1_RSYNC_MARK, PORT81_FN2),
PINMUX_DATA(BBIF1_FLOW_MARK, PORT82_FN2),
PINMUX_DATA(BB_RX_FLOW_N_MARK, PORT83_FN2),
PINMUX_DATA(MSIOF1_RSCK_MARK, PORT84_FN2),
PINMUX_DATA(MSIOF1_RSYNC_MARK, PORT85_FN2),
PINMUX_DATA(MSIOF1_MCK0_MARK, PORT86_FN2),
PINMUX_DATA(MSIOF1_MCK1_MARK, PORT87_FN2),
PINMUX_DATA(MSIOF1_TSCK_88_MARK, PORT88_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_TSYNC_89_MARK, PORT89_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_TXD_90_MARK, PORT90_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_RXD_91_MARK, PORT91_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_SS1_92_MARK, PORT92_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_SS2_93_MARK, PORT93_FN2, MSEL4CR_10_1),
PINMUX_DATA(SCIFA2_CTS1_MARK, PORT94_FN2),
PINMUX_DATA(SCIFA2_RTS1_MARK, PORT95_FN2),
PINMUX_DATA(SCIFA2_TXD1_MARK, PORT96_FN2),
PINMUX_DATA(SCIFA2_RXD1_MARK, PORT97_FN2),
PINMUX_DATA(SCIFA2_SCK1_MARK, PORT98_FN2),
PINMUX_DATA(I2C_SCL2_MARK, PORT110_FN2),
PINMUX_DATA(I2C_SDA2_MARK, PORT111_FN2),
PINMUX_DATA(I2C_SCL3_MARK, PORT114_FN2, MSEL4CR_16_1),
PINMUX_DATA(I2C_SDA3_MARK, PORT115_FN2, MSEL4CR_16_1),
PINMUX_DATA(I2C_SCL4_MARK, PORT116_FN2, MSEL4CR_17_1),
PINMUX_DATA(I2C_SDA4_MARK, PORT117_FN2, MSEL4CR_17_1),
PINMUX_DATA(MSIOF2_RSCK_MARK, PORT134_FN2),
PINMUX_DATA(MSIOF2_RSYNC_MARK, PORT135_FN2),
PINMUX_DATA(MSIOF2_MCK0_MARK, PORT136_FN2),
PINMUX_DATA(MSIOF2_MCK1_MARK, PORT137_FN2),
PINMUX_DATA(MSIOF2_SS1_MARK, PORT138_FN2),
PINMUX_DATA(MSIOF2_SS2_MARK, PORT139_FN2),
PINMUX_DATA(SCIFA3_CTS_140_MARK, PORT140_FN2, MSEL3CR_9_1),
PINMUX_DATA(SCIFA3_RTS_141_MARK, PORT141_FN2),
PINMUX_DATA(SCIFA3_SCK_MARK, PORT142_FN2),
PINMUX_DATA(SCIFA3_TXD_MARK, PORT143_FN2),
PINMUX_DATA(SCIFA3_RXD_MARK, PORT144_FN2),
PINMUX_DATA(MSIOF2_TSYNC_MARK, PORT148_FN2),
PINMUX_DATA(MSIOF2_TSCK_MARK, PORT149_FN2),
PINMUX_DATA(MSIOF2_RXD_MARK, PORT150_FN2),
PINMUX_DATA(MSIOF2_TXD_MARK, PORT151_FN2),
PINMUX_DATA(SCIFA0_SCK_MARK, PORT156_FN2),
PINMUX_DATA(SCIFA0_RTS_MARK, PORT157_FN2),
PINMUX_DATA(SCIFA0_CTS_MARK, PORT158_FN2),
PINMUX_DATA(SCIFA1_SCK_MARK, PORT159_FN2),
PINMUX_DATA(SCIFA1_RTS_MARK, PORT160_FN2),
PINMUX_DATA(SCIFA1_CTS_MARK, PORT161_FN2),
/* Function 3 */
PINMUX_DATA(VIO_CKO1_MARK, PORT16_FN3),
PINMUX_DATA(VIO_CKO2_MARK, PORT17_FN3),
PINMUX_DATA(IDIN_1_18_MARK, PORT18_FN3, MSEL4CR_14_1),
PINMUX_DATA(MSIOF1_TSCK_39_MARK, PORT39_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_TSYNC_40_MARK, PORT40_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_TXD_41_MARK, PORT41_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_RXD_42_MARK, PORT42_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_SS1_43_MARK, PORT43_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_SS2_44_MARK, PORT44_FN3, MSEL4CR_10_0),
PINMUX_DATA(MMCD1_0_MARK, PORT54_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_1_MARK, PORT55_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_2_MARK, PORT56_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_3_MARK, PORT57_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_4_MARK, PORT58_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_5_MARK, PORT59_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_6_MARK, PORT60_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_7_MARK, PORT61_FN3, MSEL4CR_15_1),
PINMUX_DATA(VINT_I_MARK, PORT65_FN3),
PINMUX_DATA(MMCCLK1_MARK, PORT66_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCCMD1_MARK, PORT67_FN3, MSEL4CR_15_1),
PINMUX_DATA(TPU0TO2_93_MARK, PORT93_FN3),
PINMUX_DATA(TPU0TO2_99_MARK, PORT99_FN3),
PINMUX_DATA(TPU0TO3_MARK, PORT112_FN3),
PINMUX_DATA(IDIN_0_MARK, PORT113_FN3),
PINMUX_DATA(EXTLP_0_MARK, PORT114_FN3),
PINMUX_DATA(OVCN2_0_MARK, PORT115_FN3),
PINMUX_DATA(PWEN_0_MARK, PORT116_FN3),
PINMUX_DATA(OVCN_0_MARK, PORT117_FN3),
PINMUX_DATA(KEYOUT7_MARK, PORT121_FN3),
PINMUX_DATA(KEYOUT6_MARK, PORT122_FN3),
PINMUX_DATA(KEYOUT5_MARK, PORT123_FN3),
PINMUX_DATA(KEYOUT4_MARK, PORT124_FN3),
PINMUX_DATA(KEYOUT3_MARK, PORT125_FN3),
PINMUX_DATA(KEYOUT2_MARK, PORT126_FN3),
PINMUX_DATA(KEYOUT1_MARK, PORT127_FN3),
PINMUX_DATA(KEYOUT0_MARK, PORT128_FN3),
PINMUX_DATA(KEYIN7_MARK, PORT129_FN3),
PINMUX_DATA(KEYIN6_MARK, PORT130_FN3),
PINMUX_DATA(KEYIN5_MARK, PORT131_FN3),
PINMUX_DATA(KEYIN4_MARK, PORT132_FN3),
PINMUX_DATA(KEYIN3_133_MARK, PORT133_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN2_134_MARK, PORT134_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN1_135_MARK, PORT135_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN0_136_MARK, PORT136_FN3, MSEL4CR_18_0),
PINMUX_DATA(TS_SPSYNC2_MARK, PORT137_FN3),
PINMUX_DATA(IROUT_139_MARK, PORT139_FN3),
PINMUX_DATA(IRDA_OUT_MARK, PORT140_FN3),
PINMUX_DATA(IRDA_IN_MARK, PORT141_FN3),
PINMUX_DATA(IRDA_FIRSEL_MARK, PORT142_FN3),
PINMUX_DATA(TS_SDAT2_MARK, PORT145_FN3),
PINMUX_DATA(TS_SDEN2_MARK, PORT146_FN3),
PINMUX_DATA(TS_SCK2_MARK, PORT147_FN3),
/* Function 4 */
PINMUX_DATA(SCIFA3_CTS_43_MARK, PORT43_FN4, MSEL3CR_9_0),
PINMUX_DATA(SCIFA3_RTS_44_MARK, PORT44_FN4),
PINMUX_DATA(GP_RX_FLAG_MARK, PORT76_FN4),
PINMUX_DATA(GP_RX_DATA_MARK, PORT77_FN4),
PINMUX_DATA(GP_TX_READY_MARK, PORT78_FN4),
PINMUX_DATA(GP_RX_WAKE_MARK, PORT79_FN4),
PINMUX_DATA(MP_TX_FLAG_MARK, PORT80_FN4),
PINMUX_DATA(MP_TX_DATA_MARK, PORT81_FN4),
PINMUX_DATA(MP_RX_READY_MARK, PORT82_FN4),
PINMUX_DATA(MP_TX_WAKE_MARK, PORT83_FN4),
PINMUX_DATA(MMCD0_0_MARK, PORT84_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_1_MARK, PORT85_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_2_MARK, PORT86_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_3_MARK, PORT87_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_4_MARK, PORT88_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_5_MARK, PORT89_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_6_MARK, PORT90_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_7_MARK, PORT91_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCCMD0_MARK, PORT92_FN4, MSEL4CR_15_0),
PINMUX_DATA(SIM_RST_MARK, PORT94_FN4),
PINMUX_DATA(SIM_CLK_MARK, PORT95_FN4),
PINMUX_DATA(SIM_D_MARK, PORT98_FN4),
PINMUX_DATA(MMCCLK0_MARK, PORT99_FN4, MSEL4CR_15_0),
PINMUX_DATA(IDIN_1_113_MARK, PORT113_FN4, MSEL4CR_14_0),
PINMUX_DATA(OVCN_1_114_MARK, PORT114_FN4, MSEL4CR_14_0),
PINMUX_DATA(PWEN_1_115_MARK, PORT115_FN4),
PINMUX_DATA(EXTLP_1_MARK, PORT116_FN4),
PINMUX_DATA(OVCN2_1_MARK, PORT117_FN4),
PINMUX_DATA(KEYIN0_121_MARK, PORT121_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN1_122_MARK, PORT122_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN2_123_MARK, PORT123_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN3_124_MARK, PORT124_FN4, MSEL4CR_18_1),
PINMUX_DATA(PWEN_1_138_MARK, PORT138_FN4),
PINMUX_DATA(IROUT_140_MARK, PORT140_FN4),
PINMUX_DATA(LCDCS_MARK, PORT145_FN4),
PINMUX_DATA(LCDWR_MARK, PORT147_FN4),
PINMUX_DATA(LCDRS_MARK, PORT149_FN4),
PINMUX_DATA(OVCN_1_162_MARK, PORT162_FN4, MSEL4CR_14_1),
/* Function 5 */
PINMUX_DATA(GPI0_MARK, PORT41_FN5),
PINMUX_DATA(GPI1_MARK, PORT42_FN5),
PINMUX_DATA(GPO0_MARK, PORT43_FN5),
PINMUX_DATA(GPO1_MARK, PORT44_FN5),
PINMUX_DATA(I2C_SCL3S_MARK, PORT137_FN5, MSEL4CR_16_0),
PINMUX_DATA(I2C_SDA3S_MARK, PORT145_FN5, MSEL4CR_16_0),
PINMUX_DATA(I2C_SCL4S_MARK, PORT146_FN5, MSEL4CR_17_0),
PINMUX_DATA(I2C_SDA4S_MARK, PORT147_FN5, MSEL4CR_17_0),
/* Function select */
PINMUX_DATA(LCDC0_SELECT_MARK, MSEL3CR_6_0),
PINMUX_DATA(LCDC1_SELECT_MARK, MSEL3CR_6_1),
PINMUX_DATA(TS0_1SELECT_MARK, MSEL3CR_21_0, MSEL3CR_20_0),
PINMUX_DATA(TS0_2SELECT_MARK, MSEL3CR_21_0, MSEL3CR_20_1),
PINMUX_DATA(TS1_1SELECT_MARK, MSEL3CR_27_0, MSEL3CR_26_0),
PINMUX_DATA(TS1_2SELECT_MARK, MSEL3CR_27_0, MSEL3CR_26_1),
PINMUX_DATA(SDENC_CPG_MARK, MSEL4CR_19_0),
PINMUX_DATA(SDENC_DV_CLKI_MARK, MSEL4CR_19_1),
PINMUX_DATA(MFIv6_MARK, MSEL4CR_6_0),
PINMUX_DATA(MFIv4_MARK, MSEL4CR_6_1),
};
static struct pinmux_gpio pinmux_gpios[] = {
/* PORT */
GPIO_PORT_ALL(),
/* IRQ */
GPIO_FN(IRQ0_6), GPIO_FN(IRQ0_162), GPIO_FN(IRQ1),
GPIO_FN(IRQ2_4), GPIO_FN(IRQ2_5), GPIO_FN(IRQ3_8),
GPIO_FN(IRQ3_16), GPIO_FN(IRQ4_17), GPIO_FN(IRQ4_163),
GPIO_FN(IRQ5), GPIO_FN(IRQ6_39), GPIO_FN(IRQ6_164),
GPIO_FN(IRQ7_40), GPIO_FN(IRQ7_167), GPIO_FN(IRQ8_41),
GPIO_FN(IRQ8_168), GPIO_FN(IRQ9_42), GPIO_FN(IRQ9_169),
GPIO_FN(IRQ10), GPIO_FN(IRQ11), GPIO_FN(IRQ12_80),
GPIO_FN(IRQ12_137), GPIO_FN(IRQ13_81), GPIO_FN(IRQ13_145),
GPIO_FN(IRQ14_82), GPIO_FN(IRQ14_146), GPIO_FN(IRQ15_83),
GPIO_FN(IRQ15_147), GPIO_FN(IRQ16_84), GPIO_FN(IRQ16_170),
GPIO_FN(IRQ17), GPIO_FN(IRQ18), GPIO_FN(IRQ19),
GPIO_FN(IRQ20), GPIO_FN(IRQ21), GPIO_FN(IRQ22),
GPIO_FN(IRQ23), GPIO_FN(IRQ24), GPIO_FN(IRQ25),
GPIO_FN(IRQ26_121), GPIO_FN(IRQ26_172), GPIO_FN(IRQ27_122),
GPIO_FN(IRQ27_180), GPIO_FN(IRQ28_123), GPIO_FN(IRQ28_181),
GPIO_FN(IRQ29_129), GPIO_FN(IRQ29_182), GPIO_FN(IRQ30_130),
GPIO_FN(IRQ30_183), GPIO_FN(IRQ31_138), GPIO_FN(IRQ31_184),
/* MSIOF0 */
GPIO_FN(MSIOF0_TSYNC), GPIO_FN(MSIOF0_TSCK), GPIO_FN(MSIOF0_RXD),
GPIO_FN(MSIOF0_RSCK), GPIO_FN(MSIOF0_RSYNC), GPIO_FN(MSIOF0_MCK0),
GPIO_FN(MSIOF0_MCK1), GPIO_FN(MSIOF0_SS1), GPIO_FN(MSIOF0_SS2),
GPIO_FN(MSIOF0_TXD),
/* MSIOF1 */
GPIO_FN(MSIOF1_TSCK_39), GPIO_FN(MSIOF1_TSCK_88),
GPIO_FN(MSIOF1_TSYNC_40), GPIO_FN(MSIOF1_TSYNC_89),
GPIO_FN(MSIOF1_TXD_41), GPIO_FN(MSIOF1_TXD_90),
GPIO_FN(MSIOF1_RXD_42), GPIO_FN(MSIOF1_RXD_91),
GPIO_FN(MSIOF1_SS1_43), GPIO_FN(MSIOF1_SS1_92),
GPIO_FN(MSIOF1_SS2_44), GPIO_FN(MSIOF1_SS2_93),
GPIO_FN(MSIOF1_RSCK), GPIO_FN(MSIOF1_RSYNC),
GPIO_FN(MSIOF1_MCK0), GPIO_FN(MSIOF1_MCK1),
/* MSIOF2 */
GPIO_FN(MSIOF2_RSCK), GPIO_FN(MSIOF2_RSYNC), GPIO_FN(MSIOF2_MCK0),
GPIO_FN(MSIOF2_MCK1), GPIO_FN(MSIOF2_SS1), GPIO_FN(MSIOF2_SS2),
GPIO_FN(MSIOF2_TSYNC), GPIO_FN(MSIOF2_TSCK), GPIO_FN(MSIOF2_RXD),
GPIO_FN(MSIOF2_TXD),
/* BBIF1 */
GPIO_FN(BBIF1_RXD), GPIO_FN(BBIF1_TSYNC), GPIO_FN(BBIF1_TSCK),
GPIO_FN(BBIF1_TXD), GPIO_FN(BBIF1_RSCK), GPIO_FN(BBIF1_RSYNC),
GPIO_FN(BBIF1_FLOW), GPIO_FN(BB_RX_FLOW_N),
/* BBIF2 */
GPIO_FN(BBIF2_TSCK1), GPIO_FN(BBIF2_TSYNC1),
GPIO_FN(BBIF2_TXD1), GPIO_FN(BBIF2_RXD),
/* FSI */
GPIO_FN(FSIACK), GPIO_FN(FSIBCK), GPIO_FN(FSIAILR),
GPIO_FN(FSIAIBT), GPIO_FN(FSIAISLD), GPIO_FN(FSIAOMC),
GPIO_FN(FSIAOLR), GPIO_FN(FSIAOBT), GPIO_FN(FSIAOSLD),
GPIO_FN(FSIASPDIF_11), GPIO_FN(FSIASPDIF_15),
/* FMSI */
GPIO_FN(FMSOCK), GPIO_FN(FMSOOLR), GPIO_FN(FMSIOLR),
GPIO_FN(FMSOOBT), GPIO_FN(FMSIOBT), GPIO_FN(FMSOSLD),
GPIO_FN(FMSOILR), GPIO_FN(FMSIILR), GPIO_FN(FMSOIBT),
GPIO_FN(FMSIIBT), GPIO_FN(FMSISLD), GPIO_FN(FMSICK),
/* SCIFA0 */
GPIO_FN(SCIFA0_TXD), GPIO_FN(SCIFA0_RXD), GPIO_FN(SCIFA0_SCK),
GPIO_FN(SCIFA0_RTS), GPIO_FN(SCIFA0_CTS),
/* SCIFA1 */
GPIO_FN(SCIFA1_TXD), GPIO_FN(SCIFA1_RXD), GPIO_FN(SCIFA1_SCK),
GPIO_FN(SCIFA1_RTS), GPIO_FN(SCIFA1_CTS),
/* SCIFA2 */
GPIO_FN(SCIFA2_CTS1), GPIO_FN(SCIFA2_RTS1), GPIO_FN(SCIFA2_TXD1),
GPIO_FN(SCIFA2_RXD1), GPIO_FN(SCIFA2_SCK1),
/* SCIFA3 */
GPIO_FN(SCIFA3_CTS_43), GPIO_FN(SCIFA3_CTS_140),
GPIO_FN(SCIFA3_RTS_44), GPIO_FN(SCIFA3_RTS_141),
GPIO_FN(SCIFA3_SCK), GPIO_FN(SCIFA3_TXD),
GPIO_FN(SCIFA3_RXD),
/* SCIFA4 */
GPIO_FN(SCIFA4_RXD), GPIO_FN(SCIFA4_TXD),
/* SCIFA5 */
GPIO_FN(SCIFA5_RXD), GPIO_FN(SCIFA5_TXD),
/* SCIFB */
GPIO_FN(SCIFB_SCK), GPIO_FN(SCIFB_RTS), GPIO_FN(SCIFB_CTS),
GPIO_FN(SCIFB_TXD), GPIO_FN(SCIFB_RXD),
/* CEU */
GPIO_FN(VIO_HD), GPIO_FN(VIO_CKO1), GPIO_FN(VIO_CKO2),
GPIO_FN(VIO_VD), GPIO_FN(VIO_CLK), GPIO_FN(VIO_FIELD),
GPIO_FN(VIO_CKO), GPIO_FN(VIO_D0), GPIO_FN(VIO_D1),
GPIO_FN(VIO_D2), GPIO_FN(VIO_D3), GPIO_FN(VIO_D4),
GPIO_FN(VIO_D5), GPIO_FN(VIO_D6), GPIO_FN(VIO_D7),
GPIO_FN(VIO_D8), GPIO_FN(VIO_D9), GPIO_FN(VIO_D10),
GPIO_FN(VIO_D11), GPIO_FN(VIO_D12), GPIO_FN(VIO_D13),
GPIO_FN(VIO_D14), GPIO_FN(VIO_D15),
/* USB0 */
GPIO_FN(IDIN_0), GPIO_FN(EXTLP_0), GPIO_FN(OVCN2_0),
GPIO_FN(PWEN_0), GPIO_FN(OVCN_0), GPIO_FN(VBUS0_0),
/* USB1 */
GPIO_FN(IDIN_1_18), GPIO_FN(IDIN_1_113),
GPIO_FN(OVCN_1_114), GPIO_FN(OVCN_1_162),
GPIO_FN(PWEN_1_115), GPIO_FN(PWEN_1_138),
GPIO_FN(EXTLP_1), GPIO_FN(OVCN2_1),
GPIO_FN(VBUS0_1),
/* GPIO */
GPIO_FN(GPI0), GPIO_FN(GPI1), GPIO_FN(GPO0), GPIO_FN(GPO1),
/* BSC */
GPIO_FN(BS), GPIO_FN(WE1), GPIO_FN(CKO),
GPIO_FN(WAIT), GPIO_FN(RDWR),
GPIO_FN(A0), GPIO_FN(A1), GPIO_FN(A2),
GPIO_FN(A3), GPIO_FN(A6), GPIO_FN(A7),
GPIO_FN(A8), GPIO_FN(A9), GPIO_FN(A10),
GPIO_FN(A11), GPIO_FN(A12), GPIO_FN(A13),
GPIO_FN(A14), GPIO_FN(A15), GPIO_FN(A16),
GPIO_FN(A17), GPIO_FN(A18), GPIO_FN(A19),
GPIO_FN(A20), GPIO_FN(A21), GPIO_FN(A22),
GPIO_FN(A23), GPIO_FN(A24), GPIO_FN(A25),
GPIO_FN(A26),
GPIO_FN(CS0), GPIO_FN(CS2), GPIO_FN(CS4),
GPIO_FN(CS5A), GPIO_FN(CS5B), GPIO_FN(CS6A),
/* BSC/FLCTL */
GPIO_FN(RD_FSC), GPIO_FN(WE0_FWE), GPIO_FN(A4_FOE),
GPIO_FN(A5_FCDE), GPIO_FN(D0_NAF0), GPIO_FN(D1_NAF1),
GPIO_FN(D2_NAF2), GPIO_FN(D3_NAF3), GPIO_FN(D4_NAF4),
GPIO_FN(D5_NAF5), GPIO_FN(D6_NAF6), GPIO_FN(D7_NAF7),
GPIO_FN(D8_NAF8), GPIO_FN(D9_NAF9), GPIO_FN(D10_NAF10),
GPIO_FN(D11_NAF11), GPIO_FN(D12_NAF12), GPIO_FN(D13_NAF13),
GPIO_FN(D14_NAF14), GPIO_FN(D15_NAF15),
/* MMCIF(1) */
GPIO_FN(MMCD0_0), GPIO_FN(MMCD0_1), GPIO_FN(MMCD0_2),
GPIO_FN(MMCD0_3), GPIO_FN(MMCD0_4), GPIO_FN(MMCD0_5),
GPIO_FN(MMCD0_6), GPIO_FN(MMCD0_7), GPIO_FN(MMCCMD0),
GPIO_FN(MMCCLK0),
/* MMCIF(2) */
GPIO_FN(MMCD1_0), GPIO_FN(MMCD1_1), GPIO_FN(MMCD1_2),
GPIO_FN(MMCD1_3), GPIO_FN(MMCD1_4), GPIO_FN(MMCD1_5),
GPIO_FN(MMCD1_6), GPIO_FN(MMCD1_7), GPIO_FN(MMCCLK1),
GPIO_FN(MMCCMD1),
/* SPU2 */
GPIO_FN(VINT_I),
/* FLCTL */
GPIO_FN(FCE1), GPIO_FN(FCE0), GPIO_FN(FRB),
/* HSI */
GPIO_FN(GP_RX_FLAG), GPIO_FN(GP_RX_DATA), GPIO_FN(GP_TX_READY),
GPIO_FN(GP_RX_WAKE), GPIO_FN(MP_TX_FLAG), GPIO_FN(MP_TX_DATA),
GPIO_FN(MP_RX_READY), GPIO_FN(MP_TX_WAKE),
/* MFI */
GPIO_FN(MFIv6),
GPIO_FN(MFIv4),
GPIO_FN(MEMC_BUSCLK_MEMC_A0), GPIO_FN(MEMC_ADV_MEMC_DREQ0),
GPIO_FN(MEMC_WAIT_MEMC_DREQ1), GPIO_FN(MEMC_CS1_MEMC_A1),
GPIO_FN(MEMC_CS0), GPIO_FN(MEMC_NOE),
GPIO_FN(MEMC_NWE), GPIO_FN(MEMC_INT),
GPIO_FN(MEMC_AD0), GPIO_FN(MEMC_AD1), GPIO_FN(MEMC_AD2),
GPIO_FN(MEMC_AD3), GPIO_FN(MEMC_AD4), GPIO_FN(MEMC_AD5),
GPIO_FN(MEMC_AD6), GPIO_FN(MEMC_AD7), GPIO_FN(MEMC_AD8),
GPIO_FN(MEMC_AD9), GPIO_FN(MEMC_AD10), GPIO_FN(MEMC_AD11),
GPIO_FN(MEMC_AD12), GPIO_FN(MEMC_AD13), GPIO_FN(MEMC_AD14),
GPIO_FN(MEMC_AD15),
/* SIM */
GPIO_FN(SIM_RST), GPIO_FN(SIM_CLK), GPIO_FN(SIM_D),
/* TPU */
GPIO_FN(TPU0TO0), GPIO_FN(TPU0TO1), GPIO_FN(TPU0TO2_93),
GPIO_FN(TPU0TO2_99), GPIO_FN(TPU0TO3),
/* I2C2 */
GPIO_FN(I2C_SCL2), GPIO_FN(I2C_SDA2),
/* I2C3(1) */
GPIO_FN(I2C_SCL3), GPIO_FN(I2C_SDA3),
/* I2C3(2) */
GPIO_FN(I2C_SCL3S), GPIO_FN(I2C_SDA3S),
/* I2C4(2) */
GPIO_FN(I2C_SCL4), GPIO_FN(I2C_SDA4),
/* I2C4(2) */
GPIO_FN(I2C_SCL4S), GPIO_FN(I2C_SDA4S),
/* KEYSC */
GPIO_FN(KEYOUT0), GPIO_FN(KEYIN0_121), GPIO_FN(KEYIN0_136),
GPIO_FN(KEYOUT1), GPIO_FN(KEYIN1_122), GPIO_FN(KEYIN1_135),
GPIO_FN(KEYOUT2), GPIO_FN(KEYIN2_123), GPIO_FN(KEYIN2_134),
GPIO_FN(KEYOUT3), GPIO_FN(KEYIN3_124), GPIO_FN(KEYIN3_133),
GPIO_FN(KEYOUT4), GPIO_FN(KEYIN4), GPIO_FN(KEYOUT5),
GPIO_FN(KEYIN5), GPIO_FN(KEYOUT6), GPIO_FN(KEYIN6),
GPIO_FN(KEYOUT7), GPIO_FN(KEYIN7),
/* LCDC */
GPIO_FN(LCDHSYN), GPIO_FN(LCDCS), GPIO_FN(LCDVSYN),
GPIO_FN(LCDDCK), GPIO_FN(LCDWR), GPIO_FN(LCDRD),
GPIO_FN(LCDDISP), GPIO_FN(LCDRS), GPIO_FN(LCDLCLK),
GPIO_FN(LCDDON),
GPIO_FN(LCDD0), GPIO_FN(LCDD1), GPIO_FN(LCDD2),
GPIO_FN(LCDD3), GPIO_FN(LCDD4), GPIO_FN(LCDD5),
GPIO_FN(LCDD6), GPIO_FN(LCDD7), GPIO_FN(LCDD8),
GPIO_FN(LCDD9), GPIO_FN(LCDD10), GPIO_FN(LCDD11),
GPIO_FN(LCDD12), GPIO_FN(LCDD13), GPIO_FN(LCDD14),
GPIO_FN(LCDD15), GPIO_FN(LCDD16), GPIO_FN(LCDD17),
GPIO_FN(LCDD18), GPIO_FN(LCDD19), GPIO_FN(LCDD20),
GPIO_FN(LCDD21), GPIO_FN(LCDD22), GPIO_FN(LCDD23),
GPIO_FN(LCDC0_SELECT),
GPIO_FN(LCDC1_SELECT),
/* IRDA */
GPIO_FN(IRDA_OUT), GPIO_FN(IRDA_IN), GPIO_FN(IRDA_FIRSEL),
GPIO_FN(IROUT_139), GPIO_FN(IROUT_140),
/* TSIF1 */
GPIO_FN(TS0_1SELECT),
GPIO_FN(TS0_2SELECT),
GPIO_FN(TS1_1SELECT),
GPIO_FN(TS1_2SELECT),
GPIO_FN(TS_SPSYNC1), GPIO_FN(TS_SDAT1),
GPIO_FN(TS_SDEN1), GPIO_FN(TS_SCK1),
/* TSIF2 */
GPIO_FN(TS_SPSYNC2), GPIO_FN(TS_SDAT2),
GPIO_FN(TS_SDEN2), GPIO_FN(TS_SCK2),
/* HDMI */
GPIO_FN(HDMI_HPD), GPIO_FN(HDMI_CEC),
/* SDHI0 */
GPIO_FN(SDHICLK0), GPIO_FN(SDHICD0), GPIO_FN(SDHICMD0),
GPIO_FN(SDHIWP0), GPIO_FN(SDHID0_0), GPIO_FN(SDHID0_1),
GPIO_FN(SDHID0_2), GPIO_FN(SDHID0_3),
/* SDHI1 */
GPIO_FN(SDHICLK1), GPIO_FN(SDHICMD1), GPIO_FN(SDHID1_0),
GPIO_FN(SDHID1_1), GPIO_FN(SDHID1_2), GPIO_FN(SDHID1_3),
/* SDHI2 */
GPIO_FN(SDHICLK2), GPIO_FN(SDHICMD2), GPIO_FN(SDHID2_0),
GPIO_FN(SDHID2_1), GPIO_FN(SDHID2_2), GPIO_FN(SDHID2_3),
/* SDENC */
GPIO_FN(SDENC_CPG),
GPIO_FN(SDENC_DV_CLKI),
};
static struct pinmux_cfg_reg pinmux_config_regs[] = {
PORTCR(0, 0xE6051000), /* PORT0CR */
PORTCR(1, 0xE6051001), /* PORT1CR */
PORTCR(2, 0xE6051002), /* PORT2CR */
PORTCR(3, 0xE6051003), /* PORT3CR */
PORTCR(4, 0xE6051004), /* PORT4CR */
PORTCR(5, 0xE6051005), /* PORT5CR */
PORTCR(6, 0xE6051006), /* PORT6CR */
PORTCR(7, 0xE6051007), /* PORT7CR */
PORTCR(8, 0xE6051008), /* PORT8CR */
PORTCR(9, 0xE6051009), /* PORT9CR */
PORTCR(10, 0xE605100A), /* PORT10CR */
PORTCR(11, 0xE605100B), /* PORT11CR */
PORTCR(12, 0xE605100C), /* PORT12CR */
PORTCR(13, 0xE605100D), /* PORT13CR */
PORTCR(14, 0xE605100E), /* PORT14CR */
PORTCR(15, 0xE605100F), /* PORT15CR */
PORTCR(16, 0xE6051010), /* PORT16CR */
PORTCR(17, 0xE6051011), /* PORT17CR */
PORTCR(18, 0xE6051012), /* PORT18CR */
PORTCR(19, 0xE6051013), /* PORT19CR */
PORTCR(20, 0xE6051014), /* PORT20CR */
PORTCR(21, 0xE6051015), /* PORT21CR */
PORTCR(22, 0xE6051016), /* PORT22CR */
PORTCR(23, 0xE6051017), /* PORT23CR */
PORTCR(24, 0xE6051018), /* PORT24CR */
PORTCR(25, 0xE6051019), /* PORT25CR */
PORTCR(26, 0xE605101A), /* PORT26CR */
PORTCR(27, 0xE605101B), /* PORT27CR */
PORTCR(28, 0xE605101C), /* PORT28CR */
PORTCR(29, 0xE605101D), /* PORT29CR */
PORTCR(30, 0xE605101E), /* PORT30CR */
PORTCR(31, 0xE605101F), /* PORT31CR */
PORTCR(32, 0xE6051020), /* PORT32CR */
PORTCR(33, 0xE6051021), /* PORT33CR */
PORTCR(34, 0xE6051022), /* PORT34CR */
PORTCR(35, 0xE6051023), /* PORT35CR */
PORTCR(36, 0xE6051024), /* PORT36CR */
PORTCR(37, 0xE6051025), /* PORT37CR */
PORTCR(38, 0xE6051026), /* PORT38CR */
PORTCR(39, 0xE6051027), /* PORT39CR */
PORTCR(40, 0xE6051028), /* PORT40CR */
PORTCR(41, 0xE6051029), /* PORT41CR */
PORTCR(42, 0xE605102A), /* PORT42CR */
PORTCR(43, 0xE605102B), /* PORT43CR */
PORTCR(44, 0xE605102C), /* PORT44CR */
PORTCR(45, 0xE605102D), /* PORT45CR */
PORTCR(46, 0xE605202E), /* PORT46CR */
PORTCR(47, 0xE605202F), /* PORT47CR */
PORTCR(48, 0xE6052030), /* PORT48CR */
PORTCR(49, 0xE6052031), /* PORT49CR */
PORTCR(50, 0xE6052032), /* PORT50CR */
PORTCR(51, 0xE6052033), /* PORT51CR */
PORTCR(52, 0xE6052034), /* PORT52CR */
PORTCR(53, 0xE6052035), /* PORT53CR */
PORTCR(54, 0xE6052036), /* PORT54CR */
PORTCR(55, 0xE6052037), /* PORT55CR */
PORTCR(56, 0xE6052038), /* PORT56CR */
PORTCR(57, 0xE6052039), /* PORT57CR */
PORTCR(58, 0xE605203A), /* PORT58CR */
PORTCR(59, 0xE605203B), /* PORT59CR */
PORTCR(60, 0xE605203C), /* PORT60CR */
PORTCR(61, 0xE605203D), /* PORT61CR */
PORTCR(62, 0xE605203E), /* PORT62CR */
PORTCR(63, 0xE605203F), /* PORT63CR */
PORTCR(64, 0xE6052040), /* PORT64CR */
PORTCR(65, 0xE6052041), /* PORT65CR */
PORTCR(66, 0xE6052042), /* PORT66CR */
PORTCR(67, 0xE6052043), /* PORT67CR */
PORTCR(68, 0xE6052044), /* PORT68CR */
PORTCR(69, 0xE6052045), /* PORT69CR */
PORTCR(70, 0xE6052046), /* PORT70CR */
PORTCR(71, 0xE6052047), /* PORT71CR */
PORTCR(72, 0xE6052048), /* PORT72CR */
PORTCR(73, 0xE6052049), /* PORT73CR */
PORTCR(74, 0xE605204A), /* PORT74CR */
PORTCR(75, 0xE605204B), /* PORT75CR */
PORTCR(76, 0xE605004C), /* PORT76CR */
PORTCR(77, 0xE605004D), /* PORT77CR */
PORTCR(78, 0xE605004E), /* PORT78CR */
PORTCR(79, 0xE605004F), /* PORT79CR */
PORTCR(80, 0xE6050050), /* PORT80CR */
PORTCR(81, 0xE6050051), /* PORT81CR */
PORTCR(82, 0xE6050052), /* PORT82CR */
PORTCR(83, 0xE6050053), /* PORT83CR */
PORTCR(84, 0xE6050054), /* PORT84CR */
PORTCR(85, 0xE6050055), /* PORT85CR */
PORTCR(86, 0xE6050056), /* PORT86CR */
PORTCR(87, 0xE6050057), /* PORT87CR */
PORTCR(88, 0xE6050058), /* PORT88CR */
PORTCR(89, 0xE6050059), /* PORT89CR */
PORTCR(90, 0xE605005A), /* PORT90CR */
PORTCR(91, 0xE605005B), /* PORT91CR */
PORTCR(92, 0xE605005C), /* PORT92CR */
PORTCR(93, 0xE605005D), /* PORT93CR */
PORTCR(94, 0xE605005E), /* PORT94CR */
PORTCR(95, 0xE605005F), /* PORT95CR */
PORTCR(96, 0xE6050060), /* PORT96CR */
PORTCR(97, 0xE6050061), /* PORT97CR */
PORTCR(98, 0xE6050062), /* PORT98CR */
PORTCR(99, 0xE6050063), /* PORT99CR */
PORTCR(100, 0xE6053064), /* PORT100CR */
PORTCR(101, 0xE6053065), /* PORT101CR */
PORTCR(102, 0xE6053066), /* PORT102CR */
PORTCR(103, 0xE6053067), /* PORT103CR */
PORTCR(104, 0xE6053068), /* PORT104CR */
PORTCR(105, 0xE6053069), /* PORT105CR */
PORTCR(106, 0xE605306A), /* PORT106CR */
PORTCR(107, 0xE605306B), /* PORT107CR */
PORTCR(108, 0xE605306C), /* PORT108CR */
PORTCR(109, 0xE605306D), /* PORT109CR */
PORTCR(110, 0xE605306E), /* PORT110CR */
PORTCR(111, 0xE605306F), /* PORT111CR */
PORTCR(112, 0xE6053070), /* PORT112CR */
PORTCR(113, 0xE6053071), /* PORT113CR */
PORTCR(114, 0xE6053072), /* PORT114CR */
PORTCR(115, 0xE6053073), /* PORT115CR */
PORTCR(116, 0xE6053074), /* PORT116CR */
PORTCR(117, 0xE6053075), /* PORT117CR */
PORTCR(118, 0xE6053076), /* PORT118CR */
PORTCR(119, 0xE6053077), /* PORT119CR */
PORTCR(120, 0xE6053078), /* PORT120CR */
PORTCR(121, 0xE6050079), /* PORT121CR */
PORTCR(122, 0xE605007A), /* PORT122CR */
PORTCR(123, 0xE605007B), /* PORT123CR */
PORTCR(124, 0xE605007C), /* PORT124CR */
PORTCR(125, 0xE605007D), /* PORT125CR */
PORTCR(126, 0xE605007E), /* PORT126CR */
PORTCR(127, 0xE605007F), /* PORT127CR */
PORTCR(128, 0xE6050080), /* PORT128CR */
PORTCR(129, 0xE6050081), /* PORT129CR */
PORTCR(130, 0xE6050082), /* PORT130CR */
PORTCR(131, 0xE6050083), /* PORT131CR */
PORTCR(132, 0xE6050084), /* PORT132CR */
PORTCR(133, 0xE6050085), /* PORT133CR */
PORTCR(134, 0xE6050086), /* PORT134CR */
PORTCR(135, 0xE6050087), /* PORT135CR */
PORTCR(136, 0xE6050088), /* PORT136CR */
PORTCR(137, 0xE6050089), /* PORT137CR */
PORTCR(138, 0xE605008A), /* PORT138CR */
PORTCR(139, 0xE605008B), /* PORT139CR */
PORTCR(140, 0xE605008C), /* PORT140CR */
PORTCR(141, 0xE605008D), /* PORT141CR */
PORTCR(142, 0xE605008E), /* PORT142CR */
PORTCR(143, 0xE605008F), /* PORT143CR */
PORTCR(144, 0xE6050090), /* PORT144CR */
PORTCR(145, 0xE6050091), /* PORT145CR */
PORTCR(146, 0xE6050092), /* PORT146CR */
PORTCR(147, 0xE6050093), /* PORT147CR */
PORTCR(148, 0xE6050094), /* PORT148CR */
PORTCR(149, 0xE6050095), /* PORT149CR */
PORTCR(150, 0xE6050096), /* PORT150CR */
PORTCR(151, 0xE6050097), /* PORT151CR */
PORTCR(152, 0xE6053098), /* PORT152CR */
PORTCR(153, 0xE6053099), /* PORT153CR */
PORTCR(154, 0xE605309A), /* PORT154CR */
PORTCR(155, 0xE605309B), /* PORT155CR */
PORTCR(156, 0xE605009C), /* PORT156CR */
PORTCR(157, 0xE605009D), /* PORT157CR */
PORTCR(158, 0xE605009E), /* PORT158CR */
PORTCR(159, 0xE605009F), /* PORT159CR */
PORTCR(160, 0xE60500A0), /* PORT160CR */
PORTCR(161, 0xE60500A1), /* PORT161CR */
PORTCR(162, 0xE60500A2), /* PORT162CR */
PORTCR(163, 0xE60500A3), /* PORT163CR */
PORTCR(164, 0xE60500A4), /* PORT164CR */
PORTCR(165, 0xE60500A5), /* PORT165CR */
PORTCR(166, 0xE60500A6), /* PORT166CR */
PORTCR(167, 0xE60520A7), /* PORT167CR */
PORTCR(168, 0xE60520A8), /* PORT168CR */
PORTCR(169, 0xE60520A9), /* PORT169CR */
PORTCR(170, 0xE60520AA), /* PORT170CR */
PORTCR(171, 0xE60520AB), /* PORT171CR */
PORTCR(172, 0xE60520AC), /* PORT172CR */
PORTCR(173, 0xE60520AD), /* PORT173CR */
PORTCR(174, 0xE60520AE), /* PORT174CR */
PORTCR(175, 0xE60520AF), /* PORT175CR */
PORTCR(176, 0xE60520B0), /* PORT176CR */
PORTCR(177, 0xE60520B1), /* PORT177CR */
PORTCR(178, 0xE60520B2), /* PORT178CR */
PORTCR(179, 0xE60520B3), /* PORT179CR */
PORTCR(180, 0xE60520B4), /* PORT180CR */
PORTCR(181, 0xE60520B5), /* PORT181CR */
PORTCR(182, 0xE60520B6), /* PORT182CR */
PORTCR(183, 0xE60520B7), /* PORT183CR */
PORTCR(184, 0xE60520B8), /* PORT184CR */
PORTCR(185, 0xE60520B9), /* PORT185CR */
PORTCR(186, 0xE60520BA), /* PORT186CR */
PORTCR(187, 0xE60520BB), /* PORT187CR */
PORTCR(188, 0xE60520BC), /* PORT188CR */
PORTCR(189, 0xE60520BD), /* PORT189CR */
PORTCR(190, 0xE60520BE), /* PORT190CR */
{ PINMUX_CFG_REG("MSEL1CR", 0xE605800C, 32, 1) {
MSEL1CR_31_0, MSEL1CR_31_1,
MSEL1CR_30_0, MSEL1CR_30_1,
MSEL1CR_29_0, MSEL1CR_29_1,
MSEL1CR_28_0, MSEL1CR_28_1,
MSEL1CR_27_0, MSEL1CR_27_1,
MSEL1CR_26_0, MSEL1CR_26_1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
MSEL1CR_16_0, MSEL1CR_16_1,
MSEL1CR_15_0, MSEL1CR_15_1,
MSEL1CR_14_0, MSEL1CR_14_1,
MSEL1CR_13_0, MSEL1CR_13_1,
MSEL1CR_12_0, MSEL1CR_12_1,
0, 0, 0, 0,
MSEL1CR_9_0, MSEL1CR_9_1,
MSEL1CR_8_0, MSEL1CR_8_1,
MSEL1CR_7_0, MSEL1CR_7_1,
MSEL1CR_6_0, MSEL1CR_6_1,
0, 0,
MSEL1CR_4_0, MSEL1CR_4_1,
MSEL1CR_3_0, MSEL1CR_3_1,
MSEL1CR_2_0, MSEL1CR_2_1,
0, 0,
MSEL1CR_0_0, MSEL1CR_0_1,
}
},
{ PINMUX_CFG_REG("MSEL3CR", 0xE6058020, 32, 1) {
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_27_0, MSEL3CR_27_1,
MSEL3CR_26_0, MSEL3CR_26_1,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_21_0, MSEL3CR_21_1,
MSEL3CR_20_0, MSEL3CR_20_1,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_15_0, MSEL3CR_15_1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0,
MSEL3CR_9_0, MSEL3CR_9_1,
0, 0, 0, 0,
MSEL3CR_6_0, MSEL3CR_6_1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_CFG_REG("MSEL4CR", 0xE6058024, 32, 1) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL4CR_19_0, MSEL4CR_19_1,
MSEL4CR_18_0, MSEL4CR_18_1,
MSEL4CR_17_0, MSEL4CR_17_1,
MSEL4CR_16_0, MSEL4CR_16_1,
MSEL4CR_15_0, MSEL4CR_15_1,
MSEL4CR_14_0, MSEL4CR_14_1,
0, 0, 0, 0,
0, 0,
MSEL4CR_10_0, MSEL4CR_10_1,
0, 0, 0, 0,
0, 0,
MSEL4CR_6_0, MSEL4CR_6_1,
0, 0,
MSEL4CR_4_0, MSEL4CR_4_1,
0, 0, 0, 0,
MSEL4CR_1_0, MSEL4CR_1_1,
0, 0,
}
},
{ },
};
static struct pinmux_data_reg pinmux_data_regs[] = {
{ PINMUX_DATA_REG("PORTL095_064DR", 0xE6054008, 32) {
PORT95_DATA, PORT94_DATA, PORT93_DATA, PORT92_DATA,
PORT91_DATA, PORT90_DATA, PORT89_DATA, PORT88_DATA,
PORT87_DATA, PORT86_DATA, PORT85_DATA, PORT84_DATA,
PORT83_DATA, PORT82_DATA, PORT81_DATA, PORT80_DATA,
PORT79_DATA, PORT78_DATA, PORT77_DATA, PORT76_DATA,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTL127_096DR", 0xE605400C, 32) {
PORT127_DATA, PORT126_DATA, PORT125_DATA, PORT124_DATA,
PORT123_DATA, PORT122_DATA, PORT121_DATA, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PORT99_DATA, PORT98_DATA, PORT97_DATA, PORT96_DATA,
}
},
{ PINMUX_DATA_REG("PORTL159_128DR", 0xE6054010, 32) {
PORT159_DATA, PORT158_DATA, PORT157_DATA, PORT156_DATA,
0, 0, 0, 0,
PORT151_DATA, PORT150_DATA, PORT149_DATA, PORT148_DATA,
PORT147_DATA, PORT146_DATA, PORT145_DATA, PORT144_DATA,
PORT143_DATA, PORT142_DATA, PORT141_DATA, PORT140_DATA,
PORT139_DATA, PORT138_DATA, PORT137_DATA, PORT136_DATA,
PORT135_DATA, PORT134_DATA, PORT133_DATA, PORT132_DATA,
PORT131_DATA, PORT130_DATA, PORT129_DATA, PORT128_DATA,
}
},
{ PINMUX_DATA_REG("PORTL191_160DR", 0xE6054014, 32) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, PORT166_DATA, PORT165_DATA, PORT164_DATA,
PORT163_DATA, PORT162_DATA, PORT161_DATA, PORT160_DATA,
}
},
{ PINMUX_DATA_REG("PORTD031_000DR", 0xE6055000, 32) {
PORT31_DATA, PORT30_DATA, PORT29_DATA, PORT28_DATA,
PORT27_DATA, PORT26_DATA, PORT25_DATA, PORT24_DATA,
PORT23_DATA, PORT22_DATA, PORT21_DATA, PORT20_DATA,
PORT19_DATA, PORT18_DATA, PORT17_DATA, PORT16_DATA,
PORT15_DATA, PORT14_DATA, PORT13_DATA, PORT12_DATA,
PORT11_DATA, PORT10_DATA, PORT9_DATA, PORT8_DATA,
PORT7_DATA, PORT6_DATA, PORT5_DATA, PORT4_DATA,
PORT3_DATA, PORT2_DATA, PORT1_DATA, PORT0_DATA,
}
},
{ PINMUX_DATA_REG("PORTD063_032DR", 0xE6055004, 32) {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, PORT45_DATA, PORT44_DATA,
PORT43_DATA, PORT42_DATA, PORT41_DATA, PORT40_DATA,
PORT39_DATA, PORT38_DATA, PORT37_DATA, PORT36_DATA,
PORT35_DATA, PORT34_DATA, PORT33_DATA, PORT32_DATA,
}
},
{ PINMUX_DATA_REG("PORTR063_032DR", 0xE6056004, 32) {
PORT63_DATA, PORT62_DATA, PORT61_DATA, PORT60_DATA,
PORT59_DATA, PORT58_DATA, PORT57_DATA, PORT56_DATA,
PORT55_DATA, PORT54_DATA, PORT53_DATA, PORT52_DATA,
PORT51_DATA, PORT50_DATA, PORT49_DATA, PORT48_DATA,
PORT47_DATA, PORT46_DATA, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTR095_064DR", 0xE6056008, 32) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PORT75_DATA, PORT74_DATA, PORT73_DATA, PORT72_DATA,
PORT71_DATA, PORT70_DATA, PORT69_DATA, PORT68_DATA,
PORT67_DATA, PORT66_DATA, PORT65_DATA, PORT64_DATA,
}
},
{ PINMUX_DATA_REG("PORTR191_160DR", 0xE6056014, 32) {
0, PORT190_DATA, PORT189_DATA, PORT188_DATA,
PORT187_DATA, PORT186_DATA, PORT185_DATA, PORT184_DATA,
PORT183_DATA, PORT182_DATA, PORT181_DATA, PORT180_DATA,
PORT179_DATA, PORT178_DATA, PORT177_DATA, PORT176_DATA,
PORT175_DATA, PORT174_DATA, PORT173_DATA, PORT172_DATA,
PORT171_DATA, PORT170_DATA, PORT169_DATA, PORT168_DATA,
PORT167_DATA, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTU127_096DR", 0xE605700C, 32) {
0, 0, 0, 0,
0, 0, 0, PORT120_DATA,
PORT119_DATA, PORT118_DATA, PORT117_DATA, PORT116_DATA,
PORT115_DATA, PORT114_DATA, PORT113_DATA, PORT112_DATA,
PORT111_DATA, PORT110_DATA, PORT109_DATA, PORT108_DATA,
PORT107_DATA, PORT106_DATA, PORT105_DATA, PORT104_DATA,
PORT103_DATA, PORT102_DATA, PORT101_DATA, PORT100_DATA,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTU159_128DR", 0xE6057010, 32) {
0, 0, 0, 0,
PORT155_DATA, PORT154_DATA, PORT153_DATA, PORT152_DATA,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ },
};
#define EXT_IRQ16L(n) evt2irq(0x200 + ((n) << 5))
#define EXT_IRQ16H(n) evt2irq(0x3200 + (((n) - 16) << 5))
static struct pinmux_irq pinmux_irqs[] = {
PINMUX_IRQ(EXT_IRQ16L(0), PORT6_FN0, PORT162_FN0),
PINMUX_IRQ(EXT_IRQ16L(1), PORT12_FN0),
PINMUX_IRQ(EXT_IRQ16L(2), PORT4_FN0, PORT5_FN0),
PINMUX_IRQ(EXT_IRQ16L(3), PORT8_FN0, PORT16_FN0),
PINMUX_IRQ(EXT_IRQ16L(4), PORT17_FN0, PORT163_FN0),
PINMUX_IRQ(EXT_IRQ16L(5), PORT18_FN0),
PINMUX_IRQ(EXT_IRQ16L(6), PORT39_FN0, PORT164_FN0),
PINMUX_IRQ(EXT_IRQ16L(7), PORT40_FN0, PORT167_FN0),
PINMUX_IRQ(EXT_IRQ16L(8), PORT41_FN0, PORT168_FN0),
PINMUX_IRQ(EXT_IRQ16L(9), PORT42_FN0, PORT169_FN0),
PINMUX_IRQ(EXT_IRQ16L(10), PORT65_FN0),
PINMUX_IRQ(EXT_IRQ16L(11), PORT67_FN0),
PINMUX_IRQ(EXT_IRQ16L(12), PORT80_FN0, PORT137_FN0),
PINMUX_IRQ(EXT_IRQ16L(13), PORT81_FN0, PORT145_FN0),
PINMUX_IRQ(EXT_IRQ16L(14), PORT82_FN0, PORT146_FN0),
PINMUX_IRQ(EXT_IRQ16L(15), PORT83_FN0, PORT147_FN0),
PINMUX_IRQ(EXT_IRQ16H(16), PORT84_FN0, PORT170_FN0),
PINMUX_IRQ(EXT_IRQ16H(17), PORT85_FN0),
PINMUX_IRQ(EXT_IRQ16H(18), PORT86_FN0),
PINMUX_IRQ(EXT_IRQ16H(19), PORT87_FN0),
PINMUX_IRQ(EXT_IRQ16H(20), PORT92_FN0),
PINMUX_IRQ(EXT_IRQ16H(21), PORT93_FN0),
PINMUX_IRQ(EXT_IRQ16H(22), PORT94_FN0),
PINMUX_IRQ(EXT_IRQ16H(23), PORT95_FN0),
PINMUX_IRQ(EXT_IRQ16H(24), PORT112_FN0),
PINMUX_IRQ(EXT_IRQ16H(25), PORT119_FN0),
PINMUX_IRQ(EXT_IRQ16H(26), PORT121_FN0, PORT172_FN0),
PINMUX_IRQ(EXT_IRQ16H(27), PORT122_FN0, PORT180_FN0),
PINMUX_IRQ(EXT_IRQ16H(28), PORT123_FN0, PORT181_FN0),
PINMUX_IRQ(EXT_IRQ16H(29), PORT129_FN0, PORT182_FN0),
PINMUX_IRQ(EXT_IRQ16H(30), PORT130_FN0, PORT183_FN0),
PINMUX_IRQ(EXT_IRQ16H(31), PORT138_FN0, PORT184_FN0),
};
static struct pinmux_info sh7372_pinmux_info = {
.name = "sh7372_pfc",
.reserved_id = PINMUX_RESERVED,
.data = { PINMUX_DATA_BEGIN, PINMUX_DATA_END },
.input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END },
.input_pu = { PINMUX_INPUT_PULLUP_BEGIN, PINMUX_INPUT_PULLUP_END },
.input_pd = { PINMUX_INPUT_PULLDOWN_BEGIN, PINMUX_INPUT_PULLDOWN_END },
.output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END },
.mark = { PINMUX_MARK_BEGIN, PINMUX_MARK_END },
.function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END },
.first_gpio = GPIO_PORT0,
.last_gpio = GPIO_FN_SDENC_DV_CLKI,
.gpios = pinmux_gpios,
.cfg_regs = pinmux_config_regs,
.data_regs = pinmux_data_regs,
.gpio_data = pinmux_data,
.gpio_data_size = ARRAY_SIZE(pinmux_data),
.gpio_irq = pinmux_irqs,
.gpio_irq_size = ARRAY_SIZE(pinmux_irqs),
};
void sh7372_pinmux_init(void)
{
register_pinmux(&sh7372_pinmux_info);
}
| gpl-2.0 |
eklovya/android_kernel_lge_p725 | drivers/rapidio/rio.c | 7987 | 33020 | /*
* RapidIO interconnect services
* (RapidIO Interconnect Specification, http://www.rapidio.org)
*
* Copyright 2005 MontaVista Software, Inc.
* Matt Porter <mporter@kernel.crashing.org>
*
* Copyright 2009 Integrated Device Technology, Inc.
* Alex Bounine <alexandre.bounine@idt.com>
* - Added Port-Write/Error Management initialization and handling
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/rio.h>
#include <linux/rio_drv.h>
#include <linux/rio_ids.h>
#include <linux/rio_regs.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include "rio.h"
static LIST_HEAD(rio_mports);
static unsigned char next_portid;
/**
* rio_local_get_device_id - Get the base/extended device id for a port
* @port: RIO master port from which to get the deviceid
*
* Reads the base/extended device id from the local device
* implementing the master port. Returns the 8/16-bit device
* id.
*/
u16 rio_local_get_device_id(struct rio_mport *port)
{
u32 result;
rio_local_read_config_32(port, RIO_DID_CSR, &result);
return (RIO_GET_DID(port->sys_size, result));
}
/**
* rio_request_inb_mbox - request inbound mailbox service
* @mport: RIO master port from which to allocate the mailbox resource
* @dev_id: Device specific pointer to pass on event
* @mbox: Mailbox number to claim
* @entries: Number of entries in inbound mailbox queue
* @minb: Callback to execute when inbound message is received
*
* Requests ownership of an inbound mailbox resource and binds
* a callback function to the resource. Returns %0 on success.
*/
int rio_request_inb_mbox(struct rio_mport *mport,
void *dev_id,
int mbox,
int entries,
void (*minb) (struct rio_mport * mport, void *dev_id, int mbox,
int slot))
{
int rc = -ENOSYS;
struct resource *res;
if (mport->ops->open_inb_mbox == NULL)
goto out;
res = kmalloc(sizeof(struct resource), GFP_KERNEL);
if (res) {
rio_init_mbox_res(res, mbox, mbox);
/* Make sure this mailbox isn't in use */
if ((rc =
request_resource(&mport->riores[RIO_INB_MBOX_RESOURCE],
res)) < 0) {
kfree(res);
goto out;
}
mport->inb_msg[mbox].res = res;
/* Hook the inbound message callback */
mport->inb_msg[mbox].mcback = minb;
rc = mport->ops->open_inb_mbox(mport, dev_id, mbox, entries);
} else
rc = -ENOMEM;
out:
return rc;
}
/**
* rio_release_inb_mbox - release inbound mailbox message service
* @mport: RIO master port from which to release the mailbox resource
* @mbox: Mailbox number to release
*
* Releases ownership of an inbound mailbox resource. Returns 0
* if the request has been satisfied.
*/
int rio_release_inb_mbox(struct rio_mport *mport, int mbox)
{
if (mport->ops->close_inb_mbox) {
mport->ops->close_inb_mbox(mport, mbox);
/* Release the mailbox resource */
return release_resource(mport->inb_msg[mbox].res);
} else
return -ENOSYS;
}
/**
* rio_request_outb_mbox - request outbound mailbox service
* @mport: RIO master port from which to allocate the mailbox resource
* @dev_id: Device specific pointer to pass on event
* @mbox: Mailbox number to claim
* @entries: Number of entries in outbound mailbox queue
* @moutb: Callback to execute when outbound message is sent
*
* Requests ownership of an outbound mailbox resource and binds
* a callback function to the resource. Returns 0 on success.
*/
int rio_request_outb_mbox(struct rio_mport *mport,
void *dev_id,
int mbox,
int entries,
void (*moutb) (struct rio_mport * mport, void *dev_id, int mbox, int slot))
{
int rc = -ENOSYS;
struct resource *res;
if (mport->ops->open_outb_mbox == NULL)
goto out;
res = kmalloc(sizeof(struct resource), GFP_KERNEL);
if (res) {
rio_init_mbox_res(res, mbox, mbox);
/* Make sure this outbound mailbox isn't in use */
if ((rc =
request_resource(&mport->riores[RIO_OUTB_MBOX_RESOURCE],
res)) < 0) {
kfree(res);
goto out;
}
mport->outb_msg[mbox].res = res;
/* Hook the inbound message callback */
mport->outb_msg[mbox].mcback = moutb;
rc = mport->ops->open_outb_mbox(mport, dev_id, mbox, entries);
} else
rc = -ENOMEM;
out:
return rc;
}
/**
* rio_release_outb_mbox - release outbound mailbox message service
* @mport: RIO master port from which to release the mailbox resource
* @mbox: Mailbox number to release
*
* Releases ownership of an inbound mailbox resource. Returns 0
* if the request has been satisfied.
*/
int rio_release_outb_mbox(struct rio_mport *mport, int mbox)
{
if (mport->ops->close_outb_mbox) {
mport->ops->close_outb_mbox(mport, mbox);
/* Release the mailbox resource */
return release_resource(mport->outb_msg[mbox].res);
} else
return -ENOSYS;
}
/**
* rio_setup_inb_dbell - bind inbound doorbell callback
* @mport: RIO master port to bind the doorbell callback
* @dev_id: Device specific pointer to pass on event
* @res: Doorbell message resource
* @dinb: Callback to execute when doorbell is received
*
* Adds a doorbell resource/callback pair into a port's
* doorbell event list. Returns 0 if the request has been
* satisfied.
*/
static int
rio_setup_inb_dbell(struct rio_mport *mport, void *dev_id, struct resource *res,
void (*dinb) (struct rio_mport * mport, void *dev_id, u16 src, u16 dst,
u16 info))
{
int rc = 0;
struct rio_dbell *dbell;
if (!(dbell = kmalloc(sizeof(struct rio_dbell), GFP_KERNEL))) {
rc = -ENOMEM;
goto out;
}
dbell->res = res;
dbell->dinb = dinb;
dbell->dev_id = dev_id;
list_add_tail(&dbell->node, &mport->dbells);
out:
return rc;
}
/**
* rio_request_inb_dbell - request inbound doorbell message service
* @mport: RIO master port from which to allocate the doorbell resource
* @dev_id: Device specific pointer to pass on event
* @start: Doorbell info range start
* @end: Doorbell info range end
* @dinb: Callback to execute when doorbell is received
*
* Requests ownership of an inbound doorbell resource and binds
* a callback function to the resource. Returns 0 if the request
* has been satisfied.
*/
int rio_request_inb_dbell(struct rio_mport *mport,
void *dev_id,
u16 start,
u16 end,
void (*dinb) (struct rio_mport * mport, void *dev_id, u16 src,
u16 dst, u16 info))
{
int rc = 0;
struct resource *res = kmalloc(sizeof(struct resource), GFP_KERNEL);
if (res) {
rio_init_dbell_res(res, start, end);
/* Make sure these doorbells aren't in use */
if ((rc =
request_resource(&mport->riores[RIO_DOORBELL_RESOURCE],
res)) < 0) {
kfree(res);
goto out;
}
/* Hook the doorbell callback */
rc = rio_setup_inb_dbell(mport, dev_id, res, dinb);
} else
rc = -ENOMEM;
out:
return rc;
}
/**
* rio_release_inb_dbell - release inbound doorbell message service
* @mport: RIO master port from which to release the doorbell resource
* @start: Doorbell info range start
* @end: Doorbell info range end
*
* Releases ownership of an inbound doorbell resource and removes
* callback from the doorbell event list. Returns 0 if the request
* has been satisfied.
*/
int rio_release_inb_dbell(struct rio_mport *mport, u16 start, u16 end)
{
int rc = 0, found = 0;
struct rio_dbell *dbell;
list_for_each_entry(dbell, &mport->dbells, node) {
if ((dbell->res->start == start) && (dbell->res->end == end)) {
found = 1;
break;
}
}
/* If we can't find an exact match, fail */
if (!found) {
rc = -EINVAL;
goto out;
}
/* Delete from list */
list_del(&dbell->node);
/* Release the doorbell resource */
rc = release_resource(dbell->res);
/* Free the doorbell event */
kfree(dbell);
out:
return rc;
}
/**
* rio_request_outb_dbell - request outbound doorbell message range
* @rdev: RIO device from which to allocate the doorbell resource
* @start: Doorbell message range start
* @end: Doorbell message range end
*
* Requests ownership of a doorbell message range. Returns a resource
* if the request has been satisfied or %NULL on failure.
*/
struct resource *rio_request_outb_dbell(struct rio_dev *rdev, u16 start,
u16 end)
{
struct resource *res = kmalloc(sizeof(struct resource), GFP_KERNEL);
if (res) {
rio_init_dbell_res(res, start, end);
/* Make sure these doorbells aren't in use */
if (request_resource(&rdev->riores[RIO_DOORBELL_RESOURCE], res)
< 0) {
kfree(res);
res = NULL;
}
}
return res;
}
/**
* rio_release_outb_dbell - release outbound doorbell message range
* @rdev: RIO device from which to release the doorbell resource
* @res: Doorbell resource to be freed
*
* Releases ownership of a doorbell message range. Returns 0 if the
* request has been satisfied.
*/
int rio_release_outb_dbell(struct rio_dev *rdev, struct resource *res)
{
int rc = release_resource(res);
kfree(res);
return rc;
}
/**
* rio_request_inb_pwrite - request inbound port-write message service
* @rdev: RIO device to which register inbound port-write callback routine
* @pwcback: Callback routine to execute when port-write is received
*
* Binds a port-write callback function to the RapidIO device.
* Returns 0 if the request has been satisfied.
*/
int rio_request_inb_pwrite(struct rio_dev *rdev,
int (*pwcback)(struct rio_dev *rdev, union rio_pw_msg *msg, int step))
{
int rc = 0;
spin_lock(&rio_global_list_lock);
if (rdev->pwcback != NULL)
rc = -ENOMEM;
else
rdev->pwcback = pwcback;
spin_unlock(&rio_global_list_lock);
return rc;
}
EXPORT_SYMBOL_GPL(rio_request_inb_pwrite);
/**
* rio_release_inb_pwrite - release inbound port-write message service
* @rdev: RIO device which registered for inbound port-write callback
*
* Removes callback from the rio_dev structure. Returns 0 if the request
* has been satisfied.
*/
int rio_release_inb_pwrite(struct rio_dev *rdev)
{
int rc = -ENOMEM;
spin_lock(&rio_global_list_lock);
if (rdev->pwcback) {
rdev->pwcback = NULL;
rc = 0;
}
spin_unlock(&rio_global_list_lock);
return rc;
}
EXPORT_SYMBOL_GPL(rio_release_inb_pwrite);
/**
* rio_mport_get_physefb - Helper function that returns register offset
* for Physical Layer Extended Features Block.
* @port: Master port to issue transaction
* @local: Indicate a local master port or remote device access
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
*/
u32
rio_mport_get_physefb(struct rio_mport *port, int local,
u16 destid, u8 hopcount)
{
u32 ext_ftr_ptr;
u32 ftr_header;
ext_ftr_ptr = rio_mport_get_efb(port, local, destid, hopcount, 0);
while (ext_ftr_ptr) {
if (local)
rio_local_read_config_32(port, ext_ftr_ptr,
&ftr_header);
else
rio_mport_read_config_32(port, destid, hopcount,
ext_ftr_ptr, &ftr_header);
ftr_header = RIO_GET_BLOCK_ID(ftr_header);
switch (ftr_header) {
case RIO_EFB_SER_EP_ID_V13P:
case RIO_EFB_SER_EP_REC_ID_V13P:
case RIO_EFB_SER_EP_FREE_ID_V13P:
case RIO_EFB_SER_EP_ID:
case RIO_EFB_SER_EP_REC_ID:
case RIO_EFB_SER_EP_FREE_ID:
case RIO_EFB_SER_EP_FREC_ID:
return ext_ftr_ptr;
default:
break;
}
ext_ftr_ptr = rio_mport_get_efb(port, local, destid,
hopcount, ext_ftr_ptr);
}
return ext_ftr_ptr;
}
/**
* rio_get_comptag - Begin or continue searching for a RIO device by component tag
* @comp_tag: RIO component tag to match
* @from: Previous RIO device found in search, or %NULL for new search
*
* Iterates through the list of known RIO devices. If a RIO device is
* found with a matching @comp_tag, a pointer to its device
* structure is returned. Otherwise, %NULL is returned. A new search
* is initiated by passing %NULL to the @from argument. Otherwise, if
* @from is not %NULL, searches continue from next device on the global
* list.
*/
struct rio_dev *rio_get_comptag(u32 comp_tag, struct rio_dev *from)
{
struct list_head *n;
struct rio_dev *rdev;
spin_lock(&rio_global_list_lock);
n = from ? from->global_list.next : rio_devices.next;
while (n && (n != &rio_devices)) {
rdev = rio_dev_g(n);
if (rdev->comp_tag == comp_tag)
goto exit;
n = n->next;
}
rdev = NULL;
exit:
spin_unlock(&rio_global_list_lock);
return rdev;
}
/**
* rio_set_port_lockout - Sets/clears LOCKOUT bit (RIO EM 1.3) for a switch port.
* @rdev: Pointer to RIO device control structure
* @pnum: Switch port number to set LOCKOUT bit
* @lock: Operation : set (=1) or clear (=0)
*/
int rio_set_port_lockout(struct rio_dev *rdev, u32 pnum, int lock)
{
u32 regval;
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_CTL_CSR(pnum),
®val);
if (lock)
regval |= RIO_PORT_N_CTL_LOCKOUT;
else
regval &= ~RIO_PORT_N_CTL_LOCKOUT;
rio_write_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_CTL_CSR(pnum),
regval);
return 0;
}
/**
* rio_chk_dev_route - Validate route to the specified device.
* @rdev: RIO device failed to respond
* @nrdev: Last active device on the route to rdev
* @npnum: nrdev's port number on the route to rdev
*
* Follows a route to the specified RIO device to determine the last available
* device (and corresponding RIO port) on the route.
*/
static int
rio_chk_dev_route(struct rio_dev *rdev, struct rio_dev **nrdev, int *npnum)
{
u32 result;
int p_port, rc = -EIO;
struct rio_dev *prev = NULL;
/* Find switch with failed RIO link */
while (rdev->prev && (rdev->prev->pef & RIO_PEF_SWITCH)) {
if (!rio_read_config_32(rdev->prev, RIO_DEV_ID_CAR, &result)) {
prev = rdev->prev;
break;
}
rdev = rdev->prev;
}
if (prev == NULL)
goto err_out;
p_port = prev->rswitch->route_table[rdev->destid];
if (p_port != RIO_INVALID_ROUTE) {
pr_debug("RIO: link failed on [%s]-P%d\n",
rio_name(prev), p_port);
*nrdev = prev;
*npnum = p_port;
rc = 0;
} else
pr_debug("RIO: failed to trace route to %s\n", rio_name(rdev));
err_out:
return rc;
}
/**
* rio_mport_chk_dev_access - Validate access to the specified device.
* @mport: Master port to send transactions
* @destid: Device destination ID in network
* @hopcount: Number of hops into the network
*/
int
rio_mport_chk_dev_access(struct rio_mport *mport, u16 destid, u8 hopcount)
{
int i = 0;
u32 tmp;
while (rio_mport_read_config_32(mport, destid, hopcount,
RIO_DEV_ID_CAR, &tmp)) {
i++;
if (i == RIO_MAX_CHK_RETRY)
return -EIO;
mdelay(1);
}
return 0;
}
/**
* rio_chk_dev_access - Validate access to the specified device.
* @rdev: Pointer to RIO device control structure
*/
static int rio_chk_dev_access(struct rio_dev *rdev)
{
return rio_mport_chk_dev_access(rdev->net->hport,
rdev->destid, rdev->hopcount);
}
/**
* rio_get_input_status - Sends a Link-Request/Input-Status control symbol and
* returns link-response (if requested).
* @rdev: RIO devive to issue Input-status command
* @pnum: Device port number to issue the command
* @lnkresp: Response from a link partner
*/
static int
rio_get_input_status(struct rio_dev *rdev, int pnum, u32 *lnkresp)
{
u32 regval;
int checkcount;
if (lnkresp) {
/* Read from link maintenance response register
* to clear valid bit */
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_MNT_RSP_CSR(pnum),
®val);
udelay(50);
}
/* Issue Input-status command */
rio_write_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_MNT_REQ_CSR(pnum),
RIO_MNT_REQ_CMD_IS);
/* Exit if the response is not expected */
if (lnkresp == NULL)
return 0;
checkcount = 3;
while (checkcount--) {
udelay(50);
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_MNT_RSP_CSR(pnum),
®val);
if (regval & RIO_PORT_N_MNT_RSP_RVAL) {
*lnkresp = regval;
return 0;
}
}
return -EIO;
}
/**
* rio_clr_err_stopped - Clears port Error-stopped states.
* @rdev: Pointer to RIO device control structure
* @pnum: Switch port number to clear errors
* @err_status: port error status (if 0 reads register from device)
*/
static int rio_clr_err_stopped(struct rio_dev *rdev, u32 pnum, u32 err_status)
{
struct rio_dev *nextdev = rdev->rswitch->nextdev[pnum];
u32 regval;
u32 far_ackid, far_linkstat, near_ackid;
if (err_status == 0)
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
&err_status);
if (err_status & RIO_PORT_N_ERR_STS_PW_OUT_ES) {
pr_debug("RIO_EM: servicing Output Error-Stopped state\n");
/*
* Send a Link-Request/Input-Status control symbol
*/
if (rio_get_input_status(rdev, pnum, ®val)) {
pr_debug("RIO_EM: Input-status response timeout\n");
goto rd_err;
}
pr_debug("RIO_EM: SP%d Input-status response=0x%08x\n",
pnum, regval);
far_ackid = (regval & RIO_PORT_N_MNT_RSP_ASTAT) >> 5;
far_linkstat = regval & RIO_PORT_N_MNT_RSP_LSTAT;
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ACK_STS_CSR(pnum),
®val);
pr_debug("RIO_EM: SP%d_ACK_STS_CSR=0x%08x\n", pnum, regval);
near_ackid = (regval & RIO_PORT_N_ACK_INBOUND) >> 24;
pr_debug("RIO_EM: SP%d far_ackID=0x%02x far_linkstat=0x%02x" \
" near_ackID=0x%02x\n",
pnum, far_ackid, far_linkstat, near_ackid);
/*
* If required, synchronize ackIDs of near and
* far sides.
*/
if ((far_ackid != ((regval & RIO_PORT_N_ACK_OUTSTAND) >> 8)) ||
(far_ackid != (regval & RIO_PORT_N_ACK_OUTBOUND))) {
/* Align near outstanding/outbound ackIDs with
* far inbound.
*/
rio_write_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ACK_STS_CSR(pnum),
(near_ackid << 24) |
(far_ackid << 8) | far_ackid);
/* Align far outstanding/outbound ackIDs with
* near inbound.
*/
far_ackid++;
if (nextdev)
rio_write_config_32(nextdev,
nextdev->phys_efptr +
RIO_PORT_N_ACK_STS_CSR(RIO_GET_PORT_NUM(nextdev->swpinfo)),
(far_ackid << 24) |
(near_ackid << 8) | near_ackid);
else
pr_debug("RIO_EM: Invalid nextdev pointer (NULL)\n");
}
rd_err:
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
&err_status);
pr_debug("RIO_EM: SP%d_ERR_STS_CSR=0x%08x\n", pnum, err_status);
}
if ((err_status & RIO_PORT_N_ERR_STS_PW_INP_ES) && nextdev) {
pr_debug("RIO_EM: servicing Input Error-Stopped state\n");
rio_get_input_status(nextdev,
RIO_GET_PORT_NUM(nextdev->swpinfo), NULL);
udelay(50);
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
&err_status);
pr_debug("RIO_EM: SP%d_ERR_STS_CSR=0x%08x\n", pnum, err_status);
}
return (err_status & (RIO_PORT_N_ERR_STS_PW_OUT_ES |
RIO_PORT_N_ERR_STS_PW_INP_ES)) ? 1 : 0;
}
/**
* rio_inb_pwrite_handler - process inbound port-write message
* @pw_msg: pointer to inbound port-write message
*
* Processes an inbound port-write message. Returns 0 if the request
* has been satisfied.
*/
int rio_inb_pwrite_handler(union rio_pw_msg *pw_msg)
{
struct rio_dev *rdev;
u32 err_status, em_perrdet, em_ltlerrdet;
int rc, portnum;
rdev = rio_get_comptag((pw_msg->em.comptag & RIO_CTAG_UDEVID), NULL);
if (rdev == NULL) {
/* Device removed or enumeration error */
pr_debug("RIO: %s No matching device for CTag 0x%08x\n",
__func__, pw_msg->em.comptag);
return -EIO;
}
pr_debug("RIO: Port-Write message from %s\n", rio_name(rdev));
#ifdef DEBUG_PW
{
u32 i;
for (i = 0; i < RIO_PW_MSG_SIZE/sizeof(u32);) {
pr_debug("0x%02x: %08x %08x %08x %08x\n",
i*4, pw_msg->raw[i], pw_msg->raw[i + 1],
pw_msg->raw[i + 2], pw_msg->raw[i + 3]);
i += 4;
}
}
#endif
/* Call an external service function (if such is registered
* for this device). This may be the service for endpoints that send
* device-specific port-write messages. End-point messages expected
* to be handled completely by EP specific device driver.
* For switches rc==0 signals that no standard processing required.
*/
if (rdev->pwcback != NULL) {
rc = rdev->pwcback(rdev, pw_msg, 0);
if (rc == 0)
return 0;
}
portnum = pw_msg->em.is_port & 0xFF;
/* Check if device and route to it are functional:
* Sometimes devices may send PW message(s) just before being
* powered down (or link being lost).
*/
if (rio_chk_dev_access(rdev)) {
pr_debug("RIO: device access failed - get link partner\n");
/* Scan route to the device and identify failed link.
* This will replace device and port reported in PW message.
* PW message should not be used after this point.
*/
if (rio_chk_dev_route(rdev, &rdev, &portnum)) {
pr_err("RIO: Route trace for %s failed\n",
rio_name(rdev));
return -EIO;
}
pw_msg = NULL;
}
/* For End-point devices processing stops here */
if (!(rdev->pef & RIO_PEF_SWITCH))
return 0;
if (rdev->phys_efptr == 0) {
pr_err("RIO_PW: Bad switch initialization for %s\n",
rio_name(rdev));
return 0;
}
/*
* Process the port-write notification from switch
*/
if (rdev->rswitch->em_handle)
rdev->rswitch->em_handle(rdev, portnum);
rio_read_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(portnum),
&err_status);
pr_debug("RIO_PW: SP%d_ERR_STS_CSR=0x%08x\n", portnum, err_status);
if (err_status & RIO_PORT_N_ERR_STS_PORT_OK) {
if (!(rdev->rswitch->port_ok & (1 << portnum))) {
rdev->rswitch->port_ok |= (1 << portnum);
rio_set_port_lockout(rdev, portnum, 0);
/* Schedule Insertion Service */
pr_debug("RIO_PW: Device Insertion on [%s]-P%d\n",
rio_name(rdev), portnum);
}
/* Clear error-stopped states (if reported).
* Depending on the link partner state, two attempts
* may be needed for successful recovery.
*/
if (err_status & (RIO_PORT_N_ERR_STS_PW_OUT_ES |
RIO_PORT_N_ERR_STS_PW_INP_ES)) {
if (rio_clr_err_stopped(rdev, portnum, err_status))
rio_clr_err_stopped(rdev, portnum, 0);
}
} else { /* if (err_status & RIO_PORT_N_ERR_STS_PORT_UNINIT) */
if (rdev->rswitch->port_ok & (1 << portnum)) {
rdev->rswitch->port_ok &= ~(1 << portnum);
rio_set_port_lockout(rdev, portnum, 1);
rio_write_config_32(rdev,
rdev->phys_efptr +
RIO_PORT_N_ACK_STS_CSR(portnum),
RIO_PORT_N_ACK_CLEAR);
/* Schedule Extraction Service */
pr_debug("RIO_PW: Device Extraction on [%s]-P%d\n",
rio_name(rdev), portnum);
}
}
rio_read_config_32(rdev,
rdev->em_efptr + RIO_EM_PN_ERR_DETECT(portnum), &em_perrdet);
if (em_perrdet) {
pr_debug("RIO_PW: RIO_EM_P%d_ERR_DETECT=0x%08x\n",
portnum, em_perrdet);
/* Clear EM Port N Error Detect CSR */
rio_write_config_32(rdev,
rdev->em_efptr + RIO_EM_PN_ERR_DETECT(portnum), 0);
}
rio_read_config_32(rdev,
rdev->em_efptr + RIO_EM_LTL_ERR_DETECT, &em_ltlerrdet);
if (em_ltlerrdet) {
pr_debug("RIO_PW: RIO_EM_LTL_ERR_DETECT=0x%08x\n",
em_ltlerrdet);
/* Clear EM L/T Layer Error Detect CSR */
rio_write_config_32(rdev,
rdev->em_efptr + RIO_EM_LTL_ERR_DETECT, 0);
}
/* Clear remaining error bits and Port-Write Pending bit */
rio_write_config_32(rdev,
rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(portnum),
err_status);
return 0;
}
EXPORT_SYMBOL_GPL(rio_inb_pwrite_handler);
/**
* rio_mport_get_efb - get pointer to next extended features block
* @port: Master port to issue transaction
* @local: Indicate a local master port or remote device access
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
* @from: Offset of current Extended Feature block header (if 0 starts
* from ExtFeaturePtr)
*/
u32
rio_mport_get_efb(struct rio_mport *port, int local, u16 destid,
u8 hopcount, u32 from)
{
u32 reg_val;
if (from == 0) {
if (local)
rio_local_read_config_32(port, RIO_ASM_INFO_CAR,
®_val);
else
rio_mport_read_config_32(port, destid, hopcount,
RIO_ASM_INFO_CAR, ®_val);
return reg_val & RIO_EXT_FTR_PTR_MASK;
} else {
if (local)
rio_local_read_config_32(port, from, ®_val);
else
rio_mport_read_config_32(port, destid, hopcount,
from, ®_val);
return RIO_GET_BLOCK_ID(reg_val);
}
}
/**
* rio_mport_get_feature - query for devices' extended features
* @port: Master port to issue transaction
* @local: Indicate a local master port or remote device access
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
* @ftr: Extended feature code
*
* Tell if a device supports a given RapidIO capability.
* Returns the offset of the requested extended feature
* block within the device's RIO configuration space or
* 0 in case the device does not support it. Possible
* values for @ftr:
*
* %RIO_EFB_PAR_EP_ID LP/LVDS EP Devices
*
* %RIO_EFB_PAR_EP_REC_ID LP/LVDS EP Recovery Devices
*
* %RIO_EFB_PAR_EP_FREE_ID LP/LVDS EP Free Devices
*
* %RIO_EFB_SER_EP_ID LP/Serial EP Devices
*
* %RIO_EFB_SER_EP_REC_ID LP/Serial EP Recovery Devices
*
* %RIO_EFB_SER_EP_FREE_ID LP/Serial EP Free Devices
*/
u32
rio_mport_get_feature(struct rio_mport * port, int local, u16 destid,
u8 hopcount, int ftr)
{
u32 asm_info, ext_ftr_ptr, ftr_header;
if (local)
rio_local_read_config_32(port, RIO_ASM_INFO_CAR, &asm_info);
else
rio_mport_read_config_32(port, destid, hopcount,
RIO_ASM_INFO_CAR, &asm_info);
ext_ftr_ptr = asm_info & RIO_EXT_FTR_PTR_MASK;
while (ext_ftr_ptr) {
if (local)
rio_local_read_config_32(port, ext_ftr_ptr,
&ftr_header);
else
rio_mport_read_config_32(port, destid, hopcount,
ext_ftr_ptr, &ftr_header);
if (RIO_GET_BLOCK_ID(ftr_header) == ftr)
return ext_ftr_ptr;
if (!(ext_ftr_ptr = RIO_GET_BLOCK_PTR(ftr_header)))
break;
}
return 0;
}
/**
* rio_get_asm - Begin or continue searching for a RIO device by vid/did/asm_vid/asm_did
* @vid: RIO vid to match or %RIO_ANY_ID to match all vids
* @did: RIO did to match or %RIO_ANY_ID to match all dids
* @asm_vid: RIO asm_vid to match or %RIO_ANY_ID to match all asm_vids
* @asm_did: RIO asm_did to match or %RIO_ANY_ID to match all asm_dids
* @from: Previous RIO device found in search, or %NULL for new search
*
* Iterates through the list of known RIO devices. If a RIO device is
* found with a matching @vid, @did, @asm_vid, @asm_did, the reference
* count to the device is incrememted and a pointer to its device
* structure is returned. Otherwise, %NULL is returned. A new search
* is initiated by passing %NULL to the @from argument. Otherwise, if
* @from is not %NULL, searches continue from next device on the global
* list. The reference count for @from is always decremented if it is
* not %NULL.
*/
struct rio_dev *rio_get_asm(u16 vid, u16 did,
u16 asm_vid, u16 asm_did, struct rio_dev *from)
{
struct list_head *n;
struct rio_dev *rdev;
WARN_ON(in_interrupt());
spin_lock(&rio_global_list_lock);
n = from ? from->global_list.next : rio_devices.next;
while (n && (n != &rio_devices)) {
rdev = rio_dev_g(n);
if ((vid == RIO_ANY_ID || rdev->vid == vid) &&
(did == RIO_ANY_ID || rdev->did == did) &&
(asm_vid == RIO_ANY_ID || rdev->asm_vid == asm_vid) &&
(asm_did == RIO_ANY_ID || rdev->asm_did == asm_did))
goto exit;
n = n->next;
}
rdev = NULL;
exit:
rio_dev_put(from);
rdev = rio_dev_get(rdev);
spin_unlock(&rio_global_list_lock);
return rdev;
}
/**
* rio_get_device - Begin or continue searching for a RIO device by vid/did
* @vid: RIO vid to match or %RIO_ANY_ID to match all vids
* @did: RIO did to match or %RIO_ANY_ID to match all dids
* @from: Previous RIO device found in search, or %NULL for new search
*
* Iterates through the list of known RIO devices. If a RIO device is
* found with a matching @vid and @did, the reference count to the
* device is incrememted and a pointer to its device structure is returned.
* Otherwise, %NULL is returned. A new search is initiated by passing %NULL
* to the @from argument. Otherwise, if @from is not %NULL, searches
* continue from next device on the global list. The reference count for
* @from is always decremented if it is not %NULL.
*/
struct rio_dev *rio_get_device(u16 vid, u16 did, struct rio_dev *from)
{
return rio_get_asm(vid, did, RIO_ANY_ID, RIO_ANY_ID, from);
}
/**
* rio_std_route_add_entry - Add switch route table entry using standard
* registers defined in RIO specification rev.1.3
* @mport: Master port to issue transaction
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
* @table: routing table ID (global or port-specific)
* @route_destid: destID entry in the RT
* @route_port: destination port for specified destID
*/
int rio_std_route_add_entry(struct rio_mport *mport, u16 destid, u8 hopcount,
u16 table, u16 route_destid, u8 route_port)
{
if (table == RIO_GLOBAL_TABLE) {
rio_mport_write_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_DESTID_SEL_CSR,
(u32)route_destid);
rio_mport_write_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_PORT_SEL_CSR,
(u32)route_port);
}
udelay(10);
return 0;
}
/**
* rio_std_route_get_entry - Read switch route table entry (port number)
* associated with specified destID using standard registers defined in RIO
* specification rev.1.3
* @mport: Master port to issue transaction
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
* @table: routing table ID (global or port-specific)
* @route_destid: destID entry in the RT
* @route_port: returned destination port for specified destID
*/
int rio_std_route_get_entry(struct rio_mport *mport, u16 destid, u8 hopcount,
u16 table, u16 route_destid, u8 *route_port)
{
u32 result;
if (table == RIO_GLOBAL_TABLE) {
rio_mport_write_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_DESTID_SEL_CSR, route_destid);
rio_mport_read_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_PORT_SEL_CSR, &result);
*route_port = (u8)result;
}
return 0;
}
/**
* rio_std_route_clr_table - Clear swotch route table using standard registers
* defined in RIO specification rev.1.3.
* @mport: Master port to issue transaction
* @destid: Destination ID of the device
* @hopcount: Number of switch hops to the device
* @table: routing table ID (global or port-specific)
*/
int rio_std_route_clr_table(struct rio_mport *mport, u16 destid, u8 hopcount,
u16 table)
{
u32 max_destid = 0xff;
u32 i, pef, id_inc = 1, ext_cfg = 0;
u32 port_sel = RIO_INVALID_ROUTE;
if (table == RIO_GLOBAL_TABLE) {
rio_mport_read_config_32(mport, destid, hopcount,
RIO_PEF_CAR, &pef);
if (mport->sys_size) {
rio_mport_read_config_32(mport, destid, hopcount,
RIO_SWITCH_RT_LIMIT,
&max_destid);
max_destid &= RIO_RT_MAX_DESTID;
}
if (pef & RIO_PEF_EXT_RT) {
ext_cfg = 0x80000000;
id_inc = 4;
port_sel = (RIO_INVALID_ROUTE << 24) |
(RIO_INVALID_ROUTE << 16) |
(RIO_INVALID_ROUTE << 8) |
RIO_INVALID_ROUTE;
}
for (i = 0; i <= max_destid;) {
rio_mport_write_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_DESTID_SEL_CSR,
ext_cfg | i);
rio_mport_write_config_32(mport, destid, hopcount,
RIO_STD_RTE_CONF_PORT_SEL_CSR,
port_sel);
i += id_inc;
}
}
udelay(10);
return 0;
}
static void rio_fixup_device(struct rio_dev *dev)
{
}
static int __devinit rio_init(void)
{
struct rio_dev *dev = NULL;
while ((dev = rio_get_device(RIO_ANY_ID, RIO_ANY_ID, dev)) != NULL) {
rio_fixup_device(dev);
}
return 0;
}
int __devinit rio_init_mports(void)
{
struct rio_mport *port;
list_for_each_entry(port, &rio_mports, node) {
if (port->host_deviceid >= 0)
rio_enum_mport(port);
else
rio_disc_mport(port);
}
rio_init();
return 0;
}
device_initcall_sync(rio_init_mports);
static int hdids[RIO_MAX_MPORTS + 1];
static int rio_get_hdid(int index)
{
if (!hdids[0] || hdids[0] <= index || index >= RIO_MAX_MPORTS)
return -1;
return hdids[index + 1];
}
static int rio_hdid_setup(char *str)
{
(void)get_options(str, ARRAY_SIZE(hdids), hdids);
return 1;
}
__setup("riohdid=", rio_hdid_setup);
int rio_register_mport(struct rio_mport *port)
{
if (next_portid >= RIO_MAX_MPORTS) {
pr_err("RIO: reached specified max number of mports\n");
return 1;
}
port->id = next_portid++;
port->host_deviceid = rio_get_hdid(port->id);
list_add_tail(&port->node, &rio_mports);
return 0;
}
EXPORT_SYMBOL_GPL(rio_local_get_device_id);
EXPORT_SYMBOL_GPL(rio_get_device);
EXPORT_SYMBOL_GPL(rio_get_asm);
EXPORT_SYMBOL_GPL(rio_request_inb_dbell);
EXPORT_SYMBOL_GPL(rio_release_inb_dbell);
EXPORT_SYMBOL_GPL(rio_request_outb_dbell);
EXPORT_SYMBOL_GPL(rio_release_outb_dbell);
EXPORT_SYMBOL_GPL(rio_request_inb_mbox);
EXPORT_SYMBOL_GPL(rio_release_inb_mbox);
EXPORT_SYMBOL_GPL(rio_request_outb_mbox);
EXPORT_SYMBOL_GPL(rio_release_outb_mbox);
| gpl-2.0 |
meizuosc/m9 | drivers/rapidio/rio-driver.c | 8499 | 6088 | /*
* RapidIO driver support
*
* Copyright 2005 MontaVista Software, Inc.
* Matt Porter <mporter@kernel.crashing.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/rio.h>
#include <linux/rio_ids.h>
#include "rio.h"
/**
* rio_match_device - Tell if a RIO device has a matching RIO device id structure
* @id: the RIO device id structure to match against
* @rdev: the RIO device structure to match against
*
* Used from driver probe and bus matching to check whether a RIO device
* matches a device id structure provided by a RIO driver. Returns the
* matching &struct rio_device_id or %NULL if there is no match.
*/
static const struct rio_device_id *rio_match_device(const struct rio_device_id
*id,
const struct rio_dev *rdev)
{
while (id->vid || id->asm_vid) {
if (((id->vid == RIO_ANY_ID) || (id->vid == rdev->vid)) &&
((id->did == RIO_ANY_ID) || (id->did == rdev->did)) &&
((id->asm_vid == RIO_ANY_ID)
|| (id->asm_vid == rdev->asm_vid))
&& ((id->asm_did == RIO_ANY_ID)
|| (id->asm_did == rdev->asm_did)))
return id;
id++;
}
return NULL;
}
/**
* rio_dev_get - Increments the reference count of the RIO device structure
*
* @rdev: RIO device being referenced
*
* Each live reference to a device should be refcounted.
*
* Drivers for RIO devices should normally record such references in
* their probe() methods, when they bind to a device, and release
* them by calling rio_dev_put(), in their disconnect() methods.
*/
struct rio_dev *rio_dev_get(struct rio_dev *rdev)
{
if (rdev)
get_device(&rdev->dev);
return rdev;
}
/**
* rio_dev_put - Release a use of the RIO device structure
*
* @rdev: RIO device being disconnected
*
* Must be called when a user of a device is finished with it.
* When the last user of the device calls this function, the
* memory of the device is freed.
*/
void rio_dev_put(struct rio_dev *rdev)
{
if (rdev)
put_device(&rdev->dev);
}
/**
* rio_device_probe - Tell if a RIO device structure has a matching RIO device id structure
* @dev: the RIO device structure to match against
*
* return 0 and set rio_dev->driver when drv claims rio_dev, else error
*/
static int rio_device_probe(struct device *dev)
{
struct rio_driver *rdrv = to_rio_driver(dev->driver);
struct rio_dev *rdev = to_rio_dev(dev);
int error = -ENODEV;
const struct rio_device_id *id;
if (!rdev->driver && rdrv->probe) {
if (!rdrv->id_table)
return error;
id = rio_match_device(rdrv->id_table, rdev);
rio_dev_get(rdev);
if (id)
error = rdrv->probe(rdev, id);
if (error >= 0) {
rdev->driver = rdrv;
error = 0;
} else
rio_dev_put(rdev);
}
return error;
}
/**
* rio_device_remove - Remove a RIO device from the system
*
* @dev: the RIO device structure to match against
*
* Remove a RIO device from the system. If it has an associated
* driver, then run the driver remove() method. Then update
* the reference count.
*/
static int rio_device_remove(struct device *dev)
{
struct rio_dev *rdev = to_rio_dev(dev);
struct rio_driver *rdrv = rdev->driver;
if (rdrv) {
if (rdrv->remove)
rdrv->remove(rdev);
rdev->driver = NULL;
}
rio_dev_put(rdev);
return 0;
}
/**
* rio_register_driver - register a new RIO driver
* @rdrv: the RIO driver structure to register
*
* Adds a &struct rio_driver to the list of registered drivers.
* Returns a negative value on error, otherwise 0. If no error
* occurred, the driver remains registered even if no device
* was claimed during registration.
*/
int rio_register_driver(struct rio_driver *rdrv)
{
/* initialize common driver fields */
rdrv->driver.name = rdrv->name;
rdrv->driver.bus = &rio_bus_type;
/* register with core */
return driver_register(&rdrv->driver);
}
/**
* rio_unregister_driver - unregister a RIO driver
* @rdrv: the RIO driver structure to unregister
*
* Deletes the &struct rio_driver from the list of registered RIO
* drivers, gives it a chance to clean up by calling its remove()
* function for each device it was responsible for, and marks those
* devices as driverless.
*/
void rio_unregister_driver(struct rio_driver *rdrv)
{
driver_unregister(&rdrv->driver);
}
/**
* rio_match_bus - Tell if a RIO device structure has a matching RIO driver device id structure
* @dev: the standard device structure to match against
* @drv: the standard driver structure containing the ids to match against
*
* Used by a driver to check whether a RIO device present in the
* system is in its list of supported devices. Returns 1 if
* there is a matching &struct rio_device_id or 0 if there is
* no match.
*/
static int rio_match_bus(struct device *dev, struct device_driver *drv)
{
struct rio_dev *rdev = to_rio_dev(dev);
struct rio_driver *rdrv = to_rio_driver(drv);
const struct rio_device_id *id = rdrv->id_table;
const struct rio_device_id *found_id;
if (!id)
goto out;
found_id = rio_match_device(id, rdev);
if (found_id)
return 1;
out:return 0;
}
struct device rio_bus = {
.init_name = "rapidio",
};
struct bus_type rio_bus_type = {
.name = "rapidio",
.match = rio_match_bus,
.dev_attrs = rio_dev_attrs,
.probe = rio_device_probe,
.remove = rio_device_remove,
};
/**
* rio_bus_init - Register the RapidIO bus with the device model
*
* Registers the RIO bus device and RIO bus type with the Linux
* device model.
*/
static int __init rio_bus_init(void)
{
if (device_register(&rio_bus) < 0)
printk("RIO: failed to register RIO bus device\n");
return bus_register(&rio_bus_type);
}
postcore_initcall(rio_bus_init);
EXPORT_SYMBOL_GPL(rio_register_driver);
EXPORT_SYMBOL_GPL(rio_unregister_driver);
EXPORT_SYMBOL_GPL(rio_bus_type);
EXPORT_SYMBOL_GPL(rio_dev_get);
EXPORT_SYMBOL_GPL(rio_dev_put);
| gpl-2.0 |
michabs/linux-imx6-3.14 | drivers/video/via/via_aux_edid.c | 9779 | 2399 | /*
* Copyright 2011 Florian Tobias Schandinat <FlorianSchandinat@gmx.de>
*
* 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 WARRANTIES OR REPRESENTATIONS; 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.
*/
/*
* generic EDID driver
*/
#include <linux/slab.h>
#include <linux/fb.h>
#include "via_aux.h"
#include "../edid.h"
static const char *name = "EDID";
static void query_edid(struct via_aux_drv *drv)
{
struct fb_monspecs *spec = drv->data;
unsigned char edid[EDID_LENGTH];
bool valid = false;
if (spec) {
fb_destroy_modedb(spec->modedb);
} else {
spec = kmalloc(sizeof(*spec), GFP_KERNEL);
if (!spec)
return;
}
spec->version = spec->revision = 0;
if (via_aux_read(drv, 0x00, edid, EDID_LENGTH)) {
fb_edid_to_monspecs(edid, spec);
valid = spec->version || spec->revision;
}
if (!valid) {
kfree(spec);
spec = NULL;
} else
printk(KERN_DEBUG "EDID: %s %s\n", spec->manufacturer, spec->monitor);
drv->data = spec;
}
static const struct fb_videomode *get_preferred_mode(struct via_aux_drv *drv)
{
struct fb_monspecs *spec = drv->data;
int i;
if (!spec || !spec->modedb || !(spec->misc & FB_MISC_1ST_DETAIL))
return NULL;
for (i = 0; i < spec->modedb_len; i++) {
if (spec->modedb[i].flag & FB_MODE_IS_FIRST &&
spec->modedb[i].flag & FB_MODE_IS_DETAILED)
return &spec->modedb[i];
}
return NULL;
}
static void cleanup(struct via_aux_drv *drv)
{
struct fb_monspecs *spec = drv->data;
if (spec)
fb_destroy_modedb(spec->modedb);
}
void via_aux_edid_probe(struct via_aux_bus *bus)
{
struct via_aux_drv drv = {
.bus = bus,
.addr = 0x50,
.name = name,
.cleanup = cleanup,
.get_preferred_mode = get_preferred_mode};
query_edid(&drv);
/* as EDID devices can be connected/disconnected just add the driver */
via_aux_add(&drv);
}
| gpl-2.0 |
weixu8/QEMU-s5l89xx-port | spice-qemu-char.c | 52 | 5364 | #include "config-host.h"
#include "trace.h"
#include "ui/qemu-spice.h"
#include <spice.h>
#include <spice-experimental.h>
#include "osdep.h"
#define dprintf(_scd, _level, _fmt, ...) \
do { \
static unsigned __dprintf_counter = 0; \
if (_scd->debug >= _level) { \
fprintf(stderr, "scd: %3d: " _fmt, ++__dprintf_counter, ## __VA_ARGS__);\
} \
} while (0)
#define VMC_MAX_HOST_WRITE 2048
typedef struct SpiceCharDriver {
CharDriverState* chr;
SpiceCharDeviceInstance sin;
char *subtype;
bool active;
uint8_t *buffer;
uint8_t *datapos;
ssize_t bufsize, datalen;
uint32_t debug;
} SpiceCharDriver;
static int vmc_write(SpiceCharDeviceInstance *sin, const uint8_t *buf, int len)
{
SpiceCharDriver *scd = container_of(sin, SpiceCharDriver, sin);
ssize_t out = 0;
ssize_t last_out;
uint8_t* p = (uint8_t*)buf;
while (len > 0) {
last_out = MIN(len, VMC_MAX_HOST_WRITE);
qemu_chr_read(scd->chr, p, last_out);
if (last_out > 0) {
out += last_out;
len -= last_out;
p += last_out;
} else {
break;
}
}
dprintf(scd, 3, "%s: %lu/%zd\n", __func__, out, len + out);
trace_spice_vmc_write(out, len + out);
return out;
}
static int vmc_read(SpiceCharDeviceInstance *sin, uint8_t *buf, int len)
{
SpiceCharDriver *scd = container_of(sin, SpiceCharDriver, sin);
int bytes = MIN(len, scd->datalen);
dprintf(scd, 2, "%s: %p %d/%d/%zd\n", __func__, scd->datapos, len, bytes, scd->datalen);
if (bytes > 0) {
memcpy(buf, scd->datapos, bytes);
scd->datapos += bytes;
scd->datalen -= bytes;
assert(scd->datalen >= 0);
if (scd->datalen == 0) {
scd->datapos = 0;
}
}
trace_spice_vmc_read(bytes, len);
return bytes;
}
static SpiceCharDeviceInterface vmc_interface = {
.base.type = SPICE_INTERFACE_CHAR_DEVICE,
.base.description = "spice virtual channel char device",
.base.major_version = SPICE_INTERFACE_CHAR_DEVICE_MAJOR,
.base.minor_version = SPICE_INTERFACE_CHAR_DEVICE_MINOR,
.write = vmc_write,
.read = vmc_read,
};
static void vmc_register_interface(SpiceCharDriver *scd)
{
if (scd->active) {
return;
}
dprintf(scd, 1, "%s\n", __func__);
scd->sin.base.sif = &vmc_interface.base;
qemu_spice_add_interface(&scd->sin.base);
scd->active = true;
trace_spice_vmc_register_interface(scd);
}
static void vmc_unregister_interface(SpiceCharDriver *scd)
{
if (!scd->active) {
return;
}
dprintf(scd, 1, "%s\n", __func__);
spice_server_remove_interface(&scd->sin.base);
scd->active = false;
trace_spice_vmc_unregister_interface(scd);
}
static int spice_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
SpiceCharDriver *s = chr->opaque;
dprintf(s, 2, "%s: %d\n", __func__, len);
vmc_register_interface(s);
assert(s->datalen == 0);
if (s->bufsize < len) {
s->bufsize = len;
s->buffer = qemu_realloc(s->buffer, s->bufsize);
}
memcpy(s->buffer, buf, len);
s->datapos = s->buffer;
s->datalen = len;
spice_server_char_device_wakeup(&s->sin);
return len;
}
static void spice_chr_close(struct CharDriverState *chr)
{
SpiceCharDriver *s = chr->opaque;
printf("%s\n", __func__);
vmc_unregister_interface(s);
qemu_free(s);
}
static void print_allowed_subtypes(void)
{
const char** psubtype;
int i;
fprintf(stderr, "allowed names: ");
for(i=0, psubtype = spice_server_char_device_recognized_subtypes();
*psubtype != NULL; ++psubtype, ++i) {
if (i == 0) {
fprintf(stderr, "%s", *psubtype);
} else {
fprintf(stderr, ", %s", *psubtype);
}
}
fprintf(stderr, "\n");
}
CharDriverState *qemu_chr_open_spice(QemuOpts *opts)
{
CharDriverState *chr;
SpiceCharDriver *s;
const char* name = qemu_opt_get(opts, "name");
uint32_t debug = qemu_opt_get_number(opts, "debug", 0);
const char** psubtype = spice_server_char_device_recognized_subtypes();
const char *subtype = NULL;
if (name == NULL) {
fprintf(stderr, "spice-qemu-char: missing name parameter\n");
print_allowed_subtypes();
return NULL;
}
for(;*psubtype != NULL; ++psubtype) {
if (strcmp(name, *psubtype) == 0) {
subtype = *psubtype;
break;
}
}
if (subtype == NULL) {
fprintf(stderr, "spice-qemu-char: unsupported name\n");
print_allowed_subtypes();
return NULL;
}
chr = qemu_mallocz(sizeof(CharDriverState));
s = qemu_mallocz(sizeof(SpiceCharDriver));
s->chr = chr;
s->debug = debug;
s->active = false;
s->sin.subtype = subtype;
chr->opaque = s;
chr->chr_write = spice_chr_write;
chr->chr_close = spice_chr_close;
qemu_chr_generic_open(chr);
return chr;
}
| gpl-2.0 |
DougFirErickson/linux | kernel/auditfilter.c | 564 | 34557 | /* auditfilter.c -- filtering of audit events
*
* Copyright 2003-2004 Red Hat, Inc.
* Copyright 2005 Hewlett-Packard Development Company, L.P.
* Copyright 2005 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/audit.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/netlink.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include "audit.h"
/*
* Locking model:
*
* audit_filter_mutex:
* Synchronizes writes and blocking reads of audit's filterlist
* data. Rcu is used to traverse the filterlist and access
* contents of structs audit_entry, audit_watch and opaque
* LSM rules during filtering. If modified, these structures
* must be copied and replace their counterparts in the filterlist.
* An audit_parent struct is not accessed during filtering, so may
* be written directly provided audit_filter_mutex is held.
*/
/* Audit filter lists, defined in <linux/audit.h> */
struct list_head audit_filter_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_filter_list[0]),
LIST_HEAD_INIT(audit_filter_list[1]),
LIST_HEAD_INIT(audit_filter_list[2]),
LIST_HEAD_INIT(audit_filter_list[3]),
LIST_HEAD_INIT(audit_filter_list[4]),
LIST_HEAD_INIT(audit_filter_list[5]),
#if AUDIT_NR_FILTERS != 6
#error Fix audit_filter_list initialiser
#endif
};
static struct list_head audit_rules_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_rules_list[0]),
LIST_HEAD_INIT(audit_rules_list[1]),
LIST_HEAD_INIT(audit_rules_list[2]),
LIST_HEAD_INIT(audit_rules_list[3]),
LIST_HEAD_INIT(audit_rules_list[4]),
LIST_HEAD_INIT(audit_rules_list[5]),
};
DEFINE_MUTEX(audit_filter_mutex);
static void audit_free_lsm_field(struct audit_field *f)
{
switch (f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
kfree(f->lsm_str);
security_audit_rule_free(f->lsm_rule);
}
}
static inline void audit_free_rule(struct audit_entry *e)
{
int i;
struct audit_krule *erule = &e->rule;
/* some rules don't have associated watches */
if (erule->watch)
audit_put_watch(erule->watch);
if (erule->fields)
for (i = 0; i < erule->field_count; i++)
audit_free_lsm_field(&erule->fields[i]);
kfree(erule->fields);
kfree(erule->filterkey);
kfree(e);
}
void audit_free_rule_rcu(struct rcu_head *head)
{
struct audit_entry *e = container_of(head, struct audit_entry, rcu);
audit_free_rule(e);
}
/* Initialize an audit filterlist entry. */
static inline struct audit_entry *audit_init_entry(u32 field_count)
{
struct audit_entry *entry;
struct audit_field *fields;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (unlikely(!entry))
return NULL;
fields = kcalloc(field_count, sizeof(*fields), GFP_KERNEL);
if (unlikely(!fields)) {
kfree(entry);
return NULL;
}
entry->rule.fields = fields;
return entry;
}
/* Unpack a filter field's string representation from user-space
* buffer. */
char *audit_unpack_string(void **bufp, size_t *remain, size_t len)
{
char *str;
if (!*bufp || (len == 0) || (len > *remain))
return ERR_PTR(-EINVAL);
/* Of the currently implemented string fields, PATH_MAX
* defines the longest valid length.
*/
if (len > PATH_MAX)
return ERR_PTR(-ENAMETOOLONG);
str = kmalloc(len + 1, GFP_KERNEL);
if (unlikely(!str))
return ERR_PTR(-ENOMEM);
memcpy(str, *bufp, len);
str[len] = 0;
*bufp += len;
*remain -= len;
return str;
}
/* Translate an inode field to kernel respresentation. */
static inline int audit_to_inode(struct audit_krule *krule,
struct audit_field *f)
{
if (krule->listnr != AUDIT_FILTER_EXIT ||
krule->inode_f || krule->watch || krule->tree ||
(f->op != Audit_equal && f->op != Audit_not_equal))
return -EINVAL;
krule->inode_f = f;
return 0;
}
static __u32 *classes[AUDIT_SYSCALL_CLASSES];
int __init audit_register_class(int class, unsigned *list)
{
__u32 *p = kcalloc(AUDIT_BITMASK_SIZE, sizeof(__u32), GFP_KERNEL);
if (!p)
return -ENOMEM;
while (*list != ~0U) {
unsigned n = *list++;
if (n >= AUDIT_BITMASK_SIZE * 32 - AUDIT_SYSCALL_CLASSES) {
kfree(p);
return -EINVAL;
}
p[AUDIT_WORD(n)] |= AUDIT_BIT(n);
}
if (class >= AUDIT_SYSCALL_CLASSES || classes[class]) {
kfree(p);
return -EINVAL;
}
classes[class] = p;
return 0;
}
int audit_match_class(int class, unsigned syscall)
{
if (unlikely(syscall >= AUDIT_BITMASK_SIZE * 32))
return 0;
if (unlikely(class >= AUDIT_SYSCALL_CLASSES || !classes[class]))
return 0;
return classes[class][AUDIT_WORD(syscall)] & AUDIT_BIT(syscall);
}
#ifdef CONFIG_AUDITSYSCALL
static inline int audit_match_class_bits(int class, u32 *mask)
{
int i;
if (classes[class]) {
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (mask[i] & classes[class][i])
return 0;
}
return 1;
}
static int audit_match_signal(struct audit_entry *entry)
{
struct audit_field *arch = entry->rule.arch_f;
if (!arch) {
/* When arch is unspecified, we must check both masks on biarch
* as syscall number alone is ambiguous. */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
entry->rule.mask) &&
audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
entry->rule.mask));
}
switch(audit_classify_arch(arch->val)) {
case 0: /* native */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
entry->rule.mask));
case 1: /* 32bit on biarch */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
entry->rule.mask));
default:
return 1;
}
}
#endif
/* Common user-space to kernel rule translation. */
static inline struct audit_entry *audit_to_entry_common(struct audit_rule_data *rule)
{
unsigned listnr;
struct audit_entry *entry;
int i, err;
err = -EINVAL;
listnr = rule->flags & ~AUDIT_FILTER_PREPEND;
switch(listnr) {
default:
goto exit_err;
#ifdef CONFIG_AUDITSYSCALL
case AUDIT_FILTER_ENTRY:
if (rule->action == AUDIT_ALWAYS)
goto exit_err;
case AUDIT_FILTER_EXIT:
case AUDIT_FILTER_TASK:
#endif
case AUDIT_FILTER_USER:
case AUDIT_FILTER_TYPE:
;
}
if (unlikely(rule->action == AUDIT_POSSIBLE)) {
pr_err("AUDIT_POSSIBLE is deprecated\n");
goto exit_err;
}
if (rule->action != AUDIT_NEVER && rule->action != AUDIT_ALWAYS)
goto exit_err;
if (rule->field_count > AUDIT_MAX_FIELDS)
goto exit_err;
err = -ENOMEM;
entry = audit_init_entry(rule->field_count);
if (!entry)
goto exit_err;
entry->rule.flags = rule->flags & AUDIT_FILTER_PREPEND;
entry->rule.listnr = listnr;
entry->rule.action = rule->action;
entry->rule.field_count = rule->field_count;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
entry->rule.mask[i] = rule->mask[i];
for (i = 0; i < AUDIT_SYSCALL_CLASSES; i++) {
int bit = AUDIT_BITMASK_SIZE * 32 - i - 1;
__u32 *p = &entry->rule.mask[AUDIT_WORD(bit)];
__u32 *class;
if (!(*p & AUDIT_BIT(bit)))
continue;
*p &= ~AUDIT_BIT(bit);
class = classes[i];
if (class) {
int j;
for (j = 0; j < AUDIT_BITMASK_SIZE; j++)
entry->rule.mask[j] |= class[j];
}
}
return entry;
exit_err:
return ERR_PTR(err);
}
static u32 audit_ops[] =
{
[Audit_equal] = AUDIT_EQUAL,
[Audit_not_equal] = AUDIT_NOT_EQUAL,
[Audit_bitmask] = AUDIT_BIT_MASK,
[Audit_bittest] = AUDIT_BIT_TEST,
[Audit_lt] = AUDIT_LESS_THAN,
[Audit_gt] = AUDIT_GREATER_THAN,
[Audit_le] = AUDIT_LESS_THAN_OR_EQUAL,
[Audit_ge] = AUDIT_GREATER_THAN_OR_EQUAL,
};
static u32 audit_to_op(u32 op)
{
u32 n;
for (n = Audit_equal; n < Audit_bad && audit_ops[n] != op; n++)
;
return n;
}
/* check if an audit field is valid */
static int audit_field_valid(struct audit_entry *entry, struct audit_field *f)
{
switch(f->type) {
case AUDIT_MSGTYPE:
if (entry->rule.listnr != AUDIT_FILTER_TYPE &&
entry->rule.listnr != AUDIT_FILTER_USER)
return -EINVAL;
break;
};
switch(f->type) {
default:
return -EINVAL;
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_LOGINUID:
case AUDIT_OBJ_UID:
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
case AUDIT_PID:
case AUDIT_PERS:
case AUDIT_MSGTYPE:
case AUDIT_PPID:
case AUDIT_DEVMAJOR:
case AUDIT_DEVMINOR:
case AUDIT_EXIT:
case AUDIT_SUCCESS:
case AUDIT_INODE:
/* bit ops are only useful on syscall args */
if (f->op == Audit_bitmask || f->op == Audit_bittest)
return -EINVAL;
break;
case AUDIT_ARG0:
case AUDIT_ARG1:
case AUDIT_ARG2:
case AUDIT_ARG3:
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
case AUDIT_WATCH:
case AUDIT_DIR:
case AUDIT_FILTERKEY:
break;
case AUDIT_LOGINUID_SET:
if ((f->val != 0) && (f->val != 1))
return -EINVAL;
/* FALL THROUGH */
case AUDIT_ARCH:
if (f->op != Audit_not_equal && f->op != Audit_equal)
return -EINVAL;
break;
case AUDIT_PERM:
if (f->val & ~15)
return -EINVAL;
break;
case AUDIT_FILETYPE:
if (f->val & ~S_IFMT)
return -EINVAL;
break;
case AUDIT_FIELD_COMPARE:
if (f->val > AUDIT_MAX_FIELD_COMPARE)
return -EINVAL;
break;
};
return 0;
}
/* Translate struct audit_rule_data to kernel's rule respresentation. */
static struct audit_entry *audit_data_to_entry(struct audit_rule_data *data,
size_t datasz)
{
int err = 0;
struct audit_entry *entry;
void *bufp;
size_t remain = datasz - sizeof(struct audit_rule_data);
int i;
char *str;
entry = audit_to_entry_common(data);
if (IS_ERR(entry))
goto exit_nofree;
bufp = data->buf;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &entry->rule.fields[i];
err = -EINVAL;
f->op = audit_to_op(data->fieldflags[i]);
if (f->op == Audit_bad)
goto exit_free;
f->type = data->fields[i];
f->val = data->values[i];
/* Support legacy tests for a valid loginuid */
if ((f->type == AUDIT_LOGINUID) && (f->val == AUDIT_UID_UNSET)) {
f->type = AUDIT_LOGINUID_SET;
f->val = 0;
entry->rule.pflags |= AUDIT_LOGINUID_LEGACY;
}
err = audit_field_valid(entry, f);
if (err)
goto exit_free;
err = -EINVAL;
switch (f->type) {
case AUDIT_LOGINUID:
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_OBJ_UID:
f->uid = make_kuid(current_user_ns(), f->val);
if (!uid_valid(f->uid))
goto exit_free;
break;
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
f->gid = make_kgid(current_user_ns(), f->val);
if (!gid_valid(f->gid))
goto exit_free;
break;
case AUDIT_ARCH:
entry->rule.arch_f = f;
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = security_audit_rule_init(f->type, f->op, str,
(void **)&f->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (err == -EINVAL) {
pr_warn("audit rule for LSM \'%s\' is invalid\n",
str);
err = 0;
}
if (err) {
kfree(str);
goto exit_free;
} else
f->lsm_str = str;
break;
case AUDIT_WATCH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_to_watch(&entry->rule, str, f->val, f->op);
if (err) {
kfree(str);
goto exit_free;
}
break;
case AUDIT_DIR:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_make_tree(&entry->rule, str, f->op);
kfree(str);
if (err)
goto exit_free;
break;
case AUDIT_INODE:
err = audit_to_inode(&entry->rule, f);
if (err)
goto exit_free;
break;
case AUDIT_FILTERKEY:
if (entry->rule.filterkey || f->val > AUDIT_MAX_KEY_LEN)
goto exit_free;
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
entry->rule.filterkey = str;
break;
}
}
if (entry->rule.inode_f && entry->rule.inode_f->op == Audit_not_equal)
entry->rule.inode_f = NULL;
exit_nofree:
return entry;
exit_free:
if (entry->rule.watch)
audit_put_watch(entry->rule.watch); /* matches initial get */
if (entry->rule.tree)
audit_put_tree(entry->rule.tree); /* that's the temporary one */
audit_free_rule(entry);
return ERR_PTR(err);
}
/* Pack a filter field's string representation into data block. */
static inline size_t audit_pack_string(void **bufp, const char *str)
{
size_t len = strlen(str);
memcpy(*bufp, str, len);
*bufp += len;
return len;
}
/* Translate kernel rule respresentation to struct audit_rule_data. */
static struct audit_rule_data *audit_krule_to_data(struct audit_krule *krule)
{
struct audit_rule_data *data;
void *bufp;
int i;
data = kmalloc(sizeof(*data) + krule->buflen, GFP_KERNEL);
if (unlikely(!data))
return NULL;
memset(data, 0, sizeof(*data));
data->flags = krule->flags | krule->listnr;
data->action = krule->action;
data->field_count = krule->field_count;
bufp = data->buf;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &krule->fields[i];
data->fields[i] = f->type;
data->fieldflags[i] = audit_ops[f->op];
switch(f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
data->buflen += data->values[i] =
audit_pack_string(&bufp, f->lsm_str);
break;
case AUDIT_WATCH:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_watch_path(krule->watch));
break;
case AUDIT_DIR:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_tree_path(krule->tree));
break;
case AUDIT_FILTERKEY:
data->buflen += data->values[i] =
audit_pack_string(&bufp, krule->filterkey);
break;
case AUDIT_LOGINUID_SET:
if (krule->pflags & AUDIT_LOGINUID_LEGACY && !f->val) {
data->fields[i] = AUDIT_LOGINUID;
data->values[i] = AUDIT_UID_UNSET;
break;
}
/* fallthrough if set */
default:
data->values[i] = f->val;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++) data->mask[i] = krule->mask[i];
return data;
}
/* Compare two rules in kernel format. Considered success if rules
* don't match. */
static int audit_compare_rule(struct audit_krule *a, struct audit_krule *b)
{
int i;
if (a->flags != b->flags ||
a->pflags != b->pflags ||
a->listnr != b->listnr ||
a->action != b->action ||
a->field_count != b->field_count)
return 1;
for (i = 0; i < a->field_count; i++) {
if (a->fields[i].type != b->fields[i].type ||
a->fields[i].op != b->fields[i].op)
return 1;
switch(a->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
if (strcmp(a->fields[i].lsm_str, b->fields[i].lsm_str))
return 1;
break;
case AUDIT_WATCH:
if (strcmp(audit_watch_path(a->watch),
audit_watch_path(b->watch)))
return 1;
break;
case AUDIT_DIR:
if (strcmp(audit_tree_path(a->tree),
audit_tree_path(b->tree)))
return 1;
break;
case AUDIT_FILTERKEY:
/* both filterkeys exist based on above type compare */
if (strcmp(a->filterkey, b->filterkey))
return 1;
break;
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_LOGINUID:
case AUDIT_OBJ_UID:
if (!uid_eq(a->fields[i].uid, b->fields[i].uid))
return 1;
break;
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
if (!gid_eq(a->fields[i].gid, b->fields[i].gid))
return 1;
break;
default:
if (a->fields[i].val != b->fields[i].val)
return 1;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (a->mask[i] != b->mask[i])
return 1;
return 0;
}
/* Duplicate LSM field information. The lsm_rule is opaque, so must be
* re-initialized. */
static inline int audit_dupe_lsm_field(struct audit_field *df,
struct audit_field *sf)
{
int ret = 0;
char *lsm_str;
/* our own copy of lsm_str */
lsm_str = kstrdup(sf->lsm_str, GFP_KERNEL);
if (unlikely(!lsm_str))
return -ENOMEM;
df->lsm_str = lsm_str;
/* our own (refreshed) copy of lsm_rule */
ret = security_audit_rule_init(df->type, df->op, df->lsm_str,
(void **)&df->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (ret == -EINVAL) {
pr_warn("audit rule for LSM \'%s\' is invalid\n",
df->lsm_str);
ret = 0;
}
return ret;
}
/* Duplicate an audit rule. This will be a deep copy with the exception
* of the watch - that pointer is carried over. The LSM specific fields
* will be updated in the copy. The point is to be able to replace the old
* rule with the new rule in the filterlist, then free the old rule.
* The rlist element is undefined; list manipulations are handled apart from
* the initial copy. */
struct audit_entry *audit_dupe_rule(struct audit_krule *old)
{
u32 fcount = old->field_count;
struct audit_entry *entry;
struct audit_krule *new;
char *fk;
int i, err = 0;
entry = audit_init_entry(fcount);
if (unlikely(!entry))
return ERR_PTR(-ENOMEM);
new = &entry->rule;
new->flags = old->flags;
new->pflags = old->pflags;
new->listnr = old->listnr;
new->action = old->action;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
new->mask[i] = old->mask[i];
new->prio = old->prio;
new->buflen = old->buflen;
new->inode_f = old->inode_f;
new->field_count = old->field_count;
/*
* note that we are OK with not refcounting here; audit_match_tree()
* never dereferences tree and we can't get false positives there
* since we'd have to have rule gone from the list *and* removed
* before the chunks found by lookup had been allocated, i.e. before
* the beginning of list scan.
*/
new->tree = old->tree;
memcpy(new->fields, old->fields, sizeof(struct audit_field) * fcount);
/* deep copy this information, updating the lsm_rule fields, because
* the originals will all be freed when the old rule is freed. */
for (i = 0; i < fcount; i++) {
switch (new->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
err = audit_dupe_lsm_field(&new->fields[i],
&old->fields[i]);
break;
case AUDIT_FILTERKEY:
fk = kstrdup(old->filterkey, GFP_KERNEL);
if (unlikely(!fk))
err = -ENOMEM;
else
new->filterkey = fk;
}
if (err) {
audit_free_rule(entry);
return ERR_PTR(err);
}
}
if (old->watch) {
audit_get_watch(old->watch);
new->watch = old->watch;
}
return entry;
}
/* Find an existing audit rule.
* Caller must hold audit_filter_mutex to prevent stale rule data. */
static struct audit_entry *audit_find_rule(struct audit_entry *entry,
struct list_head **p)
{
struct audit_entry *e, *found = NULL;
struct list_head *list;
int h;
if (entry->rule.inode_f) {
h = audit_hash_ino(entry->rule.inode_f->val);
*p = list = &audit_inode_hash[h];
} else if (entry->rule.watch) {
/* we don't know the inode number, so must walk entire hash */
for (h = 0; h < AUDIT_INODE_BUCKETS; h++) {
list = &audit_inode_hash[h];
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
}
goto out;
} else {
*p = list = &audit_filter_list[entry->rule.listnr];
}
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
out:
return found;
}
static u64 prio_low = ~0ULL/2;
static u64 prio_high = ~0ULL/2 - 1;
/* Add rule to given filterlist if not a duplicate. */
static inline int audit_add_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_watch *watch = entry->rule.watch;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int err;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (e) {
mutex_unlock(&audit_filter_mutex);
err = -EEXIST;
/* normally audit_add_tree_rule() will free it on failure */
if (tree)
audit_put_tree(tree);
goto error;
}
if (watch) {
/* audit_filter_mutex is dropped and re-taken during this call */
err = audit_add_watch(&entry->rule, &list);
if (err) {
mutex_unlock(&audit_filter_mutex);
/*
* normally audit_add_tree_rule() will free it
* on failure
*/
if (tree)
audit_put_tree(tree);
goto error;
}
}
if (tree) {
err = audit_add_tree_rule(&entry->rule);
if (err) {
mutex_unlock(&audit_filter_mutex);
goto error;
}
}
entry->rule.prio = ~0ULL;
if (entry->rule.listnr == AUDIT_FILTER_EXIT) {
if (entry->rule.flags & AUDIT_FILTER_PREPEND)
entry->rule.prio = ++prio_high;
else
entry->rule.prio = --prio_low;
}
if (entry->rule.flags & AUDIT_FILTER_PREPEND) {
list_add(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_rcu(&entry->list, list);
entry->rule.flags &= ~AUDIT_FILTER_PREPEND;
} else {
list_add_tail(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_tail_rcu(&entry->list, list);
}
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules++;
if (!audit_match_signal(entry))
audit_signals++;
#endif
mutex_unlock(&audit_filter_mutex);
return 0;
error:
if (watch)
audit_put_watch(watch); /* tmp watch, matches initial get */
return err;
}
/* Remove an existing rule from filterlist. */
static inline int audit_del_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_watch *watch = entry->rule.watch;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int ret = 0;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (!e) {
mutex_unlock(&audit_filter_mutex);
ret = -ENOENT;
goto out;
}
if (e->rule.watch)
audit_remove_watch_rule(&e->rule);
if (e->rule.tree)
audit_remove_tree_rule(&e->rule);
list_del_rcu(&e->list);
list_del(&e->rule.list);
call_rcu(&e->rcu, audit_free_rule_rcu);
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules--;
if (!audit_match_signal(entry))
audit_signals--;
#endif
mutex_unlock(&audit_filter_mutex);
out:
if (watch)
audit_put_watch(watch); /* match initial get */
if (tree)
audit_put_tree(tree); /* that's the temporary one */
return ret;
}
/* List rules using struct audit_rule_data. */
static void audit_list_rules(__u32 portid, int seq, struct sk_buff_head *q)
{
struct sk_buff *skb;
struct audit_krule *r;
int i;
/* This is a blocking read, so use audit_filter_mutex instead of rcu
* iterator to sync with list writers. */
for (i=0; i<AUDIT_NR_FILTERS; i++) {
list_for_each_entry(r, &audit_rules_list[i], list) {
struct audit_rule_data *data;
data = audit_krule_to_data(r);
if (unlikely(!data))
break;
skb = audit_make_reply(portid, seq, AUDIT_LIST_RULES,
0, 1, data,
sizeof(*data) + data->buflen);
if (skb)
skb_queue_tail(q, skb);
kfree(data);
}
}
skb = audit_make_reply(portid, seq, AUDIT_LIST_RULES, 1, 1, NULL, 0);
if (skb)
skb_queue_tail(q, skb);
}
/* Log rule additions and removals */
static void audit_log_rule_change(char *action, struct audit_krule *rule, int res)
{
struct audit_buffer *ab;
uid_t loginuid = from_kuid(&init_user_ns, audit_get_loginuid(current));
unsigned int sessionid = audit_get_sessionid(current);
if (!audit_enabled)
return;
ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
if (!ab)
return;
audit_log_format(ab, "auid=%u ses=%u" ,loginuid, sessionid);
audit_log_task_context(ab);
audit_log_format(ab, " op=");
audit_log_string(ab, action);
audit_log_key(ab, rule->filterkey);
audit_log_format(ab, " list=%d res=%d", rule->listnr, res);
audit_log_end(ab);
}
/**
* audit_rule_change - apply all rules to the specified message type
* @type: audit message type
* @portid: target port id for netlink audit messages
* @seq: netlink audit message sequence (serial) number
* @data: payload data
* @datasz: size of payload data
*/
int audit_rule_change(int type, __u32 portid, int seq, void *data,
size_t datasz)
{
int err = 0;
struct audit_entry *entry;
entry = audit_data_to_entry(data, datasz);
if (IS_ERR(entry))
return PTR_ERR(entry);
switch (type) {
case AUDIT_ADD_RULE:
err = audit_add_rule(entry);
audit_log_rule_change("add_rule", &entry->rule, !err);
break;
case AUDIT_DEL_RULE:
err = audit_del_rule(entry);
audit_log_rule_change("remove_rule", &entry->rule, !err);
break;
default:
err = -EINVAL;
WARN_ON(1);
}
if (err || type == AUDIT_DEL_RULE)
audit_free_rule(entry);
return err;
}
/**
* audit_list_rules_send - list the audit rules
* @request_skb: skb of request we are replying to (used to target the reply)
* @seq: netlink audit message sequence (serial) number
*/
int audit_list_rules_send(struct sk_buff *request_skb, int seq)
{
u32 portid = NETLINK_CB(request_skb).portid;
struct net *net = sock_net(NETLINK_CB(request_skb).sk);
struct task_struct *tsk;
struct audit_netlink_list *dest;
int err = 0;
/* We can't just spew out the rules here because we might fill
* the available socket buffer space and deadlock waiting for
* auditctl to read from it... which isn't ever going to
* happen if we're actually running in the context of auditctl
* trying to _send_ the stuff */
dest = kmalloc(sizeof(struct audit_netlink_list), GFP_KERNEL);
if (!dest)
return -ENOMEM;
dest->net = get_net(net);
dest->portid = portid;
skb_queue_head_init(&dest->q);
mutex_lock(&audit_filter_mutex);
audit_list_rules(portid, seq, &dest->q);
mutex_unlock(&audit_filter_mutex);
tsk = kthread_run(audit_send_list, dest, "audit_send_list");
if (IS_ERR(tsk)) {
skb_queue_purge(&dest->q);
kfree(dest);
err = PTR_ERR(tsk);
}
return err;
}
int audit_comparator(u32 left, u32 op, u32 right)
{
switch (op) {
case Audit_equal:
return (left == right);
case Audit_not_equal:
return (left != right);
case Audit_lt:
return (left < right);
case Audit_le:
return (left <= right);
case Audit_gt:
return (left > right);
case Audit_ge:
return (left >= right);
case Audit_bitmask:
return (left & right);
case Audit_bittest:
return ((left & right) == right);
default:
BUG();
return 0;
}
}
int audit_uid_comparator(kuid_t left, u32 op, kuid_t right)
{
switch (op) {
case Audit_equal:
return uid_eq(left, right);
case Audit_not_equal:
return !uid_eq(left, right);
case Audit_lt:
return uid_lt(left, right);
case Audit_le:
return uid_lte(left, right);
case Audit_gt:
return uid_gt(left, right);
case Audit_ge:
return uid_gte(left, right);
case Audit_bitmask:
case Audit_bittest:
default:
BUG();
return 0;
}
}
int audit_gid_comparator(kgid_t left, u32 op, kgid_t right)
{
switch (op) {
case Audit_equal:
return gid_eq(left, right);
case Audit_not_equal:
return !gid_eq(left, right);
case Audit_lt:
return gid_lt(left, right);
case Audit_le:
return gid_lte(left, right);
case Audit_gt:
return gid_gt(left, right);
case Audit_ge:
return gid_gte(left, right);
case Audit_bitmask:
case Audit_bittest:
default:
BUG();
return 0;
}
}
/**
* parent_len - find the length of the parent portion of a pathname
* @path: pathname of which to determine length
*/
int parent_len(const char *path)
{
int plen;
const char *p;
plen = strlen(path);
if (plen == 0)
return plen;
/* disregard trailing slashes */
p = path + plen - 1;
while ((*p == '/') && (p > path))
p--;
/* walk backward until we find the next slash or hit beginning */
while ((*p != '/') && (p > path))
p--;
/* did we find a slash? Then increment to include it in path */
if (*p == '/')
p++;
return p - path;
}
/**
* audit_compare_dname_path - compare given dentry name with last component in
* given path. Return of 0 indicates a match.
* @dname: dentry name that we're comparing
* @path: full pathname that we're comparing
* @parentlen: length of the parent if known. Passing in AUDIT_NAME_FULL
* here indicates that we must compute this value.
*/
int audit_compare_dname_path(const char *dname, const char *path, int parentlen)
{
int dlen, pathlen;
const char *p;
dlen = strlen(dname);
pathlen = strlen(path);
if (pathlen < dlen)
return 1;
parentlen = parentlen == AUDIT_NAME_FULL ? parent_len(path) : parentlen;
if (pathlen - parentlen != dlen)
return 1;
p = path + parentlen;
return strncmp(p, dname, dlen);
}
static int audit_filter_user_rules(struct audit_krule *rule, int type,
enum audit_state *state)
{
int i;
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &rule->fields[i];
pid_t pid;
int result = 0;
u32 sid;
switch (f->type) {
case AUDIT_PID:
pid = task_pid_nr(current);
result = audit_comparator(pid, f->op, f->val);
break;
case AUDIT_UID:
result = audit_uid_comparator(current_uid(), f->op, f->uid);
break;
case AUDIT_GID:
result = audit_gid_comparator(current_gid(), f->op, f->gid);
break;
case AUDIT_LOGINUID:
result = audit_uid_comparator(audit_get_loginuid(current),
f->op, f->uid);
break;
case AUDIT_LOGINUID_SET:
result = audit_comparator(audit_loginuid_set(current),
f->op, f->val);
break;
case AUDIT_MSGTYPE:
result = audit_comparator(type, f->op, f->val);
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
if (f->lsm_rule) {
security_task_getsecid(current, &sid);
result = security_audit_rule_match(sid,
f->type,
f->op,
f->lsm_rule,
NULL);
}
break;
}
if (!result)
return 0;
}
switch (rule->action) {
case AUDIT_NEVER: *state = AUDIT_DISABLED; break;
case AUDIT_ALWAYS: *state = AUDIT_RECORD_CONTEXT; break;
}
return 1;
}
int audit_filter_user(int type)
{
enum audit_state state = AUDIT_DISABLED;
struct audit_entry *e;
int rc, ret;
ret = 1; /* Audit by default */
rcu_read_lock();
list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_USER], list) {
rc = audit_filter_user_rules(&e->rule, type, &state);
if (rc) {
if (rc > 0 && state == AUDIT_DISABLED)
ret = 0;
break;
}
}
rcu_read_unlock();
return ret;
}
int audit_filter_type(int type)
{
struct audit_entry *e;
int result = 0;
rcu_read_lock();
if (list_empty(&audit_filter_list[AUDIT_FILTER_TYPE]))
goto unlock_and_return;
list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TYPE],
list) {
int i;
for (i = 0; i < e->rule.field_count; i++) {
struct audit_field *f = &e->rule.fields[i];
if (f->type == AUDIT_MSGTYPE) {
result = audit_comparator(type, f->op, f->val);
if (!result)
break;
}
}
if (result)
goto unlock_and_return;
}
unlock_and_return:
rcu_read_unlock();
return result;
}
static int update_lsm_rule(struct audit_krule *r)
{
struct audit_entry *entry = container_of(r, struct audit_entry, rule);
struct audit_entry *nentry;
int err = 0;
if (!security_audit_rule_known(r))
return 0;
nentry = audit_dupe_rule(r);
if (IS_ERR(nentry)) {
/* save the first error encountered for the
* return value */
err = PTR_ERR(nentry);
audit_panic("error updating LSM filters");
if (r->watch)
list_del(&r->rlist);
list_del_rcu(&entry->list);
list_del(&r->list);
} else {
if (r->watch || r->tree)
list_replace_init(&r->rlist, &nentry->rule.rlist);
list_replace_rcu(&entry->list, &nentry->list);
list_replace(&r->list, &nentry->rule.list);
}
call_rcu(&entry->rcu, audit_free_rule_rcu);
return err;
}
/* This function will re-initialize the lsm_rule field of all applicable rules.
* It will traverse the filter lists serarching for rules that contain LSM
* specific filter fields. When such a rule is found, it is copied, the
* LSM field is re-initialized, and the old rule is replaced with the
* updated rule. */
int audit_update_lsm_rules(void)
{
struct audit_krule *r, *n;
int i, err = 0;
/* audit_filter_mutex synchronizes the writers */
mutex_lock(&audit_filter_mutex);
for (i = 0; i < AUDIT_NR_FILTERS; i++) {
list_for_each_entry_safe(r, n, &audit_rules_list[i], list) {
int res = update_lsm_rule(r);
if (!err)
err = res;
}
}
mutex_unlock(&audit_filter_mutex);
return err;
}
| gpl-2.0 |
softirq/linux-2.6.32.60 | drivers/media/dvb/frontends/s921_module.c | 564 | 4554 | /*
* Driver for Sharp s921 driver
*
* Copyright (C) 2008 Markus Rechberger <mrechberger@sundtek.de>
*
* All rights reserved.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include "dvb_frontend.h"
#include "s921_module.h"
#include "s921_core.h"
static unsigned int debug = 0;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug,"s921 debugging (default off)");
#define dprintk(fmt, args...) if (debug) do {\
printk("s921 debug: " fmt, ##args); } while (0)
struct s921_state
{
struct dvb_frontend frontend;
fe_modulation_t current_modulation;
__u32 snr;
__u32 current_frequency;
__u8 addr;
struct s921_isdb_t dev;
struct i2c_adapter *i2c;
};
static int s921_set_parameters(struct dvb_frontend *fe, struct dvb_frontend_parameters *param) {
struct s921_state *state = (struct s921_state *)fe->demodulator_priv;
struct s921_isdb_t_transmission_mode_params params;
struct s921_isdb_t_tune_params tune_params;
tune_params.frequency = param->frequency;
s921_isdb_cmd(&state->dev, ISDB_T_CMD_SET_PARAM, ¶ms);
s921_isdb_cmd(&state->dev, ISDB_T_CMD_TUNE, &tune_params);
mdelay(100);
return 0;
}
static int s921_init(struct dvb_frontend *fe) {
printk("s921 init\n");
return 0;
}
static int s921_sleep(struct dvb_frontend *fe) {
printk("s921 sleep\n");
return 0;
}
static int s921_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct s921_state *state = (struct s921_state *)fe->demodulator_priv;
unsigned int ret;
mdelay(5);
s921_isdb_cmd(&state->dev, ISDB_T_CMD_GET_STATUS, &ret);
*status = 0;
printk("status: %02x\n", ret);
if (ret == 1) {
*status |= FE_HAS_CARRIER;
*status |= FE_HAS_VITERBI;
*status |= FE_HAS_LOCK;
*status |= FE_HAS_SYNC;
*status |= FE_HAS_SIGNAL;
}
return 0;
}
static int s921_read_ber(struct dvb_frontend *fe, __u32 *ber)
{
dprintk("read ber\n");
return 0;
}
static int s921_read_snr(struct dvb_frontend *fe, __u16 *snr)
{
dprintk("read snr\n");
return 0;
}
static int s921_read_ucblocks(struct dvb_frontend *fe, __u32 *ucblocks)
{
dprintk("read ucblocks\n");
return 0;
}
static void s921_release(struct dvb_frontend *fe)
{
struct s921_state *state = (struct s921_state *)fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops demod_s921={
.info = {
.name = "SHARP S921",
.type = FE_OFDM,
.frequency_min = 473143000,
.frequency_max = 767143000,
.frequency_stepsize = 6000000,
.frequency_tolerance = 0,
.caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 |
FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 |
FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO | FE_CAN_RECOVER |
FE_CAN_MUTE_TS
},
.init = s921_init,
.sleep = s921_sleep,
.set_frontend = s921_set_parameters,
.read_snr = s921_read_snr,
.read_ber = s921_read_ber,
.read_status = s921_read_status,
.read_ucblocks = s921_read_ucblocks,
.release = s921_release,
};
static int s921_write(void *dev, u8 reg, u8 val) {
struct s921_state *state = dev;
char buf[2]={reg,val};
int err;
struct i2c_msg i2cmsgs = {
.addr = state->addr,
.flags = 0,
.len = 2,
.buf = buf
};
if((err = i2c_transfer(state->i2c, &i2cmsgs, 1))<0) {
printk("%s i2c_transfer error %d\n", __func__, err);
if (err < 0)
return err;
else
return -EREMOTEIO;
}
return 0;
}
static int s921_read(void *dev, u8 reg) {
struct s921_state *state = dev;
u8 b1;
int ret;
struct i2c_msg msg[2] = { { .addr = state->addr,
.flags = 0,
.buf = ®, .len = 1 },
{ .addr = state->addr,
.flags = I2C_M_RD,
.buf = &b1, .len = 1 } };
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2)
return ret;
return b1;
}
struct dvb_frontend* s921_attach(const struct s921_config *config,
struct i2c_adapter *i2c)
{
struct s921_state *state;
state = kzalloc(sizeof(struct s921_state), GFP_KERNEL);
if (state == NULL)
return NULL;
state->addr = config->i2c_address;
state->i2c = i2c;
state->dev.i2c_write = &s921_write;
state->dev.i2c_read = &s921_read;
state->dev.priv_dev = state;
s921_isdb_cmd(&state->dev, ISDB_T_CMD_INIT, NULL);
memcpy(&state->frontend.ops, &demod_s921, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
}
EXPORT_SYMBOL_GPL(s921_attach);
MODULE_AUTHOR("Markus Rechberger <mrechberger@empiatech.com>");
MODULE_DESCRIPTION("Sharp S921 ISDB-T 1Seg");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Seagate/SMR_FS-EXT4 | kernel/drivers/video/fbdev/vt8500lcdfb.c | 1332 | 12987 | /*
* linux/drivers/video/vt8500lcdfb.c
*
* Copyright (C) 2010 Alexey Charkov <alchark@gmail.com>
*
* Based on skeletonfb.c and pxafb.c
*
* 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/delay.h>
#include <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/wait.h>
#include <video/of_display_timing.h>
#include "vt8500lcdfb.h"
#include "wmt_ge_rops.h"
#ifdef CONFIG_OF
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <linux/memblock.h>
#endif
#define to_vt8500lcd_info(__info) container_of(__info, \
struct vt8500lcd_info, fb)
static int vt8500lcd_set_par(struct fb_info *info)
{
struct vt8500lcd_info *fbi = to_vt8500lcd_info(info);
int reg_bpp = 5; /* 16bpp */
int i;
unsigned long control0;
if (!fbi)
return -EINVAL;
if (info->var.bits_per_pixel <= 8) {
/* palettized */
info->var.red.offset = 0;
info->var.red.length = info->var.bits_per_pixel;
info->var.red.msb_right = 0;
info->var.green.offset = 0;
info->var.green.length = info->var.bits_per_pixel;
info->var.green.msb_right = 0;
info->var.blue.offset = 0;
info->var.blue.length = info->var.bits_per_pixel;
info->var.blue.msb_right = 0;
info->var.transp.offset = 0;
info->var.transp.length = 0;
info->var.transp.msb_right = 0;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.line_length = info->var.xres_virtual /
(8/info->var.bits_per_pixel);
} else {
/* non-palettized */
info->var.transp.offset = 0;
info->var.transp.length = 0;
info->var.transp.msb_right = 0;
if (info->var.bits_per_pixel == 16) {
/* RGB565 */
info->var.red.offset = 11;
info->var.red.length = 5;
info->var.red.msb_right = 0;
info->var.green.offset = 5;
info->var.green.length = 6;
info->var.green.msb_right = 0;
info->var.blue.offset = 0;
info->var.blue.length = 5;
info->var.blue.msb_right = 0;
} else {
/* Equal depths per channel */
info->var.red.offset = info->var.bits_per_pixel
* 2 / 3;
info->var.red.length = info->var.bits_per_pixel / 3;
info->var.red.msb_right = 0;
info->var.green.offset = info->var.bits_per_pixel / 3;
info->var.green.length = info->var.bits_per_pixel / 3;
info->var.green.msb_right = 0;
info->var.blue.offset = 0;
info->var.blue.length = info->var.bits_per_pixel / 3;
info->var.blue.msb_right = 0;
}
info->fix.visual = FB_VISUAL_TRUECOLOR;
info->fix.line_length = info->var.bits_per_pixel > 16 ?
info->var.xres_virtual << 2 :
info->var.xres_virtual << 1;
}
for (i = 0; i < 8; i++) {
if (bpp_values[i] == info->var.bits_per_pixel)
reg_bpp = i;
}
control0 = readl(fbi->regbase) & ~0xf;
writel(0, fbi->regbase);
while (readl(fbi->regbase + 0x38) & 0x10)
/* wait */;
writel((((info->var.hsync_len - 1) & 0x3f) << 26)
| ((info->var.left_margin & 0xff) << 18)
| (((info->var.xres - 1) & 0x3ff) << 8)
| (info->var.right_margin & 0xff), fbi->regbase + 0x4);
writel((((info->var.vsync_len - 1) & 0x3f) << 26)
| ((info->var.upper_margin & 0xff) << 18)
| (((info->var.yres - 1) & 0x3ff) << 8)
| (info->var.lower_margin & 0xff), fbi->regbase + 0x8);
writel((((info->var.yres - 1) & 0x400) << 2)
| ((info->var.xres - 1) & 0x400), fbi->regbase + 0x10);
writel(0x80000000, fbi->regbase + 0x20);
writel(control0 | (reg_bpp << 1) | 0x100, fbi->regbase);
return 0;
}
static inline u_int chan_to_field(u_int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int vt8500lcd_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info) {
struct vt8500lcd_info *fbi = to_vt8500lcd_info(info);
int ret = 1;
unsigned int val;
if (regno >= 256)
return -EINVAL;
if (info->var.grayscale)
red = green = blue =
(19595 * red + 38470 * green + 7471 * blue) >> 16;
switch (fbi->fb.fix.visual) {
case FB_VISUAL_TRUECOLOR:
if (regno < 16) {
u32 *pal = fbi->fb.pseudo_palette;
val = chan_to_field(red, &fbi->fb.var.red);
val |= chan_to_field(green, &fbi->fb.var.green);
val |= chan_to_field(blue, &fbi->fb.var.blue);
pal[regno] = val;
ret = 0;
}
break;
case FB_VISUAL_STATIC_PSEUDOCOLOR:
case FB_VISUAL_PSEUDOCOLOR:
writew((red & 0xf800)
| ((green >> 5) & 0x7e0)
| ((blue >> 11) & 0x1f),
fbi->palette_cpu + sizeof(u16) * regno);
break;
}
return ret;
}
static int vt8500lcd_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
int ret = 0;
struct vt8500lcd_info *fbi = to_vt8500lcd_info(info);
if (cmd == FBIO_WAITFORVSYNC) {
/* Unmask End of Frame interrupt */
writel(0xffffffff ^ (1 << 3), fbi->regbase + 0x3c);
ret = wait_event_interruptible_timeout(fbi->wait,
readl(fbi->regbase + 0x38) & (1 << 3), HZ / 10);
/* Mask back to reduce unwanted interrupt traffic */
writel(0xffffffff, fbi->regbase + 0x3c);
if (ret < 0)
return ret;
if (ret == 0)
return -ETIMEDOUT;
}
return ret;
}
static int vt8500lcd_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
unsigned pixlen = info->fix.line_length / info->var.xres_virtual;
unsigned off = pixlen * var->xoffset
+ info->fix.line_length * var->yoffset;
struct vt8500lcd_info *fbi = to_vt8500lcd_info(info);
writel((1 << 31)
| (((info->var.xres_virtual - info->var.xres) * pixlen / 4) << 20)
| (off >> 2), fbi->regbase + 0x20);
return 0;
}
/*
* vt8500lcd_blank():
* Blank the display by setting all palette values to zero. Note,
* True Color modes do not really use the palette, so this will not
* blank the display in all modes.
*/
static int vt8500lcd_blank(int blank, struct fb_info *info)
{
int i;
switch (blank) {
case FB_BLANK_POWERDOWN:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_NORMAL:
if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR ||
info->fix.visual == FB_VISUAL_STATIC_PSEUDOCOLOR)
for (i = 0; i < 256; i++)
vt8500lcd_setcolreg(i, 0, 0, 0, 0, info);
case FB_BLANK_UNBLANK:
if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR ||
info->fix.visual == FB_VISUAL_STATIC_PSEUDOCOLOR)
fb_set_cmap(&info->cmap, info);
}
return 0;
}
static struct fb_ops vt8500lcd_ops = {
.owner = THIS_MODULE,
.fb_set_par = vt8500lcd_set_par,
.fb_setcolreg = vt8500lcd_setcolreg,
.fb_fillrect = wmt_ge_fillrect,
.fb_copyarea = wmt_ge_copyarea,
.fb_imageblit = sys_imageblit,
.fb_sync = wmt_ge_sync,
.fb_ioctl = vt8500lcd_ioctl,
.fb_pan_display = vt8500lcd_pan_display,
.fb_blank = vt8500lcd_blank,
};
static irqreturn_t vt8500lcd_handle_irq(int irq, void *dev_id)
{
struct vt8500lcd_info *fbi = dev_id;
if (readl(fbi->regbase + 0x38) & (1 << 3))
wake_up_interruptible(&fbi->wait);
writel(0xffffffff, fbi->regbase + 0x38);
return IRQ_HANDLED;
}
static int vt8500lcd_probe(struct platform_device *pdev)
{
struct vt8500lcd_info *fbi;
struct resource *res;
struct display_timings *disp_timing;
void *addr;
int irq, ret;
struct fb_videomode of_mode;
u32 bpp;
dma_addr_t fb_mem_phys;
unsigned long fb_mem_len;
void *fb_mem_virt;
ret = -ENOMEM;
fbi = NULL;
fbi = devm_kzalloc(&pdev->dev, sizeof(struct vt8500lcd_info)
+ sizeof(u32) * 16, GFP_KERNEL);
if (!fbi) {
dev_err(&pdev->dev, "Failed to initialize framebuffer device\n");
return -ENOMEM;
}
strcpy(fbi->fb.fix.id, "VT8500 LCD");
fbi->fb.fix.type = FB_TYPE_PACKED_PIXELS;
fbi->fb.fix.xpanstep = 0;
fbi->fb.fix.ypanstep = 1;
fbi->fb.fix.ywrapstep = 0;
fbi->fb.fix.accel = FB_ACCEL_NONE;
fbi->fb.var.nonstd = 0;
fbi->fb.var.activate = FB_ACTIVATE_NOW;
fbi->fb.var.height = -1;
fbi->fb.var.width = -1;
fbi->fb.var.vmode = FB_VMODE_NONINTERLACED;
fbi->fb.fbops = &vt8500lcd_ops;
fbi->fb.flags = FBINFO_DEFAULT
| FBINFO_HWACCEL_COPYAREA
| FBINFO_HWACCEL_FILLRECT
| FBINFO_HWACCEL_YPAN
| FBINFO_VIRTFB
| FBINFO_PARTIAL_PAN_OK;
fbi->fb.node = -1;
addr = fbi;
addr = addr + sizeof(struct vt8500lcd_info);
fbi->fb.pseudo_palette = addr;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "no I/O memory resource defined\n");
return -ENODEV;
}
res = request_mem_region(res->start, resource_size(res), "vt8500lcd");
if (res == NULL) {
dev_err(&pdev->dev, "failed to request I/O memory\n");
return -EBUSY;
}
fbi->regbase = ioremap(res->start, resource_size(res));
if (fbi->regbase == NULL) {
dev_err(&pdev->dev, "failed to map I/O memory\n");
ret = -EBUSY;
goto failed_free_res;
}
disp_timing = of_get_display_timings(pdev->dev.of_node);
if (!disp_timing) {
ret = -EINVAL;
goto failed_free_io;
}
ret = of_get_fb_videomode(pdev->dev.of_node, &of_mode,
OF_USE_NATIVE_MODE);
if (ret)
goto failed_free_io;
ret = of_property_read_u32(pdev->dev.of_node, "bits-per-pixel", &bpp);
if (ret)
goto failed_free_io;
/* try allocating the framebuffer */
fb_mem_len = of_mode.xres * of_mode.yres * 2 * (bpp / 8);
fb_mem_virt = dma_alloc_coherent(&pdev->dev, fb_mem_len, &fb_mem_phys,
GFP_KERNEL);
if (!fb_mem_virt) {
pr_err("%s: Failed to allocate framebuffer\n", __func__);
ret = -ENOMEM;
goto failed_free_io;
}
fbi->fb.fix.smem_start = fb_mem_phys;
fbi->fb.fix.smem_len = fb_mem_len;
fbi->fb.screen_base = fb_mem_virt;
fbi->palette_size = PAGE_ALIGN(512);
fbi->palette_cpu = dma_alloc_coherent(&pdev->dev,
fbi->palette_size,
&fbi->palette_phys,
GFP_KERNEL);
if (fbi->palette_cpu == NULL) {
dev_err(&pdev->dev, "Failed to allocate palette buffer\n");
ret = -ENOMEM;
goto failed_free_io;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "no IRQ defined\n");
ret = -ENODEV;
goto failed_free_palette;
}
ret = request_irq(irq, vt8500lcd_handle_irq, 0, "LCD", fbi);
if (ret) {
dev_err(&pdev->dev, "request_irq failed: %d\n", ret);
ret = -EBUSY;
goto failed_free_palette;
}
init_waitqueue_head(&fbi->wait);
if (fb_alloc_cmap(&fbi->fb.cmap, 256, 0) < 0) {
dev_err(&pdev->dev, "Failed to allocate color map\n");
ret = -ENOMEM;
goto failed_free_irq;
}
fb_videomode_to_var(&fbi->fb.var, &of_mode);
fbi->fb.var.xres_virtual = of_mode.xres;
fbi->fb.var.yres_virtual = of_mode.yres * 2;
fbi->fb.var.bits_per_pixel = bpp;
ret = vt8500lcd_set_par(&fbi->fb);
if (ret) {
dev_err(&pdev->dev, "Failed to set parameters\n");
goto failed_free_cmap;
}
writel(fbi->fb.fix.smem_start >> 22, fbi->regbase + 0x1c);
writel((fbi->palette_phys & 0xfffffe00) | 1, fbi->regbase + 0x18);
platform_set_drvdata(pdev, fbi);
ret = register_framebuffer(&fbi->fb);
if (ret < 0) {
dev_err(&pdev->dev,
"Failed to register framebuffer device: %d\n", ret);
goto failed_free_cmap;
}
/*
* Ok, now enable the LCD controller
*/
writel(readl(fbi->regbase) | 1, fbi->regbase);
return 0;
failed_free_cmap:
if (fbi->fb.cmap.len)
fb_dealloc_cmap(&fbi->fb.cmap);
failed_free_irq:
free_irq(irq, fbi);
failed_free_palette:
dma_free_coherent(&pdev->dev, fbi->palette_size,
fbi->palette_cpu, fbi->palette_phys);
failed_free_io:
iounmap(fbi->regbase);
failed_free_res:
release_mem_region(res->start, resource_size(res));
return ret;
}
static int vt8500lcd_remove(struct platform_device *pdev)
{
struct vt8500lcd_info *fbi = platform_get_drvdata(pdev);
struct resource *res;
int irq;
unregister_framebuffer(&fbi->fb);
writel(0, fbi->regbase);
if (fbi->fb.cmap.len)
fb_dealloc_cmap(&fbi->fb.cmap);
irq = platform_get_irq(pdev, 0);
free_irq(irq, fbi);
dma_free_coherent(&pdev->dev, fbi->palette_size,
fbi->palette_cpu, fbi->palette_phys);
iounmap(fbi->regbase);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
return 0;
}
static const struct of_device_id via_dt_ids[] = {
{ .compatible = "via,vt8500-fb", },
{}
};
static struct platform_driver vt8500lcd_driver = {
.probe = vt8500lcd_probe,
.remove = vt8500lcd_remove,
.driver = {
.name = "vt8500-lcd",
.of_match_table = of_match_ptr(via_dt_ids),
},
};
module_platform_driver(vt8500lcd_driver);
MODULE_AUTHOR("Alexey Charkov <alchark@gmail.com>");
MODULE_DESCRIPTION("LCD controller driver for VIA VT8500");
MODULE_LICENSE("GPL v2");
MODULE_DEVICE_TABLE(of, via_dt_ids);
| gpl-2.0 |
XileForce/Linaro-LSK | drivers/media/common/saa7146/saa7146_video.c | 2100 | 35406 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <media/saa7146_vv.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-event.h>
#include <media/v4l2-ctrls.h>
#include <linux/module.h>
static int max_memory = 32;
module_param(max_memory, int, 0644);
MODULE_PARM_DESC(max_memory, "maximum memory usage for capture buffers (default: 32Mb)");
#define IS_CAPTURE_ACTIVE(fh) \
(((vv->video_status & STATUS_CAPTURE) != 0) && (vv->video_fh == fh))
#define IS_OVERLAY_ACTIVE(fh) \
(((vv->video_status & STATUS_OVERLAY) != 0) && (vv->video_fh == fh))
/* format descriptions for capture and preview */
static struct saa7146_format formats[] = {
{
.name = "RGB-8 (3-3-2)",
.pixelformat = V4L2_PIX_FMT_RGB332,
.trans = RGB08_COMPOSED,
.depth = 8,
.flags = 0,
}, {
.name = "RGB-16 (5/B-6/G-5/R)",
.pixelformat = V4L2_PIX_FMT_RGB565,
.trans = RGB16_COMPOSED,
.depth = 16,
.flags = 0,
}, {
.name = "RGB-24 (B-G-R)",
.pixelformat = V4L2_PIX_FMT_BGR24,
.trans = RGB24_COMPOSED,
.depth = 24,
.flags = 0,
}, {
.name = "RGB-32 (B-G-R)",
.pixelformat = V4L2_PIX_FMT_BGR32,
.trans = RGB32_COMPOSED,
.depth = 32,
.flags = 0,
}, {
.name = "RGB-32 (R-G-B)",
.pixelformat = V4L2_PIX_FMT_RGB32,
.trans = RGB32_COMPOSED,
.depth = 32,
.flags = 0,
.swap = 0x2,
}, {
.name = "Greyscale-8",
.pixelformat = V4L2_PIX_FMT_GREY,
.trans = Y8,
.depth = 8,
.flags = 0,
}, {
.name = "YUV 4:2:2 planar (Y-Cb-Cr)",
.pixelformat = V4L2_PIX_FMT_YUV422P,
.trans = YUV422_DECOMPOSED,
.depth = 16,
.flags = FORMAT_BYTE_SWAP|FORMAT_IS_PLANAR,
}, {
.name = "YVU 4:2:0 planar (Y-Cb-Cr)",
.pixelformat = V4L2_PIX_FMT_YVU420,
.trans = YUV420_DECOMPOSED,
.depth = 12,
.flags = FORMAT_BYTE_SWAP|FORMAT_IS_PLANAR,
}, {
.name = "YUV 4:2:0 planar (Y-Cb-Cr)",
.pixelformat = V4L2_PIX_FMT_YUV420,
.trans = YUV420_DECOMPOSED,
.depth = 12,
.flags = FORMAT_IS_PLANAR,
}, {
.name = "YUV 4:2:2 (U-Y-V-Y)",
.pixelformat = V4L2_PIX_FMT_UYVY,
.trans = YUV422_COMPOSED,
.depth = 16,
.flags = 0,
}
};
/* unfortunately, the saa7146 contains a bug which prevents it from doing on-the-fly byte swaps.
due to this, it's impossible to provide additional *packed* formats, which are simply byte swapped
(like V4L2_PIX_FMT_YUYV) ... 8-( */
static int NUM_FORMATS = sizeof(formats)/sizeof(struct saa7146_format);
struct saa7146_format* saa7146_format_by_fourcc(struct saa7146_dev *dev, int fourcc)
{
int i, j = NUM_FORMATS;
for (i = 0; i < j; i++) {
if (formats[i].pixelformat == fourcc) {
return formats+i;
}
}
DEB_D("unknown pixelformat:'%4.4s'\n", (char *)&fourcc);
return NULL;
}
static int vidioc_try_fmt_vid_overlay(struct file *file, void *fh, struct v4l2_format *f);
int saa7146_start_preview(struct saa7146_fh *fh)
{
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
struct v4l2_format fmt;
int ret = 0, err = 0;
DEB_EE("dev:%p, fh:%p\n", dev, fh);
/* check if we have overlay information */
if (vv->ov.fh == NULL) {
DEB_D("no overlay data available. try S_FMT first.\n");
return -EAGAIN;
}
/* check if streaming capture is running */
if (IS_CAPTURE_ACTIVE(fh) != 0) {
DEB_D("streaming capture is active\n");
return -EBUSY;
}
/* check if overlay is running */
if (IS_OVERLAY_ACTIVE(fh) != 0) {
if (vv->video_fh == fh) {
DEB_D("overlay is already active\n");
return 0;
}
DEB_D("overlay is already active in another open\n");
return -EBUSY;
}
if (0 == saa7146_res_get(fh, RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP)) {
DEB_D("cannot get necessary overlay resources\n");
return -EBUSY;
}
fmt.fmt.win = vv->ov.win;
err = vidioc_try_fmt_vid_overlay(NULL, fh, &fmt);
if (0 != err) {
saa7146_res_free(vv->video_fh, RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP);
return -EBUSY;
}
vv->ov.win = fmt.fmt.win;
DEB_D("%dx%d+%d+%d %s field=%s\n",
vv->ov.win.w.width, vv->ov.win.w.height,
vv->ov.win.w.left, vv->ov.win.w.top,
vv->ov_fmt->name, v4l2_field_names[vv->ov.win.field]);
if (0 != (ret = saa7146_enable_overlay(fh))) {
DEB_D("enabling overlay failed: %d\n", ret);
saa7146_res_free(vv->video_fh, RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP);
return ret;
}
vv->video_status = STATUS_OVERLAY;
vv->video_fh = fh;
return 0;
}
EXPORT_SYMBOL_GPL(saa7146_start_preview);
int saa7146_stop_preview(struct saa7146_fh *fh)
{
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
DEB_EE("dev:%p, fh:%p\n", dev, fh);
/* check if streaming capture is running */
if (IS_CAPTURE_ACTIVE(fh) != 0) {
DEB_D("streaming capture is active\n");
return -EBUSY;
}
/* check if overlay is running at all */
if ((vv->video_status & STATUS_OVERLAY) == 0) {
DEB_D("no active overlay\n");
return 0;
}
if (vv->video_fh != fh) {
DEB_D("overlay is active, but in another open\n");
return -EBUSY;
}
vv->video_status = 0;
vv->video_fh = NULL;
saa7146_disable_overlay(fh);
saa7146_res_free(fh, RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP);
return 0;
}
EXPORT_SYMBOL_GPL(saa7146_stop_preview);
/********************************************************************************/
/* common pagetable functions */
static int saa7146_pgtable_build(struct saa7146_dev *dev, struct saa7146_buf *buf)
{
struct pci_dev *pci = dev->pci;
struct videobuf_dmabuf *dma=videobuf_to_dma(&buf->vb);
struct scatterlist *list = dma->sglist;
int length = dma->sglen;
struct saa7146_format *sfmt = saa7146_format_by_fourcc(dev,buf->fmt->pixelformat);
DEB_EE("dev:%p, buf:%p, sg_len:%d\n", dev, buf, length);
if( 0 != IS_PLANAR(sfmt->trans)) {
struct saa7146_pgtable *pt1 = &buf->pt[0];
struct saa7146_pgtable *pt2 = &buf->pt[1];
struct saa7146_pgtable *pt3 = &buf->pt[2];
__le32 *ptr1, *ptr2, *ptr3;
__le32 fill;
int size = buf->fmt->width*buf->fmt->height;
int i,p,m1,m2,m3,o1,o2;
switch( sfmt->depth ) {
case 12: {
/* create some offsets inside the page table */
m1 = ((size+PAGE_SIZE)/PAGE_SIZE)-1;
m2 = ((size+(size/4)+PAGE_SIZE)/PAGE_SIZE)-1;
m3 = ((size+(size/2)+PAGE_SIZE)/PAGE_SIZE)-1;
o1 = size%PAGE_SIZE;
o2 = (size+(size/4))%PAGE_SIZE;
DEB_CAP("size:%d, m1:%d, m2:%d, m3:%d, o1:%d, o2:%d\n",
size, m1, m2, m3, o1, o2);
break;
}
case 16: {
/* create some offsets inside the page table */
m1 = ((size+PAGE_SIZE)/PAGE_SIZE)-1;
m2 = ((size+(size/2)+PAGE_SIZE)/PAGE_SIZE)-1;
m3 = ((2*size+PAGE_SIZE)/PAGE_SIZE)-1;
o1 = size%PAGE_SIZE;
o2 = (size+(size/2))%PAGE_SIZE;
DEB_CAP("size:%d, m1:%d, m2:%d, m3:%d, o1:%d, o2:%d\n",
size, m1, m2, m3, o1, o2);
break;
}
default: {
return -1;
}
}
ptr1 = pt1->cpu;
ptr2 = pt2->cpu;
ptr3 = pt3->cpu;
/* walk all pages, copy all page addresses to ptr1 */
for (i = 0; i < length; i++, list++) {
for (p = 0; p * 4096 < list->length; p++, ptr1++) {
*ptr1 = cpu_to_le32(sg_dma_address(list) - list->offset);
}
}
/*
ptr1 = pt1->cpu;
for(j=0;j<40;j++) {
printk("ptr1 %d: 0x%08x\n",j,ptr1[j]);
}
*/
/* if we have a user buffer, the first page may not be
aligned to a page boundary. */
pt1->offset = dma->sglist->offset;
pt2->offset = pt1->offset+o1;
pt3->offset = pt1->offset+o2;
/* create video-dma2 page table */
ptr1 = pt1->cpu;
for(i = m1; i <= m2 ; i++, ptr2++) {
*ptr2 = ptr1[i];
}
fill = *(ptr2-1);
for(;i<1024;i++,ptr2++) {
*ptr2 = fill;
}
/* create video-dma3 page table */
ptr1 = pt1->cpu;
for(i = m2; i <= m3; i++,ptr3++) {
*ptr3 = ptr1[i];
}
fill = *(ptr3-1);
for(;i<1024;i++,ptr3++) {
*ptr3 = fill;
}
/* finally: finish up video-dma1 page table */
ptr1 = pt1->cpu+m1;
fill = pt1->cpu[m1];
for(i=m1;i<1024;i++,ptr1++) {
*ptr1 = fill;
}
/*
ptr1 = pt1->cpu;
ptr2 = pt2->cpu;
ptr3 = pt3->cpu;
for(j=0;j<40;j++) {
printk("ptr1 %d: 0x%08x\n",j,ptr1[j]);
}
for(j=0;j<40;j++) {
printk("ptr2 %d: 0x%08x\n",j,ptr2[j]);
}
for(j=0;j<40;j++) {
printk("ptr3 %d: 0x%08x\n",j,ptr3[j]);
}
*/
} else {
struct saa7146_pgtable *pt = &buf->pt[0];
return saa7146_pgtable_build_single(pci, pt, list, length);
}
return 0;
}
/********************************************************************************/
/* file operations */
static int video_begin(struct saa7146_fh *fh)
{
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_format *fmt = NULL;
unsigned int resource;
int ret = 0, err = 0;
DEB_EE("dev:%p, fh:%p\n", dev, fh);
if ((vv->video_status & STATUS_CAPTURE) != 0) {
if (vv->video_fh == fh) {
DEB_S("already capturing\n");
return 0;
}
DEB_S("already capturing in another open\n");
return -EBUSY;
}
if ((vv->video_status & STATUS_OVERLAY) != 0) {
DEB_S("warning: suspending overlay video for streaming capture\n");
vv->ov_suspend = vv->video_fh;
err = saa7146_stop_preview(vv->video_fh); /* side effect: video_status is now 0, video_fh is NULL */
if (0 != err) {
DEB_D("suspending video failed. aborting\n");
return err;
}
}
fmt = saa7146_format_by_fourcc(dev, vv->video_fmt.pixelformat);
/* we need to have a valid format set here */
BUG_ON(NULL == fmt);
if (0 != (fmt->flags & FORMAT_IS_PLANAR)) {
resource = RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP|RESOURCE_DMA3_BRS;
} else {
resource = RESOURCE_DMA1_HPS;
}
ret = saa7146_res_get(fh, resource);
if (0 == ret) {
DEB_S("cannot get capture resource %d\n", resource);
if (vv->ov_suspend != NULL) {
saa7146_start_preview(vv->ov_suspend);
vv->ov_suspend = NULL;
}
return -EBUSY;
}
/* clear out beginning of streaming bit (rps register 0)*/
saa7146_write(dev, MC2, MASK_27 );
/* enable rps0 irqs */
SAA7146_IER_ENABLE(dev, MASK_27);
vv->video_fh = fh;
vv->video_status = STATUS_CAPTURE;
return 0;
}
static int video_end(struct saa7146_fh *fh, struct file *file)
{
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_format *fmt = NULL;
unsigned long flags;
unsigned int resource;
u32 dmas = 0;
DEB_EE("dev:%p, fh:%p\n", dev, fh);
if ((vv->video_status & STATUS_CAPTURE) != STATUS_CAPTURE) {
DEB_S("not capturing\n");
return 0;
}
if (vv->video_fh != fh) {
DEB_S("capturing, but in another open\n");
return -EBUSY;
}
fmt = saa7146_format_by_fourcc(dev, vv->video_fmt.pixelformat);
/* we need to have a valid format set here */
BUG_ON(NULL == fmt);
if (0 != (fmt->flags & FORMAT_IS_PLANAR)) {
resource = RESOURCE_DMA1_HPS|RESOURCE_DMA2_CLP|RESOURCE_DMA3_BRS;
dmas = MASK_22 | MASK_21 | MASK_20;
} else {
resource = RESOURCE_DMA1_HPS;
dmas = MASK_22;
}
spin_lock_irqsave(&dev->slock,flags);
/* disable rps0 */
saa7146_write(dev, MC1, MASK_28);
/* disable rps0 irqs */
SAA7146_IER_DISABLE(dev, MASK_27);
/* shut down all used video dma transfers */
saa7146_write(dev, MC1, dmas);
spin_unlock_irqrestore(&dev->slock, flags);
vv->video_fh = NULL;
vv->video_status = 0;
saa7146_res_free(fh, resource);
if (vv->ov_suspend != NULL) {
saa7146_start_preview(vv->ov_suspend);
vv->ov_suspend = NULL;
}
return 0;
}
static int vidioc_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
{
struct video_device *vdev = video_devdata(file);
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
strcpy((char *)cap->driver, "saa7146 v4l2");
strlcpy((char *)cap->card, dev->ext->name, sizeof(cap->card));
sprintf((char *)cap->bus_info, "PCI:%s", pci_name(dev->pci));
cap->device_caps =
V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VIDEO_OVERLAY |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING;
cap->device_caps |= dev->ext_vv_data->capabilities;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
if (vdev->vfl_type == VFL_TYPE_GRABBER)
cap->device_caps &=
~(V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_OUTPUT);
else
cap->device_caps &=
~(V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OVERLAY | V4L2_CAP_AUDIO);
return 0;
}
static int vidioc_g_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *fb)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
*fb = vv->ov_fb;
fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
fb->flags = V4L2_FBUF_FLAG_PRIMARY;
return 0;
}
static int vidioc_s_fbuf(struct file *file, void *fh, const struct v4l2_framebuffer *fb)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_format *fmt;
DEB_EE("VIDIOC_S_FBUF\n");
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
return -EPERM;
/* check args */
fmt = saa7146_format_by_fourcc(dev, fb->fmt.pixelformat);
if (NULL == fmt)
return -EINVAL;
/* planar formats are not allowed for overlay video, clipping and video dma would clash */
if (fmt->flags & FORMAT_IS_PLANAR)
DEB_S("planar pixelformat '%4.4s' not allowed for overlay\n",
(char *)&fmt->pixelformat);
/* check if overlay is running */
if (IS_OVERLAY_ACTIVE(fh) != 0) {
if (vv->video_fh != fh) {
DEB_D("refusing to change framebuffer informations while overlay is active in another open\n");
return -EBUSY;
}
}
/* ok, accept it */
vv->ov_fb = *fb;
vv->ov_fmt = fmt;
if (vv->ov_fb.fmt.bytesperline < vv->ov_fb.fmt.width) {
vv->ov_fb.fmt.bytesperline = vv->ov_fb.fmt.width * fmt->depth / 8;
DEB_D("setting bytesperline to %d\n", vv->ov_fb.fmt.bytesperline);
}
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *f)
{
if (f->index >= NUM_FORMATS)
return -EINVAL;
strlcpy((char *)f->description, formats[f->index].name,
sizeof(f->description));
f->pixelformat = formats[f->index].pixelformat;
return 0;
}
int saa7146_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct saa7146_dev *dev = container_of(ctrl->handler,
struct saa7146_dev, ctrl_handler);
struct saa7146_vv *vv = dev->vv_data;
u32 val;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
val = saa7146_read(dev, BCS_CTRL);
val &= 0x00ffffff;
val |= (ctrl->val << 24);
saa7146_write(dev, BCS_CTRL, val);
saa7146_write(dev, MC2, MASK_22 | MASK_06);
break;
case V4L2_CID_CONTRAST:
val = saa7146_read(dev, BCS_CTRL);
val &= 0xff00ffff;
val |= (ctrl->val << 16);
saa7146_write(dev, BCS_CTRL, val);
saa7146_write(dev, MC2, MASK_22 | MASK_06);
break;
case V4L2_CID_SATURATION:
val = saa7146_read(dev, BCS_CTRL);
val &= 0xffffff00;
val |= (ctrl->val << 0);
saa7146_write(dev, BCS_CTRL, val);
saa7146_write(dev, MC2, MASK_22 | MASK_06);
break;
case V4L2_CID_HFLIP:
/* fixme: we can support changing VFLIP and HFLIP here... */
if ((vv->video_status & STATUS_CAPTURE))
return -EBUSY;
vv->hflip = ctrl->val;
break;
case V4L2_CID_VFLIP:
if ((vv->video_status & STATUS_CAPTURE))
return -EBUSY;
vv->vflip = ctrl->val;
break;
default:
return -EINVAL;
}
if ((vv->video_status & STATUS_OVERLAY) != 0) { /* CHECK: && (vv->video_fh == fh)) */
struct saa7146_fh *fh = vv->video_fh;
saa7146_stop_preview(fh);
saa7146_start_preview(fh);
}
return 0;
}
static int vidioc_g_parm(struct file *file, void *fh,
struct v4l2_streamparm *parm)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
parm->parm.capture.readbuffers = 1;
v4l2_video_std_frame_period(vv->standard->id,
&parm->parm.capture.timeperframe);
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
f->fmt.pix = vv->video_fmt;
return 0;
}
static int vidioc_g_fmt_vid_overlay(struct file *file, void *fh, struct v4l2_format *f)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
f->fmt.win = vv->ov.win;
return 0;
}
static int vidioc_g_fmt_vbi_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
f->fmt.vbi = vv->vbi_fmt;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_format *fmt;
enum v4l2_field field;
int maxw, maxh;
int calc_bpl;
DEB_EE("V4L2_BUF_TYPE_VIDEO_CAPTURE: dev:%p, fh:%p\n", dev, fh);
fmt = saa7146_format_by_fourcc(dev, f->fmt.pix.pixelformat);
if (NULL == fmt)
return -EINVAL;
field = f->fmt.pix.field;
maxw = vv->standard->h_max_out;
maxh = vv->standard->v_max_out;
if (V4L2_FIELD_ANY == field) {
field = (f->fmt.pix.height > maxh / 2)
? V4L2_FIELD_INTERLACED
: V4L2_FIELD_BOTTOM;
}
switch (field) {
case V4L2_FIELD_ALTERNATE:
vv->last_field = V4L2_FIELD_TOP;
maxh = maxh / 2;
break;
case V4L2_FIELD_TOP:
case V4L2_FIELD_BOTTOM:
vv->last_field = V4L2_FIELD_INTERLACED;
maxh = maxh / 2;
break;
case V4L2_FIELD_INTERLACED:
vv->last_field = V4L2_FIELD_INTERLACED;
break;
default:
DEB_D("no known field mode '%d'\n", field);
return -EINVAL;
}
f->fmt.pix.field = field;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
if (f->fmt.pix.width > maxw)
f->fmt.pix.width = maxw;
if (f->fmt.pix.height > maxh)
f->fmt.pix.height = maxh;
calc_bpl = (f->fmt.pix.width * fmt->depth) / 8;
if (f->fmt.pix.bytesperline < calc_bpl)
f->fmt.pix.bytesperline = calc_bpl;
if (f->fmt.pix.bytesperline > (2 * PAGE_SIZE * fmt->depth) / 8) /* arbitrary constraint */
f->fmt.pix.bytesperline = calc_bpl;
f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * f->fmt.pix.height;
DEB_D("w:%d, h:%d, bytesperline:%d, sizeimage:%d\n",
f->fmt.pix.width, f->fmt.pix.height,
f->fmt.pix.bytesperline, f->fmt.pix.sizeimage);
return 0;
}
static int vidioc_try_fmt_vid_overlay(struct file *file, void *fh, struct v4l2_format *f)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
struct v4l2_window *win = &f->fmt.win;
enum v4l2_field field;
int maxw, maxh;
DEB_EE("dev:%p\n", dev);
if (NULL == vv->ov_fb.base) {
DEB_D("no fb base set\n");
return -EINVAL;
}
if (NULL == vv->ov_fmt) {
DEB_D("no fb fmt set\n");
return -EINVAL;
}
if (win->w.width < 48 || win->w.height < 32) {
DEB_D("min width/height. (%d,%d)\n",
win->w.width, win->w.height);
return -EINVAL;
}
if (win->clipcount > 16) {
DEB_D("clipcount too big\n");
return -EINVAL;
}
field = win->field;
maxw = vv->standard->h_max_out;
maxh = vv->standard->v_max_out;
if (V4L2_FIELD_ANY == field) {
field = (win->w.height > maxh / 2)
? V4L2_FIELD_INTERLACED
: V4L2_FIELD_TOP;
}
switch (field) {
case V4L2_FIELD_TOP:
case V4L2_FIELD_BOTTOM:
case V4L2_FIELD_ALTERNATE:
maxh = maxh / 2;
break;
case V4L2_FIELD_INTERLACED:
break;
default:
DEB_D("no known field mode '%d'\n", field);
return -EINVAL;
}
win->field = field;
if (win->w.width > maxw)
win->w.width = maxw;
if (win->w.height > maxh)
win->w.height = maxh;
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *__fh, struct v4l2_format *f)
{
struct saa7146_fh *fh = __fh;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
int err;
DEB_EE("V4L2_BUF_TYPE_VIDEO_CAPTURE: dev:%p, fh:%p\n", dev, fh);
if (IS_CAPTURE_ACTIVE(fh) != 0) {
DEB_EE("streaming capture is active\n");
return -EBUSY;
}
err = vidioc_try_fmt_vid_cap(file, fh, f);
if (0 != err)
return err;
vv->video_fmt = f->fmt.pix;
DEB_EE("set to pixelformat '%4.4s'\n",
(char *)&vv->video_fmt.pixelformat);
return 0;
}
static int vidioc_s_fmt_vid_overlay(struct file *file, void *__fh, struct v4l2_format *f)
{
struct saa7146_fh *fh = __fh;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
int err;
DEB_EE("V4L2_BUF_TYPE_VIDEO_OVERLAY: dev:%p, fh:%p\n", dev, fh);
err = vidioc_try_fmt_vid_overlay(file, fh, f);
if (0 != err)
return err;
vv->ov.win = f->fmt.win;
vv->ov.nclips = f->fmt.win.clipcount;
if (vv->ov.nclips > 16)
vv->ov.nclips = 16;
if (copy_from_user(vv->ov.clips, f->fmt.win.clips,
sizeof(struct v4l2_clip) * vv->ov.nclips)) {
return -EFAULT;
}
/* vv->ov.fh is used to indicate that we have valid overlay informations, too */
vv->ov.fh = fh;
/* check if our current overlay is active */
if (IS_OVERLAY_ACTIVE(fh) != 0) {
saa7146_stop_preview(fh);
saa7146_start_preview(fh);
}
return 0;
}
static int vidioc_g_std(struct file *file, void *fh, v4l2_std_id *norm)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
*norm = vv->standard->id;
return 0;
}
/* the saa7146 supfhrts (used in conjunction with the saa7111a for example)
PAL / NTSC / SECAM. if your hardware does not (or does more)
-- override this function in your extension */
/*
case VIDIOC_ENUMSTD:
{
struct v4l2_standard *e = arg;
if (e->index < 0 )
return -EINVAL;
if( e->index < dev->ext_vv_data->num_stds ) {
DEB_EE("VIDIOC_ENUMSTD: index:%d\n", e->index);
v4l2_video_std_construct(e, dev->ext_vv_data->stds[e->index].id, dev->ext_vv_data->stds[e->index].name);
return 0;
}
return -EINVAL;
}
*/
static int vidioc_s_std(struct file *file, void *fh, v4l2_std_id id)
{
struct saa7146_dev *dev = ((struct saa7146_fh *)fh)->dev;
struct saa7146_vv *vv = dev->vv_data;
int found = 0;
int err, i;
DEB_EE("VIDIOC_S_STD\n");
if ((vv->video_status & STATUS_CAPTURE) == STATUS_CAPTURE) {
DEB_D("cannot change video standard while streaming capture is active\n");
return -EBUSY;
}
if ((vv->video_status & STATUS_OVERLAY) != 0) {
vv->ov_suspend = vv->video_fh;
err = saa7146_stop_preview(vv->video_fh); /* side effect: video_status is now 0, video_fh is NULL */
if (0 != err) {
DEB_D("suspending video failed. aborting\n");
return err;
}
}
for (i = 0; i < dev->ext_vv_data->num_stds; i++)
if (id & dev->ext_vv_data->stds[i].id)
break;
if (i != dev->ext_vv_data->num_stds) {
vv->standard = &dev->ext_vv_data->stds[i];
if (NULL != dev->ext_vv_data->std_callback)
dev->ext_vv_data->std_callback(dev, vv->standard);
found = 1;
}
if (vv->ov_suspend != NULL) {
saa7146_start_preview(vv->ov_suspend);
vv->ov_suspend = NULL;
}
if (!found) {
DEB_EE("VIDIOC_S_STD: standard not found\n");
return -EINVAL;
}
DEB_EE("VIDIOC_S_STD: set to standard to '%s'\n", vv->standard->name);
return 0;
}
static int vidioc_overlay(struct file *file, void *fh, unsigned int on)
{
int err;
DEB_D("VIDIOC_OVERLAY on:%d\n", on);
if (on)
err = saa7146_start_preview(fh);
else
err = saa7146_stop_preview(fh);
return err;
}
static int vidioc_reqbufs(struct file *file, void *__fh, struct v4l2_requestbuffers *b)
{
struct saa7146_fh *fh = __fh;
if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return videobuf_reqbufs(&fh->video_q, b);
if (b->type == V4L2_BUF_TYPE_VBI_CAPTURE)
return videobuf_reqbufs(&fh->vbi_q, b);
return -EINVAL;
}
static int vidioc_querybuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct saa7146_fh *fh = __fh;
if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return videobuf_querybuf(&fh->video_q, buf);
if (buf->type == V4L2_BUF_TYPE_VBI_CAPTURE)
return videobuf_querybuf(&fh->vbi_q, buf);
return -EINVAL;
}
static int vidioc_qbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct saa7146_fh *fh = __fh;
if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return videobuf_qbuf(&fh->video_q, buf);
if (buf->type == V4L2_BUF_TYPE_VBI_CAPTURE)
return videobuf_qbuf(&fh->vbi_q, buf);
return -EINVAL;
}
static int vidioc_dqbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct saa7146_fh *fh = __fh;
if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return videobuf_dqbuf(&fh->video_q, buf, file->f_flags & O_NONBLOCK);
if (buf->type == V4L2_BUF_TYPE_VBI_CAPTURE)
return videobuf_dqbuf(&fh->vbi_q, buf, file->f_flags & O_NONBLOCK);
return -EINVAL;
}
static int vidioc_streamon(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct saa7146_fh *fh = __fh;
int err;
DEB_D("VIDIOC_STREAMON, type:%d\n", type);
err = video_begin(fh);
if (err)
return err;
if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return videobuf_streamon(&fh->video_q);
if (type == V4L2_BUF_TYPE_VBI_CAPTURE)
return videobuf_streamon(&fh->vbi_q);
return -EINVAL;
}
static int vidioc_streamoff(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct saa7146_fh *fh = __fh;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
int err;
DEB_D("VIDIOC_STREAMOFF, type:%d\n", type);
/* ugly: we need to copy some checks from video_end(),
because videobuf_streamoff() relies on the capture running.
check and fix this */
if ((vv->video_status & STATUS_CAPTURE) != STATUS_CAPTURE) {
DEB_S("not capturing\n");
return 0;
}
if (vv->video_fh != fh) {
DEB_S("capturing, but in another open\n");
return -EBUSY;
}
err = -EINVAL;
if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
err = videobuf_streamoff(&fh->video_q);
else if (type == V4L2_BUF_TYPE_VBI_CAPTURE)
err = videobuf_streamoff(&fh->vbi_q);
if (0 != err) {
DEB_D("warning: videobuf_streamoff() failed\n");
video_end(fh, file);
} else {
err = video_end(fh, file);
}
return err;
}
static int vidioc_g_chip_ident(struct file *file, void *__fh,
struct v4l2_dbg_chip_ident *chip)
{
struct saa7146_fh *fh = __fh;
struct saa7146_dev *dev = fh->dev;
chip->ident = V4L2_IDENT_NONE;
chip->revision = 0;
if (chip->match.type == V4L2_CHIP_MATCH_HOST) {
if (v4l2_chip_match_host(&chip->match))
chip->ident = V4L2_IDENT_SAA7146;
return 0;
}
if (chip->match.type != V4L2_CHIP_MATCH_I2C_DRIVER &&
chip->match.type != V4L2_CHIP_MATCH_I2C_ADDR)
return -EINVAL;
return v4l2_device_call_until_err(&dev->v4l2_dev, 0,
core, g_chip_ident, chip);
}
const struct v4l2_ioctl_ops saa7146_video_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_enum_fmt_vid_overlay = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_g_fmt_vid_overlay = vidioc_g_fmt_vid_overlay,
.vidioc_try_fmt_vid_overlay = vidioc_try_fmt_vid_overlay,
.vidioc_s_fmt_vid_overlay = vidioc_s_fmt_vid_overlay,
.vidioc_g_chip_ident = vidioc_g_chip_ident,
.vidioc_overlay = vidioc_overlay,
.vidioc_g_fbuf = vidioc_g_fbuf,
.vidioc_s_fbuf = vidioc_s_fbuf,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
const struct v4l2_ioctl_ops saa7146_vbi_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_g_chip_ident = vidioc_g_chip_ident,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
/*********************************************************************************/
/* buffer handling functions */
static int buffer_activate (struct saa7146_dev *dev,
struct saa7146_buf *buf,
struct saa7146_buf *next)
{
struct saa7146_vv *vv = dev->vv_data;
buf->vb.state = VIDEOBUF_ACTIVE;
saa7146_set_capture(dev,buf,next);
mod_timer(&vv->video_dmaq.timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
static void release_all_pagetables(struct saa7146_dev *dev, struct saa7146_buf *buf)
{
saa7146_pgtable_free(dev->pci, &buf->pt[0]);
saa7146_pgtable_free(dev->pci, &buf->pt[1]);
saa7146_pgtable_free(dev->pci, &buf->pt[2]);
}
static int buffer_prepare(struct videobuf_queue *q,
struct videobuf_buffer *vb, enum v4l2_field field)
{
struct file *file = q->priv_data;
struct saa7146_fh *fh = file->private_data;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_buf *buf = (struct saa7146_buf *)vb;
int size,err = 0;
DEB_CAP("vbuf:%p\n", vb);
/* sanity checks */
if (vv->video_fmt.width < 48 ||
vv->video_fmt.height < 32 ||
vv->video_fmt.width > vv->standard->h_max_out ||
vv->video_fmt.height > vv->standard->v_max_out) {
DEB_D("w (%d) / h (%d) out of bounds\n",
vv->video_fmt.width, vv->video_fmt.height);
return -EINVAL;
}
size = vv->video_fmt.sizeimage;
if (0 != buf->vb.baddr && buf->vb.bsize < size) {
DEB_D("size mismatch\n");
return -EINVAL;
}
DEB_CAP("buffer_prepare [size=%dx%d,bytes=%d,fields=%s]\n",
vv->video_fmt.width, vv->video_fmt.height,
size, v4l2_field_names[vv->video_fmt.field]);
if (buf->vb.width != vv->video_fmt.width ||
buf->vb.bytesperline != vv->video_fmt.bytesperline ||
buf->vb.height != vv->video_fmt.height ||
buf->vb.size != size ||
buf->vb.field != field ||
buf->vb.field != vv->video_fmt.field ||
buf->fmt != &vv->video_fmt) {
saa7146_dma_free(dev,q,buf);
}
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
struct saa7146_format *sfmt;
buf->vb.bytesperline = vv->video_fmt.bytesperline;
buf->vb.width = vv->video_fmt.width;
buf->vb.height = vv->video_fmt.height;
buf->vb.size = size;
buf->vb.field = field;
buf->fmt = &vv->video_fmt;
buf->vb.field = vv->video_fmt.field;
sfmt = saa7146_format_by_fourcc(dev,buf->fmt->pixelformat);
release_all_pagetables(dev, buf);
if( 0 != IS_PLANAR(sfmt->trans)) {
saa7146_pgtable_alloc(dev->pci, &buf->pt[0]);
saa7146_pgtable_alloc(dev->pci, &buf->pt[1]);
saa7146_pgtable_alloc(dev->pci, &buf->pt[2]);
} else {
saa7146_pgtable_alloc(dev->pci, &buf->pt[0]);
}
err = videobuf_iolock(q,&buf->vb, &vv->ov_fb);
if (err)
goto oops;
err = saa7146_pgtable_build(dev,buf);
if (err)
goto oops;
}
buf->vb.state = VIDEOBUF_PREPARED;
buf->activate = buffer_activate;
return 0;
oops:
DEB_D("error out\n");
saa7146_dma_free(dev,q,buf);
return err;
}
static int buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
{
struct file *file = q->priv_data;
struct saa7146_fh *fh = file->private_data;
struct saa7146_vv *vv = fh->dev->vv_data;
if (0 == *count || *count > MAX_SAA7146_CAPTURE_BUFFERS)
*count = MAX_SAA7146_CAPTURE_BUFFERS;
*size = vv->video_fmt.sizeimage;
/* check if we exceed the "max_memory" parameter */
if( (*count * *size) > (max_memory*1048576) ) {
*count = (max_memory*1048576) / *size;
}
DEB_CAP("%d buffers, %d bytes each\n", *count, *size);
return 0;
}
static void buffer_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
struct file *file = q->priv_data;
struct saa7146_fh *fh = file->private_data;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_buf *buf = (struct saa7146_buf *)vb;
DEB_CAP("vbuf:%p\n", vb);
saa7146_buffer_queue(fh->dev, &vv->video_dmaq, buf);
}
static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
struct file *file = q->priv_data;
struct saa7146_fh *fh = file->private_data;
struct saa7146_dev *dev = fh->dev;
struct saa7146_buf *buf = (struct saa7146_buf *)vb;
DEB_CAP("vbuf:%p\n", vb);
saa7146_dma_free(dev,q,buf);
release_all_pagetables(dev, buf);
}
static struct videobuf_queue_ops video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/********************************************************************************/
/* file operations */
static void video_init(struct saa7146_dev *dev, struct saa7146_vv *vv)
{
INIT_LIST_HEAD(&vv->video_dmaq.queue);
init_timer(&vv->video_dmaq.timeout);
vv->video_dmaq.timeout.function = saa7146_buffer_timeout;
vv->video_dmaq.timeout.data = (unsigned long)(&vv->video_dmaq);
vv->video_dmaq.dev = dev;
/* set some default values */
vv->standard = &dev->ext_vv_data->stds[0];
/* FIXME: what's this? */
vv->current_hps_source = SAA7146_HPS_SOURCE_PORT_A;
vv->current_hps_sync = SAA7146_HPS_SYNC_PORT_A;
}
static int video_open(struct saa7146_dev *dev, struct file *file)
{
struct saa7146_fh *fh = file->private_data;
videobuf_queue_sg_init(&fh->video_q, &video_qops,
&dev->pci->dev, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_INTERLACED,
sizeof(struct saa7146_buf),
file, &dev->v4l2_lock);
return 0;
}
static void video_close(struct saa7146_dev *dev, struct file *file)
{
struct saa7146_fh *fh = file->private_data;
struct saa7146_vv *vv = dev->vv_data;
struct videobuf_queue *q = &fh->video_q;
if (IS_CAPTURE_ACTIVE(fh) != 0)
video_end(fh, file);
else if (IS_OVERLAY_ACTIVE(fh) != 0)
saa7146_stop_preview(fh);
videobuf_stop(q);
/* hmm, why is this function declared void? */
}
static void video_irq_done(struct saa7146_dev *dev, unsigned long st)
{
struct saa7146_vv *vv = dev->vv_data;
struct saa7146_dmaqueue *q = &vv->video_dmaq;
spin_lock(&dev->slock);
DEB_CAP("called\n");
/* only finish the buffer if we have one... */
if( NULL != q->curr ) {
saa7146_buffer_finish(dev,q,VIDEOBUF_DONE);
}
saa7146_buffer_next(dev,q,0);
spin_unlock(&dev->slock);
}
static ssize_t video_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
{
struct saa7146_fh *fh = file->private_data;
struct saa7146_dev *dev = fh->dev;
struct saa7146_vv *vv = dev->vv_data;
ssize_t ret = 0;
DEB_EE("called\n");
if ((vv->video_status & STATUS_CAPTURE) != 0) {
/* fixme: should we allow read() captures while streaming capture? */
if (vv->video_fh == fh) {
DEB_S("already capturing\n");
return -EBUSY;
}
DEB_S("already capturing in another open\n");
return -EBUSY;
}
ret = video_begin(fh);
if( 0 != ret) {
goto out;
}
ret = videobuf_read_one(&fh->video_q , data, count, ppos,
file->f_flags & O_NONBLOCK);
if (ret != 0) {
video_end(fh, file);
} else {
ret = video_end(fh, file);
}
out:
/* restart overlay if it was active before */
if (vv->ov_suspend != NULL) {
saa7146_start_preview(vv->ov_suspend);
vv->ov_suspend = NULL;
}
return ret;
}
struct saa7146_use_ops saa7146_video_uops = {
.init = video_init,
.open = video_open,
.release = video_close,
.irq_done = video_irq_done,
.read = video_read,
};
| gpl-2.0 |
MingquanLiang/linux | scripts/kconfig/lxdialog/textbox.c | 3380 | 9206 | /*
* textbox.c -- implements the text box
*
* ORIGINAL AUTHOR: Savio Lam (lam836@cs.cuhk.hk)
* MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap (roadcap@cfw.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 "dialog.h"
static void back_lines(int n);
static void print_page(WINDOW *win, int height, int width, update_text_fn
update_text, void *data);
static void print_line(WINDOW *win, int row, int width);
static char *get_line(void);
static void print_position(WINDOW * win);
static int hscroll;
static int begin_reached, end_reached, page_length;
static char *buf;
static char *page;
/*
* refresh window content
*/
static void refresh_text_box(WINDOW *dialog, WINDOW *box, int boxh, int boxw,
int cur_y, int cur_x, update_text_fn update_text,
void *data)
{
print_page(box, boxh, boxw, update_text, data);
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
/*
* Display text from a file in a dialog box.
*
* keys is a null-terminated array
* update_text() may not add or remove any '\n' or '\0' in tbuf
*/
int dialog_textbox(const char *title, char *tbuf, int initial_height,
int initial_width, int *keys, int *_vscroll, int *_hscroll,
update_text_fn update_text, void *data)
{
int i, x, y, cur_x, cur_y, key = 0;
int height, width, boxh, boxw;
WINDOW *dialog, *box;
bool done = false;
begin_reached = 1;
end_reached = 0;
page_length = 0;
hscroll = 0;
buf = tbuf;
page = buf; /* page is pointer to start of page to be displayed */
if (_vscroll && *_vscroll) {
begin_reached = 0;
for (i = 0; i < *_vscroll; i++)
get_line();
}
if (_hscroll)
hscroll = *_hscroll;
do_resize:
getmaxyx(stdscr, height, width);
if (height < TEXTBOX_HEIGTH_MIN || width < TEXTBOX_WIDTH_MIN)
return -ERRDISPLAYTOOSMALL;
if (initial_height != 0)
height = initial_height;
else
if (height > 4)
height -= 4;
else
height = 0;
if (initial_width != 0)
width = initial_width;
else
if (width > 5)
width -= 5;
else
width = 0;
/* center dialog box on screen */
x = (getmaxx(stdscr) - width) / 2;
y = (getmaxy(stdscr) - height) / 2;
draw_shadow(stdscr, y, x, height, width);
dialog = newwin(height, width, y, x);
keypad(dialog, TRUE);
/* Create window for box region, used for scrolling text */
boxh = height - 4;
boxw = width - 2;
box = subwin(dialog, boxh, boxw, y + 1, x + 1);
wattrset(box, dlg.dialog.atr);
wbkgdset(box, dlg.dialog.atr & A_COLOR);
keypad(box, TRUE);
/* register the new window, along with its borders */
draw_box(dialog, 0, 0, height, width,
dlg.dialog.atr, dlg.border.atr);
wattrset(dialog, dlg.border.atr);
mvwaddch(dialog, height - 3, 0, ACS_LTEE);
for (i = 0; i < width - 2; i++)
waddch(dialog, ACS_HLINE);
wattrset(dialog, dlg.dialog.atr);
wbkgdset(dialog, dlg.dialog.atr & A_COLOR);
waddch(dialog, ACS_RTEE);
print_title(dialog, title, width);
print_button(dialog, gettext(" Exit "), height - 2, width / 2 - 4, TRUE);
wnoutrefresh(dialog);
getyx(dialog, cur_y, cur_x); /* Save cursor position */
/* Print first page of text */
attr_clear(box, boxh, boxw, dlg.dialog.atr);
refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x, update_text,
data);
while (!done) {
key = wgetch(dialog);
switch (key) {
case 'E': /* Exit */
case 'e':
case 'X':
case 'x':
case 'q':
case '\n':
done = true;
break;
case 'g': /* First page */
case KEY_HOME:
if (!begin_reached) {
begin_reached = 1;
page = buf;
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x, update_text,
data);
}
break;
case 'G': /* Last page */
case KEY_END:
end_reached = 1;
/* point to last char in buf */
page = buf + strlen(buf);
back_lines(boxh);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case 'K': /* Previous line */
case 'k':
case KEY_UP:
if (begin_reached)
break;
back_lines(page_length + 1);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case 'B': /* Previous page */
case 'b':
case 'u':
case KEY_PPAGE:
if (begin_reached)
break;
back_lines(page_length + boxh);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case 'J': /* Next line */
case 'j':
case KEY_DOWN:
if (end_reached)
break;
back_lines(page_length - 1);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case KEY_NPAGE: /* Next page */
case ' ':
case 'd':
if (end_reached)
break;
begin_reached = 0;
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case '0': /* Beginning of line */
case 'H': /* Scroll left */
case 'h':
case KEY_LEFT:
if (hscroll <= 0)
break;
if (key == '0')
hscroll = 0;
else
hscroll--;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case 'L': /* Scroll right */
case 'l':
case KEY_RIGHT:
if (hscroll >= MAX_LEN)
break;
hscroll++;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw, cur_y,
cur_x, update_text, data);
break;
case KEY_ESC:
if (on_key_esc(dialog) == KEY_ESC)
done = true;
break;
case KEY_RESIZE:
back_lines(height);
delwin(box);
delwin(dialog);
on_key_resize();
goto do_resize;
default:
for (i = 0; keys[i]; i++) {
if (key == keys[i]) {
done = true;
break;
}
}
}
}
delwin(box);
delwin(dialog);
if (_vscroll) {
const char *s;
s = buf;
*_vscroll = 0;
back_lines(page_length);
while (s < page && (s = strchr(s, '\n'))) {
(*_vscroll)++;
s++;
}
}
if (_hscroll)
*_hscroll = hscroll;
return key;
}
/*
* Go back 'n' lines in text. Called by dialog_textbox().
* 'page' will be updated to point to the desired line in 'buf'.
*/
static void back_lines(int n)
{
int i;
begin_reached = 0;
/* Go back 'n' lines */
for (i = 0; i < n; i++) {
if (*page == '\0') {
if (end_reached) {
end_reached = 0;
continue;
}
}
if (page == buf) {
begin_reached = 1;
return;
}
page--;
do {
if (page == buf) {
begin_reached = 1;
return;
}
page--;
} while (*page != '\n');
page++;
}
}
/*
* Print a new page of text.
*/
static void print_page(WINDOW *win, int height, int width, update_text_fn
update_text, void *data)
{
int i, passed_end = 0;
if (update_text) {
char *end;
for (i = 0; i < height; i++)
get_line();
end = page;
back_lines(height);
update_text(buf, page - buf, end - buf, data);
}
page_length = 0;
for (i = 0; i < height; i++) {
print_line(win, i, width);
if (!passed_end)
page_length++;
if (end_reached && !passed_end)
passed_end = 1;
}
wnoutrefresh(win);
}
/*
* Print a new line of text.
*/
static void print_line(WINDOW * win, int row, int width)
{
char *line;
line = get_line();
line += MIN(strlen(line), hscroll); /* Scroll horizontally */
wmove(win, row, 0); /* move cursor to correct line */
waddch(win, ' ');
waddnstr(win, line, MIN(strlen(line), width - 2));
/* Clear 'residue' of previous line */
#if OLD_NCURSES
{
int x = getcurx(win);
int i;
for (i = 0; i < width - x; i++)
waddch(win, ' ');
}
#else
wclrtoeol(win);
#endif
}
/*
* Return current line of text. Called by dialog_textbox() and print_line().
* 'page' should point to start of current line before calling, and will be
* updated to point to start of next line.
*/
static char *get_line(void)
{
int i = 0;
static char line[MAX_LEN + 1];
end_reached = 0;
while (*page != '\n') {
if (*page == '\0') {
end_reached = 1;
break;
} else if (i < MAX_LEN)
line[i++] = *(page++);
else {
/* Truncate lines longer than MAX_LEN characters */
if (i == MAX_LEN)
line[i++] = '\0';
page++;
}
}
if (i <= MAX_LEN)
line[i] = '\0';
if (!end_reached)
page++; /* move past '\n' */
return line;
}
/*
* Print current position
*/
static void print_position(WINDOW * win)
{
int percent;
wattrset(win, dlg.position_indicator.atr);
wbkgdset(win, dlg.position_indicator.atr & A_COLOR);
percent = (page - buf) * 100 / strlen(buf);
wmove(win, getmaxy(win) - 3, getmaxx(win) - 9);
wprintw(win, "(%3d%%)", percent);
}
| gpl-2.0 |
crdroid-devices/android_kernel_htc_msm8974 | arch/cris/kernel/ptrace.c | 4404 | 1050 | /*
* linux/arch/cris/kernel/ptrace.c
*
* Parts taken from the m68k port.
*
* Copyright (c) 2000, 2001, 2002 Axis Communications AB
*
* Authors: Bjorn Wesen
*
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/user.h>
#include <linux/tracehook.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
/* notification of userspace execution resumption
* - triggered by current->work.notify_resume
*/
extern int do_signal(int canrestart, struct pt_regs *regs);
void do_notify_resume(int canrestart, struct pt_regs *regs,
__u32 thread_info_flags)
{
/* deal with pending signal delivery */
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(canrestart,regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
}
| gpl-2.0 |
119/aircam-openwrt | build_dir/toolchain-arm_v5te_gcc-linaro_uClibc-0.9.32_eabi/linux-2.6.28.fa2/arch/arm/mach-footbridge/personal-pci.c | 4404 | 1400 | /*
* linux/arch/arm/mach-footbridge/personal-pci.c
*
* PCI bios-type initialisation for PCI machines
*
* Bits taken from various places.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/irq.h>
#include <asm/mach/pci.h>
#include <asm/mach-types.h>
static int irqmap_personal_server[] __initdata = {
IRQ_IN0, IRQ_IN1, IRQ_IN2, IRQ_IN3, 0, 0, 0,
IRQ_DOORBELLHOST, IRQ_DMA1, IRQ_DMA2, IRQ_PCI
};
static int __init personal_server_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
unsigned char line;
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &line);
if (line > 0x40 && line <= 0x5f) {
/* line corresponds to the bit controlling this interrupt
* in the footbridge. Ignore the first 8 interrupt bits,
* look up the rest in the map. IN0 is bit number 8
*/
return irqmap_personal_server[(line & 0x1f) - 8];
} else if (line == 0) {
/* no interrupt */
return 0;
} else
return irqmap_personal_server[(line - 1) & 3];
}
static struct hw_pci personal_server_pci __initdata = {
.map_irq = personal_server_map_irq,
.nr_controllers = 1,
.setup = dc21285_setup,
.scan = dc21285_scan_bus,
.preinit = dc21285_preinit,
.postinit = dc21285_postinit,
};
static int __init personal_pci_init(void)
{
if (machine_is_personal_server())
pci_common_init(&personal_server_pci);
return 0;
}
subsys_initcall(personal_pci_init);
| gpl-2.0 |
F4uzan/lge-kernel-lproj | arch/s390/appldata/appldata_net_sum.c | 7732 | 4252 | /*
* arch/s390/appldata/appldata_net_sum.c
*
* Data gathering module for Linux-VM Monitor Stream, Stage 1.
* Collects accumulated network statistics (Packets received/transmitted,
* dropped, errors, ...).
*
* Copyright (C) 2003,2006 IBM Corporation, IBM Deutschland Entwicklung GmbH.
*
* Author: Gerald Schaefer <gerald.schaefer@de.ibm.com>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel_stat.h>
#include <linux/netdevice.h>
#include <net/net_namespace.h>
#include "appldata.h"
/*
* Network data
*
* This is accessed as binary data by z/VM. If changes to it can't be avoided,
* the structure version (product ID, see appldata_base.c) needs to be changed
* as well and all documentation and z/VM applications using it must be updated.
*
* The record layout is documented in the Linux for zSeries Device Drivers
* book:
* http://oss.software.ibm.com/developerworks/opensource/linux390/index.shtml
*/
static struct appldata_net_sum_data {
u64 timestamp;
u32 sync_count_1; /* after VM collected the record data, */
u32 sync_count_2; /* sync_count_1 and sync_count_2 should be the
same. If not, the record has been updated on
the Linux side while VM was collecting the
(possibly corrupt) data */
u32 nr_interfaces; /* nr. of network interfaces being monitored */
u32 padding; /* next value is 64-bit aligned, so these */
/* 4 byte would be padded out by compiler */
u64 rx_packets; /* total packets received */
u64 tx_packets; /* total packets transmitted */
u64 rx_bytes; /* total bytes received */
u64 tx_bytes; /* total bytes transmitted */
u64 rx_errors; /* bad packets received */
u64 tx_errors; /* packet transmit problems */
u64 rx_dropped; /* no space in linux buffers */
u64 tx_dropped; /* no space available in linux */
u64 collisions; /* collisions while transmitting */
} __attribute__((packed)) appldata_net_sum_data;
/*
* appldata_get_net_sum_data()
*
* gather accumulated network statistics
*/
static void appldata_get_net_sum_data(void *data)
{
int i;
struct appldata_net_sum_data *net_data;
struct net_device *dev;
unsigned long rx_packets, tx_packets, rx_bytes, tx_bytes, rx_errors,
tx_errors, rx_dropped, tx_dropped, collisions;
net_data = data;
net_data->sync_count_1++;
i = 0;
rx_packets = 0;
tx_packets = 0;
rx_bytes = 0;
tx_bytes = 0;
rx_errors = 0;
tx_errors = 0;
rx_dropped = 0;
tx_dropped = 0;
collisions = 0;
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
const struct rtnl_link_stats64 *stats;
struct rtnl_link_stats64 temp;
stats = dev_get_stats(dev, &temp);
rx_packets += stats->rx_packets;
tx_packets += stats->tx_packets;
rx_bytes += stats->rx_bytes;
tx_bytes += stats->tx_bytes;
rx_errors += stats->rx_errors;
tx_errors += stats->tx_errors;
rx_dropped += stats->rx_dropped;
tx_dropped += stats->tx_dropped;
collisions += stats->collisions;
i++;
}
rcu_read_unlock();
net_data->nr_interfaces = i;
net_data->rx_packets = rx_packets;
net_data->tx_packets = tx_packets;
net_data->rx_bytes = rx_bytes;
net_data->tx_bytes = tx_bytes;
net_data->rx_errors = rx_errors;
net_data->tx_errors = tx_errors;
net_data->rx_dropped = rx_dropped;
net_data->tx_dropped = tx_dropped;
net_data->collisions = collisions;
net_data->timestamp = get_clock();
net_data->sync_count_2++;
}
static struct appldata_ops ops = {
.name = "net_sum",
.record_nr = APPLDATA_RECORD_NET_SUM_ID,
.size = sizeof(struct appldata_net_sum_data),
.callback = &appldata_get_net_sum_data,
.data = &appldata_net_sum_data,
.owner = THIS_MODULE,
.mod_lvl = {0xF0, 0xF0}, /* EBCDIC "00" */
};
/*
* appldata_net_init()
*
* init data, register ops
*/
static int __init appldata_net_init(void)
{
return appldata_register_ops(&ops);
}
/*
* appldata_net_exit()
*
* unregister ops
*/
static void __exit appldata_net_exit(void)
{
appldata_unregister_ops(&ops);
}
module_init(appldata_net_init);
module_exit(appldata_net_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Gerald Schaefer");
MODULE_DESCRIPTION("Linux-VM Monitor Stream, accumulated network statistics");
| gpl-2.0 |
nimengyu2/ti-a8-linux-04.06.00.07 | fs/ocfs2/symlink.c | 7988 | 4177 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* linux/cluster/ssi/cfs/symlink.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE
* or NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Questions/Comments/Bugfixes to ssic-linux-devel@lists.sourceforge.net
*
* Copyright (C) 1992 Rick Sladkey
*
* Optimization changes Copyright (C) 1994 Florian La Roche
*
* Jun 7 1999, cache symlink lookups in the page cache. -DaveM
*
* Portions Copyright (C) 2001 Compaq Computer Corporation
*
* ocfs2 symlink handling code.
*
* Copyright (C) 2004, 2005 Oracle.
*
*/
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/namei.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "file.h"
#include "inode.h"
#include "journal.h"
#include "symlink.h"
#include "xattr.h"
#include "buffer_head_io.h"
static char *ocfs2_fast_symlink_getlink(struct inode *inode,
struct buffer_head **bh)
{
int status;
char *link = NULL;
struct ocfs2_dinode *fe;
status = ocfs2_read_inode_block(inode, bh);
if (status < 0) {
mlog_errno(status);
link = ERR_PTR(status);
goto bail;
}
fe = (struct ocfs2_dinode *) (*bh)->b_data;
link = (char *) fe->id2.i_symlink;
bail:
return link;
}
static int ocfs2_readlink(struct dentry *dentry,
char __user *buffer,
int buflen)
{
int ret;
char *link;
struct buffer_head *bh = NULL;
struct inode *inode = dentry->d_inode;
link = ocfs2_fast_symlink_getlink(inode, &bh);
if (IS_ERR(link)) {
ret = PTR_ERR(link);
goto out;
}
/*
* Without vfsmount we can't update atime now,
* but we will update atime here ultimately.
*/
ret = vfs_readlink(dentry, buffer, buflen, link);
brelse(bh);
out:
if (ret < 0)
mlog_errno(ret);
return ret;
}
static void *ocfs2_fast_follow_link(struct dentry *dentry,
struct nameidata *nd)
{
int status = 0;
int len;
char *target, *link = ERR_PTR(-ENOMEM);
struct inode *inode = dentry->d_inode;
struct buffer_head *bh = NULL;
BUG_ON(!ocfs2_inode_is_fast_symlink(inode));
target = ocfs2_fast_symlink_getlink(inode, &bh);
if (IS_ERR(target)) {
status = PTR_ERR(target);
mlog_errno(status);
goto bail;
}
/* Fast symlinks can't be large */
len = strnlen(target, ocfs2_fast_symlink_chars(inode->i_sb));
link = kzalloc(len + 1, GFP_NOFS);
if (!link) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
memcpy(link, target, len);
bail:
nd_set_link(nd, status ? ERR_PTR(status) : link);
brelse(bh);
if (status)
mlog_errno(status);
return NULL;
}
static void ocfs2_fast_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
char *link = nd_get_link(nd);
if (!IS_ERR(link))
kfree(link);
}
const struct inode_operations ocfs2_symlink_inode_operations = {
.readlink = page_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
.getattr = ocfs2_getattr,
.setattr = ocfs2_setattr,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ocfs2_listxattr,
.removexattr = generic_removexattr,
.fiemap = ocfs2_fiemap,
};
const struct inode_operations ocfs2_fast_symlink_inode_operations = {
.readlink = ocfs2_readlink,
.follow_link = ocfs2_fast_follow_link,
.put_link = ocfs2_fast_put_link,
.getattr = ocfs2_getattr,
.setattr = ocfs2_setattr,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ocfs2_listxattr,
.removexattr = generic_removexattr,
.fiemap = ocfs2_fiemap,
};
| gpl-2.0 |
NoelMacwan/SXDNickiKernels | fs/ocfs2/symlink.c | 7988 | 4177 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* linux/cluster/ssi/cfs/symlink.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE
* or NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Questions/Comments/Bugfixes to ssic-linux-devel@lists.sourceforge.net
*
* Copyright (C) 1992 Rick Sladkey
*
* Optimization changes Copyright (C) 1994 Florian La Roche
*
* Jun 7 1999, cache symlink lookups in the page cache. -DaveM
*
* Portions Copyright (C) 2001 Compaq Computer Corporation
*
* ocfs2 symlink handling code.
*
* Copyright (C) 2004, 2005 Oracle.
*
*/
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/namei.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "file.h"
#include "inode.h"
#include "journal.h"
#include "symlink.h"
#include "xattr.h"
#include "buffer_head_io.h"
static char *ocfs2_fast_symlink_getlink(struct inode *inode,
struct buffer_head **bh)
{
int status;
char *link = NULL;
struct ocfs2_dinode *fe;
status = ocfs2_read_inode_block(inode, bh);
if (status < 0) {
mlog_errno(status);
link = ERR_PTR(status);
goto bail;
}
fe = (struct ocfs2_dinode *) (*bh)->b_data;
link = (char *) fe->id2.i_symlink;
bail:
return link;
}
static int ocfs2_readlink(struct dentry *dentry,
char __user *buffer,
int buflen)
{
int ret;
char *link;
struct buffer_head *bh = NULL;
struct inode *inode = dentry->d_inode;
link = ocfs2_fast_symlink_getlink(inode, &bh);
if (IS_ERR(link)) {
ret = PTR_ERR(link);
goto out;
}
/*
* Without vfsmount we can't update atime now,
* but we will update atime here ultimately.
*/
ret = vfs_readlink(dentry, buffer, buflen, link);
brelse(bh);
out:
if (ret < 0)
mlog_errno(ret);
return ret;
}
static void *ocfs2_fast_follow_link(struct dentry *dentry,
struct nameidata *nd)
{
int status = 0;
int len;
char *target, *link = ERR_PTR(-ENOMEM);
struct inode *inode = dentry->d_inode;
struct buffer_head *bh = NULL;
BUG_ON(!ocfs2_inode_is_fast_symlink(inode));
target = ocfs2_fast_symlink_getlink(inode, &bh);
if (IS_ERR(target)) {
status = PTR_ERR(target);
mlog_errno(status);
goto bail;
}
/* Fast symlinks can't be large */
len = strnlen(target, ocfs2_fast_symlink_chars(inode->i_sb));
link = kzalloc(len + 1, GFP_NOFS);
if (!link) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
memcpy(link, target, len);
bail:
nd_set_link(nd, status ? ERR_PTR(status) : link);
brelse(bh);
if (status)
mlog_errno(status);
return NULL;
}
static void ocfs2_fast_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
char *link = nd_get_link(nd);
if (!IS_ERR(link))
kfree(link);
}
const struct inode_operations ocfs2_symlink_inode_operations = {
.readlink = page_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
.getattr = ocfs2_getattr,
.setattr = ocfs2_setattr,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ocfs2_listxattr,
.removexattr = generic_removexattr,
.fiemap = ocfs2_fiemap,
};
const struct inode_operations ocfs2_fast_symlink_inode_operations = {
.readlink = ocfs2_readlink,
.follow_link = ocfs2_fast_follow_link,
.put_link = ocfs2_fast_put_link,
.getattr = ocfs2_getattr,
.setattr = ocfs2_setattr,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ocfs2_listxattr,
.removexattr = generic_removexattr,
.fiemap = ocfs2_fiemap,
};
| gpl-2.0 |
garwynn/L900_NE2_Kernel | net/activity_stats.c | 7988 | 2833 | /* net/activity_stats.c
*
* Copyright (C) 2010 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.
*
* Author: Mike Chan (mike@android.com)
*/
#include <linux/proc_fs.h>
#include <linux/suspend.h>
#include <net/net_namespace.h>
/*
* Track transmission rates in buckets (power of 2).
* 1,2,4,8...512 seconds.
*
* Buckets represent the count of network transmissions at least
* N seconds apart, where N is 1 << bucket index.
*/
#define BUCKET_MAX 10
/* Track network activity frequency */
static unsigned long activity_stats[BUCKET_MAX];
static ktime_t last_transmit;
static ktime_t suspend_time;
static DEFINE_SPINLOCK(activity_lock);
void activity_stats_update(void)
{
int i;
unsigned long flags;
ktime_t now;
s64 delta;
spin_lock_irqsave(&activity_lock, flags);
now = ktime_get();
delta = ktime_to_ns(ktime_sub(now, last_transmit));
for (i = BUCKET_MAX - 1; i >= 0; i--) {
/*
* Check if the time delta between network activity is within the
* minimum bucket range.
*/
if (delta < (1000000000ULL << i))
continue;
activity_stats[i]++;
last_transmit = now;
break;
}
spin_unlock_irqrestore(&activity_lock, flags);
}
static int activity_stats_read_proc(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
int i;
int len;
char *p = page;
/* Only print if offset is 0, or we have enough buffer space */
if (off || count < (30 * BUCKET_MAX + 22))
return -ENOMEM;
len = snprintf(p, count, "Min Bucket(sec) Count\n");
count -= len;
p += len;
for (i = 0; i < BUCKET_MAX; i++) {
len = snprintf(p, count, "%15d %lu\n", 1 << i, activity_stats[i]);
count -= len;
p += len;
}
*eof = 1;
return p - page;
}
static int activity_stats_notifier(struct notifier_block *nb,
unsigned long event, void *dummy)
{
switch (event) {
case PM_SUSPEND_PREPARE:
suspend_time = ktime_get_real();
break;
case PM_POST_SUSPEND:
suspend_time = ktime_sub(ktime_get_real(), suspend_time);
last_transmit = ktime_sub(last_transmit, suspend_time);
}
return 0;
}
static struct notifier_block activity_stats_notifier_block = {
.notifier_call = activity_stats_notifier,
};
static int __init activity_stats_init(void)
{
create_proc_read_entry("activity", S_IRUGO,
init_net.proc_net_stat, activity_stats_read_proc, NULL);
return register_pm_notifier(&activity_stats_notifier_block);
}
subsys_initcall(activity_stats_init);
| gpl-2.0 |
Orion116/kernel_samsung_lt03wifi_rebase | crypto/tea.c | 10036 | 7253 | /*
* Cryptographic API.
*
* TEA, XTEA, and XETA crypto alogrithms
*
* The TEA and Xtended TEA algorithms were developed by David Wheeler
* and Roger Needham at the Computer Laboratory of Cambridge University.
*
* Due to the order of evaluation in XTEA many people have incorrectly
* implemented it. XETA (XTEA in the wrong order), exists for
* compatibility with these implementations.
*
* Copyright (c) 2004 Aaron Grothe ajgrothe@yahoo.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/init.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <asm/byteorder.h>
#include <linux/crypto.h>
#include <linux/types.h>
#define TEA_KEY_SIZE 16
#define TEA_BLOCK_SIZE 8
#define TEA_ROUNDS 32
#define TEA_DELTA 0x9e3779b9
#define XTEA_KEY_SIZE 16
#define XTEA_BLOCK_SIZE 8
#define XTEA_ROUNDS 32
#define XTEA_DELTA 0x9e3779b9
struct tea_ctx {
u32 KEY[4];
};
struct xtea_ctx {
u32 KEY[4];
};
static int tea_setkey(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *key = (const __le32 *)in_key;
ctx->KEY[0] = le32_to_cpu(key[0]);
ctx->KEY[1] = le32_to_cpu(key[1]);
ctx->KEY[2] = le32_to_cpu(key[2]);
ctx->KEY[3] = le32_to_cpu(key[3]);
return 0;
}
static void tea_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, n, sum = 0;
u32 k0, k1, k2, k3;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
k0 = ctx->KEY[0];
k1 = ctx->KEY[1];
k2 = ctx->KEY[2];
k3 = ctx->KEY[3];
n = TEA_ROUNDS;
while (n-- > 0) {
sum += TEA_DELTA;
y += ((z << 4) + k0) ^ (z + sum) ^ ((z >> 5) + k1);
z += ((y << 4) + k2) ^ (y + sum) ^ ((y >> 5) + k3);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void tea_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, n, sum;
u32 k0, k1, k2, k3;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
k0 = ctx->KEY[0];
k1 = ctx->KEY[1];
k2 = ctx->KEY[2];
k3 = ctx->KEY[3];
sum = TEA_DELTA << 5;
n = TEA_ROUNDS;
while (n-- > 0) {
z -= ((y << 4) + k2) ^ (y + sum) ^ ((y >> 5) + k3);
y -= ((z << 4) + k0) ^ (z + sum) ^ ((z >> 5) + k1);
sum -= TEA_DELTA;
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static int xtea_setkey(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *key = (const __le32 *)in_key;
ctx->KEY[0] = le32_to_cpu(key[0]);
ctx->KEY[1] = le32_to_cpu(key[1]);
ctx->KEY[2] = le32_to_cpu(key[2]);
ctx->KEY[3] = le32_to_cpu(key[3]);
return 0;
}
static void xtea_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum = 0;
u32 limit = XTEA_DELTA * XTEA_ROUNDS;
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
while (sum != limit) {
y += ((z << 4 ^ z >> 5) + z) ^ (sum + ctx->KEY[sum&3]);
sum += XTEA_DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + ctx->KEY[sum>>11 &3]);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xtea_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
sum = XTEA_DELTA * XTEA_ROUNDS;
while (sum) {
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + ctx->KEY[sum>>11 & 3]);
sum -= XTEA_DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + ctx->KEY[sum & 3]);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xeta_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum = 0;
u32 limit = XTEA_DELTA * XTEA_ROUNDS;
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
while (sum != limit) {
y += (z << 4 ^ z >> 5) + (z ^ sum) + ctx->KEY[sum&3];
sum += XTEA_DELTA;
z += (y << 4 ^ y >> 5) + (y ^ sum) + ctx->KEY[sum>>11 &3];
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xeta_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
sum = XTEA_DELTA * XTEA_ROUNDS;
while (sum) {
z -= (y << 4 ^ y >> 5) + (y ^ sum) + ctx->KEY[sum>>11 & 3];
sum -= XTEA_DELTA;
y -= (z << 4 ^ z >> 5) + (z ^ sum) + ctx->KEY[sum & 3];
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static struct crypto_alg tea_alg = {
.cra_name = "tea",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = TEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct tea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(tea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = TEA_KEY_SIZE,
.cia_max_keysize = TEA_KEY_SIZE,
.cia_setkey = tea_setkey,
.cia_encrypt = tea_encrypt,
.cia_decrypt = tea_decrypt } }
};
static struct crypto_alg xtea_alg = {
.cra_name = "xtea",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = XTEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct xtea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(xtea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = XTEA_KEY_SIZE,
.cia_max_keysize = XTEA_KEY_SIZE,
.cia_setkey = xtea_setkey,
.cia_encrypt = xtea_encrypt,
.cia_decrypt = xtea_decrypt } }
};
static struct crypto_alg xeta_alg = {
.cra_name = "xeta",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = XTEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct xtea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(xtea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = XTEA_KEY_SIZE,
.cia_max_keysize = XTEA_KEY_SIZE,
.cia_setkey = xtea_setkey,
.cia_encrypt = xeta_encrypt,
.cia_decrypt = xeta_decrypt } }
};
static int __init tea_mod_init(void)
{
int ret = 0;
ret = crypto_register_alg(&tea_alg);
if (ret < 0)
goto out;
ret = crypto_register_alg(&xtea_alg);
if (ret < 0) {
crypto_unregister_alg(&tea_alg);
goto out;
}
ret = crypto_register_alg(&xeta_alg);
if (ret < 0) {
crypto_unregister_alg(&tea_alg);
crypto_unregister_alg(&xtea_alg);
goto out;
}
out:
return ret;
}
static void __exit tea_mod_fini(void)
{
crypto_unregister_alg(&tea_alg);
crypto_unregister_alg(&xtea_alg);
crypto_unregister_alg(&xeta_alg);
}
MODULE_ALIAS("xtea");
MODULE_ALIAS("xeta");
module_init(tea_mod_init);
module_exit(tea_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TEA, XTEA & XETA Cryptographic Algorithms");
| gpl-2.0 |
walac/linux | drivers/net/ethernet/intel/ice/ice_dcb_lib.c | 53 | 23720 | // SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2019, Intel Corporation. */
#include "ice_dcb_lib.h"
#include "ice_dcb_nl.h"
/**
* ice_vsi_cfg_netdev_tc - Setup the netdev TC configuration
* @vsi: the VSI being configured
* @ena_tc: TC map to be enabled
*/
void ice_vsi_cfg_netdev_tc(struct ice_vsi *vsi, u8 ena_tc)
{
struct net_device *netdev = vsi->netdev;
struct ice_pf *pf = vsi->back;
struct ice_dcbx_cfg *dcbcfg;
u8 netdev_tc;
int i;
if (!netdev)
return;
if (!ena_tc) {
netdev_reset_tc(netdev);
return;
}
if (netdev_set_num_tc(netdev, vsi->tc_cfg.numtc))
return;
dcbcfg = &pf->hw.port_info->local_dcbx_cfg;
ice_for_each_traffic_class(i)
if (vsi->tc_cfg.ena_tc & BIT(i))
netdev_set_tc_queue(netdev,
vsi->tc_cfg.tc_info[i].netdev_tc,
vsi->tc_cfg.tc_info[i].qcount_tx,
vsi->tc_cfg.tc_info[i].qoffset);
for (i = 0; i < ICE_MAX_USER_PRIORITY; i++) {
u8 ets_tc = dcbcfg->etscfg.prio_table[i];
/* Get the mapped netdev TC# for the UP */
netdev_tc = vsi->tc_cfg.tc_info[ets_tc].netdev_tc;
netdev_set_prio_tc_map(netdev, i, netdev_tc);
}
}
/**
* ice_dcb_get_ena_tc - return bitmap of enabled TCs
* @dcbcfg: DCB config to evaluate for enabled TCs
*/
u8 ice_dcb_get_ena_tc(struct ice_dcbx_cfg *dcbcfg)
{
u8 i, num_tc, ena_tc = 1;
num_tc = ice_dcb_get_num_tc(dcbcfg);
for (i = 0; i < num_tc; i++)
ena_tc |= BIT(i);
return ena_tc;
}
/**
* ice_is_pfc_causing_hung_q
* @pf: pointer to PF structure
* @txqueue: Tx queue which is supposedly hung queue
*
* find if PFC is causing the hung queue, if yes return true else false
*/
bool ice_is_pfc_causing_hung_q(struct ice_pf *pf, unsigned int txqueue)
{
u8 num_tcs = 0, i, tc, up_mapped_tc, up_in_tc = 0;
u64 ref_prio_xoff[ICE_MAX_UP];
struct ice_vsi *vsi;
u32 up2tc;
vsi = ice_get_main_vsi(pf);
if (!vsi)
return false;
ice_for_each_traffic_class(i)
if (vsi->tc_cfg.ena_tc & BIT(i))
num_tcs++;
/* first find out the TC to which the hung queue belongs to */
for (tc = 0; tc < num_tcs - 1; tc++)
if (ice_find_q_in_range(vsi->tc_cfg.tc_info[tc].qoffset,
vsi->tc_cfg.tc_info[tc + 1].qoffset,
txqueue))
break;
/* Build a bit map of all UPs associated to the suspect hung queue TC,
* so that we check for its counter increment.
*/
up2tc = rd32(&pf->hw, PRTDCB_TUP2TC);
for (i = 0; i < ICE_MAX_UP; i++) {
up_mapped_tc = (up2tc >> (i * 3)) & 0x7;
if (up_mapped_tc == tc)
up_in_tc |= BIT(i);
}
/* Now that we figured out that hung queue is PFC enabled, still the
* Tx timeout can be legitimate. So to make sure Tx timeout is
* absolutely caused by PFC storm, check if the counters are
* incrementing.
*/
for (i = 0; i < ICE_MAX_UP; i++)
if (up_in_tc & BIT(i))
ref_prio_xoff[i] = pf->stats.priority_xoff_rx[i];
ice_update_dcb_stats(pf);
for (i = 0; i < ICE_MAX_UP; i++)
if (up_in_tc & BIT(i))
if (pf->stats.priority_xoff_rx[i] > ref_prio_xoff[i])
return true;
return false;
}
/**
* ice_dcb_get_mode - gets the DCB mode
* @port_info: pointer to port info structure
* @host: if set it's HOST if not it's MANAGED
*/
static u8 ice_dcb_get_mode(struct ice_port_info *port_info, bool host)
{
u8 mode;
if (host)
mode = DCB_CAP_DCBX_HOST;
else
mode = DCB_CAP_DCBX_LLD_MANAGED;
if (port_info->local_dcbx_cfg.dcbx_mode & ICE_DCBX_MODE_CEE)
return mode | DCB_CAP_DCBX_VER_CEE;
else
return mode | DCB_CAP_DCBX_VER_IEEE;
}
/**
* ice_dcb_get_num_tc - Get the number of TCs from DCBX config
* @dcbcfg: config to retrieve number of TCs from
*/
u8 ice_dcb_get_num_tc(struct ice_dcbx_cfg *dcbcfg)
{
bool tc_unused = false;
u8 num_tc = 0;
u8 ret = 0;
int i;
/* Scan the ETS Config Priority Table to find traffic classes
* enabled and create a bitmask of enabled TCs
*/
for (i = 0; i < CEE_DCBX_MAX_PRIO; i++)
num_tc |= BIT(dcbcfg->etscfg.prio_table[i]);
/* Scan bitmask for contiguous TCs starting with TC0 */
for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) {
if (num_tc & BIT(i)) {
if (!tc_unused) {
ret++;
} else {
pr_err("Non-contiguous TCs - Disabling DCB\n");
return 1;
}
} else {
tc_unused = true;
}
}
/* There is always at least 1 TC */
if (!ret)
ret = 1;
return ret;
}
/**
* ice_dcb_get_tc - Get the TC associated with the queue
* @vsi: ptr to the VSI
* @queue_index: queue number associated with VSI
*/
u8 ice_dcb_get_tc(struct ice_vsi *vsi, int queue_index)
{
return vsi->tx_rings[queue_index]->dcb_tc;
}
/**
* ice_vsi_cfg_dcb_rings - Update rings to reflect DCB TC
* @vsi: VSI owner of rings being updated
*/
void ice_vsi_cfg_dcb_rings(struct ice_vsi *vsi)
{
struct ice_ring *tx_ring, *rx_ring;
u16 qoffset, qcount;
int i, n;
if (!test_bit(ICE_FLAG_DCB_ENA, vsi->back->flags)) {
/* Reset the TC information */
for (i = 0; i < vsi->num_txq; i++) {
tx_ring = vsi->tx_rings[i];
tx_ring->dcb_tc = 0;
}
for (i = 0; i < vsi->num_rxq; i++) {
rx_ring = vsi->rx_rings[i];
rx_ring->dcb_tc = 0;
}
return;
}
ice_for_each_traffic_class(n) {
if (!(vsi->tc_cfg.ena_tc & BIT(n)))
break;
qoffset = vsi->tc_cfg.tc_info[n].qoffset;
qcount = vsi->tc_cfg.tc_info[n].qcount_tx;
for (i = qoffset; i < (qoffset + qcount); i++) {
tx_ring = vsi->tx_rings[i];
rx_ring = vsi->rx_rings[i];
tx_ring->dcb_tc = n;
rx_ring->dcb_tc = n;
}
}
}
/**
* ice_dcb_bwchk - check if ETS bandwidth input parameters are correct
* @pf: pointer to the PF struct
* @dcbcfg: pointer to DCB config structure
*/
int ice_dcb_bwchk(struct ice_pf *pf, struct ice_dcbx_cfg *dcbcfg)
{
struct ice_dcb_ets_cfg *etscfg = &dcbcfg->etscfg;
u8 num_tc, total_bw = 0;
int i;
/* returns number of contigous TCs and 1 TC for non-contigous TCs,
* since at least 1 TC has to be configured
*/
num_tc = ice_dcb_get_num_tc(dcbcfg);
/* no bandwidth checks required if there's only one TC, so assign
* all bandwidth to TC0 and return
*/
if (num_tc == 1) {
etscfg->tcbwtable[0] = ICE_TC_MAX_BW;
return 0;
}
for (i = 0; i < num_tc; i++)
total_bw += etscfg->tcbwtable[i];
if (!total_bw) {
etscfg->tcbwtable[0] = ICE_TC_MAX_BW;
} else if (total_bw != ICE_TC_MAX_BW) {
dev_err(ice_pf_to_dev(pf), "Invalid config, total bandwidth must equal 100\n");
return -EINVAL;
}
return 0;
}
/**
* ice_pf_dcb_cfg - Apply new DCB configuration
* @pf: pointer to the PF struct
* @new_cfg: DCBX config to apply
* @locked: is the RTNL held
*/
int ice_pf_dcb_cfg(struct ice_pf *pf, struct ice_dcbx_cfg *new_cfg, bool locked)
{
struct ice_aqc_port_ets_elem buf = { 0 };
struct ice_dcbx_cfg *old_cfg, *curr_cfg;
struct device *dev = ice_pf_to_dev(pf);
int ret = ICE_DCB_NO_HW_CHG;
struct ice_vsi *pf_vsi;
curr_cfg = &pf->hw.port_info->local_dcbx_cfg;
/* FW does not care if change happened */
if (!pf->hw.port_info->is_sw_lldp)
ret = ICE_DCB_HW_CHG_RST;
/* Enable DCB tagging only when more than one TC */
if (ice_dcb_get_num_tc(new_cfg) > 1) {
dev_dbg(dev, "DCB tagging enabled (num TC > 1)\n");
set_bit(ICE_FLAG_DCB_ENA, pf->flags);
} else {
dev_dbg(dev, "DCB tagging disabled (num TC = 1)\n");
clear_bit(ICE_FLAG_DCB_ENA, pf->flags);
}
if (!memcmp(new_cfg, curr_cfg, sizeof(*new_cfg))) {
dev_dbg(dev, "No change in DCB config required\n");
return ret;
}
if (ice_dcb_bwchk(pf, new_cfg))
return -EINVAL;
/* Store old config in case FW config fails */
old_cfg = kmemdup(curr_cfg, sizeof(*old_cfg), GFP_KERNEL);
if (!old_cfg)
return -ENOMEM;
dev_info(dev, "Commit DCB Configuration to the hardware\n");
pf_vsi = ice_get_main_vsi(pf);
if (!pf_vsi) {
dev_dbg(dev, "PF VSI doesn't exist\n");
ret = -EINVAL;
goto free_cfg;
}
/* avoid race conditions by holding the lock while disabling and
* re-enabling the VSI
*/
if (!locked)
rtnl_lock();
ice_dis_vsi(pf_vsi, true);
memcpy(curr_cfg, new_cfg, sizeof(*curr_cfg));
memcpy(&curr_cfg->etsrec, &curr_cfg->etscfg, sizeof(curr_cfg->etsrec));
memcpy(&new_cfg->etsrec, &curr_cfg->etscfg, sizeof(curr_cfg->etsrec));
/* Only send new config to HW if we are in SW LLDP mode. Otherwise,
* the new config came from the HW in the first place.
*/
if (pf->hw.port_info->is_sw_lldp) {
ret = ice_set_dcb_cfg(pf->hw.port_info);
if (ret) {
dev_err(dev, "Set DCB Config failed\n");
/* Restore previous settings to local config */
memcpy(curr_cfg, old_cfg, sizeof(*curr_cfg));
goto out;
}
}
ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL);
if (ret) {
dev_err(dev, "Query Port ETS failed\n");
goto out;
}
ice_pf_dcb_recfg(pf);
out:
ice_ena_vsi(pf_vsi, true);
if (!locked)
rtnl_unlock();
free_cfg:
kfree(old_cfg);
return ret;
}
/**
* ice_cfg_etsrec_defaults - Set default ETS recommended DCB config
* @pi: port information structure
*/
static void ice_cfg_etsrec_defaults(struct ice_port_info *pi)
{
struct ice_dcbx_cfg *dcbcfg = &pi->local_dcbx_cfg;
u8 i;
/* Ensure ETS recommended DCB configuration is not already set */
if (dcbcfg->etsrec.maxtcs)
return;
/* In CEE mode, set the default to 1 TC */
dcbcfg->etsrec.maxtcs = 1;
for (i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
dcbcfg->etsrec.tcbwtable[i] = i ? 0 : 100;
dcbcfg->etsrec.tsatable[i] = i ? ICE_IEEE_TSA_STRICT :
ICE_IEEE_TSA_ETS;
}
}
/**
* ice_dcb_need_recfg - Check if DCB needs reconfig
* @pf: board private structure
* @old_cfg: current DCB config
* @new_cfg: new DCB config
*/
static bool
ice_dcb_need_recfg(struct ice_pf *pf, struct ice_dcbx_cfg *old_cfg,
struct ice_dcbx_cfg *new_cfg)
{
struct device *dev = ice_pf_to_dev(pf);
bool need_reconfig = false;
/* Check if ETS configuration has changed */
if (memcmp(&new_cfg->etscfg, &old_cfg->etscfg,
sizeof(new_cfg->etscfg))) {
/* If Priority Table has changed reconfig is needed */
if (memcmp(&new_cfg->etscfg.prio_table,
&old_cfg->etscfg.prio_table,
sizeof(new_cfg->etscfg.prio_table))) {
need_reconfig = true;
dev_dbg(dev, "ETS UP2TC changed.\n");
}
if (memcmp(&new_cfg->etscfg.tcbwtable,
&old_cfg->etscfg.tcbwtable,
sizeof(new_cfg->etscfg.tcbwtable)))
dev_dbg(dev, "ETS TC BW Table changed.\n");
if (memcmp(&new_cfg->etscfg.tsatable,
&old_cfg->etscfg.tsatable,
sizeof(new_cfg->etscfg.tsatable)))
dev_dbg(dev, "ETS TSA Table changed.\n");
}
/* Check if PFC configuration has changed */
if (memcmp(&new_cfg->pfc, &old_cfg->pfc, sizeof(new_cfg->pfc))) {
need_reconfig = true;
dev_dbg(dev, "PFC config change detected.\n");
}
/* Check if APP Table has changed */
if (memcmp(&new_cfg->app, &old_cfg->app, sizeof(new_cfg->app))) {
need_reconfig = true;
dev_dbg(dev, "APP Table change detected.\n");
}
dev_dbg(dev, "dcb need_reconfig=%d\n", need_reconfig);
return need_reconfig;
}
/**
* ice_dcb_rebuild - rebuild DCB post reset
* @pf: physical function instance
*/
void ice_dcb_rebuild(struct ice_pf *pf)
{
struct ice_aqc_port_ets_elem buf = { 0 };
struct device *dev = ice_pf_to_dev(pf);
struct ice_dcbx_cfg *err_cfg;
enum ice_status ret;
ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL);
if (ret) {
dev_err(dev, "Query Port ETS failed\n");
goto dcb_error;
}
mutex_lock(&pf->tc_mutex);
if (!pf->hw.port_info->is_sw_lldp)
ice_cfg_etsrec_defaults(pf->hw.port_info);
ret = ice_set_dcb_cfg(pf->hw.port_info);
if (ret) {
dev_err(dev, "Failed to set DCB config in rebuild\n");
goto dcb_error;
}
if (!pf->hw.port_info->is_sw_lldp) {
ret = ice_cfg_lldp_mib_change(&pf->hw, true);
if (ret && !pf->hw.port_info->is_sw_lldp) {
dev_err(dev, "Failed to register for MIB changes\n");
goto dcb_error;
}
}
dev_info(dev, "DCB info restored\n");
ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL);
if (ret) {
dev_err(dev, "Query Port ETS failed\n");
goto dcb_error;
}
mutex_unlock(&pf->tc_mutex);
return;
dcb_error:
dev_err(dev, "Disabling DCB until new settings occur\n");
err_cfg = kzalloc(sizeof(*err_cfg), GFP_KERNEL);
if (!err_cfg) {
mutex_unlock(&pf->tc_mutex);
return;
}
err_cfg->etscfg.willing = true;
err_cfg->etscfg.tcbwtable[0] = ICE_TC_MAX_BW;
err_cfg->etscfg.tsatable[0] = ICE_IEEE_TSA_ETS;
memcpy(&err_cfg->etsrec, &err_cfg->etscfg, sizeof(err_cfg->etsrec));
/* Coverity warns the return code of ice_pf_dcb_cfg() is not checked
* here as is done for other calls to that function. That check is
* not necessary since this is in this function's error cleanup path.
* Suppress the Coverity warning with the following comment...
*/
/* coverity[check_return] */
ice_pf_dcb_cfg(pf, err_cfg, false);
kfree(err_cfg);
mutex_unlock(&pf->tc_mutex);
}
/**
* ice_dcb_init_cfg - set the initial DCB config in SW
* @pf: PF to apply config to
* @locked: Is the RTNL held
*/
static int ice_dcb_init_cfg(struct ice_pf *pf, bool locked)
{
struct ice_dcbx_cfg *newcfg;
struct ice_port_info *pi;
int ret = 0;
pi = pf->hw.port_info;
newcfg = kmemdup(&pi->local_dcbx_cfg, sizeof(*newcfg), GFP_KERNEL);
if (!newcfg)
return -ENOMEM;
memset(&pi->local_dcbx_cfg, 0, sizeof(*newcfg));
dev_info(ice_pf_to_dev(pf), "Configuring initial DCB values\n");
if (ice_pf_dcb_cfg(pf, newcfg, locked))
ret = -EINVAL;
kfree(newcfg);
return ret;
}
/**
* ice_dcb_sw_dflt_cfg - Apply a default DCB config
* @pf: PF to apply config to
* @ets_willing: configure ETS willing
* @locked: was this function called with RTNL held
*/
static int ice_dcb_sw_dflt_cfg(struct ice_pf *pf, bool ets_willing, bool locked)
{
struct ice_aqc_port_ets_elem buf = { 0 };
struct ice_dcbx_cfg *dcbcfg;
struct ice_port_info *pi;
struct ice_hw *hw;
int ret;
hw = &pf->hw;
pi = hw->port_info;
dcbcfg = kzalloc(sizeof(*dcbcfg), GFP_KERNEL);
if (!dcbcfg)
return -ENOMEM;
memset(&pi->local_dcbx_cfg, 0, sizeof(*dcbcfg));
dcbcfg->etscfg.willing = ets_willing ? 1 : 0;
dcbcfg->etscfg.maxtcs = hw->func_caps.common_cap.maxtc;
dcbcfg->etscfg.tcbwtable[0] = 100;
dcbcfg->etscfg.tsatable[0] = ICE_IEEE_TSA_ETS;
memcpy(&dcbcfg->etsrec, &dcbcfg->etscfg,
sizeof(dcbcfg->etsrec));
dcbcfg->etsrec.willing = 0;
dcbcfg->pfc.willing = 1;
dcbcfg->pfc.pfccap = hw->func_caps.common_cap.maxtc;
dcbcfg->numapps = 1;
dcbcfg->app[0].selector = ICE_APP_SEL_ETHTYPE;
dcbcfg->app[0].priority = 3;
dcbcfg->app[0].prot_id = ICE_APP_PROT_ID_FCOE;
ret = ice_pf_dcb_cfg(pf, dcbcfg, locked);
kfree(dcbcfg);
if (ret)
return ret;
return ice_query_port_ets(pi, &buf, sizeof(buf), NULL);
}
/**
* ice_dcb_tc_contig - Check that TCs are contiguous
* @prio_table: pointer to priority table
*
* Check if TCs begin with TC0 and are contiguous
*/
static bool ice_dcb_tc_contig(u8 *prio_table)
{
bool found_empty = false;
u8 used_tc = 0;
int i;
/* Create a bitmap of used TCs */
for (i = 0; i < CEE_DCBX_MAX_PRIO; i++)
used_tc |= BIT(prio_table[i]);
for (i = 0; i < CEE_DCBX_MAX_PRIO; i++) {
if (used_tc & BIT(i)) {
if (found_empty)
return false;
} else {
found_empty = true;
}
}
return true;
}
/**
* ice_dcb_noncontig_cfg - Configure DCB for non-contiguous TCs
* @pf: pointer to the PF struct
*
* If non-contiguous TCs, then configure SW DCB with TC0 and ETS non-willing
*/
static int ice_dcb_noncontig_cfg(struct ice_pf *pf)
{
struct ice_dcbx_cfg *dcbcfg = &pf->hw.port_info->local_dcbx_cfg;
struct device *dev = ice_pf_to_dev(pf);
int ret;
/* Configure SW DCB default with ETS non-willing */
ret = ice_dcb_sw_dflt_cfg(pf, false, true);
if (ret) {
dev_err(dev, "Failed to set local DCB config %d\n", ret);
return ret;
}
/* Reconfigure with ETS willing so that FW will send LLDP MIB event */
dcbcfg->etscfg.willing = 1;
ret = ice_set_dcb_cfg(pf->hw.port_info);
if (ret)
dev_err(dev, "Failed to set DCB to unwilling\n");
return ret;
}
/**
* ice_pf_dcb_recfg - Reconfigure all VEBs and VSIs
* @pf: pointer to the PF struct
*
* Assumed caller has already disabled all VSIs before
* calling this function. Reconfiguring DCB based on
* local_dcbx_cfg.
*/
void ice_pf_dcb_recfg(struct ice_pf *pf)
{
struct ice_dcbx_cfg *dcbcfg = &pf->hw.port_info->local_dcbx_cfg;
u8 tc_map = 0;
int v, ret;
/* Update each VSI */
ice_for_each_vsi(pf, v) {
struct ice_vsi *vsi = pf->vsi[v];
if (!vsi)
continue;
if (vsi->type == ICE_VSI_PF) {
tc_map = ice_dcb_get_ena_tc(dcbcfg);
/* If DCBX request non-contiguous TC, then configure
* default TC
*/
if (!ice_dcb_tc_contig(dcbcfg->etscfg.prio_table)) {
tc_map = ICE_DFLT_TRAFFIC_CLASS;
ice_dcb_noncontig_cfg(pf);
}
} else {
tc_map = ICE_DFLT_TRAFFIC_CLASS;
}
ret = ice_vsi_cfg_tc(vsi, tc_map);
if (ret) {
dev_err(ice_pf_to_dev(pf), "Failed to config TC for VSI index: %d\n",
vsi->idx);
continue;
}
ice_vsi_map_rings_to_vectors(vsi);
if (vsi->type == ICE_VSI_PF)
ice_dcbnl_set_all(vsi);
}
}
/**
* ice_init_pf_dcb - initialize DCB for a PF
* @pf: PF to initialize DCB for
* @locked: Was function called with RTNL held
*/
int ice_init_pf_dcb(struct ice_pf *pf, bool locked)
{
struct device *dev = ice_pf_to_dev(pf);
struct ice_port_info *port_info;
struct ice_hw *hw = &pf->hw;
int err;
port_info = hw->port_info;
err = ice_init_dcb(hw, false);
if (err && !port_info->is_sw_lldp) {
dev_err(dev, "Error initializing DCB %d\n", err);
goto dcb_init_err;
}
dev_info(dev, "DCB is enabled in the hardware, max number of TCs supported on this port are %d\n",
pf->hw.func_caps.common_cap.maxtc);
if (err) {
struct ice_vsi *pf_vsi;
/* FW LLDP is disabled, activate SW DCBX/LLDP mode */
dev_info(dev, "FW LLDP is disabled, DCBx/LLDP in SW mode.\n");
clear_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags);
err = ice_dcb_sw_dflt_cfg(pf, true, locked);
if (err) {
dev_err(dev, "Failed to set local DCB config %d\n",
err);
err = -EIO;
goto dcb_init_err;
}
/* If the FW DCBX engine is not running then Rx LLDP packets
* need to be redirected up the stack.
*/
pf_vsi = ice_get_main_vsi(pf);
if (!pf_vsi) {
dev_err(dev, "Failed to set local DCB config\n");
err = -EIO;
goto dcb_init_err;
}
ice_cfg_sw_lldp(pf_vsi, false, true);
pf->dcbx_cap = ice_dcb_get_mode(port_info, true);
return 0;
}
set_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags);
/* DCBX/LLDP enabled in FW, set DCBNL mode advertisement */
pf->dcbx_cap = ice_dcb_get_mode(port_info, false);
err = ice_dcb_init_cfg(pf, locked);
if (err)
goto dcb_init_err;
return err;
dcb_init_err:
dev_err(dev, "DCB init failed\n");
return err;
}
/**
* ice_update_dcb_stats - Update DCB stats counters
* @pf: PF whose stats needs to be updated
*/
void ice_update_dcb_stats(struct ice_pf *pf)
{
struct ice_hw_port_stats *prev_ps, *cur_ps;
struct ice_hw *hw = &pf->hw;
u8 port;
int i;
port = hw->port_info->lport;
prev_ps = &pf->stats_prev;
cur_ps = &pf->stats;
for (i = 0; i < 8; i++) {
ice_stat_update32(hw, GLPRT_PXOFFRXC(port, i),
pf->stat_prev_loaded,
&prev_ps->priority_xoff_rx[i],
&cur_ps->priority_xoff_rx[i]);
ice_stat_update32(hw, GLPRT_PXONRXC(port, i),
pf->stat_prev_loaded,
&prev_ps->priority_xon_rx[i],
&cur_ps->priority_xon_rx[i]);
ice_stat_update32(hw, GLPRT_PXONTXC(port, i),
pf->stat_prev_loaded,
&prev_ps->priority_xon_tx[i],
&cur_ps->priority_xon_tx[i]);
ice_stat_update32(hw, GLPRT_PXOFFTXC(port, i),
pf->stat_prev_loaded,
&prev_ps->priority_xoff_tx[i],
&cur_ps->priority_xoff_tx[i]);
ice_stat_update32(hw, GLPRT_RXON2OFFCNT(port, i),
pf->stat_prev_loaded,
&prev_ps->priority_xon_2_xoff[i],
&cur_ps->priority_xon_2_xoff[i]);
}
}
/**
* ice_tx_prepare_vlan_flags_dcb - prepare VLAN tagging for DCB
* @tx_ring: ring to send buffer on
* @first: pointer to struct ice_tx_buf
*
* This should not be called if the outer VLAN is software offloaded as the VLAN
* tag will already be configured with the correct ID and priority bits
*/
void
ice_tx_prepare_vlan_flags_dcb(struct ice_ring *tx_ring,
struct ice_tx_buf *first)
{
struct sk_buff *skb = first->skb;
if (!test_bit(ICE_FLAG_DCB_ENA, tx_ring->vsi->back->flags))
return;
/* Insert 802.1p priority into VLAN header */
if ((first->tx_flags & ICE_TX_FLAGS_HW_VLAN) ||
skb->priority != TC_PRIO_CONTROL) {
first->tx_flags &= ~ICE_TX_FLAGS_VLAN_PR_M;
/* Mask the lower 3 bits to set the 802.1p priority */
first->tx_flags |= (skb->priority & 0x7) <<
ICE_TX_FLAGS_VLAN_PR_S;
/* if this is not already set it means a VLAN 0 + priority needs
* to be offloaded
*/
first->tx_flags |= ICE_TX_FLAGS_HW_VLAN;
}
}
/**
* ice_dcb_process_lldp_set_mib_change - Process MIB change
* @pf: ptr to ice_pf
* @event: pointer to the admin queue receive event
*/
void
ice_dcb_process_lldp_set_mib_change(struct ice_pf *pf,
struct ice_rq_event_info *event)
{
struct ice_aqc_port_ets_elem buf = { 0 };
struct device *dev = ice_pf_to_dev(pf);
struct ice_aqc_lldp_get_mib *mib;
struct ice_dcbx_cfg tmp_dcbx_cfg;
bool need_reconfig = false;
struct ice_port_info *pi;
struct ice_vsi *pf_vsi;
u8 mib_type;
int ret;
/* Not DCB capable or capability disabled */
if (!(test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags)))
return;
if (pf->dcbx_cap & DCB_CAP_DCBX_HOST) {
dev_dbg(dev, "MIB Change Event in HOST mode\n");
return;
}
pi = pf->hw.port_info;
mib = (struct ice_aqc_lldp_get_mib *)&event->desc.params.raw;
/* Ignore if event is not for Nearest Bridge */
mib_type = ((mib->type >> ICE_AQ_LLDP_BRID_TYPE_S) &
ICE_AQ_LLDP_BRID_TYPE_M);
dev_dbg(dev, "LLDP event MIB bridge type 0x%x\n", mib_type);
if (mib_type != ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID)
return;
/* Check MIB Type and return if event for Remote MIB update */
mib_type = mib->type & ICE_AQ_LLDP_MIB_TYPE_M;
dev_dbg(dev, "LLDP event mib type %s\n", mib_type ? "remote" : "local");
if (mib_type == ICE_AQ_LLDP_MIB_REMOTE) {
/* Update the remote cached instance and return */
ret = ice_aq_get_dcb_cfg(pi->hw, ICE_AQ_LLDP_MIB_REMOTE,
ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID,
&pi->remote_dcbx_cfg);
if (ret) {
dev_err(dev, "Failed to get remote DCB config\n");
return;
}
}
mutex_lock(&pf->tc_mutex);
/* store the old configuration */
tmp_dcbx_cfg = pf->hw.port_info->local_dcbx_cfg;
/* Reset the old DCBX configuration data */
memset(&pi->local_dcbx_cfg, 0, sizeof(pi->local_dcbx_cfg));
/* Get updated DCBX data from firmware */
ret = ice_get_dcb_cfg(pf->hw.port_info);
if (ret) {
dev_err(dev, "Failed to get DCB config\n");
goto out;
}
/* No change detected in DCBX configs */
if (!memcmp(&tmp_dcbx_cfg, &pi->local_dcbx_cfg, sizeof(tmp_dcbx_cfg))) {
dev_dbg(dev, "No change detected in DCBX configuration.\n");
goto out;
}
pf->dcbx_cap = ice_dcb_get_mode(pi, false);
need_reconfig = ice_dcb_need_recfg(pf, &tmp_dcbx_cfg,
&pi->local_dcbx_cfg);
ice_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &pi->local_dcbx_cfg);
if (!need_reconfig)
goto out;
/* Enable DCB tagging only when more than one TC */
if (ice_dcb_get_num_tc(&pi->local_dcbx_cfg) > 1) {
dev_dbg(dev, "DCB tagging enabled (num TC > 1)\n");
set_bit(ICE_FLAG_DCB_ENA, pf->flags);
} else {
dev_dbg(dev, "DCB tagging disabled (num TC = 1)\n");
clear_bit(ICE_FLAG_DCB_ENA, pf->flags);
}
pf_vsi = ice_get_main_vsi(pf);
if (!pf_vsi) {
dev_dbg(dev, "PF VSI doesn't exist\n");
goto out;
}
rtnl_lock();
ice_dis_vsi(pf_vsi, true);
ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL);
if (ret) {
dev_err(dev, "Query Port ETS failed\n");
goto unlock_rtnl;
}
/* changes in configuration update VSI */
ice_pf_dcb_recfg(pf);
ice_ena_vsi(pf_vsi, true);
unlock_rtnl:
rtnl_unlock();
out:
mutex_unlock(&pf->tc_mutex);
}
| gpl-2.0 |
joninvski/ts_7500_kernel | drivers/rtc/rtc-rs5c348.c | 53 | 7198 | /*
* A SPI driver for the Ricoh RS5C348 RTC
*
* Copyright (C) 2006 Atsushi Nemoto <anemo@mba.ocn.ne.jp>
*
* 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.
*
* The board specific init code should provide characteristics of this
* device:
* Mode 1 (High-Active, Shift-Then-Sample), High Avtive CS
*/
#include <linux/bcd.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/rtc.h>
#include <linux/workqueue.h>
#include <linux/spi/spi.h>
#define DRV_VERSION "0.2"
#define RS5C348_REG_SECS 0
#define RS5C348_REG_MINS 1
#define RS5C348_REG_HOURS 2
#define RS5C348_REG_WDAY 3
#define RS5C348_REG_DAY 4
#define RS5C348_REG_MONTH 5
#define RS5C348_REG_YEAR 6
#define RS5C348_REG_CTL1 14
#define RS5C348_REG_CTL2 15
#define RS5C348_SECS_MASK 0x7f
#define RS5C348_MINS_MASK 0x7f
#define RS5C348_HOURS_MASK 0x3f
#define RS5C348_WDAY_MASK 0x03
#define RS5C348_DAY_MASK 0x3f
#define RS5C348_MONTH_MASK 0x1f
#define RS5C348_BIT_PM 0x20 /* REG_HOURS */
#define RS5C348_BIT_Y2K 0x80 /* REG_MONTH */
#define RS5C348_BIT_24H 0x20 /* REG_CTL1 */
#define RS5C348_BIT_XSTP 0x10 /* REG_CTL2 */
#define RS5C348_BIT_VDET 0x40 /* REG_CTL2 */
#define RS5C348_CMD_W(addr) (((addr) << 4) | 0x08) /* single write */
#define RS5C348_CMD_R(addr) (((addr) << 4) | 0x0c) /* single read */
#define RS5C348_CMD_MW(addr) (((addr) << 4) | 0x00) /* burst write */
#define RS5C348_CMD_MR(addr) (((addr) << 4) | 0x04) /* burst read */
struct rs5c348_plat_data {
struct rtc_device *rtc;
int rtc_24h;
};
static int
rs5c348_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct spi_device *spi = to_spi_device(dev);
struct rs5c348_plat_data *pdata = spi->dev.platform_data;
u8 txbuf[5+7], *txp;
int ret;
/* Transfer 5 bytes before writing SEC. This gives 31us for carry. */
txp = txbuf;
txbuf[0] = RS5C348_CMD_R(RS5C348_REG_CTL2); /* cmd, ctl2 */
txbuf[1] = 0; /* dummy */
txbuf[2] = RS5C348_CMD_R(RS5C348_REG_CTL2); /* cmd, ctl2 */
txbuf[3] = 0; /* dummy */
txbuf[4] = RS5C348_CMD_MW(RS5C348_REG_SECS); /* cmd, sec, ... */
txp = &txbuf[5];
txp[RS5C348_REG_SECS] = BIN2BCD(tm->tm_sec);
txp[RS5C348_REG_MINS] = BIN2BCD(tm->tm_min);
if (pdata->rtc_24h) {
txp[RS5C348_REG_HOURS] = BIN2BCD(tm->tm_hour);
} else {
/* hour 0 is AM12, noon is PM12 */
txp[RS5C348_REG_HOURS] = BIN2BCD((tm->tm_hour + 11) % 12 + 1) |
(tm->tm_hour >= 12 ? RS5C348_BIT_PM : 0);
}
txp[RS5C348_REG_WDAY] = BIN2BCD(tm->tm_wday);
txp[RS5C348_REG_DAY] = BIN2BCD(tm->tm_mday);
txp[RS5C348_REG_MONTH] = BIN2BCD(tm->tm_mon + 1) |
(tm->tm_year >= 100 ? RS5C348_BIT_Y2K : 0);
txp[RS5C348_REG_YEAR] = BIN2BCD(tm->tm_year % 100);
/* write in one transfer to avoid data inconsistency */
ret = spi_write_then_read(spi, txbuf, sizeof(txbuf), NULL, 0);
udelay(62); /* Tcsr 62us */
return ret;
}
static int
rs5c348_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct spi_device *spi = to_spi_device(dev);
struct rs5c348_plat_data *pdata = spi->dev.platform_data;
u8 txbuf[5], rxbuf[7];
int ret;
/* Transfer 5 byte befores reading SEC. This gives 31us for carry. */
txbuf[0] = RS5C348_CMD_R(RS5C348_REG_CTL2); /* cmd, ctl2 */
txbuf[1] = 0; /* dummy */
txbuf[2] = RS5C348_CMD_R(RS5C348_REG_CTL2); /* cmd, ctl2 */
txbuf[3] = 0; /* dummy */
txbuf[4] = RS5C348_CMD_MR(RS5C348_REG_SECS); /* cmd, sec, ... */
/* read in one transfer to avoid data inconsistency */
ret = spi_write_then_read(spi, txbuf, sizeof(txbuf),
rxbuf, sizeof(rxbuf));
udelay(62); /* Tcsr 62us */
if (ret < 0)
return ret;
tm->tm_sec = BCD2BIN(rxbuf[RS5C348_REG_SECS] & RS5C348_SECS_MASK);
tm->tm_min = BCD2BIN(rxbuf[RS5C348_REG_MINS] & RS5C348_MINS_MASK);
tm->tm_hour = BCD2BIN(rxbuf[RS5C348_REG_HOURS] & RS5C348_HOURS_MASK);
if (!pdata->rtc_24h) {
tm->tm_hour %= 12;
if (rxbuf[RS5C348_REG_HOURS] & RS5C348_BIT_PM)
tm->tm_hour += 12;
}
tm->tm_wday = BCD2BIN(rxbuf[RS5C348_REG_WDAY] & RS5C348_WDAY_MASK);
tm->tm_mday = BCD2BIN(rxbuf[RS5C348_REG_DAY] & RS5C348_DAY_MASK);
tm->tm_mon =
BCD2BIN(rxbuf[RS5C348_REG_MONTH] & RS5C348_MONTH_MASK) - 1;
/* year is 1900 + tm->tm_year */
tm->tm_year = BCD2BIN(rxbuf[RS5C348_REG_YEAR]) +
((rxbuf[RS5C348_REG_MONTH] & RS5C348_BIT_Y2K) ? 100 : 0);
if (rtc_valid_tm(tm) < 0) {
dev_err(&spi->dev, "retrieved date/time is not valid.\n");
rtc_time_to_tm(0, tm);
}
return 0;
}
static const struct rtc_class_ops rs5c348_rtc_ops = {
.read_time = rs5c348_rtc_read_time,
.set_time = rs5c348_rtc_set_time,
};
static struct spi_driver rs5c348_driver;
static int __devinit rs5c348_probe(struct spi_device *spi)
{
int ret;
struct rtc_device *rtc;
struct rs5c348_plat_data *pdata;
pdata = kzalloc(sizeof(struct rs5c348_plat_data), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
spi->dev.platform_data = pdata;
/* Check D7 of SECOND register */
ret = spi_w8r8(spi, RS5C348_CMD_R(RS5C348_REG_SECS));
if (ret < 0 || (ret & 0x80)) {
dev_err(&spi->dev, "not found.\n");
goto kfree_exit;
}
dev_info(&spi->dev, "chip found, driver version " DRV_VERSION "\n");
dev_info(&spi->dev, "spiclk %u KHz.\n",
(spi->max_speed_hz + 500) / 1000);
/* turn RTC on if it was not on */
ret = spi_w8r8(spi, RS5C348_CMD_R(RS5C348_REG_CTL2));
if (ret < 0)
goto kfree_exit;
if (ret & (RS5C348_BIT_XSTP | RS5C348_BIT_VDET)) {
u8 buf[2];
struct rtc_time tm;
if (ret & RS5C348_BIT_VDET)
dev_warn(&spi->dev, "voltage-low detected.\n");
if (ret & RS5C348_BIT_XSTP)
dev_warn(&spi->dev, "oscillator-stop detected.\n");
rtc_time_to_tm(0, &tm); /* 1970/1/1 */
ret = rs5c348_rtc_set_time(&spi->dev, &tm);
if (ret < 0)
goto kfree_exit;
buf[0] = RS5C348_CMD_W(RS5C348_REG_CTL2);
buf[1] = 0;
ret = spi_write_then_read(spi, buf, sizeof(buf), NULL, 0);
if (ret < 0)
goto kfree_exit;
}
ret = spi_w8r8(spi, RS5C348_CMD_R(RS5C348_REG_CTL1));
if (ret < 0)
goto kfree_exit;
if (ret & RS5C348_BIT_24H)
pdata->rtc_24h = 1;
rtc = rtc_device_register(rs5c348_driver.driver.name, &spi->dev,
&rs5c348_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc)) {
ret = PTR_ERR(rtc);
goto kfree_exit;
}
pdata->rtc = rtc;
return 0;
kfree_exit:
kfree(pdata);
return ret;
}
static int __devexit rs5c348_remove(struct spi_device *spi)
{
struct rs5c348_plat_data *pdata = spi->dev.platform_data;
struct rtc_device *rtc = pdata->rtc;
if (rtc)
rtc_device_unregister(rtc);
kfree(pdata);
return 0;
}
static struct spi_driver rs5c348_driver = {
.driver = {
.name = "rtc-rs5c348",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = rs5c348_probe,
.remove = __devexit_p(rs5c348_remove),
};
static __init int rs5c348_init(void)
{
return spi_register_driver(&rs5c348_driver);
}
static __exit void rs5c348_exit(void)
{
spi_unregister_driver(&rs5c348_driver);
}
module_init(rs5c348_init);
module_exit(rs5c348_exit);
MODULE_AUTHOR("Atsushi Nemoto <anemo@mba.ocn.ne.jp>");
MODULE_DESCRIPTION("Ricoh RS5C348 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
garwynn/D710SPR_GB27_Kernel | arch/arm/mm/alignment.c | 53 | 25338 | /*
* linux/arch/arm/mm/alignment.c
*
* Copyright (C) 1995 Linus Torvalds
* Modifications for ARM processor (c) 1995-2001 Russell King
* Thumb alignment fault fixups (c) 2004 MontaVista Software, Inc.
* - Adapted from gdb/sim/arm/thumbemu.c -- Thumb instruction emulation.
* Copyright (C) 1996, Cygnus Software Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/moduleparam.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include "fault.h"
/*
* 32-bit misaligned trap handler (c) 1998 San Mehat (CCC) -July 1998
* /proc/sys/debug/alignment, modified and integrated into
* Linux 2.1 by Russell King
*
* Speed optimisations and better fault handling by Russell King.
*
* *** NOTE ***
* This code is not portable to processors with late data abort handling.
*/
#define CODING_BITS(i) (i & 0x0e000000)
#define LDST_I_BIT(i) (i & (1 << 26)) /* Immediate constant */
#define LDST_P_BIT(i) (i & (1 << 24)) /* Preindex */
#define LDST_U_BIT(i) (i & (1 << 23)) /* Add offset */
#define LDST_W_BIT(i) (i & (1 << 21)) /* Writeback */
#define LDST_L_BIT(i) (i & (1 << 20)) /* Load */
#define LDST_P_EQ_U(i) ((((i) ^ ((i) >> 1)) & (1 << 23)) == 0)
#define LDSTHD_I_BIT(i) (i & (1 << 22)) /* double/half-word immed */
#define LDM_S_BIT(i) (i & (1 << 22)) /* write CPSR from SPSR */
#define RN_BITS(i) ((i >> 16) & 15) /* Rn */
#define RD_BITS(i) ((i >> 12) & 15) /* Rd */
#define RM_BITS(i) (i & 15) /* Rm */
#define REGMASK_BITS(i) (i & 0xffff)
#define OFFSET_BITS(i) (i & 0x0fff)
#define IS_SHIFT(i) (i & 0x0ff0)
#define SHIFT_BITS(i) ((i >> 7) & 0x1f)
#define SHIFT_TYPE(i) (i & 0x60)
#define SHIFT_LSL 0x00
#define SHIFT_LSR 0x20
#define SHIFT_ASR 0x40
#define SHIFT_RORRRX 0x60
#define BAD_INSTR 0xdeadc0de
/* Thumb-2 32 bit format per ARMv7 DDI0406A A6.3, either f800h,e800h,f800h */
#define IS_T32(hi16) \
(((hi16) & 0xe000) == 0xe000 && ((hi16) & 0x1800))
static unsigned long ai_user;
static unsigned long ai_sys;
static unsigned long ai_skipped;
static unsigned long ai_half;
static unsigned long ai_word;
static unsigned long ai_dword;
static unsigned long ai_multi;
static int ai_usermode;
core_param(alignment, ai_usermode, int, 0600);
#define UM_WARN (1 << 0)
#define UM_FIXUP (1 << 1)
#define UM_SIGNAL (1 << 2)
#ifdef CONFIG_PROC_FS
static const char *usermode_action[] = {
"ignored",
"warn",
"fixup",
"fixup+warn",
"signal",
"signal+warn"
};
static int alignment_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "User:\t\t%lu\n", ai_user);
seq_printf(m, "System:\t\t%lu\n", ai_sys);
seq_printf(m, "Skipped:\t%lu\n", ai_skipped);
seq_printf(m, "Half:\t\t%lu\n", ai_half);
seq_printf(m, "Word:\t\t%lu\n", ai_word);
if (cpu_architecture() >= CPU_ARCH_ARMv5TE)
seq_printf(m, "DWord:\t\t%lu\n", ai_dword);
seq_printf(m, "Multi:\t\t%lu\n", ai_multi);
seq_printf(m, "User faults:\t%i (%s)\n", ai_usermode,
usermode_action[ai_usermode]);
return 0;
}
static int alignment_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, alignment_proc_show, NULL);
}
static ssize_t alignment_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *pos)
{
char mode;
if (count > 0) {
if (get_user(mode, buffer))
return -EFAULT;
if (mode >= '0' && mode <= '5')
ai_usermode = mode - '0';
}
return count;
}
static const struct file_operations alignment_proc_fops = {
.open = alignment_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = alignment_proc_write,
};
#endif /* CONFIG_PROC_FS */
union offset_union {
unsigned long un;
signed long sn;
};
#define TYPE_ERROR 0
#define TYPE_FAULT 1
#define TYPE_LDST 2
#define TYPE_DONE 3
#ifdef __ARMEB__
#define BE 1
#define FIRST_BYTE_16 "mov %1, %1, ror #8\n"
#define FIRST_BYTE_32 "mov %1, %1, ror #24\n"
#define NEXT_BYTE "ror #24"
#else
#define BE 0
#define FIRST_BYTE_16
#define FIRST_BYTE_32
#define NEXT_BYTE "lsr #8"
#endif
#define __get8_unaligned_check(ins,val,addr,err) \
__asm__( \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
"2:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"3: mov %0, #1\n" \
" b 2b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 3b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (val), "=r" (addr) \
: "0" (err), "2" (addr))
#define __get16_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v, a = addr; \
__get8_unaligned_check(ins,v,a,err); \
val = v << ((BE) ? 8 : 0); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 0 : 8); \
if (err) \
goto fault; \
} while (0)
#define get16_unaligned_check(val,addr) \
__get16_unaligned_check("ldrb",val,addr)
#define get16t_unaligned_check(val,addr) \
__get16_unaligned_check("ldrbt",val,addr)
#define __get32_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v, a = addr; \
__get8_unaligned_check(ins,v,a,err); \
val = v << ((BE) ? 24 : 0); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 16 : 8); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 8 : 16); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 0 : 24); \
if (err) \
goto fault; \
} while (0)
#define get32_unaligned_check(val,addr) \
__get32_unaligned_check("ldrb",val,addr)
#define get32t_unaligned_check(val,addr) \
__get32_unaligned_check("ldrbt",val,addr)
#define __put16_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( FIRST_BYTE_16 \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
"2: "ins" %1, [%2]\n" \
"3:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"4: mov %0, #1\n" \
" b 3b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 4b\n" \
" .long 2b, 4b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define put16_unaligned_check(val,addr) \
__put16_unaligned_check("strb",val,addr)
#define put16t_unaligned_check(val,addr) \
__put16_unaligned_check("strbt",val,addr)
#define __put32_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( FIRST_BYTE_32 \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
ARM( "2: "ins" %1, [%2], #1\n" ) \
THUMB( "2: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
ARM( "3: "ins" %1, [%2], #1\n" ) \
THUMB( "3: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
"4: "ins" %1, [%2]\n" \
"5:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"6: mov %0, #1\n" \
" b 5b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 6b\n" \
" .long 2b, 6b\n" \
" .long 3b, 6b\n" \
" .long 4b, 6b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define put32_unaligned_check(val,addr) \
__put32_unaligned_check("strb", val, addr)
#define put32t_unaligned_check(val,addr) \
__put32_unaligned_check("strbt", val, addr)
static void
do_alignment_finish_ldst(unsigned long addr, unsigned long instr, struct pt_regs *regs, union offset_union offset)
{
if (!LDST_U_BIT(instr))
offset.un = -offset.un;
if (!LDST_P_BIT(instr))
addr += offset.un;
if (!LDST_P_BIT(instr) || LDST_W_BIT(instr))
regs->uregs[RN_BITS(instr)] = addr;
}
static int
do_alignment_ldrhstrh(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
ai_half += 1;
if (user_mode(regs))
goto user;
if (LDST_L_BIT(instr)) {
unsigned long val;
get16_unaligned_check(val, addr);
/* signed half-word? */
if (instr & 0x40)
val = (signed long)((signed short) val);
regs->uregs[rd] = val;
} else
put16_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
user:
if (LDST_L_BIT(instr)) {
unsigned long val;
get16t_unaligned_check(val, addr);
/* signed half-word? */
if (instr & 0x40)
val = (signed long)((signed short) val);
regs->uregs[rd] = val;
} else
put16t_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
fault:
return TYPE_FAULT;
}
static int
do_alignment_ldrdstrd(unsigned long addr, unsigned long instr,
struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
unsigned int rd2;
int load;
if ((instr & 0xfe000000) == 0xe8000000) {
/* ARMv7 Thumb-2 32-bit LDRD/STRD */
rd2 = (instr >> 8) & 0xf;
load = !!(LDST_L_BIT(instr));
} else if (((rd & 1) == 1) || (rd == 14))
goto bad;
else {
load = ((instr & 0xf0) == 0xd0);
rd2 = rd + 1;
}
ai_dword += 1;
if (user_mode(regs))
goto user;
if (load) {
unsigned long val;
get32_unaligned_check(val, addr);
regs->uregs[rd] = val;
get32_unaligned_check(val, addr + 4);
regs->uregs[rd2] = val;
} else {
put32_unaligned_check(regs->uregs[rd], addr);
put32_unaligned_check(regs->uregs[rd2], addr + 4);
}
return TYPE_LDST;
user:
if (load) {
unsigned long val;
get32t_unaligned_check(val, addr);
regs->uregs[rd] = val;
get32t_unaligned_check(val, addr + 4);
regs->uregs[rd2] = val;
} else {
put32t_unaligned_check(regs->uregs[rd], addr);
put32t_unaligned_check(regs->uregs[rd2], addr + 4);
}
return TYPE_LDST;
bad:
return TYPE_ERROR;
fault:
return TYPE_FAULT;
}
static int
do_alignment_ldrstr(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
ai_word += 1;
if ((!LDST_P_BIT(instr) && LDST_W_BIT(instr)) || user_mode(regs))
goto trans;
if (LDST_L_BIT(instr)) {
unsigned int val;
get32_unaligned_check(val, addr);
regs->uregs[rd] = val;
} else
put32_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
trans:
if (LDST_L_BIT(instr)) {
unsigned int val;
get32t_unaligned_check(val, addr);
regs->uregs[rd] = val;
} else
put32t_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
fault:
return TYPE_FAULT;
}
/*
* LDM/STM alignment handler.
*
* There are 4 variants of this instruction:
*
* B = rn pointer before instruction, A = rn pointer after instruction
* ------ increasing address ----->
* | | r0 | r1 | ... | rx | |
* PU = 01 B A
* PU = 11 B A
* PU = 00 A B
* PU = 10 A B
*/
static int
do_alignment_ldmstm(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd, rn, correction, nr_regs, regbits;
unsigned long eaddr, newaddr;
if (LDM_S_BIT(instr))
goto bad;
correction = 4; /* processor implementation defined */
regs->ARM_pc += correction;
ai_multi += 1;
/* count the number of registers in the mask to be transferred */
nr_regs = hweight16(REGMASK_BITS(instr)) * 4;
rn = RN_BITS(instr);
newaddr = eaddr = regs->uregs[rn];
if (!LDST_U_BIT(instr))
nr_regs = -nr_regs;
newaddr += nr_regs;
if (!LDST_U_BIT(instr))
eaddr = newaddr;
if (LDST_P_EQ_U(instr)) /* U = P */
eaddr += 4;
/*
* For alignment faults on the ARM922T/ARM920T the MMU makes
* the FSR (and hence addr) equal to the updated base address
* of the multiple access rather than the restored value.
* Switch this message off if we've got a ARM92[02], otherwise
* [ls]dm alignment faults are noisy!
*/
#if !(defined CONFIG_CPU_ARM922T) && !(defined CONFIG_CPU_ARM920T)
/*
* This is a "hint" - we already have eaddr worked out by the
* processor for us.
*/
if (addr != eaddr) {
printk(KERN_ERR "LDMSTM: PC = %08lx, instr = %08lx, "
"addr = %08lx, eaddr = %08lx\n",
instruction_pointer(regs), instr, addr, eaddr);
show_regs(regs);
}
#endif
if (user_mode(regs)) {
for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
regbits >>= 1, rd += 1)
if (regbits & 1) {
if (LDST_L_BIT(instr)) {
unsigned int val;
get32t_unaligned_check(val, eaddr);
regs->uregs[rd] = val;
} else
put32t_unaligned_check(regs->uregs[rd], eaddr);
eaddr += 4;
}
} else {
for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
regbits >>= 1, rd += 1)
if (regbits & 1) {
if (LDST_L_BIT(instr)) {
unsigned int val;
get32_unaligned_check(val, eaddr);
regs->uregs[rd] = val;
} else
put32_unaligned_check(regs->uregs[rd], eaddr);
eaddr += 4;
}
}
if (LDST_W_BIT(instr))
regs->uregs[rn] = newaddr;
if (!LDST_L_BIT(instr) || !(REGMASK_BITS(instr) & (1 << 15)))
regs->ARM_pc -= correction;
return TYPE_DONE;
fault:
regs->ARM_pc -= correction;
return TYPE_FAULT;
bad:
printk(KERN_ERR "Alignment trap: not handling ldm with s-bit set\n");
return TYPE_ERROR;
}
/*
* Convert Thumb ld/st instruction forms to equivalent ARM instructions so
* we can reuse ARM userland alignment fault fixups for Thumb.
*
* This implementation was initially based on the algorithm found in
* gdb/sim/arm/thumbemu.c. It is basically just a code reduction of same
* to convert only Thumb ld/st instruction forms to equivalent ARM forms.
*
* NOTES:
* 1. Comments below refer to ARM ARM DDI0100E Thumb Instruction sections.
* 2. If for some reason we're passed an non-ld/st Thumb instruction to
* decode, we return 0xdeadc0de. This should never happen under normal
* circumstances but if it does, we've got other problems to deal with
* elsewhere and we obviously can't fix those problems here.
*/
static unsigned long
thumb2arm(u16 tinstr)
{
u32 L = (tinstr & (1<<11)) >> 11;
switch ((tinstr & 0xf800) >> 11) {
/* 6.5.1 Format 1: */
case 0x6000 >> 11: /* 7.1.52 STR(1) */
case 0x6800 >> 11: /* 7.1.26 LDR(1) */
case 0x7000 >> 11: /* 7.1.55 STRB(1) */
case 0x7800 >> 11: /* 7.1.30 LDRB(1) */
return 0xe5800000 |
((tinstr & (1<<12)) << (22-12)) | /* fixup */
(L<<20) | /* L==1? */
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (31<<6)) >> /* immed_5 */
(6 - ((tinstr & (1<<12)) ? 0 : 2)));
case 0x8000 >> 11: /* 7.1.57 STRH(1) */
case 0x8800 >> 11: /* 7.1.32 LDRH(1) */
return 0xe1c000b0 |
(L<<20) | /* L==1? */
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (7<<6)) >> (6-1)) | /* immed_5[2:0] */
((tinstr & (3<<9)) >> (9-8)); /* immed_5[4:3] */
/* 6.5.1 Format 2: */
case 0x5000 >> 11:
case 0x5800 >> 11:
{
static const u32 subset[8] = {
0xe7800000, /* 7.1.53 STR(2) */
0xe18000b0, /* 7.1.58 STRH(2) */
0xe7c00000, /* 7.1.56 STRB(2) */
0xe19000d0, /* 7.1.34 LDRSB */
0xe7900000, /* 7.1.27 LDR(2) */
0xe19000b0, /* 7.1.33 LDRH(2) */
0xe7d00000, /* 7.1.31 LDRB(2) */
0xe19000f0 /* 7.1.35 LDRSH */
};
return subset[(tinstr & (7<<9)) >> 9] |
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (7<<6)) >> (6-0)); /* Rm */
}
/* 6.5.1 Format 3: */
case 0x4800 >> 11: /* 7.1.28 LDR(3) */
/* NOTE: This case is not technically possible. We're
* loading 32-bit memory data via PC relative
* addressing mode. So we can and should eliminate
* this case. But I'll leave it here for now.
*/
return 0xe59f0000 |
((tinstr & (7<<8)) << (12-8)) | /* Rd */
((tinstr & 255) << (2-0)); /* immed_8 */
/* 6.5.1 Format 4: */
case 0x9000 >> 11: /* 7.1.54 STR(3) */
case 0x9800 >> 11: /* 7.1.29 LDR(4) */
return 0xe58d0000 |
(L<<20) | /* L==1? */
((tinstr & (7<<8)) << (12-8)) | /* Rd */
((tinstr & 255) << 2); /* immed_8 */
/* 6.6.1 Format 1: */
case 0xc000 >> 11: /* 7.1.51 STMIA */
case 0xc800 >> 11: /* 7.1.25 LDMIA */
{
u32 Rn = (tinstr & (7<<8)) >> 8;
u32 W = ((L<<Rn) & (tinstr&255)) ? 0 : 1<<21;
return 0xe8800000 | W | (L<<20) | (Rn<<16) |
(tinstr&255);
}
/* 6.6.1 Format 2: */
case 0xb000 >> 11: /* 7.1.48 PUSH */
case 0xb800 >> 11: /* 7.1.47 POP */
if ((tinstr & (3 << 9)) == 0x0400) {
static const u32 subset[4] = {
0xe92d0000, /* STMDB sp!,{registers} */
0xe92d4000, /* STMDB sp!,{registers,lr} */
0xe8bd0000, /* LDMIA sp!,{registers} */
0xe8bd8000 /* LDMIA sp!,{registers,pc} */
};
return subset[(L<<1) | ((tinstr & (1<<8)) >> 8)] |
(tinstr & 255); /* register_list */
}
/* Else fall through for illegal instruction case */
default:
return BAD_INSTR;
}
}
/*
* Convert Thumb-2 32 bit LDM, STM, LDRD, STRD to equivalent instruction
* handlable by ARM alignment handler, also find the corresponding handler,
* so that we can reuse ARM userland alignment fault fixups for Thumb.
*
* @pinstr: original Thumb-2 instruction; returns new handlable instruction
* @regs: register context.
* @poffset: return offset from faulted addr for later writeback
*
* NOTES:
* 1. Comments below refer to ARMv7 DDI0406A Thumb Instruction sections.
* 2. Register name Rt from ARMv7 is same as Rd from ARMv6 (Rd is Rt)
*/
static void *
do_alignment_t32_to_handler(unsigned long *pinstr, struct pt_regs *regs,
union offset_union *poffset)
{
unsigned long instr = *pinstr;
u16 tinst1 = (instr >> 16) & 0xffff;
u16 tinst2 = instr & 0xffff;
poffset->un = 0;
switch (tinst1 & 0xffe0) {
/* A6.3.5 Load/Store multiple */
case 0xe880: /* STM/STMIA/STMEA,LDM/LDMIA, PUSH/POP T2 */
case 0xe8a0: /* ...above writeback version */
case 0xe900: /* STMDB/STMFD, LDMDB/LDMEA */
case 0xe920: /* ...above writeback version */
/* no need offset decision since handler calculates it */
return do_alignment_ldmstm;
case 0xf840: /* POP/PUSH T3 (single register) */
if (RN_BITS(instr) == 13 && (tinst2 & 0x09ff) == 0x0904) {
u32 L = !!(LDST_L_BIT(instr));
const u32 subset[2] = {
0xe92d0000, /* STMDB sp!,{registers} */
0xe8bd0000, /* LDMIA sp!,{registers} */
};
*pinstr = subset[L] | (1<<RD_BITS(instr));
return do_alignment_ldmstm;
}
/* Else fall through for illegal instruction case */
break;
/* A6.3.6 Load/store double, STRD/LDRD(immed, lit, reg) */
case 0xe860:
case 0xe960:
case 0xe8e0:
case 0xe9e0:
poffset->un = (tinst2 & 0xff) << 2;
case 0xe940:
case 0xe9c0:
return do_alignment_ldrdstrd;
/*
* No need to handle load/store instructions up to word size
* since ARMv6 and later CPUs can perform unaligned accesses.
*/
default:
break;
}
return NULL;
}
static int
do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
union offset_union offset;
unsigned long instr = 0, instrptr;
int (*handler)(unsigned long addr, unsigned long instr, struct pt_regs *regs);
unsigned int type;
unsigned int fault;
u16 tinstr = 0;
int isize = 4;
int thumb2_32b = 0;
instrptr = instruction_pointer(regs);
if (thumb_mode(regs)) {
u16 *ptr = (u16 *)(instrptr & ~1);
fault = probe_kernel_address(ptr, tinstr);
if (!fault) {
if (cpu_architecture() >= CPU_ARCH_ARMv7 &&
IS_T32(tinstr)) {
/* Thumb-2 32-bit */
u16 tinst2 = 0;
fault = probe_kernel_address(ptr + 1, tinst2);
instr = (tinstr << 16) | tinst2;
thumb2_32b = 1;
} else {
isize = 2;
instr = thumb2arm(tinstr);
}
}
} else
fault = probe_kernel_address(instrptr, instr);
if (fault) {
type = TYPE_FAULT;
goto bad_or_fault;
}
if (user_mode(regs))
goto user;
ai_sys += 1;
fixup:
regs->ARM_pc += isize;
switch (CODING_BITS(instr)) {
case 0x00000000: /* 3.13.4 load/store instruction extensions */
if (LDSTHD_I_BIT(instr))
offset.un = (instr & 0xf00) >> 4 | (instr & 15);
else
offset.un = regs->uregs[RM_BITS(instr)];
if ((instr & 0x000000f0) == 0x000000b0 || /* LDRH, STRH */
(instr & 0x001000f0) == 0x001000f0) /* LDRSH */
handler = do_alignment_ldrhstrh;
else if ((instr & 0x001000f0) == 0x000000d0 || /* LDRD */
(instr & 0x001000f0) == 0x000000f0) /* STRD */
handler = do_alignment_ldrdstrd;
else if ((instr & 0x01f00ff0) == 0x01000090) /* SWP */
goto swp;
else
goto bad;
break;
case 0x04000000: /* ldr or str immediate */
offset.un = OFFSET_BITS(instr);
handler = do_alignment_ldrstr;
break;
case 0x06000000: /* ldr or str register */
offset.un = regs->uregs[RM_BITS(instr)];
if (IS_SHIFT(instr)) {
unsigned int shiftval = SHIFT_BITS(instr);
switch(SHIFT_TYPE(instr)) {
case SHIFT_LSL:
offset.un <<= shiftval;
break;
case SHIFT_LSR:
offset.un >>= shiftval;
break;
case SHIFT_ASR:
offset.sn >>= shiftval;
break;
case SHIFT_RORRRX:
if (shiftval == 0) {
offset.un >>= 1;
if (regs->ARM_cpsr & PSR_C_BIT)
offset.un |= 1 << 31;
} else
offset.un = offset.un >> shiftval |
offset.un << (32 - shiftval);
break;
}
}
handler = do_alignment_ldrstr;
break;
case 0x08000000: /* ldm or stm, or thumb-2 32bit instruction */
if (thumb2_32b)
handler = do_alignment_t32_to_handler(&instr, regs, &offset);
else
handler = do_alignment_ldmstm;
break;
default:
goto bad;
}
if (!handler)
goto bad;
type = handler(addr, instr, regs);
if (type == TYPE_ERROR || type == TYPE_FAULT) {
regs->ARM_pc -= isize;
goto bad_or_fault;
}
if (type == TYPE_LDST)
do_alignment_finish_ldst(addr, instr, regs, offset);
return 0;
bad_or_fault:
if (type == TYPE_ERROR)
goto bad;
/*
* We got a fault - fix it up, or die.
*/
do_bad_area(addr, fsr, regs);
return 0;
swp:
printk(KERN_ERR "Alignment trap: not handling swp instruction\n");
bad:
/*
* Oops, we didn't handle the instruction.
*/
printk(KERN_ERR "Alignment trap: not handling instruction "
"%0*lx at [<%08lx>]\n",
isize << 1,
isize == 2 ? tinstr : instr, instrptr);
ai_skipped += 1;
return 1;
user:
ai_user += 1;
if (ai_usermode & UM_WARN)
printk("Alignment trap: %s (%d) PC=0x%08lx Instr=0x%0*lx "
"Address=0x%08lx FSR 0x%03x\n", current->comm,
task_pid_nr(current), instrptr,
isize << 1,
isize == 2 ? tinstr : instr,
addr, fsr);
if (ai_usermode & UM_FIXUP)
goto fixup;
if (ai_usermode & UM_SIGNAL)
force_sig(SIGBUS, current);
else {
/*
* We're about to disable the alignment trap and return to
* user space. But if an interrupt occurs before actually
* reaching user space, then the IRQ vector entry code will
* notice that we were still in kernel space and therefore
* the alignment trap won't be re-enabled in that case as it
* is presumed to be always on from kernel space.
* Let's prevent that race by disabling interrupts here (they
* are disabled on the way back to user space anyway in
* entry-common.S) and disable the alignment trap only if
* there is no work pending for this thread.
*/
raw_local_irq_disable();
if (!(current_thread_info()->flags & _TIF_WORK_MASK))
set_cr(cr_no_alignment);
}
return 0;
}
/*
* This needs to be done after sysctl_init, otherwise sys/ will be
* overwritten. Actually, this shouldn't be in sys/ at all since
* it isn't a sysctl, and it doesn't contain sysctl information.
* We now locate it in /proc/cpu/alignment instead.
*/
static int __init alignment_init(void)
{
#if defined(CONFIG_PROC_FS) && !defined(CONFIG_FAST_RESUME)
struct proc_dir_entry *res;
res = proc_create("cpu/alignment", S_IWUSR | S_IRUGO, NULL,
&alignment_proc_fops);
if (!res)
return -ENOMEM;
#endif
/*
* ARMv6 and later CPUs can perform unaligned accesses for
* most single load and store instructions up to word size.
* LDM, STM, LDRD and STRD still need to be handled.
*
* Ignoring the alignment fault is not an option on these
* CPUs since we spin re-faulting the instruction without
* making any progress.
*/
if (cpu_architecture() >= CPU_ARCH_ARMv6 && (cr_alignment & CR_U)) {
cr_alignment &= ~CR_A;
cr_no_alignment &= ~CR_A;
set_cr(cr_alignment);
ai_usermode = UM_FIXUP;
}
hook_fault_code(1, do_alignment, SIGBUS, BUS_ADRALN,
"alignment exception");
/*
* ARMv6K and ARMv7 use fault status 3 (0b00011) as Access Flag section
* fault, not as alignment error.
*
* TODO: handle ARMv6K properly. Runtime check for 'K' extension is
* needed.
*/
if (cpu_architecture() <= CPU_ARCH_ARMv6) {
hook_fault_code(3, do_alignment, SIGBUS, BUS_ADRALN,
"alignment exception");
}
return 0;
}
#ifdef CONFIG_FAST_RESUME
beforeresume_initcall(alignment_init);
#else
fs_initcall(alignment_init);
#endif
| gpl-2.0 |
nmathewson/linux-2.6 | net/bridge/netfilter/ebtables.c | 53 | 64854 | /*
* ebtables
*
* Author:
* Bart De Schuymer <bdschuym@pandora.be>
*
* ebtables.c,v 2.0, July, 2002
*
* This code is stongly inspired on the iptables code which is
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <net/sock.h>
/* needed for logical [in,out]-dev filtering */
#include "../br_private.h"
#define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
"report to author: "format, ## args)
/* #define BUGPRINT(format, args...) */
/*
* Each cpu has its own set of counters, so there is no need for write_lock in
* the softirq
* For reading or updating the counters, the user context needs to
* get a write_lock
*/
/* The size of each set of counters is altered to get cache alignment */
#define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
#define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
#define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
COUNTER_OFFSET(n) * cpu))
static DEFINE_MUTEX(ebt_mutex);
#ifdef CONFIG_COMPAT
static void ebt_standard_compat_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v >= 0)
v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
memcpy(dst, &v, sizeof(v));
}
static int ebt_standard_compat_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv >= 0)
cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
#endif
static struct xt_target ebt_standard_target = {
.name = "standard",
.revision = 0,
.family = NFPROTO_BRIDGE,
.targetsize = sizeof(int),
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = ebt_standard_compat_from_user,
.compat_to_user = ebt_standard_compat_to_user,
#endif
};
static inline int
ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
struct xt_action_param *par)
{
par->target = w->u.watcher;
par->targinfo = w->data;
w->u.watcher->target(skb, par);
/* watchers don't give a verdict */
return 0;
}
static inline int
ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
struct xt_action_param *par)
{
par->match = m->u.match;
par->matchinfo = m->data;
return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
}
static inline int
ebt_dev_check(const char *entry, const struct net_device *device)
{
int i = 0;
const char *devname;
if (*entry == '\0')
return 0;
if (!device)
return 1;
devname = device->name;
/* 1 is the wildcard token */
while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
i++;
return (devname[i] != entry[i] && entry[i] != 1);
}
#define FWINV2(bool,invflg) ((bool) ^ !!(e->invflags & invflg))
/* process standard matches */
static inline int
ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out)
{
const struct ethhdr *h = eth_hdr(skb);
__be16 ethproto;
int verdict, i;
if (vlan_tx_tag_present(skb))
ethproto = htons(ETH_P_8021Q);
else
ethproto = h->h_proto;
if (e->bitmask & EBT_802_3) {
if (FWINV2(ntohs(ethproto) >= 1536, EBT_IPROTO))
return 1;
} else if (!(e->bitmask & EBT_NOPROTO) &&
FWINV2(e->ethproto != ethproto, EBT_IPROTO))
return 1;
if (FWINV2(ebt_dev_check(e->in, in), EBT_IIN))
return 1;
if (FWINV2(ebt_dev_check(e->out, out), EBT_IOUT))
return 1;
/* rcu_read_lock()ed by nf_hook_slow */
if (in && br_port_exists(in) &&
FWINV2(ebt_dev_check(e->logical_in, br_port_get_rcu(in)->br->dev),
EBT_ILOGICALIN))
return 1;
if (out && br_port_exists(out) &&
FWINV2(ebt_dev_check(e->logical_out, br_port_get_rcu(out)->br->dev),
EBT_ILOGICALOUT))
return 1;
if (e->bitmask & EBT_SOURCEMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_source[i] ^ e->sourcemac[i]) &
e->sourcemsk[i];
if (FWINV2(verdict != 0, EBT_ISOURCE) )
return 1;
}
if (e->bitmask & EBT_DESTMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_dest[i] ^ e->destmac[i]) &
e->destmsk[i];
if (FWINV2(verdict != 0, EBT_IDEST) )
return 1;
}
return 0;
}
static inline __pure
struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Do some firewalling */
unsigned int ebt_do_table (unsigned int hook, struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
struct ebt_table *table)
{
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.family = NFPROTO_BRIDGE;
acpar.in = in;
acpar.out = out;
acpar.hotdrop = false;
acpar.hooknum = hook;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, in, out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
what to do with the packet */
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
#ifdef CONFIG_NETFILTER_DEBUG
if (sp == 0) {
BUGPRINT("RETURN on base chain");
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
#endif
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
#ifdef CONFIG_NETFILTER_DEBUG
if (verdict < 0) {
BUGPRINT("bogus standard verdict\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
#ifdef CONFIG_NETFILTER_DEBUG
if (chaininfo->distinguisher) {
BUGPRINT("jump to non-chain\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* If it succeeds, returns element and locks mutex */
static inline void *
find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
struct mutex *mutex)
{
struct {
struct list_head list;
char name[EBT_FUNCTION_MAXNAMELEN];
} *e;
*error = mutex_lock_interruptible(mutex);
if (*error != 0)
return NULL;
list_for_each_entry(e, head, list) {
if (strcmp(e->name, name) == 0)
return e;
}
*error = -ENOENT;
mutex_unlock(mutex);
return NULL;
}
static void *
find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
int *error, struct mutex *mutex)
{
return try_then_request_module(
find_inlist_lock_noload(head, name, error, mutex),
"%s%s", prefix, name);
}
static inline struct ebt_table *
find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
static inline int
ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_match *match;
size_t left = ((char *)e + e->watchers_offset) - (char *)m;
int ret;
if (left < sizeof(struct ebt_entry_match) ||
left - sizeof(struct ebt_entry_match) < m->match_size)
return -EINVAL;
match = xt_request_find_match(NFPROTO_BRIDGE, m->u.name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
m->u.match = match;
par->match = match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->match_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(match->me);
return ret;
}
(*cnt)++;
return 0;
}
static inline int
ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_target *watcher;
size_t left = ((char *)e + e->target_offset) - (char *)w;
int ret;
if (left < sizeof(struct ebt_entry_watcher) ||
left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
return -EINVAL;
watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
if (IS_ERR(watcher))
return PTR_ERR(watcher);
w->u.watcher = watcher;
par->target = watcher;
par->targinfo = w->data;
ret = xt_check_target(par, w->watcher_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(watcher->me);
return ret;
}
(*cnt)++;
return 0;
}
static int ebt_verify_pointers(const struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
unsigned int limit = repl->entries_size;
unsigned int valid_hooks = repl->valid_hooks;
unsigned int offset = 0;
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++)
newinfo->hook_entry[i] = NULL;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
while (offset < limit) {
size_t left = limit - offset;
struct ebt_entry *e = (void *)newinfo->entries + offset;
if (left < sizeof(unsigned int))
break;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((valid_hooks & (1 << i)) == 0)
continue;
if ((char __user *)repl->hook_entry[i] ==
repl->entries + offset)
break;
}
if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
if (e->bitmask != 0) {
/* we make userspace set this right,
so there is no misunderstanding */
BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
"in distinguisher\n");
return -EINVAL;
}
if (i != NF_BR_NUMHOOKS)
newinfo->hook_entry[i] = (struct ebt_entries *)e;
if (left < sizeof(struct ebt_entries))
break;
offset += sizeof(struct ebt_entries);
} else {
if (left < sizeof(struct ebt_entry))
break;
if (left < e->next_offset)
break;
if (e->next_offset < sizeof(struct ebt_entry))
return -EINVAL;
offset += e->next_offset;
}
}
if (offset != limit) {
BUGPRINT("entries_size too small\n");
return -EINVAL;
}
/* check if all valid hooks have a chain */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i] &&
(valid_hooks & (1 << i))) {
BUGPRINT("Valid hook without chain\n");
return -EINVAL;
}
}
return 0;
}
/*
* this one is very careful, as it is the first function
* to parse the userspace data
*/
static inline int
ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
const struct ebt_table_info *newinfo,
unsigned int *n, unsigned int *cnt,
unsigned int *totalcnt, unsigned int *udc_cnt)
{
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((void *)e == (void *)newinfo->hook_entry[i])
break;
}
/* beginning of a new chain
if i == NF_BR_NUMHOOKS it must be a user defined chain */
if (i != NF_BR_NUMHOOKS || !e->bitmask) {
/* this checks if the previous chain has as many entries
as it said it has */
if (*n != *cnt) {
BUGPRINT("nentries does not equal the nr of entries "
"in the chain\n");
return -EINVAL;
}
if (((struct ebt_entries *)e)->policy != EBT_DROP &&
((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
/* only RETURN from udc */
if (i != NF_BR_NUMHOOKS ||
((struct ebt_entries *)e)->policy != EBT_RETURN) {
BUGPRINT("bad policy\n");
return -EINVAL;
}
}
if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
(*udc_cnt)++;
if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
BUGPRINT("counter_offset != totalcnt");
return -EINVAL;
}
*n = ((struct ebt_entries *)e)->nentries;
*cnt = 0;
return 0;
}
/* a plain old entry, heh */
if (sizeof(struct ebt_entry) > e->watchers_offset ||
e->watchers_offset > e->target_offset ||
e->target_offset >= e->next_offset) {
BUGPRINT("entry offsets not in right order\n");
return -EINVAL;
}
/* this is not checked anywhere else */
if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
BUGPRINT("target size too small\n");
return -EINVAL;
}
(*cnt)++;
(*totalcnt)++;
return 0;
}
struct ebt_cl_stack
{
struct ebt_chainstack cs;
int from;
unsigned int hookmask;
};
/*
* we need these positions to check that the jumps to a different part of the
* entries is a jump to the beginning of a new chain.
*/
static inline int
ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
unsigned int *n, struct ebt_cl_stack *udc)
{
int i;
/* we're only interested in chain starts */
if (e->bitmask)
return 0;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
break;
}
/* only care about udc */
if (i != NF_BR_NUMHOOKS)
return 0;
udc[*n].cs.chaininfo = (struct ebt_entries *)e;
/* these initialisations are depended on later in check_chainloops() */
udc[*n].cs.n = 0;
udc[*n].hookmask = 0;
(*n)++;
return 0;
}
static inline int
ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
{
struct xt_mtdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.match = m->u.match;
par.matchinfo = m->data;
par.family = NFPROTO_BRIDGE;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
return 0;
}
static inline int
ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
{
struct xt_tgdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.target = w->u.watcher;
par.targinfo = w->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
{
struct xt_tgdtor_param par;
struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
/* we're done */
if (cnt && (*cnt)-- == 0)
return 1;
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
par.net = net;
par.target = t->u.target;
par.targinfo = t->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_check_entry(struct ebt_entry *e, struct net *net,
const struct ebt_table_info *newinfo,
const char *name, unsigned int *cnt,
struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
{
struct ebt_entry_target *t;
struct xt_target *target;
unsigned int i, j, hook = 0, hookmask = 0;
size_t gap;
int ret;
struct xt_mtchk_param mtpar;
struct xt_tgchk_param tgpar;
/* don't mess with the struct ebt_entries */
if (e->bitmask == 0)
return 0;
if (e->bitmask & ~EBT_F_MASK) {
BUGPRINT("Unknown flag for bitmask\n");
return -EINVAL;
}
if (e->invflags & ~EBT_INV_MASK) {
BUGPRINT("Unknown flag for inv bitmask\n");
return -EINVAL;
}
if ( (e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3) ) {
BUGPRINT("NOPROTO & 802_3 not allowed\n");
return -EINVAL;
}
/* what hook do we belong to? */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i])
continue;
if ((char *)newinfo->hook_entry[i] < (char *)e)
hook = i;
else
break;
}
/* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
a base chain */
if (i < NF_BR_NUMHOOKS)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else {
for (i = 0; i < udc_cnt; i++)
if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
break;
if (i == 0)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else
hookmask = cl_s[i - 1].hookmask;
}
i = 0;
mtpar.net = tgpar.net = net;
mtpar.table = tgpar.table = name;
mtpar.entryinfo = tgpar.entryinfo = e;
mtpar.hook_mask = tgpar.hook_mask = hookmask;
mtpar.family = tgpar.family = NFPROTO_BRIDGE;
ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
if (ret != 0)
goto cleanup_matches;
j = 0;
ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
if (ret != 0)
goto cleanup_watchers;
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
gap = e->next_offset - e->target_offset;
target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto cleanup_watchers;
}
t->u.target = target;
if (t->u.target == &ebt_standard_target) {
if (gap < sizeof(struct ebt_standard_target)) {
BUGPRINT("Standard target size too big\n");
ret = -EFAULT;
goto cleanup_watchers;
}
if (((struct ebt_standard_target *)t)->verdict <
-NUM_STANDARD_TARGETS) {
BUGPRINT("Invalid standard target\n");
ret = -EFAULT;
goto cleanup_watchers;
}
} else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
module_put(t->u.target->me);
ret = -EFAULT;
goto cleanup_watchers;
}
tgpar.target = target;
tgpar.targinfo = t->data;
ret = xt_check_target(&tgpar, t->target_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(target->me);
goto cleanup_watchers;
}
(*cnt)++;
return 0;
cleanup_watchers:
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
cleanup_matches:
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
return ret;
}
/*
* checks for loops and sets the hook mask for udc
* the hook mask for udc tells us from which base chains the udc can be
* accessed. This mask is a parameter to the check() functions of the extensions
*/
static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
unsigned int udc_cnt, unsigned int hooknr, char *base)
{
int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
const struct ebt_entry *e = (struct ebt_entry *)chain->data;
const struct ebt_entry_target *t;
while (pos < nentries || chain_nr != -1) {
/* end of udc, go back one 'recursion' step */
if (pos == nentries) {
/* put back values of the time when this chain was called */
e = cl_s[chain_nr].cs.e;
if (cl_s[chain_nr].from != -1)
nentries =
cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
else
nentries = chain->nentries;
pos = cl_s[chain_nr].cs.n;
/* make sure we won't see a loop that isn't one */
cl_s[chain_nr].cs.n = 0;
chain_nr = cl_s[chain_nr].from;
if (pos == nentries)
continue;
}
t = (struct ebt_entry_target *)
(((char *)e) + e->target_offset);
if (strcmp(t->u.name, EBT_STANDARD_TARGET))
goto letscontinue;
if (e->target_offset + sizeof(struct ebt_standard_target) >
e->next_offset) {
BUGPRINT("Standard target size too big\n");
return -1;
}
verdict = ((struct ebt_standard_target *)t)->verdict;
if (verdict >= 0) { /* jump to another chain */
struct ebt_entries *hlp2 =
(struct ebt_entries *)(base + verdict);
for (i = 0; i < udc_cnt; i++)
if (hlp2 == cl_s[i].cs.chaininfo)
break;
/* bad destination or loop */
if (i == udc_cnt) {
BUGPRINT("bad destination\n");
return -1;
}
if (cl_s[i].cs.n) {
BUGPRINT("loop\n");
return -1;
}
if (cl_s[i].hookmask & (1 << hooknr))
goto letscontinue;
/* this can't be 0, so the loop test is correct */
cl_s[i].cs.n = pos + 1;
pos = 0;
cl_s[i].cs.e = ebt_next_entry(e);
e = (struct ebt_entry *)(hlp2->data);
nentries = hlp2->nentries;
cl_s[i].from = chain_nr;
chain_nr = i;
/* this udc is accessible from the base chain for hooknr */
cl_s[i].hookmask |= (1 << hooknr);
continue;
}
letscontinue:
e = ebt_next_entry(e);
pos++;
}
return 0;
}
/* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
static int translate_table(struct net *net, const char *name,
struct ebt_table_info *newinfo)
{
unsigned int i, j, k, udc_cnt;
int ret;
struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
i = 0;
while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
i++;
if (i == NF_BR_NUMHOOKS) {
BUGPRINT("No valid hooks specified\n");
return -EINVAL;
}
if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
BUGPRINT("Chains don't start at beginning\n");
return -EINVAL;
}
/* make sure chains are ordered after each other in same order
as their corresponding hooks */
for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
if (!newinfo->hook_entry[j])
continue;
if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
BUGPRINT("Hook order must be followed\n");
return -EINVAL;
}
i = j;
}
/* do some early checkings and initialize some things */
i = 0; /* holds the expected nr. of entries for the chain */
j = 0; /* holds the up to now counted entries for the chain */
k = 0; /* holds the total nr. of entries, should equal
newinfo->nentries afterwards */
udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry_size_and_hooks, newinfo,
&i, &j, &k, &udc_cnt);
if (ret != 0)
return ret;
if (i != j) {
BUGPRINT("nentries does not equal the nr of entries in the "
"(last) chain\n");
return -EINVAL;
}
if (k != newinfo->nentries) {
BUGPRINT("Total nentries is wrong\n");
return -EINVAL;
}
/* get the location of the udc, put them in an array
while we're at it, allocate the chainstack */
if (udc_cnt) {
/* this will get free'd in do_replace()/ebt_register_table()
if an error occurs */
newinfo->chainstack =
vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
if (!newinfo->chainstack)
return -ENOMEM;
for_each_possible_cpu(i) {
newinfo->chainstack[i] =
vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
if (!newinfo->chainstack[i]) {
while (i)
vfree(newinfo->chainstack[--i]);
vfree(newinfo->chainstack);
newinfo->chainstack = NULL;
return -ENOMEM;
}
}
cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
if (!cl_s)
return -ENOMEM;
i = 0; /* the i'th udc */
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_get_udc_positions, newinfo, &i, cl_s);
/* sanity check */
if (i != udc_cnt) {
BUGPRINT("i != udc_cnt\n");
vfree(cl_s);
return -EFAULT;
}
}
/* Check for loops */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
if (newinfo->hook_entry[i])
if (check_chainloops(newinfo->hook_entry[i],
cl_s, udc_cnt, i, newinfo->entries)) {
vfree(cl_s);
return -EINVAL;
}
/* we now know the following (along with E=mc²):
- the nr of entries in each chain is right
- the size of the allocated space is right
- all valid hooks have a corresponding chain
- there are no loops
- wrong data can still be on the level of a single entry
- could be there are jumps to places that are not the
beginning of a chain. This can only occur in chains that
are not accessible from any base chains, so we don't care. */
/* used to know what we need to clean up if something goes wrong */
i = 0;
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
if (ret != 0) {
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, &i);
}
vfree(cl_s);
return ret;
}
/* called under write_lock */
static void get_counters(const struct ebt_counter *oldcounters,
struct ebt_counter *counters, unsigned int nentries)
{
int i, cpu;
struct ebt_counter *counter_base;
/* counters of cpu 0 */
memcpy(counters, oldcounters,
sizeof(struct ebt_counter) * nentries);
/* add other counters to those of cpu 0 */
for_each_possible_cpu(cpu) {
if (cpu == 0)
continue;
counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
for (i = 0; i < nentries; i++) {
counters[i].pcnt += counter_base[i].pcnt;
counters[i].bcnt += counter_base[i].bcnt;
}
}
}
static int do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
the check on the size is done later, when we have the lock */
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
allocation. Only reason why this is done is because this way the lock
is held only once, while this doesn't bring the kernel into a
dangerous state. */
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
ret = -EFAULT;
}
else
ret = 0;
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
/* replace the table */
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
struct ebt_table *
ebt_register_table(struct net *net, const struct ebt_table *input_table)
{
struct ebt_table_info *newinfo;
struct ebt_table *t, *table;
struct ebt_replace_kernel *repl;
int ret, i, countersize;
void *p;
if (input_table == NULL || (repl = input_table->table) == NULL ||
repl->entries == 0 || repl->entries_size == 0 ||
repl->counters != NULL || input_table->private != NULL) {
BUGPRINT("Bad table data for ebt_register_table!!!\n");
return ERR_PTR(-EINVAL);
}
/* Don't add one table to multiple lists. */
table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
ret = -ENOMEM;
if (!newinfo)
goto free_table;
p = vmalloc(repl->entries_size);
if (!p)
goto free_newinfo;
memcpy(p, repl->entries, repl->entries_size);
newinfo->entries = p;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
if (countersize)
memset(newinfo->counters, 0, countersize);
/* fill in newinfo and parse the entries */
newinfo->chainstack = NULL;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((repl->valid_hooks & (1 << i)) == 0)
newinfo->hook_entry[i] = NULL;
else
newinfo->hook_entry[i] = p +
((char *)repl->hook_entry[i] - repl->entries);
}
ret = translate_table(net, repl->name, newinfo);
if (ret != 0) {
BUGPRINT("Translate_table failed\n");
goto free_chainstack;
}
if (table->check && table->check(newinfo, table->valid_hooks)) {
BUGPRINT("The table doesn't like its own initial data, lol\n");
return ERR_PTR(-EINVAL);
}
table->private = newinfo;
rwlock_init(&table->lock);
ret = mutex_lock_interruptible(&ebt_mutex);
if (ret != 0)
goto free_chainstack;
list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
if (strcmp(t->name, table->name) == 0) {
ret = -EEXIST;
BUGPRINT("Table name already exists\n");
goto free_unlock;
}
}
/* Hold a reference count if the chains aren't empty */
if (newinfo->nentries && !try_module_get(table->me)) {
ret = -ENOENT;
goto free_unlock;
}
list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
mutex_unlock(&ebt_mutex);
return table;
free_unlock:
mutex_unlock(&ebt_mutex);
free_chainstack:
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
free_table:
kfree(table);
out:
return ERR_PTR(ret);
}
void ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
if (!table) {
BUGPRINT("Request to unregister NULL table!!!\n");
return;
}
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
/* userspace just supplied us with counters */
static int do_update_counters(struct net *net, const char *name,
struct ebt_counter __user *counters,
unsigned int num_counters,
const void __user *user, unsigned int len)
{
int i, ret;
struct ebt_counter *tmp;
struct ebt_table *t;
if (num_counters == 0)
return -EINVAL;
tmp = vmalloc(num_counters * sizeof(*tmp));
if (!tmp)
return -ENOMEM;
t = find_table_lock(net, name, &ret, &ebt_mutex);
if (!t)
goto free_tmp;
if (num_counters != t->private->nentries) {
BUGPRINT("Wrong nr of counters\n");
ret = -EINVAL;
goto unlock_mutex;
}
if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
ret = -EFAULT;
goto unlock_mutex;
}
/* we want an atomic add of the counters */
write_lock_bh(&t->lock);
/* we add to the counters of the first cpu */
for (i = 0; i < num_counters; i++) {
t->private->counters[i].pcnt += tmp[i].pcnt;
t->private->counters[i].bcnt += tmp[i].bcnt;
}
write_unlock_bh(&t->lock);
ret = 0;
unlock_mutex:
mutex_unlock(&ebt_mutex);
free_tmp:
vfree(tmp);
return ret;
}
static int update_counters(struct net *net, const void __user *user,
unsigned int len)
{
struct ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return -EINVAL;
return do_update_counters(net, hlp.name, hlp.counters,
hlp.num_counters, user, len);
}
static inline int ebt_make_matchname(const struct ebt_entry_match *m,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)m - base);
if (copy_to_user(hlp, m->u.match->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int ebt_make_watchername(const struct ebt_entry_watcher *w,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)w - base);
if (copy_to_user(hlp , w->u.watcher->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int
ebt_make_names(struct ebt_entry *e, const char *base, char __user *ubase)
{
int ret;
char __user *hlp;
const struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
hlp = ubase + (((char *)e + e->target_offset) - base);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase);
if (ret != 0)
return ret;
ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase);
if (ret != 0)
return ret;
if (copy_to_user(hlp, t->u.target->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static int copy_counters_to_user(struct ebt_table *t,
const struct ebt_counter *oldcounters,
void __user *user, unsigned int num_counters,
unsigned int nentries)
{
struct ebt_counter *counterstmp;
int ret = 0;
/* userspace might not need the counters */
if (num_counters == 0)
return 0;
if (num_counters != nentries) {
BUGPRINT("Num_counters wrong\n");
return -EINVAL;
}
counterstmp = vmalloc(nentries * sizeof(*counterstmp));
if (!counterstmp)
return -ENOMEM;
write_lock_bh(&t->lock);
get_counters(oldcounters, counterstmp, nentries);
write_unlock_bh(&t->lock);
if (copy_to_user(user, counterstmp,
nentries * sizeof(struct ebt_counter)))
ret = -EFAULT;
vfree(counterstmp);
return ret;
}
/* called with ebt_mutex locked */
static int copy_everything_to_user(struct ebt_table *t, void __user *user,
const int *len, int cmd)
{
struct ebt_replace tmp;
const struct ebt_counter *oldcounters;
unsigned int entries_size, nentries;
int ret;
char *entries;
if (cmd == EBT_SO_GET_ENTRIES) {
entries_size = t->private->entries_size;
nentries = t->private->nentries;
entries = t->private->entries;
oldcounters = t->private->counters;
} else {
entries_size = t->table->entries_size;
nentries = t->table->nentries;
entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (*len != sizeof(struct ebt_replace) + entries_size +
(tmp.num_counters? nentries * sizeof(struct ebt_counter): 0))
return -EINVAL;
if (tmp.nentries != nentries) {
BUGPRINT("Nentries wrong\n");
return -EINVAL;
}
if (tmp.entries_size != entries_size) {
BUGPRINT("Wrong size\n");
return -EINVAL;
}
ret = copy_counters_to_user(t, oldcounters, tmp.counters,
tmp.num_counters, nentries);
if (ret)
return ret;
if (copy_to_user(tmp.entries, entries, entries_size)) {
BUGPRINT("Couldn't copy entries to userspace\n");
return -EFAULT;
}
/* set the match/watcher/target names right */
return EBT_ENTRY_ITERATE(entries, entries_size,
ebt_make_names, entries, tmp.entries);
}
static int do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch(cmd) {
case EBT_SO_SET_ENTRIES:
ret = do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
struct ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
switch(cmd) {
case EBT_SO_GET_INFO:
case EBT_SO_GET_INIT_INFO:
if (*len != sizeof(struct ebt_replace)){
ret = -EINVAL;
mutex_unlock(&ebt_mutex);
break;
}
if (cmd == EBT_SO_GET_INFO) {
tmp.nentries = t->private->nentries;
tmp.entries_size = t->private->entries_size;
tmp.valid_hooks = t->valid_hooks;
} else {
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
}
mutex_unlock(&ebt_mutex);
if (copy_to_user(user, &tmp, *len) != 0){
BUGPRINT("c2u Didn't work\n");
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
ret = copy_everything_to_user(t, user, len, cmd);
mutex_unlock(&ebt_mutex);
break;
default:
mutex_unlock(&ebt_mutex);
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_COMPAT
/* 32 bit-userspace compatibility definitions. */
struct compat_ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
compat_uint_t valid_hooks;
compat_uint_t nentries;
compat_uint_t entries_size;
/* start of the chains */
compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
/* nr of counters userspace expects back */
compat_uint_t num_counters;
/* where the kernel will put the old counters. */
compat_uptr_t counters;
compat_uptr_t entries;
};
/* struct ebt_entry_match, _target and _watcher have same layout */
struct compat_ebt_entry_mwt {
union {
char name[EBT_FUNCTION_MAXNAMELEN];
compat_uptr_t ptr;
} u;
compat_uint_t match_size;
compat_uint_t data[0];
};
/* account for possible padding between match_size and ->data */
static int ebt_compat_entry_padsize(void)
{
BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
}
static int ebt_compat_match_offset(const struct xt_match *match,
unsigned int userlen)
{
/*
* ebt_among needs special handling. The kernel .matchsize is
* set to -1 at registration time; at runtime an EBT_ALIGN()ed
* value is expected.
* Example: userspace sends 4500, ebt_among.c wants 4504.
*/
if (unlikely(match->matchsize == -1))
return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
return xt_compat_match_offset(match);
}
static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
unsigned int *size)
{
const struct xt_match *match = m->u.match;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = ebt_compat_match_offset(match, m->match_size);
compat_uint_t msize = m->match_size - off;
BUG_ON(off >= m->match_size);
if (copy_to_user(cm->u.name, match->name,
strlen(match->name) + 1) || put_user(msize, &cm->match_size))
return -EFAULT;
if (match->compat_to_user) {
if (match->compat_to_user(cm->data, m->data))
return -EFAULT;
} else if (copy_to_user(cm->data, m->data, msize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += msize;
return 0;
}
static int compat_target_to_user(struct ebt_entry_target *t,
void __user **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.target;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = xt_compat_target_offset(target);
compat_uint_t tsize = t->target_size - off;
BUG_ON(off >= t->target_size);
if (copy_to_user(cm->u.name, target->name,
strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
return -EFAULT;
if (target->compat_to_user) {
if (target->compat_to_user(cm->data, t->data))
return -EFAULT;
} else if (copy_to_user(cm->data, t->data, tsize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += tsize;
return 0;
}
static int compat_watcher_to_user(struct ebt_entry_watcher *w,
void __user **dstptr,
unsigned int *size)
{
return compat_target_to_user((struct ebt_entry_target *)w,
dstptr, size);
}
static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
unsigned int *size)
{
struct ebt_entry_target *t;
struct ebt_entry __user *ce;
u32 watchers_offset, target_offset, next_offset;
compat_uint_t origsize;
int ret;
if (e->bitmask == 0) {
if (*size < sizeof(struct ebt_entries))
return -EINVAL;
if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
return -EFAULT;
*dstptr += sizeof(struct ebt_entries);
*size -= sizeof(struct ebt_entries);
return 0;
}
if (*size < sizeof(*ce))
return -EINVAL;
ce = (struct ebt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(*ce)))
return -EFAULT;
origsize = *size;
*dstptr += sizeof(*ce);
ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
if (ret)
return ret;
watchers_offset = e->watchers_offset - (origsize - *size);
ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
if (ret)
return ret;
target_offset = e->target_offset - (origsize - *size);
t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
ret = compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(watchers_offset, &ce->watchers_offset) ||
put_user(target_offset, &ce->target_offset) ||
put_user(next_offset, &ce->next_offset))
return -EFAULT;
*size -= sizeof(*ce);
return 0;
}
static int compat_calc_match(struct ebt_entry_match *m, int *off)
{
*off += ebt_compat_match_offset(m->u.match, m->match_size);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
{
*off += xt_compat_target_offset(w->u.watcher);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_entry(const struct ebt_entry *e,
const struct ebt_table_info *info,
const void *base,
struct compat_ebt_replace *newinfo)
{
const struct ebt_entry_target *t;
unsigned int entry_offset;
int off, ret, i;
if (e->bitmask == 0)
return 0;
off = 0;
entry_offset = (void *)e - base;
EBT_MATCH_ITERATE(e, compat_calc_match, &off);
EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
off += xt_compat_target_offset(t->u.target);
off += ebt_compat_entry_padsize();
newinfo->entries_size -= off;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
const void *hookptr = info->hook_entry[i];
if (info->hook_entry[i] &&
(e < (struct ebt_entry *)(base - hookptr))) {
newinfo->hook_entry[i] -= off;
pr_debug("0x%08X -> 0x%08X\n",
newinfo->hook_entry[i] + off,
newinfo->hook_entry[i]);
}
}
return 0;
}
static int compat_table_info(const struct ebt_table_info *info,
struct compat_ebt_replace *newinfo)
{
unsigned int size = info->entries_size;
const void *entries = info->entries;
newinfo->entries_size = size;
return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
entries, newinfo);
}
static int compat_copy_everything_to_user(struct ebt_table *t,
void __user *user, int *len, int cmd)
{
struct compat_ebt_replace repl, tmp;
struct ebt_counter *oldcounters;
struct ebt_table_info tinfo;
int ret;
void __user *pos;
memset(&tinfo, 0, sizeof(tinfo));
if (cmd == EBT_SO_GET_ENTRIES) {
tinfo.entries_size = t->private->entries_size;
tinfo.nentries = t->private->nentries;
tinfo.entries = t->private->entries;
oldcounters = t->private->counters;
} else {
tinfo.entries_size = t->table->entries_size;
tinfo.nentries = t->table->nentries;
tinfo.entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (tmp.nentries != tinfo.nentries ||
(tmp.num_counters && tmp.num_counters != tinfo.nentries))
return -EINVAL;
memcpy(&repl, &tmp, sizeof(repl));
if (cmd == EBT_SO_GET_ENTRIES)
ret = compat_table_info(t->private, &repl);
else
ret = compat_table_info(&tinfo, &repl);
if (ret)
return ret;
if (*len != sizeof(tmp) + repl.entries_size +
(tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
*len, tinfo.entries_size, repl.entries_size);
return -EINVAL;
}
/* userspace might not need the counters */
ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
tmp.num_counters, tinfo.nentries);
if (ret)
return ret;
pos = compat_ptr(tmp.entries);
return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
compat_copy_entry_to_user, &pos, &tmp.entries_size);
}
struct ebt_entries_buf_state {
char *buf_kern_start; /* kernel buffer to copy (translated) data to */
u32 buf_kern_len; /* total size of kernel buffer */
u32 buf_kern_offset; /* amount of data copied so far */
u32 buf_user_offset; /* read position in userspace buffer */
};
static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
{
state->buf_kern_offset += sz;
return state->buf_kern_offset >= sz ? 0 : -EINVAL;
}
static int ebt_buf_add(struct ebt_entries_buf_state *state,
void *data, unsigned int sz)
{
if (state->buf_kern_start == NULL)
goto count_only;
BUG_ON(state->buf_kern_offset + sz > state->buf_kern_len);
memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
count_only:
state->buf_user_offset += sz;
return ebt_buf_count(state, sz);
}
static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
{
char *b = state->buf_kern_start;
BUG_ON(b && state->buf_kern_offset > state->buf_kern_len);
if (b != NULL && sz > 0)
memset(b + state->buf_kern_offset, 0, sz);
/* do not adjust ->buf_user_offset here, we added kernel-side padding */
return ebt_buf_count(state, sz);
}
enum compat_mwt {
EBT_COMPAT_MATCH,
EBT_COMPAT_WATCHER,
EBT_COMPAT_TARGET,
};
static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt,
enum compat_mwt compat_mwt,
struct ebt_entries_buf_state *state,
const unsigned char *base)
{
char name[EBT_FUNCTION_MAXNAMELEN];
struct xt_match *match;
struct xt_target *wt;
void *dst = NULL;
int off, pad = 0, ret = 0;
unsigned int size_kern, entry_offset, match_size = mwt->match_size;
strlcpy(name, mwt->u.name, sizeof(name));
if (state->buf_kern_start)
dst = state->buf_kern_start + state->buf_kern_offset;
entry_offset = (unsigned char *) mwt - base;
switch (compat_mwt) {
case EBT_COMPAT_MATCH:
match = try_then_request_module(xt_find_match(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (match == NULL)
return -ENOENT;
if (IS_ERR(match))
return PTR_ERR(match);
off = ebt_compat_match_offset(match, match_size);
if (dst) {
if (match->compat_from_user)
match->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = match->matchsize;
if (unlikely(size_kern == -1))
size_kern = match_size;
module_put(match->me);
break;
case EBT_COMPAT_WATCHER: /* fallthrough */
case EBT_COMPAT_TARGET:
wt = try_then_request_module(xt_find_target(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (wt == NULL)
return -ENOENT;
if (IS_ERR(wt))
return PTR_ERR(wt);
off = xt_compat_target_offset(wt);
if (dst) {
if (wt->compat_from_user)
wt->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = wt->targetsize;
module_put(wt->me);
break;
}
if (!dst) {
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset,
off + ebt_compat_entry_padsize());
if (ret < 0)
return ret;
}
state->buf_kern_offset += match_size + off;
state->buf_user_offset += match_size;
pad = XT_ALIGN(size_kern) - size_kern;
if (pad > 0 && dst) {
BUG_ON(state->buf_kern_len <= pad);
BUG_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad);
memset(dst + size_kern, 0, pad);
}
return off + match_size;
}
/*
* return size of all matches, watchers or target, including necessary
* alignment and padding.
*/
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
BUG_ON(ret < match32->match_size);
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
#define EBT_COMPAT_WATCHER_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__watcher; \
\
for (__i = e->watchers_offset; \
__i < (e)->target_offset; \
__i += __watcher->watcher_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__watcher = (void *)(e) + __i; \
__ret = fn(__watcher , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->target_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
#define EBT_COMPAT_MATCH_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__match; \
\
for (__i = sizeof(struct ebt_entry); \
__i < (e)->watchers_offset; \
__i += __match->match_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__match = (void *)(e) + __i; \
__ret = fn(__match , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->watchers_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
/* called for all ebt_entry structures. */
static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/*
* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start;
buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
startoff = state->buf_user_offset - startoff;
BUG_ON(*total < startoff);
*total -= startoff;
return 0;
}
/*
* repl->entries_size is the size of the ebt_entry blob in userspace.
* It might need more memory when copied to a 64 bit kernel in case
* userspace is 32-bit. So, first task: find out how much memory is needed.
*
* Called before validation is performed.
*/
static int compat_copy_entries(unsigned char *data, unsigned int size_user,
struct ebt_entries_buf_state *state)
{
unsigned int size_remaining = size_user;
int ret;
ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
&size_remaining, state);
if (ret < 0)
return ret;
WARN_ON(size_remaining);
return state->buf_kern_offset;
}
static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
void __user *user, unsigned int len)
{
struct compat_ebt_replace tmp;
int i;
if (len < sizeof(tmp))
return -EINVAL;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size)
return -EINVAL;
if (tmp.entries_size == 0)
return -EINVAL;
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
/* starting with hook_entry, 32 vs. 64 bit structures are different */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
repl->num_counters = tmp.num_counters;
repl->counters = compat_ptr(tmp.counters);
repl->entries = compat_ptr(tmp.entries);
return 0;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret, i, countersize, size64;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
struct ebt_entries_buf_state state;
void *entries_tmp;
ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
if (ret) {
/* try real handler in case userland supplied needed padding */
if (ret == -EINVAL && do_replace(net, user, len) == 0)
ret = 0;
return ret;
}
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
memset(&state, 0, sizeof(state));
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
ret = -EFAULT;
goto free_entries;
}
entries_tmp = newinfo->entries;
xt_compat_lock(NFPROTO_BRIDGE);
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (ret < 0)
goto out_unlock;
pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
size64 = ret;
newinfo->entries = vmalloc(size64);
if (!newinfo->entries) {
vfree(entries_tmp);
ret = -ENOMEM;
goto out_unlock;
}
memset(&state, 0, sizeof(state));
state.buf_kern_start = newinfo->entries;
state.buf_kern_len = size64;
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
BUG_ON(ret < 0); /* parses same data again */
vfree(entries_tmp);
tmp.entries_size = size64;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
char __user *usrptr;
if (tmp.hook_entry[i]) {
unsigned int delta;
usrptr = (char __user *) tmp.hook_entry[i];
delta = usrptr - tmp.entries;
usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
}
}
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
goto free_entries;
}
static int compat_update_counters(struct net *net, void __user *user,
unsigned int len)
{
struct compat_ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
/* try real handler in case userland supplied needed padding */
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return update_counters(net, user, len);
return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
hlp.num_counters, user, len);
}
static int compat_do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = compat_update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
void __user *user, int *len)
{
int ret;
struct compat_ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* try real handler in case userland supplied needed padding */
if ((cmd == EBT_SO_GET_INFO ||
cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
return do_ebt_get_ctl(sk, cmd, user, len);
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
xt_compat_lock(NFPROTO_BRIDGE);
switch (cmd) {
case EBT_SO_GET_INFO:
tmp.nentries = t->private->nentries;
ret = compat_table_info(t->private, &tmp);
if (ret)
goto out;
tmp.valid_hooks = t->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_INIT_INFO:
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
/*
* try real handler first in case of userland-side padding.
* in case we are dealing with an 'ordinary' 32 bit binary
* without 64bit compatibility padding, this will fail right
* after copy_from_user when the *len argument is validated.
*
* the compat_ variant needs to do one pass over the kernel
* data set to adjust for size differences before it the check.
*/
if (copy_everything_to_user(t, user, len, cmd) == 0)
ret = 0;
else
ret = compat_copy_everything_to_user(t, user, len, cmd);
break;
default:
ret = -EINVAL;
}
out:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
mutex_unlock(&ebt_mutex);
return ret;
}
#endif
static struct nf_sockopt_ops ebt_sockopts =
{
.pf = PF_INET,
.set_optmin = EBT_BASE_CTL,
.set_optmax = EBT_SO_SET_MAX + 1,
.set = do_ebt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ebt_set_ctl,
#endif
.get_optmin = EBT_BASE_CTL,
.get_optmax = EBT_SO_GET_MAX + 1,
.get = do_ebt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ebt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __init ebtables_init(void)
{
int ret;
ret = xt_register_target(&ebt_standard_target);
if (ret < 0)
return ret;
ret = nf_register_sockopt(&ebt_sockopts);
if (ret < 0) {
xt_unregister_target(&ebt_standard_target);
return ret;
}
printk(KERN_INFO "Ebtables v2.0 registered\n");
return 0;
}
static void __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
printk(KERN_INFO "Ebtables v2.0 unregistered\n");
}
EXPORT_SYMBOL(ebt_register_table);
EXPORT_SYMBOL(ebt_unregister_table);
EXPORT_SYMBOL(ebt_do_table);
module_init(ebtables_init);
module_exit(ebtables_fini);
MODULE_LICENSE("GPL");
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE601KL | external/iproute2/lib/ll_map.c | 53 | 4158 | /*
* ll_map.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <linux/if.h>
#include "libnetlink.h"
#include "ll_map.h"
extern unsigned int if_nametoindex (const char *);
struct ll_cache
{
struct ll_cache *idx_next;
unsigned flags;
int index;
unsigned short type;
unsigned short alen;
char name[IFNAMSIZ];
unsigned char addr[20];
};
#define IDXMAP_SIZE 1024
static struct ll_cache *idx_head[IDXMAP_SIZE];
static inline struct ll_cache *idxhead(int idx)
{
return idx_head[idx & (IDXMAP_SIZE - 1)];
}
int ll_remember_index(const struct sockaddr_nl *who,
struct nlmsghdr *n, void *arg)
{
int h;
struct ifinfomsg *ifi = NLMSG_DATA(n);
struct ll_cache *im, **imp;
struct rtattr *tb[IFLA_MAX+1];
if (n->nlmsg_type != RTM_NEWLINK)
return 0;
if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi)))
return -1;
memset(tb, 0, sizeof(tb));
parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n));
if (tb[IFLA_IFNAME] == NULL)
return 0;
h = ifi->ifi_index & (IDXMAP_SIZE - 1);
for (imp = &idx_head[h]; (im=*imp)!=NULL; imp = &im->idx_next)
if (im->index == ifi->ifi_index)
break;
if (im == NULL) {
im = malloc(sizeof(*im));
if (im == NULL)
return 0;
im->idx_next = *imp;
im->index = ifi->ifi_index;
*imp = im;
}
im->type = ifi->ifi_type;
im->flags = ifi->ifi_flags;
if (tb[IFLA_ADDRESS]) {
int alen;
im->alen = alen = RTA_PAYLOAD(tb[IFLA_ADDRESS]);
if (alen > sizeof(im->addr))
alen = sizeof(im->addr);
memcpy(im->addr, RTA_DATA(tb[IFLA_ADDRESS]), alen);
} else {
im->alen = 0;
memset(im->addr, 0, sizeof(im->addr));
}
strcpy(im->name, RTA_DATA(tb[IFLA_IFNAME]));
return 0;
}
const char *ll_idx_n2a(unsigned idx, char *buf)
{
const struct ll_cache *im;
if (idx == 0)
return "*";
for (im = idxhead(idx); im; im = im->idx_next)
if (im->index == idx)
return im->name;
snprintf(buf, IFNAMSIZ, "if%d", idx);
return buf;
}
const char *ll_index_to_name(unsigned idx)
{
static char nbuf[IFNAMSIZ];
return ll_idx_n2a(idx, nbuf);
}
int ll_index_to_type(unsigned idx)
{
const struct ll_cache *im;
if (idx == 0)
return -1;
for (im = idxhead(idx); im; im = im->idx_next)
if (im->index == idx)
return im->type;
return -1;
}
unsigned ll_index_to_flags(unsigned idx)
{
const struct ll_cache *im;
if (idx == 0)
return 0;
for (im = idxhead(idx); im; im = im->idx_next)
if (im->index == idx)
return im->flags;
return 0;
}
unsigned ll_index_to_addr(unsigned idx, unsigned char *addr,
unsigned alen)
{
const struct ll_cache *im;
if (idx == 0)
return 0;
for (im = idxhead(idx); im; im = im->idx_next) {
if (im->index == idx) {
if (alen > sizeof(im->addr))
alen = sizeof(im->addr);
if (alen > im->alen)
alen = im->alen;
memcpy(addr, im->addr, alen);
return alen;
}
}
return 0;
}
unsigned ll_name_to_index(const char *name)
{
static char ncache[IFNAMSIZ];
static int icache;
struct ll_cache *im;
int i;
unsigned idx;
if (name == NULL)
return 0;
if (icache && strcmp(name, ncache) == 0)
return icache;
for (i=0; i<IDXMAP_SIZE; i++) {
for (im = idx_head[i]; im; im = im->idx_next) {
if (strcmp(im->name, name) == 0) {
icache = im->index;
strcpy(ncache, name);
return im->index;
}
}
}
idx = if_nametoindex(name);
if (idx == 0)
sscanf(name, "if%u", &idx);
return idx;
}
int ll_init_map(struct rtnl_handle *rth)
{
static int initialized;
if (initialized)
return 0;
if (rtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK) < 0) {
perror("Cannot send dump request");
exit(1);
}
if (rtnl_dump_filter(rth, ll_remember_index, NULL) < 0) {
fprintf(stderr, "Dump terminated\n");
exit(1);
}
initialized = 1;
return 0;
}
| gpl-2.0 |
scotthartbti/android_kernel_huawei_angler | drivers/soc/qcom/ipc_router_mhi_xprt.c | 309 | 27743 | /* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
* IPC ROUTER MHI XPRT module.
*/
#include <linux/delay.h>
#include <linux/ipc_router_xprt.h>
#include <linux/module.h>
#include <linux/msm_mhi.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/types.h>
static int ipc_router_mhi_xprt_debug_mask;
module_param_named(debug_mask, ipc_router_mhi_xprt_debug_mask,
int, S_IRUGO | S_IWUSR | S_IWGRP);
#define D(x...) do { \
if (ipc_router_mhi_xprt_debug_mask) \
pr_info(x); \
} while (0)
#define NUM_MHI_XPRTS 1
#define XPRT_NAME_LEN 32
#define IPC_ROUTER_MHI_XPRT_MAX_PKT_SIZE 0x1000
#define IPC_ROUTER_MHI_XPRT_NUM_TRBS 10
/**
* ipc_router_mhi_channel - MHI Channel related information
* @out_chan_id: Out channel ID for use by IPC ROUTER enumerated in MHI driver.
* @out_handle: MHI Output channel handle.
* @out_clnt_info: IPC Router callbacks/info to be passed to the MHI driver.
* @in_chan_id: In channel ID for use by IPC ROUTER enumerated in MHI driver.
* @in_handle: MHI Input channel handle.
* @in_clnt_info: IPC Router callbacks/info to be passed to the MHI driver.
* @state_lock: Lock to protect access to the state information.
* @out_chan_enabled: State of the outgoing channel.
* @in_chan_enabled: State of the incoming channel.
* @bytes_to_tx: Remaining bytes to be transmitted in a packet.
* @bytes_to_rx: Remaining bytes to be received in a packet.
* @in_skbq_lock: Lock to protect access to the input skbs queue.
* @in_skbq: Queue containing the input buffers.
* @max_packet_size: Possible maximum packet size.
* @num_trbs: Number of TRBs.
* @mhi_xprtp: Pointer to IPC Router MHI XPRT.
*/
struct ipc_router_mhi_channel {
enum MHI_CLIENT_CHANNEL out_chan_id;
struct mhi_client_handle *out_handle;
struct mhi_client_info_t out_clnt_info;
enum MHI_CLIENT_CHANNEL in_chan_id;
struct mhi_client_handle *in_handle;
struct mhi_client_info_t in_clnt_info;
struct mutex state_lock;
bool out_chan_enabled;
bool in_chan_enabled;
int bytes_to_tx;
int bytes_to_rx;
struct mutex in_skbq_lock;
struct sk_buff_head in_skbq;
size_t max_packet_size;
uint32_t num_trbs;
void *mhi_xprtp;
};
/**
* ipc_router_mhi_xprt - IPC Router's MHI XPRT structure
* @list: IPC router's MHI XPRTs list.
* @ch_hndl: Data Structure to hold MHI Channel information.
* @xprt_name: Name of the XPRT to be registered with IPC Router.
* @xprt: IPC Router XPRT structure to contain MHI XPRT specific info.
* @wq: Workqueue to queue read & other XPRT related works.
* @read_work: Read Work to perform read operation from MHI Driver.
* @in_pkt: Pointer to any partially read packet.
* @write_wait_q: Wait Queue to handle the write events.
* @sft_close_complete: Variable to indicate completion of SSR handling
* by IPC Router.
* @xprt_version: IPC Router header version supported by this XPRT.
* @xprt_option: XPRT specific options to be handled by IPC Router.
*/
struct ipc_router_mhi_xprt {
struct list_head list;
struct ipc_router_mhi_channel ch_hndl;
char xprt_name[XPRT_NAME_LEN];
struct msm_ipc_router_xprt xprt;
struct workqueue_struct *wq;
struct work_struct read_work;
struct rr_packet *in_pkt;
wait_queue_head_t write_wait_q;
struct completion sft_close_complete;
unsigned xprt_version;
unsigned xprt_option;
};
struct ipc_router_mhi_xprt_work {
struct ipc_router_mhi_xprt *mhi_xprtp;
enum MHI_CLIENT_CHANNEL chan_id;
struct work_struct work;
};
static void mhi_xprt_read_data(struct work_struct *work);
static void mhi_xprt_enable_event(struct work_struct *work);
static void mhi_xprt_disable_event(struct work_struct *work);
/**
* ipc_router_mhi_xprt_config - Config. Info. of each MHI XPRT
* @out_chan_id: Out channel ID for use by IPC ROUTER enumerated in MHI driver.
* @in_chan_id: In channel ID for use by IPC ROUTER enumerated in MHI driver.
* @xprt_name: Name of the XPRT to be registered with IPC Router.
* @link_id: Network Cluster ID to which this XPRT belongs to.
* @xprt_version: IPC Router header version supported by this XPRT.
*/
struct ipc_router_mhi_xprt_config {
enum MHI_CLIENT_CHANNEL out_chan_id;
enum MHI_CLIENT_CHANNEL in_chan_id;
char xprt_name[XPRT_NAME_LEN];
uint32_t link_id;
uint32_t xprt_version;
};
#define MODULE_NAME "ipc_router_mhi_xprt"
static DEFINE_MUTEX(mhi_xprt_list_lock_lha1);
static LIST_HEAD(mhi_xprt_list);
/*
* mhi_xprt_queue_in_buffers() - Queue input buffers
* @mhi_xprtp: MHI XPRT in which the input buffer has to be queued.
* @num_trbs: Number of buffers to be queued.
*
* @return: number of buffers queued.
*/
int mhi_xprt_queue_in_buffers(struct ipc_router_mhi_xprt *mhi_xprtp,
uint32_t num_trbs)
{
int i;
struct sk_buff *skb;
dma_addr_t dma_addr;
uint32_t buf_size = mhi_xprtp->ch_hndl.max_packet_size;
enum MHI_STATUS rc_val = MHI_STATUS_SUCCESS;
for (i = 0; i < num_trbs; i++) {
skb = alloc_skb(buf_size, GFP_KERNEL);
if (!skb) {
IPC_RTR_ERR("%s: Could not allocate %d SKB(s)\n",
__func__, (i + 1));
break;
}
dma_addr = dma_map_single(NULL, skb->data,
buf_size, DMA_BIDIRECTIONAL);
if (dma_mapping_error(NULL, dma_addr)) {
IPC_RTR_ERR("%s: Failed to map DMA for SKB # %d\n",
__func__, (i + 1));
kfree_skb(skb);
break;
}
mutex_lock(&mhi_xprtp->ch_hndl.in_skbq_lock);
rc_val = mhi_queue_xfer(mhi_xprtp->ch_hndl.in_handle,
dma_addr, buf_size, MHI_EOT);
if (rc_val != MHI_STATUS_SUCCESS) {
mutex_unlock(&mhi_xprtp->ch_hndl.in_skbq_lock);
IPC_RTR_ERR("%s: Failed to queue TRB # %d into MHI\n",
__func__, (i + 1));
dma_unmap_single(NULL, dma_addr,
buf_size, DMA_TO_DEVICE);
kfree_skb(skb);
break;
}
skb_queue_tail(&mhi_xprtp->ch_hndl.in_skbq, skb);
mutex_unlock(&mhi_xprtp->ch_hndl.in_skbq_lock);
}
return i;
}
/**
* ipc_router_mhi_get_xprt_version() - Get IPC Router header version
* supported by the XPRT
* @xprt: XPRT for which the version information is required.
*
* @return: IPC Router header version supported by the XPRT.
*/
static int ipc_router_mhi_get_xprt_version(struct msm_ipc_router_xprt *xprt)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
if (!xprt)
return -EINVAL;
mhi_xprtp = container_of(xprt, struct ipc_router_mhi_xprt, xprt);
return (int)mhi_xprtp->xprt_version;
}
/**
* ipc_router_mhi_get_xprt_option() - Get XPRT options
* @xprt: XPRT for which the option information is required.
*
* @return: Options supported by the XPRT.
*/
static int ipc_router_mhi_get_xprt_option(struct msm_ipc_router_xprt *xprt)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
if (!xprt)
return -EINVAL;
mhi_xprtp = container_of(xprt, struct ipc_router_mhi_xprt, xprt);
return (int)mhi_xprtp->xprt_option;
}
/**
* ipc_router_mhi_write_avail() - Get available write space
* @xprt: XPRT for which the available write space info. is required.
*
* @return: Write space in bytes on success, 0 on SSR.
*/
static int ipc_router_mhi_write_avail(struct msm_ipc_router_xprt *xprt)
{
int write_avail;
struct ipc_router_mhi_xprt *mhi_xprtp =
container_of(xprt, struct ipc_router_mhi_xprt, xprt);
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
if (!mhi_xprtp->ch_hndl.out_chan_enabled)
write_avail = 0;
else
write_avail = mhi_get_free_desc(mhi_xprtp->ch_hndl.out_handle) *
mhi_xprtp->ch_hndl.max_packet_size;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
return write_avail;
}
/**
* ipc_router_mhi_write_skb() - Write a single SKB onto the XPRT
* @mhi_xprtp: XPRT in which the SKB has to be written.
* @skb: SKB to be written.
*
* @return: return number of bytes written on success,
* standard Linux error codes on failure.
*/
static int ipc_router_mhi_write_skb(struct ipc_router_mhi_xprt *mhi_xprtp,
struct sk_buff *skb)
{
size_t sz_to_write = 0;
size_t offset = 0;
int rc;
dma_addr_t dma_addr;
while (offset < skb->len) {
wait_event(mhi_xprtp->write_wait_q,
mhi_get_free_desc(mhi_xprtp->ch_hndl.out_handle) ||
!mhi_xprtp->ch_hndl.out_chan_enabled);
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
if (!mhi_xprtp->ch_hndl.out_chan_enabled) {
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
IPC_RTR_ERR("%s: %s chnl reset\n",
__func__, mhi_xprtp->xprt_name);
return -ENETRESET;
}
sz_to_write = min((size_t)(skb->len - offset),
(size_t)IPC_ROUTER_MHI_XPRT_MAX_PKT_SIZE);
dma_addr = dma_map_single(NULL, skb->data + offset,
sz_to_write, DMA_TO_DEVICE);
if (dma_mapping_error(NULL, dma_addr)) {
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
IPC_RTR_ERR("%s: Failed to map DMA 0x%x\n",
__func__, sz_to_write);
return -ENOMEM;
}
rc = mhi_queue_xfer(mhi_xprtp->ch_hndl.out_handle,
dma_addr, sz_to_write, MHI_EOT | MHI_EOB);
if (rc != 0) {
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
dma_unmap_single(NULL, dma_addr, sz_to_write,
DMA_TO_DEVICE);
IPC_RTR_ERR("%s: Error queueing mhi_xfer 0x%x\n",
__func__, sz_to_write);
return -EFAULT;
} else {
offset += sz_to_write;
mhi_xprtp->ch_hndl.bytes_to_tx += sz_to_write;
}
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
}
return skb->len;
}
/**
* ipc_router_mhi_write() - Write to XPRT
* @data: Data to be written to the XPRT.
* @len: Length of the data to be written.
* @xprt: XPRT to which the data has to be written.
*
* @return: Data Length on success, standard Linux error codes on failure.
*/
static int ipc_router_mhi_write(void *data,
uint32_t len, struct msm_ipc_router_xprt *xprt)
{
struct rr_packet *pkt = (struct rr_packet *)data;
struct sk_buff *ipc_rtr_pkt;
int rc;
struct ipc_router_mhi_xprt *mhi_xprtp =
container_of(xprt, struct ipc_router_mhi_xprt, xprt);
if (!pkt)
return -EINVAL;
if (!len || pkt->length != len)
return -EINVAL;
D("%s: Ready to write %d bytes\n", __func__, len);
skb_queue_walk(pkt->pkt_fragment_q, ipc_rtr_pkt) {
rc = ipc_router_mhi_write_skb(mhi_xprtp, ipc_rtr_pkt);
if (rc < 0) {
IPC_RTR_ERR("%s: Error writing SKB %d\n",
__func__, rc);
break;
}
}
wait_event(mhi_xprtp->write_wait_q, !mhi_xprtp->ch_hndl.bytes_to_tx);
if (rc < 0)
return rc;
else
return len;
}
/**
* mhi_xprt_read_data() - Read work to read from the XPRT
* @work: Read work to be executed.
*
* This function is a read work item queued on a XPRT specific workqueue.
* The work parameter contains information regarding the XPRT on which this
* read work has to be performed. The work item keeps reading from the MHI
* endpoint, until the endpoint returns an error.
*/
static void mhi_xprt_read_data(struct work_struct *work)
{
dma_addr_t data_addr;
ssize_t data_sz;
void *skb_data;
struct sk_buff *skb;
struct ipc_router_mhi_xprt *mhi_xprtp =
container_of(work, struct ipc_router_mhi_xprt, read_work);
struct mhi_result result;
int rc;
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
if (!mhi_xprtp->ch_hndl.in_chan_enabled) {
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
if (mhi_xprtp->in_pkt)
release_pkt(mhi_xprtp->in_pkt);
mhi_xprtp->in_pkt = NULL;
mhi_xprtp->ch_hndl.bytes_to_rx = 0;
IPC_RTR_ERR("%s: %s channel reset\n",
__func__, mhi_xprtp->xprt.name);
return;
}
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
while (1) {
rc = mhi_poll_inbound(mhi_xprtp->ch_hndl.in_handle, &result);
if (rc || !result.payload_buf || !result.bytes_xferd) {
if (rc != MHI_STATUS_RING_EMPTY)
IPC_RTR_ERR("%s: Poll failed %s:%d:%p:%zu\n",
__func__, mhi_xprtp->xprt_name, rc,
(void *)result.payload_buf,
result.bytes_xferd);
break;
}
data_addr = result.payload_buf;
data_sz = result.bytes_xferd;
/* Create a new rr_packet, if first fragment */
if (!mhi_xprtp->ch_hndl.bytes_to_rx) {
mhi_xprtp->in_pkt = create_pkt(NULL);
if (!mhi_xprtp->in_pkt) {
IPC_RTR_ERR("%s: Couldn't alloc rr_packet\n",
__func__);
return;
}
D("%s: Allocated rr_packet\n", __func__);
}
skb_data = dma_to_virt(NULL, data_addr);
dma_unmap_single(NULL, data_addr, data_sz, DMA_BIDIRECTIONAL);
mutex_lock(&mhi_xprtp->ch_hndl.in_skbq_lock);
skb_queue_walk(&mhi_xprtp->ch_hndl.in_skbq, skb) {
if (skb->data == skb_data) {
skb_unlink(skb, &mhi_xprtp->ch_hndl.in_skbq);
break;
}
}
mutex_unlock(&mhi_xprtp->ch_hndl.in_skbq_lock);
skb_put(skb, data_sz);
skb_queue_tail(mhi_xprtp->in_pkt->pkt_fragment_q, skb);
mhi_xprtp->in_pkt->length += data_sz;
if (!mhi_xprtp->ch_hndl.bytes_to_rx)
mhi_xprtp->ch_hndl.bytes_to_rx =
ipc_router_peek_pkt_size(skb_data) - data_sz;
else
mhi_xprtp->ch_hndl.bytes_to_rx -= data_sz;
/* Packet is completely read, so notify to router */
if (!mhi_xprtp->ch_hndl.bytes_to_rx) {
D("%s: Packet size read %d\n",
__func__, mhi_xprtp->in_pkt->length);
msm_ipc_router_xprt_notify(&mhi_xprtp->xprt,
IPC_ROUTER_XPRT_EVENT_DATA,
(void *)mhi_xprtp->in_pkt);
release_pkt(mhi_xprtp->in_pkt);
mhi_xprtp->in_pkt = NULL;
}
while (mhi_xprt_queue_in_buffers(mhi_xprtp, 1) != 1 &&
mhi_xprtp->ch_hndl.in_chan_enabled)
msleep(100);
}
}
/**
* ipc_router_mhi_close() - Close the XPRT
* @xprt: XPRT which needs to be closed.
*
* @return: 0 on success, standard Linux error codes on failure.
*/
static int ipc_router_mhi_close(struct msm_ipc_router_xprt *xprt)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
if (!xprt)
return -EINVAL;
mhi_xprtp = container_of(xprt, struct ipc_router_mhi_xprt, xprt);
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
mhi_xprtp->ch_hndl.out_chan_enabled = false;
mhi_xprtp->ch_hndl.in_chan_enabled = false;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
flush_workqueue(mhi_xprtp->wq);
mhi_close_channel(mhi_xprtp->ch_hndl.in_handle);
mhi_close_channel(mhi_xprtp->ch_hndl.out_handle);
return 0;
}
/**
* mhi_xprt_sft_close_done() - Completion of XPRT reset
* @xprt: XPRT on which the reset operation is complete.
*
* This function is used by IPC Router to signal this MHI XPRT Abstraction
* Layer(XAL) that the reset of XPRT is completely handled by IPC Router.
*/
static void mhi_xprt_sft_close_done(struct msm_ipc_router_xprt *xprt)
{
struct ipc_router_mhi_xprt *mhi_xprtp =
container_of(xprt, struct ipc_router_mhi_xprt, xprt);
complete_all(&mhi_xprtp->sft_close_complete);
}
/**
* mhi_xprt_enable_event() - Enable the MHI link for communication
* @work: Work containing some reference to the link to be enabled.
*
* This work is scheduled when the MHI link to the peripheral is up.
*/
static void mhi_xprt_enable_event(struct work_struct *work)
{
struct ipc_router_mhi_xprt_work *xprt_work =
container_of(work, struct ipc_router_mhi_xprt_work, work);
struct ipc_router_mhi_xprt *mhi_xprtp = xprt_work->mhi_xprtp;
int rc;
bool notify = false;
if (xprt_work->chan_id == mhi_xprtp->ch_hndl.out_chan_id) {
rc = mhi_open_channel(mhi_xprtp->ch_hndl.out_handle);
if (rc != MHI_STATUS_SUCCESS) {
IPC_RTR_ERR("%s Failed to open chan 0x%x, rc %d\n",
__func__, mhi_xprtp->ch_hndl.out_chan_id, rc);
goto out_enable_event;
}
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
mhi_xprtp->ch_hndl.out_chan_enabled = true;
notify = mhi_xprtp->ch_hndl.out_chan_enabled &&
mhi_xprtp->ch_hndl.in_chan_enabled;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
} else if (xprt_work->chan_id == mhi_xprtp->ch_hndl.in_chan_id) {
rc = mhi_open_channel(mhi_xprtp->ch_hndl.in_handle);
if (rc != MHI_STATUS_SUCCESS) {
IPC_RTR_ERR("%s Failed to open chan 0x%x, rc %d\n",
__func__, mhi_xprtp->ch_hndl.in_chan_id, rc);
goto out_enable_event;
}
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
mhi_xprtp->ch_hndl.in_chan_enabled = true;
notify = mhi_xprtp->ch_hndl.out_chan_enabled &&
mhi_xprtp->ch_hndl.in_chan_enabled;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
}
/* Register the XPRT before receiving any data */
if (notify) {
msm_ipc_router_xprt_notify(&mhi_xprtp->xprt,
IPC_ROUTER_XPRT_EVENT_OPEN, NULL);
D("%s: Notified IPC Router of %s OPEN\n",
__func__, mhi_xprtp->xprt.name);
}
if (xprt_work->chan_id != mhi_xprtp->ch_hndl.in_chan_id)
goto out_enable_event;
rc = mhi_xprt_queue_in_buffers(mhi_xprtp, mhi_xprtp->ch_hndl.num_trbs);
if (rc > 0)
goto out_enable_event;
IPC_RTR_ERR("%s: Could not queue one TRB atleast\n", __func__);
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
mhi_xprtp->ch_hndl.in_chan_enabled = false;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
if (notify)
msm_ipc_router_xprt_notify(&mhi_xprtp->xprt,
IPC_ROUTER_XPRT_EVENT_CLOSE, NULL);
mhi_close_channel(mhi_xprtp->ch_hndl.in_handle);
out_enable_event:
kfree(xprt_work);
}
/**
* mhi_xprt_disable_event() - Disable the MHI link for communication
* @work: Work containing some reference to the link to be disabled.
*
* This work is scheduled when the MHI link to the peripheral is down.
*/
static void mhi_xprt_disable_event(struct work_struct *work)
{
struct ipc_router_mhi_xprt_work *xprt_work =
container_of(work, struct ipc_router_mhi_xprt_work, work);
struct ipc_router_mhi_xprt *mhi_xprtp = xprt_work->mhi_xprtp;
bool notify = false;
if (xprt_work->chan_id == mhi_xprtp->ch_hndl.out_chan_id) {
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
notify = mhi_xprtp->ch_hndl.out_chan_enabled &&
mhi_xprtp->ch_hndl.in_chan_enabled;
mhi_xprtp->ch_hndl.out_chan_enabled = false;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
wake_up(&mhi_xprtp->write_wait_q);
mhi_close_channel(mhi_xprtp->ch_hndl.out_handle);
} else if (xprt_work->chan_id == mhi_xprtp->ch_hndl.in_chan_id) {
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
notify = mhi_xprtp->ch_hndl.out_chan_enabled &&
mhi_xprtp->ch_hndl.in_chan_enabled;
mhi_xprtp->ch_hndl.in_chan_enabled = false;
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
/* Queue a read work to remove any partially read packets */
queue_work(mhi_xprtp->wq, &mhi_xprtp->read_work);
flush_workqueue(mhi_xprtp->wq);
mhi_close_channel(mhi_xprtp->ch_hndl.in_handle);
}
if (notify) {
init_completion(&mhi_xprtp->sft_close_complete);
msm_ipc_router_xprt_notify(&mhi_xprtp->xprt,
IPC_ROUTER_XPRT_EVENT_CLOSE, NULL);
D("%s: Notified IPC Router of %s CLOSE\n",
__func__, mhi_xprtp->xprt.name);
wait_for_completion(&mhi_xprtp->sft_close_complete);
}
kfree(xprt_work);
}
/**
* mhi_xprt_xfer_event() - Function to handle MHI XFER Callbacks
* @cb_info: Information containing xfer callback details.
*
* This function is called when the MHI generates a XFER event to the
* IPC Router. This function is used to handle events like tx/rx.
*/
static void mhi_xprt_xfer_event(struct mhi_cb_info *cb_info)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
mhi_xprtp = (struct ipc_router_mhi_xprt *)(cb_info->result->user_data);
if (cb_info->chan == mhi_xprtp->ch_hndl.out_chan_id) {
dma_unmap_single(NULL, (dma_addr_t)cb_info->result->payload_buf,
cb_info->result->bytes_xferd, DMA_TO_DEVICE);
mutex_lock(&mhi_xprtp->ch_hndl.state_lock);
mhi_xprtp->ch_hndl.bytes_to_tx -= cb_info->result->bytes_xferd;
if (!mhi_xprtp->ch_hndl.bytes_to_tx)
wake_up(&mhi_xprtp->write_wait_q);
mutex_unlock(&mhi_xprtp->ch_hndl.state_lock);
} else if (cb_info->chan == mhi_xprtp->ch_hndl.in_chan_id) {
queue_work(mhi_xprtp->wq, &mhi_xprtp->read_work);
} else {
IPC_RTR_ERR("%s: chan_id %d not part of %s\n",
__func__, cb_info->chan, mhi_xprtp->xprt_name);
}
}
/**
* ipc_router_mhi_xprt_cb() - Callback to notify events on a channel
* @cb_info: Information containing the details of callback.
*
* This function is called by the MHI driver to notify different events
* like successful tx/rx, SSR events etc.
*/
static void ipc_router_mhi_xprt_cb(struct mhi_cb_info *cb_info)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
struct ipc_router_mhi_xprt_work *xprt_work;
if (cb_info->result == NULL) {
IPC_RTR_ERR("%s: Result not available in cb_info\n", __func__);
return;
}
mhi_xprtp = (struct ipc_router_mhi_xprt *)(cb_info->result->user_data);
switch (cb_info->cb_reason) {
case MHI_CB_MHI_ENABLED:
case MHI_CB_MHI_DISABLED:
xprt_work = kmalloc(sizeof(*xprt_work), GFP_KERNEL);
if (!xprt_work) {
IPC_RTR_ERR("%s: Couldn't handle %d event on %s\n",
__func__, cb_info->cb_reason,
mhi_xprtp->xprt_name);
return;
}
xprt_work->mhi_xprtp = mhi_xprtp;
xprt_work->chan_id = cb_info->chan;
if (cb_info->cb_reason == MHI_CB_MHI_ENABLED)
INIT_WORK(&xprt_work->work, mhi_xprt_enable_event);
else
INIT_WORK(&xprt_work->work, mhi_xprt_disable_event);
queue_work(mhi_xprtp->wq, &xprt_work->work);
break;
case MHI_CB_XFER:
mhi_xprt_xfer_event(cb_info);
break;
default:
IPC_RTR_ERR("%s: Invalid cb reason %x\n",
__func__, cb_info->cb_reason);
}
}
/**
* ipc_router_mhi_driver_register() - register for MHI channels
*
* @mhi_xprtp: pointer to IPC router mhi xprt structure.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called when a new XPRT is added.
*/
static int ipc_router_mhi_driver_register(
struct ipc_router_mhi_xprt *mhi_xprtp)
{
enum MHI_STATUS rc_status;
rc_status = mhi_register_channel(&mhi_xprtp->ch_hndl.out_handle,
mhi_xprtp->ch_hndl.out_chan_id, 0,
&mhi_xprtp->ch_hndl.out_clnt_info,
(void *)mhi_xprtp);
if (rc_status != MHI_STATUS_SUCCESS) {
IPC_RTR_ERR("%s: Error %d registering out_chan for %s\n",
__func__, rc_status, mhi_xprtp->xprt_name);
return -EFAULT;
}
rc_status = mhi_register_channel(&mhi_xprtp->ch_hndl.in_handle,
mhi_xprtp->ch_hndl.in_chan_id, 0,
&mhi_xprtp->ch_hndl.in_clnt_info,
(void *)mhi_xprtp);
if (rc_status != MHI_STATUS_SUCCESS) {
mhi_deregister_channel(mhi_xprtp->ch_hndl.out_handle);
IPC_RTR_ERR("%s: Error %d registering in_chan for %s\n",
__func__, rc_status, mhi_xprtp->xprt_name);
return -EFAULT;
}
return 0;
}
/**
* ipc_router_mhi_config_init() - init MHI xprt configs
*
* @mhi_xprt_config: pointer to MHI xprt configurations.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called to initialize the MHI XPRT pointer with
* the MHI XPRT configurations from device tree.
*/
static int ipc_router_mhi_config_init(
struct ipc_router_mhi_xprt_config *mhi_xprt_config)
{
struct ipc_router_mhi_xprt *mhi_xprtp;
char wq_name[XPRT_NAME_LEN];
int rc;
mhi_xprtp = kzalloc(sizeof(struct ipc_router_mhi_xprt), GFP_KERNEL);
if (IS_ERR_OR_NULL(mhi_xprtp)) {
IPC_RTR_ERR("%s: kzalloc() failed for mhi_xprtp:%s\n",
__func__, mhi_xprt_config->xprt_name);
return -ENOMEM;
}
scnprintf(wq_name, XPRT_NAME_LEN, "MHI_XPRT%x:%x",
mhi_xprt_config->out_chan_id, mhi_xprt_config->in_chan_id);
mhi_xprtp->wq = create_singlethread_workqueue(wq_name);
if (!mhi_xprtp->wq) {
IPC_RTR_ERR("%s: %s create WQ failed\n",
__func__, mhi_xprt_config->xprt_name);
kfree(mhi_xprtp);
return -EFAULT;
}
INIT_WORK(&mhi_xprtp->read_work, mhi_xprt_read_data);
init_waitqueue_head(&mhi_xprtp->write_wait_q);
mhi_xprtp->xprt_version = mhi_xprt_config->xprt_version;
strlcpy(mhi_xprtp->xprt_name, mhi_xprt_config->xprt_name,
XPRT_NAME_LEN);
/* Initialize XPRT operations and parameters registered with IPC RTR */
mhi_xprtp->xprt.link_id = mhi_xprt_config->link_id;
mhi_xprtp->xprt.name = mhi_xprtp->xprt_name;
mhi_xprtp->xprt.get_version = ipc_router_mhi_get_xprt_version;
mhi_xprtp->xprt.get_option = ipc_router_mhi_get_xprt_option;
mhi_xprtp->xprt.read_avail = NULL;
mhi_xprtp->xprt.read = NULL;
mhi_xprtp->xprt.write_avail = ipc_router_mhi_write_avail;
mhi_xprtp->xprt.write = ipc_router_mhi_write;
mhi_xprtp->xprt.close = ipc_router_mhi_close;
mhi_xprtp->xprt.sft_close_done = mhi_xprt_sft_close_done;
mhi_xprtp->xprt.priv = NULL;
/* Initialize channel handle parameters */
mhi_xprtp->ch_hndl.out_chan_id = mhi_xprt_config->out_chan_id;
mhi_xprtp->ch_hndl.in_chan_id = mhi_xprt_config->in_chan_id;
mhi_xprtp->ch_hndl.out_clnt_info.mhi_client_cb = ipc_router_mhi_xprt_cb;
mhi_xprtp->ch_hndl.in_clnt_info.mhi_client_cb = ipc_router_mhi_xprt_cb;
mutex_init(&mhi_xprtp->ch_hndl.state_lock);
mutex_init(&mhi_xprtp->ch_hndl.in_skbq_lock);
skb_queue_head_init(&mhi_xprtp->ch_hndl.in_skbq);
mhi_xprtp->ch_hndl.max_packet_size = IPC_ROUTER_MHI_XPRT_MAX_PKT_SIZE;
mhi_xprtp->ch_hndl.num_trbs = IPC_ROUTER_MHI_XPRT_NUM_TRBS;
mhi_xprtp->ch_hndl.mhi_xprtp = mhi_xprtp;
rc = ipc_router_mhi_driver_register(mhi_xprtp);
return rc;
}
/**
* parse_devicetree() - parse device tree binding
*
* @node: pointer to device tree node
* @mhi_xprt_config: pointer to MHI XPRT configurations
*
* @return: 0 on success, -ENODEV on failure.
*/
static int parse_devicetree(struct device_node *node,
struct ipc_router_mhi_xprt_config *mhi_xprt_config)
{
int rc;
uint32_t out_chan_id;
uint32_t in_chan_id;
const char *remote_ss;
uint32_t link_id;
uint32_t version;
char *key;
key = "qcom,out-chan-id";
rc = of_property_read_u32(node, key, &out_chan_id);
if (rc)
goto error;
mhi_xprt_config->out_chan_id = out_chan_id;
key = "qcom,in-chan-id";
rc = of_property_read_u32(node, key, &in_chan_id);
if (rc)
goto error;
mhi_xprt_config->in_chan_id = in_chan_id;
key = "qcom,xprt-remote";
remote_ss = of_get_property(node, key, NULL);
if (!remote_ss)
goto error;
key = "qcom,xprt-linkid";
rc = of_property_read_u32(node, key, &link_id);
if (rc)
goto error;
mhi_xprt_config->link_id = link_id;
key = "qcom,xprt-version";
rc = of_property_read_u32(node, key, &version);
if (rc)
goto error;
mhi_xprt_config->xprt_version = version;
scnprintf(mhi_xprt_config->xprt_name, XPRT_NAME_LEN,
"IPCRTR_MHI%x:%x_%s",
out_chan_id, in_chan_id, remote_ss);
return 0;
error:
IPC_RTR_ERR("%s: missing key: %s\n", __func__, key);
return -ENODEV;
}
/**
* ipc_router_mhi_xprt_probe() - Probe an MHI xprt
* @pdev: Platform device corresponding to MHI xprt.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called when the underlying device tree driver registers
* a platform device, mapped to an MHI transport.
*/
static int ipc_router_mhi_xprt_probe(struct platform_device *pdev)
{
int rc;
struct ipc_router_mhi_xprt_config mhi_xprt_config;
if (pdev && pdev->dev.of_node) {
rc = parse_devicetree(pdev->dev.of_node, &mhi_xprt_config);
if (rc) {
IPC_RTR_ERR("%s: failed to parse device tree\n",
__func__);
return rc;
}
rc = ipc_router_mhi_config_init(&mhi_xprt_config);
if (rc) {
IPC_RTR_ERR("%s: init failed\n", __func__);
return rc;
}
}
return rc;
}
static struct of_device_id ipc_router_mhi_xprt_match_table[] = {
{ .compatible = "qcom,ipc_router_mhi_xprt" },
{},
};
static struct platform_driver ipc_router_mhi_xprt_driver = {
.probe = ipc_router_mhi_xprt_probe,
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table = ipc_router_mhi_xprt_match_table,
},
};
static int __init ipc_router_mhi_xprt_init(void)
{
int rc;
rc = platform_driver_register(&ipc_router_mhi_xprt_driver);
if (rc) {
IPC_RTR_ERR("%s: ipc_router_mhi_xprt_driver reg. failed %d\n",
__func__, rc);
return rc;
}
return 0;
}
module_init(ipc_router_mhi_xprt_init);
MODULE_DESCRIPTION("IPC Router MHI XPRT");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
kraml/desire-sense-kernel | drivers/mtd/nand/cmx270_nand.c | 565 | 6077 | /*
* linux/drivers/mtd/nand/cmx270-nand.c
*
* Copyright (C) 2006 Compulab, Ltd.
* Mike Rapoport <mike@compulab.co.il>
*
* Derived from drivers/mtd/nand/h1910.c
* Copyright (C) 2002 Marius Gröger (mag@sysgo.de)
* Copyright (c) 2001 Thomas Gleixner (gleixner@autronix.de)
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Overview:
* This is a device driver for the NAND flash device found on the
* CM-X270 board.
*/
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/gpio.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/pxa2xx-regs.h>
#define GPIO_NAND_CS (11)
#define GPIO_NAND_RB (89)
/* MTD structure for CM-X270 board */
static struct mtd_info *cmx270_nand_mtd;
/* remaped IO address of the device */
static void __iomem *cmx270_nand_io;
/*
* Define static partitions for flash device
*/
static struct mtd_partition partition_info[] = {
[0] = {
.name = "cmx270-0",
.offset = 0,
.size = MTDPART_SIZ_FULL
}
};
#define NUM_PARTITIONS (ARRAY_SIZE(partition_info))
const char *part_probes[] = { "cmdlinepart", NULL };
static u_char cmx270_read_byte(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
return (readl(this->IO_ADDR_R) >> 16);
}
static void cmx270_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i=0; i<len; i++)
writel((*buf++ << 16), this->IO_ADDR_W);
}
static void cmx270_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i=0; i<len; i++)
*buf++ = readl(this->IO_ADDR_R) >> 16;
}
static int cmx270_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i=0; i<len; i++)
if (buf[i] != (u_char)(readl(this->IO_ADDR_R) >> 16))
return -EFAULT;
return 0;
}
static inline void nand_cs_on(void)
{
gpio_set_value(GPIO_NAND_CS, 0);
}
static void nand_cs_off(void)
{
dsb();
gpio_set_value(GPIO_NAND_CS, 1);
}
/*
* hardware specific access to control-lines
*/
static void cmx270_hwcontrol(struct mtd_info *mtd, int dat,
unsigned int ctrl)
{
struct nand_chip* this = mtd->priv;
unsigned int nandaddr = (unsigned int)this->IO_ADDR_W;
dsb();
if (ctrl & NAND_CTRL_CHANGE) {
if ( ctrl & NAND_ALE )
nandaddr |= (1 << 3);
else
nandaddr &= ~(1 << 3);
if ( ctrl & NAND_CLE )
nandaddr |= (1 << 2);
else
nandaddr &= ~(1 << 2);
if ( ctrl & NAND_NCE )
nand_cs_on();
else
nand_cs_off();
}
dsb();
this->IO_ADDR_W = (void __iomem*)nandaddr;
if (dat != NAND_CMD_NONE)
writel((dat << 16), this->IO_ADDR_W);
dsb();
}
/*
* read device ready pin
*/
static int cmx270_device_ready(struct mtd_info *mtd)
{
dsb();
return (gpio_get_value(GPIO_NAND_RB));
}
/*
* Main initialization routine
*/
static int __init cmx270_init(void)
{
struct nand_chip *this;
const char *part_type;
struct mtd_partition *mtd_parts;
int mtd_parts_nb = 0;
int ret;
if (!(machine_is_armcore() && cpu_is_pxa27x()))
return -ENODEV;
ret = gpio_request(GPIO_NAND_CS, "NAND CS");
if (ret) {
pr_warning("CM-X270: failed to request NAND CS gpio\n");
return ret;
}
gpio_direction_output(GPIO_NAND_CS, 1);
ret = gpio_request(GPIO_NAND_RB, "NAND R/B");
if (ret) {
pr_warning("CM-X270: failed to request NAND R/B gpio\n");
goto err_gpio_request;
}
gpio_direction_input(GPIO_NAND_RB);
/* Allocate memory for MTD device structure and private data */
cmx270_nand_mtd = kzalloc(sizeof(struct mtd_info) +
sizeof(struct nand_chip),
GFP_KERNEL);
if (!cmx270_nand_mtd) {
pr_debug("Unable to allocate CM-X270 NAND MTD device structure.\n");
ret = -ENOMEM;
goto err_kzalloc;
}
cmx270_nand_io = ioremap(PXA_CS1_PHYS, 12);
if (!cmx270_nand_io) {
pr_debug("Unable to ioremap NAND device\n");
ret = -EINVAL;
goto err_ioremap;
}
/* Get pointer to private data */
this = (struct nand_chip *)(&cmx270_nand_mtd[1]);
/* Link the private data with the MTD structure */
cmx270_nand_mtd->owner = THIS_MODULE;
cmx270_nand_mtd->priv = this;
/* insert callbacks */
this->IO_ADDR_R = cmx270_nand_io;
this->IO_ADDR_W = cmx270_nand_io;
this->cmd_ctrl = cmx270_hwcontrol;
this->dev_ready = cmx270_device_ready;
/* 15 us command delay time */
this->chip_delay = 20;
this->ecc.mode = NAND_ECC_SOFT;
/* read/write functions */
this->read_byte = cmx270_read_byte;
this->read_buf = cmx270_read_buf;
this->write_buf = cmx270_write_buf;
this->verify_buf = cmx270_verify_buf;
/* Scan to find existence of the device */
if (nand_scan (cmx270_nand_mtd, 1)) {
pr_notice("No NAND device\n");
ret = -ENXIO;
goto err_scan;
}
#ifdef CONFIG_MTD_CMDLINE_PARTS
mtd_parts_nb = parse_mtd_partitions(cmx270_nand_mtd, part_probes,
&mtd_parts, 0);
if (mtd_parts_nb > 0)
part_type = "command line";
else
mtd_parts_nb = 0;
#endif
if (!mtd_parts_nb) {
mtd_parts = partition_info;
mtd_parts_nb = NUM_PARTITIONS;
part_type = "static";
}
/* Register the partitions */
pr_notice("Using %s partition definition\n", part_type);
ret = add_mtd_partitions(cmx270_nand_mtd, mtd_parts, mtd_parts_nb);
if (ret)
goto err_scan;
/* Return happy */
return 0;
err_scan:
iounmap(cmx270_nand_io);
err_ioremap:
kfree(cmx270_nand_mtd);
err_kzalloc:
gpio_free(GPIO_NAND_RB);
err_gpio_request:
gpio_free(GPIO_NAND_CS);
return ret;
}
module_init(cmx270_init);
/*
* Clean up routine
*/
static void __exit cmx270_cleanup(void)
{
/* Release resources, unregister device */
nand_release(cmx270_nand_mtd);
gpio_free(GPIO_NAND_RB);
gpio_free(GPIO_NAND_CS);
iounmap(cmx270_nand_io);
/* Free the MTD device structure */
kfree (cmx270_nand_mtd);
}
module_exit(cmx270_cleanup);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_DESCRIPTION("NAND flash driver for Compulab CM-X270 Module");
| gpl-2.0 |
bayger/kernel_amlogic | net/mac80211/tx.c | 821 | 72386 | /*
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright 2006-2007 Jiri Benc <jbenc@suse.cz>
* Copyright 2007 Johannes Berg <johannes@sipsolutions.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*
* Transmit and frame generation functions.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/bitmap.h>
#include <linux/rcupdate.h>
#include <net/net_namespace.h>
#include <net/ieee80211_radiotap.h>
#include <net/cfg80211.h>
#include <net/mac80211.h>
#include <asm/unaligned.h>
#include "ieee80211_i.h"
#include "driver-ops.h"
#include "led.h"
#include "mesh.h"
#include "wep.h"
#include "wpa.h"
#include "wme.h"
#include "rate.h"
/* misc utils */
static __le16 ieee80211_duration(struct ieee80211_tx_data *tx, int group_addr,
int next_frag_len)
{
int rate, mrate, erp, dur, i;
struct ieee80211_rate *txrate;
struct ieee80211_local *local = tx->local;
struct ieee80211_supported_band *sband;
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
/* assume HW handles this */
if (info->control.rates[0].flags & IEEE80211_TX_RC_MCS)
return 0;
/* uh huh? */
if (WARN_ON_ONCE(info->control.rates[0].idx < 0))
return 0;
sband = local->hw.wiphy->bands[tx->channel->band];
txrate = &sband->bitrates[info->control.rates[0].idx];
erp = txrate->flags & IEEE80211_RATE_ERP_G;
/*
* data and mgmt (except PS Poll):
* - during CFP: 32768
* - during contention period:
* if addr1 is group address: 0
* if more fragments = 0 and addr1 is individual address: time to
* transmit one ACK plus SIFS
* if more fragments = 1 and addr1 is individual address: time to
* transmit next fragment plus 2 x ACK plus 3 x SIFS
*
* IEEE 802.11, 9.6:
* - control response frame (CTS or ACK) shall be transmitted using the
* same rate as the immediately previous frame in the frame exchange
* sequence, if this rate belongs to the PHY mandatory rates, or else
* at the highest possible rate belonging to the PHY rates in the
* BSSBasicRateSet
*/
hdr = (struct ieee80211_hdr *)tx->skb->data;
if (ieee80211_is_ctl(hdr->frame_control)) {
/* TODO: These control frames are not currently sent by
* mac80211, but should they be implemented, this function
* needs to be updated to support duration field calculation.
*
* RTS: time needed to transmit pending data/mgmt frame plus
* one CTS frame plus one ACK frame plus 3 x SIFS
* CTS: duration of immediately previous RTS minus time
* required to transmit CTS and its SIFS
* ACK: 0 if immediately previous directed data/mgmt had
* more=0, with more=1 duration in ACK frame is duration
* from previous frame minus time needed to transmit ACK
* and its SIFS
* PS Poll: BIT(15) | BIT(14) | aid
*/
return 0;
}
/* data/mgmt */
if (0 /* FIX: data/mgmt during CFP */)
return cpu_to_le16(32768);
if (group_addr) /* Group address as the destination - no ACK */
return 0;
/* Individual destination address:
* IEEE 802.11, Ch. 9.6 (after IEEE 802.11g changes)
* CTS and ACK frames shall be transmitted using the highest rate in
* basic rate set that is less than or equal to the rate of the
* immediately previous frame and that is using the same modulation
* (CCK or OFDM). If no basic rate set matches with these requirements,
* the highest mandatory rate of the PHY that is less than or equal to
* the rate of the previous frame is used.
* Mandatory rates for IEEE 802.11g PHY: 1, 2, 5.5, 11, 6, 12, 24 Mbps
*/
rate = -1;
/* use lowest available if everything fails */
mrate = sband->bitrates[0].bitrate;
for (i = 0; i < sband->n_bitrates; i++) {
struct ieee80211_rate *r = &sband->bitrates[i];
if (r->bitrate > txrate->bitrate)
break;
if (tx->sdata->vif.bss_conf.basic_rates & BIT(i))
rate = r->bitrate;
switch (sband->band) {
case IEEE80211_BAND_2GHZ: {
u32 flag;
if (tx->sdata->flags & IEEE80211_SDATA_OPERATING_GMODE)
flag = IEEE80211_RATE_MANDATORY_G;
else
flag = IEEE80211_RATE_MANDATORY_B;
if (r->flags & flag)
mrate = r->bitrate;
break;
}
case IEEE80211_BAND_5GHZ:
if (r->flags & IEEE80211_RATE_MANDATORY_A)
mrate = r->bitrate;
break;
case IEEE80211_NUM_BANDS:
WARN_ON(1);
break;
}
}
if (rate == -1) {
/* No matching basic rate found; use highest suitable mandatory
* PHY rate */
rate = mrate;
}
/* Time needed to transmit ACK
* (10 bytes + 4-byte FCS = 112 bits) plus SIFS; rounded up
* to closest integer */
dur = ieee80211_frame_duration(local, 10, rate, erp,
tx->sdata->vif.bss_conf.use_short_preamble);
if (next_frag_len) {
/* Frame is fragmented: duration increases with time needed to
* transmit next fragment plus ACK and 2 x SIFS. */
dur *= 2; /* ACK + SIFS */
/* next fragment */
dur += ieee80211_frame_duration(local, next_frag_len,
txrate->bitrate, erp,
tx->sdata->vif.bss_conf.use_short_preamble);
}
return cpu_to_le16(dur);
}
static inline int is_ieee80211_device(struct ieee80211_local *local,
struct net_device *dev)
{
return local == wdev_priv(dev->ieee80211_ptr);
}
/* tx handlers */
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_dynamic_ps(struct ieee80211_tx_data *tx)
{
struct ieee80211_local *local = tx->local;
struct ieee80211_if_managed *ifmgd;
/* driver doesn't support power save */
if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS))
return TX_CONTINUE;
/* hardware does dynamic power save */
if (local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS)
return TX_CONTINUE;
/* dynamic power save disabled */
if (local->hw.conf.dynamic_ps_timeout <= 0)
return TX_CONTINUE;
/* we are scanning, don't enable power save */
if (local->scanning)
return TX_CONTINUE;
if (!local->ps_sdata)
return TX_CONTINUE;
/* No point if we're going to suspend */
if (local->quiescing)
return TX_CONTINUE;
/* dynamic ps is supported only in managed mode */
if (tx->sdata->vif.type != NL80211_IFTYPE_STATION)
return TX_CONTINUE;
ifmgd = &tx->sdata->u.mgd;
/*
* Don't wakeup from power save if u-apsd is enabled, voip ac has
* u-apsd enabled and the frame is in voip class. This effectively
* means that even if all access categories have u-apsd enabled, in
* practise u-apsd is only used with the voip ac. This is a
* workaround for the case when received voip class packets do not
* have correct qos tag for some reason, due the network or the
* peer application.
*
* Note: local->uapsd_queues access is racy here. If the value is
* changed via debugfs, user needs to reassociate manually to have
* everything in sync.
*/
if ((ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED)
&& (local->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO)
&& skb_get_queue_mapping(tx->skb) == 0)
return TX_CONTINUE;
if (local->hw.conf.flags & IEEE80211_CONF_PS) {
ieee80211_stop_queues_by_reason(&local->hw,
IEEE80211_QUEUE_STOP_REASON_PS);
ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED;
ieee80211_queue_work(&local->hw,
&local->dynamic_ps_disable_work);
}
/* Don't restart the timer if we're not disassociated */
if (!ifmgd->associated)
return TX_CONTINUE;
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(local->hw.conf.dynamic_ps_timeout));
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_check_assoc(struct ieee80211_tx_data *tx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
u32 sta_flags;
if (unlikely(info->flags & IEEE80211_TX_CTL_INJECTED))
return TX_CONTINUE;
if (unlikely(test_bit(SCAN_SW_SCANNING, &tx->local->scanning)) &&
test_bit(SDATA_STATE_OFFCHANNEL, &tx->sdata->state) &&
!ieee80211_is_probe_req(hdr->frame_control) &&
!ieee80211_is_nullfunc(hdr->frame_control))
/*
* When software scanning only nullfunc frames (to notify
* the sleep state to the AP) and probe requests (for the
* active scan) are allowed, all other frames should not be
* sent and we should not get here, but if we do
* nonetheless, drop them to avoid sending them
* off-channel. See the link below and
* ieee80211_start_scan() for more.
*
* http://article.gmane.org/gmane.linux.kernel.wireless.general/30089
*/
return TX_DROP;
if (tx->sdata->vif.type == NL80211_IFTYPE_WDS)
return TX_CONTINUE;
if (tx->sdata->vif.type == NL80211_IFTYPE_MESH_POINT)
return TX_CONTINUE;
if (tx->flags & IEEE80211_TX_PS_BUFFERED)
return TX_CONTINUE;
sta_flags = tx->sta ? get_sta_flags(tx->sta) : 0;
if (likely(tx->flags & IEEE80211_TX_UNICAST)) {
if (unlikely(!(sta_flags & WLAN_STA_ASSOC) &&
tx->sdata->vif.type != NL80211_IFTYPE_ADHOC &&
ieee80211_is_data(hdr->frame_control))) {
#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
printk(KERN_DEBUG "%s: dropped data frame to not "
"associated station %pM\n",
tx->sdata->name, hdr->addr1);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */
I802_DEBUG_INC(tx->local->tx_handlers_drop_not_assoc);
return TX_DROP;
}
} else {
if (unlikely(ieee80211_is_data(hdr->frame_control) &&
tx->local->num_sta == 0 &&
tx->sdata->vif.type != NL80211_IFTYPE_ADHOC)) {
/*
* No associated STAs - no need to send multicast
* frames.
*/
return TX_DROP;
}
return TX_CONTINUE;
}
return TX_CONTINUE;
}
/* This function is called whenever the AP is about to exceed the maximum limit
* of buffered frames for power saving STAs. This situation should not really
* happen often during normal operation, so dropping the oldest buffered packet
* from each queue should be OK to make some room for new frames. */
static void purge_old_ps_buffers(struct ieee80211_local *local)
{
int total = 0, purged = 0;
struct sk_buff *skb;
struct ieee80211_sub_if_data *sdata;
struct sta_info *sta;
/*
* virtual interfaces are protected by RCU
*/
rcu_read_lock();
list_for_each_entry_rcu(sdata, &local->interfaces, list) {
struct ieee80211_if_ap *ap;
if (sdata->vif.type != NL80211_IFTYPE_AP)
continue;
ap = &sdata->u.ap;
skb = skb_dequeue(&ap->ps_bc_buf);
if (skb) {
purged++;
dev_kfree_skb(skb);
}
total += skb_queue_len(&ap->ps_bc_buf);
}
list_for_each_entry_rcu(sta, &local->sta_list, list) {
skb = skb_dequeue(&sta->ps_tx_buf);
if (skb) {
purged++;
dev_kfree_skb(skb);
}
total += skb_queue_len(&sta->ps_tx_buf);
}
rcu_read_unlock();
local->total_ps_buffered = total;
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
wiphy_debug(local->hw.wiphy, "PS buffers full - purged %d frames\n",
purged);
#endif
}
static ieee80211_tx_result
ieee80211_tx_h_multicast_ps_buf(struct ieee80211_tx_data *tx)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data;
/*
* broadcast/multicast frame
*
* If any of the associated stations is in power save mode,
* the frame is buffered to be sent after DTIM beacon frame.
* This is done either by the hardware or us.
*/
/* powersaving STAs only in AP/VLAN mode */
if (!tx->sdata->bss)
return TX_CONTINUE;
/* no buffering for ordered frames */
if (ieee80211_has_order(hdr->frame_control))
return TX_CONTINUE;
/* no stations in PS mode */
if (!atomic_read(&tx->sdata->bss->num_sta_ps))
return TX_CONTINUE;
info->flags |= IEEE80211_TX_CTL_SEND_AFTER_DTIM;
/* device releases frame after DTIM beacon */
if (!(tx->local->hw.flags & IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING))
return TX_CONTINUE;
/* buffered in mac80211 */
if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
purge_old_ps_buffers(tx->local);
if (skb_queue_len(&tx->sdata->bss->ps_bc_buf) >= AP_MAX_BC_BUFFER) {
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
if (net_ratelimit())
printk(KERN_DEBUG "%s: BC TX buffer full - dropping the oldest frame\n",
tx->sdata->name);
#endif
dev_kfree_skb(skb_dequeue(&tx->sdata->bss->ps_bc_buf));
} else
tx->local->total_ps_buffered++;
skb_queue_tail(&tx->sdata->bss->ps_bc_buf, tx->skb);
return TX_QUEUED;
}
static int ieee80211_use_mfp(__le16 fc, struct sta_info *sta,
struct sk_buff *skb)
{
if (!ieee80211_is_mgmt(fc))
return 0;
if (sta == NULL || !test_sta_flags(sta, WLAN_STA_MFP))
return 0;
if (!ieee80211_is_robust_mgmt_frame((struct ieee80211_hdr *)
skb->data))
return 0;
return 1;
}
static ieee80211_tx_result
ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx)
{
struct sta_info *sta = tx->sta;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data;
struct ieee80211_local *local = tx->local;
u32 staflags;
if (unlikely(!sta ||
ieee80211_is_probe_resp(hdr->frame_control) ||
ieee80211_is_auth(hdr->frame_control) ||
ieee80211_is_assoc_resp(hdr->frame_control) ||
ieee80211_is_reassoc_resp(hdr->frame_control)))
return TX_CONTINUE;
staflags = get_sta_flags(sta);
if (unlikely((staflags & (WLAN_STA_PS_STA | WLAN_STA_PS_DRIVER)) &&
!(info->flags & IEEE80211_TX_CTL_PSPOLL_RESPONSE))) {
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
printk(KERN_DEBUG "STA %pM aid %d: PS buffer (entries "
"before %d)\n",
sta->sta.addr, sta->sta.aid,
skb_queue_len(&sta->ps_tx_buf));
#endif /* CONFIG_MAC80211_VERBOSE_PS_DEBUG */
if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
purge_old_ps_buffers(tx->local);
if (skb_queue_len(&sta->ps_tx_buf) >= STA_MAX_TX_BUFFER) {
struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf);
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
if (net_ratelimit()) {
printk(KERN_DEBUG "%s: STA %pM TX "
"buffer full - dropping oldest frame\n",
tx->sdata->name, sta->sta.addr);
}
#endif
dev_kfree_skb(old);
} else
tx->local->total_ps_buffered++;
/*
* Queue frame to be sent after STA wakes up/polls,
* but don't set the TIM bit if the driver is blocking
* wakeup or poll response transmissions anyway.
*/
if (skb_queue_empty(&sta->ps_tx_buf) &&
!(staflags & WLAN_STA_PS_DRIVER))
sta_info_set_tim_bit(sta);
info->control.jiffies = jiffies;
info->control.vif = &tx->sdata->vif;
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
skb_queue_tail(&sta->ps_tx_buf, tx->skb);
if (!timer_pending(&local->sta_cleanup))
mod_timer(&local->sta_cleanup,
round_jiffies(jiffies +
STA_INFO_CLEANUP_INTERVAL));
return TX_QUEUED;
}
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
else if (unlikely(staflags & WLAN_STA_PS_STA)) {
printk(KERN_DEBUG "%s: STA %pM in PS mode, but pspoll "
"set -> send frame\n", tx->sdata->name,
sta->sta.addr);
}
#endif /* CONFIG_MAC80211_VERBOSE_PS_DEBUG */
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_ps_buf(struct ieee80211_tx_data *tx)
{
if (unlikely(tx->flags & IEEE80211_TX_PS_BUFFERED))
return TX_CONTINUE;
if (tx->flags & IEEE80211_TX_UNICAST)
return ieee80211_tx_h_unicast_ps_buf(tx);
else
return ieee80211_tx_h_multicast_ps_buf(tx);
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_check_control_port_protocol(struct ieee80211_tx_data *tx)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
if (unlikely(tx->sdata->control_port_protocol == tx->skb->protocol &&
tx->sdata->control_port_no_encrypt))
info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx)
{
struct ieee80211_key *key = NULL;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data;
if (unlikely(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT))
tx->key = NULL;
else if (tx->sta && (key = rcu_dereference(tx->sta->ptk)))
tx->key = key;
else if (ieee80211_is_mgmt(hdr->frame_control) &&
is_multicast_ether_addr(hdr->addr1) &&
ieee80211_is_robust_mgmt_frame(hdr) &&
(key = rcu_dereference(tx->sdata->default_mgmt_key)))
tx->key = key;
else if (is_multicast_ether_addr(hdr->addr1) &&
(key = rcu_dereference(tx->sdata->default_multicast_key)))
tx->key = key;
else if (!is_multicast_ether_addr(hdr->addr1) &&
(key = rcu_dereference(tx->sdata->default_unicast_key)))
tx->key = key;
else if (tx->sdata->drop_unencrypted &&
(tx->skb->protocol != tx->sdata->control_port_protocol) &&
!(info->flags & IEEE80211_TX_CTL_INJECTED) &&
(!ieee80211_is_robust_mgmt_frame(hdr) ||
(ieee80211_is_action(hdr->frame_control) &&
tx->sta && test_sta_flags(tx->sta, WLAN_STA_MFP)))) {
I802_DEBUG_INC(tx->local->tx_handlers_drop_unencrypted);
return TX_DROP;
} else
tx->key = NULL;
if (tx->key) {
bool skip_hw = false;
tx->key->tx_rx_count++;
/* TODO: add threshold stuff again */
switch (tx->key->conf.cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
if (ieee80211_is_auth(hdr->frame_control))
break;
case WLAN_CIPHER_SUITE_TKIP:
if (!ieee80211_is_data_present(hdr->frame_control))
tx->key = NULL;
break;
case WLAN_CIPHER_SUITE_CCMP:
if (!ieee80211_is_data_present(hdr->frame_control) &&
!ieee80211_use_mfp(hdr->frame_control, tx->sta,
tx->skb))
tx->key = NULL;
else
skip_hw = (tx->key->conf.flags &
IEEE80211_KEY_FLAG_SW_MGMT) &&
ieee80211_is_mgmt(hdr->frame_control);
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
if (!ieee80211_is_mgmt(hdr->frame_control))
tx->key = NULL;
break;
}
if (!skip_hw && tx->key &&
tx->key->flags & KEY_FLAG_UPLOADED_TO_HARDWARE)
info->control.hw_key = &tx->key->conf;
}
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_rate_ctrl(struct ieee80211_tx_data *tx)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_hdr *hdr = (void *)tx->skb->data;
struct ieee80211_supported_band *sband;
struct ieee80211_rate *rate;
int i;
u32 len;
bool inval = false, rts = false, short_preamble = false;
struct ieee80211_tx_rate_control txrc;
u32 sta_flags;
memset(&txrc, 0, sizeof(txrc));
sband = tx->local->hw.wiphy->bands[tx->channel->band];
len = min_t(u32, tx->skb->len + FCS_LEN,
tx->local->hw.wiphy->frag_threshold);
/* set up the tx rate control struct we give the RC algo */
txrc.hw = local_to_hw(tx->local);
txrc.sband = sband;
txrc.bss_conf = &tx->sdata->vif.bss_conf;
txrc.skb = tx->skb;
txrc.reported_rate.idx = -1;
txrc.rate_idx_mask = tx->sdata->rc_rateidx_mask[tx->channel->band];
if (txrc.rate_idx_mask == (1 << sband->n_bitrates) - 1)
txrc.max_rate_idx = -1;
else
txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1;
txrc.bss = (tx->sdata->vif.type == NL80211_IFTYPE_AP ||
tx->sdata->vif.type == NL80211_IFTYPE_ADHOC);
/* set up RTS protection if desired */
if (len > tx->local->hw.wiphy->rts_threshold) {
txrc.rts = rts = true;
}
/*
* Use short preamble if the BSS can handle it, but not for
* management frames unless we know the receiver can handle
* that -- the management frame might be to a station that
* just wants a probe response.
*/
if (tx->sdata->vif.bss_conf.use_short_preamble &&
(ieee80211_is_data(hdr->frame_control) ||
(tx->sta && test_sta_flags(tx->sta, WLAN_STA_SHORT_PREAMBLE))))
txrc.short_preamble = short_preamble = true;
sta_flags = tx->sta ? get_sta_flags(tx->sta) : 0;
/*
* Lets not bother rate control if we're associated and cannot
* talk to the sta. This should not happen.
*/
if (WARN(test_bit(SCAN_SW_SCANNING, &tx->local->scanning) &&
(sta_flags & WLAN_STA_ASSOC) &&
!rate_usable_index_exists(sband, &tx->sta->sta),
"%s: Dropped data frame as no usable bitrate found while "
"scanning and associated. Target station: "
"%pM on %d GHz band\n",
tx->sdata->name, hdr->addr1,
tx->channel->band ? 5 : 2))
return TX_DROP;
/*
* If we're associated with the sta at this point we know we can at
* least send the frame at the lowest bit rate.
*/
rate_control_get_rate(tx->sdata, tx->sta, &txrc);
if (unlikely(info->control.rates[0].idx < 0))
return TX_DROP;
if (txrc.reported_rate.idx < 0) {
txrc.reported_rate = info->control.rates[0];
if (tx->sta && ieee80211_is_data(hdr->frame_control))
tx->sta->last_tx_rate = txrc.reported_rate;
} else if (tx->sta)
tx->sta->last_tx_rate = txrc.reported_rate;
if (unlikely(!info->control.rates[0].count))
info->control.rates[0].count = 1;
if (WARN_ON_ONCE((info->control.rates[0].count > 1) &&
(info->flags & IEEE80211_TX_CTL_NO_ACK)))
info->control.rates[0].count = 1;
if (is_multicast_ether_addr(hdr->addr1)) {
/*
* XXX: verify the rate is in the basic rateset
*/
return TX_CONTINUE;
}
/*
* set up the RTS/CTS rate as the fastest basic rate
* that is not faster than the data rate
*
* XXX: Should this check all retry rates?
*/
if (!(info->control.rates[0].flags & IEEE80211_TX_RC_MCS)) {
s8 baserate = 0;
rate = &sband->bitrates[info->control.rates[0].idx];
for (i = 0; i < sband->n_bitrates; i++) {
/* must be a basic rate */
if (!(tx->sdata->vif.bss_conf.basic_rates & BIT(i)))
continue;
/* must not be faster than the data rate */
if (sband->bitrates[i].bitrate > rate->bitrate)
continue;
/* maximum */
if (sband->bitrates[baserate].bitrate <
sband->bitrates[i].bitrate)
baserate = i;
}
info->control.rts_cts_rate_idx = baserate;
}
for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) {
/*
* make sure there's no valid rate following
* an invalid one, just in case drivers don't
* take the API seriously to stop at -1.
*/
if (inval) {
info->control.rates[i].idx = -1;
continue;
}
if (info->control.rates[i].idx < 0) {
inval = true;
continue;
}
/*
* For now assume MCS is already set up correctly, this
* needs to be fixed.
*/
if (info->control.rates[i].flags & IEEE80211_TX_RC_MCS) {
WARN_ON(info->control.rates[i].idx > 76);
continue;
}
/* set up RTS protection if desired */
if (rts)
info->control.rates[i].flags |=
IEEE80211_TX_RC_USE_RTS_CTS;
/* RC is busted */
if (WARN_ON_ONCE(info->control.rates[i].idx >=
sband->n_bitrates)) {
info->control.rates[i].idx = -1;
continue;
}
rate = &sband->bitrates[info->control.rates[i].idx];
/* set up short preamble */
if (short_preamble &&
rate->flags & IEEE80211_RATE_SHORT_PREAMBLE)
info->control.rates[i].flags |=
IEEE80211_TX_RC_USE_SHORT_PREAMBLE;
/* set up G protection */
if (!rts && tx->sdata->vif.bss_conf.use_cts_prot &&
rate->flags & IEEE80211_RATE_ERP_G)
info->control.rates[i].flags |=
IEEE80211_TX_RC_USE_CTS_PROTECT;
}
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_sequence(struct ieee80211_tx_data *tx)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data;
u16 *seq;
u8 *qc;
int tid;
/*
* Packet injection may want to control the sequence
* number, if we have no matching interface then we
* neither assign one ourselves nor ask the driver to.
*/
if (unlikely(info->control.vif->type == NL80211_IFTYPE_MONITOR))
return TX_CONTINUE;
if (unlikely(ieee80211_is_ctl(hdr->frame_control)))
return TX_CONTINUE;
if (ieee80211_hdrlen(hdr->frame_control) < 24)
return TX_CONTINUE;
/*
* Anything but QoS data that has a sequence number field
* (is long enough) gets a sequence number from the global
* counter.
*/
if (!ieee80211_is_data_qos(hdr->frame_control)) {
/* driver should assign sequence number */
info->flags |= IEEE80211_TX_CTL_ASSIGN_SEQ;
/* for pure STA mode without beacons, we can do it */
hdr->seq_ctrl = cpu_to_le16(tx->sdata->sequence_number);
tx->sdata->sequence_number += 0x10;
return TX_CONTINUE;
}
/*
* This should be true for injected/management frames only, for
* management frames we have set the IEEE80211_TX_CTL_ASSIGN_SEQ
* above since they are not QoS-data frames.
*/
if (!tx->sta)
return TX_CONTINUE;
/* include per-STA, per-TID sequence counter */
qc = ieee80211_get_qos_ctl(hdr);
tid = *qc & IEEE80211_QOS_CTL_TID_MASK;
seq = &tx->sta->tid_seq[tid];
hdr->seq_ctrl = cpu_to_le16(*seq);
/* Increase the sequence number. */
*seq = (*seq + 0x10) & IEEE80211_SCTL_SEQ;
return TX_CONTINUE;
}
static int ieee80211_fragment(struct ieee80211_local *local,
struct sk_buff *skb, int hdrlen,
int frag_threshold)
{
struct sk_buff *tail = skb, *tmp;
int per_fragm = frag_threshold - hdrlen - FCS_LEN;
int pos = hdrlen + per_fragm;
int rem = skb->len - hdrlen - per_fragm;
if (WARN_ON(rem < 0))
return -EINVAL;
while (rem) {
int fraglen = per_fragm;
if (fraglen > rem)
fraglen = rem;
rem -= fraglen;
tmp = dev_alloc_skb(local->tx_headroom +
frag_threshold +
IEEE80211_ENCRYPT_HEADROOM +
IEEE80211_ENCRYPT_TAILROOM);
if (!tmp)
return -ENOMEM;
tail->next = tmp;
tail = tmp;
skb_reserve(tmp, local->tx_headroom +
IEEE80211_ENCRYPT_HEADROOM);
/* copy control information */
memcpy(tmp->cb, skb->cb, sizeof(tmp->cb));
skb_copy_queue_mapping(tmp, skb);
tmp->priority = skb->priority;
tmp->dev = skb->dev;
/* copy header and data */
memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen);
memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen);
pos += fraglen;
}
skb->len = hdrlen + per_fragm;
return 0;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_fragment(struct ieee80211_tx_data *tx)
{
struct sk_buff *skb = tx->skb;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (void *)skb->data;
int frag_threshold = tx->local->hw.wiphy->frag_threshold;
int hdrlen;
int fragnum;
if (!(tx->flags & IEEE80211_TX_FRAGMENTED))
return TX_CONTINUE;
/*
* Warn when submitting a fragmented A-MPDU frame and drop it.
* This scenario is handled in ieee80211_tx_prepare but extra
* caution taken here as fragmented ampdu may cause Tx stop.
*/
if (WARN_ON(info->flags & IEEE80211_TX_CTL_AMPDU))
return TX_DROP;
hdrlen = ieee80211_hdrlen(hdr->frame_control);
/* internal error, why is TX_FRAGMENTED set? */
if (WARN_ON(skb->len + FCS_LEN <= frag_threshold))
return TX_DROP;
/*
* Now fragment the frame. This will allocate all the fragments and
* chain them (using skb as the first fragment) to skb->next.
* During transmission, we will remove the successfully transmitted
* fragments from this list. When the low-level driver rejects one
* of the fragments then we will simply pretend to accept the skb
* but store it away as pending.
*/
if (ieee80211_fragment(tx->local, skb, hdrlen, frag_threshold))
return TX_DROP;
/* update duration/seq/flags of fragments */
fragnum = 0;
do {
int next_len;
const __le16 morefrags = cpu_to_le16(IEEE80211_FCTL_MOREFRAGS);
hdr = (void *)skb->data;
info = IEEE80211_SKB_CB(skb);
if (skb->next) {
hdr->frame_control |= morefrags;
next_len = skb->next->len;
/*
* No multi-rate retries for fragmented frames, that
* would completely throw off the NAV at other STAs.
*/
info->control.rates[1].idx = -1;
info->control.rates[2].idx = -1;
info->control.rates[3].idx = -1;
info->control.rates[4].idx = -1;
BUILD_BUG_ON(IEEE80211_TX_MAX_RATES != 5);
info->flags &= ~IEEE80211_TX_CTL_RATE_CTRL_PROBE;
} else {
hdr->frame_control &= ~morefrags;
next_len = 0;
}
hdr->duration_id = ieee80211_duration(tx, 0, next_len);
hdr->seq_ctrl |= cpu_to_le16(fragnum & IEEE80211_SCTL_FRAG);
fragnum++;
} while ((skb = skb->next));
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_stats(struct ieee80211_tx_data *tx)
{
struct sk_buff *skb = tx->skb;
if (!tx->sta)
return TX_CONTINUE;
tx->sta->tx_packets++;
do {
tx->sta->tx_fragments++;
tx->sta->tx_bytes += skb->len;
} while ((skb = skb->next));
return TX_CONTINUE;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_encrypt(struct ieee80211_tx_data *tx)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
if (!tx->key)
return TX_CONTINUE;
switch (tx->key->conf.cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
return ieee80211_crypto_wep_encrypt(tx);
case WLAN_CIPHER_SUITE_TKIP:
return ieee80211_crypto_tkip_encrypt(tx);
case WLAN_CIPHER_SUITE_CCMP:
return ieee80211_crypto_ccmp_encrypt(tx);
case WLAN_CIPHER_SUITE_AES_CMAC:
return ieee80211_crypto_aes_cmac_encrypt(tx);
default:
/* handle hw-only algorithm */
if (info->control.hw_key) {
ieee80211_tx_set_protected(tx);
return TX_CONTINUE;
}
break;
}
return TX_DROP;
}
static ieee80211_tx_result debug_noinline
ieee80211_tx_h_calculate_duration(struct ieee80211_tx_data *tx)
{
struct sk_buff *skb = tx->skb;
struct ieee80211_hdr *hdr;
int next_len;
bool group_addr;
do {
hdr = (void *) skb->data;
if (unlikely(ieee80211_is_pspoll(hdr->frame_control)))
break; /* must not overwrite AID */
next_len = skb->next ? skb->next->len : 0;
group_addr = is_multicast_ether_addr(hdr->addr1);
hdr->duration_id =
ieee80211_duration(tx, group_addr, next_len);
} while ((skb = skb->next));
return TX_CONTINUE;
}
/* actual transmit path */
/*
* deal with packet injection down monitor interface
* with Radiotap Header -- only called for monitor mode interface
*/
static bool __ieee80211_parse_tx_radiotap(struct ieee80211_tx_data *tx,
struct sk_buff *skb)
{
/*
* this is the moment to interpret and discard the radiotap header that
* must be at the start of the packet injected in Monitor mode
*
* Need to take some care with endian-ness since radiotap
* args are little-endian
*/
struct ieee80211_radiotap_iterator iterator;
struct ieee80211_radiotap_header *rthdr =
(struct ieee80211_radiotap_header *) skb->data;
bool hw_frag;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
int ret = ieee80211_radiotap_iterator_init(&iterator, rthdr, skb->len,
NULL);
info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
tx->flags &= ~IEEE80211_TX_FRAGMENTED;
/* packet is fragmented in HW if we have a non-NULL driver callback */
hw_frag = (tx->local->ops->set_frag_threshold != NULL);
/*
* for every radiotap entry that is present
* (ieee80211_radiotap_iterator_next returns -ENOENT when no more
* entries present, or -EINVAL on error)
*/
while (!ret) {
ret = ieee80211_radiotap_iterator_next(&iterator);
if (ret)
continue;
/* see if this argument is something we can use */
switch (iterator.this_arg_index) {
/*
* You must take care when dereferencing iterator.this_arg
* for multibyte types... the pointer is not aligned. Use
* get_unaligned((type *)iterator.this_arg) to dereference
* iterator.this_arg for type "type" safely on all arches.
*/
case IEEE80211_RADIOTAP_FLAGS:
if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FCS) {
/*
* this indicates that the skb we have been
* handed has the 32-bit FCS CRC at the end...
* we should react to that by snipping it off
* because it will be recomputed and added
* on transmission
*/
if (skb->len < (iterator._max_length + FCS_LEN))
return false;
skb_trim(skb, skb->len - FCS_LEN);
}
if (*iterator.this_arg & IEEE80211_RADIOTAP_F_WEP)
info->flags &= ~IEEE80211_TX_INTFL_DONT_ENCRYPT;
if ((*iterator.this_arg & IEEE80211_RADIOTAP_F_FRAG) &&
!hw_frag)
tx->flags |= IEEE80211_TX_FRAGMENTED;
break;
/*
* Please update the file
* Documentation/networking/mac80211-injection.txt
* when parsing new fields here.
*/
default:
break;
}
}
if (ret != -ENOENT) /* ie, if we didn't simply run out of fields */
return false;
/*
* remove the radiotap header
* iterator->_max_length was sanity-checked against
* skb->len by iterator init
*/
skb_pull(skb, iterator._max_length);
return true;
}
static bool ieee80211_tx_prep_agg(struct ieee80211_tx_data *tx,
struct sk_buff *skb,
struct ieee80211_tx_info *info,
struct tid_ampdu_tx *tid_tx,
int tid)
{
bool queued = false;
if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) {
info->flags |= IEEE80211_TX_CTL_AMPDU;
} else if (test_bit(HT_AGG_STATE_WANT_START, &tid_tx->state)) {
/*
* nothing -- this aggregation session is being started
* but that might still fail with the driver
*/
} else {
spin_lock(&tx->sta->lock);
/*
* Need to re-check now, because we may get here
*
* 1) in the window during which the setup is actually
* already done, but not marked yet because not all
* packets are spliced over to the driver pending
* queue yet -- if this happened we acquire the lock
* either before or after the splice happens, but
* need to recheck which of these cases happened.
*
* 2) during session teardown, if the OPERATIONAL bit
* was cleared due to the teardown but the pointer
* hasn't been assigned NULL yet (or we loaded it
* before it was assigned) -- in this case it may
* now be NULL which means we should just let the
* packet pass through because splicing the frames
* back is already done.
*/
tid_tx = rcu_dereference_protected_tid_tx(tx->sta, tid);
if (!tid_tx) {
/* do nothing, let packet pass through */
} else if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) {
info->flags |= IEEE80211_TX_CTL_AMPDU;
} else {
queued = true;
info->control.vif = &tx->sdata->vif;
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
__skb_queue_tail(&tid_tx->pending, skb);
}
spin_unlock(&tx->sta->lock);
}
return queued;
}
/*
* initialises @tx
*/
static ieee80211_tx_result
ieee80211_tx_prepare(struct ieee80211_sub_if_data *sdata,
struct ieee80211_tx_data *tx,
struct sk_buff *skb)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
int hdrlen, tid;
u8 *qc;
memset(tx, 0, sizeof(*tx));
tx->skb = skb;
tx->local = local;
tx->sdata = sdata;
tx->channel = local->hw.conf.channel;
/*
* Set this flag (used below to indicate "automatic fragmentation"),
* it will be cleared/left by radiotap as desired.
* Only valid when fragmentation is done by the stack.
*/
if (!local->ops->set_frag_threshold)
tx->flags |= IEEE80211_TX_FRAGMENTED;
/* process and remove the injection radiotap header */
if (unlikely(info->flags & IEEE80211_TX_INTFL_HAS_RADIOTAP)) {
if (!__ieee80211_parse_tx_radiotap(tx, skb))
return TX_DROP;
/*
* __ieee80211_parse_tx_radiotap has now removed
* the radiotap header that was present and pre-filled
* 'tx' with tx control information.
*/
info->flags &= ~IEEE80211_TX_INTFL_HAS_RADIOTAP;
}
/*
* If this flag is set to true anywhere, and we get here,
* we are doing the needed processing, so remove the flag
* now.
*/
info->flags &= ~IEEE80211_TX_INTFL_NEED_TXPROCESSING;
hdr = (struct ieee80211_hdr *) skb->data;
if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
tx->sta = rcu_dereference(sdata->u.vlan.sta);
if (!tx->sta && sdata->dev->ieee80211_ptr->use_4addr)
return TX_DROP;
} else if (info->flags & IEEE80211_TX_CTL_INJECTED) {
tx->sta = sta_info_get_bss(sdata, hdr->addr1);
}
if (!tx->sta)
tx->sta = sta_info_get(sdata, hdr->addr1);
if (tx->sta && ieee80211_is_data_qos(hdr->frame_control) &&
(local->hw.flags & IEEE80211_HW_AMPDU_AGGREGATION)) {
struct tid_ampdu_tx *tid_tx;
qc = ieee80211_get_qos_ctl(hdr);
tid = *qc & IEEE80211_QOS_CTL_TID_MASK;
tid_tx = rcu_dereference(tx->sta->ampdu_mlme.tid_tx[tid]);
if (tid_tx) {
bool queued;
queued = ieee80211_tx_prep_agg(tx, skb, info,
tid_tx, tid);
if (unlikely(queued))
return TX_QUEUED;
}
}
if (is_multicast_ether_addr(hdr->addr1)) {
tx->flags &= ~IEEE80211_TX_UNICAST;
info->flags |= IEEE80211_TX_CTL_NO_ACK;
} else {
tx->flags |= IEEE80211_TX_UNICAST;
if (unlikely(local->wifi_wme_noack_test))
info->flags |= IEEE80211_TX_CTL_NO_ACK;
else
info->flags &= ~IEEE80211_TX_CTL_NO_ACK;
}
if (tx->flags & IEEE80211_TX_FRAGMENTED) {
if ((tx->flags & IEEE80211_TX_UNICAST) &&
skb->len + FCS_LEN > local->hw.wiphy->frag_threshold &&
!(info->flags & IEEE80211_TX_CTL_AMPDU))
tx->flags |= IEEE80211_TX_FRAGMENTED;
else
tx->flags &= ~IEEE80211_TX_FRAGMENTED;
}
if (!tx->sta)
info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
else if (test_and_clear_sta_flags(tx->sta, WLAN_STA_CLEAR_PS_FILT))
info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
hdrlen = ieee80211_hdrlen(hdr->frame_control);
if (skb->len > hdrlen + sizeof(rfc1042_header) + 2) {
u8 *pos = &skb->data[hdrlen + sizeof(rfc1042_header)];
tx->ethertype = (pos[0] << 8) | pos[1];
}
info->flags |= IEEE80211_TX_CTL_FIRST_FRAGMENT;
return TX_CONTINUE;
}
/*
* Returns false if the frame couldn't be transmitted but was queued instead.
*/
static bool __ieee80211_tx(struct ieee80211_local *local, struct sk_buff **skbp,
struct sta_info *sta, bool txpending)
{
struct sk_buff *skb = *skbp, *next;
struct ieee80211_tx_info *info;
struct ieee80211_sub_if_data *sdata;
unsigned long flags;
int len;
bool fragm = false;
while (skb) {
int q = skb_get_queue_mapping(skb);
__le16 fc;
spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
if (local->queue_stop_reasons[q] ||
(!txpending && !skb_queue_empty(&local->pending[q]))) {
/*
* Since queue is stopped, queue up frames for later
* transmission from the tx-pending tasklet when the
* queue is woken again.
*/
do {
next = skb->next;
skb->next = NULL;
/*
* NB: If txpending is true, next must already
* be NULL since we must've gone through this
* loop before already; therefore we can just
* queue the frame to the head without worrying
* about reordering of fragments.
*/
if (unlikely(txpending))
__skb_queue_head(&local->pending[q],
skb);
else
__skb_queue_tail(&local->pending[q],
skb);
} while ((skb = next));
spin_unlock_irqrestore(&local->queue_stop_reason_lock,
flags);
return false;
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
info = IEEE80211_SKB_CB(skb);
if (fragm)
info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT |
IEEE80211_TX_CTL_FIRST_FRAGMENT);
next = skb->next;
len = skb->len;
if (next)
info->flags |= IEEE80211_TX_CTL_MORE_FRAMES;
sdata = vif_to_sdata(info->control.vif);
switch (sdata->vif.type) {
case NL80211_IFTYPE_MONITOR:
info->control.vif = NULL;
break;
case NL80211_IFTYPE_AP_VLAN:
info->control.vif = &container_of(sdata->bss,
struct ieee80211_sub_if_data, u.ap)->vif;
break;
default:
/* keep */
break;
}
if (sta && sta->uploaded)
info->control.sta = &sta->sta;
else
info->control.sta = NULL;
fc = ((struct ieee80211_hdr *)skb->data)->frame_control;
drv_tx(local, skb);
ieee80211_tpt_led_trig_tx(local, fc, len);
*skbp = skb = next;
ieee80211_led_tx(local, 1);
fragm = true;
}
return true;
}
/*
* Invoke TX handlers, return 0 on success and non-zero if the
* frame was dropped or queued.
*/
static int invoke_tx_handlers(struct ieee80211_tx_data *tx)
{
struct sk_buff *skb = tx->skb;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
ieee80211_tx_result res = TX_DROP;
#define CALL_TXH(txh) \
do { \
res = txh(tx); \
if (res != TX_CONTINUE) \
goto txh_done; \
} while (0)
CALL_TXH(ieee80211_tx_h_dynamic_ps);
CALL_TXH(ieee80211_tx_h_check_assoc);
CALL_TXH(ieee80211_tx_h_ps_buf);
CALL_TXH(ieee80211_tx_h_check_control_port_protocol);
CALL_TXH(ieee80211_tx_h_select_key);
if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL))
CALL_TXH(ieee80211_tx_h_rate_ctrl);
if (unlikely(info->flags & IEEE80211_TX_INTFL_RETRANSMISSION))
goto txh_done;
CALL_TXH(ieee80211_tx_h_michael_mic_add);
CALL_TXH(ieee80211_tx_h_sequence);
CALL_TXH(ieee80211_tx_h_fragment);
/* handlers after fragment must be aware of tx info fragmentation! */
CALL_TXH(ieee80211_tx_h_stats);
CALL_TXH(ieee80211_tx_h_encrypt);
if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL))
CALL_TXH(ieee80211_tx_h_calculate_duration);
#undef CALL_TXH
txh_done:
if (unlikely(res == TX_DROP)) {
I802_DEBUG_INC(tx->local->tx_handlers_drop);
while (skb) {
struct sk_buff *next;
next = skb->next;
dev_kfree_skb(skb);
skb = next;
}
return -1;
} else if (unlikely(res == TX_QUEUED)) {
I802_DEBUG_INC(tx->local->tx_handlers_queued);
return -1;
}
return 0;
}
/*
* Returns false if the frame couldn't be transmitted but was queued instead.
*/
static bool ieee80211_tx(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb, bool txpending)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_tx_data tx;
ieee80211_tx_result res_prepare;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
bool result = true;
if (unlikely(skb->len < 10)) {
dev_kfree_skb(skb);
return true;
}
rcu_read_lock();
/* initialises tx */
res_prepare = ieee80211_tx_prepare(sdata, &tx, skb);
if (unlikely(res_prepare == TX_DROP)) {
dev_kfree_skb(skb);
goto out;
} else if (unlikely(res_prepare == TX_QUEUED)) {
goto out;
}
tx.channel = local->hw.conf.channel;
info->band = tx.channel->band;
if (!invoke_tx_handlers(&tx))
result = __ieee80211_tx(local, &tx.skb, tx.sta, txpending);
out:
rcu_read_unlock();
return result;
}
/* device xmit handlers */
static int ieee80211_skb_resize(struct ieee80211_local *local,
struct sk_buff *skb,
int head_need, bool may_encrypt)
{
int tail_need = 0;
/*
* This could be optimised, devices that do full hardware
* crypto (including TKIP MMIC) need no tailroom... But we
* have no drivers for such devices currently.
*/
if (may_encrypt) {
tail_need = IEEE80211_ENCRYPT_TAILROOM;
tail_need -= skb_tailroom(skb);
tail_need = max_t(int, tail_need, 0);
}
if (head_need || tail_need) {
/* Sorry. Can't account for this any more */
skb_orphan(skb);
}
if (skb_cloned(skb))
I802_DEBUG_INC(local->tx_expand_skb_head_cloned);
else if (head_need || tail_need)
I802_DEBUG_INC(local->tx_expand_skb_head);
else
return 0;
if (pskb_expand_head(skb, head_need, tail_need, GFP_ATOMIC)) {
wiphy_debug(local->hw.wiphy,
"failed to reallocate TX buffer\n");
return -ENOMEM;
}
/* update truesize too */
skb->truesize += head_need + tail_need;
return 0;
}
static void ieee80211_xmit(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct ieee80211_sub_if_data *tmp_sdata;
int headroom;
bool may_encrypt;
rcu_read_lock();
if (unlikely(sdata->vif.type == NL80211_IFTYPE_MONITOR)) {
int hdrlen;
u16 len_rthdr;
info->flags |= IEEE80211_TX_CTL_INJECTED |
IEEE80211_TX_INTFL_HAS_RADIOTAP;
len_rthdr = ieee80211_get_radiotap_len(skb->data);
hdr = (struct ieee80211_hdr *)(skb->data + len_rthdr);
hdrlen = ieee80211_hdrlen(hdr->frame_control);
/* check the header is complete in the frame */
if (likely(skb->len >= len_rthdr + hdrlen)) {
/*
* We process outgoing injected frames that have a
* local address we handle as though they are our
* own frames.
* This code here isn't entirely correct, the local
* MAC address is not necessarily enough to find
* the interface to use; for that proper VLAN/WDS
* support we will need a different mechanism.
*/
list_for_each_entry_rcu(tmp_sdata, &local->interfaces,
list) {
if (!ieee80211_sdata_running(tmp_sdata))
continue;
if (tmp_sdata->vif.type ==
NL80211_IFTYPE_MONITOR ||
tmp_sdata->vif.type ==
NL80211_IFTYPE_AP_VLAN ||
tmp_sdata->vif.type ==
NL80211_IFTYPE_WDS)
continue;
if (compare_ether_addr(tmp_sdata->vif.addr,
hdr->addr2) == 0) {
sdata = tmp_sdata;
break;
}
}
}
}
may_encrypt = !(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT);
headroom = local->tx_headroom;
if (may_encrypt)
headroom += IEEE80211_ENCRYPT_HEADROOM;
headroom -= skb_headroom(skb);
headroom = max_t(int, 0, headroom);
if (ieee80211_skb_resize(local, skb, headroom, may_encrypt)) {
dev_kfree_skb(skb);
rcu_read_unlock();
return;
}
hdr = (struct ieee80211_hdr *) skb->data;
info->control.vif = &sdata->vif;
if (ieee80211_vif_is_mesh(&sdata->vif) &&
ieee80211_is_data(hdr->frame_control) &&
!is_multicast_ether_addr(hdr->addr1))
if (mesh_nexthop_lookup(skb, sdata)) {
/* skb queued: don't free */
rcu_read_unlock();
return;
}
ieee80211_set_qos_hdr(local, skb);
ieee80211_tx(sdata, skb, false);
rcu_read_unlock();
}
netdev_tx_t ieee80211_monitor_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ieee80211_local *local = wdev_priv(dev->ieee80211_ptr);
struct ieee80211_channel *chan = local->hw.conf.channel;
struct ieee80211_radiotap_header *prthdr =
(struct ieee80211_radiotap_header *)skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
u16 len_rthdr;
/*
* Frame injection is not allowed if beaconing is not allowed
* or if we need radar detection. Beaconing is usually not allowed when
* the mode or operation (Adhoc, AP, Mesh) does not support DFS.
* Passive scan is also used in world regulatory domains where
* your country is not known and as such it should be treated as
* NO TX unless the channel is explicitly allowed in which case
* your current regulatory domain would not have the passive scan
* flag.
*
* Since AP mode uses monitor interfaces to inject/TX management
* frames we can make AP mode the exception to this rule once it
* supports radar detection as its implementation can deal with
* radar detection by itself. We can do that later by adding a
* monitor flag interfaces used for AP support.
*/
if ((chan->flags & (IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_PASSIVE_SCAN)))
goto fail;
/* check for not even having the fixed radiotap header part */
if (unlikely(skb->len < sizeof(struct ieee80211_radiotap_header)))
goto fail; /* too short to be possibly valid */
/* is it a header version we can trust to find length from? */
if (unlikely(prthdr->it_version))
goto fail; /* only version 0 is supported */
/* then there must be a radiotap header with a length we can use */
len_rthdr = ieee80211_get_radiotap_len(skb->data);
/* does the skb contain enough to deliver on the alleged length? */
if (unlikely(skb->len < len_rthdr))
goto fail; /* skb too short for claimed rt header extent */
/*
* fix up the pointers accounting for the radiotap
* header still being in there. We are being given
* a precooked IEEE80211 header so no need for
* normal processing
*/
skb_set_mac_header(skb, len_rthdr);
/*
* these are just fixed to the end of the rt area since we
* don't have any better information and at this point, nobody cares
*/
skb_set_network_header(skb, len_rthdr);
skb_set_transport_header(skb, len_rthdr);
memset(info, 0, sizeof(*info));
info->flags |= IEEE80211_TX_CTL_REQ_TX_STATUS;
/* pass the radiotap header up to xmit */
ieee80211_xmit(IEEE80211_DEV_TO_SUB_IF(dev), skb);
return NETDEV_TX_OK;
fail:
dev_kfree_skb(skb);
return NETDEV_TX_OK; /* meaning, we dealt with the skb */
}
/**
* ieee80211_subif_start_xmit - netif start_xmit function for Ethernet-type
* subinterfaces (wlan#, WDS, and VLAN interfaces)
* @skb: packet to be sent
* @dev: incoming interface
*
* Returns: 0 on success (and frees skb in this case) or 1 on failure (skb will
* not be freed, and caller is responsible for either retrying later or freeing
* skb).
*
* This function takes in an Ethernet header and encapsulates it with suitable
* IEEE 802.11 header based on which interface the packet is coming in. The
* encapsulated packet will then be passed to master interface, wlan#.11, for
* transmission (through low-level driver).
*/
netdev_tx_t ieee80211_subif_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
struct ieee80211_local *local = sdata->local;
struct ieee80211_tx_info *info;
int ret = NETDEV_TX_BUSY, head_need;
u16 ethertype, hdrlen, meshhdrlen = 0;
__le16 fc;
struct ieee80211_hdr hdr;
struct ieee80211s_hdr mesh_hdr __maybe_unused;
struct mesh_path __maybe_unused *mppath = NULL;
const u8 *encaps_data;
int encaps_len, skip_header_bytes;
int nh_pos, h_pos;
struct sta_info *sta = NULL;
u32 sta_flags = 0;
struct sk_buff *tmp_skb;
if (unlikely(skb->len < ETH_HLEN)) {
ret = NETDEV_TX_OK;
goto fail;
}
/* convert Ethernet header to proper 802.11 header (based on
* operation mode) */
ethertype = (skb->data[12] << 8) | skb->data[13];
fc = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_DATA);
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP_VLAN:
rcu_read_lock();
sta = rcu_dereference(sdata->u.vlan.sta);
if (sta) {
fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS);
/* RA TA DA SA */
memcpy(hdr.addr1, sta->sta.addr, ETH_ALEN);
memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN);
memcpy(hdr.addr3, skb->data, ETH_ALEN);
memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN);
hdrlen = 30;
sta_flags = get_sta_flags(sta);
}
rcu_read_unlock();
if (sta)
break;
/* fall through */
case NL80211_IFTYPE_AP:
fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS);
/* DA BSSID SA */
memcpy(hdr.addr1, skb->data, ETH_ALEN);
memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN);
memcpy(hdr.addr3, skb->data + ETH_ALEN, ETH_ALEN);
hdrlen = 24;
break;
case NL80211_IFTYPE_WDS:
fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS);
/* RA TA DA SA */
memcpy(hdr.addr1, sdata->u.wds.remote_addr, ETH_ALEN);
memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN);
memcpy(hdr.addr3, skb->data, ETH_ALEN);
memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN);
hdrlen = 30;
break;
#ifdef CONFIG_MAC80211_MESH
case NL80211_IFTYPE_MESH_POINT:
if (!sdata->u.mesh.mshcfg.dot11MeshTTL) {
/* Do not send frames with mesh_ttl == 0 */
sdata->u.mesh.mshstats.dropped_frames_ttl++;
ret = NETDEV_TX_OK;
goto fail;
}
rcu_read_lock();
if (!is_multicast_ether_addr(skb->data))
mppath = mpp_path_lookup(skb->data, sdata);
/*
* Use address extension if it is a packet from
* another interface or if we know the destination
* is being proxied by a portal (i.e. portal address
* differs from proxied address)
*/
if (compare_ether_addr(sdata->vif.addr,
skb->data + ETH_ALEN) == 0 &&
!(mppath && compare_ether_addr(mppath->mpp, skb->data))) {
hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc,
skb->data, skb->data + ETH_ALEN);
rcu_read_unlock();
meshhdrlen = ieee80211_new_mesh_header(&mesh_hdr,
sdata, NULL, NULL);
} else {
int is_mesh_mcast = 1;
const u8 *mesh_da;
if (is_multicast_ether_addr(skb->data))
/* DA TA mSA AE:SA */
mesh_da = skb->data;
else {
static const u8 bcast[ETH_ALEN] =
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
if (mppath) {
/* RA TA mDA mSA AE:DA SA */
mesh_da = mppath->mpp;
is_mesh_mcast = 0;
} else {
/* DA TA mSA AE:SA */
mesh_da = bcast;
}
}
hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc,
mesh_da, sdata->vif.addr);
rcu_read_unlock();
if (is_mesh_mcast)
meshhdrlen =
ieee80211_new_mesh_header(&mesh_hdr,
sdata,
skb->data + ETH_ALEN,
NULL);
else
meshhdrlen =
ieee80211_new_mesh_header(&mesh_hdr,
sdata,
skb->data,
skb->data + ETH_ALEN);
}
break;
#endif
case NL80211_IFTYPE_STATION:
memcpy(hdr.addr1, sdata->u.mgd.bssid, ETH_ALEN);
if (sdata->u.mgd.use_4addr &&
cpu_to_be16(ethertype) != sdata->control_port_protocol) {
fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS);
/* RA TA DA SA */
memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN);
memcpy(hdr.addr3, skb->data, ETH_ALEN);
memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN);
hdrlen = 30;
} else {
fc |= cpu_to_le16(IEEE80211_FCTL_TODS);
/* BSSID SA DA */
memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN);
memcpy(hdr.addr3, skb->data, ETH_ALEN);
hdrlen = 24;
}
break;
case NL80211_IFTYPE_ADHOC:
/* DA SA BSSID */
memcpy(hdr.addr1, skb->data, ETH_ALEN);
memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN);
memcpy(hdr.addr3, sdata->u.ibss.bssid, ETH_ALEN);
hdrlen = 24;
break;
default:
ret = NETDEV_TX_OK;
goto fail;
}
/*
* There's no need to try to look up the destination
* if it is a multicast address (which can only happen
* in AP mode)
*/
if (!is_multicast_ether_addr(hdr.addr1)) {
rcu_read_lock();
sta = sta_info_get(sdata, hdr.addr1);
if (sta)
sta_flags = get_sta_flags(sta);
rcu_read_unlock();
}
/* receiver and we are QoS enabled, use a QoS type frame */
if ((sta_flags & WLAN_STA_WME) && local->hw.queues >= 4) {
fc |= cpu_to_le16(IEEE80211_STYPE_QOS_DATA);
hdrlen += 2;
}
/*
* Drop unicast frames to unauthorised stations unless they are
* EAPOL frames from the local station.
*/
if (!ieee80211_vif_is_mesh(&sdata->vif) &&
unlikely(!is_multicast_ether_addr(hdr.addr1) &&
!(sta_flags & WLAN_STA_AUTHORIZED) &&
!(cpu_to_be16(ethertype) == sdata->control_port_protocol &&
compare_ether_addr(sdata->vif.addr,
skb->data + ETH_ALEN) == 0))) {
#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
if (net_ratelimit())
printk(KERN_DEBUG "%s: dropped frame to %pM"
" (unauthorized port)\n", dev->name,
hdr.addr1);
#endif
I802_DEBUG_INC(local->tx_handlers_drop_unauth_port);
ret = NETDEV_TX_OK;
goto fail;
}
/*
* If the skb is shared we need to obtain our own copy.
*/
if (skb_shared(skb)) {
tmp_skb = skb;
skb = skb_clone(skb, GFP_ATOMIC);
kfree_skb(tmp_skb);
if (!skb) {
ret = NETDEV_TX_OK;
goto fail;
}
}
hdr.frame_control = fc;
hdr.duration_id = 0;
hdr.seq_ctrl = 0;
skip_header_bytes = ETH_HLEN;
if (ethertype == ETH_P_AARP || ethertype == ETH_P_IPX) {
encaps_data = bridge_tunnel_header;
encaps_len = sizeof(bridge_tunnel_header);
skip_header_bytes -= 2;
} else if (ethertype >= 0x600) {
encaps_data = rfc1042_header;
encaps_len = sizeof(rfc1042_header);
skip_header_bytes -= 2;
} else {
encaps_data = NULL;
encaps_len = 0;
}
nh_pos = skb_network_header(skb) - skb->data;
h_pos = skb_transport_header(skb) - skb->data;
skb_pull(skb, skip_header_bytes);
nh_pos -= skip_header_bytes;
h_pos -= skip_header_bytes;
head_need = hdrlen + encaps_len + meshhdrlen - skb_headroom(skb);
/*
* So we need to modify the skb header and hence need a copy of
* that. The head_need variable above doesn't, so far, include
* the needed header space that we don't need right away. If we
* can, then we don't reallocate right now but only after the
* frame arrives at the master device (if it does...)
*
* If we cannot, however, then we will reallocate to include all
* the ever needed space. Also, if we need to reallocate it anyway,
* make it big enough for everything we may ever need.
*/
if (head_need > 0 || skb_cloned(skb)) {
head_need += IEEE80211_ENCRYPT_HEADROOM;
head_need += local->tx_headroom;
head_need = max_t(int, 0, head_need);
if (ieee80211_skb_resize(local, skb, head_need, true))
goto fail;
}
if (encaps_data) {
memcpy(skb_push(skb, encaps_len), encaps_data, encaps_len);
nh_pos += encaps_len;
h_pos += encaps_len;
}
#ifdef CONFIG_MAC80211_MESH
if (meshhdrlen > 0) {
memcpy(skb_push(skb, meshhdrlen), &mesh_hdr, meshhdrlen);
nh_pos += meshhdrlen;
h_pos += meshhdrlen;
}
#endif
if (ieee80211_is_data_qos(fc)) {
__le16 *qos_control;
qos_control = (__le16*) skb_push(skb, 2);
memcpy(skb_push(skb, hdrlen - 2), &hdr, hdrlen - 2);
/*
* Maybe we could actually set some fields here, for now just
* initialise to zero to indicate no special operation.
*/
*qos_control = 0;
} else
memcpy(skb_push(skb, hdrlen), &hdr, hdrlen);
nh_pos += hdrlen;
h_pos += hdrlen;
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
/* Update skb pointers to various headers since this modified frame
* is going to go through Linux networking code that may potentially
* need things like pointer to IP header. */
skb_set_mac_header(skb, 0);
skb_set_network_header(skb, nh_pos);
skb_set_transport_header(skb, h_pos);
info = IEEE80211_SKB_CB(skb);
memset(info, 0, sizeof(*info));
dev->trans_start = jiffies;
ieee80211_xmit(sdata, skb);
return NETDEV_TX_OK;
fail:
if (ret == NETDEV_TX_OK)
dev_kfree_skb(skb);
return ret;
}
/*
* ieee80211_clear_tx_pending may not be called in a context where
* it is possible that it packets could come in again.
*/
void ieee80211_clear_tx_pending(struct ieee80211_local *local)
{
int i;
for (i = 0; i < local->hw.queues; i++)
skb_queue_purge(&local->pending[i]);
}
/*
* Returns false if the frame couldn't be transmitted but was queued instead,
* which in this case means re-queued -- take as an indication to stop sending
* more pending frames.
*/
static bool ieee80211_tx_pending_skb(struct ieee80211_local *local,
struct sk_buff *skb)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_sub_if_data *sdata;
struct sta_info *sta;
struct ieee80211_hdr *hdr;
bool result;
sdata = vif_to_sdata(info->control.vif);
if (info->flags & IEEE80211_TX_INTFL_NEED_TXPROCESSING) {
result = ieee80211_tx(sdata, skb, true);
} else {
hdr = (struct ieee80211_hdr *)skb->data;
sta = sta_info_get(sdata, hdr->addr1);
result = __ieee80211_tx(local, &skb, sta, true);
}
return result;
}
/*
* Transmit all pending packets. Called from tasklet.
*/
void ieee80211_tx_pending(unsigned long data)
{
struct ieee80211_local *local = (struct ieee80211_local *)data;
struct ieee80211_sub_if_data *sdata;
unsigned long flags;
int i;
bool txok;
rcu_read_lock();
spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
for (i = 0; i < local->hw.queues; i++) {
/*
* If queue is stopped by something other than due to pending
* frames, or we have no pending frames, proceed to next queue.
*/
if (local->queue_stop_reasons[i] ||
skb_queue_empty(&local->pending[i]))
continue;
while (!skb_queue_empty(&local->pending[i])) {
struct sk_buff *skb = __skb_dequeue(&local->pending[i]);
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
if (WARN_ON(!info->control.vif)) {
kfree_skb(skb);
continue;
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock,
flags);
txok = ieee80211_tx_pending_skb(local, skb);
spin_lock_irqsave(&local->queue_stop_reason_lock,
flags);
if (!txok)
break;
}
if (skb_queue_empty(&local->pending[i]))
list_for_each_entry_rcu(sdata, &local->interfaces, list)
netif_wake_subqueue(sdata->dev, i);
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
rcu_read_unlock();
}
/* functions for drivers to get certain frames */
static void ieee80211_beacon_add_tim(struct ieee80211_if_ap *bss,
struct sk_buff *skb,
struct beacon_data *beacon)
{
u8 *pos, *tim;
int aid0 = 0;
int i, have_bits = 0, n1, n2;
/* Generate bitmap for TIM only if there are any STAs in power save
* mode. */
if (atomic_read(&bss->num_sta_ps) > 0)
/* in the hope that this is faster than
* checking byte-for-byte */
have_bits = !bitmap_empty((unsigned long*)bss->tim,
IEEE80211_MAX_AID+1);
if (bss->dtim_count == 0)
bss->dtim_count = beacon->dtim_period - 1;
else
bss->dtim_count--;
tim = pos = (u8 *) skb_put(skb, 6);
*pos++ = WLAN_EID_TIM;
*pos++ = 4;
*pos++ = bss->dtim_count;
*pos++ = beacon->dtim_period;
if (bss->dtim_count == 0 && !skb_queue_empty(&bss->ps_bc_buf))
aid0 = 1;
bss->dtim_bc_mc = aid0 == 1;
if (have_bits) {
/* Find largest even number N1 so that bits numbered 1 through
* (N1 x 8) - 1 in the bitmap are 0 and number N2 so that bits
* (N2 + 1) x 8 through 2007 are 0. */
n1 = 0;
for (i = 0; i < IEEE80211_MAX_TIM_LEN; i++) {
if (bss->tim[i]) {
n1 = i & 0xfe;
break;
}
}
n2 = n1;
for (i = IEEE80211_MAX_TIM_LEN - 1; i >= n1; i--) {
if (bss->tim[i]) {
n2 = i;
break;
}
}
/* Bitmap control */
*pos++ = n1 | aid0;
/* Part Virt Bitmap */
memcpy(pos, bss->tim + n1, n2 - n1 + 1);
tim[1] = n2 - n1 + 4;
skb_put(skb, n2 - n1);
} else {
*pos++ = aid0; /* Bitmap control */
*pos++ = 0; /* Part Virt Bitmap */
}
}
struct sk_buff *ieee80211_beacon_get_tim(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
u16 *tim_offset, u16 *tim_length)
{
struct ieee80211_local *local = hw_to_local(hw);
struct sk_buff *skb = NULL;
struct ieee80211_tx_info *info;
struct ieee80211_sub_if_data *sdata = NULL;
struct ieee80211_if_ap *ap = NULL;
struct beacon_data *beacon;
struct ieee80211_supported_band *sband;
enum ieee80211_band band = local->hw.conf.channel->band;
struct ieee80211_tx_rate_control txrc;
sband = local->hw.wiphy->bands[band];
rcu_read_lock();
sdata = vif_to_sdata(vif);
if (!ieee80211_sdata_running(sdata))
goto out;
if (tim_offset)
*tim_offset = 0;
if (tim_length)
*tim_length = 0;
if (sdata->vif.type == NL80211_IFTYPE_AP) {
ap = &sdata->u.ap;
beacon = rcu_dereference(ap->beacon);
if (beacon) {
/*
* headroom, head length,
* tail length and maximum TIM length
*/
skb = dev_alloc_skb(local->tx_headroom +
beacon->head_len +
beacon->tail_len + 256);
if (!skb)
goto out;
skb_reserve(skb, local->tx_headroom);
memcpy(skb_put(skb, beacon->head_len), beacon->head,
beacon->head_len);
/*
* Not very nice, but we want to allow the driver to call
* ieee80211_beacon_get() as a response to the set_tim()
* callback. That, however, is already invoked under the
* sta_lock to guarantee consistent and race-free update
* of the tim bitmap in mac80211 and the driver.
*/
if (local->tim_in_locked_section) {
ieee80211_beacon_add_tim(ap, skb, beacon);
} else {
unsigned long flags;
spin_lock_irqsave(&local->sta_lock, flags);
ieee80211_beacon_add_tim(ap, skb, beacon);
spin_unlock_irqrestore(&local->sta_lock, flags);
}
if (tim_offset)
*tim_offset = beacon->head_len;
if (tim_length)
*tim_length = skb->len - beacon->head_len;
if (beacon->tail)
memcpy(skb_put(skb, beacon->tail_len),
beacon->tail, beacon->tail_len);
} else
goto out;
} else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
struct ieee80211_if_ibss *ifibss = &sdata->u.ibss;
struct ieee80211_hdr *hdr;
struct sk_buff *presp = rcu_dereference(ifibss->presp);
if (!presp)
goto out;
skb = skb_copy(presp, GFP_ATOMIC);
if (!skb)
goto out;
hdr = (struct ieee80211_hdr *) skb->data;
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_BEACON);
} else if (ieee80211_vif_is_mesh(&sdata->vif)) {
struct ieee80211_mgmt *mgmt;
u8 *pos;
#ifdef CONFIG_MAC80211_MESH
if (!sdata->u.mesh.mesh_id_len)
goto out;
#endif
/* headroom, head length, tail length and maximum TIM length */
skb = dev_alloc_skb(local->tx_headroom + 400 +
sdata->u.mesh.ie_len);
if (!skb)
goto out;
skb_reserve(skb, local->hw.extra_tx_headroom);
mgmt = (struct ieee80211_mgmt *)
skb_put(skb, 24 + sizeof(mgmt->u.beacon));
memset(mgmt, 0, 24 + sizeof(mgmt->u.beacon));
mgmt->frame_control =
cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_BEACON);
memset(mgmt->da, 0xff, ETH_ALEN);
memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN);
memcpy(mgmt->bssid, sdata->vif.addr, ETH_ALEN);
mgmt->u.beacon.beacon_int =
cpu_to_le16(sdata->vif.bss_conf.beacon_int);
mgmt->u.beacon.capab_info = 0x0; /* 0x0 for MPs */
pos = skb_put(skb, 2);
*pos++ = WLAN_EID_SSID;
*pos++ = 0x0;
mesh_mgmt_ies_add(skb, sdata);
} else {
WARN_ON(1);
goto out;
}
info = IEEE80211_SKB_CB(skb);
info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
info->flags |= IEEE80211_TX_CTL_NO_ACK;
info->band = band;
memset(&txrc, 0, sizeof(txrc));
txrc.hw = hw;
txrc.sband = sband;
txrc.bss_conf = &sdata->vif.bss_conf;
txrc.skb = skb;
txrc.reported_rate.idx = -1;
txrc.rate_idx_mask = sdata->rc_rateidx_mask[band];
if (txrc.rate_idx_mask == (1 << sband->n_bitrates) - 1)
txrc.max_rate_idx = -1;
else
txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1;
txrc.bss = true;
rate_control_get_rate(sdata, NULL, &txrc);
info->control.vif = vif;
info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT |
IEEE80211_TX_CTL_ASSIGN_SEQ |
IEEE80211_TX_CTL_FIRST_FRAGMENT;
out:
rcu_read_unlock();
return skb;
}
EXPORT_SYMBOL(ieee80211_beacon_get_tim);
struct sk_buff *ieee80211_pspoll_get(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ieee80211_sub_if_data *sdata;
struct ieee80211_if_managed *ifmgd;
struct ieee80211_pspoll *pspoll;
struct ieee80211_local *local;
struct sk_buff *skb;
if (WARN_ON(vif->type != NL80211_IFTYPE_STATION))
return NULL;
sdata = vif_to_sdata(vif);
ifmgd = &sdata->u.mgd;
local = sdata->local;
skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*pspoll));
if (!skb) {
printk(KERN_DEBUG "%s: failed to allocate buffer for "
"pspoll template\n", sdata->name);
return NULL;
}
skb_reserve(skb, local->hw.extra_tx_headroom);
pspoll = (struct ieee80211_pspoll *) skb_put(skb, sizeof(*pspoll));
memset(pspoll, 0, sizeof(*pspoll));
pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
IEEE80211_STYPE_PSPOLL);
pspoll->aid = cpu_to_le16(ifmgd->aid);
/* aid in PS-Poll has its two MSBs each set to 1 */
pspoll->aid |= cpu_to_le16(1 << 15 | 1 << 14);
memcpy(pspoll->bssid, ifmgd->bssid, ETH_ALEN);
memcpy(pspoll->ta, vif->addr, ETH_ALEN);
return skb;
}
EXPORT_SYMBOL(ieee80211_pspoll_get);
struct sk_buff *ieee80211_nullfunc_get(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ieee80211_hdr_3addr *nullfunc;
struct ieee80211_sub_if_data *sdata;
struct ieee80211_if_managed *ifmgd;
struct ieee80211_local *local;
struct sk_buff *skb;
if (WARN_ON(vif->type != NL80211_IFTYPE_STATION))
return NULL;
sdata = vif_to_sdata(vif);
ifmgd = &sdata->u.mgd;
local = sdata->local;
skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*nullfunc));
if (!skb) {
printk(KERN_DEBUG "%s: failed to allocate buffer for nullfunc "
"template\n", sdata->name);
return NULL;
}
skb_reserve(skb, local->hw.extra_tx_headroom);
nullfunc = (struct ieee80211_hdr_3addr *) skb_put(skb,
sizeof(*nullfunc));
memset(nullfunc, 0, sizeof(*nullfunc));
nullfunc->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC |
IEEE80211_FCTL_TODS);
memcpy(nullfunc->addr1, ifmgd->bssid, ETH_ALEN);
memcpy(nullfunc->addr2, vif->addr, ETH_ALEN);
memcpy(nullfunc->addr3, ifmgd->bssid, ETH_ALEN);
return skb;
}
EXPORT_SYMBOL(ieee80211_nullfunc_get);
struct sk_buff *ieee80211_probereq_get(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const u8 *ssid, size_t ssid_len,
const u8 *ie, size_t ie_len)
{
struct ieee80211_sub_if_data *sdata;
struct ieee80211_local *local;
struct ieee80211_hdr_3addr *hdr;
struct sk_buff *skb;
size_t ie_ssid_len;
u8 *pos;
sdata = vif_to_sdata(vif);
local = sdata->local;
ie_ssid_len = 2 + ssid_len;
skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*hdr) +
ie_ssid_len + ie_len);
if (!skb) {
printk(KERN_DEBUG "%s: failed to allocate buffer for probe "
"request template\n", sdata->name);
return NULL;
}
skb_reserve(skb, local->hw.extra_tx_headroom);
hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr));
memset(hdr, 0, sizeof(*hdr));
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_PROBE_REQ);
memset(hdr->addr1, 0xff, ETH_ALEN);
memcpy(hdr->addr2, vif->addr, ETH_ALEN);
memset(hdr->addr3, 0xff, ETH_ALEN);
pos = skb_put(skb, ie_ssid_len);
*pos++ = WLAN_EID_SSID;
*pos++ = ssid_len;
if (ssid)
memcpy(pos, ssid, ssid_len);
pos += ssid_len;
if (ie) {
pos = skb_put(skb, ie_len);
memcpy(pos, ie, ie_len);
}
return skb;
}
EXPORT_SYMBOL(ieee80211_probereq_get);
void ieee80211_rts_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
const void *frame, size_t frame_len,
const struct ieee80211_tx_info *frame_txctl,
struct ieee80211_rts *rts)
{
const struct ieee80211_hdr *hdr = frame;
rts->frame_control =
cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_RTS);
rts->duration = ieee80211_rts_duration(hw, vif, frame_len,
frame_txctl);
memcpy(rts->ra, hdr->addr1, sizeof(rts->ra));
memcpy(rts->ta, hdr->addr2, sizeof(rts->ta));
}
EXPORT_SYMBOL(ieee80211_rts_get);
void ieee80211_ctstoself_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
const void *frame, size_t frame_len,
const struct ieee80211_tx_info *frame_txctl,
struct ieee80211_cts *cts)
{
const struct ieee80211_hdr *hdr = frame;
cts->frame_control =
cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_CTS);
cts->duration = ieee80211_ctstoself_duration(hw, vif,
frame_len, frame_txctl);
memcpy(cts->ra, hdr->addr1, sizeof(cts->ra));
}
EXPORT_SYMBOL(ieee80211_ctstoself_get);
struct sk_buff *
ieee80211_get_buffered_bc(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ieee80211_local *local = hw_to_local(hw);
struct sk_buff *skb = NULL;
struct ieee80211_tx_data tx;
struct ieee80211_sub_if_data *sdata;
struct ieee80211_if_ap *bss = NULL;
struct beacon_data *beacon;
struct ieee80211_tx_info *info;
sdata = vif_to_sdata(vif);
bss = &sdata->u.ap;
rcu_read_lock();
beacon = rcu_dereference(bss->beacon);
if (sdata->vif.type != NL80211_IFTYPE_AP || !beacon || !beacon->head)
goto out;
if (bss->dtim_count != 0 || !bss->dtim_bc_mc)
goto out; /* send buffered bc/mc only after DTIM beacon */
while (1) {
skb = skb_dequeue(&bss->ps_bc_buf);
if (!skb)
goto out;
local->total_ps_buffered--;
if (!skb_queue_empty(&bss->ps_bc_buf) && skb->len >= 2) {
struct ieee80211_hdr *hdr =
(struct ieee80211_hdr *) skb->data;
/* more buffered multicast/broadcast frames ==> set
* MoreData flag in IEEE 802.11 header to inform PS
* STAs */
hdr->frame_control |=
cpu_to_le16(IEEE80211_FCTL_MOREDATA);
}
if (!ieee80211_tx_prepare(sdata, &tx, skb))
break;
dev_kfree_skb_any(skb);
}
info = IEEE80211_SKB_CB(skb);
tx.flags |= IEEE80211_TX_PS_BUFFERED;
tx.channel = local->hw.conf.channel;
info->band = tx.channel->band;
if (invoke_tx_handlers(&tx))
skb = NULL;
out:
rcu_read_unlock();
return skb;
}
EXPORT_SYMBOL(ieee80211_get_buffered_bc);
void ieee80211_tx_skb(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb)
{
skb_set_mac_header(skb, 0);
skb_set_network_header(skb, 0);
skb_set_transport_header(skb, 0);
/* Send all internal mgmt frames on VO. Accordingly set TID to 7. */
skb_set_queue_mapping(skb, IEEE80211_AC_VO);
skb->priority = 7;
/*
* The other path calling ieee80211_xmit is from the tasklet,
* and while we can handle concurrent transmissions locking
* requirements are that we do not come into tx with bhs on.
*/
local_bh_disable();
ieee80211_xmit(sdata, skb);
local_bh_enable();
}
| gpl-2.0 |
auras76/aur-kernel-XZxx | drivers/soc/qcom/scm-boot.c | 821 | 3056 | /* Copyright (c) 2010, 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <soc/qcom/scm.h>
#include <soc/qcom/scm-boot.h>
/*
* Set the cold/warm boot address for one of the CPU cores.
*/
int scm_set_boot_addr(phys_addr_t addr, unsigned int flags)
{
struct {
u32 flags;
u32 addr;
} cmd;
cmd.addr = addr;
cmd.flags = flags;
return scm_call(SCM_SVC_BOOT, SCM_BOOT_ADDR,
&cmd, sizeof(cmd), NULL, 0);
}
EXPORT_SYMBOL(scm_set_boot_addr);
/**
* scm_set_boot_addr_mc - Set entry physical address for cpus
* @addr: 32bit physical address
* @aff0: Collective bitmask of the affinity-level-0 of the mpidr
* 1<<aff0_CPU0| 1<<aff0_CPU1....... | 1<<aff0_CPU32
* Supports maximum 32 cpus under any affinity level.
* @aff1: Collective bitmask of the affinity-level-1 of the mpidr
* @aff2: Collective bitmask of the affinity-level-2 of the mpidr
* @flags: Flag to differentiate between coldboot vs warmboot
*/
int scm_set_boot_addr_mc(phys_addr_t addr, u32 aff0,
u32 aff1, u32 aff2, u32 flags)
{
struct {
u32 addr;
u32 aff0;
u32 aff1;
u32 aff2;
u32 reserved;
u32 flags;
} cmd;
struct scm_desc desc = {0};
if (!is_scm_armv8()) {
cmd.addr = addr;
cmd.aff0 = aff0;
cmd.aff1 = aff1;
cmd.aff2 = aff2;
/*
* Reserved for future chips with affinity level 3 effectively
* 1 << 0
*/
cmd.reserved = ~0U;
cmd.flags = flags | SCM_FLAG_HLOS;
return scm_call(SCM_SVC_BOOT, SCM_BOOT_ADDR_MC,
&cmd, sizeof(cmd), NULL, 0);
}
flags = flags | SCM_FLAG_HLOS;
desc.args[0] = addr;
desc.args[1] = aff0;
desc.args[2] = aff1;
desc.args[3] = aff2;
desc.args[4] = ~0ULL;
desc.args[5] = flags;
desc.arginfo = SCM_ARGS(6);
return scm_call2(SCM_SIP_FNID(SCM_SVC_BOOT, SCM_BOOT_ADDR_MC), &desc);
}
EXPORT_SYMBOL(scm_set_boot_addr_mc);
/**
* scm_set_warm_boot_addr_mc_for_all -
* Set entry physical address for __all__ possible cpus
* This API passes all_set mask to secure-os and relies
* on secure-os to appropriately
* set the boot-address on the current system.
* @addr: 32bit physical address
*/
int scm_set_warm_boot_addr_mc_for_all(phys_addr_t addr)
{
return scm_set_boot_addr_mc(addr, ~0U, ~0U, ~0U,
SCM_FLAG_WARMBOOT_MC);
}
EXPORT_SYMBOL(scm_set_warm_boot_addr_mc_for_all);
/**
* scm_is_mc_boot_available -
* Checks if TZ supports the boot API for multi-cluster configuration
* Returns true if available and false otherwise
*/
int scm_is_mc_boot_available(void)
{
return scm_is_call_available(SCM_SVC_BOOT, SCM_BOOT_ADDR_MC);
}
EXPORT_SYMBOL(scm_is_mc_boot_available);
| gpl-2.0 |
Shaky156/Shield-Tablet-CPU2.5Ghz-GPU060Mhz-Overclock | drivers/misc/uid_stat.c | 1077 | 3788 | /* drivers/misc/uid_stat.c
*
* Copyright (C) 2008 - 2009 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 <asm/atomic.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/stat.h>
#include <linux/uid_stat.h>
#include <net/activity_stats.h>
static DEFINE_SPINLOCK(uid_lock);
static LIST_HEAD(uid_list);
static struct proc_dir_entry *parent;
struct uid_stat {
struct list_head link;
uid_t uid;
atomic_t tcp_rcv;
atomic_t tcp_snd;
};
static struct uid_stat *find_uid_stat(uid_t uid) {
struct uid_stat *entry;
list_for_each_entry(entry, &uid_list, link) {
if (entry->uid == uid) {
return entry;
}
}
return NULL;
}
static int uid_stat_atomic_int_show(struct seq_file *m, void *v)
{
unsigned int bytes;
atomic_t *counter = m->private;
bytes = (unsigned int) (atomic_read(counter) + INT_MIN);
return seq_printf(m, "%u\n", bytes);
}
static int uid_stat_read_atomic_int_open(struct inode *inode, struct file *file)
{
return single_open(file, uid_stat_atomic_int_show, PDE_DATA(inode));
}
static const struct file_operations uid_stat_read_atomic_int_fops = {
.open = uid_stat_read_atomic_int_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/* Create a new entry for tracking the specified uid. */
static struct uid_stat *create_stat(uid_t uid) {
struct uid_stat *new_uid;
/* Create the uid stat struct and append it to the list. */
new_uid = kmalloc(sizeof(struct uid_stat), GFP_ATOMIC);
if (!new_uid)
return NULL;
new_uid->uid = uid;
/* Counters start at INT_MIN, so we can track 4GB of network traffic. */
atomic_set(&new_uid->tcp_rcv, INT_MIN);
atomic_set(&new_uid->tcp_snd, INT_MIN);
list_add_tail(&new_uid->link, &uid_list);
return new_uid;
}
static void create_stat_proc(struct uid_stat *new_uid)
{
char uid_s[32];
struct proc_dir_entry *entry;
sprintf(uid_s, "%d", new_uid->uid);
entry = proc_mkdir(uid_s, parent);
/* Keep reference to uid_stat so we know what uid to read stats from. */
proc_create_data("tcp_snd", S_IRUGO, entry,
&uid_stat_read_atomic_int_fops, &new_uid->tcp_snd);
proc_create_data("tcp_rcv", S_IRUGO, entry,
&uid_stat_read_atomic_int_fops, &new_uid->tcp_rcv);
}
static struct uid_stat *find_or_create_uid_stat(uid_t uid)
{
struct uid_stat *entry;
unsigned long flags;
spin_lock_irqsave(&uid_lock, flags);
entry = find_uid_stat(uid);
if (entry) {
spin_unlock_irqrestore(&uid_lock, flags);
return entry;
}
entry = create_stat(uid);
spin_unlock_irqrestore(&uid_lock, flags);
if (entry)
create_stat_proc(entry);
return entry;
}
int uid_stat_tcp_snd(uid_t uid, int size) {
struct uid_stat *entry;
activity_stats_update();
entry = find_or_create_uid_stat(uid);
if (!entry)
return -1;
atomic_add(size, &entry->tcp_snd);
return 0;
}
int uid_stat_tcp_rcv(uid_t uid, int size) {
struct uid_stat *entry;
activity_stats_update();
entry = find_or_create_uid_stat(uid);
if (!entry)
return -1;
atomic_add(size, &entry->tcp_rcv);
return 0;
}
static int __init uid_stat_init(void)
{
parent = proc_mkdir("uid_stat", NULL);
if (!parent) {
pr_err("uid_stat: failed to create proc entry\n");
return -1;
}
return 0;
}
__initcall(uid_stat_init);
| gpl-2.0 |
bigsupersquid/android_kernel_lge_msm7x27-3.0.x | drivers/vhost/vhost.c | 1333 | 38629 | /* Copyright (C) 2009 Red Hat, Inc.
* Copyright (C) 2006 Rusty Russell IBM Corporation
*
* Author: Michael S. Tsirkin <mst@redhat.com>
*
* Inspiration, some code, and most witty comments come from
* Documentation/virtual/lguest/lguest.c, by Rusty Russell
*
* This work is licensed under the terms of the GNU GPL, version 2.
*
* Generic code for virtio server in host kernel.
*/
#include <linux/eventfd.h>
#include <linux/vhost.h>
#include <linux/virtio_net.h>
#include <linux/mm.h>
#include <linux/mmu_context.h>
#include <linux/miscdevice.h>
#include <linux/mutex.h>
#include <linux/rcupdate.h>
#include <linux/poll.h>
#include <linux/file.h>
#include <linux/highmem.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/cgroup.h>
#include <linux/net.h>
#include <linux/if_packet.h>
#include <linux/if_arp.h>
#include "vhost.h"
enum {
VHOST_MEMORY_MAX_NREGIONS = 64,
VHOST_MEMORY_F_LOG = 0x1,
};
#define vhost_used_event(vq) ((u16 __user *)&vq->avail->ring[vq->num])
#define vhost_avail_event(vq) ((u16 __user *)&vq->used->ring[vq->num])
static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
poll_table *pt)
{
struct vhost_poll *poll;
poll = container_of(pt, struct vhost_poll, table);
poll->wqh = wqh;
add_wait_queue(wqh, &poll->wait);
}
static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
void *key)
{
struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
if (!((unsigned long)key & poll->mask))
return 0;
vhost_poll_queue(poll);
return 0;
}
static void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
{
INIT_LIST_HEAD(&work->node);
work->fn = fn;
init_waitqueue_head(&work->done);
work->flushing = 0;
work->queue_seq = work->done_seq = 0;
}
/* Init poll structure */
void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
unsigned long mask, struct vhost_dev *dev)
{
init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
init_poll_funcptr(&poll->table, vhost_poll_func);
poll->mask = mask;
poll->dev = dev;
vhost_work_init(&poll->work, fn);
}
/* Start polling a file. We add ourselves to file's wait queue. The caller must
* keep a reference to a file until after vhost_poll_stop is called. */
void vhost_poll_start(struct vhost_poll *poll, struct file *file)
{
unsigned long mask;
mask = file->f_op->poll(file, &poll->table);
if (mask)
vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
}
/* Stop polling a file. After this function returns, it becomes safe to drop the
* file reference. You must also flush afterwards. */
void vhost_poll_stop(struct vhost_poll *poll)
{
remove_wait_queue(poll->wqh, &poll->wait);
}
static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
unsigned seq)
{
int left;
spin_lock_irq(&dev->work_lock);
left = seq - work->done_seq;
spin_unlock_irq(&dev->work_lock);
return left <= 0;
}
static void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
{
unsigned seq;
int flushing;
spin_lock_irq(&dev->work_lock);
seq = work->queue_seq;
work->flushing++;
spin_unlock_irq(&dev->work_lock);
wait_event(work->done, vhost_work_seq_done(dev, work, seq));
spin_lock_irq(&dev->work_lock);
flushing = --work->flushing;
spin_unlock_irq(&dev->work_lock);
BUG_ON(flushing < 0);
}
/* Flush any work that has been scheduled. When calling this, don't hold any
* locks that are also used by the callback. */
void vhost_poll_flush(struct vhost_poll *poll)
{
vhost_work_flush(poll->dev, &poll->work);
}
static inline void vhost_work_queue(struct vhost_dev *dev,
struct vhost_work *work)
{
unsigned long flags;
spin_lock_irqsave(&dev->work_lock, flags);
if (list_empty(&work->node)) {
list_add_tail(&work->node, &dev->work_list);
work->queue_seq++;
wake_up_process(dev->worker);
}
spin_unlock_irqrestore(&dev->work_lock, flags);
}
void vhost_poll_queue(struct vhost_poll *poll)
{
vhost_work_queue(poll->dev, &poll->work);
}
static void vhost_vq_reset(struct vhost_dev *dev,
struct vhost_virtqueue *vq)
{
vq->num = 1;
vq->desc = NULL;
vq->avail = NULL;
vq->used = NULL;
vq->last_avail_idx = 0;
vq->avail_idx = 0;
vq->last_used_idx = 0;
vq->signalled_used = 0;
vq->signalled_used_valid = false;
vq->used_flags = 0;
vq->log_used = false;
vq->log_addr = -1ull;
vq->vhost_hlen = 0;
vq->sock_hlen = 0;
vq->private_data = NULL;
vq->log_base = NULL;
vq->error_ctx = NULL;
vq->error = NULL;
vq->kick = NULL;
vq->call_ctx = NULL;
vq->call = NULL;
vq->log_ctx = NULL;
}
static int vhost_worker(void *data)
{
struct vhost_dev *dev = data;
struct vhost_work *work = NULL;
unsigned uninitialized_var(seq);
use_mm(dev->mm);
for (;;) {
/* mb paired w/ kthread_stop */
set_current_state(TASK_INTERRUPTIBLE);
spin_lock_irq(&dev->work_lock);
if (work) {
work->done_seq = seq;
if (work->flushing)
wake_up_all(&work->done);
}
if (kthread_should_stop()) {
spin_unlock_irq(&dev->work_lock);
__set_current_state(TASK_RUNNING);
break;
}
if (!list_empty(&dev->work_list)) {
work = list_first_entry(&dev->work_list,
struct vhost_work, node);
list_del_init(&work->node);
seq = work->queue_seq;
} else
work = NULL;
spin_unlock_irq(&dev->work_lock);
if (work) {
__set_current_state(TASK_RUNNING);
work->fn(work);
} else
schedule();
}
unuse_mm(dev->mm);
return 0;
}
/* Helper to allocate iovec buffers for all vqs. */
static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
{
int i;
for (i = 0; i < dev->nvqs; ++i) {
dev->vqs[i].indirect = kmalloc(sizeof *dev->vqs[i].indirect *
UIO_MAXIOV, GFP_KERNEL);
dev->vqs[i].log = kmalloc(sizeof *dev->vqs[i].log * UIO_MAXIOV,
GFP_KERNEL);
dev->vqs[i].heads = kmalloc(sizeof *dev->vqs[i].heads *
UIO_MAXIOV, GFP_KERNEL);
if (!dev->vqs[i].indirect || !dev->vqs[i].log ||
!dev->vqs[i].heads)
goto err_nomem;
}
return 0;
err_nomem:
for (; i >= 0; --i) {
kfree(dev->vqs[i].indirect);
kfree(dev->vqs[i].log);
kfree(dev->vqs[i].heads);
}
return -ENOMEM;
}
static void vhost_dev_free_iovecs(struct vhost_dev *dev)
{
int i;
for (i = 0; i < dev->nvqs; ++i) {
kfree(dev->vqs[i].indirect);
dev->vqs[i].indirect = NULL;
kfree(dev->vqs[i].log);
dev->vqs[i].log = NULL;
kfree(dev->vqs[i].heads);
dev->vqs[i].heads = NULL;
}
}
long vhost_dev_init(struct vhost_dev *dev,
struct vhost_virtqueue *vqs, int nvqs)
{
int i;
dev->vqs = vqs;
dev->nvqs = nvqs;
mutex_init(&dev->mutex);
dev->log_ctx = NULL;
dev->log_file = NULL;
dev->memory = NULL;
dev->mm = NULL;
spin_lock_init(&dev->work_lock);
INIT_LIST_HEAD(&dev->work_list);
dev->worker = NULL;
for (i = 0; i < dev->nvqs; ++i) {
dev->vqs[i].log = NULL;
dev->vqs[i].indirect = NULL;
dev->vqs[i].heads = NULL;
dev->vqs[i].dev = dev;
mutex_init(&dev->vqs[i].mutex);
vhost_vq_reset(dev, dev->vqs + i);
if (dev->vqs[i].handle_kick)
vhost_poll_init(&dev->vqs[i].poll,
dev->vqs[i].handle_kick, POLLIN, dev);
}
return 0;
}
/* Caller should have device mutex */
long vhost_dev_check_owner(struct vhost_dev *dev)
{
/* Are you the owner? If not, I don't think you mean to do that */
return dev->mm == current->mm ? 0 : -EPERM;
}
struct vhost_attach_cgroups_struct {
struct vhost_work work;
struct task_struct *owner;
int ret;
};
static void vhost_attach_cgroups_work(struct vhost_work *work)
{
struct vhost_attach_cgroups_struct *s;
s = container_of(work, struct vhost_attach_cgroups_struct, work);
s->ret = cgroup_attach_task_all(s->owner, current);
}
static int vhost_attach_cgroups(struct vhost_dev *dev)
{
struct vhost_attach_cgroups_struct attach;
attach.owner = current;
vhost_work_init(&attach.work, vhost_attach_cgroups_work);
vhost_work_queue(dev, &attach.work);
vhost_work_flush(dev, &attach.work);
return attach.ret;
}
/* Caller should have device mutex */
static long vhost_dev_set_owner(struct vhost_dev *dev)
{
struct task_struct *worker;
int err;
/* Is there an owner already? */
if (dev->mm) {
err = -EBUSY;
goto err_mm;
}
/* No owner, become one */
dev->mm = get_task_mm(current);
worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
if (IS_ERR(worker)) {
err = PTR_ERR(worker);
goto err_worker;
}
dev->worker = worker;
wake_up_process(worker); /* avoid contributing to loadavg */
err = vhost_attach_cgroups(dev);
if (err)
goto err_cgroup;
err = vhost_dev_alloc_iovecs(dev);
if (err)
goto err_cgroup;
return 0;
err_cgroup:
kthread_stop(worker);
dev->worker = NULL;
err_worker:
if (dev->mm)
mmput(dev->mm);
dev->mm = NULL;
err_mm:
return err;
}
/* Caller should have device mutex */
long vhost_dev_reset_owner(struct vhost_dev *dev)
{
struct vhost_memory *memory;
/* Restore memory to default empty mapping. */
memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
if (!memory)
return -ENOMEM;
vhost_dev_cleanup(dev);
memory->nregions = 0;
RCU_INIT_POINTER(dev->memory, memory);
return 0;
}
/* Caller should have device mutex */
void vhost_dev_cleanup(struct vhost_dev *dev)
{
int i;
for (i = 0; i < dev->nvqs; ++i) {
if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
vhost_poll_stop(&dev->vqs[i].poll);
vhost_poll_flush(&dev->vqs[i].poll);
}
if (dev->vqs[i].error_ctx)
eventfd_ctx_put(dev->vqs[i].error_ctx);
if (dev->vqs[i].error)
fput(dev->vqs[i].error);
if (dev->vqs[i].kick)
fput(dev->vqs[i].kick);
if (dev->vqs[i].call_ctx)
eventfd_ctx_put(dev->vqs[i].call_ctx);
if (dev->vqs[i].call)
fput(dev->vqs[i].call);
vhost_vq_reset(dev, dev->vqs + i);
}
vhost_dev_free_iovecs(dev);
if (dev->log_ctx)
eventfd_ctx_put(dev->log_ctx);
dev->log_ctx = NULL;
if (dev->log_file)
fput(dev->log_file);
dev->log_file = NULL;
/* No one will access memory at this point */
kfree(rcu_dereference_protected(dev->memory,
lockdep_is_held(&dev->mutex)));
RCU_INIT_POINTER(dev->memory, NULL);
WARN_ON(!list_empty(&dev->work_list));
if (dev->worker) {
kthread_stop(dev->worker);
dev->worker = NULL;
}
if (dev->mm)
mmput(dev->mm);
dev->mm = NULL;
}
static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
{
u64 a = addr / VHOST_PAGE_SIZE / 8;
/* Make sure 64 bit math will not overflow. */
if (a > ULONG_MAX - (unsigned long)log_base ||
a + (unsigned long)log_base > ULONG_MAX)
return 0;
return access_ok(VERIFY_WRITE, log_base + a,
(sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
}
/* Caller should have vq mutex and device mutex. */
static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
int log_all)
{
int i;
if (!mem)
return 0;
for (i = 0; i < mem->nregions; ++i) {
struct vhost_memory_region *m = mem->regions + i;
unsigned long a = m->userspace_addr;
if (m->memory_size > ULONG_MAX)
return 0;
else if (!access_ok(VERIFY_WRITE, (void __user *)a,
m->memory_size))
return 0;
else if (log_all && !log_access_ok(log_base,
m->guest_phys_addr,
m->memory_size))
return 0;
}
return 1;
}
/* Can we switch to this memory table? */
/* Caller should have device mutex but not vq mutex */
static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
int log_all)
{
int i;
for (i = 0; i < d->nvqs; ++i) {
int ok;
mutex_lock(&d->vqs[i].mutex);
/* If ring is inactive, will check when it's enabled. */
if (d->vqs[i].private_data)
ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
log_all);
else
ok = 1;
mutex_unlock(&d->vqs[i].mutex);
if (!ok)
return 0;
}
return 1;
}
static int vq_access_ok(struct vhost_dev *d, unsigned int num,
struct vring_desc __user *desc,
struct vring_avail __user *avail,
struct vring_used __user *used)
{
size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
access_ok(VERIFY_READ, avail,
sizeof *avail + num * sizeof *avail->ring + s) &&
access_ok(VERIFY_WRITE, used,
sizeof *used + num * sizeof *used->ring + s);
}
/* Can we log writes? */
/* Caller should have device mutex but not vq mutex */
int vhost_log_access_ok(struct vhost_dev *dev)
{
struct vhost_memory *mp;
mp = rcu_dereference_protected(dev->memory,
lockdep_is_held(&dev->mutex));
return memory_access_ok(dev, mp, 1);
}
/* Verify access for write logging. */
/* Caller should have vq mutex and device mutex */
static int vq_log_access_ok(struct vhost_dev *d, struct vhost_virtqueue *vq,
void __user *log_base)
{
struct vhost_memory *mp;
size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
mp = rcu_dereference_protected(vq->dev->memory,
lockdep_is_held(&vq->mutex));
return vq_memory_access_ok(log_base, mp,
vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
(!vq->log_used || log_access_ok(log_base, vq->log_addr,
sizeof *vq->used +
vq->num * sizeof *vq->used->ring + s));
}
/* Can we start vq? */
/* Caller should have vq mutex and device mutex */
int vhost_vq_access_ok(struct vhost_virtqueue *vq)
{
return vq_access_ok(vq->dev, vq->num, vq->desc, vq->avail, vq->used) &&
vq_log_access_ok(vq->dev, vq, vq->log_base);
}
static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
{
struct vhost_memory mem, *newmem, *oldmem;
unsigned long size = offsetof(struct vhost_memory, regions);
if (copy_from_user(&mem, m, size))
return -EFAULT;
if (mem.padding)
return -EOPNOTSUPP;
if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
return -E2BIG;
newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
if (!newmem)
return -ENOMEM;
memcpy(newmem, &mem, size);
if (copy_from_user(newmem->regions, m->regions,
mem.nregions * sizeof *m->regions)) {
kfree(newmem);
return -EFAULT;
}
if (!memory_access_ok(d, newmem,
vhost_has_feature(d, VHOST_F_LOG_ALL))) {
kfree(newmem);
return -EFAULT;
}
oldmem = rcu_dereference_protected(d->memory,
lockdep_is_held(&d->mutex));
rcu_assign_pointer(d->memory, newmem);
synchronize_rcu();
kfree(oldmem);
return 0;
}
static int init_used(struct vhost_virtqueue *vq,
struct vring_used __user *used)
{
int r = put_user(vq->used_flags, &used->flags);
if (r)
return r;
vq->signalled_used_valid = false;
return get_user(vq->last_used_idx, &used->idx);
}
static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
{
struct file *eventfp, *filep = NULL,
*pollstart = NULL, *pollstop = NULL;
struct eventfd_ctx *ctx = NULL;
u32 __user *idxp = argp;
struct vhost_virtqueue *vq;
struct vhost_vring_state s;
struct vhost_vring_file f;
struct vhost_vring_addr a;
u32 idx;
long r;
r = get_user(idx, idxp);
if (r < 0)
return r;
if (idx >= d->nvqs)
return -ENOBUFS;
vq = d->vqs + idx;
mutex_lock(&vq->mutex);
switch (ioctl) {
case VHOST_SET_VRING_NUM:
/* Resizing ring with an active backend?
* You don't want to do that. */
if (vq->private_data) {
r = -EBUSY;
break;
}
if (copy_from_user(&s, argp, sizeof s)) {
r = -EFAULT;
break;
}
if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
r = -EINVAL;
break;
}
vq->num = s.num;
break;
case VHOST_SET_VRING_BASE:
/* Moving base with an active backend?
* You don't want to do that. */
if (vq->private_data) {
r = -EBUSY;
break;
}
if (copy_from_user(&s, argp, sizeof s)) {
r = -EFAULT;
break;
}
if (s.num > 0xffff) {
r = -EINVAL;
break;
}
vq->last_avail_idx = s.num;
/* Forget the cached index value. */
vq->avail_idx = vq->last_avail_idx;
break;
case VHOST_GET_VRING_BASE:
s.index = idx;
s.num = vq->last_avail_idx;
if (copy_to_user(argp, &s, sizeof s))
r = -EFAULT;
break;
case VHOST_SET_VRING_ADDR:
if (copy_from_user(&a, argp, sizeof a)) {
r = -EFAULT;
break;
}
if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
r = -EOPNOTSUPP;
break;
}
/* For 32bit, verify that the top 32bits of the user
data are set to zero. */
if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
(u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
(u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
r = -EFAULT;
break;
}
if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
(a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
(a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
r = -EINVAL;
break;
}
/* We only verify access here if backend is configured.
* If it is not, we don't as size might not have been setup.
* We will verify when backend is configured. */
if (vq->private_data) {
if (!vq_access_ok(d, vq->num,
(void __user *)(unsigned long)a.desc_user_addr,
(void __user *)(unsigned long)a.avail_user_addr,
(void __user *)(unsigned long)a.used_user_addr)) {
r = -EINVAL;
break;
}
/* Also validate log access for used ring if enabled. */
if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
!log_access_ok(vq->log_base, a.log_guest_addr,
sizeof *vq->used +
vq->num * sizeof *vq->used->ring)) {
r = -EINVAL;
break;
}
}
r = init_used(vq, (struct vring_used __user *)(unsigned long)
a.used_user_addr);
if (r)
break;
vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
vq->log_addr = a.log_guest_addr;
vq->used = (void __user *)(unsigned long)a.used_user_addr;
break;
case VHOST_SET_VRING_KICK:
if (copy_from_user(&f, argp, sizeof f)) {
r = -EFAULT;
break;
}
eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != vq->kick) {
pollstop = filep = vq->kick;
pollstart = vq->kick = eventfp;
} else
filep = eventfp;
break;
case VHOST_SET_VRING_CALL:
if (copy_from_user(&f, argp, sizeof f)) {
r = -EFAULT;
break;
}
eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != vq->call) {
filep = vq->call;
ctx = vq->call_ctx;
vq->call = eventfp;
vq->call_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
break;
case VHOST_SET_VRING_ERR:
if (copy_from_user(&f, argp, sizeof f)) {
r = -EFAULT;
break;
}
eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != vq->error) {
filep = vq->error;
vq->error = eventfp;
ctx = vq->error_ctx;
vq->error_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
break;
default:
r = -ENOIOCTLCMD;
}
if (pollstop && vq->handle_kick)
vhost_poll_stop(&vq->poll);
if (ctx)
eventfd_ctx_put(ctx);
if (filep)
fput(filep);
if (pollstart && vq->handle_kick)
vhost_poll_start(&vq->poll, vq->kick);
mutex_unlock(&vq->mutex);
if (pollstop && vq->handle_kick)
vhost_poll_flush(&vq->poll);
return r;
}
/* Caller must have device mutex */
long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
{
void __user *argp = (void __user *)arg;
struct file *eventfp, *filep = NULL;
struct eventfd_ctx *ctx = NULL;
u64 p;
long r;
int i, fd;
/* If you are not the owner, you can become one */
if (ioctl == VHOST_SET_OWNER) {
r = vhost_dev_set_owner(d);
goto done;
}
/* You must be the owner to do anything else */
r = vhost_dev_check_owner(d);
if (r)
goto done;
switch (ioctl) {
case VHOST_SET_MEM_TABLE:
r = vhost_set_memory(d, argp);
break;
case VHOST_SET_LOG_BASE:
if (copy_from_user(&p, argp, sizeof p)) {
r = -EFAULT;
break;
}
if ((u64)(unsigned long)p != p) {
r = -EFAULT;
break;
}
for (i = 0; i < d->nvqs; ++i) {
struct vhost_virtqueue *vq;
void __user *base = (void __user *)(unsigned long)p;
vq = d->vqs + i;
mutex_lock(&vq->mutex);
/* If ring is inactive, will check when it's enabled. */
if (vq->private_data && !vq_log_access_ok(d, vq, base))
r = -EFAULT;
else
vq->log_base = base;
mutex_unlock(&vq->mutex);
}
break;
case VHOST_SET_LOG_FD:
r = get_user(fd, (int __user *)argp);
if (r < 0)
break;
eventfp = fd == -1 ? NULL : eventfd_fget(fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != d->log_file) {
filep = d->log_file;
ctx = d->log_ctx;
d->log_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
for (i = 0; i < d->nvqs; ++i) {
mutex_lock(&d->vqs[i].mutex);
d->vqs[i].log_ctx = d->log_ctx;
mutex_unlock(&d->vqs[i].mutex);
}
if (ctx)
eventfd_ctx_put(ctx);
if (filep)
fput(filep);
break;
default:
r = vhost_set_vring(d, ioctl, argp);
break;
}
done:
return r;
}
static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
__u64 addr, __u32 len)
{
struct vhost_memory_region *reg;
int i;
/* linear search is not brilliant, but we really have on the order of 6
* regions in practice */
for (i = 0; i < mem->nregions; ++i) {
reg = mem->regions + i;
if (reg->guest_phys_addr <= addr &&
reg->guest_phys_addr + reg->memory_size - 1 >= addr)
return reg;
}
return NULL;
}
/* TODO: This is really inefficient. We need something like get_user()
* (instruction directly accesses the data, with an exception table entry
* returning -EFAULT). See Documentation/x86/exception-tables.txt.
*/
static int set_bit_to_user(int nr, void __user *addr)
{
unsigned long log = (unsigned long)addr;
struct page *page;
void *base;
int bit = nr + (log % PAGE_SIZE) * 8;
int r;
r = get_user_pages_fast(log, 1, 1, &page);
if (r < 0)
return r;
BUG_ON(r != 1);
base = kmap_atomic(page, KM_USER0);
set_bit(bit, base);
kunmap_atomic(base, KM_USER0);
set_page_dirty_lock(page);
put_page(page);
return 0;
}
static int log_write(void __user *log_base,
u64 write_address, u64 write_length)
{
u64 write_page = write_address / VHOST_PAGE_SIZE;
int r;
if (!write_length)
return 0;
write_length += write_address % VHOST_PAGE_SIZE;
for (;;) {
u64 base = (u64)(unsigned long)log_base;
u64 log = base + write_page / 8;
int bit = write_page % 8;
if ((u64)(unsigned long)log != log)
return -EFAULT;
r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
if (r < 0)
return r;
if (write_length <= VHOST_PAGE_SIZE)
break;
write_length -= VHOST_PAGE_SIZE;
write_page += 1;
}
return r;
}
int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
unsigned int log_num, u64 len)
{
int i, r;
/* Make sure data written is seen before log. */
smp_wmb();
for (i = 0; i < log_num; ++i) {
u64 l = min(log[i].len, len);
r = log_write(vq->log_base, log[i].addr, l);
if (r < 0)
return r;
len -= l;
if (!len) {
if (vq->log_ctx)
eventfd_signal(vq->log_ctx, 1);
return 0;
}
}
/* Length written exceeds what we have stored. This is a bug. */
BUG();
return 0;
}
static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
struct iovec iov[], int iov_size)
{
const struct vhost_memory_region *reg;
struct vhost_memory *mem;
struct iovec *_iov;
u64 s = 0;
int ret = 0;
rcu_read_lock();
mem = rcu_dereference(dev->memory);
while ((u64)len > s) {
u64 size;
if (unlikely(ret >= iov_size)) {
ret = -ENOBUFS;
break;
}
reg = find_region(mem, addr, len);
if (unlikely(!reg)) {
ret = -EFAULT;
break;
}
_iov = iov + ret;
size = reg->memory_size - addr + reg->guest_phys_addr;
_iov->iov_len = min((u64)len, size);
_iov->iov_base = (void __user *)(unsigned long)
(reg->userspace_addr + addr - reg->guest_phys_addr);
s += size;
addr += size;
++ret;
}
rcu_read_unlock();
return ret;
}
/* Each buffer in the virtqueues is actually a chain of descriptors. This
* function returns the next descriptor in the chain,
* or -1U if we're at the end. */
static unsigned next_desc(struct vring_desc *desc)
{
unsigned int next;
/* If this descriptor says it doesn't chain, we're done. */
if (!(desc->flags & VRING_DESC_F_NEXT))
return -1U;
/* Check they're not leading us off end of descriptors. */
next = desc->next;
/* Make sure compiler knows to grab that: we don't want it changing! */
/* We will use the result as an index in an array, so most
* architectures only need a compiler barrier here. */
read_barrier_depends();
return next;
}
static int get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
struct iovec iov[], unsigned int iov_size,
unsigned int *out_num, unsigned int *in_num,
struct vhost_log *log, unsigned int *log_num,
struct vring_desc *indirect)
{
struct vring_desc desc;
unsigned int i = 0, count, found = 0;
int ret;
/* Sanity check */
if (unlikely(indirect->len % sizeof desc)) {
vq_err(vq, "Invalid length in indirect descriptor: "
"len 0x%llx not multiple of 0x%zx\n",
(unsigned long long)indirect->len,
sizeof desc);
return -EINVAL;
}
ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
UIO_MAXIOV);
if (unlikely(ret < 0)) {
vq_err(vq, "Translation failure %d in indirect.\n", ret);
return ret;
}
/* We will use the result as an address to read from, so most
* architectures only need a compiler barrier here. */
read_barrier_depends();
count = indirect->len / sizeof desc;
/* Buffers are chained via a 16 bit next field, so
* we can have at most 2^16 of these. */
if (unlikely(count > USHRT_MAX + 1)) {
vq_err(vq, "Indirect buffer length too big: %d\n",
indirect->len);
return -E2BIG;
}
do {
unsigned iov_count = *in_num + *out_num;
if (unlikely(++found > count)) {
vq_err(vq, "Loop detected: last one at %u "
"indirect size %u\n",
i, count);
return -EINVAL;
}
if (unlikely(memcpy_fromiovec((unsigned char *)&desc,
vq->indirect, sizeof desc))) {
vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
i, (size_t)indirect->addr + i * sizeof desc);
return -EINVAL;
}
if (unlikely(desc.flags & VRING_DESC_F_INDIRECT)) {
vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
i, (size_t)indirect->addr + i * sizeof desc);
return -EINVAL;
}
ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
iov_size - iov_count);
if (unlikely(ret < 0)) {
vq_err(vq, "Translation failure %d indirect idx %d\n",
ret, i);
return ret;
}
/* If this is an input descriptor, increment that count. */
if (desc.flags & VRING_DESC_F_WRITE) {
*in_num += ret;
if (unlikely(log)) {
log[*log_num].addr = desc.addr;
log[*log_num].len = desc.len;
++*log_num;
}
} else {
/* If it's an output descriptor, they're all supposed
* to come before any input descriptors. */
if (unlikely(*in_num)) {
vq_err(vq, "Indirect descriptor "
"has out after in: idx %d\n", i);
return -EINVAL;
}
*out_num += ret;
}
} while ((i = next_desc(&desc)) != -1);
return 0;
}
/* This looks in the virtqueue and for the first available buffer, and converts
* it to an iovec for convenient access. Since descriptors consist of some
* number of output then some number of input descriptors, it's actually two
* iovecs, but we pack them into one and note how many of each there were.
*
* This function returns the descriptor number found, or vq->num (which is
* never a valid descriptor number) if none was found. A negative code is
* returned on error. */
int vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
struct iovec iov[], unsigned int iov_size,
unsigned int *out_num, unsigned int *in_num,
struct vhost_log *log, unsigned int *log_num)
{
struct vring_desc desc;
unsigned int i, head, found = 0;
u16 last_avail_idx;
int ret;
/* Check it isn't doing very strange things with descriptor numbers. */
last_avail_idx = vq->last_avail_idx;
if (unlikely(__get_user(vq->avail_idx, &vq->avail->idx))) {
vq_err(vq, "Failed to access avail idx at %p\n",
&vq->avail->idx);
return -EFAULT;
}
if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
vq_err(vq, "Guest moved used index from %u to %u",
last_avail_idx, vq->avail_idx);
return -EFAULT;
}
/* If there's nothing new since last we looked, return invalid. */
if (vq->avail_idx == last_avail_idx)
return vq->num;
/* Only get avail ring entries after they have been exposed by guest. */
smp_rmb();
/* Grab the next descriptor number they're advertising, and increment
* the index we've seen. */
if (unlikely(__get_user(head,
&vq->avail->ring[last_avail_idx % vq->num]))) {
vq_err(vq, "Failed to read head: idx %d address %p\n",
last_avail_idx,
&vq->avail->ring[last_avail_idx % vq->num]);
return -EFAULT;
}
/* If their number is silly, that's an error. */
if (unlikely(head >= vq->num)) {
vq_err(vq, "Guest says index %u > %u is available",
head, vq->num);
return -EINVAL;
}
/* When we start there are none of either input nor output. */
*out_num = *in_num = 0;
if (unlikely(log))
*log_num = 0;
i = head;
do {
unsigned iov_count = *in_num + *out_num;
if (unlikely(i >= vq->num)) {
vq_err(vq, "Desc index is %u > %u, head = %u",
i, vq->num, head);
return -EINVAL;
}
if (unlikely(++found > vq->num)) {
vq_err(vq, "Loop detected: last one at %u "
"vq size %u head %u\n",
i, vq->num, head);
return -EINVAL;
}
ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
if (unlikely(ret)) {
vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
i, vq->desc + i);
return -EFAULT;
}
if (desc.flags & VRING_DESC_F_INDIRECT) {
ret = get_indirect(dev, vq, iov, iov_size,
out_num, in_num,
log, log_num, &desc);
if (unlikely(ret < 0)) {
vq_err(vq, "Failure detected "
"in indirect descriptor at idx %d\n", i);
return ret;
}
continue;
}
ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
iov_size - iov_count);
if (unlikely(ret < 0)) {
vq_err(vq, "Translation failure %d descriptor idx %d\n",
ret, i);
return ret;
}
if (desc.flags & VRING_DESC_F_WRITE) {
/* If this is an input descriptor,
* increment that count. */
*in_num += ret;
if (unlikely(log)) {
log[*log_num].addr = desc.addr;
log[*log_num].len = desc.len;
++*log_num;
}
} else {
/* If it's an output descriptor, they're all supposed
* to come before any input descriptors. */
if (unlikely(*in_num)) {
vq_err(vq, "Descriptor has out after in: "
"idx %d\n", i);
return -EINVAL;
}
*out_num += ret;
}
} while ((i = next_desc(&desc)) != -1);
/* On success, increment avail index. */
vq->last_avail_idx++;
/* Assume notifications from guest are disabled at this point,
* if they aren't we would need to update avail_event index. */
BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
return head;
}
/* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
{
vq->last_avail_idx -= n;
}
/* After we've used one of their buffers, we tell them about it. We'll then
* want to notify the guest, using eventfd. */
int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
{
struct vring_used_elem __user *used;
/* The virtqueue contains a ring of used buffers. Get a pointer to the
* next entry in that used ring. */
used = &vq->used->ring[vq->last_used_idx % vq->num];
if (__put_user(head, &used->id)) {
vq_err(vq, "Failed to write used id");
return -EFAULT;
}
if (__put_user(len, &used->len)) {
vq_err(vq, "Failed to write used len");
return -EFAULT;
}
/* Make sure buffer is written before we update index. */
smp_wmb();
if (__put_user(vq->last_used_idx + 1, &vq->used->idx)) {
vq_err(vq, "Failed to increment used idx");
return -EFAULT;
}
if (unlikely(vq->log_used)) {
/* Make sure data is seen before log. */
smp_wmb();
/* Log used ring entry write. */
log_write(vq->log_base,
vq->log_addr +
((void __user *)used - (void __user *)vq->used),
sizeof *used);
/* Log used index update. */
log_write(vq->log_base,
vq->log_addr + offsetof(struct vring_used, idx),
sizeof vq->used->idx);
if (vq->log_ctx)
eventfd_signal(vq->log_ctx, 1);
}
vq->last_used_idx++;
/* If the driver never bothers to signal in a very long while,
* used index might wrap around. If that happens, invalidate
* signalled_used index we stored. TODO: make sure driver
* signals at least once in 2^16 and remove this. */
if (unlikely(vq->last_used_idx == vq->signalled_used))
vq->signalled_used_valid = false;
return 0;
}
static int __vhost_add_used_n(struct vhost_virtqueue *vq,
struct vring_used_elem *heads,
unsigned count)
{
struct vring_used_elem __user *used;
u16 old, new;
int start;
start = vq->last_used_idx % vq->num;
used = vq->used->ring + start;
if (__copy_to_user(used, heads, count * sizeof *used)) {
vq_err(vq, "Failed to write used");
return -EFAULT;
}
if (unlikely(vq->log_used)) {
/* Make sure data is seen before log. */
smp_wmb();
/* Log used ring entry write. */
log_write(vq->log_base,
vq->log_addr +
((void __user *)used - (void __user *)vq->used),
count * sizeof *used);
}
old = vq->last_used_idx;
new = (vq->last_used_idx += count);
/* If the driver never bothers to signal in a very long while,
* used index might wrap around. If that happens, invalidate
* signalled_used index we stored. TODO: make sure driver
* signals at least once in 2^16 and remove this. */
if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
vq->signalled_used_valid = false;
return 0;
}
/* After we've used one of their buffers, we tell them about it. We'll then
* want to notify the guest, using eventfd. */
int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
unsigned count)
{
int start, n, r;
start = vq->last_used_idx % vq->num;
n = vq->num - start;
if (n < count) {
r = __vhost_add_used_n(vq, heads, n);
if (r < 0)
return r;
heads += n;
count -= n;
}
r = __vhost_add_used_n(vq, heads, count);
/* Make sure buffer is written before we update index. */
smp_wmb();
if (put_user(vq->last_used_idx, &vq->used->idx)) {
vq_err(vq, "Failed to increment used idx");
return -EFAULT;
}
if (unlikely(vq->log_used)) {
/* Log used index update. */
log_write(vq->log_base,
vq->log_addr + offsetof(struct vring_used, idx),
sizeof vq->used->idx);
if (vq->log_ctx)
eventfd_signal(vq->log_ctx, 1);
}
return r;
}
static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
{
__u16 old, new, event;
bool v;
/* Flush out used index updates. This is paired
* with the barrier that the Guest executes when enabling
* interrupts. */
smp_mb();
if (vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
unlikely(vq->avail_idx == vq->last_avail_idx))
return true;
if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
__u16 flags;
if (__get_user(flags, &vq->avail->flags)) {
vq_err(vq, "Failed to get flags");
return true;
}
return !(flags & VRING_AVAIL_F_NO_INTERRUPT);
}
old = vq->signalled_used;
v = vq->signalled_used_valid;
new = vq->signalled_used = vq->last_used_idx;
vq->signalled_used_valid = true;
if (unlikely(!v))
return true;
if (get_user(event, vhost_used_event(vq))) {
vq_err(vq, "Failed to get used event idx");
return true;
}
return vring_need_event(event, new, old);
}
/* This actually signals the guest, using eventfd. */
void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
{
/* Signal the Guest tell them we used something up. */
if (vq->call_ctx && vhost_notify(dev, vq))
eventfd_signal(vq->call_ctx, 1);
}
/* And here's the combo meal deal. Supersize me! */
void vhost_add_used_and_signal(struct vhost_dev *dev,
struct vhost_virtqueue *vq,
unsigned int head, int len)
{
vhost_add_used(vq, head, len);
vhost_signal(dev, vq);
}
/* multi-buffer version of vhost_add_used_and_signal */
void vhost_add_used_and_signal_n(struct vhost_dev *dev,
struct vhost_virtqueue *vq,
struct vring_used_elem *heads, unsigned count)
{
vhost_add_used_n(vq, heads, count);
vhost_signal(dev, vq);
}
/* OK, now we need to know about added descriptors. */
bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
{
u16 avail_idx;
int r;
if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
return false;
vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
r = put_user(vq->used_flags, &vq->used->flags);
if (r) {
vq_err(vq, "Failed to enable notification at %p: %d\n",
&vq->used->flags, r);
return false;
}
} else {
r = put_user(vq->avail_idx, vhost_avail_event(vq));
if (r) {
vq_err(vq, "Failed to update avail event index at %p: %d\n",
vhost_avail_event(vq), r);
return false;
}
}
if (unlikely(vq->log_used)) {
void __user *used;
/* Make sure data is seen before log. */
smp_wmb();
used = vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX) ?
&vq->used->flags : vhost_avail_event(vq);
/* Log used flags or event index entry write. Both are 16 bit
* fields. */
log_write(vq->log_base, vq->log_addr +
(used - (void __user *)vq->used),
sizeof(u16));
if (vq->log_ctx)
eventfd_signal(vq->log_ctx, 1);
}
/* They could have slipped one in as we were doing that: make
* sure it's written, then check again. */
smp_mb();
r = __get_user(avail_idx, &vq->avail->idx);
if (r) {
vq_err(vq, "Failed to check avail idx at %p: %d\n",
&vq->avail->idx, r);
return false;
}
return avail_idx != vq->avail_idx;
}
/* We don't need to be notified again. */
void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
{
int r;
if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
return;
vq->used_flags |= VRING_USED_F_NO_NOTIFY;
if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
r = put_user(vq->used_flags, &vq->used->flags);
if (r)
vq_err(vq, "Failed to enable notification at %p: %d\n",
&vq->used->flags, r);
}
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.