repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
ipodtouchdude/linux-amlogic | arch/arm/mach-omap2/omap-pm-noop.c | 3281 | 9174 | /*
* omap-pm-noop.c - OMAP power management interface - dummy version
*
* This code implements the OMAP power management interface to
* drivers, CPUIdle, CPUFreq, and DSP Bridge. It is strictly for
* debug/demonstration use, as it does nothing but printk() whenever a
* function is called (when DEBUG is defined, below)
*
* Copyright (C) 2008-2009 Texas Instruments, Inc.
* Copyright (C) 2008-2009 Nokia Corporation
* Paul Walmsley
*
* Interface developed by (in alphabetical order):
* Karthik Dasu, Tony Lindgren, Rajendra Nayak, Sakari Poussa, Veeramanikandan
* Raju, Anand Sawant, Igor Stoppa, Paul Walmsley, Richard Woodruff
*/
#undef DEBUG
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include "omap_device.h"
#include "omap-pm.h"
static bool off_mode_enabled;
static int dummy_context_loss_counter;
/*
* Device-driver-originated constraints (via board-*.c files)
*/
int omap_pm_set_max_mpu_wakeup_lat(struct device *dev, long t)
{
if (!dev || t < -1) {
WARN(1, "OMAP PM: %s: invalid parameter(s)", __func__);
return -EINVAL;
}
if (t == -1)
pr_debug("OMAP PM: remove max MPU wakeup latency constraint: dev %s\n",
dev_name(dev));
else
pr_debug("OMAP PM: add max MPU wakeup latency constraint: dev %s, t = %ld usec\n",
dev_name(dev), t);
/*
* For current Linux, this needs to map the MPU to a
* powerdomain, then go through the list of current max lat
* constraints on the MPU and find the smallest. If
* the latency constraint has changed, the code should
* recompute the state to enter for the next powerdomain
* state.
*
* TI CDP code can call constraint_set here.
*/
return 0;
}
int omap_pm_set_min_bus_tput(struct device *dev, u8 agent_id, unsigned long r)
{
if (!dev || (agent_id != OCP_INITIATOR_AGENT &&
agent_id != OCP_TARGET_AGENT)) {
WARN(1, "OMAP PM: %s: invalid parameter(s)", __func__);
return -EINVAL;
}
if (r == 0)
pr_debug("OMAP PM: remove min bus tput constraint: dev %s for agent_id %d\n",
dev_name(dev), agent_id);
else
pr_debug("OMAP PM: add min bus tput constraint: dev %s for agent_id %d: rate %ld KiB\n",
dev_name(dev), agent_id, r);
/*
* This code should model the interconnect and compute the
* required clock frequency, convert that to a VDD2 OPP ID, then
* set the VDD2 OPP appropriately.
*
* TI CDP code can call constraint_set here on the VDD2 OPP.
*/
return 0;
}
int omap_pm_set_max_dev_wakeup_lat(struct device *req_dev, struct device *dev,
long t)
{
if (!req_dev || !dev || t < -1) {
WARN(1, "OMAP PM: %s: invalid parameter(s)", __func__);
return -EINVAL;
}
if (t == -1)
pr_debug("OMAP PM: remove max device latency constraint: dev %s\n",
dev_name(dev));
else
pr_debug("OMAP PM: add max device latency constraint: dev %s, t = %ld usec\n",
dev_name(dev), t);
/*
* For current Linux, this needs to map the device to a
* powerdomain, then go through the list of current max lat
* constraints on that powerdomain and find the smallest. If
* the latency constraint has changed, the code should
* recompute the state to enter for the next powerdomain
* state. Conceivably, this code should also determine
* whether to actually disable the device clocks or not,
* depending on how long it takes to re-enable the clocks.
*
* TI CDP code can call constraint_set here.
*/
return 0;
}
int omap_pm_set_max_sdma_lat(struct device *dev, long t)
{
if (!dev || t < -1) {
WARN(1, "OMAP PM: %s: invalid parameter(s)", __func__);
return -EINVAL;
}
if (t == -1)
pr_debug("OMAP PM: remove max DMA latency constraint: dev %s\n",
dev_name(dev));
else
pr_debug("OMAP PM: add max DMA latency constraint: dev %s, t = %ld usec\n",
dev_name(dev), t);
/*
* For current Linux PM QOS params, this code should scan the
* list of maximum CPU and DMA latencies and select the
* smallest, then set cpu_dma_latency pm_qos_param
* accordingly.
*
* For future Linux PM QOS params, with separate CPU and DMA
* latency params, this code should just set the dma_latency param.
*
* TI CDP code can call constraint_set here.
*/
return 0;
}
int omap_pm_set_min_clk_rate(struct device *dev, struct clk *c, long r)
{
if (!dev || !c || r < 0) {
WARN(1, "OMAP PM: %s: invalid parameter(s)", __func__);
return -EINVAL;
}
if (r == 0)
pr_debug("OMAP PM: remove min clk rate constraint: dev %s\n",
dev_name(dev));
else
pr_debug("OMAP PM: add min clk rate constraint: dev %s, rate = %ld Hz\n",
dev_name(dev), r);
/*
* Code in a real implementation should keep track of these
* constraints on the clock, and determine the highest minimum
* clock rate. It should iterate over each OPP and determine
* whether the OPP will result in a clock rate that would
* satisfy this constraint (and any other PM constraint in effect
* at that time). Once it finds the lowest-voltage OPP that
* meets those conditions, it should switch to it, or return
* an error if the code is not capable of doing so.
*/
return 0;
}
/*
* DSP Bridge-specific constraints
*/
const struct omap_opp *omap_pm_dsp_get_opp_table(void)
{
pr_debug("OMAP PM: DSP request for OPP table\n");
/*
* Return DSP frequency table here: The final item in the
* array should have .rate = .opp_id = 0.
*/
return NULL;
}
void omap_pm_dsp_set_min_opp(u8 opp_id)
{
if (opp_id == 0) {
WARN_ON(1);
return;
}
pr_debug("OMAP PM: DSP requests minimum VDD1 OPP to be %d\n", opp_id);
/*
*
* For l-o dev tree, our VDD1 clk is keyed on OPP ID, so we
* can just test to see which is higher, the CPU's desired OPP
* ID or the DSP's desired OPP ID, and use whichever is
* highest.
*
* In CDP12.14+, the VDD1 OPP custom clock that controls the DSP
* rate is keyed on MPU speed, not the OPP ID. So we need to
* map the OPP ID to the MPU speed for use with clk_set_rate()
* if it is higher than the current OPP clock rate.
*
*/
}
u8 omap_pm_dsp_get_opp(void)
{
pr_debug("OMAP PM: DSP requests current DSP OPP ID\n");
/*
* For l-o dev tree, call clk_get_rate() on VDD1 OPP clock
*
* CDP12.14+:
* Call clk_get_rate() on the OPP custom clock, map that to an
* OPP ID using the tables defined in board-*.c/chip-*.c files.
*/
return 0;
}
/*
* CPUFreq-originated constraint
*
* In the future, this should be handled by custom OPP clocktype
* functions.
*/
struct cpufreq_frequency_table **omap_pm_cpu_get_freq_table(void)
{
pr_debug("OMAP PM: CPUFreq request for frequency table\n");
/*
* Return CPUFreq frequency table here: loop over
* all VDD1 clkrates, pull out the mpu_ck frequencies, build
* table
*/
return NULL;
}
void omap_pm_cpu_set_freq(unsigned long f)
{
if (f == 0) {
WARN_ON(1);
return;
}
pr_debug("OMAP PM: CPUFreq requests CPU frequency to be set to %lu\n",
f);
/*
* For l-o dev tree, determine whether MPU freq or DSP OPP id
* freq is higher. Find the OPP ID corresponding to the
* higher frequency. Call clk_round_rate() and clk_set_rate()
* on the OPP custom clock.
*
* CDP should just be able to set the VDD1 OPP clock rate here.
*/
}
unsigned long omap_pm_cpu_get_freq(void)
{
pr_debug("OMAP PM: CPUFreq requests current CPU frequency\n");
/*
* Call clk_get_rate() on the mpu_ck.
*/
return 0;
}
/**
* omap_pm_enable_off_mode - notify OMAP PM that off-mode is enabled
*
* Intended for use only by OMAP PM core code to notify this layer
* that off mode has been enabled.
*/
void omap_pm_enable_off_mode(void)
{
off_mode_enabled = true;
}
/**
* omap_pm_disable_off_mode - notify OMAP PM that off-mode is disabled
*
* Intended for use only by OMAP PM core code to notify this layer
* that off mode has been disabled.
*/
void omap_pm_disable_off_mode(void)
{
off_mode_enabled = false;
}
/*
* Device context loss tracking
*/
#ifdef CONFIG_ARCH_OMAP2PLUS
int omap_pm_get_dev_context_loss_count(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
int count;
if (WARN_ON(!dev))
return -ENODEV;
if (dev->pm_domain == &omap_device_pm_domain) {
count = omap_device_get_context_loss_count(pdev);
} else {
WARN_ONCE(off_mode_enabled, "omap_pm: using dummy context loss counter; device %s should be converted to omap_device",
dev_name(dev));
count = dummy_context_loss_counter;
if (off_mode_enabled) {
count++;
/*
* Context loss count has to be a non-negative value.
* Clear the sign bit to get a value range from 0 to
* INT_MAX.
*/
count &= INT_MAX;
dummy_context_loss_counter = count;
}
}
pr_debug("OMAP PM: context loss count for dev %s = %d\n",
dev_name(dev), count);
return count;
}
#else
int omap_pm_get_dev_context_loss_count(struct device *dev)
{
return dummy_context_loss_counter;
}
#endif
/* Should be called before clk framework init */
int __init omap_pm_if_early_init(void)
{
return 0;
}
/* Must be called after clock framework is initialized */
int __init omap_pm_if_init(void)
{
return 0;
}
void omap_pm_if_exit(void)
{
/* Deallocate CPUFreq frequency table here */
}
| gpl-2.0 |
byzvulture/android_kernel_zte_nx503a | drivers/gpu/drm/radeon/r300.c | 4049 | 43236 | /*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <drm/drmP.h>
#include <drm/drm.h>
#include <drm/drm_crtc_helper.h>
#include "radeon_reg.h"
#include "radeon.h"
#include "radeon_asic.h"
#include "radeon_drm.h"
#include "r100_track.h"
#include "r300d.h"
#include "rv350d.h"
#include "r300_reg_safe.h"
/* This files gather functions specifics to: r300,r350,rv350,rv370,rv380
*
* GPU Errata:
* - HOST_PATH_CNTL: r300 family seems to dislike write to HOST_PATH_CNTL
* using MMIO to flush host path read cache, this lead to HARDLOCKUP.
* However, scheduling such write to the ring seems harmless, i suspect
* the CP read collide with the flush somehow, or maybe the MC, hard to
* tell. (Jerome Glisse)
*/
/*
* rv370,rv380 PCIE GART
*/
static int rv370_debugfs_pcie_gart_info_init(struct radeon_device *rdev);
void rv370_pcie_gart_tlb_flush(struct radeon_device *rdev)
{
uint32_t tmp;
int i;
/* Workaround HW bug do flush 2 times */
for (i = 0; i < 2; i++) {
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp | RADEON_PCIE_TX_GART_INVALIDATE_TLB);
(void)RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
}
mb();
}
#define R300_PTE_WRITEABLE (1 << 2)
#define R300_PTE_READABLE (1 << 3)
int rv370_pcie_gart_set_page(struct radeon_device *rdev, int i, uint64_t addr)
{
void __iomem *ptr = rdev->gart.ptr;
if (i < 0 || i > rdev->gart.num_gpu_pages) {
return -EINVAL;
}
addr = (lower_32_bits(addr) >> 8) |
((upper_32_bits(addr) & 0xff) << 24) |
R300_PTE_WRITEABLE | R300_PTE_READABLE;
/* on x86 we want this to be CPU endian, on powerpc
* on powerpc without HW swappers, it'll get swapped on way
* into VRAM - so no need for cpu_to_le32 on VRAM tables */
writel(addr, ((void __iomem *)ptr) + (i * 4));
return 0;
}
int rv370_pcie_gart_init(struct radeon_device *rdev)
{
int r;
if (rdev->gart.robj) {
WARN(1, "RV370 PCIE GART already initialized\n");
return 0;
}
/* Initialize common gart structure */
r = radeon_gart_init(rdev);
if (r)
return r;
r = rv370_debugfs_pcie_gart_info_init(rdev);
if (r)
DRM_ERROR("Failed to register debugfs file for PCIE gart !\n");
rdev->gart.table_size = rdev->gart.num_gpu_pages * 4;
rdev->asic->gart.tlb_flush = &rv370_pcie_gart_tlb_flush;
rdev->asic->gart.set_page = &rv370_pcie_gart_set_page;
return radeon_gart_table_vram_alloc(rdev);
}
int rv370_pcie_gart_enable(struct radeon_device *rdev)
{
uint32_t table_addr;
uint32_t tmp;
int r;
if (rdev->gart.robj == NULL) {
dev_err(rdev->dev, "No VRAM object for PCIE GART.\n");
return -EINVAL;
}
r = radeon_gart_table_vram_pin(rdev);
if (r)
return r;
radeon_gart_restore(rdev);
/* discard memory request outside of configured range */
tmp = RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_LO, rdev->mc.gtt_start);
tmp = rdev->mc.gtt_end & ~RADEON_GPU_PAGE_MASK;
WREG32_PCIE(RADEON_PCIE_TX_GART_END_LO, tmp);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_HI, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_HI, 0);
table_addr = rdev->gart.table_addr;
WREG32_PCIE(RADEON_PCIE_TX_GART_BASE, table_addr);
/* FIXME: setup default page */
WREG32_PCIE(RADEON_PCIE_TX_DISCARD_RD_ADDR_LO, rdev->mc.vram_start);
WREG32_PCIE(RADEON_PCIE_TX_DISCARD_RD_ADDR_HI, 0);
/* Clear error */
WREG32_PCIE(RADEON_PCIE_TX_GART_ERROR, 0);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
tmp |= RADEON_PCIE_TX_GART_EN;
tmp |= RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
rv370_pcie_gart_tlb_flush(rdev);
DRM_INFO("PCIE GART of %uM enabled (table at 0x%016llX).\n",
(unsigned)(rdev->mc.gtt_size >> 20),
(unsigned long long)table_addr);
rdev->gart.ready = true;
return 0;
}
void rv370_pcie_gart_disable(struct radeon_device *rdev)
{
u32 tmp;
WREG32_PCIE(RADEON_PCIE_TX_GART_START_LO, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_LO, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_HI, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_HI, 0);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
tmp |= RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp & ~RADEON_PCIE_TX_GART_EN);
radeon_gart_table_vram_unpin(rdev);
}
void rv370_pcie_gart_fini(struct radeon_device *rdev)
{
radeon_gart_fini(rdev);
rv370_pcie_gart_disable(rdev);
radeon_gart_table_vram_free(rdev);
}
void r300_fence_ring_emit(struct radeon_device *rdev,
struct radeon_fence *fence)
{
struct radeon_ring *ring = &rdev->ring[fence->ring];
/* Who ever call radeon_fence_emit should call ring_lock and ask
* for enough space (today caller are ib schedule and buffer move) */
/* Write SC register so SC & US assert idle */
radeon_ring_write(ring, PACKET0(R300_RE_SCISSORS_TL, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RE_SCISSORS_BR, 0));
radeon_ring_write(ring, 0);
/* Flush 3D cache */
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH);
/* Wait until IDLE & CLEAN */
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring, (RADEON_WAIT_3D_IDLECLEAN |
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_DMA_GUI_IDLE));
radeon_ring_write(ring, PACKET0(RADEON_HOST_PATH_CNTL, 0));
radeon_ring_write(ring, rdev->config.r300.hdp_cntl |
RADEON_HDP_READ_BUFFER_INVALIDATE);
radeon_ring_write(ring, PACKET0(RADEON_HOST_PATH_CNTL, 0));
radeon_ring_write(ring, rdev->config.r300.hdp_cntl);
/* Emit fence sequence & fire IRQ */
radeon_ring_write(ring, PACKET0(rdev->fence_drv[fence->ring].scratch_reg, 0));
radeon_ring_write(ring, fence->seq);
radeon_ring_write(ring, PACKET0(RADEON_GEN_INT_STATUS, 0));
radeon_ring_write(ring, RADEON_SW_INT_FIRE);
}
void r300_ring_start(struct radeon_device *rdev, struct radeon_ring *ring)
{
unsigned gb_tile_config;
int r;
/* Sub pixel 1/12 so we can have 4K rendering according to doc */
gb_tile_config = (R300_ENABLE_TILING | R300_TILE_SIZE_16);
switch(rdev->num_gb_pipes) {
case 2:
gb_tile_config |= R300_PIPE_COUNT_R300;
break;
case 3:
gb_tile_config |= R300_PIPE_COUNT_R420_3P;
break;
case 4:
gb_tile_config |= R300_PIPE_COUNT_R420;
break;
case 1:
default:
gb_tile_config |= R300_PIPE_COUNT_RV350;
break;
}
r = radeon_ring_lock(rdev, ring, 64);
if (r) {
return;
}
radeon_ring_write(ring, PACKET0(RADEON_ISYNC_CNTL, 0));
radeon_ring_write(ring,
RADEON_ISYNC_ANY2D_IDLE3D |
RADEON_ISYNC_ANY3D_IDLE2D |
RADEON_ISYNC_WAIT_IDLEGUI |
RADEON_ISYNC_CPSCRATCH_IDLEGUI);
radeon_ring_write(ring, PACKET0(R300_GB_TILE_CONFIG, 0));
radeon_ring_write(ring, gb_tile_config);
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring,
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_3D_IDLECLEAN);
radeon_ring_write(ring, PACKET0(R300_DST_PIPE_CONFIG, 0));
radeon_ring_write(ring, R300_PIPE_AUTO_CONFIG);
radeon_ring_write(ring, PACKET0(R300_GB_SELECT, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_GB_ENABLE, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH | R300_RB3D_DC_FREE);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH | R300_ZC_FREE);
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring,
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_3D_IDLECLEAN);
radeon_ring_write(ring, PACKET0(R300_GB_AA_CONFIG, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH | R300_RB3D_DC_FREE);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH | R300_ZC_FREE);
radeon_ring_write(ring, PACKET0(R300_GB_MSPOS0, 0));
radeon_ring_write(ring,
((6 << R300_MS_X0_SHIFT) |
(6 << R300_MS_Y0_SHIFT) |
(6 << R300_MS_X1_SHIFT) |
(6 << R300_MS_Y1_SHIFT) |
(6 << R300_MS_X2_SHIFT) |
(6 << R300_MS_Y2_SHIFT) |
(6 << R300_MSBD0_Y_SHIFT) |
(6 << R300_MSBD0_X_SHIFT)));
radeon_ring_write(ring, PACKET0(R300_GB_MSPOS1, 0));
radeon_ring_write(ring,
((6 << R300_MS_X3_SHIFT) |
(6 << R300_MS_Y3_SHIFT) |
(6 << R300_MS_X4_SHIFT) |
(6 << R300_MS_Y4_SHIFT) |
(6 << R300_MS_X5_SHIFT) |
(6 << R300_MS_Y5_SHIFT) |
(6 << R300_MSBD1_SHIFT)));
radeon_ring_write(ring, PACKET0(R300_GA_ENHANCE, 0));
radeon_ring_write(ring, R300_GA_DEADLOCK_CNTL | R300_GA_FASTSYNC_CNTL);
radeon_ring_write(ring, PACKET0(R300_GA_POLY_MODE, 0));
radeon_ring_write(ring,
R300_FRONT_PTYPE_TRIANGE | R300_BACK_PTYPE_TRIANGE);
radeon_ring_write(ring, PACKET0(R300_GA_ROUND_MODE, 0));
radeon_ring_write(ring,
R300_GEOMETRY_ROUND_NEAREST |
R300_COLOR_ROUND_NEAREST);
radeon_ring_unlock_commit(rdev, ring);
}
void r300_errata(struct radeon_device *rdev)
{
rdev->pll_errata = 0;
if (rdev->family == CHIP_R300 &&
(RREG32(RADEON_CONFIG_CNTL) & RADEON_CFG_ATI_REV_ID_MASK) == RADEON_CFG_ATI_REV_A11) {
rdev->pll_errata |= CHIP_ERRATA_R300_CG;
}
}
int r300_mc_wait_for_idle(struct radeon_device *rdev)
{
unsigned i;
uint32_t tmp;
for (i = 0; i < rdev->usec_timeout; i++) {
/* read MC_STATUS */
tmp = RREG32(RADEON_MC_STATUS);
if (tmp & R300_MC_IDLE) {
return 0;
}
DRM_UDELAY(1);
}
return -1;
}
void r300_gpu_init(struct radeon_device *rdev)
{
uint32_t gb_tile_config, tmp;
if ((rdev->family == CHIP_R300 && rdev->pdev->device != 0x4144) ||
(rdev->family == CHIP_R350 && rdev->pdev->device != 0x4148)) {
/* r300,r350 */
rdev->num_gb_pipes = 2;
} else {
/* rv350,rv370,rv380,r300 AD, r350 AH */
rdev->num_gb_pipes = 1;
}
rdev->num_z_pipes = 1;
gb_tile_config = (R300_ENABLE_TILING | R300_TILE_SIZE_16);
switch (rdev->num_gb_pipes) {
case 2:
gb_tile_config |= R300_PIPE_COUNT_R300;
break;
case 3:
gb_tile_config |= R300_PIPE_COUNT_R420_3P;
break;
case 4:
gb_tile_config |= R300_PIPE_COUNT_R420;
break;
default:
case 1:
gb_tile_config |= R300_PIPE_COUNT_RV350;
break;
}
WREG32(R300_GB_TILE_CONFIG, gb_tile_config);
if (r100_gui_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait GUI idle while "
"programming pipes. Bad things might happen.\n");
}
tmp = RREG32(R300_DST_PIPE_CONFIG);
WREG32(R300_DST_PIPE_CONFIG, tmp | R300_PIPE_AUTO_CONFIG);
WREG32(R300_RB2D_DSTCACHE_MODE,
R300_DC_AUTOFLUSH_ENABLE |
R300_DC_DC_DISABLE_IGNORE_PE);
if (r100_gui_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait GUI idle while "
"programming pipes. Bad things might happen.\n");
}
if (r300_mc_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait MC idle while "
"programming pipes. Bad things might happen.\n");
}
DRM_INFO("radeon: %d quad pipes, %d Z pipes initialized.\n",
rdev->num_gb_pipes, rdev->num_z_pipes);
}
bool r300_gpu_is_lockup(struct radeon_device *rdev, struct radeon_ring *ring)
{
u32 rbbm_status;
int r;
rbbm_status = RREG32(R_000E40_RBBM_STATUS);
if (!G_000E40_GUI_ACTIVE(rbbm_status)) {
r100_gpu_lockup_update(&rdev->config.r300.lockup, ring);
return false;
}
/* force CP activities */
r = radeon_ring_lock(rdev, ring, 2);
if (!r) {
/* PACKET2 NOP */
radeon_ring_write(ring, 0x80000000);
radeon_ring_write(ring, 0x80000000);
radeon_ring_unlock_commit(rdev, ring);
}
ring->rptr = RREG32(RADEON_CP_RB_RPTR);
return r100_gpu_cp_is_lockup(rdev, &rdev->config.r300.lockup, ring);
}
int r300_asic_reset(struct radeon_device *rdev)
{
struct r100_mc_save save;
u32 status, tmp;
int ret = 0;
status = RREG32(R_000E40_RBBM_STATUS);
if (!G_000E40_GUI_ACTIVE(status)) {
return 0;
}
r100_mc_stop(rdev, &save);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* stop CP */
WREG32(RADEON_CP_CSQ_CNTL, 0);
tmp = RREG32(RADEON_CP_RB_CNTL);
WREG32(RADEON_CP_RB_CNTL, tmp | RADEON_RB_RPTR_WR_ENA);
WREG32(RADEON_CP_RB_RPTR_WR, 0);
WREG32(RADEON_CP_RB_WPTR, 0);
WREG32(RADEON_CP_RB_CNTL, tmp);
/* save PCI state */
pci_save_state(rdev->pdev);
/* disable bus mastering */
r100_bm_disable(rdev);
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_VAP(1) |
S_0000F0_SOFT_RESET_GA(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* resetting the CP seems to be problematic sometimes it end up
* hard locking the computer, but it's necessary for successful
* reset more test & playing is needed on R3XX/R4XX to find a
* reliable (if any solution)
*/
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_CP(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* restore PCI & busmastering */
pci_restore_state(rdev->pdev);
r100_enable_bm(rdev);
/* Check if GPU is idle */
if (G_000E40_GA_BUSY(status) || G_000E40_VAP_BUSY(status)) {
dev_err(rdev->dev, "failed to reset GPU\n");
rdev->gpu_lockup = true;
ret = -1;
} else
dev_info(rdev->dev, "GPU reset succeed\n");
r100_mc_resume(rdev, &save);
return ret;
}
/*
* r300,r350,rv350,rv380 VRAM info
*/
void r300_mc_init(struct radeon_device *rdev)
{
u64 base;
u32 tmp;
/* DDR for all card after R300 & IGP */
rdev->mc.vram_is_ddr = true;
tmp = RREG32(RADEON_MEM_CNTL);
tmp &= R300_MEM_NUM_CHANNELS_MASK;
switch (tmp) {
case 0: rdev->mc.vram_width = 64; break;
case 1: rdev->mc.vram_width = 128; break;
case 2: rdev->mc.vram_width = 256; break;
default: rdev->mc.vram_width = 128; break;
}
r100_vram_init_sizes(rdev);
base = rdev->mc.aper_base;
if (rdev->flags & RADEON_IS_IGP)
base = (RREG32(RADEON_NB_TOM) & 0xffff) << 16;
radeon_vram_location(rdev, &rdev->mc, base);
rdev->mc.gtt_base_align = 0;
if (!(rdev->flags & RADEON_IS_AGP))
radeon_gtt_location(rdev, &rdev->mc);
radeon_update_bandwidth_info(rdev);
}
void rv370_set_pcie_lanes(struct radeon_device *rdev, int lanes)
{
uint32_t link_width_cntl, mask;
if (rdev->flags & RADEON_IS_IGP)
return;
if (!(rdev->flags & RADEON_IS_PCIE))
return;
/* FIXME wait for idle */
switch (lanes) {
case 0:
mask = RADEON_PCIE_LC_LINK_WIDTH_X0;
break;
case 1:
mask = RADEON_PCIE_LC_LINK_WIDTH_X1;
break;
case 2:
mask = RADEON_PCIE_LC_LINK_WIDTH_X2;
break;
case 4:
mask = RADEON_PCIE_LC_LINK_WIDTH_X4;
break;
case 8:
mask = RADEON_PCIE_LC_LINK_WIDTH_X8;
break;
case 12:
mask = RADEON_PCIE_LC_LINK_WIDTH_X12;
break;
case 16:
default:
mask = RADEON_PCIE_LC_LINK_WIDTH_X16;
break;
}
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
if ((link_width_cntl & RADEON_PCIE_LC_LINK_WIDTH_RD_MASK) ==
(mask << RADEON_PCIE_LC_LINK_WIDTH_RD_SHIFT))
return;
link_width_cntl &= ~(RADEON_PCIE_LC_LINK_WIDTH_MASK |
RADEON_PCIE_LC_RECONFIG_NOW |
RADEON_PCIE_LC_RECONFIG_LATER |
RADEON_PCIE_LC_SHORT_RECONFIG_EN);
link_width_cntl |= mask;
WREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL, link_width_cntl);
WREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL, (link_width_cntl |
RADEON_PCIE_LC_RECONFIG_NOW));
/* wait for lane set to complete */
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
while (link_width_cntl == 0xffffffff)
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
}
int rv370_get_pcie_lanes(struct radeon_device *rdev)
{
u32 link_width_cntl;
if (rdev->flags & RADEON_IS_IGP)
return 0;
if (!(rdev->flags & RADEON_IS_PCIE))
return 0;
/* FIXME wait for idle */
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
switch ((link_width_cntl & RADEON_PCIE_LC_LINK_WIDTH_RD_MASK) >> RADEON_PCIE_LC_LINK_WIDTH_RD_SHIFT) {
case RADEON_PCIE_LC_LINK_WIDTH_X0:
return 0;
case RADEON_PCIE_LC_LINK_WIDTH_X1:
return 1;
case RADEON_PCIE_LC_LINK_WIDTH_X2:
return 2;
case RADEON_PCIE_LC_LINK_WIDTH_X4:
return 4;
case RADEON_PCIE_LC_LINK_WIDTH_X8:
return 8;
case RADEON_PCIE_LC_LINK_WIDTH_X16:
default:
return 16;
}
}
#if defined(CONFIG_DEBUG_FS)
static int rv370_debugfs_pcie_gart_info(struct seq_file *m, void *data)
{
struct drm_info_node *node = (struct drm_info_node *) m->private;
struct drm_device *dev = node->minor->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t tmp;
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
seq_printf(m, "PCIE_TX_GART_CNTL 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_BASE);
seq_printf(m, "PCIE_TX_GART_BASE 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_START_LO);
seq_printf(m, "PCIE_TX_GART_START_LO 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_START_HI);
seq_printf(m, "PCIE_TX_GART_START_HI 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_END_LO);
seq_printf(m, "PCIE_TX_GART_END_LO 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_END_HI);
seq_printf(m, "PCIE_TX_GART_END_HI 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_ERROR);
seq_printf(m, "PCIE_TX_GART_ERROR 0x%08x\n", tmp);
return 0;
}
static struct drm_info_list rv370_pcie_gart_info_list[] = {
{"rv370_pcie_gart_info", rv370_debugfs_pcie_gart_info, 0, NULL},
};
#endif
static int rv370_debugfs_pcie_gart_info_init(struct radeon_device *rdev)
{
#if defined(CONFIG_DEBUG_FS)
return radeon_debugfs_add_files(rdev, rv370_pcie_gart_info_list, 1);
#else
return 0;
#endif
}
static int r300_packet0_check(struct radeon_cs_parser *p,
struct radeon_cs_packet *pkt,
unsigned idx, unsigned reg)
{
struct radeon_cs_reloc *reloc;
struct r100_cs_track *track;
volatile uint32_t *ib;
uint32_t tmp, tile_flags = 0;
unsigned i;
int r;
u32 idx_value;
ib = p->ib->ptr;
track = (struct r100_cs_track *)p->track;
idx_value = radeon_get_ib_value(p, idx);
switch(reg) {
case AVIVO_D1MODE_VLINE_START_END:
case RADEON_CRTC_GUI_TRIG_VLINE:
r = r100_cs_packet_parse_vline(p);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
break;
case RADEON_DST_PITCH_OFFSET:
case RADEON_SRC_PITCH_OFFSET:
r = r100_reloc_pitch_offset(p, pkt, idx, reg);
if (r)
return r;
break;
case R300_RB3D_COLOROFFSET0:
case R300_RB3D_COLOROFFSET1:
case R300_RB3D_COLOROFFSET2:
case R300_RB3D_COLOROFFSET3:
i = (reg - R300_RB3D_COLOROFFSET0) >> 2;
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->cb[i].robj = reloc->robj;
track->cb[i].offset = idx_value;
track->cb_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_ZB_DEPTHOFFSET:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->zb.robj = reloc->robj;
track->zb.offset = idx_value;
track->zb_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_TX_OFFSET_0:
case R300_TX_OFFSET_0+4:
case R300_TX_OFFSET_0+8:
case R300_TX_OFFSET_0+12:
case R300_TX_OFFSET_0+16:
case R300_TX_OFFSET_0+20:
case R300_TX_OFFSET_0+24:
case R300_TX_OFFSET_0+28:
case R300_TX_OFFSET_0+32:
case R300_TX_OFFSET_0+36:
case R300_TX_OFFSET_0+40:
case R300_TX_OFFSET_0+44:
case R300_TX_OFFSET_0+48:
case R300_TX_OFFSET_0+52:
case R300_TX_OFFSET_0+56:
case R300_TX_OFFSET_0+60:
i = (reg - R300_TX_OFFSET_0) >> 2;
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS) {
ib[idx] = (idx_value & 31) | /* keep the 1st 5 bits */
((idx_value & ~31) + (u32)reloc->lobj.gpu_offset);
} else {
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_TXO_MACRO_TILE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_TXO_MICRO_TILE;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_TXO_MICRO_TILE_SQUARE;
tmp = idx_value + ((u32)reloc->lobj.gpu_offset);
tmp |= tile_flags;
ib[idx] = tmp;
}
track->textures[i].robj = reloc->robj;
track->tex_dirty = true;
break;
/* Tracked registers */
case 0x2084:
/* VAP_VF_CNTL */
track->vap_vf_cntl = idx_value;
break;
case 0x20B4:
/* VAP_VTX_SIZE */
track->vtx_size = idx_value & 0x7F;
break;
case 0x2134:
/* VAP_VF_MAX_VTX_INDX */
track->max_indx = idx_value & 0x00FFFFFFUL;
break;
case 0x2088:
/* VAP_ALT_NUM_VERTICES - only valid on r500 */
if (p->rdev->family < CHIP_RV515)
goto fail;
track->vap_alt_nverts = idx_value & 0xFFFFFF;
break;
case 0x43E4:
/* SC_SCISSOR1 */
track->maxy = ((idx_value >> 13) & 0x1FFF) + 1;
if (p->rdev->family < CHIP_RV515) {
track->maxy -= 1440;
}
track->cb_dirty = true;
track->zb_dirty = true;
break;
case 0x4E00:
/* RB3D_CCTL */
if ((idx_value & (1 << 10)) && /* CMASK_ENABLE */
p->rdev->cmask_filp != p->filp) {
DRM_ERROR("Invalid RB3D_CCTL: Cannot enable CMASK.\n");
return -EINVAL;
}
track->num_cb = ((idx_value >> 5) & 0x3) + 1;
track->cb_dirty = true;
break;
case 0x4E38:
case 0x4E3C:
case 0x4E40:
case 0x4E44:
/* RB3D_COLORPITCH0 */
/* RB3D_COLORPITCH1 */
/* RB3D_COLORPITCH2 */
/* RB3D_COLORPITCH3 */
if (!(p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS)) {
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_COLOR_TILE_ENABLE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_COLOR_MICROTILE_ENABLE;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_COLOR_MICROTILE_SQUARE_ENABLE;
tmp = idx_value & ~(0x7 << 16);
tmp |= tile_flags;
ib[idx] = tmp;
}
i = (reg - 0x4E38) >> 2;
track->cb[i].pitch = idx_value & 0x3FFE;
switch (((idx_value >> 21) & 0xF)) {
case 9:
case 11:
case 12:
track->cb[i].cpp = 1;
break;
case 3:
case 4:
case 13:
case 15:
track->cb[i].cpp = 2;
break;
case 5:
if (p->rdev->family < CHIP_RV515) {
DRM_ERROR("Invalid color buffer format (%d)!\n",
((idx_value >> 21) & 0xF));
return -EINVAL;
}
/* Pass through. */
case 6:
track->cb[i].cpp = 4;
break;
case 10:
track->cb[i].cpp = 8;
break;
case 7:
track->cb[i].cpp = 16;
break;
default:
DRM_ERROR("Invalid color buffer format (%d) !\n",
((idx_value >> 21) & 0xF));
return -EINVAL;
}
track->cb_dirty = true;
break;
case 0x4F00:
/* ZB_CNTL */
if (idx_value & 2) {
track->z_enabled = true;
} else {
track->z_enabled = false;
}
track->zb_dirty = true;
break;
case 0x4F10:
/* ZB_FORMAT */
switch ((idx_value & 0xF)) {
case 0:
case 1:
track->zb.cpp = 2;
break;
case 2:
track->zb.cpp = 4;
break;
default:
DRM_ERROR("Invalid z buffer format (%d) !\n",
(idx_value & 0xF));
return -EINVAL;
}
track->zb_dirty = true;
break;
case 0x4F24:
/* ZB_DEPTHPITCH */
if (!(p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS)) {
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_DEPTHMACROTILE_ENABLE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_DEPTHMICROTILE_TILED;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_DEPTHMICROTILE_TILED_SQUARE;
tmp = idx_value & ~(0x7 << 16);
tmp |= tile_flags;
ib[idx] = tmp;
}
track->zb.pitch = idx_value & 0x3FFC;
track->zb_dirty = true;
break;
case 0x4104:
/* TX_ENABLE */
for (i = 0; i < 16; i++) {
bool enabled;
enabled = !!(idx_value & (1 << i));
track->textures[i].enabled = enabled;
}
track->tex_dirty = true;
break;
case 0x44C0:
case 0x44C4:
case 0x44C8:
case 0x44CC:
case 0x44D0:
case 0x44D4:
case 0x44D8:
case 0x44DC:
case 0x44E0:
case 0x44E4:
case 0x44E8:
case 0x44EC:
case 0x44F0:
case 0x44F4:
case 0x44F8:
case 0x44FC:
/* TX_FORMAT1_[0-15] */
i = (reg - 0x44C0) >> 2;
tmp = (idx_value >> 25) & 0x3;
track->textures[i].tex_coord_type = tmp;
switch ((idx_value & 0x1F)) {
case R300_TX_FORMAT_X8:
case R300_TX_FORMAT_Y4X4:
case R300_TX_FORMAT_Z3Y3X2:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_X16:
case R300_TX_FORMAT_FL_I16:
case R300_TX_FORMAT_Y8X8:
case R300_TX_FORMAT_Z5Y6X5:
case R300_TX_FORMAT_Z6Y5X5:
case R300_TX_FORMAT_W4Z4Y4X4:
case R300_TX_FORMAT_W1Z5Y5X5:
case R300_TX_FORMAT_D3DMFT_CxV8U8:
case R300_TX_FORMAT_B8G8_B8G8:
case R300_TX_FORMAT_G8R8_G8B8:
track->textures[i].cpp = 2;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_Y16X16:
case R300_TX_FORMAT_FL_I16A16:
case R300_TX_FORMAT_Z11Y11X10:
case R300_TX_FORMAT_Z10Y11X11:
case R300_TX_FORMAT_W8Z8Y8X8:
case R300_TX_FORMAT_W2Z10Y10X10:
case 0x17:
case R300_TX_FORMAT_FL_I32:
case 0x1e:
track->textures[i].cpp = 4;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_W16Z16Y16X16:
case R300_TX_FORMAT_FL_R16G16B16A16:
case R300_TX_FORMAT_FL_I32A32:
track->textures[i].cpp = 8;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_FL_R32G32B32A32:
track->textures[i].cpp = 16;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_DXT1:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_DXT1;
break;
case R300_TX_FORMAT_ATI2N:
if (p->rdev->family < CHIP_R420) {
DRM_ERROR("Invalid texture format %u\n",
(idx_value & 0x1F));
return -EINVAL;
}
/* The same rules apply as for DXT3/5. */
/* Pass through. */
case R300_TX_FORMAT_DXT3:
case R300_TX_FORMAT_DXT5:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_DXT35;
break;
default:
DRM_ERROR("Invalid texture format %u\n",
(idx_value & 0x1F));
return -EINVAL;
}
track->tex_dirty = true;
break;
case 0x4400:
case 0x4404:
case 0x4408:
case 0x440C:
case 0x4410:
case 0x4414:
case 0x4418:
case 0x441C:
case 0x4420:
case 0x4424:
case 0x4428:
case 0x442C:
case 0x4430:
case 0x4434:
case 0x4438:
case 0x443C:
/* TX_FILTER0_[0-15] */
i = (reg - 0x4400) >> 2;
tmp = idx_value & 0x7;
if (tmp == 2 || tmp == 4 || tmp == 6) {
track->textures[i].roundup_w = false;
}
tmp = (idx_value >> 3) & 0x7;
if (tmp == 2 || tmp == 4 || tmp == 6) {
track->textures[i].roundup_h = false;
}
track->tex_dirty = true;
break;
case 0x4500:
case 0x4504:
case 0x4508:
case 0x450C:
case 0x4510:
case 0x4514:
case 0x4518:
case 0x451C:
case 0x4520:
case 0x4524:
case 0x4528:
case 0x452C:
case 0x4530:
case 0x4534:
case 0x4538:
case 0x453C:
/* TX_FORMAT2_[0-15] */
i = (reg - 0x4500) >> 2;
tmp = idx_value & 0x3FFF;
track->textures[i].pitch = tmp + 1;
if (p->rdev->family >= CHIP_RV515) {
tmp = ((idx_value >> 15) & 1) << 11;
track->textures[i].width_11 = tmp;
tmp = ((idx_value >> 16) & 1) << 11;
track->textures[i].height_11 = tmp;
/* ATI1N */
if (idx_value & (1 << 14)) {
/* The same rules apply as for DXT1. */
track->textures[i].compress_format =
R100_TRACK_COMP_DXT1;
}
} else if (idx_value & (1 << 14)) {
DRM_ERROR("Forbidden bit TXFORMAT_MSB\n");
return -EINVAL;
}
track->tex_dirty = true;
break;
case 0x4480:
case 0x4484:
case 0x4488:
case 0x448C:
case 0x4490:
case 0x4494:
case 0x4498:
case 0x449C:
case 0x44A0:
case 0x44A4:
case 0x44A8:
case 0x44AC:
case 0x44B0:
case 0x44B4:
case 0x44B8:
case 0x44BC:
/* TX_FORMAT0_[0-15] */
i = (reg - 0x4480) >> 2;
tmp = idx_value & 0x7FF;
track->textures[i].width = tmp + 1;
tmp = (idx_value >> 11) & 0x7FF;
track->textures[i].height = tmp + 1;
tmp = (idx_value >> 26) & 0xF;
track->textures[i].num_levels = tmp;
tmp = idx_value & (1 << 31);
track->textures[i].use_pitch = !!tmp;
tmp = (idx_value >> 22) & 0xF;
track->textures[i].txdepth = tmp;
track->tex_dirty = true;
break;
case R300_ZB_ZPASS_ADDR:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case 0x4e0c:
/* RB3D_COLOR_CHANNEL_MASK */
track->color_channel_mask = idx_value;
track->cb_dirty = true;
break;
case 0x43a4:
/* SC_HYPERZ_EN */
/* r300c emits this register - we need to disable hyperz for it
* without complaining */
if (p->rdev->hyperz_filp != p->filp) {
if (idx_value & 0x1)
ib[idx] = idx_value & ~1;
}
break;
case 0x4f1c:
/* ZB_BW_CNTL */
track->zb_cb_clear = !!(idx_value & (1 << 5));
track->cb_dirty = true;
track->zb_dirty = true;
if (p->rdev->hyperz_filp != p->filp) {
if (idx_value & (R300_HIZ_ENABLE |
R300_RD_COMP_ENABLE |
R300_WR_COMP_ENABLE |
R300_FAST_FILL_ENABLE))
goto fail;
}
break;
case 0x4e04:
/* RB3D_BLENDCNTL */
track->blend_read_enable = !!(idx_value & (1 << 2));
track->cb_dirty = true;
break;
case R300_RB3D_AARESOLVE_OFFSET:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->aa.robj = reloc->robj;
track->aa.offset = idx_value;
track->aa_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_RB3D_AARESOLVE_PITCH:
track->aa.pitch = idx_value & 0x3FFE;
track->aa_dirty = true;
break;
case R300_RB3D_AARESOLVE_CTL:
track->aaresolve = idx_value & 0x1;
track->aa_dirty = true;
break;
case 0x4f30: /* ZB_MASK_OFFSET */
case 0x4f34: /* ZB_ZMASK_PITCH */
case 0x4f44: /* ZB_HIZ_OFFSET */
case 0x4f54: /* ZB_HIZ_PITCH */
if (idx_value && (p->rdev->hyperz_filp != p->filp))
goto fail;
break;
case 0x4028:
if (idx_value && (p->rdev->hyperz_filp != p->filp))
goto fail;
/* GB_Z_PEQ_CONFIG */
if (p->rdev->family >= CHIP_RV350)
break;
goto fail;
break;
case 0x4be8:
/* valid register only on RV530 */
if (p->rdev->family == CHIP_RV530)
break;
/* fallthrough do not move */
default:
goto fail;
}
return 0;
fail:
printk(KERN_ERR "Forbidden register 0x%04X in cs at %d (val=%08x)\n",
reg, idx, idx_value);
return -EINVAL;
}
static int r300_packet3_check(struct radeon_cs_parser *p,
struct radeon_cs_packet *pkt)
{
struct radeon_cs_reloc *reloc;
struct r100_cs_track *track;
volatile uint32_t *ib;
unsigned idx;
int r;
ib = p->ib->ptr;
idx = pkt->idx + 1;
track = (struct r100_cs_track *)p->track;
switch(pkt->opcode) {
case PACKET3_3D_LOAD_VBPNTR:
r = r100_packet3_load_vbpntr(p, pkt, idx);
if (r)
return r;
break;
case PACKET3_INDX_BUFFER:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for packet3 %d\n", pkt->opcode);
r100_cs_dump_packet(p, pkt);
return r;
}
ib[idx+1] = radeon_get_ib_value(p, idx + 1) + ((u32)reloc->lobj.gpu_offset);
r = r100_cs_track_check_pkt3_indx_buffer(p, pkt, reloc->robj);
if (r) {
return r;
}
break;
/* Draw packet */
case PACKET3_3D_DRAW_IMMD:
/* Number of dwords is vtx_size * (num_vertices - 1)
* PRIM_WALK must be equal to 3 vertex data in embedded
* in cmd stream */
if (((radeon_get_ib_value(p, idx + 1) >> 4) & 0x3) != 3) {
DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
return -EINVAL;
}
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
track->immd_dwords = pkt->count - 1;
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_IMMD_2:
/* Number of dwords is vtx_size * (num_vertices - 1)
* PRIM_WALK must be equal to 3 vertex data in embedded
* in cmd stream */
if (((radeon_get_ib_value(p, idx) >> 4) & 0x3) != 3) {
DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
return -EINVAL;
}
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
track->immd_dwords = pkt->count;
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_VBUF:
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_VBUF_2:
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_INDX:
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_INDX_2:
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_CLEAR_HIZ:
case PACKET3_3D_CLEAR_ZMASK:
if (p->rdev->hyperz_filp != p->filp)
return -EINVAL;
break;
case PACKET3_3D_CLEAR_CMASK:
if (p->rdev->cmask_filp != p->filp)
return -EINVAL;
break;
case PACKET3_NOP:
break;
default:
DRM_ERROR("Packet3 opcode %x not supported\n", pkt->opcode);
return -EINVAL;
}
return 0;
}
int r300_cs_parse(struct radeon_cs_parser *p)
{
struct radeon_cs_packet pkt;
struct r100_cs_track *track;
int r;
track = kzalloc(sizeof(*track), GFP_KERNEL);
if (track == NULL)
return -ENOMEM;
r100_cs_track_clear(p->rdev, track);
p->track = track;
do {
r = r100_cs_packet_parse(p, &pkt, p->idx);
if (r) {
return r;
}
p->idx += pkt.count + 2;
switch (pkt.type) {
case PACKET_TYPE0:
r = r100_cs_parse_packet0(p, &pkt,
p->rdev->config.r300.reg_safe_bm,
p->rdev->config.r300.reg_safe_bm_size,
&r300_packet0_check);
break;
case PACKET_TYPE2:
break;
case PACKET_TYPE3:
r = r300_packet3_check(p, &pkt);
break;
default:
DRM_ERROR("Unknown packet type %d !\n", pkt.type);
return -EINVAL;
}
if (r) {
return r;
}
} while (p->idx < p->chunks[p->chunk_ib_idx].length_dw);
return 0;
}
void r300_set_reg_safe(struct radeon_device *rdev)
{
rdev->config.r300.reg_safe_bm = r300_reg_safe_bm;
rdev->config.r300.reg_safe_bm_size = ARRAY_SIZE(r300_reg_safe_bm);
}
void r300_mc_program(struct radeon_device *rdev)
{
struct r100_mc_save save;
int r;
r = r100_debugfs_mc_info_init(rdev);
if (r) {
dev_err(rdev->dev, "Failed to create r100_mc debugfs file.\n");
}
/* Stops all mc clients */
r100_mc_stop(rdev, &save);
if (rdev->flags & RADEON_IS_AGP) {
WREG32(R_00014C_MC_AGP_LOCATION,
S_00014C_MC_AGP_START(rdev->mc.gtt_start >> 16) |
S_00014C_MC_AGP_TOP(rdev->mc.gtt_end >> 16));
WREG32(R_000170_AGP_BASE, lower_32_bits(rdev->mc.agp_base));
WREG32(R_00015C_AGP_BASE_2,
upper_32_bits(rdev->mc.agp_base) & 0xff);
} else {
WREG32(R_00014C_MC_AGP_LOCATION, 0x0FFFFFFF);
WREG32(R_000170_AGP_BASE, 0);
WREG32(R_00015C_AGP_BASE_2, 0);
}
/* Wait for mc idle */
if (r300_mc_wait_for_idle(rdev))
DRM_INFO("Failed to wait MC idle before programming MC.\n");
/* Program MC, should be a 32bits limited address space */
WREG32(R_000148_MC_FB_LOCATION,
S_000148_MC_FB_START(rdev->mc.vram_start >> 16) |
S_000148_MC_FB_TOP(rdev->mc.vram_end >> 16));
r100_mc_resume(rdev, &save);
}
void r300_clock_startup(struct radeon_device *rdev)
{
u32 tmp;
if (radeon_dynclks != -1 && radeon_dynclks)
radeon_legacy_set_clock_gating(rdev, 1);
/* We need to force on some of the block */
tmp = RREG32_PLL(R_00000D_SCLK_CNTL);
tmp |= S_00000D_FORCE_CP(1) | S_00000D_FORCE_VIP(1);
if ((rdev->family == CHIP_RV350) || (rdev->family == CHIP_RV380))
tmp |= S_00000D_FORCE_VAP(1);
WREG32_PLL(R_00000D_SCLK_CNTL, tmp);
}
static int r300_startup(struct radeon_device *rdev)
{
int r;
/* set common regs */
r100_set_common_regs(rdev);
/* program mc */
r300_mc_program(rdev);
/* Resume clock */
r300_clock_startup(rdev);
/* Initialize GPU configuration (# pipes, ...) */
r300_gpu_init(rdev);
/* Initialize GART (initialize after TTM so we can allocate
* memory through TTM but finalize after TTM) */
if (rdev->flags & RADEON_IS_PCIE) {
r = rv370_pcie_gart_enable(rdev);
if (r)
return r;
}
if (rdev->family == CHIP_R300 ||
rdev->family == CHIP_R350 ||
rdev->family == CHIP_RV350)
r100_enable_bm(rdev);
if (rdev->flags & RADEON_IS_PCI) {
r = r100_pci_gart_enable(rdev);
if (r)
return r;
}
/* allocate wb buffer */
r = radeon_wb_init(rdev);
if (r)
return r;
r = radeon_fence_driver_start_ring(rdev, RADEON_RING_TYPE_GFX_INDEX);
if (r) {
dev_err(rdev->dev, "failed initializing CP fences (%d).\n", r);
return r;
}
/* Enable IRQ */
r100_irq_set(rdev);
rdev->config.r300.hdp_cntl = RREG32(RADEON_HOST_PATH_CNTL);
/* 1M ring buffer */
r = r100_cp_init(rdev, 1024 * 1024);
if (r) {
dev_err(rdev->dev, "failed initializing CP (%d).\n", r);
return r;
}
r = radeon_ib_pool_start(rdev);
if (r)
return r;
r = radeon_ib_test(rdev, RADEON_RING_TYPE_GFX_INDEX, &rdev->ring[RADEON_RING_TYPE_GFX_INDEX]);
if (r) {
dev_err(rdev->dev, "failed testing IB (%d).\n", r);
rdev->accel_working = false;
return r;
}
return 0;
}
int r300_resume(struct radeon_device *rdev)
{
int r;
/* Make sur GART are not working */
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_disable(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_disable(rdev);
/* Resume clock before doing reset */
r300_clock_startup(rdev);
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev, "GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* post */
radeon_combios_asic_init(rdev->ddev);
/* Resume clock after posting */
r300_clock_startup(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
rdev->accel_working = true;
r = r300_startup(rdev);
if (r) {
rdev->accel_working = false;
}
return r;
}
int r300_suspend(struct radeon_device *rdev)
{
radeon_ib_pool_suspend(rdev);
r100_cp_disable(rdev);
radeon_wb_disable(rdev);
r100_irq_disable(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_disable(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_disable(rdev);
return 0;
}
void r300_fini(struct radeon_device *rdev)
{
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
r100_ib_fini(rdev);
radeon_gem_fini(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_fini(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_fini(rdev);
radeon_agp_fini(rdev);
radeon_irq_kms_fini(rdev);
radeon_fence_driver_fini(rdev);
radeon_bo_fini(rdev);
radeon_atombios_fini(rdev);
kfree(rdev->bios);
rdev->bios = NULL;
}
int r300_init(struct radeon_device *rdev)
{
int r;
/* Disable VGA */
r100_vga_render_disable(rdev);
/* Initialize scratch registers */
radeon_scratch_init(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
/* TODO: disable VGA need to use VGA request */
/* restore some register to sane defaults */
r100_restore_sanity(rdev);
/* BIOS*/
if (!radeon_get_bios(rdev)) {
if (ASIC_IS_AVIVO(rdev))
return -EINVAL;
}
if (rdev->is_atom_bios) {
dev_err(rdev->dev, "Expecting combios for RS400/RS480 GPU\n");
return -EINVAL;
} else {
r = radeon_combios_init(rdev);
if (r)
return r;
}
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev,
"GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* check if cards are posted or not */
if (radeon_boot_test_post_card(rdev) == false)
return -EINVAL;
/* Set asic errata */
r300_errata(rdev);
/* Initialize clocks */
radeon_get_clock_info(rdev->ddev);
/* initialize AGP */
if (rdev->flags & RADEON_IS_AGP) {
r = radeon_agp_init(rdev);
if (r) {
radeon_agp_disable(rdev);
}
}
/* initialize memory controller */
r300_mc_init(rdev);
/* Fence driver */
r = radeon_fence_driver_init(rdev);
if (r)
return r;
r = radeon_irq_kms_init(rdev);
if (r)
return r;
/* Memory manager */
r = radeon_bo_init(rdev);
if (r)
return r;
if (rdev->flags & RADEON_IS_PCIE) {
r = rv370_pcie_gart_init(rdev);
if (r)
return r;
}
if (rdev->flags & RADEON_IS_PCI) {
r = r100_pci_gart_init(rdev);
if (r)
return r;
}
r300_set_reg_safe(rdev);
r = radeon_ib_pool_init(rdev);
rdev->accel_working = true;
if (r) {
dev_err(rdev->dev, "IB initialization failed (%d).\n", r);
rdev->accel_working = false;
}
r = r300_startup(rdev);
if (r) {
/* Somethings want wront with the accel init stop accel */
dev_err(rdev->dev, "Disabling GPU acceleration\n");
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
r100_ib_fini(rdev);
radeon_irq_kms_fini(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_fini(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_fini(rdev);
radeon_agp_fini(rdev);
rdev->accel_working = false;
}
return 0;
}
| gpl-2.0 |
SlimKat-U8950/chil360-kernel | arch/mips/pnx833x/common/interrupts.c | 4561 | 10035 | /*
* interrupts.c: Interrupt mappings for PNX833X.
*
* Copyright 2008 NXP Semiconductors
* Chris Steel <chris.steel@nxp.com>
* Daniel Laird <daniel.j.laird@nxp.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/irq.h>
#include <linux/hardirq.h>
#include <linux/interrupt.h>
#include <asm/mipsregs.h>
#include <asm/irq_cpu.h>
#include <asm/setup.h>
#include <irq.h>
#include <irq-mapping.h>
#include <gpio.h>
static int mips_cpu_timer_irq;
static const unsigned int irq_prio[PNX833X_PIC_NUM_IRQ] =
{
0, /* unused */
4, /* PNX833X_PIC_I2C0_INT 1 */
4, /* PNX833X_PIC_I2C1_INT 2 */
1, /* PNX833X_PIC_UART0_INT 3 */
1, /* PNX833X_PIC_UART1_INT 4 */
6, /* PNX833X_PIC_TS_IN0_DV_INT 5 */
6, /* PNX833X_PIC_TS_IN0_DMA_INT 6 */
7, /* PNX833X_PIC_GPIO_INT 7 */
4, /* PNX833X_PIC_AUDIO_DEC_INT 8 */
5, /* PNX833X_PIC_VIDEO_DEC_INT 9 */
4, /* PNX833X_PIC_CONFIG_INT 10 */
4, /* PNX833X_PIC_AOI_INT 11 */
9, /* PNX833X_PIC_SYNC_INT 12 */
9, /* PNX8335_PIC_SATA_INT 13 */
4, /* PNX833X_PIC_OSD_INT 14 */
9, /* PNX833X_PIC_DISP1_INT 15 */
4, /* PNX833X_PIC_DEINTERLACER_INT 16 */
9, /* PNX833X_PIC_DISPLAY2_INT 17 */
4, /* PNX833X_PIC_VC_INT 18 */
4, /* PNX833X_PIC_SC_INT 19 */
9, /* PNX833X_PIC_IDE_INT 20 */
9, /* PNX833X_PIC_IDE_DMA_INT 21 */
6, /* PNX833X_PIC_TS_IN1_DV_INT 22 */
6, /* PNX833X_PIC_TS_IN1_DMA_INT 23 */
4, /* PNX833X_PIC_SGDX_DMA_INT 24 */
4, /* PNX833X_PIC_TS_OUT_INT 25 */
4, /* PNX833X_PIC_IR_INT 26 */
3, /* PNX833X_PIC_VMSP1_INT 27 */
3, /* PNX833X_PIC_VMSP2_INT 28 */
4, /* PNX833X_PIC_PIBC_INT 29 */
4, /* PNX833X_PIC_TS_IN0_TRD_INT 30 */
4, /* PNX833X_PIC_SGDX_TPD_INT 31 */
5, /* PNX833X_PIC_USB_INT 32 */
4, /* PNX833X_PIC_TS_IN1_TRD_INT 33 */
4, /* PNX833X_PIC_CLOCK_INT 34 */
4, /* PNX833X_PIC_SGDX_PARSER_INT 35 */
4, /* PNX833X_PIC_VMSP_DMA_INT 36 */
#if defined(CONFIG_SOC_PNX8335)
4, /* PNX8335_PIC_MIU_INT 37 */
4, /* PNX8335_PIC_AVCHIP_IRQ_INT 38 */
9, /* PNX8335_PIC_SYNC_HD_INT 39 */
9, /* PNX8335_PIC_DISP_HD_INT 40 */
9, /* PNX8335_PIC_DISP_SCALER_INT 41 */
4, /* PNX8335_PIC_OSD_HD1_INT 42 */
4, /* PNX8335_PIC_DTL_WRITER_Y_INT 43 */
4, /* PNX8335_PIC_DTL_WRITER_C_INT 44 */
4, /* PNX8335_PIC_DTL_EMULATOR_Y_IR_INT 45 */
4, /* PNX8335_PIC_DTL_EMULATOR_C_IR_INT 46 */
4, /* PNX8335_PIC_DENC_TTX_INT 47 */
4, /* PNX8335_PIC_MMI_SIF0_INT 48 */
4, /* PNX8335_PIC_MMI_SIF1_INT 49 */
4, /* PNX8335_PIC_MMI_CDMMU_INT 50 */
4, /* PNX8335_PIC_PIBCS_INT 51 */
12, /* PNX8335_PIC_ETHERNET_INT 52 */
3, /* PNX8335_PIC_VMSP1_0_INT 53 */
3, /* PNX8335_PIC_VMSP1_1_INT 54 */
4, /* PNX8335_PIC_VMSP1_DMA_INT 55 */
4, /* PNX8335_PIC_TDGR_DE_INT 56 */
4, /* PNX8335_PIC_IR1_IRQ_INT 57 */
#endif
};
static void pnx833x_timer_dispatch(void)
{
do_IRQ(mips_cpu_timer_irq);
}
static void pic_dispatch(void)
{
unsigned int irq = PNX833X_REGFIELD(PIC_INT_SRC, INT_SRC);
if ((irq >= 1) && (irq < (PNX833X_PIC_NUM_IRQ))) {
unsigned long priority = PNX833X_PIC_INT_PRIORITY;
PNX833X_PIC_INT_PRIORITY = irq_prio[irq];
if (irq == PNX833X_PIC_GPIO_INT) {
unsigned long mask = PNX833X_PIO_INT_STATUS & PNX833X_PIO_INT_ENABLE;
int pin;
while ((pin = ffs(mask & 0xffff))) {
pin -= 1;
do_IRQ(PNX833X_GPIO_IRQ_BASE + pin);
mask &= ~(1 << pin);
}
} else {
do_IRQ(irq + PNX833X_PIC_IRQ_BASE);
}
PNX833X_PIC_INT_PRIORITY = priority;
} else {
printk(KERN_ERR "plat_irq_dispatch: unexpected irq %u\n", irq);
}
}
asmlinkage void plat_irq_dispatch(void)
{
unsigned int pending = read_c0_status() & read_c0_cause();
if (pending & STATUSF_IP4)
pic_dispatch();
else if (pending & STATUSF_IP7)
do_IRQ(PNX833X_TIMER_IRQ);
else
spurious_interrupt();
}
static inline void pnx833x_hard_enable_pic_irq(unsigned int irq)
{
/* Currently we do this by setting IRQ priority to 1.
If priority support is being implemented, 1 should be repalced
by a better value. */
PNX833X_PIC_INT_REG(irq) = irq_prio[irq];
}
static inline void pnx833x_hard_disable_pic_irq(unsigned int irq)
{
/* Disable IRQ by writing setting it's priority to 0 */
PNX833X_PIC_INT_REG(irq) = 0;
}
static DEFINE_RAW_SPINLOCK(pnx833x_irq_lock);
static unsigned int pnx833x_startup_pic_irq(unsigned int irq)
{
unsigned long flags;
unsigned int pic_irq = irq - PNX833X_PIC_IRQ_BASE;
raw_spin_lock_irqsave(&pnx833x_irq_lock, flags);
pnx833x_hard_enable_pic_irq(pic_irq);
raw_spin_unlock_irqrestore(&pnx833x_irq_lock, flags);
return 0;
}
static void pnx833x_enable_pic_irq(struct irq_data *d)
{
unsigned long flags;
unsigned int pic_irq = d->irq - PNX833X_PIC_IRQ_BASE;
raw_spin_lock_irqsave(&pnx833x_irq_lock, flags);
pnx833x_hard_enable_pic_irq(pic_irq);
raw_spin_unlock_irqrestore(&pnx833x_irq_lock, flags);
}
static void pnx833x_disable_pic_irq(struct irq_data *d)
{
unsigned long flags;
unsigned int pic_irq = d->irq - PNX833X_PIC_IRQ_BASE;
raw_spin_lock_irqsave(&pnx833x_irq_lock, flags);
pnx833x_hard_disable_pic_irq(pic_irq);
raw_spin_unlock_irqrestore(&pnx833x_irq_lock, flags);
}
static DEFINE_RAW_SPINLOCK(pnx833x_gpio_pnx833x_irq_lock);
static void pnx833x_enable_gpio_irq(struct irq_data *d)
{
int pin = d->irq - PNX833X_GPIO_IRQ_BASE;
unsigned long flags;
raw_spin_lock_irqsave(&pnx833x_gpio_pnx833x_irq_lock, flags);
pnx833x_gpio_enable_irq(pin);
raw_spin_unlock_irqrestore(&pnx833x_gpio_pnx833x_irq_lock, flags);
}
static void pnx833x_disable_gpio_irq(struct irq_data *d)
{
int pin = d->irq - PNX833X_GPIO_IRQ_BASE;
unsigned long flags;
raw_spin_lock_irqsave(&pnx833x_gpio_pnx833x_irq_lock, flags);
pnx833x_gpio_disable_irq(pin);
raw_spin_unlock_irqrestore(&pnx833x_gpio_pnx833x_irq_lock, flags);
}
static int pnx833x_set_type_gpio_irq(struct irq_data *d, unsigned int flow_type)
{
int pin = d->irq - PNX833X_GPIO_IRQ_BASE;
int gpio_mode;
switch (flow_type) {
case IRQ_TYPE_EDGE_RISING:
gpio_mode = GPIO_INT_EDGE_RISING;
break;
case IRQ_TYPE_EDGE_FALLING:
gpio_mode = GPIO_INT_EDGE_FALLING;
break;
case IRQ_TYPE_EDGE_BOTH:
gpio_mode = GPIO_INT_EDGE_BOTH;
break;
case IRQ_TYPE_LEVEL_HIGH:
gpio_mode = GPIO_INT_LEVEL_HIGH;
break;
case IRQ_TYPE_LEVEL_LOW:
gpio_mode = GPIO_INT_LEVEL_LOW;
break;
default:
gpio_mode = GPIO_INT_NONE;
break;
}
pnx833x_gpio_setup_irq(gpio_mode, pin);
return 0;
}
static struct irq_chip pnx833x_pic_irq_type = {
.name = "PNX-PIC",
.irq_enable = pnx833x_enable_pic_irq,
.irq_disable = pnx833x_disable_pic_irq,
};
static struct irq_chip pnx833x_gpio_irq_type = {
.name = "PNX-GPIO",
.irq_enable = pnx833x_enable_gpio_irq,
.irq_disable = pnx833x_disable_gpio_irq,
.irq_set_type = pnx833x_set_type_gpio_irq,
};
void __init arch_init_irq(void)
{
unsigned int irq;
/* setup standard internal cpu irqs */
mips_cpu_irq_init();
/* Set IRQ information in irq_desc */
for (irq = PNX833X_PIC_IRQ_BASE; irq < (PNX833X_PIC_IRQ_BASE + PNX833X_PIC_NUM_IRQ); irq++) {
pnx833x_hard_disable_pic_irq(irq);
irq_set_chip_and_handler(irq, &pnx833x_pic_irq_type,
handle_simple_irq);
}
for (irq = PNX833X_GPIO_IRQ_BASE; irq < (PNX833X_GPIO_IRQ_BASE + PNX833X_GPIO_NUM_IRQ); irq++)
irq_set_chip_and_handler(irq, &pnx833x_gpio_irq_type,
handle_simple_irq);
/* Set PIC priority limiter register to 0 */
PNX833X_PIC_INT_PRIORITY = 0;
/* Setup GPIO IRQ dispatching */
pnx833x_startup_pic_irq(PNX833X_PIC_GPIO_INT);
/* Enable PIC IRQs (HWIRQ2) */
if (cpu_has_vint)
set_vi_handler(4, pic_dispatch);
write_c0_status(read_c0_status() | IE_IRQ2);
}
unsigned int __cpuinit get_c0_compare_int(void)
{
if (cpu_has_vint)
set_vi_handler(cp0_compare_irq, pnx833x_timer_dispatch);
mips_cpu_timer_irq = MIPS_CPU_IRQ_BASE + cp0_compare_irq;
return mips_cpu_timer_irq;
}
void __init plat_time_init(void)
{
/* calculate mips_hpt_frequency based on PNX833X_CLOCK_CPUCP_CTL reg */
extern unsigned long mips_hpt_frequency;
unsigned long reg = PNX833X_CLOCK_CPUCP_CTL;
if (!(PNX833X_BIT(reg, CLOCK_CPUCP_CTL, EXIT_RESET))) {
/* Functional clock is disabled so use crystal frequency */
mips_hpt_frequency = 25;
} else {
#if defined(CONFIG_SOC_PNX8335)
/* Functional clock is enabled, so get clock multiplier */
mips_hpt_frequency = 90 + (10 * PNX8335_REGFIELD(CLOCK_PLL_CPU_CTL, FREQ));
#else
static const unsigned long int freq[4] = {240, 160, 120, 80};
mips_hpt_frequency = freq[PNX833X_FIELD(reg, CLOCK_CPUCP_CTL, DIV_CLOCK)];
#endif
}
printk(KERN_INFO "CPU clock is %ld MHz\n", mips_hpt_frequency);
mips_hpt_frequency *= 500000;
}
| gpl-2.0 |
blackdeviant/hybrid-nicki | drivers/net/wireless/iwlwifi/iwl-notif-wait.c | 4817 | 5451 | /******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2007 - 2012 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2005 - 2012 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <linux/sched.h>
#include "iwl-notif-wait.h"
void iwl_notification_wait_init(struct iwl_notif_wait_data *notif_wait)
{
spin_lock_init(¬if_wait->notif_wait_lock);
INIT_LIST_HEAD(¬if_wait->notif_waits);
init_waitqueue_head(¬if_wait->notif_waitq);
}
void iwl_notification_wait_notify(struct iwl_notif_wait_data *notif_wait,
struct iwl_rx_packet *pkt)
{
if (!list_empty(¬if_wait->notif_waits)) {
struct iwl_notification_wait *w;
spin_lock(¬if_wait->notif_wait_lock);
list_for_each_entry(w, ¬if_wait->notif_waits, list) {
if (w->cmd != pkt->hdr.cmd)
continue;
w->triggered = true;
if (w->fn)
w->fn(notif_wait, pkt, w->fn_data);
}
spin_unlock(¬if_wait->notif_wait_lock);
wake_up_all(¬if_wait->notif_waitq);
}
}
void iwl_abort_notification_waits(struct iwl_notif_wait_data *notif_wait)
{
unsigned long flags;
struct iwl_notification_wait *wait_entry;
spin_lock_irqsave(¬if_wait->notif_wait_lock, flags);
list_for_each_entry(wait_entry, ¬if_wait->notif_waits, list)
wait_entry->aborted = true;
spin_unlock_irqrestore(¬if_wait->notif_wait_lock, flags);
wake_up_all(¬if_wait->notif_waitq);
}
void
iwl_init_notification_wait(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry,
u8 cmd,
void (*fn)(struct iwl_notif_wait_data *notif_wait,
struct iwl_rx_packet *pkt, void *data),
void *fn_data)
{
wait_entry->fn = fn;
wait_entry->fn_data = fn_data;
wait_entry->cmd = cmd;
wait_entry->triggered = false;
wait_entry->aborted = false;
spin_lock_bh(¬if_wait->notif_wait_lock);
list_add(&wait_entry->list, ¬if_wait->notif_waits);
spin_unlock_bh(¬if_wait->notif_wait_lock);
}
int iwl_wait_notification(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry,
unsigned long timeout)
{
int ret;
ret = wait_event_timeout(notif_wait->notif_waitq,
wait_entry->triggered || wait_entry->aborted,
timeout);
spin_lock_bh(¬if_wait->notif_wait_lock);
list_del(&wait_entry->list);
spin_unlock_bh(¬if_wait->notif_wait_lock);
if (wait_entry->aborted)
return -EIO;
/* return value is always >= 0 */
if (ret <= 0)
return -ETIMEDOUT;
return 0;
}
void iwl_remove_notification(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry)
{
spin_lock_bh(¬if_wait->notif_wait_lock);
list_del(&wait_entry->list);
spin_unlock_bh(¬if_wait->notif_wait_lock);
}
| gpl-2.0 |
newhor1z0n/furnace_kernel_motorola_falcon | drivers/s390/cio/device_fsm.c | 5073 | 31250 | /*
* drivers/s390/cio/device_fsm.c
* finite state machine for device handling
*
* Copyright IBM Corp. 2002,2008
* Author(s): Cornelia Huck (cornelia.huck@de.ibm.com)
* Martin Schwidefsky (schwidefsky@de.ibm.com)
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/string.h>
#include <asm/ccwdev.h>
#include <asm/cio.h>
#include <asm/chpid.h>
#include "cio.h"
#include "cio_debug.h"
#include "css.h"
#include "device.h"
#include "chsc.h"
#include "ioasm.h"
#include "chp.h"
static int timeout_log_enabled;
static int __init ccw_timeout_log_setup(char *unused)
{
timeout_log_enabled = 1;
return 1;
}
__setup("ccw_timeout_log", ccw_timeout_log_setup);
static void ccw_timeout_log(struct ccw_device *cdev)
{
struct schib schib;
struct subchannel *sch;
struct io_subchannel_private *private;
union orb *orb;
int cc;
sch = to_subchannel(cdev->dev.parent);
private = to_io_private(sch);
orb = &private->orb;
cc = stsch_err(sch->schid, &schib);
printk(KERN_WARNING "cio: ccw device timeout occurred at %llx, "
"device information:\n", get_clock());
printk(KERN_WARNING "cio: orb:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
orb, sizeof(*orb), 0);
printk(KERN_WARNING "cio: ccw device bus id: %s\n",
dev_name(&cdev->dev));
printk(KERN_WARNING "cio: subchannel bus id: %s\n",
dev_name(&sch->dev));
printk(KERN_WARNING "cio: subchannel lpm: %02x, opm: %02x, "
"vpm: %02x\n", sch->lpm, sch->opm, sch->vpm);
if (orb->tm.b) {
printk(KERN_WARNING "cio: orb indicates transport mode\n");
printk(KERN_WARNING "cio: last tcw:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
(void *)(addr_t)orb->tm.tcw,
sizeof(struct tcw), 0);
} else {
printk(KERN_WARNING "cio: orb indicates command mode\n");
if ((void *)(addr_t)orb->cmd.cpa == &private->sense_ccw ||
(void *)(addr_t)orb->cmd.cpa == cdev->private->iccws)
printk(KERN_WARNING "cio: last channel program "
"(intern):\n");
else
printk(KERN_WARNING "cio: last channel program:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
(void *)(addr_t)orb->cmd.cpa,
sizeof(struct ccw1), 0);
}
printk(KERN_WARNING "cio: ccw device state: %d\n",
cdev->private->state);
printk(KERN_WARNING "cio: store subchannel returned: cc=%d\n", cc);
printk(KERN_WARNING "cio: schib:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
&schib, sizeof(schib), 0);
printk(KERN_WARNING "cio: ccw device flags:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
&cdev->private->flags, sizeof(cdev->private->flags), 0);
}
/*
* Timeout function. It just triggers a DEV_EVENT_TIMEOUT.
*/
static void
ccw_device_timeout(unsigned long data)
{
struct ccw_device *cdev;
cdev = (struct ccw_device *) data;
spin_lock_irq(cdev->ccwlock);
if (timeout_log_enabled)
ccw_timeout_log(cdev);
dev_fsm_event(cdev, DEV_EVENT_TIMEOUT);
spin_unlock_irq(cdev->ccwlock);
}
/*
* Set timeout
*/
void
ccw_device_set_timeout(struct ccw_device *cdev, int expires)
{
if (expires == 0) {
del_timer(&cdev->private->timer);
return;
}
if (timer_pending(&cdev->private->timer)) {
if (mod_timer(&cdev->private->timer, jiffies + expires))
return;
}
cdev->private->timer.function = ccw_device_timeout;
cdev->private->timer.data = (unsigned long) cdev;
cdev->private->timer.expires = jiffies + expires;
add_timer(&cdev->private->timer);
}
/*
* Cancel running i/o. This is called repeatedly since halt/clear are
* asynchronous operations. We do one try with cio_cancel, two tries
* with cio_halt, 255 tries with cio_clear. If everythings fails panic.
* Returns 0 if device now idle, -ENODEV for device not operational and
* -EBUSY if an interrupt is expected (either from halt/clear or from a
* status pending).
*/
int
ccw_device_cancel_halt_clear(struct ccw_device *cdev)
{
struct subchannel *sch;
int ret;
sch = to_subchannel(cdev->dev.parent);
if (cio_update_schib(sch))
return -ENODEV;
if (!sch->schib.pmcw.ena)
/* Not operational -> done. */
return 0;
/* Stage 1: cancel io. */
if (!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_HALT_PEND) &&
!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_CLEAR_PEND)) {
if (!scsw_is_tm(&sch->schib.scsw)) {
ret = cio_cancel(sch);
if (ret != -EINVAL)
return ret;
}
/* cancel io unsuccessful or not applicable (transport mode).
* Continue with asynchronous instructions. */
cdev->private->iretry = 3; /* 3 halt retries. */
}
if (!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_CLEAR_PEND)) {
/* Stage 2: halt io. */
if (cdev->private->iretry) {
cdev->private->iretry--;
ret = cio_halt(sch);
if (ret != -EBUSY)
return (ret == 0) ? -EBUSY : ret;
}
/* halt io unsuccessful. */
cdev->private->iretry = 255; /* 255 clear retries. */
}
/* Stage 3: clear io. */
if (cdev->private->iretry) {
cdev->private->iretry--;
ret = cio_clear (sch);
return (ret == 0) ? -EBUSY : ret;
}
/* Function was unsuccessful */
CIO_MSG_EVENT(0, "0.%x.%04x: could not stop I/O\n",
cdev->private->dev_id.ssid, cdev->private->dev_id.devno);
return -EIO;
}
void ccw_device_update_sense_data(struct ccw_device *cdev)
{
memset(&cdev->id, 0, sizeof(cdev->id));
cdev->id.cu_type = cdev->private->senseid.cu_type;
cdev->id.cu_model = cdev->private->senseid.cu_model;
cdev->id.dev_type = cdev->private->senseid.dev_type;
cdev->id.dev_model = cdev->private->senseid.dev_model;
}
int ccw_device_test_sense_data(struct ccw_device *cdev)
{
return cdev->id.cu_type == cdev->private->senseid.cu_type &&
cdev->id.cu_model == cdev->private->senseid.cu_model &&
cdev->id.dev_type == cdev->private->senseid.dev_type &&
cdev->id.dev_model == cdev->private->senseid.dev_model;
}
/*
* The machine won't give us any notification by machine check if a chpid has
* been varied online on the SE so we have to find out by magic (i. e. driving
* the channel subsystem to device selection and updating our path masks).
*/
static void
__recover_lost_chpids(struct subchannel *sch, int old_lpm)
{
int mask, i;
struct chp_id chpid;
chp_id_init(&chpid);
for (i = 0; i<8; i++) {
mask = 0x80 >> i;
if (!(sch->lpm & mask))
continue;
if (old_lpm & mask)
continue;
chpid.id = sch->schib.pmcw.chpid[i];
if (!chp_is_registered(chpid))
css_schedule_eval_all();
}
}
/*
* Stop device recognition.
*/
static void
ccw_device_recog_done(struct ccw_device *cdev, int state)
{
struct subchannel *sch;
int old_lpm;
sch = to_subchannel(cdev->dev.parent);
if (cio_disable_subchannel(sch))
state = DEV_STATE_NOT_OPER;
/*
* Now that we tried recognition, we have performed device selection
* through ssch() and the path information is up to date.
*/
old_lpm = sch->lpm;
/* Check since device may again have become not operational. */
if (cio_update_schib(sch))
state = DEV_STATE_NOT_OPER;
else
sch->lpm = sch->schib.pmcw.pam & sch->opm;
if (cdev->private->state == DEV_STATE_DISCONNECTED_SENSE_ID)
/* Force reprobe on all chpids. */
old_lpm = 0;
if (sch->lpm != old_lpm)
__recover_lost_chpids(sch, old_lpm);
if (cdev->private->state == DEV_STATE_DISCONNECTED_SENSE_ID &&
(state == DEV_STATE_NOT_OPER || state == DEV_STATE_BOXED)) {
cdev->private->flags.recog_done = 1;
cdev->private->state = DEV_STATE_DISCONNECTED;
wake_up(&cdev->private->wait_q);
return;
}
if (cdev->private->flags.resuming) {
cdev->private->state = state;
cdev->private->flags.recog_done = 1;
wake_up(&cdev->private->wait_q);
return;
}
switch (state) {
case DEV_STATE_NOT_OPER:
break;
case DEV_STATE_OFFLINE:
if (!cdev->online) {
ccw_device_update_sense_data(cdev);
break;
}
cdev->private->state = DEV_STATE_OFFLINE;
cdev->private->flags.recog_done = 1;
if (ccw_device_test_sense_data(cdev)) {
cdev->private->flags.donotify = 1;
ccw_device_online(cdev);
wake_up(&cdev->private->wait_q);
} else {
ccw_device_update_sense_data(cdev);
ccw_device_sched_todo(cdev, CDEV_TODO_REBIND);
}
return;
case DEV_STATE_BOXED:
if (cdev->id.cu_type != 0) { /* device was recognized before */
cdev->private->flags.recog_done = 1;
cdev->private->state = DEV_STATE_BOXED;
wake_up(&cdev->private->wait_q);
return;
}
break;
}
cdev->private->state = state;
io_subchannel_recog_done(cdev);
wake_up(&cdev->private->wait_q);
}
/*
* Function called from device_id.c after sense id has completed.
*/
void
ccw_device_sense_id_done(struct ccw_device *cdev, int err)
{
switch (err) {
case 0:
ccw_device_recog_done(cdev, DEV_STATE_OFFLINE);
break;
case -ETIME: /* Sense id stopped by timeout. */
ccw_device_recog_done(cdev, DEV_STATE_BOXED);
break;
default:
ccw_device_recog_done(cdev, DEV_STATE_NOT_OPER);
break;
}
}
/**
* ccw_device_notify() - inform the device's driver about an event
* @cdev: device for which an event occurred
* @event: event that occurred
*
* Returns:
* -%EINVAL if the device is offline or has no driver.
* -%EOPNOTSUPP if the device's driver has no notifier registered.
* %NOTIFY_OK if the driver wants to keep the device.
* %NOTIFY_BAD if the driver doesn't want to keep the device.
*/
int ccw_device_notify(struct ccw_device *cdev, int event)
{
int ret = -EINVAL;
if (!cdev->drv)
goto out;
if (!cdev->online)
goto out;
CIO_MSG_EVENT(2, "notify called for 0.%x.%04x, event=%d\n",
cdev->private->dev_id.ssid, cdev->private->dev_id.devno,
event);
if (!cdev->drv->notify) {
ret = -EOPNOTSUPP;
goto out;
}
if (cdev->drv->notify(cdev, event))
ret = NOTIFY_OK;
else
ret = NOTIFY_BAD;
out:
return ret;
}
static void ccw_device_oper_notify(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
if (ccw_device_notify(cdev, CIO_OPER) == NOTIFY_OK) {
/* Reenable channel measurements, if needed. */
ccw_device_sched_todo(cdev, CDEV_TODO_ENABLE_CMF);
/* Save indication for new paths. */
cdev->private->path_new_mask = sch->vpm;
return;
}
/* Driver doesn't want device back. */
ccw_device_set_notoper(cdev);
ccw_device_sched_todo(cdev, CDEV_TODO_REBIND);
}
/*
* Finished with online/offline processing.
*/
static void
ccw_device_done(struct ccw_device *cdev, int state)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
ccw_device_set_timeout(cdev, 0);
if (state != DEV_STATE_ONLINE)
cio_disable_subchannel(sch);
/* Reset device status. */
memset(&cdev->private->irb, 0, sizeof(struct irb));
cdev->private->state = state;
switch (state) {
case DEV_STATE_BOXED:
CIO_MSG_EVENT(0, "Boxed device %04x on subchannel %04x\n",
cdev->private->dev_id.devno, sch->schid.sch_no);
if (cdev->online &&
ccw_device_notify(cdev, CIO_BOXED) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
cdev->private->flags.donotify = 0;
break;
case DEV_STATE_NOT_OPER:
CIO_MSG_EVENT(0, "Device %04x gone on subchannel %04x\n",
cdev->private->dev_id.devno, sch->schid.sch_no);
if (ccw_device_notify(cdev, CIO_GONE) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
else
ccw_device_set_disconnected(cdev);
cdev->private->flags.donotify = 0;
break;
case DEV_STATE_DISCONNECTED:
CIO_MSG_EVENT(0, "Disconnected device %04x on subchannel "
"%04x\n", cdev->private->dev_id.devno,
sch->schid.sch_no);
if (ccw_device_notify(cdev, CIO_NO_PATH) != NOTIFY_OK) {
cdev->private->state = DEV_STATE_NOT_OPER;
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
} else
ccw_device_set_disconnected(cdev);
cdev->private->flags.donotify = 0;
break;
default:
break;
}
if (cdev->private->flags.donotify) {
cdev->private->flags.donotify = 0;
ccw_device_oper_notify(cdev);
}
wake_up(&cdev->private->wait_q);
}
/*
* Start device recognition.
*/
void ccw_device_recognition(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
/*
* We used to start here with a sense pgid to find out whether a device
* is locked by someone else. Unfortunately, the sense pgid command
* code has other meanings on devices predating the path grouping
* algorithm, so we start with sense id and box the device after an
* timeout (or if sense pgid during path verification detects the device
* is locked, as may happen on newer devices).
*/
cdev->private->flags.recog_done = 0;
cdev->private->state = DEV_STATE_SENSE_ID;
if (cio_enable_subchannel(sch, (u32) (addr_t) sch)) {
ccw_device_recog_done(cdev, DEV_STATE_NOT_OPER);
return;
}
ccw_device_sense_id_start(cdev);
}
/*
* Handle events for states that use the ccw request infrastructure.
*/
static void ccw_device_request_event(struct ccw_device *cdev, enum dev_event e)
{
switch (e) {
case DEV_EVENT_NOTOPER:
ccw_request_notoper(cdev);
break;
case DEV_EVENT_INTERRUPT:
ccw_request_handler(cdev);
break;
case DEV_EVENT_TIMEOUT:
ccw_request_timeout(cdev);
break;
default:
break;
}
}
static void ccw_device_report_path_events(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
int path_event[8];
int chp, mask;
for (chp = 0, mask = 0x80; chp < 8; chp++, mask >>= 1) {
path_event[chp] = PE_NONE;
if (mask & cdev->private->path_gone_mask & ~(sch->vpm))
path_event[chp] |= PE_PATH_GONE;
if (mask & cdev->private->path_new_mask & sch->vpm)
path_event[chp] |= PE_PATH_AVAILABLE;
if (mask & cdev->private->pgid_reset_mask & sch->vpm)
path_event[chp] |= PE_PATHGROUP_ESTABLISHED;
}
if (cdev->online && cdev->drv->path_event)
cdev->drv->path_event(cdev, path_event);
}
static void ccw_device_reset_path_events(struct ccw_device *cdev)
{
cdev->private->path_gone_mask = 0;
cdev->private->path_new_mask = 0;
cdev->private->pgid_reset_mask = 0;
}
static void create_fake_irb(struct irb *irb, int type)
{
memset(irb, 0, sizeof(*irb));
if (type == FAKE_CMD_IRB) {
struct cmd_scsw *scsw = &irb->scsw.cmd;
scsw->cc = 1;
scsw->fctl = SCSW_FCTL_START_FUNC;
scsw->actl = SCSW_ACTL_START_PEND;
scsw->stctl = SCSW_STCTL_STATUS_PEND;
} else if (type == FAKE_TM_IRB) {
struct tm_scsw *scsw = &irb->scsw.tm;
scsw->x = 1;
scsw->cc = 1;
scsw->fctl = SCSW_FCTL_START_FUNC;
scsw->actl = SCSW_ACTL_START_PEND;
scsw->stctl = SCSW_STCTL_STATUS_PEND;
}
}
void ccw_device_verify_done(struct ccw_device *cdev, int err)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
/* Update schib - pom may have changed. */
if (cio_update_schib(sch)) {
err = -ENODEV;
goto callback;
}
/* Update lpm with verified path mask. */
sch->lpm = sch->vpm;
/* Repeat path verification? */
if (cdev->private->flags.doverify) {
ccw_device_verify_start(cdev);
return;
}
callback:
switch (err) {
case 0:
ccw_device_done(cdev, DEV_STATE_ONLINE);
/* Deliver fake irb to device driver, if needed. */
if (cdev->private->flags.fake_irb) {
create_fake_irb(&cdev->private->irb,
cdev->private->flags.fake_irb);
cdev->private->flags.fake_irb = 0;
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
&cdev->private->irb);
memset(&cdev->private->irb, 0, sizeof(struct irb));
}
ccw_device_report_path_events(cdev);
break;
case -ETIME:
case -EUSERS:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_BOXED);
break;
case -EACCES:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_DISCONNECTED);
break;
default:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
break;
}
ccw_device_reset_path_events(cdev);
}
/*
* Get device online.
*/
int
ccw_device_online(struct ccw_device *cdev)
{
struct subchannel *sch;
int ret;
if ((cdev->private->state != DEV_STATE_OFFLINE) &&
(cdev->private->state != DEV_STATE_BOXED))
return -EINVAL;
sch = to_subchannel(cdev->dev.parent);
ret = cio_enable_subchannel(sch, (u32)(addr_t)sch);
if (ret != 0) {
/* Couldn't enable the subchannel for i/o. Sick device. */
if (ret == -ENODEV)
dev_fsm_event(cdev, DEV_EVENT_NOTOPER);
return ret;
}
/* Start initial path verification. */
cdev->private->state = DEV_STATE_VERIFY;
ccw_device_verify_start(cdev);
return 0;
}
void
ccw_device_disband_done(struct ccw_device *cdev, int err)
{
switch (err) {
case 0:
ccw_device_done(cdev, DEV_STATE_OFFLINE);
break;
case -ETIME:
ccw_device_done(cdev, DEV_STATE_BOXED);
break;
default:
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
break;
}
}
/*
* Shutdown device.
*/
int
ccw_device_offline(struct ccw_device *cdev)
{
struct subchannel *sch;
/* Allow ccw_device_offline while disconnected. */
if (cdev->private->state == DEV_STATE_DISCONNECTED ||
cdev->private->state == DEV_STATE_NOT_OPER) {
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
return 0;
}
if (cdev->private->state == DEV_STATE_BOXED) {
ccw_device_done(cdev, DEV_STATE_BOXED);
return 0;
}
if (ccw_device_is_orphan(cdev)) {
ccw_device_done(cdev, DEV_STATE_OFFLINE);
return 0;
}
sch = to_subchannel(cdev->dev.parent);
if (cio_update_schib(sch))
return -ENODEV;
if (scsw_actl(&sch->schib.scsw) != 0)
return -EBUSY;
if (cdev->private->state != DEV_STATE_ONLINE)
return -EINVAL;
/* Are we doing path grouping? */
if (!cdev->private->flags.pgroup) {
/* No, set state offline immediately. */
ccw_device_done(cdev, DEV_STATE_OFFLINE);
return 0;
}
/* Start Set Path Group commands. */
cdev->private->state = DEV_STATE_DISBAND_PGID;
ccw_device_disband_start(cdev);
return 0;
}
/*
* Handle not operational event in non-special state.
*/
static void ccw_device_generic_notoper(struct ccw_device *cdev,
enum dev_event dev_event)
{
if (ccw_device_notify(cdev, CIO_GONE) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
else
ccw_device_set_disconnected(cdev);
}
/*
* Handle path verification event in offline state.
*/
static void ccw_device_offline_verify(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
css_schedule_eval(sch->schid);
}
/*
* Handle path verification event.
*/
static void
ccw_device_online_verify(struct ccw_device *cdev, enum dev_event dev_event)
{
struct subchannel *sch;
if (cdev->private->state == DEV_STATE_W4SENSE) {
cdev->private->flags.doverify = 1;
return;
}
sch = to_subchannel(cdev->dev.parent);
/*
* Since we might not just be coming from an interrupt from the
* subchannel we have to update the schib.
*/
if (cio_update_schib(sch)) {
ccw_device_verify_done(cdev, -ENODEV);
return;
}
if (scsw_actl(&sch->schib.scsw) != 0 ||
(scsw_stctl(&sch->schib.scsw) & SCSW_STCTL_STATUS_PEND) ||
(scsw_stctl(&cdev->private->irb.scsw) & SCSW_STCTL_STATUS_PEND)) {
/*
* No final status yet or final status not yet delivered
* to the device driver. Can't do path verification now,
* delay until final status was delivered.
*/
cdev->private->flags.doverify = 1;
return;
}
/* Device is idle, we can do the path verification. */
cdev->private->state = DEV_STATE_VERIFY;
ccw_device_verify_start(cdev);
}
/*
* Handle path verification event in boxed state.
*/
static void ccw_device_boxed_verify(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
if (cdev->online) {
if (cio_enable_subchannel(sch, (u32) (addr_t) sch))
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
else
ccw_device_online_verify(cdev, dev_event);
} else
css_schedule_eval(sch->schid);
}
/*
* Got an interrupt for a normal io (state online).
*/
static void
ccw_device_irq(struct ccw_device *cdev, enum dev_event dev_event)
{
struct irb *irb;
int is_cmd;
irb = (struct irb *)&S390_lowcore.irb;
is_cmd = !scsw_is_tm(&irb->scsw);
/* Check for unsolicited interrupt. */
if (!scsw_is_solicited(&irb->scsw)) {
if (is_cmd && (irb->scsw.cmd.dstat & DEV_STAT_UNIT_CHECK) &&
!irb->esw.esw0.erw.cons) {
/* Unit check but no sense data. Need basic sense. */
if (ccw_device_do_sense(cdev, irb) != 0)
goto call_handler_unsol;
memcpy(&cdev->private->irb, irb, sizeof(struct irb));
cdev->private->state = DEV_STATE_W4SENSE;
cdev->private->intparm = 0;
return;
}
call_handler_unsol:
if (cdev->handler)
cdev->handler (cdev, 0, irb);
if (cdev->private->flags.doverify)
ccw_device_online_verify(cdev, 0);
return;
}
/* Accumulate status and find out if a basic sense is needed. */
ccw_device_accumulate_irb(cdev, irb);
if (is_cmd && cdev->private->flags.dosense) {
if (ccw_device_do_sense(cdev, irb) == 0) {
cdev->private->state = DEV_STATE_W4SENSE;
}
return;
}
/* Call the handler. */
if (ccw_device_call_handler(cdev) && cdev->private->flags.doverify)
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
}
/*
* Got an timeout in online state.
*/
static void
ccw_device_online_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ccw_device_set_timeout(cdev, 0);
cdev->private->iretry = 255;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
cdev->private->state = DEV_STATE_TIMEOUT_KILL;
return;
}
if (ret)
dev_fsm_event(cdev, DEV_EVENT_NOTOPER);
else if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-ETIMEDOUT));
}
/*
* Got an interrupt for a basic sense.
*/
static void
ccw_device_w4sense(struct ccw_device *cdev, enum dev_event dev_event)
{
struct irb *irb;
irb = (struct irb *)&S390_lowcore.irb;
/* Check for unsolicited interrupt. */
if (scsw_stctl(&irb->scsw) ==
(SCSW_STCTL_STATUS_PEND | SCSW_STCTL_ALERT_STATUS)) {
if (scsw_cc(&irb->scsw) == 1)
/* Basic sense hasn't started. Try again. */
ccw_device_do_sense(cdev, irb);
else {
CIO_MSG_EVENT(0, "0.%x.%04x: unsolicited "
"interrupt during w4sense...\n",
cdev->private->dev_id.ssid,
cdev->private->dev_id.devno);
if (cdev->handler)
cdev->handler (cdev, 0, irb);
}
return;
}
/*
* Check if a halt or clear has been issued in the meanwhile. If yes,
* only deliver the halt/clear interrupt to the device driver as if it
* had killed the original request.
*/
if (scsw_fctl(&irb->scsw) &
(SCSW_FCTL_CLEAR_FUNC | SCSW_FCTL_HALT_FUNC)) {
cdev->private->flags.dosense = 0;
memset(&cdev->private->irb, 0, sizeof(struct irb));
ccw_device_accumulate_irb(cdev, irb);
goto call_handler;
}
/* Add basic sense info to irb. */
ccw_device_accumulate_basic_sense(cdev, irb);
if (cdev->private->flags.dosense) {
/* Another basic sense is needed. */
ccw_device_do_sense(cdev, irb);
return;
}
call_handler:
cdev->private->state = DEV_STATE_ONLINE;
/* In case sensing interfered with setting the device online */
wake_up(&cdev->private->wait_q);
/* Call the handler. */
if (ccw_device_call_handler(cdev) && cdev->private->flags.doverify)
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
}
static void
ccw_device_killing_irq(struct ccw_device *cdev, enum dev_event dev_event)
{
ccw_device_set_timeout(cdev, 0);
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
/* OK, i/o is dead now. Call interrupt handler. */
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
static void
ccw_device_killing_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
return;
}
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
void ccw_device_kill_io(struct ccw_device *cdev)
{
int ret;
cdev->private->iretry = 255;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
cdev->private->state = DEV_STATE_TIMEOUT_KILL;
return;
}
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
static void
ccw_device_delay_verify(struct ccw_device *cdev, enum dev_event dev_event)
{
/* Start verification after current task finished. */
cdev->private->flags.doverify = 1;
}
static void
ccw_device_start_id(struct ccw_device *cdev, enum dev_event dev_event)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
if (cio_enable_subchannel(sch, (u32)(addr_t)sch) != 0)
/* Couldn't enable the subchannel for i/o. Sick device. */
return;
cdev->private->state = DEV_STATE_DISCONNECTED_SENSE_ID;
ccw_device_sense_id_start(cdev);
}
void ccw_device_trigger_reprobe(struct ccw_device *cdev)
{
struct subchannel *sch;
if (cdev->private->state != DEV_STATE_DISCONNECTED)
return;
sch = to_subchannel(cdev->dev.parent);
/* Update some values. */
if (cio_update_schib(sch))
return;
/*
* The pim, pam, pom values may not be accurate, but they are the best
* we have before performing device selection :/
*/
sch->lpm = sch->schib.pmcw.pam & sch->opm;
/*
* Use the initial configuration since we can't be shure that the old
* paths are valid.
*/
io_subchannel_init_config(sch);
if (cio_commit_config(sch))
return;
/* We should also udate ssd info, but this has to wait. */
/* Check if this is another device which appeared on the same sch. */
if (sch->schib.pmcw.dev != cdev->private->dev_id.devno)
css_schedule_eval(sch->schid);
else
ccw_device_start_id(cdev, 0);
}
static void ccw_device_disabled_irq(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
/*
* An interrupt in a disabled state means a previous disable was not
* successful - should not happen, but we try to disable again.
*/
cio_disable_subchannel(sch);
}
static void
ccw_device_change_cmfstate(struct ccw_device *cdev, enum dev_event dev_event)
{
retry_set_schib(cdev);
cdev->private->state = DEV_STATE_ONLINE;
dev_fsm_event(cdev, dev_event);
}
static void ccw_device_update_cmfblock(struct ccw_device *cdev,
enum dev_event dev_event)
{
cmf_retry_copy_block(cdev);
cdev->private->state = DEV_STATE_ONLINE;
dev_fsm_event(cdev, dev_event);
}
static void
ccw_device_quiesce_done(struct ccw_device *cdev, enum dev_event dev_event)
{
ccw_device_set_timeout(cdev, 0);
cdev->private->state = DEV_STATE_NOT_OPER;
wake_up(&cdev->private->wait_q);
}
static void
ccw_device_quiesce_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, HZ/10);
} else {
cdev->private->state = DEV_STATE_NOT_OPER;
wake_up(&cdev->private->wait_q);
}
}
/*
* No operation action. This is used e.g. to ignore a timeout event in
* state offline.
*/
static void
ccw_device_nop(struct ccw_device *cdev, enum dev_event dev_event)
{
}
/*
* device statemachine
*/
fsm_func_t *dev_jumptable[NR_DEV_STATES][NR_DEV_EVENTS] = {
[DEV_STATE_NOT_OPER] = {
[DEV_EVENT_NOTOPER] = ccw_device_nop,
[DEV_EVENT_INTERRUPT] = ccw_device_disabled_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_SENSE_PGID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_SENSE_ID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_OFFLINE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_disabled_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_offline_verify,
},
[DEV_STATE_VERIFY] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_delay_verify,
},
[DEV_STATE_ONLINE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_online_timeout,
[DEV_EVENT_VERIFY] = ccw_device_online_verify,
},
[DEV_STATE_W4SENSE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_w4sense,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_online_verify,
},
[DEV_STATE_DISBAND_PGID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_BOXED] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_nop,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_boxed_verify,
},
/* states to wait for i/o completion before doing something */
[DEV_STATE_TIMEOUT_KILL] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_killing_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_killing_timeout,
[DEV_EVENT_VERIFY] = ccw_device_nop, //FIXME
},
[DEV_STATE_QUIESCE] = {
[DEV_EVENT_NOTOPER] = ccw_device_quiesce_done,
[DEV_EVENT_INTERRUPT] = ccw_device_quiesce_done,
[DEV_EVENT_TIMEOUT] = ccw_device_quiesce_timeout,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
/* special states for devices gone not operational */
[DEV_STATE_DISCONNECTED] = {
[DEV_EVENT_NOTOPER] = ccw_device_nop,
[DEV_EVENT_INTERRUPT] = ccw_device_start_id,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_start_id,
},
[DEV_STATE_DISCONNECTED_SENSE_ID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_CMFCHANGE] = {
[DEV_EVENT_NOTOPER] = ccw_device_change_cmfstate,
[DEV_EVENT_INTERRUPT] = ccw_device_change_cmfstate,
[DEV_EVENT_TIMEOUT] = ccw_device_change_cmfstate,
[DEV_EVENT_VERIFY] = ccw_device_change_cmfstate,
},
[DEV_STATE_CMFUPDATE] = {
[DEV_EVENT_NOTOPER] = ccw_device_update_cmfblock,
[DEV_EVENT_INTERRUPT] = ccw_device_update_cmfblock,
[DEV_EVENT_TIMEOUT] = ccw_device_update_cmfblock,
[DEV_EVENT_VERIFY] = ccw_device_update_cmfblock,
},
[DEV_STATE_STEAL_LOCK] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
};
EXPORT_SYMBOL_GPL(ccw_device_set_timeout);
| gpl-2.0 |
hiikezoe/android_kernel_kyocera_msm8960 | sound/soc/pxa/imote2.c | 5073 | 2237 |
#include <linux/module.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include "../codecs/wm8940.h"
#include "pxa2xx-i2s.h"
static int imote2_asoc_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
unsigned int clk = 0;
int ret;
switch (params_rate(params)) {
case 8000:
case 16000:
case 48000:
case 96000:
clk = 12288000;
break;
case 11025:
case 22050:
case 44100:
clk = 11289600;
break;
}
ret = snd_soc_dai_set_sysclk(codec_dai, 0, clk,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
/* set the I2S system clock as input (unused) */
ret = snd_soc_dai_set_sysclk(cpu_dai, PXA2XX_I2S_SYSCLK, clk,
SND_SOC_CLOCK_OUT);
return ret;
}
static struct snd_soc_ops imote2_asoc_ops = {
.hw_params = imote2_asoc_hw_params,
};
static struct snd_soc_dai_link imote2_dai = {
.name = "WM8940",
.stream_name = "WM8940",
.cpu_dai_name = "pxa2xx-i2s",
.codec_dai_name = "wm8940-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm8940-codec.0-0034",
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBS_CFS,
.ops = &imote2_asoc_ops,
};
static struct snd_soc_card imote2 = {
.name = "Imote2",
.owner = THIS_MODULE,
.dai_link = &imote2_dai,
.num_links = 1,
};
static int __devinit imote2_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &imote2;
int ret;
card->dev = &pdev->dev;
ret = snd_soc_register_card(card);
if (ret)
dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n",
ret);
return ret;
}
static int __devexit imote2_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
return 0;
}
static struct platform_driver imote2_driver = {
.driver = {
.name = "imote2-audio",
.owner = THIS_MODULE,
},
.probe = imote2_probe,
.remove = __devexit_p(imote2_remove),
};
module_platform_driver(imote2_driver);
MODULE_AUTHOR("Jonathan Cameron");
MODULE_DESCRIPTION("ALSA SoC Imote 2");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:imote2-audio");
| gpl-2.0 |
xXminiWHOOPERxX/dlxpul-kernel-final | drivers/media/dvb/dm1105/dm1105.c | 5073 | 29946 | /*
* dm1105.c - driver for DVB cards based on SDMC DM1105 PCI chip
*
* Copyright (C) 2008 Igor M. Liplianin <liplianin@me.by>
*
* 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/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <media/rc-core.h>
#include "demux.h"
#include "dmxdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "dvbdev.h"
#include "dvb-pll.h"
#include "stv0299.h"
#include "stv0288.h"
#include "stb6000.h"
#include "si21xx.h"
#include "cx24116.h"
#include "z0194a.h"
#include "ds3000.h"
#define MODULE_NAME "dm1105"
#define UNSET (-1U)
#define DM1105_BOARD_NOAUTO UNSET
#define DM1105_BOARD_UNKNOWN 0
#define DM1105_BOARD_DVBWORLD_2002 1
#define DM1105_BOARD_DVBWORLD_2004 2
#define DM1105_BOARD_AXESS_DM05 3
#define DM1105_BOARD_UNBRANDED_I2C_ON_GPIO 4
/* ----------------------------------------------- */
/*
* PCI ID's
*/
#ifndef PCI_VENDOR_ID_TRIGEM
#define PCI_VENDOR_ID_TRIGEM 0x109f
#endif
#ifndef PCI_VENDOR_ID_AXESS
#define PCI_VENDOR_ID_AXESS 0x195d
#endif
#ifndef PCI_DEVICE_ID_DM1105
#define PCI_DEVICE_ID_DM1105 0x036f
#endif
#ifndef PCI_DEVICE_ID_DW2002
#define PCI_DEVICE_ID_DW2002 0x2002
#endif
#ifndef PCI_DEVICE_ID_DW2004
#define PCI_DEVICE_ID_DW2004 0x2004
#endif
#ifndef PCI_DEVICE_ID_DM05
#define PCI_DEVICE_ID_DM05 0x1105
#endif
/* ----------------------------------------------- */
/* sdmc dm1105 registers */
/* TS Control */
#define DM1105_TSCTR 0x00
#define DM1105_DTALENTH 0x04
/* GPIO Interface */
#define DM1105_GPIOVAL 0x08
#define DM1105_GPIOCTR 0x0c
/* PID serial number */
#define DM1105_PIDN 0x10
/* Odd-even secret key select */
#define DM1105_CWSEL 0x14
/* Host Command Interface */
#define DM1105_HOST_CTR 0x18
#define DM1105_HOST_AD 0x1c
/* PCI Interface */
#define DM1105_CR 0x30
#define DM1105_RST 0x34
#define DM1105_STADR 0x38
#define DM1105_RLEN 0x3c
#define DM1105_WRP 0x40
#define DM1105_INTCNT 0x44
#define DM1105_INTMAK 0x48
#define DM1105_INTSTS 0x4c
/* CW Value */
#define DM1105_ODD 0x50
#define DM1105_EVEN 0x58
/* PID Value */
#define DM1105_PID 0x60
/* IR Control */
#define DM1105_IRCTR 0x64
#define DM1105_IRMODE 0x68
#define DM1105_SYSTEMCODE 0x6c
#define DM1105_IRCODE 0x70
/* Unknown Values */
#define DM1105_ENCRYPT 0x74
#define DM1105_VER 0x7c
/* I2C Interface */
#define DM1105_I2CCTR 0x80
#define DM1105_I2CSTS 0x81
#define DM1105_I2CDAT 0x82
#define DM1105_I2C_RA 0x83
/* ----------------------------------------------- */
/* Interrupt Mask Bits */
#define INTMAK_TSIRQM 0x01
#define INTMAK_HIRQM 0x04
#define INTMAK_IRM 0x08
#define INTMAK_ALLMASK (INTMAK_TSIRQM | \
INTMAK_HIRQM | \
INTMAK_IRM)
#define INTMAK_NONEMASK 0x00
/* Interrupt Status Bits */
#define INTSTS_TSIRQ 0x01
#define INTSTS_HIRQ 0x04
#define INTSTS_IR 0x08
/* IR Control Bits */
#define DM1105_IR_EN 0x01
#define DM1105_SYS_CHK 0x02
#define DM1105_REP_FLG 0x08
/* EEPROM addr */
#define IIC_24C01_addr 0xa0
/* Max board count */
#define DM1105_MAX 0x04
#define DRIVER_NAME "dm1105"
#define DM1105_I2C_GPIO_NAME "dm1105-gpio"
#define DM1105_DMA_PACKETS 47
#define DM1105_DMA_PACKET_LENGTH (128*4)
#define DM1105_DMA_BYTES (128 * 4 * DM1105_DMA_PACKETS)
/* */
#define GPIO08 (1 << 8)
#define GPIO13 (1 << 13)
#define GPIO14 (1 << 14)
#define GPIO15 (1 << 15)
#define GPIO16 (1 << 16)
#define GPIO17 (1 << 17)
#define GPIO_ALL 0x03ffff
/* GPIO's for LNB power control */
#define DM1105_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM1105_LNB_OFF GPIO17
#define DM1105_LNB_13V (GPIO16 | GPIO08)
#define DM1105_LNB_18V GPIO08
/* GPIO's for LNB power control for Axess DM05 */
#define DM05_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM05_LNB_OFF GPIO17/* actually 13v */
#define DM05_LNB_13V GPIO17
#define DM05_LNB_18V (GPIO17 | GPIO16)
/* GPIO's for LNB power control for unbranded with I2C on GPIO */
#define UNBR_LNB_MASK (GPIO17 | GPIO16)
#define UNBR_LNB_OFF 0
#define UNBR_LNB_13V GPIO17
#define UNBR_LNB_18V (GPIO17 | GPIO16)
static unsigned int card[] = {[0 ... 3] = UNSET };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
static int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "enable debugging information for IR decoding");
static unsigned int dm1105_devcount;
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct dm1105_board {
char *name;
struct {
u32 mask, off, v13, v18;
} lnb;
u32 gpio_scl, gpio_sda;
};
struct dm1105_subid {
u16 subvendor;
u16 subdevice;
u32 card;
};
static const struct dm1105_board dm1105_boards[] = {
[DM1105_BOARD_UNKNOWN] = {
.name = "UNKNOWN/GENERIC",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2002] = {
.name = "DVBWorld PCI 2002",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2004] = {
.name = "DVBWorld PCI 2004",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_AXESS_DM05] = {
.name = "Axess/EasyTv DM05",
.lnb = {
.mask = DM05_LNB_MASK,
.off = DM05_LNB_OFF,
.v13 = DM05_LNB_13V,
.v18 = DM05_LNB_18V,
},
},
[DM1105_BOARD_UNBRANDED_I2C_ON_GPIO] = {
.name = "Unbranded DM1105 with i2c on GPIOs",
.lnb = {
.mask = UNBR_LNB_MASK,
.off = UNBR_LNB_OFF,
.v13 = UNBR_LNB_13V,
.v18 = UNBR_LNB_18V,
},
.gpio_scl = GPIO14,
.gpio_sda = GPIO13,
},
};
static const struct dm1105_subid dm1105_subids[] = {
{
.subvendor = 0x0000,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0001,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0000,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x0001,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x195d,
.subdevice = 0x1105,
.card = DM1105_BOARD_AXESS_DM05,
},
};
static void dm1105_card_list(struct pci_dev *pci)
{
int i;
if (0 == pci->subsystem_vendor &&
0 == pci->subsystem_device) {
printk(KERN_ERR
"dm1105: Your board has no valid PCI Subsystem ID\n"
"dm1105: and thus can't be autodetected\n"
"dm1105: Please pass card=<n> insmod option to\n"
"dm1105: workaround that. Redirect complaints to\n"
"dm1105: the vendor of the TV card. Best regards,\n"
"dm1105: -- tux\n");
} else {
printk(KERN_ERR
"dm1105: Your board isn't known (yet) to the driver.\n"
"dm1105: You can try to pick one of the existing\n"
"dm1105: card configs via card=<n> insmod option.\n"
"dm1105: Updating to the latest version might help\n"
"dm1105: as well.\n");
}
printk(KERN_ERR "Here is a list of valid choices for the card=<n> "
"insmod option:\n");
for (i = 0; i < ARRAY_SIZE(dm1105_boards); i++)
printk(KERN_ERR "dm1105: card=%d -> %s\n",
i, dm1105_boards[i].name);
}
/* infrared remote control */
struct infrared {
struct rc_dev *dev;
char input_phys[32];
struct work_struct work;
u32 ir_command;
};
struct dm1105_dev {
/* pci */
struct pci_dev *pdev;
u8 __iomem *io_mem;
/* ir */
struct infrared ir;
/* dvb */
struct dmx_frontend hw_frontend;
struct dmx_frontend mem_frontend;
struct dmxdev dmxdev;
struct dvb_adapter dvb_adapter;
struct dvb_demux demux;
struct dvb_frontend *fe;
struct dvb_net dvbnet;
unsigned int full_ts_users;
unsigned int boardnr;
int nr;
/* i2c */
struct i2c_adapter i2c_adap;
struct i2c_adapter i2c_bb_adap;
struct i2c_algo_bit_data i2c_bit;
/* irq */
struct work_struct work;
struct workqueue_struct *wq;
char wqn[16];
/* dma */
dma_addr_t dma_addr;
unsigned char *ts_buf;
u32 wrp;
u32 nextwrp;
u32 buffer_size;
unsigned int PacketErrorCount;
unsigned int dmarst;
spinlock_t lock;
};
#define dm_io_mem(reg) ((unsigned long)(&dev->io_mem[reg]))
#define dm_readb(reg) inb(dm_io_mem(reg))
#define dm_writeb(reg, value) outb((value), (dm_io_mem(reg)))
#define dm_readw(reg) inw(dm_io_mem(reg))
#define dm_writew(reg, value) outw((value), (dm_io_mem(reg)))
#define dm_readl(reg) inl(dm_io_mem(reg))
#define dm_writel(reg, value) outl((value), (dm_io_mem(reg)))
#define dm_andorl(reg, mask, value) \
outl((inl(dm_io_mem(reg)) & ~(mask)) |\
((value) & (mask)), (dm_io_mem(reg)))
#define dm_setl(reg, bit) dm_andorl((reg), (bit), (bit))
#define dm_clearl(reg, bit) dm_andorl((reg), (bit), 0)
/* The chip has 18 GPIOs. In HOST mode GPIO's used as 15 bit address lines,
so we can use only 3 GPIO's from GPIO15 to GPIO17.
Here I don't check whether HOST is enebled as it is not implemented yet.
*/
static void dm1105_gpio_set(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_setl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_clear(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_clearl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_andor(struct dm1105_dev *dev, u32 mask, u32 val)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_andorl(DM1105_GPIOVAL, mask & 0x0003ffff, val);
}
static u32 dm1105_gpio_get(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
return dm_readl(DM1105_GPIOVAL) & mask & 0x0003ffff;
return 0;
}
static void dm1105_gpio_enable(struct dm1105_dev *dev, u32 mask, int asoutput)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if ((mask & 0x0003ffff) && asoutput)
dm_clearl(DM1105_GPIOCTR, mask & 0x0003ffff);
else if ((mask & 0x0003ffff) && !asoutput)
dm_setl(DM1105_GPIOCTR, mask & 0x0003ffff);
}
static void dm1105_setline(struct dm1105_dev *dev, u32 line, int state)
{
if (state)
dm1105_gpio_enable(dev, line, 0);
else {
dm1105_gpio_enable(dev, line, 1);
dm1105_gpio_clear(dev, line);
}
}
static void dm1105_setsda(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_sda, state);
}
static void dm1105_setscl(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_scl, state);
}
static int dm1105_getsda(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_sda)
? 1 : 0;
}
static int dm1105_getscl(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_scl)
? 1 : 0;
}
static int dm1105_i2c_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg *msgs, int num)
{
struct dm1105_dev *dev ;
int addr, rc, i, j, k, len, byte, data;
u8 status;
dev = i2c_adap->algo_data;
for (i = 0; i < num; i++) {
dm_writeb(DM1105_I2CCTR, 0x00);
if (msgs[i].flags & I2C_M_RD) {
/* read bytes */
addr = msgs[i].addr << 1;
addr |= 1;
dm_writeb(DM1105_I2CDAT, addr);
for (byte = 0; byte < msgs[i].len; byte++)
dm_writeb(DM1105_I2CDAT + byte + 1, 0);
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 55; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 55)
return -1;
for (byte = 0; byte < msgs[i].len; byte++) {
rc = dm_readb(DM1105_I2CDAT + byte + 1);
if (rc < 0)
goto err;
msgs[i].buf[byte] = rc;
}
} else if ((msgs[i].buf[0] == 0xf7) && (msgs[i].addr == 0x55)) {
/* prepaired for cx24116 firmware */
/* Write in small blocks */
len = msgs[i].len - 1;
k = 1;
do {
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
dm_writeb(DM1105_I2CDAT + 1, 0xf7);
for (byte = 0; byte < (len > 48 ? 48 : len); byte++) {
data = msgs[i].buf[k + byte];
dm_writeb(DM1105_I2CDAT + byte + 2, data);
}
dm_writeb(DM1105_I2CCTR, 0x82 + (len > 48 ? 48 : len));
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
k += 48;
len -= 48;
} while (len > 0);
} else {
/* write bytes */
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
for (byte = 0; byte < msgs[i].len; byte++) {
data = msgs[i].buf[byte];
dm_writeb(DM1105_I2CDAT + byte + 1, data);
}
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
}
}
return num;
err:
return rc;
}
static u32 functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm dm1105_algo = {
.master_xfer = dm1105_i2c_xfer,
.functionality = functionality,
};
static inline struct dm1105_dev *feed_to_dm1105_dev(struct dvb_demux_feed *feed)
{
return container_of(feed->demux, struct dm1105_dev, demux);
}
static inline struct dm1105_dev *frontend_to_dm1105_dev(struct dvb_frontend *fe)
{
return container_of(fe->dvb, struct dm1105_dev, dvb_adapter);
}
static int dm1105_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct dm1105_dev *dev = frontend_to_dm1105_dev(fe);
dm1105_gpio_enable(dev, dm1105_boards[dev->boardnr].lnb.mask, 1);
if (voltage == SEC_VOLTAGE_18)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v18);
else if (voltage == SEC_VOLTAGE_13)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v13);
else
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.off);
return 0;
}
static void dm1105_set_dma_addr(struct dm1105_dev *dev)
{
dm_writel(DM1105_STADR, cpu_to_le32(dev->dma_addr));
}
static int __devinit dm1105_dma_map(struct dm1105_dev *dev)
{
dev->ts_buf = pci_alloc_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
&dev->dma_addr);
return !dev->ts_buf;
}
static void dm1105_dma_unmap(struct dm1105_dev *dev)
{
pci_free_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
dev->ts_buf,
dev->dma_addr);
}
static void dm1105_enable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_ALLMASK);
dm_writeb(DM1105_CR, 1);
}
static void dm1105_disable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_IRM);
dm_writeb(DM1105_CR, 0);
}
static int dm1105_start_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (dev->full_ts_users++ == 0)
dm1105_enable_irqs(dev);
return 0;
}
static int dm1105_stop_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (--dev->full_ts_users == 0)
dm1105_disable_irqs(dev);
return 0;
}
/* ir work handler */
static void dm1105_emit_key(struct work_struct *work)
{
struct infrared *ir = container_of(work, struct infrared, work);
u32 ircom = ir->ir_command;
u8 data;
if (ir_debug)
printk(KERN_INFO "%s: received byte 0x%04x\n", __func__, ircom);
data = (ircom >> 8) & 0x7f;
rc_keydown(ir->dev, data, 0);
}
/* work handler */
static void dm1105_dmx_buffer(struct work_struct *work)
{
struct dm1105_dev *dev = container_of(work, struct dm1105_dev, work);
unsigned int nbpackets;
u32 oldwrp = dev->wrp;
u32 nextwrp = dev->nextwrp;
if (!((dev->ts_buf[oldwrp] == 0x47) &&
(dev->ts_buf[oldwrp + 188] == 0x47) &&
(dev->ts_buf[oldwrp + 188 * 2] == 0x47))) {
dev->PacketErrorCount++;
/* bad packet found */
if ((dev->PacketErrorCount >= 2) &&
(dev->dmarst == 0)) {
dm_writeb(DM1105_RST, 1);
dev->wrp = 0;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
return;
}
}
if (nextwrp < oldwrp) {
memcpy(dev->ts_buf + dev->buffer_size, dev->ts_buf, nextwrp);
nbpackets = ((dev->buffer_size - oldwrp) + nextwrp) / 188;
} else
nbpackets = (nextwrp - oldwrp) / 188;
dev->wrp = nextwrp;
dvb_dmx_swfilter_packets(&dev->demux, &dev->ts_buf[oldwrp], nbpackets);
}
static irqreturn_t dm1105_irq(int irq, void *dev_id)
{
struct dm1105_dev *dev = dev_id;
/* Read-Write INSTS Ack's Interrupt for DM1105 chip 16.03.2008 */
unsigned int intsts = dm_readb(DM1105_INTSTS);
dm_writeb(DM1105_INTSTS, intsts);
switch (intsts) {
case INTSTS_TSIRQ:
case (INTSTS_TSIRQ | INTSTS_IR):
dev->nextwrp = dm_readl(DM1105_WRP) - dm_readl(DM1105_STADR);
queue_work(dev->wq, &dev->work);
break;
case INTSTS_IR:
dev->ir.ir_command = dm_readl(DM1105_IRCODE);
schedule_work(&dev->ir.work);
break;
}
return IRQ_HANDLED;
}
int __devinit dm1105_ir_init(struct dm1105_dev *dm1105)
{
struct rc_dev *dev;
int err = -ENOMEM;
dev = rc_allocate_device();
if (!dev)
return -ENOMEM;
snprintf(dm1105->ir.input_phys, sizeof(dm1105->ir.input_phys),
"pci-%s/ir0", pci_name(dm1105->pdev));
dev->driver_name = MODULE_NAME;
dev->map_name = RC_MAP_DM1105_NEC;
dev->driver_type = RC_DRIVER_SCANCODE;
dev->input_name = "DVB on-card IR receiver";
dev->input_phys = dm1105->ir.input_phys;
dev->input_id.bustype = BUS_PCI;
dev->input_id.version = 1;
if (dm1105->pdev->subsystem_vendor) {
dev->input_id.vendor = dm1105->pdev->subsystem_vendor;
dev->input_id.product = dm1105->pdev->subsystem_device;
} else {
dev->input_id.vendor = dm1105->pdev->vendor;
dev->input_id.product = dm1105->pdev->device;
}
dev->dev.parent = &dm1105->pdev->dev;
INIT_WORK(&dm1105->ir.work, dm1105_emit_key);
err = rc_register_device(dev);
if (err < 0) {
rc_free_device(dev);
return err;
}
dm1105->ir.dev = dev;
return 0;
}
void __devexit dm1105_ir_exit(struct dm1105_dev *dm1105)
{
rc_unregister_device(dm1105->ir.dev);
}
static int __devinit dm1105_hw_init(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
dm_writeb(DM1105_HOST_CTR, 0);
/*DATALEN 188,*/
dm_writeb(DM1105_DTALENTH, 188);
/*TS_STRT TS_VALP MSBFIRST TS_MODE ALPAS TSPES*/
dm_writew(DM1105_TSCTR, 0xc10a);
/* map DMA and set address */
dm1105_dma_map(dev);
dm1105_set_dma_addr(dev);
/* big buffer */
dm_writel(DM1105_RLEN, 5 * DM1105_DMA_BYTES);
dm_writeb(DM1105_INTCNT, 47);
/* IR NEC mode enable */
dm_writeb(DM1105_IRCTR, (DM1105_IR_EN | DM1105_SYS_CHK));
dm_writeb(DM1105_IRMODE, 0);
dm_writew(DM1105_SYSTEMCODE, 0);
return 0;
}
static void dm1105_hw_exit(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
/* IR disable */
dm_writeb(DM1105_IRCTR, 0);
dm_writeb(DM1105_INTMAK, INTMAK_NONEMASK);
dm1105_dma_unmap(dev);
}
static struct stv0299_config sharp_z0194a_config = {
.demod_address = 0x68,
.inittab = sharp_z0194a_inittab,
.mclk = 88000000UL,
.invert = 1,
.skip_reinit = 0,
.lock_output = STV0299_LOCKOUTPUT_1,
.volt13_op0_op1 = STV0299_VOLT13_OP1,
.min_delay_ms = 100,
.set_symbol_rate = sharp_z0194a_set_symbol_rate,
};
static struct stv0288_config earda_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct si21xx_config serit_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct cx24116_config serit_sp2633_config = {
.demod_address = 0x55,
};
static struct ds3000_config dvbworld_ds3000_config = {
.demod_address = 0x68,
};
static int __devinit frontend_init(struct dm1105_dev *dev)
{
int ret;
switch (dev->boardnr) {
case DM1105_BOARD_UNBRANDED_I2C_ON_GPIO:
dm1105_gpio_enable(dev, GPIO15, 1);
dm1105_gpio_clear(dev, GPIO15);
msleep(100);
dm1105_gpio_set(dev, GPIO15);
msleep(200);
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_bb_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_bb_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_bb_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
case DM1105_BOARD_DVBWORLD_2004:
dev->fe = dvb_attach(
cx24116_attach, &serit_sp2633_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
}
dev->fe = dvb_attach(
ds3000_attach, &dvbworld_ds3000_config,
&dev->i2c_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
case DM1105_BOARD_DVBWORLD_2002:
case DM1105_BOARD_AXESS_DM05:
default:
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
}
if (!dev->fe) {
dev_err(&dev->pdev->dev, "could not attach frontend\n");
return -ENODEV;
}
ret = dvb_register_frontend(&dev->dvb_adapter, dev->fe);
if (ret < 0) {
if (dev->fe->ops.release)
dev->fe->ops.release(dev->fe);
dev->fe = NULL;
return ret;
}
return 0;
}
static void __devinit dm1105_read_mac(struct dm1105_dev *dev, u8 *mac)
{
static u8 command[1] = { 0x28 };
struct i2c_msg msg[] = {
{
.addr = IIC_24C01_addr >> 1,
.flags = 0,
.buf = command,
.len = 1
}, {
.addr = IIC_24C01_addr >> 1,
.flags = I2C_M_RD,
.buf = mac,
.len = 6
},
};
dm1105_i2c_xfer(&dev->i2c_adap, msg , 2);
dev_info(&dev->pdev->dev, "MAC %pM\n", mac);
}
static int __devinit dm1105_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct dm1105_dev *dev;
struct dvb_adapter *dvb_adapter;
struct dvb_demux *dvbdemux;
struct dmx_demux *dmx;
int ret = -ENOMEM;
int i;
dev = kzalloc(sizeof(struct dm1105_dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
/* board config */
dev->nr = dm1105_devcount;
dev->boardnr = UNSET;
if (card[dev->nr] < ARRAY_SIZE(dm1105_boards))
dev->boardnr = card[dev->nr];
for (i = 0; UNSET == dev->boardnr &&
i < ARRAY_SIZE(dm1105_subids); i++)
if (pdev->subsystem_vendor ==
dm1105_subids[i].subvendor &&
pdev->subsystem_device ==
dm1105_subids[i].subdevice)
dev->boardnr = dm1105_subids[i].card;
if (UNSET == dev->boardnr) {
dev->boardnr = DM1105_BOARD_UNKNOWN;
dm1105_card_list(pdev);
}
dm1105_devcount++;
dev->pdev = pdev;
dev->buffer_size = 5 * DM1105_DMA_BYTES;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
ret = pci_enable_device(pdev);
if (ret < 0)
goto err_kfree;
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret < 0)
goto err_pci_disable_device;
pci_set_master(pdev);
ret = pci_request_regions(pdev, DRIVER_NAME);
if (ret < 0)
goto err_pci_disable_device;
dev->io_mem = pci_iomap(pdev, 0, pci_resource_len(pdev, 0));
if (!dev->io_mem) {
ret = -EIO;
goto err_pci_release_regions;
}
spin_lock_init(&dev->lock);
pci_set_drvdata(pdev, dev);
ret = dm1105_hw_init(dev);
if (ret < 0)
goto err_pci_iounmap;
/* i2c */
i2c_set_adapdata(&dev->i2c_adap, dev);
strcpy(dev->i2c_adap.name, DRIVER_NAME);
dev->i2c_adap.owner = THIS_MODULE;
dev->i2c_adap.dev.parent = &pdev->dev;
dev->i2c_adap.algo = &dm1105_algo;
dev->i2c_adap.algo_data = dev;
ret = i2c_add_adapter(&dev->i2c_adap);
if (ret < 0)
goto err_dm1105_hw_exit;
i2c_set_adapdata(&dev->i2c_bb_adap, dev);
strcpy(dev->i2c_bb_adap.name, DM1105_I2C_GPIO_NAME);
dev->i2c_bb_adap.owner = THIS_MODULE;
dev->i2c_bb_adap.dev.parent = &pdev->dev;
dev->i2c_bb_adap.algo_data = &dev->i2c_bit;
dev->i2c_bit.data = dev;
dev->i2c_bit.setsda = dm1105_setsda;
dev->i2c_bit.setscl = dm1105_setscl;
dev->i2c_bit.getsda = dm1105_getsda;
dev->i2c_bit.getscl = dm1105_getscl;
dev->i2c_bit.udelay = 10;
dev->i2c_bit.timeout = 10;
/* Raise SCL and SDA */
dm1105_setsda(dev, 1);
dm1105_setscl(dev, 1);
ret = i2c_bit_add_bus(&dev->i2c_bb_adap);
if (ret < 0)
goto err_i2c_del_adapter;
/* dvb */
ret = dvb_register_adapter(&dev->dvb_adapter, DRIVER_NAME,
THIS_MODULE, &pdev->dev, adapter_nr);
if (ret < 0)
goto err_i2c_del_adapters;
dvb_adapter = &dev->dvb_adapter;
dm1105_read_mac(dev, dvb_adapter->proposed_mac);
dvbdemux = &dev->demux;
dvbdemux->filternum = 256;
dvbdemux->feednum = 256;
dvbdemux->start_feed = dm1105_start_feed;
dvbdemux->stop_feed = dm1105_stop_feed;
dvbdemux->dmx.capabilities = (DMX_TS_FILTERING |
DMX_SECTION_FILTERING | DMX_MEMORY_BASED_FILTERING);
ret = dvb_dmx_init(dvbdemux);
if (ret < 0)
goto err_dvb_unregister_adapter;
dmx = &dvbdemux->dmx;
dev->dmxdev.filternum = 256;
dev->dmxdev.demux = dmx;
dev->dmxdev.capabilities = 0;
ret = dvb_dmxdev_init(&dev->dmxdev, dvb_adapter);
if (ret < 0)
goto err_dvb_dmx_release;
dev->hw_frontend.source = DMX_FRONTEND_0;
ret = dmx->add_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_dvb_dmxdev_release;
dev->mem_frontend.source = DMX_MEMORY_FE;
ret = dmx->add_frontend(dmx, &dev->mem_frontend);
if (ret < 0)
goto err_remove_hw_frontend;
ret = dmx->connect_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_remove_mem_frontend;
ret = dvb_net_init(dvb_adapter, &dev->dvbnet, dmx);
if (ret < 0)
goto err_disconnect_frontend;
ret = frontend_init(dev);
if (ret < 0)
goto err_dvb_net;
dm1105_ir_init(dev);
INIT_WORK(&dev->work, dm1105_dmx_buffer);
sprintf(dev->wqn, "%s/%d", dvb_adapter->name, dvb_adapter->num);
dev->wq = create_singlethread_workqueue(dev->wqn);
if (!dev->wq)
goto err_dvb_net;
ret = request_irq(pdev->irq, dm1105_irq, IRQF_SHARED,
DRIVER_NAME, dev);
if (ret < 0)
goto err_workqueue;
return 0;
err_workqueue:
destroy_workqueue(dev->wq);
err_dvb_net:
dvb_net_release(&dev->dvbnet);
err_disconnect_frontend:
dmx->disconnect_frontend(dmx);
err_remove_mem_frontend:
dmx->remove_frontend(dmx, &dev->mem_frontend);
err_remove_hw_frontend:
dmx->remove_frontend(dmx, &dev->hw_frontend);
err_dvb_dmxdev_release:
dvb_dmxdev_release(&dev->dmxdev);
err_dvb_dmx_release:
dvb_dmx_release(dvbdemux);
err_dvb_unregister_adapter:
dvb_unregister_adapter(dvb_adapter);
err_i2c_del_adapters:
i2c_del_adapter(&dev->i2c_bb_adap);
err_i2c_del_adapter:
i2c_del_adapter(&dev->i2c_adap);
err_dm1105_hw_exit:
dm1105_hw_exit(dev);
err_pci_iounmap:
pci_iounmap(pdev, dev->io_mem);
err_pci_release_regions:
pci_release_regions(pdev);
err_pci_disable_device:
pci_disable_device(pdev);
err_kfree:
pci_set_drvdata(pdev, NULL);
kfree(dev);
return ret;
}
static void __devexit dm1105_remove(struct pci_dev *pdev)
{
struct dm1105_dev *dev = pci_get_drvdata(pdev);
struct dvb_adapter *dvb_adapter = &dev->dvb_adapter;
struct dvb_demux *dvbdemux = &dev->demux;
struct dmx_demux *dmx = &dvbdemux->dmx;
dm1105_ir_exit(dev);
dmx->close(dmx);
dvb_net_release(&dev->dvbnet);
if (dev->fe)
dvb_unregister_frontend(dev->fe);
dmx->disconnect_frontend(dmx);
dmx->remove_frontend(dmx, &dev->mem_frontend);
dmx->remove_frontend(dmx, &dev->hw_frontend);
dvb_dmxdev_release(&dev->dmxdev);
dvb_dmx_release(dvbdemux);
dvb_unregister_adapter(dvb_adapter);
if (&dev->i2c_adap)
i2c_del_adapter(&dev->i2c_adap);
dm1105_hw_exit(dev);
synchronize_irq(pdev->irq);
free_irq(pdev->irq, dev);
pci_iounmap(pdev, dev->io_mem);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
dm1105_devcount--;
kfree(dev);
}
static struct pci_device_id dm1105_id_table[] __devinitdata = {
{
.vendor = PCI_VENDOR_ID_TRIGEM,
.device = PCI_DEVICE_ID_DM1105,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
.vendor = PCI_VENDOR_ID_AXESS,
.device = PCI_DEVICE_ID_DM05,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
/* empty */
},
};
MODULE_DEVICE_TABLE(pci, dm1105_id_table);
static struct pci_driver dm1105_driver = {
.name = DRIVER_NAME,
.id_table = dm1105_id_table,
.probe = dm1105_probe,
.remove = __devexit_p(dm1105_remove),
};
static int __init dm1105_init(void)
{
return pci_register_driver(&dm1105_driver);
}
static void __exit dm1105_exit(void)
{
pci_unregister_driver(&dm1105_driver);
}
module_init(dm1105_init);
module_exit(dm1105_exit);
MODULE_AUTHOR("Igor M. Liplianin <liplianin@me.by>");
MODULE_DESCRIPTION("SDMC DM1105 DVB driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TeamVee/SKernel_Vee | sound/soc/codecs/pcm3008.c | 5073 | 4301 | /*
* ALSA Soc PCM3008 codec support
*
* Author: Hugo Villeneuve
* Copyright (C) 2008 Lyrtech inc
*
* Based on AC97 Soc codec, original copyright follow:
* Copyright 2005 Wolfson Microelectronics PLC.
*
* 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.
*
* Generic PCM3008 support.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include "pcm3008.h"
#define PCM3008_VERSION "0.2"
#define PCM3008_RATES (SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \
SNDRV_PCM_RATE_48000)
static struct snd_soc_dai_driver pcm3008_dai = {
.name = "pcm3008-hifi",
.playback = {
.stream_name = "PCM3008 Playback",
.channels_min = 1,
.channels_max = 2,
.rates = PCM3008_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.capture = {
.stream_name = "PCM3008 Capture",
.channels_min = 1,
.channels_max = 2,
.rates = PCM3008_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
};
static void pcm3008_gpio_free(struct pcm3008_setup_data *setup)
{
gpio_free(setup->dem0_pin);
gpio_free(setup->dem1_pin);
gpio_free(setup->pdad_pin);
gpio_free(setup->pdda_pin);
}
static int pcm3008_soc_probe(struct snd_soc_codec *codec)
{
struct pcm3008_setup_data *setup = codec->dev->platform_data;
int ret = 0;
printk(KERN_INFO "PCM3008 SoC Audio Codec %s\n", PCM3008_VERSION);
/* DEM1 DEM0 DE-EMPHASIS_MODE
* Low Low De-emphasis 44.1 kHz ON
* Low High De-emphasis OFF
* High Low De-emphasis 48 kHz ON
* High High De-emphasis 32 kHz ON
*/
/* Configure DEM0 GPIO (turning OFF DAC De-emphasis). */
ret = gpio_request(setup->dem0_pin, "codec_dem0");
if (ret == 0)
ret = gpio_direction_output(setup->dem0_pin, 1);
if (ret != 0)
goto gpio_err;
/* Configure DEM1 GPIO (turning OFF DAC De-emphasis). */
ret = gpio_request(setup->dem1_pin, "codec_dem1");
if (ret == 0)
ret = gpio_direction_output(setup->dem1_pin, 0);
if (ret != 0)
goto gpio_err;
/* Configure PDAD GPIO. */
ret = gpio_request(setup->pdad_pin, "codec_pdad");
if (ret == 0)
ret = gpio_direction_output(setup->pdad_pin, 1);
if (ret != 0)
goto gpio_err;
/* Configure PDDA GPIO. */
ret = gpio_request(setup->pdda_pin, "codec_pdda");
if (ret == 0)
ret = gpio_direction_output(setup->pdda_pin, 1);
if (ret != 0)
goto gpio_err;
return ret;
gpio_err:
pcm3008_gpio_free(setup);
return ret;
}
static int pcm3008_soc_remove(struct snd_soc_codec *codec)
{
struct pcm3008_setup_data *setup = codec->dev->platform_data;
pcm3008_gpio_free(setup);
return 0;
}
#ifdef CONFIG_PM
static int pcm3008_soc_suspend(struct snd_soc_codec *codec)
{
struct pcm3008_setup_data *setup = codec->dev->platform_data;
gpio_set_value(setup->pdad_pin, 0);
gpio_set_value(setup->pdda_pin, 0);
return 0;
}
static int pcm3008_soc_resume(struct snd_soc_codec *codec)
{
struct pcm3008_setup_data *setup = codec->dev->platform_data;
gpio_set_value(setup->pdad_pin, 1);
gpio_set_value(setup->pdda_pin, 1);
return 0;
}
#else
#define pcm3008_soc_suspend NULL
#define pcm3008_soc_resume NULL
#endif
static struct snd_soc_codec_driver soc_codec_dev_pcm3008 = {
.probe = pcm3008_soc_probe,
.remove = pcm3008_soc_remove,
.suspend = pcm3008_soc_suspend,
.resume = pcm3008_soc_resume,
};
static int __devinit pcm3008_codec_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_pcm3008, &pcm3008_dai, 1);
}
static int __devexit pcm3008_codec_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
MODULE_ALIAS("platform:pcm3008-codec");
static struct platform_driver pcm3008_codec_driver = {
.probe = pcm3008_codec_probe,
.remove = __devexit_p(pcm3008_codec_remove),
.driver = {
.name = "pcm3008-codec",
.owner = THIS_MODULE,
},
};
module_platform_driver(pcm3008_codec_driver);
MODULE_DESCRIPTION("Soc PCM3008 driver");
MODULE_AUTHOR("Hugo Villeneuve");
MODULE_LICENSE("GPL");
| gpl-2.0 |
juldiadia/kernel_stock_g3815 | drivers/hid/hid-gaff.c | 5329 | 4868 | /*
* Force feedback support for GreenAsia (Product ID 0x12) based devices
*
* The devices are distributed under various names and the same USB device ID
* can be used in many game controllers.
*
*
* 0e8f:0012 "GreenAsia Inc. USB Joystick "
* - tested with MANTA Warior MM816 and SpeedLink Strike2 SL-6635.
*
* Copyright (c) 2008 Lukasz Lubojanski <lukasz@lubojanski.info>
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
#ifdef CONFIG_GREENASIA_FF
#include "usbhid/usbhid.h"
struct gaff_device {
struct hid_report *report;
};
static int hid_gaff_play(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct gaff_device *gaff = data;
int left, right;
left = effect->u.rumble.strong_magnitude;
right = effect->u.rumble.weak_magnitude;
dbg_hid("called with 0x%04x 0x%04x", left, right);
left = left * 0xfe / 0xffff;
right = right * 0xfe / 0xffff;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x0;
gaff->report->field[0]->value[2] = right;
gaff->report->field[0]->value[3] = 0;
gaff->report->field[0]->value[4] = left;
gaff->report->field[0]->value[5] = 0;
dbg_hid("running with 0x%02x 0x%02x", left, right);
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
gaff->report->field[0]->value[2] = 0x0;
gaff->report->field[0]->value[4] = 0x0;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
return 0;
}
static int gaff_init(struct hid_device *hid)
{
struct gaff_device *gaff;
struct hid_report *report;
struct hid_input *hidinput = list_entry(hid->inputs.next,
struct hid_input, list);
struct list_head *report_list =
&hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct list_head *report_ptr = report_list;
struct input_dev *dev = hidinput->input;
int error;
if (list_empty(report_list)) {
hid_err(hid, "no output reports found\n");
return -ENODEV;
}
report_ptr = report_ptr->next;
report = list_entry(report_ptr, struct hid_report, list);
if (report->maxfield < 1) {
hid_err(hid, "no fields in the report\n");
return -ENODEV;
}
if (report->field[0]->report_count < 6) {
hid_err(hid, "not enough values in the field\n");
return -ENODEV;
}
gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL);
if (!gaff)
return -ENOMEM;
set_bit(FF_RUMBLE, dev->ffbit);
error = input_ff_create_memless(dev, gaff, hid_gaff_play);
if (error) {
kfree(gaff);
return error;
}
gaff->report = report;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x00;
gaff->report->field[0]->value[2] = 0x00;
gaff->report->field[0]->value[3] = 0x00;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
hid_info(hid, "Force Feedback for GreenAsia 0x12 devices by Lukasz Lubojanski <lukasz@lubojanski.info>\n");
return 0;
}
#else
static inline int gaff_init(struct hid_device *hdev)
{
return 0;
}
#endif
static int ga_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
int ret;
dev_dbg(&hdev->dev, "Greenasia HID hardware probe...");
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err;
}
gaff_init(hdev);
return 0;
err:
return ret;
}
static const struct hid_device_id ga_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012), },
{ }
};
MODULE_DEVICE_TABLE(hid, ga_devices);
static struct hid_driver ga_driver = {
.name = "greenasia",
.id_table = ga_devices,
.probe = ga_probe,
};
static int __init ga_init(void)
{
return hid_register_driver(&ga_driver);
}
static void __exit ga_exit(void)
{
hid_unregister_driver(&ga_driver);
}
module_init(ga_init);
module_exit(ga_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
AOKP/kernel_motorola_msm8960dt | kernel/stacktrace.c | 6865 | 1084 | /*
* kernel/stacktrace.c
*
* Stack trace management functions
*
* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/kallsyms.h>
#include <linux/stacktrace.h>
void print_stack_trace(struct stack_trace *trace, int spaces)
{
int i;
if (WARN_ON(!trace->entries))
return;
for (i = 0; i < trace->nr_entries; i++) {
printk("%*c", 1 + spaces, ' ');
print_ip_sym(trace->entries[i]);
}
}
EXPORT_SYMBOL_GPL(print_stack_trace);
/*
* Architectures that do not implement save_stack_trace_tsk or
* save_stack_trace_regs get this weak alias and a once-per-bootup warning
* (whenever this facility is utilized - for example by procfs):
*/
__weak void
save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace)
{
WARN_ONCE(1, KERN_INFO "save_stack_trace_tsk() not implemented yet.\n");
}
__weak void
save_stack_trace_regs(struct pt_regs *regs, struct stack_trace *trace)
{
WARN_ONCE(1, KERN_INFO "save_stack_trace_regs() not implemented yet.\n");
}
| gpl-2.0 |
thestealth131205/k2_u-ul | arch/tile/lib/cpumask.c | 7889 | 1350 | /*
* Copyright 2010 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.
*/
#include <linux/cpumask.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include <linux/smp.h>
/*
* Allow cropping out bits beyond the end of the array.
* Move to "lib" directory if more clients want to use this routine.
*/
int bitmap_parselist_crop(const char *bp, unsigned long *maskp, int nmaskbits)
{
unsigned a, b;
bitmap_zero(maskp, nmaskbits);
do {
if (!isdigit(*bp))
return -EINVAL;
a = simple_strtoul(bp, (char **)&bp, 10);
b = a;
if (*bp == '-') {
bp++;
if (!isdigit(*bp))
return -EINVAL;
b = simple_strtoul(bp, (char **)&bp, 10);
}
if (!(a <= b))
return -EINVAL;
if (b >= nmaskbits)
b = nmaskbits-1;
while (a <= b) {
set_bit(a, maskp);
a++;
}
if (*bp == ',')
bp++;
} while (*bp != '\0' && *bp != '\n');
return 0;
}
| gpl-2.0 |
zombi-x/grimlock_kernel_asus_tegra3_unified | drivers/char/dtlk.c | 8401 | 16693 | /* -*- linux-c -*-
* dtlk.c - DoubleTalk PC driver for Linux
*
* Original author: Chris Pallotta <chris@allmedia.com>
* Current maintainer: Jim Van Zandt <jrv@vanzandt.mv.com>
*
* 2000-03-18 Jim Van Zandt: Fix polling.
* Eliminate dtlk_timer_active flag and separate dtlk_stop_timer
* function. Don't restart timer in dtlk_timer_tick. Restart timer
* in dtlk_poll after every poll. dtlk_poll returns mask (duh).
* Eliminate unused function dtlk_write_byte. Misc. code cleanups.
*/
/* This driver is for the DoubleTalk PC, a speech synthesizer
manufactured by RC Systems (http://www.rcsys.com/). It was written
based on documentation in their User's Manual file and Developer's
Tools disk.
The DoubleTalk PC contains four voice synthesizers: text-to-speech
(TTS), linear predictive coding (LPC), PCM/ADPCM, and CVSD. It
also has a tone generator. Output data for LPC are written to the
LPC port, and output data for the other modes are written to the
TTS port.
Two kinds of data can be read from the DoubleTalk: status
information (in response to the "\001?" interrogation command) is
read from the TTS port, and index markers (which mark the progress
of the speech) are read from the LPC port. Not all models of the
DoubleTalk PC implement index markers. Both the TTS and LPC ports
can also display status flags.
The DoubleTalk PC generates no interrupts.
These characteristics are mapped into the Unix stream I/O model as
follows:
"write" sends bytes to the TTS port. It is the responsibility of
the user program to switch modes among TTS, PCM/ADPCM, and CVSD.
This driver was written for use with the text-to-speech
synthesizer. If LPC output is needed some day, other minor device
numbers can be used to select among output modes.
"read" gets index markers from the LPC port. If the device does
not implement index markers, the read will fail with error EINVAL.
Status information is available using the DTLK_INTERROGATE ioctl.
*/
#include <linux/module.h>
#define KERNEL
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/errno.h> /* for -EBUSY */
#include <linux/ioport.h> /* for request_region */
#include <linux/delay.h> /* for loops_per_jiffy */
#include <linux/sched.h>
#include <linux/mutex.h>
#include <asm/io.h> /* for inb_p, outb_p, inb, outb, etc. */
#include <asm/uaccess.h> /* for get_user, etc. */
#include <linux/wait.h> /* for wait_queue */
#include <linux/init.h> /* for __init, module_{init,exit} */
#include <linux/poll.h> /* for POLLIN, etc. */
#include <linux/dtlk.h> /* local header file for DoubleTalk values */
#ifdef TRACING
#define TRACE_TEXT(str) printk(str);
#define TRACE_RET printk(")")
#else /* !TRACING */
#define TRACE_TEXT(str) ((void) 0)
#define TRACE_RET ((void) 0)
#endif /* TRACING */
static DEFINE_MUTEX(dtlk_mutex);
static void dtlk_timer_tick(unsigned long data);
static int dtlk_major;
static int dtlk_port_lpc;
static int dtlk_port_tts;
static int dtlk_busy;
static int dtlk_has_indexing;
static unsigned int dtlk_portlist[] =
{0x25e, 0x29e, 0x2de, 0x31e, 0x35e, 0x39e, 0};
static wait_queue_head_t dtlk_process_list;
static DEFINE_TIMER(dtlk_timer, dtlk_timer_tick, 0, 0);
/* prototypes for file_operations struct */
static ssize_t dtlk_read(struct file *, char __user *,
size_t nbytes, loff_t * ppos);
static ssize_t dtlk_write(struct file *, const char __user *,
size_t nbytes, loff_t * ppos);
static unsigned int dtlk_poll(struct file *, poll_table *);
static int dtlk_open(struct inode *, struct file *);
static int dtlk_release(struct inode *, struct file *);
static long dtlk_ioctl(struct file *file,
unsigned int cmd, unsigned long arg);
static const struct file_operations dtlk_fops =
{
.owner = THIS_MODULE,
.read = dtlk_read,
.write = dtlk_write,
.poll = dtlk_poll,
.unlocked_ioctl = dtlk_ioctl,
.open = dtlk_open,
.release = dtlk_release,
.llseek = no_llseek,
};
/* local prototypes */
static int dtlk_dev_probe(void);
static struct dtlk_settings *dtlk_interrogate(void);
static int dtlk_readable(void);
static char dtlk_read_lpc(void);
static char dtlk_read_tts(void);
static int dtlk_writeable(void);
static char dtlk_write_bytes(const char *buf, int n);
static char dtlk_write_tts(char);
/*
static void dtlk_handle_error(char, char, unsigned int);
*/
static ssize_t dtlk_read(struct file *file, char __user *buf,
size_t count, loff_t * ppos)
{
unsigned int minor = iminor(file->f_path.dentry->d_inode);
char ch;
int i = 0, retries;
TRACE_TEXT("(dtlk_read");
/* printk("DoubleTalk PC - dtlk_read()\n"); */
if (minor != DTLK_MINOR || !dtlk_has_indexing)
return -EINVAL;
for (retries = 0; retries < loops_per_jiffy; retries++) {
while (i < count && dtlk_readable()) {
ch = dtlk_read_lpc();
/* printk("dtlk_read() reads 0x%02x\n", ch); */
if (put_user(ch, buf++))
return -EFAULT;
i++;
}
if (i)
return i;
if (file->f_flags & O_NONBLOCK)
break;
msleep_interruptible(100);
}
if (retries == loops_per_jiffy)
printk(KERN_ERR "dtlk_read times out\n");
TRACE_RET;
return -EAGAIN;
}
static ssize_t dtlk_write(struct file *file, const char __user *buf,
size_t count, loff_t * ppos)
{
int i = 0, retries = 0, ch;
TRACE_TEXT("(dtlk_write");
#ifdef TRACING
printk(" \"");
{
int i, ch;
for (i = 0; i < count; i++) {
if (get_user(ch, buf + i))
return -EFAULT;
if (' ' <= ch && ch <= '~')
printk("%c", ch);
else
printk("\\%03o", ch);
}
printk("\"");
}
#endif
if (iminor(file->f_path.dentry->d_inode) != DTLK_MINOR)
return -EINVAL;
while (1) {
while (i < count && !get_user(ch, buf) &&
(ch == DTLK_CLEAR || dtlk_writeable())) {
dtlk_write_tts(ch);
buf++;
i++;
if (i % 5 == 0)
/* We yield our time until scheduled
again. This reduces the transfer
rate to 500 bytes/sec, but that's
still enough to keep up with the
speech synthesizer. */
msleep_interruptible(1);
else {
/* the RDY bit goes zero 2-3 usec
after writing, and goes 1 again
180-190 usec later. Here, we wait
up to 250 usec for the RDY bit to
go nonzero. */
for (retries = 0;
retries < loops_per_jiffy / (4000/HZ);
retries++)
if (inb_p(dtlk_port_tts) &
TTS_WRITABLE)
break;
}
retries = 0;
}
if (i == count)
return i;
if (file->f_flags & O_NONBLOCK)
break;
msleep_interruptible(1);
if (++retries > 10 * HZ) { /* wait no more than 10 sec
from last write */
printk("dtlk: write timeout. "
"inb_p(dtlk_port_tts) = 0x%02x\n",
inb_p(dtlk_port_tts));
TRACE_RET;
return -EBUSY;
}
}
TRACE_RET;
return -EAGAIN;
}
static unsigned int dtlk_poll(struct file *file, poll_table * wait)
{
int mask = 0;
unsigned long expires;
TRACE_TEXT(" dtlk_poll");
/*
static long int j;
printk(".");
printk("<%ld>", jiffies-j);
j=jiffies;
*/
poll_wait(file, &dtlk_process_list, wait);
if (dtlk_has_indexing && dtlk_readable()) {
del_timer(&dtlk_timer);
mask = POLLIN | POLLRDNORM;
}
if (dtlk_writeable()) {
del_timer(&dtlk_timer);
mask |= POLLOUT | POLLWRNORM;
}
/* there are no exception conditions */
/* There won't be any interrupts, so we set a timer instead. */
expires = jiffies + 3*HZ / 100;
mod_timer(&dtlk_timer, expires);
return mask;
}
static void dtlk_timer_tick(unsigned long data)
{
TRACE_TEXT(" dtlk_timer_tick");
wake_up_interruptible(&dtlk_process_list);
}
static long dtlk_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
char __user *argp = (char __user *)arg;
struct dtlk_settings *sp;
char portval;
TRACE_TEXT(" dtlk_ioctl");
switch (cmd) {
case DTLK_INTERROGATE:
mutex_lock(&dtlk_mutex);
sp = dtlk_interrogate();
mutex_unlock(&dtlk_mutex);
if (copy_to_user(argp, sp, sizeof(struct dtlk_settings)))
return -EINVAL;
return 0;
case DTLK_STATUS:
portval = inb_p(dtlk_port_tts);
return put_user(portval, argp);
default:
return -EINVAL;
}
}
/* Note that nobody ever sets dtlk_busy... */
static int dtlk_open(struct inode *inode, struct file *file)
{
TRACE_TEXT("(dtlk_open");
nonseekable_open(inode, file);
switch (iminor(inode)) {
case DTLK_MINOR:
if (dtlk_busy)
return -EBUSY;
return nonseekable_open(inode, file);
default:
return -ENXIO;
}
}
static int dtlk_release(struct inode *inode, struct file *file)
{
TRACE_TEXT("(dtlk_release");
switch (iminor(inode)) {
case DTLK_MINOR:
break;
default:
break;
}
TRACE_RET;
del_timer_sync(&dtlk_timer);
return 0;
}
static int __init dtlk_init(void)
{
int err;
dtlk_port_lpc = 0;
dtlk_port_tts = 0;
dtlk_busy = 0;
dtlk_major = register_chrdev(0, "dtlk", &dtlk_fops);
if (dtlk_major < 0) {
printk(KERN_ERR "DoubleTalk PC - cannot register device\n");
return dtlk_major;
}
err = dtlk_dev_probe();
if (err) {
unregister_chrdev(dtlk_major, "dtlk");
return err;
}
printk(", MAJOR %d\n", dtlk_major);
init_waitqueue_head(&dtlk_process_list);
return 0;
}
static void __exit dtlk_cleanup (void)
{
dtlk_write_bytes("goodbye", 8);
msleep_interruptible(500); /* nap 0.50 sec but
could be awakened
earlier by
signals... */
dtlk_write_tts(DTLK_CLEAR);
unregister_chrdev(dtlk_major, "dtlk");
release_region(dtlk_port_lpc, DTLK_IO_EXTENT);
}
module_init(dtlk_init);
module_exit(dtlk_cleanup);
/* ------------------------------------------------------------------------ */
static int dtlk_readable(void)
{
#ifdef TRACING
printk(" dtlk_readable=%u@%u", inb_p(dtlk_port_lpc) != 0x7f, jiffies);
#endif
return inb_p(dtlk_port_lpc) != 0x7f;
}
static int dtlk_writeable(void)
{
/* TRACE_TEXT(" dtlk_writeable"); */
#ifdef TRACINGMORE
printk(" dtlk_writeable=%u", (inb_p(dtlk_port_tts) & TTS_WRITABLE)!=0);
#endif
return inb_p(dtlk_port_tts) & TTS_WRITABLE;
}
static int __init dtlk_dev_probe(void)
{
unsigned int testval = 0;
int i = 0;
struct dtlk_settings *sp;
if (dtlk_port_lpc | dtlk_port_tts)
return -EBUSY;
for (i = 0; dtlk_portlist[i]; i++) {
#if 0
printk("DoubleTalk PC - Port %03x = %04x\n",
dtlk_portlist[i], (testval = inw_p(dtlk_portlist[i])));
#endif
if (!request_region(dtlk_portlist[i], DTLK_IO_EXTENT,
"dtlk"))
continue;
testval = inw_p(dtlk_portlist[i]);
if ((testval &= 0xfbff) == 0x107f) {
dtlk_port_lpc = dtlk_portlist[i];
dtlk_port_tts = dtlk_port_lpc + 1;
sp = dtlk_interrogate();
printk("DoubleTalk PC at %03x-%03x, "
"ROM version %s, serial number %u",
dtlk_portlist[i], dtlk_portlist[i] +
DTLK_IO_EXTENT - 1,
sp->rom_version, sp->serial_number);
/* put LPC port into known state, so
dtlk_readable() gives valid result */
outb_p(0xff, dtlk_port_lpc);
/* INIT string and index marker */
dtlk_write_bytes("\036\1@\0\0012I\r", 8);
/* posting an index takes 18 msec. Here, we
wait up to 100 msec to see whether it
appears. */
msleep_interruptible(100);
dtlk_has_indexing = dtlk_readable();
#ifdef TRACING
printk(", indexing %d\n", dtlk_has_indexing);
#endif
#ifdef INSCOPE
{
/* This macro records ten samples read from the LPC port, for later display */
#define LOOK \
for (i = 0; i < 10; i++) \
{ \
buffer[b++] = inb_p(dtlk_port_lpc); \
__delay(loops_per_jiffy/(1000000/HZ)); \
}
char buffer[1000];
int b = 0, i, j;
LOOK
outb_p(0xff, dtlk_port_lpc);
buffer[b++] = 0;
LOOK
dtlk_write_bytes("\0012I\r", 4);
buffer[b++] = 0;
__delay(50 * loops_per_jiffy / (1000/HZ));
outb_p(0xff, dtlk_port_lpc);
buffer[b++] = 0;
LOOK
printk("\n");
for (j = 0; j < b; j++)
printk(" %02x", buffer[j]);
printk("\n");
}
#endif /* INSCOPE */
#ifdef OUTSCOPE
{
/* This macro records ten samples read from the TTS port, for later display */
#define LOOK \
for (i = 0; i < 10; i++) \
{ \
buffer[b++] = inb_p(dtlk_port_tts); \
__delay(loops_per_jiffy/(1000000/HZ)); /* 1 us */ \
}
char buffer[1000];
int b = 0, i, j;
mdelay(10); /* 10 ms */
LOOK
outb_p(0x03, dtlk_port_tts);
buffer[b++] = 0;
LOOK
LOOK
printk("\n");
for (j = 0; j < b; j++)
printk(" %02x", buffer[j]);
printk("\n");
}
#endif /* OUTSCOPE */
dtlk_write_bytes("Double Talk found", 18);
return 0;
}
release_region(dtlk_portlist[i], DTLK_IO_EXTENT);
}
printk(KERN_INFO "DoubleTalk PC - not found\n");
return -ENODEV;
}
/*
static void dtlk_handle_error(char op, char rc, unsigned int minor)
{
printk(KERN_INFO"\nDoubleTalk PC - MINOR: %d, OPCODE: %d, ERROR: %d\n",
minor, op, rc);
return;
}
*/
/* interrogate the DoubleTalk PC and return its settings */
static struct dtlk_settings *dtlk_interrogate(void)
{
unsigned char *t;
static char buf[sizeof(struct dtlk_settings) + 1];
int total, i;
static struct dtlk_settings status;
TRACE_TEXT("(dtlk_interrogate");
dtlk_write_bytes("\030\001?", 3);
for (total = 0, i = 0; i < 50; i++) {
buf[total] = dtlk_read_tts();
if (total > 2 && buf[total] == 0x7f)
break;
if (total < sizeof(struct dtlk_settings))
total++;
}
/*
if (i==50) printk("interrogate() read overrun\n");
for (i=0; i<sizeof(buf); i++)
printk(" %02x", buf[i]);
printk("\n");
*/
t = buf;
status.serial_number = t[0] + t[1] * 256; /* serial number is
little endian */
t += 2;
i = 0;
while (*t != '\r') {
status.rom_version[i] = *t;
if (i < sizeof(status.rom_version) - 1)
i++;
t++;
}
status.rom_version[i] = 0;
t++;
status.mode = *t++;
status.punc_level = *t++;
status.formant_freq = *t++;
status.pitch = *t++;
status.speed = *t++;
status.volume = *t++;
status.tone = *t++;
status.expression = *t++;
status.ext_dict_loaded = *t++;
status.ext_dict_status = *t++;
status.free_ram = *t++;
status.articulation = *t++;
status.reverb = *t++;
status.eob = *t++;
status.has_indexing = dtlk_has_indexing;
TRACE_RET;
return &status;
}
static char dtlk_read_tts(void)
{
int portval, retries = 0;
char ch;
TRACE_TEXT("(dtlk_read_tts");
/* verify DT is ready, read char, wait for ACK */
do {
portval = inb_p(dtlk_port_tts);
} while ((portval & TTS_READABLE) == 0 &&
retries++ < DTLK_MAX_RETRIES);
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_read_tts() timeout\n");
ch = inb_p(dtlk_port_tts); /* input from TTS port */
ch &= 0x7f;
outb_p(ch, dtlk_port_tts);
retries = 0;
do {
portval = inb_p(dtlk_port_tts);
} while ((portval & TTS_READABLE) != 0 &&
retries++ < DTLK_MAX_RETRIES);
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_read_tts() timeout\n");
TRACE_RET;
return ch;
}
static char dtlk_read_lpc(void)
{
int retries = 0;
char ch;
TRACE_TEXT("(dtlk_read_lpc");
/* no need to test -- this is only called when the port is readable */
ch = inb_p(dtlk_port_lpc); /* input from LPC port */
outb_p(0xff, dtlk_port_lpc);
/* acknowledging a read takes 3-4
usec. Here, we wait up to 20 usec
for the acknowledgement */
retries = (loops_per_jiffy * 20) / (1000000/HZ);
while (inb_p(dtlk_port_lpc) != 0x7f && --retries > 0);
if (retries == 0)
printk(KERN_ERR "dtlk_read_lpc() timeout\n");
TRACE_RET;
return ch;
}
/* write n bytes to tts port */
static char dtlk_write_bytes(const char *buf, int n)
{
char val = 0;
/* printk("dtlk_write_bytes(\"%-*s\", %d)\n", n, buf, n); */
TRACE_TEXT("(dtlk_write_bytes");
while (n-- > 0)
val = dtlk_write_tts(*buf++);
TRACE_RET;
return val;
}
static char dtlk_write_tts(char ch)
{
int retries = 0;
#ifdef TRACINGMORE
printk(" dtlk_write_tts(");
if (' ' <= ch && ch <= '~')
printk("'%c'", ch);
else
printk("0x%02x", ch);
#endif
if (ch != DTLK_CLEAR) /* no flow control for CLEAR command */
while ((inb_p(dtlk_port_tts) & TTS_WRITABLE) == 0 &&
retries++ < DTLK_MAX_RETRIES) /* DT ready? */
;
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_write_tts() timeout\n");
outb_p(ch, dtlk_port_tts); /* output to TTS port */
/* the RDY bit goes zero 2-3 usec after writing, and goes
1 again 180-190 usec later. Here, we wait up to 10
usec for the RDY bit to go zero. */
for (retries = 0; retries < loops_per_jiffy / (100000/HZ); retries++)
if ((inb_p(dtlk_port_tts) & TTS_WRITABLE) == 0)
break;
#ifdef TRACINGMORE
printk(")\n");
#endif
return 0;
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
cnexus/NexTKernel-d2spr | arch/powerpc/boot/wii.c | 13265 | 3221 | /*
* arch/powerpc/boot/wii.c
*
* Nintendo Wii bootwrapper support
* Copyright (C) 2008-2009 The GameCube Linux Team
* Copyright (C) 2008,2009 Albert Herranz
*
* 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 <stddef.h>
#include "stdio.h"
#include "types.h"
#include "io.h"
#include "ops.h"
#include "ugecon.h"
BSS_STACK(8192);
#define HW_REG(x) ((void *)(x))
#define EXI_CTRL HW_REG(0x0d800070)
#define EXI_CTRL_ENABLE (1<<0)
#define MEM2_TOP (0x10000000 + 64*1024*1024)
#define FIRMWARE_DEFAULT_SIZE (12*1024*1024)
struct mipc_infohdr {
char magic[3];
u8 version;
u32 mem2_boundary;
u32 ipc_in;
size_t ipc_in_size;
u32 ipc_out;
size_t ipc_out_size;
};
static int mipc_check_address(u32 pa)
{
/* only MEM2 addresses */
if (pa < 0x10000000 || pa > 0x14000000)
return -EINVAL;
return 0;
}
static struct mipc_infohdr *mipc_get_infohdr(void)
{
struct mipc_infohdr **hdrp, *hdr;
/* 'mini' header pointer is the last word of MEM2 memory */
hdrp = (struct mipc_infohdr **)0x13fffffc;
if (mipc_check_address((u32)hdrp)) {
printf("mini: invalid hdrp %08X\n", (u32)hdrp);
hdr = NULL;
goto out;
}
hdr = *hdrp;
if (mipc_check_address((u32)hdr)) {
printf("mini: invalid hdr %08X\n", (u32)hdr);
hdr = NULL;
goto out;
}
if (memcmp(hdr->magic, "IPC", 3)) {
printf("mini: invalid magic\n");
hdr = NULL;
goto out;
}
out:
return hdr;
}
static int mipc_get_mem2_boundary(u32 *mem2_boundary)
{
struct mipc_infohdr *hdr;
int error;
hdr = mipc_get_infohdr();
if (!hdr) {
error = -1;
goto out;
}
if (mipc_check_address(hdr->mem2_boundary)) {
printf("mini: invalid mem2_boundary %08X\n",
hdr->mem2_boundary);
error = -EINVAL;
goto out;
}
*mem2_boundary = hdr->mem2_boundary;
error = 0;
out:
return error;
}
static void platform_fixups(void)
{
void *mem;
u32 reg[4];
u32 mem2_boundary;
int len;
int error;
mem = finddevice("/memory");
if (!mem)
fatal("Can't find memory node\n");
/* two ranges of (address, size) words */
len = getprop(mem, "reg", reg, sizeof(reg));
if (len != sizeof(reg)) {
/* nothing to do */
goto out;
}
/* retrieve MEM2 boundary from 'mini' */
error = mipc_get_mem2_boundary(&mem2_boundary);
if (error) {
/* if that fails use a sane value */
mem2_boundary = MEM2_TOP - FIRMWARE_DEFAULT_SIZE;
}
if (mem2_boundary > reg[2] && mem2_boundary < reg[2] + reg[3]) {
reg[3] = mem2_boundary - reg[2];
printf("top of MEM2 @ %08X\n", reg[2] + reg[3]);
setprop(mem, "reg", reg, sizeof(reg));
}
out:
return;
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5)
{
u32 heapsize = 24*1024*1024 - (u32)_end;
simple_alloc_init(_end, heapsize, 32, 64);
fdt_init(_dtb_start);
/*
* 'mini' boots the Broadway processor with EXI disabled.
* We need it enabled before probing for the USB Gecko.
*/
out_be32(EXI_CTRL, in_be32(EXI_CTRL) | EXI_CTRL_ENABLE);
if (ug_probe())
console_ops.write = ug_console_write;
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
virtuous/kernel-7x30-gingerbread-v3 | drivers/isdn/hisax/config.c | 210 | 48207 | /* $Id: config.c,v 2.84.2.5 2004/02/11 13:21:33 keil Exp $
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
* by Kai Germaschewski <kai.germaschewski@gmx.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* For changes and modifications please read
* Documentation/isdn/HiSax.cert
*
* based on the teles driver from Jan den Ouden
*
*/
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/timer.h>
#include <linux/init.h>
#include "hisax.h"
#include <linux/module.h>
#include <linux/kernel_stat.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#define HISAX_STATUS_BUFSIZE 4096
/*
* This structure array contains one entry per card. An entry looks
* like this:
*
* { type, protocol, p0, p1, p2, NULL }
*
* type
* 1 Teles 16.0 p0=irq p1=membase p2=iobase
* 2 Teles 8.0 p0=irq p1=membase
* 3 Teles 16.3 p0=irq p1=iobase
* 4 Creatix PNP p0=irq p1=IO0 (ISAC) p2=IO1 (HSCX)
* 5 AVM A1 (Fritz) p0=irq p1=iobase
* 6 ELSA PC [p0=iobase] or nothing (autodetect)
* 7 ELSA Quickstep p0=irq p1=iobase
* 8 Teles PCMCIA p0=irq p1=iobase
* 9 ITK ix1-micro p0=irq p1=iobase
* 10 ELSA PCMCIA p0=irq p1=iobase
* 11 Eicon.Diehl Diva p0=irq p1=iobase
* 12 Asuscom ISDNLink p0=irq p1=iobase
* 13 Teleint p0=irq p1=iobase
* 14 Teles 16.3c p0=irq p1=iobase
* 15 Sedlbauer speed p0=irq p1=iobase
* 15 Sedlbauer PC/104 p0=irq p1=iobase
* 15 Sedlbauer speed pci no parameter
* 16 USR Sportster internal p0=irq p1=iobase
* 17 MIC card p0=irq p1=iobase
* 18 ELSA Quickstep 1000PCI no parameter
* 19 Compaq ISDN S0 ISA card p0=irq p1=IO0 (HSCX) p2=IO1 (ISAC) p3=IO2
* 20 Travers Technologies NETjet-S PCI card
* 21 TELES PCI no parameter
* 22 Sedlbauer Speed Star p0=irq p1=iobase
* 23 reserved
* 24 Dr Neuhaus Niccy PnP/PCI card p0=irq p1=IO0 p2=IO1 (PnP only)
* 25 Teles S0Box p0=irq p1=iobase (from isapnp setup)
* 26 AVM A1 PCMCIA (Fritz) p0=irq p1=iobase
* 27 AVM PnP/PCI p0=irq p1=iobase (PCI no parameter)
* 28 Sedlbauer Speed Fax+ p0=irq p1=iobase (from isapnp setup)
* 29 Siemens I-Surf p0=irq p1=iobase p2=memory (from isapnp setup)
* 30 ACER P10 p0=irq p1=iobase (from isapnp setup)
* 31 HST Saphir p0=irq p1=iobase
* 32 Telekom A4T none
* 33 Scitel Quadro p0=subcontroller (4*S0, subctrl 1...4)
* 34 Gazel ISDN cards
* 35 HFC 2BDS0 PCI none
* 36 Winbond 6692 PCI none
* 37 HFC 2BDS0 S+/SP p0=irq p1=iobase
* 38 Travers Technologies NETspider-U PCI card
* 39 HFC 2BDS0-SP PCMCIA p0=irq p1=iobase
* 40 hotplug interface
* 41 Formula-n enter:now ISDN PCI a/b none
*
* protocol can be either ISDN_PTYPE_EURO or ISDN_PTYPE_1TR6 or ISDN_PTYPE_NI1
*
*
*/
const char *CardType[] = {
"No Card", "Teles 16.0", "Teles 8.0", "Teles 16.3",
"Creatix/Teles PnP", "AVM A1", "Elsa ML", "Elsa Quickstep",
"Teles PCMCIA", "ITK ix1-micro Rev.2", "Elsa PCMCIA",
"Eicon.Diehl Diva", "ISDNLink", "TeleInt", "Teles 16.3c",
"Sedlbauer Speed Card", "USR Sportster", "ith mic Linux",
"Elsa PCI", "Compaq ISA", "NETjet-S", "Teles PCI",
"Sedlbauer Speed Star (PCMCIA)", "AMD 7930", "NICCY", "S0Box",
"AVM A1 (PCMCIA)", "AVM Fritz PnP/PCI", "Sedlbauer Speed Fax +",
"Siemens I-Surf", "Acer P10", "HST Saphir", "Telekom A4T",
"Scitel Quadro", "Gazel", "HFC 2BDS0 PCI", "Winbond 6692",
"HFC 2BDS0 SX", "NETspider-U", "HFC-2BDS0-SP PCMCIA",
"Hotplug", "Formula-n enter:now PCI a/b",
};
#ifdef CONFIG_HISAX_ELSA
#define DEFAULT_CARD ISDN_CTYPE_ELSA
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_AVM_A1
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_A1
#define DEFAULT_CFG {10,0x340,0,0}
#endif
#ifdef CONFIG_HISAX_AVM_A1_PCMCIA
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_A1_PCMCIA
#define DEFAULT_CFG {11,0x170,0,0}
#endif
#ifdef CONFIG_HISAX_FRITZPCI
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_FRITZPCI
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_16_3
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_16_3
#define DEFAULT_CFG {15,0x180,0,0}
#endif
#ifdef CONFIG_HISAX_S0BOX
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_S0BOX
#define DEFAULT_CFG {7,0x378,0,0}
#endif
#ifdef CONFIG_HISAX_16_0
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_16_0
#define DEFAULT_CFG {15,0xd0000,0xd80,0}
#endif
#ifdef CONFIG_HISAX_TELESPCI
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_TELESPCI
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_IX1MICROR2
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_IX1MICROR2
#define DEFAULT_CFG {5,0x390,0,0}
#endif
#ifdef CONFIG_HISAX_DIEHLDIVA
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_DIEHLDIVA
#define DEFAULT_CFG {0,0x0,0,0}
#endif
#ifdef CONFIG_HISAX_ASUSCOM
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_ASUSCOM
#define DEFAULT_CFG {5,0x200,0,0}
#endif
#ifdef CONFIG_HISAX_TELEINT
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_TELEINT
#define DEFAULT_CFG {5,0x300,0,0}
#endif
#ifdef CONFIG_HISAX_SEDLBAUER
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_SEDLBAUER
#define DEFAULT_CFG {11,0x270,0,0}
#endif
#ifdef CONFIG_HISAX_SPORTSTER
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_SPORTSTER
#define DEFAULT_CFG {7,0x268,0,0}
#endif
#ifdef CONFIG_HISAX_MIC
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_MIC
#define DEFAULT_CFG {12,0x3e0,0,0}
#endif
#ifdef CONFIG_HISAX_NETJET
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_NETJET_S
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_HFCS
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_TELES3C
#define DEFAULT_CFG {5,0x500,0,0}
#endif
#ifdef CONFIG_HISAX_HFC_PCI
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_HFC_PCI
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_HFC_SX
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_HFC_SX
#define DEFAULT_CFG {5,0x2E0,0,0}
#endif
#ifdef CONFIG_HISAX_NICCY
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_NICCY
#define DEFAULT_CFG {0,0x0,0,0}
#endif
#ifdef CONFIG_HISAX_ISURF
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_ISURF
#define DEFAULT_CFG {5,0x100,0xc8000,0}
#endif
#ifdef CONFIG_HISAX_HSTSAPHIR
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_HSTSAPHIR
#define DEFAULT_CFG {5,0x250,0,0}
#endif
#ifdef CONFIG_HISAX_BKM_A4T
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_BKM_A4T
#define DEFAULT_CFG {0,0x0,0,0}
#endif
#ifdef CONFIG_HISAX_SCT_QUADRO
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_SCT_QUADRO
#define DEFAULT_CFG {1,0x0,0,0}
#endif
#ifdef CONFIG_HISAX_GAZEL
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_GAZEL
#define DEFAULT_CFG {15,0x180,0,0}
#endif
#ifdef CONFIG_HISAX_W6692
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_W6692
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_NETJET_U
#undef DEFAULT_CARD
#undef DEFAULT_CFG
#define DEFAULT_CARD ISDN_CTYPE_NETJET_U
#define DEFAULT_CFG {0,0,0,0}
#endif
#ifdef CONFIG_HISAX_1TR6
#define DEFAULT_PROTO ISDN_PTYPE_1TR6
#define DEFAULT_PROTO_NAME "1TR6"
#endif
#ifdef CONFIG_HISAX_NI1
#undef DEFAULT_PROTO
#define DEFAULT_PROTO ISDN_PTYPE_NI1
#undef DEFAULT_PROTO_NAME
#define DEFAULT_PROTO_NAME "NI1"
#endif
#ifdef CONFIG_HISAX_EURO
#undef DEFAULT_PROTO
#define DEFAULT_PROTO ISDN_PTYPE_EURO
#undef DEFAULT_PROTO_NAME
#define DEFAULT_PROTO_NAME "EURO"
#endif
#ifndef DEFAULT_PROTO
#define DEFAULT_PROTO ISDN_PTYPE_UNKNOWN
#define DEFAULT_PROTO_NAME "UNKNOWN"
#endif
#ifndef DEFAULT_CARD
#define DEFAULT_CARD 0
#define DEFAULT_CFG {0,0,0,0}
#endif
#define FIRST_CARD { \
DEFAULT_CARD, \
DEFAULT_PROTO, \
DEFAULT_CFG, \
NULL, \
}
struct IsdnCard cards[HISAX_MAX_CARDS] = {
FIRST_CARD,
};
#define HISAX_IDSIZE (HISAX_MAX_CARDS*8)
static char HiSaxID[HISAX_IDSIZE] = { 0, };
static char *HiSax_id = HiSaxID;
#ifdef MODULE
/* Variables for insmod */
static int type[HISAX_MAX_CARDS] = { 0, };
static int protocol[HISAX_MAX_CARDS] = { 0, };
static int io[HISAX_MAX_CARDS] = { 0, };
#undef IO0_IO1
#ifdef CONFIG_HISAX_16_3
#define IO0_IO1
#endif
#ifdef CONFIG_HISAX_NICCY
#undef IO0_IO1
#define IO0_IO1
#endif
#ifdef IO0_IO1
static int io0[HISAX_MAX_CARDS] __devinitdata = { 0, };
static int io1[HISAX_MAX_CARDS] __devinitdata = { 0, };
#endif
static int irq[HISAX_MAX_CARDS] __devinitdata = { 0, };
static int mem[HISAX_MAX_CARDS] __devinitdata = { 0, };
static char *id = HiSaxID;
MODULE_DESCRIPTION("ISDN4Linux: Driver for passive ISDN cards");
MODULE_AUTHOR("Karsten Keil");
MODULE_LICENSE("GPL");
module_param_array(type, int, NULL, 0);
module_param_array(protocol, int, NULL, 0);
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(mem, int, NULL, 0);
module_param(id, charp, 0);
#ifdef IO0_IO1
module_param_array(io0, int, NULL, 0);
module_param_array(io1, int, NULL, 0);
#endif
#endif /* MODULE */
int nrcards;
char *HiSax_getrev(const char *revision)
{
char *rev;
char *p;
if ((p = strchr(revision, ':'))) {
rev = p + 2;
p = strchr(rev, '$');
*--p = 0;
} else
rev = "???";
return rev;
}
static void __init HiSaxVersion(void)
{
char tmp[64];
printk(KERN_INFO "HiSax: Linux Driver for passive ISDN cards\n");
#ifdef MODULE
printk(KERN_INFO "HiSax: Version 3.5 (module)\n");
#else
printk(KERN_INFO "HiSax: Version 3.5 (kernel)\n");
#endif
strcpy(tmp, l1_revision);
printk(KERN_INFO "HiSax: Layer1 Revision %s\n", HiSax_getrev(tmp));
strcpy(tmp, l2_revision);
printk(KERN_INFO "HiSax: Layer2 Revision %s\n", HiSax_getrev(tmp));
strcpy(tmp, tei_revision);
printk(KERN_INFO "HiSax: TeiMgr Revision %s\n", HiSax_getrev(tmp));
strcpy(tmp, l3_revision);
printk(KERN_INFO "HiSax: Layer3 Revision %s\n", HiSax_getrev(tmp));
strcpy(tmp, lli_revision);
printk(KERN_INFO "HiSax: LinkLayer Revision %s\n",
HiSax_getrev(tmp));
}
#ifndef MODULE
#define MAX_ARG (HISAX_MAX_CARDS*5)
static int __init HiSax_setup(char *line)
{
int i, j, argc;
int ints[MAX_ARG + 1];
char *str;
str = get_options(line, MAX_ARG, ints);
argc = ints[0];
printk(KERN_DEBUG "HiSax_setup: argc(%d) str(%s)\n", argc, str);
i = 0;
j = 1;
while (argc && (i < HISAX_MAX_CARDS)) {
cards[i].protocol = DEFAULT_PROTO;
if (argc) {
cards[i].typ = ints[j];
j++;
argc--;
}
if (argc) {
cards[i].protocol = ints[j];
j++;
argc--;
}
if (argc) {
cards[i].para[0] = ints[j];
j++;
argc--;
}
if (argc) {
cards[i].para[1] = ints[j];
j++;
argc--;
}
if (argc) {
cards[i].para[2] = ints[j];
j++;
argc--;
}
i++;
}
if (str && *str) {
if (strlen(str) < HISAX_IDSIZE)
strcpy(HiSaxID, str);
else
printk(KERN_WARNING "HiSax: ID too long!");
} else
strcpy(HiSaxID, "HiSax");
HiSax_id = HiSaxID;
return 1;
}
__setup("hisax=", HiSax_setup);
#endif /* MODULES */
#if CARD_TELES0
extern int setup_teles0(struct IsdnCard *card);
#endif
#if CARD_TELES3
extern int setup_teles3(struct IsdnCard *card);
#endif
#if CARD_S0BOX
extern int setup_s0box(struct IsdnCard *card);
#endif
#if CARD_TELESPCI
extern int setup_telespci(struct IsdnCard *card);
#endif
#if CARD_AVM_A1
extern int setup_avm_a1(struct IsdnCard *card);
#endif
#if CARD_AVM_A1_PCMCIA
extern int setup_avm_a1_pcmcia(struct IsdnCard *card);
#endif
#if CARD_FRITZPCI
extern int setup_avm_pcipnp(struct IsdnCard *card);
#endif
#if CARD_ELSA
extern int setup_elsa(struct IsdnCard *card);
#endif
#if CARD_IX1MICROR2
extern int setup_ix1micro(struct IsdnCard *card);
#endif
#if CARD_DIEHLDIVA
extern int setup_diva(struct IsdnCard *card);
#endif
#if CARD_ASUSCOM
extern int setup_asuscom(struct IsdnCard *card);
#endif
#if CARD_TELEINT
extern int setup_TeleInt(struct IsdnCard *card);
#endif
#if CARD_SEDLBAUER
extern int setup_sedlbauer(struct IsdnCard *card);
#endif
#if CARD_SPORTSTER
extern int setup_sportster(struct IsdnCard *card);
#endif
#if CARD_MIC
extern int setup_mic(struct IsdnCard *card);
#endif
#if CARD_NETJET_S
extern int setup_netjet_s(struct IsdnCard *card);
#endif
#if CARD_HFCS
extern int setup_hfcs(struct IsdnCard *card);
#endif
#if CARD_HFC_PCI
extern int setup_hfcpci(struct IsdnCard *card);
#endif
#if CARD_HFC_SX
extern int setup_hfcsx(struct IsdnCard *card);
#endif
#if CARD_NICCY
extern int setup_niccy(struct IsdnCard *card);
#endif
#if CARD_ISURF
extern int setup_isurf(struct IsdnCard *card);
#endif
#if CARD_HSTSAPHIR
extern int setup_saphir(struct IsdnCard *card);
#endif
#if CARD_BKM_A4T
extern int setup_bkm_a4t(struct IsdnCard *card);
#endif
#if CARD_SCT_QUADRO
extern int setup_sct_quadro(struct IsdnCard *card);
#endif
#if CARD_GAZEL
extern int setup_gazel(struct IsdnCard *card);
#endif
#if CARD_W6692
extern int setup_w6692(struct IsdnCard *card);
#endif
#if CARD_NETJET_U
extern int setup_netjet_u(struct IsdnCard *card);
#endif
#if CARD_FN_ENTERNOW_PCI
extern int setup_enternow_pci(struct IsdnCard *card);
#endif
/*
* Find card with given driverId
*/
static inline struct IsdnCardState *hisax_findcard(int driverid)
{
int i;
for (i = 0; i < nrcards; i++)
if (cards[i].cs)
if (cards[i].cs->myid == driverid)
return cards[i].cs;
return NULL;
}
/*
* Find card with given card number
*/
#if 0
struct IsdnCardState *hisax_get_card(int cardnr)
{
if ((cardnr <= nrcards) && (cardnr > 0))
if (cards[cardnr - 1].cs)
return cards[cardnr - 1].cs;
return NULL;
}
#endif /* 0 */
static int HiSax_readstatus(u_char __user *buf, int len, int id, int channel)
{
int count, cnt;
u_char __user *p = buf;
struct IsdnCardState *cs = hisax_findcard(id);
if (cs) {
if (len > HISAX_STATUS_BUFSIZE) {
printk(KERN_WARNING
"HiSax: status overflow readstat %d/%d\n",
len, HISAX_STATUS_BUFSIZE);
}
count = cs->status_end - cs->status_read + 1;
if (count >= len)
count = len;
if (copy_to_user(p, cs->status_read, count))
return -EFAULT;
cs->status_read += count;
if (cs->status_read > cs->status_end)
cs->status_read = cs->status_buf;
p += count;
count = len - count;
while (count) {
if (count > HISAX_STATUS_BUFSIZE)
cnt = HISAX_STATUS_BUFSIZE;
else
cnt = count;
if (copy_to_user(p, cs->status_read, cnt))
return -EFAULT;
p += cnt;
cs->status_read += cnt % HISAX_STATUS_BUFSIZE;
count -= cnt;
}
return len;
} else {
printk(KERN_ERR
"HiSax: if_readstatus called with invalid driverId!\n");
return -ENODEV;
}
}
int jiftime(char *s, long mark)
{
s += 8;
*s-- = '\0';
*s-- = mark % 10 + '0';
mark /= 10;
*s-- = mark % 10 + '0';
mark /= 10;
*s-- = '.';
*s-- = mark % 10 + '0';
mark /= 10;
*s-- = mark % 6 + '0';
mark /= 6;
*s-- = ':';
*s-- = mark % 10 + '0';
mark /= 10;
*s-- = mark % 10 + '0';
return 8;
}
static u_char tmpbuf[HISAX_STATUS_BUFSIZE];
void VHiSax_putstatus(struct IsdnCardState *cs, char *head, char *fmt,
va_list args)
{
/* if head == NULL the fmt contains the full info */
u_long flags;
int count, i;
u_char *p;
isdn_ctrl ic;
int len;
if (!cs) {
printk(KERN_WARNING "HiSax: No CardStatus for message");
return;
}
spin_lock_irqsave(&cs->statlock, flags);
p = tmpbuf;
if (head) {
p += jiftime(p, jiffies);
p += sprintf(p, " %s", head);
p += vsprintf(p, fmt, args);
*p++ = '\n';
*p = 0;
len = p - tmpbuf;
p = tmpbuf;
} else {
p = fmt;
len = strlen(fmt);
}
if (len > HISAX_STATUS_BUFSIZE) {
spin_unlock_irqrestore(&cs->statlock, flags);
printk(KERN_WARNING "HiSax: status overflow %d/%d\n",
len, HISAX_STATUS_BUFSIZE);
return;
}
count = len;
i = cs->status_end - cs->status_write + 1;
if (i >= len)
i = len;
len -= i;
memcpy(cs->status_write, p, i);
cs->status_write += i;
if (cs->status_write > cs->status_end)
cs->status_write = cs->status_buf;
p += i;
if (len) {
memcpy(cs->status_write, p, len);
cs->status_write += len;
}
#ifdef KERNELSTACK_DEBUG
i = (ulong) & len - current->kernel_stack_page;
sprintf(tmpbuf, "kstack %s %lx use %ld\n", current->comm,
current->kernel_stack_page, i);
len = strlen(tmpbuf);
for (p = tmpbuf, i = len; i > 0; i--, p++) {
*cs->status_write++ = *p;
if (cs->status_write > cs->status_end)
cs->status_write = cs->status_buf;
count++;
}
#endif
spin_unlock_irqrestore(&cs->statlock, flags);
if (count) {
ic.command = ISDN_STAT_STAVAIL;
ic.driver = cs->myid;
ic.arg = count;
cs->iif.statcallb(&ic);
}
}
void HiSax_putstatus(struct IsdnCardState *cs, char *head, char *fmt, ...)
{
va_list args;
va_start(args, fmt);
VHiSax_putstatus(cs, head, fmt, args);
va_end(args);
}
int ll_run(struct IsdnCardState *cs, int addfeatures)
{
isdn_ctrl ic;
ic.driver = cs->myid;
ic.command = ISDN_STAT_RUN;
cs->iif.features |= addfeatures;
cs->iif.statcallb(&ic);
return 0;
}
static void ll_stop(struct IsdnCardState *cs)
{
isdn_ctrl ic;
ic.command = ISDN_STAT_STOP;
ic.driver = cs->myid;
cs->iif.statcallb(&ic);
// CallcFreeChan(cs);
}
static void ll_unload(struct IsdnCardState *cs)
{
isdn_ctrl ic;
ic.command = ISDN_STAT_UNLOAD;
ic.driver = cs->myid;
cs->iif.statcallb(&ic);
kfree(cs->status_buf);
cs->status_read = NULL;
cs->status_write = NULL;
cs->status_end = NULL;
kfree(cs->dlog);
cs->dlog = NULL;
}
static void closecard(int cardnr)
{
struct IsdnCardState *csta = cards[cardnr].cs;
if (csta->bcs->BC_Close != NULL) {
csta->bcs->BC_Close(csta->bcs + 1);
csta->bcs->BC_Close(csta->bcs);
}
skb_queue_purge(&csta->rq);
skb_queue_purge(&csta->sq);
kfree(csta->rcvbuf);
csta->rcvbuf = NULL;
if (csta->tx_skb) {
dev_kfree_skb(csta->tx_skb);
csta->tx_skb = NULL;
}
if (csta->DC_Close != NULL) {
csta->DC_Close(csta);
}
if (csta->cardmsg)
csta->cardmsg(csta, CARD_RELEASE, NULL);
if (csta->dbusytimer.function != NULL) // FIXME?
del_timer(&csta->dbusytimer);
ll_unload(csta);
}
static irqreturn_t card_irq(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
irqreturn_t ret = cs->irq_func(intno, cs);
if (ret == IRQ_HANDLED)
cs->irq_cnt++;
return ret;
}
static int init_card(struct IsdnCardState *cs)
{
int irq_cnt, cnt = 3, ret;
if (!cs->irq) {
ret = cs->cardmsg(cs, CARD_INIT, NULL);
return(ret);
}
irq_cnt = cs->irq_cnt = 0;
printk(KERN_INFO "%s: IRQ %d count %d\n", CardType[cs->typ],
cs->irq, irq_cnt);
if (request_irq(cs->irq, card_irq, cs->irq_flags, "HiSax", cs)) {
printk(KERN_WARNING "HiSax: couldn't get interrupt %d\n",
cs->irq);
return 1;
}
while (cnt) {
cs->cardmsg(cs, CARD_INIT, NULL);
/* Timeout 10ms */
msleep(10);
printk(KERN_INFO "%s: IRQ %d count %d\n",
CardType[cs->typ], cs->irq, cs->irq_cnt);
if (cs->irq_cnt == irq_cnt) {
printk(KERN_WARNING
"%s: IRQ(%d) getting no interrupts during init %d\n",
CardType[cs->typ], cs->irq, 4 - cnt);
if (cnt == 1) {
free_irq(cs->irq, cs);
return 2;
} else {
cs->cardmsg(cs, CARD_RESET, NULL);
cnt--;
}
} else {
cs->cardmsg(cs, CARD_TEST, NULL);
return 0;
}
}
return 3;
}
static int __devinit hisax_cs_setup_card(struct IsdnCard *card)
{
int ret;
switch (card->typ) {
#if CARD_TELES0
case ISDN_CTYPE_16_0:
case ISDN_CTYPE_8_0:
ret = setup_teles0(card);
break;
#endif
#if CARD_TELES3
case ISDN_CTYPE_16_3:
case ISDN_CTYPE_PNP:
case ISDN_CTYPE_TELESPCMCIA:
case ISDN_CTYPE_COMPAQ_ISA:
ret = setup_teles3(card);
break;
#endif
#if CARD_S0BOX
case ISDN_CTYPE_S0BOX:
ret = setup_s0box(card);
break;
#endif
#if CARD_TELESPCI
case ISDN_CTYPE_TELESPCI:
ret = setup_telespci(card);
break;
#endif
#if CARD_AVM_A1
case ISDN_CTYPE_A1:
ret = setup_avm_a1(card);
break;
#endif
#if CARD_AVM_A1_PCMCIA
case ISDN_CTYPE_A1_PCMCIA:
ret = setup_avm_a1_pcmcia(card);
break;
#endif
#if CARD_FRITZPCI
case ISDN_CTYPE_FRITZPCI:
ret = setup_avm_pcipnp(card);
break;
#endif
#if CARD_ELSA
case ISDN_CTYPE_ELSA:
case ISDN_CTYPE_ELSA_PNP:
case ISDN_CTYPE_ELSA_PCMCIA:
case ISDN_CTYPE_ELSA_PCI:
ret = setup_elsa(card);
break;
#endif
#if CARD_IX1MICROR2
case ISDN_CTYPE_IX1MICROR2:
ret = setup_ix1micro(card);
break;
#endif
#if CARD_DIEHLDIVA
case ISDN_CTYPE_DIEHLDIVA:
ret = setup_diva(card);
break;
#endif
#if CARD_ASUSCOM
case ISDN_CTYPE_ASUSCOM:
ret = setup_asuscom(card);
break;
#endif
#if CARD_TELEINT
case ISDN_CTYPE_TELEINT:
ret = setup_TeleInt(card);
break;
#endif
#if CARD_SEDLBAUER
case ISDN_CTYPE_SEDLBAUER:
case ISDN_CTYPE_SEDLBAUER_PCMCIA:
case ISDN_CTYPE_SEDLBAUER_FAX:
ret = setup_sedlbauer(card);
break;
#endif
#if CARD_SPORTSTER
case ISDN_CTYPE_SPORTSTER:
ret = setup_sportster(card);
break;
#endif
#if CARD_MIC
case ISDN_CTYPE_MIC:
ret = setup_mic(card);
break;
#endif
#if CARD_NETJET_S
case ISDN_CTYPE_NETJET_S:
ret = setup_netjet_s(card);
break;
#endif
#if CARD_HFCS
case ISDN_CTYPE_TELES3C:
case ISDN_CTYPE_ACERP10:
ret = setup_hfcs(card);
break;
#endif
#if CARD_HFC_PCI
case ISDN_CTYPE_HFC_PCI:
ret = setup_hfcpci(card);
break;
#endif
#if CARD_HFC_SX
case ISDN_CTYPE_HFC_SX:
ret = setup_hfcsx(card);
break;
#endif
#if CARD_NICCY
case ISDN_CTYPE_NICCY:
ret = setup_niccy(card);
break;
#endif
#if CARD_ISURF
case ISDN_CTYPE_ISURF:
ret = setup_isurf(card);
break;
#endif
#if CARD_HSTSAPHIR
case ISDN_CTYPE_HSTSAPHIR:
ret = setup_saphir(card);
break;
#endif
#if CARD_BKM_A4T
case ISDN_CTYPE_BKM_A4T:
ret = setup_bkm_a4t(card);
break;
#endif
#if CARD_SCT_QUADRO
case ISDN_CTYPE_SCT_QUADRO:
ret = setup_sct_quadro(card);
break;
#endif
#if CARD_GAZEL
case ISDN_CTYPE_GAZEL:
ret = setup_gazel(card);
break;
#endif
#if CARD_W6692
case ISDN_CTYPE_W6692:
ret = setup_w6692(card);
break;
#endif
#if CARD_NETJET_U
case ISDN_CTYPE_NETJET_U:
ret = setup_netjet_u(card);
break;
#endif
#if CARD_FN_ENTERNOW_PCI
case ISDN_CTYPE_ENTERNOW:
ret = setup_enternow_pci(card);
break;
#endif
case ISDN_CTYPE_DYNAMIC:
ret = 2;
break;
default:
printk(KERN_WARNING
"HiSax: Support for %s Card not selected\n",
CardType[card->typ]);
ret = 0;
break;
}
return ret;
}
static int hisax_cs_new(int cardnr, char *id, struct IsdnCard *card,
struct IsdnCardState **cs_out, int *busy_flag,
struct module *lockowner)
{
struct IsdnCardState *cs;
*cs_out = NULL;
cs = kzalloc(sizeof(struct IsdnCardState), GFP_ATOMIC);
if (!cs) {
printk(KERN_WARNING
"HiSax: No memory for IsdnCardState(card %d)\n",
cardnr + 1);
goto out;
}
card->cs = cs;
spin_lock_init(&cs->statlock);
spin_lock_init(&cs->lock);
cs->chanlimit = 2; /* maximum B-channel number */
cs->logecho = 0; /* No echo logging */
cs->cardnr = cardnr;
cs->debug = L1_DEB_WARN;
cs->HW_Flags = 0;
cs->busy_flag = busy_flag;
cs->irq_flags = I4L_IRQ_FLAG;
#if TEI_PER_CARD
if (card->protocol == ISDN_PTYPE_NI1)
test_and_set_bit(FLG_TWO_DCHAN, &cs->HW_Flags);
#else
test_and_set_bit(FLG_TWO_DCHAN, &cs->HW_Flags);
#endif
cs->protocol = card->protocol;
if (card->typ <= 0 || card->typ > ISDN_CTYPE_COUNT) {
printk(KERN_WARNING
"HiSax: Card Type %d out of range\n", card->typ);
goto outf_cs;
}
if (!(cs->dlog = kmalloc(MAX_DLOG_SPACE, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for dlog(card %d)\n", cardnr + 1);
goto outf_cs;
}
if (!(cs->status_buf = kmalloc(HISAX_STATUS_BUFSIZE, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for status_buf(card %d)\n",
cardnr + 1);
goto outf_dlog;
}
cs->stlist = NULL;
cs->status_read = cs->status_buf;
cs->status_write = cs->status_buf;
cs->status_end = cs->status_buf + HISAX_STATUS_BUFSIZE - 1;
cs->typ = card->typ;
#ifdef MODULE
cs->iif.owner = lockowner;
#endif
strcpy(cs->iif.id, id);
cs->iif.channels = 2;
cs->iif.maxbufsize = MAX_DATA_SIZE;
cs->iif.hl_hdrlen = MAX_HEADER_LEN;
cs->iif.features =
ISDN_FEATURE_L2_X75I |
ISDN_FEATURE_L2_HDLC |
ISDN_FEATURE_L2_HDLC_56K |
ISDN_FEATURE_L2_TRANS |
ISDN_FEATURE_L3_TRANS |
#ifdef CONFIG_HISAX_1TR6
ISDN_FEATURE_P_1TR6 |
#endif
#ifdef CONFIG_HISAX_EURO
ISDN_FEATURE_P_EURO |
#endif
#ifdef CONFIG_HISAX_NI1
ISDN_FEATURE_P_NI1 |
#endif
0;
cs->iif.command = HiSax_command;
cs->iif.writecmd = NULL;
cs->iif.writebuf_skb = HiSax_writebuf_skb;
cs->iif.readstat = HiSax_readstatus;
register_isdn(&cs->iif);
cs->myid = cs->iif.channels;
*cs_out = cs;
return 1; /* success */
outf_dlog:
kfree(cs->dlog);
outf_cs:
kfree(cs);
card->cs = NULL;
out:
return 0; /* error */
}
static int hisax_cs_setup(int cardnr, struct IsdnCard *card,
struct IsdnCardState *cs)
{
int ret;
if (!(cs->rcvbuf = kmalloc(MAX_DFRAME_LEN_L1, GFP_ATOMIC))) {
printk(KERN_WARNING "HiSax: No memory for isac rcvbuf\n");
ll_unload(cs);
goto outf_cs;
}
cs->rcvidx = 0;
cs->tx_skb = NULL;
cs->tx_cnt = 0;
cs->event = 0;
skb_queue_head_init(&cs->rq);
skb_queue_head_init(&cs->sq);
init_bcstate(cs, 0);
init_bcstate(cs, 1);
/* init_card only handles interrupts which are not */
/* used here for the loadable driver */
switch (card->typ) {
case ISDN_CTYPE_DYNAMIC:
ret = 0;
break;
default:
ret = init_card(cs);
break;
}
if (ret) {
closecard(cardnr);
goto outf_cs;
}
init_tei(cs, cs->protocol);
ret = CallcNewChan(cs);
if (ret) {
closecard(cardnr);
goto outf_cs;
}
/* ISAR needs firmware download first */
if (!test_bit(HW_ISAR, &cs->HW_Flags))
ll_run(cs, 0);
return 1;
outf_cs:
kfree(cs);
card->cs = NULL;
return 0;
}
/* Used from an exported function but calls __devinit functions.
* Tell modpost not to warn (__ref)
*/
static int __ref checkcard(int cardnr, char *id, int *busy_flag,
struct module *lockowner,
hisax_setup_func_t card_setup)
{
int ret;
struct IsdnCard *card = cards + cardnr;
struct IsdnCardState *cs;
ret = hisax_cs_new(cardnr, id, card, &cs, busy_flag, lockowner);
if (!ret)
return 0;
printk(KERN_INFO
"HiSax: Card %d Protocol %s Id=%s (%d)\n", cardnr + 1,
(card->protocol == ISDN_PTYPE_1TR6) ? "1TR6" :
(card->protocol == ISDN_PTYPE_EURO) ? "EDSS1" :
(card->protocol == ISDN_PTYPE_LEASED) ? "LEASED" :
(card->protocol == ISDN_PTYPE_NI1) ? "NI1" :
"NONE", cs->iif.id, cs->myid);
ret = card_setup(card);
if (!ret) {
ll_unload(cs);
goto outf_cs;
}
ret = hisax_cs_setup(cardnr, card, cs);
goto out;
outf_cs:
kfree(cs);
card->cs = NULL;
out:
return ret;
}
static void HiSax_shiftcards(int idx)
{
int i;
for (i = idx; i < (HISAX_MAX_CARDS - 1); i++)
memcpy(&cards[i], &cards[i + 1], sizeof(cards[i]));
}
static int __init HiSax_inithardware(int *busy_flag)
{
int foundcards = 0;
int i = 0;
int t = ',';
int flg = 0;
char *id;
char *next_id = HiSax_id;
char ids[20];
if (strchr(HiSax_id, ','))
t = ',';
else if (strchr(HiSax_id, '%'))
t = '%';
while (i < nrcards) {
if (cards[i].typ < 1)
break;
id = next_id;
if ((next_id = strchr(id, t))) {
*next_id++ = 0;
strcpy(ids, id);
flg = i + 1;
} else {
next_id = id;
if (flg >= i)
strcpy(ids, id);
else
sprintf(ids, "%s%d", id, i);
}
if (checkcard(i, ids, busy_flag, THIS_MODULE,
hisax_cs_setup_card)) {
foundcards++;
i++;
} else {
/* make sure we don't oops the module */
if (cards[i].typ > 0 && cards[i].typ <= ISDN_CTYPE_COUNT) {
printk(KERN_WARNING
"HiSax: Card %s not installed !\n",
CardType[cards[i].typ]);
}
HiSax_shiftcards(i);
nrcards--;
}
}
return foundcards;
}
void HiSax_closecard(int cardnr)
{
int i, last = nrcards - 1;
if (cardnr > last || cardnr < 0)
return;
if (cards[cardnr].cs) {
ll_stop(cards[cardnr].cs);
release_tei(cards[cardnr].cs);
CallcFreeChan(cards[cardnr].cs);
closecard(cardnr);
if (cards[cardnr].cs->irq)
free_irq(cards[cardnr].cs->irq, cards[cardnr].cs);
kfree((void *) cards[cardnr].cs);
cards[cardnr].cs = NULL;
}
i = cardnr;
while (i <= last) {
cards[i] = cards[i + 1];
i++;
}
nrcards--;
}
void HiSax_reportcard(int cardnr, int sel)
{
struct IsdnCardState *cs = cards[cardnr].cs;
printk(KERN_DEBUG "HiSax: reportcard No %d\n", cardnr + 1);
printk(KERN_DEBUG "HiSax: Type %s\n", CardType[cs->typ]);
printk(KERN_DEBUG "HiSax: debuglevel %x\n", cs->debug);
printk(KERN_DEBUG "HiSax: HiSax_reportcard address 0x%lX\n",
(ulong) & HiSax_reportcard);
printk(KERN_DEBUG "HiSax: cs 0x%lX\n", (ulong) cs);
printk(KERN_DEBUG "HiSax: HW_Flags %lx bc0 flg %lx bc1 flg %lx\n",
cs->HW_Flags, cs->bcs[0].Flag, cs->bcs[1].Flag);
printk(KERN_DEBUG "HiSax: bcs 0 mode %d ch%d\n",
cs->bcs[0].mode, cs->bcs[0].channel);
printk(KERN_DEBUG "HiSax: bcs 1 mode %d ch%d\n",
cs->bcs[1].mode, cs->bcs[1].channel);
#ifdef ERROR_STATISTIC
printk(KERN_DEBUG "HiSax: dc errors(rx,crc,tx) %d,%d,%d\n",
cs->err_rx, cs->err_crc, cs->err_tx);
printk(KERN_DEBUG
"HiSax: bc0 errors(inv,rdo,crc,tx) %d,%d,%d,%d\n",
cs->bcs[0].err_inv, cs->bcs[0].err_rdo, cs->bcs[0].err_crc,
cs->bcs[0].err_tx);
printk(KERN_DEBUG
"HiSax: bc1 errors(inv,rdo,crc,tx) %d,%d,%d,%d\n",
cs->bcs[1].err_inv, cs->bcs[1].err_rdo, cs->bcs[1].err_crc,
cs->bcs[1].err_tx);
if (sel == 99) {
cs->err_rx = 0;
cs->err_crc = 0;
cs->err_tx = 0;
cs->bcs[0].err_inv = 0;
cs->bcs[0].err_rdo = 0;
cs->bcs[0].err_crc = 0;
cs->bcs[0].err_tx = 0;
cs->bcs[1].err_inv = 0;
cs->bcs[1].err_rdo = 0;
cs->bcs[1].err_crc = 0;
cs->bcs[1].err_tx = 0;
}
#endif
}
static int __init HiSax_init(void)
{
int i, retval;
#ifdef MODULE
int j;
int nzproto = 0;
#endif
HiSaxVersion();
retval = CallcNew();
if (retval)
goto out;
retval = Isdnl3New();
if (retval)
goto out_callc;
retval = Isdnl2New();
if (retval)
goto out_isdnl3;
retval = TeiNew();
if (retval)
goto out_isdnl2;
retval = Isdnl1New();
if (retval)
goto out_tei;
#ifdef MODULE
if (!type[0]) {
/* We 'll register drivers later, but init basic functions */
for (i = 0; i < HISAX_MAX_CARDS; i++)
cards[i].typ = 0;
return 0;
}
#ifdef CONFIG_HISAX_ELSA
if (type[0] == ISDN_CTYPE_ELSA_PCMCIA) {
/* we have exported and return in this case */
return 0;
}
#endif
#ifdef CONFIG_HISAX_SEDLBAUER
if (type[0] == ISDN_CTYPE_SEDLBAUER_PCMCIA) {
/* we have to export and return in this case */
return 0;
}
#endif
#ifdef CONFIG_HISAX_AVM_A1_PCMCIA
if (type[0] == ISDN_CTYPE_A1_PCMCIA) {
/* we have to export and return in this case */
return 0;
}
#endif
#ifdef CONFIG_HISAX_HFC_SX
if (type[0] == ISDN_CTYPE_HFC_SP_PCMCIA) {
/* we have to export and return in this case */
return 0;
}
#endif
#endif
nrcards = 0;
#ifdef MODULE
if (id) /* If id= string used */
HiSax_id = id;
for (i = j = 0; j < HISAX_MAX_CARDS; i++) {
cards[j].typ = type[i];
if (protocol[i]) {
cards[j].protocol = protocol[i];
nzproto++;
} else {
cards[j].protocol = DEFAULT_PROTO;
}
switch (type[i]) {
case ISDN_CTYPE_16_0:
cards[j].para[0] = irq[i];
cards[j].para[1] = mem[i];
cards[j].para[2] = io[i];
break;
case ISDN_CTYPE_8_0:
cards[j].para[0] = irq[i];
cards[j].para[1] = mem[i];
break;
#ifdef IO0_IO1
case ISDN_CTYPE_PNP:
case ISDN_CTYPE_NICCY:
cards[j].para[0] = irq[i];
cards[j].para[1] = io0[i];
cards[j].para[2] = io1[i];
break;
case ISDN_CTYPE_COMPAQ_ISA:
cards[j].para[0] = irq[i];
cards[j].para[1] = io0[i];
cards[j].para[2] = io1[i];
cards[j].para[3] = io[i];
break;
#endif
case ISDN_CTYPE_ELSA:
case ISDN_CTYPE_HFC_PCI:
cards[j].para[0] = io[i];
break;
case ISDN_CTYPE_16_3:
case ISDN_CTYPE_TELESPCMCIA:
case ISDN_CTYPE_A1:
case ISDN_CTYPE_A1_PCMCIA:
case ISDN_CTYPE_ELSA_PNP:
case ISDN_CTYPE_ELSA_PCMCIA:
case ISDN_CTYPE_IX1MICROR2:
case ISDN_CTYPE_DIEHLDIVA:
case ISDN_CTYPE_ASUSCOM:
case ISDN_CTYPE_TELEINT:
case ISDN_CTYPE_SEDLBAUER:
case ISDN_CTYPE_SEDLBAUER_PCMCIA:
case ISDN_CTYPE_SEDLBAUER_FAX:
case ISDN_CTYPE_SPORTSTER:
case ISDN_CTYPE_MIC:
case ISDN_CTYPE_TELES3C:
case ISDN_CTYPE_ACERP10:
case ISDN_CTYPE_S0BOX:
case ISDN_CTYPE_FRITZPCI:
case ISDN_CTYPE_HSTSAPHIR:
case ISDN_CTYPE_GAZEL:
case ISDN_CTYPE_HFC_SX:
case ISDN_CTYPE_HFC_SP_PCMCIA:
cards[j].para[0] = irq[i];
cards[j].para[1] = io[i];
break;
case ISDN_CTYPE_ISURF:
cards[j].para[0] = irq[i];
cards[j].para[1] = io[i];
cards[j].para[2] = mem[i];
break;
case ISDN_CTYPE_ELSA_PCI:
case ISDN_CTYPE_NETJET_S:
case ISDN_CTYPE_TELESPCI:
case ISDN_CTYPE_W6692:
case ISDN_CTYPE_NETJET_U:
break;
case ISDN_CTYPE_BKM_A4T:
break;
case ISDN_CTYPE_SCT_QUADRO:
if (irq[i]) {
cards[j].para[0] = irq[i];
} else {
/* QUADRO is a 4 BRI card */
cards[j++].para[0] = 1;
/* we need to check if further cards can be added */
if (j < HISAX_MAX_CARDS) {
cards[j].typ = ISDN_CTYPE_SCT_QUADRO;
cards[j].protocol = protocol[i];
cards[j++].para[0] = 2;
}
if (j < HISAX_MAX_CARDS) {
cards[j].typ = ISDN_CTYPE_SCT_QUADRO;
cards[j].protocol = protocol[i];
cards[j++].para[0] = 3;
}
if (j < HISAX_MAX_CARDS) {
cards[j].typ = ISDN_CTYPE_SCT_QUADRO;
cards[j].protocol = protocol[i];
cards[j].para[0] = 4;
}
}
break;
}
j++;
}
if (!nzproto) {
printk(KERN_WARNING
"HiSax: Warning - no protocol specified\n");
printk(KERN_WARNING "HiSax: using protocol %s\n",
DEFAULT_PROTO_NAME);
}
#endif
if (!HiSax_id)
HiSax_id = HiSaxID;
if (!HiSaxID[0])
strcpy(HiSaxID, "HiSax");
for (i = 0; i < HISAX_MAX_CARDS; i++)
if (cards[i].typ > 0)
nrcards++;
printk(KERN_DEBUG "HiSax: Total %d card%s defined\n",
nrcards, (nrcards > 1) ? "s" : "");
/* Install only, if at least one card found */
if (!HiSax_inithardware(NULL))
return -ENODEV;
return 0;
out_tei:
TeiFree();
out_isdnl2:
Isdnl2Free();
out_isdnl3:
Isdnl3Free();
out_callc:
CallcFree();
out:
return retval;
}
static void __exit HiSax_exit(void)
{
int cardnr = nrcards - 1;
while (cardnr >= 0)
HiSax_closecard(cardnr--);
Isdnl1Free();
TeiFree();
Isdnl2Free();
Isdnl3Free();
CallcFree();
printk(KERN_INFO "HiSax module removed\n");
}
#ifdef CONFIG_HOTPLUG
int __devinit hisax_init_pcmcia(void *pcm_iob, int *busy_flag, struct IsdnCard *card)
{
u_char ids[16];
int ret = -1;
cards[nrcards] = *card;
if (nrcards)
sprintf(ids, "HiSax%d", nrcards);
else
sprintf(ids, "HiSax");
if (!checkcard(nrcards, ids, busy_flag, THIS_MODULE,
hisax_cs_setup_card))
goto error;
ret = nrcards;
nrcards++;
error:
return ret;
}
EXPORT_SYMBOL(hisax_init_pcmcia);
#endif
EXPORT_SYMBOL(HiSax_closecard);
#include "hisax_if.h"
EXPORT_SYMBOL(hisax_register);
EXPORT_SYMBOL(hisax_unregister);
static void hisax_d_l1l2(struct hisax_if *ifc, int pr, void *arg);
static void hisax_b_l1l2(struct hisax_if *ifc, int pr, void *arg);
static void hisax_d_l2l1(struct PStack *st, int pr, void *arg);
static void hisax_b_l2l1(struct PStack *st, int pr, void *arg);
static int hisax_cardmsg(struct IsdnCardState *cs, int mt, void *arg);
static int hisax_bc_setstack(struct PStack *st, struct BCState *bcs);
static void hisax_bc_close(struct BCState *bcs);
static void hisax_bh(struct work_struct *work);
static void EChannel_proc_rcv(struct hisax_d_if *d_if);
static int hisax_setup_card_dynamic(struct IsdnCard *card)
{
return 2;
}
int hisax_register(struct hisax_d_if *hisax_d_if, struct hisax_b_if *b_if[],
char *name, int protocol)
{
int i, retval;
char id[20];
struct IsdnCardState *cs;
for (i = 0; i < HISAX_MAX_CARDS; i++) {
if (!cards[i].typ)
break;
}
if (i >= HISAX_MAX_CARDS)
return -EBUSY;
cards[i].typ = ISDN_CTYPE_DYNAMIC;
cards[i].protocol = protocol;
sprintf(id, "%s%d", name, i);
nrcards++;
retval = checkcard(i, id, NULL, hisax_d_if->owner,
hisax_setup_card_dynamic);
if (retval == 0) { // yuck
cards[i].typ = 0;
nrcards--;
return -EINVAL;
}
cs = cards[i].cs;
hisax_d_if->cs = cs;
cs->hw.hisax_d_if = hisax_d_if;
cs->cardmsg = hisax_cardmsg;
INIT_WORK(&cs->tqueue, hisax_bh);
cs->channel[0].d_st->l2.l2l1 = hisax_d_l2l1;
for (i = 0; i < 2; i++) {
cs->bcs[i].BC_SetStack = hisax_bc_setstack;
cs->bcs[i].BC_Close = hisax_bc_close;
b_if[i]->ifc.l1l2 = hisax_b_l1l2;
hisax_d_if->b_if[i] = b_if[i];
}
hisax_d_if->ifc.l1l2 = hisax_d_l1l2;
skb_queue_head_init(&hisax_d_if->erq);
clear_bit(0, &hisax_d_if->ph_state);
return 0;
}
void hisax_unregister(struct hisax_d_if *hisax_d_if)
{
cards[hisax_d_if->cs->cardnr].typ = 0;
HiSax_closecard(hisax_d_if->cs->cardnr);
skb_queue_purge(&hisax_d_if->erq);
}
#include "isdnl1.h"
static void hisax_sched_event(struct IsdnCardState *cs, int event)
{
test_and_set_bit(event, &cs->event);
schedule_work(&cs->tqueue);
}
static void hisax_bh(struct work_struct *work)
{
struct IsdnCardState *cs =
container_of(work, struct IsdnCardState, tqueue);
struct PStack *st;
int pr;
if (test_and_clear_bit(D_RCVBUFREADY, &cs->event))
DChannel_proc_rcv(cs);
if (test_and_clear_bit(E_RCVBUFREADY, &cs->event))
EChannel_proc_rcv(cs->hw.hisax_d_if);
if (test_and_clear_bit(D_L1STATECHANGE, &cs->event)) {
if (test_bit(0, &cs->hw.hisax_d_if->ph_state))
pr = PH_ACTIVATE | INDICATION;
else
pr = PH_DEACTIVATE | INDICATION;
for (st = cs->stlist; st; st = st->next)
st->l1.l1l2(st, pr, NULL);
}
}
static void hisax_b_sched_event(struct BCState *bcs, int event)
{
test_and_set_bit(event, &bcs->event);
schedule_work(&bcs->tqueue);
}
static inline void D_L2L1(struct hisax_d_if *d_if, int pr, void *arg)
{
struct hisax_if *ifc = (struct hisax_if *) d_if;
ifc->l2l1(ifc, pr, arg);
}
static inline void B_L2L1(struct hisax_b_if *b_if, int pr, void *arg)
{
struct hisax_if *ifc = (struct hisax_if *) b_if;
ifc->l2l1(ifc, pr, arg);
}
static void hisax_d_l1l2(struct hisax_if *ifc, int pr, void *arg)
{
struct hisax_d_if *d_if = (struct hisax_d_if *) ifc;
struct IsdnCardState *cs = d_if->cs;
struct PStack *st;
struct sk_buff *skb;
switch (pr) {
case PH_ACTIVATE | INDICATION:
set_bit(0, &d_if->ph_state);
hisax_sched_event(cs, D_L1STATECHANGE);
break;
case PH_DEACTIVATE | INDICATION:
clear_bit(0, &d_if->ph_state);
hisax_sched_event(cs, D_L1STATECHANGE);
break;
case PH_DATA | INDICATION:
skb_queue_tail(&cs->rq, arg);
hisax_sched_event(cs, D_RCVBUFREADY);
break;
case PH_DATA | CONFIRM:
skb = skb_dequeue(&cs->sq);
if (skb) {
D_L2L1(d_if, PH_DATA | REQUEST, skb);
break;
}
clear_bit(FLG_L1_DBUSY, &cs->HW_Flags);
for (st = cs->stlist; st; st = st->next) {
if (test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags)) {
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
break;
}
}
break;
case PH_DATA_E | INDICATION:
skb_queue_tail(&d_if->erq, arg);
hisax_sched_event(cs, E_RCVBUFREADY);
break;
default:
printk("pr %#x\n", pr);
break;
}
}
static void hisax_b_l1l2(struct hisax_if *ifc, int pr, void *arg)
{
struct hisax_b_if *b_if = (struct hisax_b_if *) ifc;
struct BCState *bcs = b_if->bcs;
struct PStack *st = bcs->st;
struct sk_buff *skb;
// FIXME use isdnl1?
switch (pr) {
case PH_ACTIVATE | INDICATION:
st->l1.l1l2(st, pr, NULL);
break;
case PH_DEACTIVATE | INDICATION:
st->l1.l1l2(st, pr, NULL);
clear_bit(BC_FLG_BUSY, &bcs->Flag);
skb_queue_purge(&bcs->squeue);
bcs->hw.b_if = NULL;
break;
case PH_DATA | INDICATION:
skb_queue_tail(&bcs->rqueue, arg);
hisax_b_sched_event(bcs, B_RCVBUFREADY);
break;
case PH_DATA | CONFIRM:
bcs->tx_cnt -= (long)arg;
if (test_bit(FLG_LLI_L1WAKEUP,&bcs->st->lli.flag)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += (long)arg;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
skb = skb_dequeue(&bcs->squeue);
if (skb) {
B_L2L1(b_if, PH_DATA | REQUEST, skb);
break;
}
clear_bit(BC_FLG_BUSY, &bcs->Flag);
if (test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags)) {
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
}
break;
default:
printk("hisax_b_l1l2 pr %#x\n", pr);
break;
}
}
static void hisax_d_l2l1(struct PStack *st, int pr, void *arg)
{
struct IsdnCardState *cs = st->l1.hardware;
struct hisax_d_if *hisax_d_if = cs->hw.hisax_d_if;
struct sk_buff *skb = arg;
switch (pr) {
case PH_DATA | REQUEST:
case PH_PULL | INDICATION:
if (cs->debug & DEB_DLOG_HEX)
LogFrame(cs, skb->data, skb->len);
if (cs->debug & DEB_DLOG_VERBOSE)
dlogframe(cs, skb, 0);
Logl2Frame(cs, skb, "PH_DATA_REQ", 0);
// FIXME lock?
if (!test_and_set_bit(FLG_L1_DBUSY, &cs->HW_Flags))
D_L2L1(hisax_d_if, PH_DATA | REQUEST, skb);
else
skb_queue_tail(&cs->sq, skb);
break;
case PH_PULL | REQUEST:
if (!test_bit(FLG_L1_DBUSY, &cs->HW_Flags))
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
else
set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
default:
D_L2L1(hisax_d_if, pr, arg);
break;
}
}
static int hisax_cardmsg(struct IsdnCardState *cs, int mt, void *arg)
{
return 0;
}
static void hisax_b_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct hisax_b_if *b_if = bcs->hw.b_if;
switch (pr) {
case PH_ACTIVATE | REQUEST:
B_L2L1(b_if, pr, (void *)(unsigned long)st->l1.mode);
break;
case PH_DATA | REQUEST:
case PH_PULL | INDICATION:
// FIXME lock?
if (!test_and_set_bit(BC_FLG_BUSY, &bcs->Flag)) {
B_L2L1(b_if, PH_DATA | REQUEST, arg);
} else {
skb_queue_tail(&bcs->squeue, arg);
}
break;
case PH_PULL | REQUEST:
if (!test_bit(BC_FLG_BUSY, &bcs->Flag))
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
else
set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case PH_DEACTIVATE | REQUEST:
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
skb_queue_purge(&bcs->squeue);
default:
B_L2L1(b_if, pr, arg);
break;
}
}
static int hisax_bc_setstack(struct PStack *st, struct BCState *bcs)
{
struct IsdnCardState *cs = st->l1.hardware;
struct hisax_d_if *hisax_d_if = cs->hw.hisax_d_if;
bcs->channel = st->l1.bc;
bcs->hw.b_if = hisax_d_if->b_if[st->l1.bc];
hisax_d_if->b_if[st->l1.bc]->bcs = bcs;
st->l1.bcs = bcs;
st->l2.l2l1 = hisax_b_l2l1;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
return 0;
}
static void hisax_bc_close(struct BCState *bcs)
{
struct hisax_b_if *b_if = bcs->hw.b_if;
if (b_if)
B_L2L1(b_if, PH_DEACTIVATE | REQUEST, NULL);
}
static void EChannel_proc_rcv(struct hisax_d_if *d_if)
{
struct IsdnCardState *cs = d_if->cs;
u_char *ptr;
struct sk_buff *skb;
while ((skb = skb_dequeue(&d_if->erq)) != NULL) {
if (cs->debug & DEB_DLOG_HEX) {
ptr = cs->dlog;
if ((skb->len) < MAX_DLOG_SPACE / 3 - 10) {
*ptr++ = 'E';
*ptr++ = 'C';
*ptr++ = 'H';
*ptr++ = 'O';
*ptr++ = ':';
ptr += QuickHex(ptr, skb->data, skb->len);
ptr--;
*ptr++ = '\n';
*ptr = 0;
HiSax_putstatus(cs, NULL, cs->dlog);
} else
HiSax_putstatus(cs, "LogEcho: ",
"warning Frame too big (%d)",
skb->len);
}
dev_kfree_skb_any(skb);
}
}
#ifdef CONFIG_PCI
#include <linux/pci.h>
static struct pci_device_id hisax_pci_tbl[] __devinitdata = {
#ifdef CONFIG_HISAX_FRITZPCI
{PCI_VENDOR_ID_AVM, PCI_DEVICE_ID_AVM_A1, PCI_ANY_ID, PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_DIEHLDIVA
{PCI_VENDOR_ID_EICON, PCI_DEVICE_ID_EICON_DIVA20, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_EICON, PCI_DEVICE_ID_EICON_DIVA20_U, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_EICON, PCI_DEVICE_ID_EICON_DIVA201, PCI_ANY_ID, PCI_ANY_ID},
//#########################################################################################
{PCI_VENDOR_ID_EICON, PCI_DEVICE_ID_EICON_DIVA202, PCI_ANY_ID, PCI_ANY_ID},
//#########################################################################################
#endif
#ifdef CONFIG_HISAX_ELSA
{PCI_VENDOR_ID_ELSA, PCI_DEVICE_ID_ELSA_MICROLINK, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_ELSA, PCI_DEVICE_ID_ELSA_QS3000, PCI_ANY_ID, PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_GAZEL
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_R685, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_R753, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_DJINN_ITOO, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_OLITEC, PCI_ANY_ID, PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_SCT_QUADRO
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050, PCI_ANY_ID, PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_NICCY
{PCI_VENDOR_ID_SATSAGEM, PCI_DEVICE_ID_SATSAGEM_NICCY, PCI_ANY_ID,PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_SEDLBAUER
{PCI_VENDOR_ID_TIGERJET, PCI_DEVICE_ID_TIGERJET_100, PCI_ANY_ID,PCI_ANY_ID},
#endif
#if defined(CONFIG_HISAX_NETJET) || defined(CONFIG_HISAX_NETJET_U)
{PCI_VENDOR_ID_TIGERJET, PCI_DEVICE_ID_TIGERJET_300, PCI_ANY_ID,PCI_ANY_ID},
#endif
#if defined(CONFIG_HISAX_TELESPCI) || defined(CONFIG_HISAX_SCT_QUADRO)
{PCI_VENDOR_ID_ZORAN, PCI_DEVICE_ID_ZORAN_36120, PCI_ANY_ID,PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_W6692
{PCI_VENDOR_ID_DYNALINK, PCI_DEVICE_ID_DYNALINK_IS64PH, PCI_ANY_ID,PCI_ANY_ID},
{PCI_VENDOR_ID_WINBOND2, PCI_DEVICE_ID_WINBOND2_6692, PCI_ANY_ID,PCI_ANY_ID},
#endif
#ifdef CONFIG_HISAX_HFC_PCI
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_2BD0, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B000, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B006, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B007, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B008, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B009, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B00A, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B00B, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B00C, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B100, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B700, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_B701, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_ABOCOM, PCI_DEVICE_ID_ABOCOM_2BD1, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_ASUSTEK, PCI_DEVICE_ID_ASUSTEK_0675, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_BERKOM, PCI_DEVICE_ID_BERKOM_T_CONCEPT, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_BERKOM, PCI_DEVICE_ID_BERKOM_A1T, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_ANIGMA, PCI_DEVICE_ID_ANIGMA_MC145575, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_ZOLTRIX, PCI_DEVICE_ID_ZOLTRIX_2BD0, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_DIGI, PCI_DEVICE_ID_DIGI_DF_M_IOM2_E, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_DIGI, PCI_DEVICE_ID_DIGI_DF_M_E, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_DIGI, PCI_DEVICE_ID_DIGI_DF_M_IOM2_A, PCI_ANY_ID, PCI_ANY_ID},
{PCI_VENDOR_ID_DIGI, PCI_DEVICE_ID_DIGI_DF_M_A, PCI_ANY_ID, PCI_ANY_ID},
#endif
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, hisax_pci_tbl);
#endif /* CONFIG_PCI */
module_init(HiSax_init);
module_exit(HiSax_exit);
EXPORT_SYMBOL(FsmNew);
EXPORT_SYMBOL(FsmFree);
EXPORT_SYMBOL(FsmEvent);
EXPORT_SYMBOL(FsmChangeState);
EXPORT_SYMBOL(FsmInitTimer);
EXPORT_SYMBOL(FsmDelTimer);
EXPORT_SYMBOL(FsmRestartTimer);
| gpl-2.0 |
JPG-Consulting/linux | drivers/net/ethernet/stmicro/stmmac/dwmac-socfpga.c | 210 | 7486 | /* Copyright Altera Corporation (C) 2014. 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,
* 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/>.
*
* Adopted from dwmac-sti.c
*/
#include <linux/mfd/syscon.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_net.h>
#include <linux/phy.h>
#include <linux/regmap.h>
#include <linux/reset.h>
#include <linux/stmmac.h>
#include "stmmac.h"
#include "stmmac_platform.h"
#define SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_GMII_MII 0x0
#define SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_RGMII 0x1
#define SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_RMII 0x2
#define SYSMGR_EMACGRP_CTRL_PHYSEL_WIDTH 2
#define SYSMGR_EMACGRP_CTRL_PHYSEL_MASK 0x00000003
#define EMAC_SPLITTER_CTRL_REG 0x0
#define EMAC_SPLITTER_CTRL_SPEED_MASK 0x3
#define EMAC_SPLITTER_CTRL_SPEED_10 0x2
#define EMAC_SPLITTER_CTRL_SPEED_100 0x3
#define EMAC_SPLITTER_CTRL_SPEED_1000 0x0
struct socfpga_dwmac {
int interface;
u32 reg_offset;
u32 reg_shift;
struct device *dev;
struct regmap *sys_mgr_base_addr;
struct reset_control *stmmac_rst;
void __iomem *splitter_base;
};
static void socfpga_dwmac_fix_mac_speed(void *priv, unsigned int speed)
{
struct socfpga_dwmac *dwmac = (struct socfpga_dwmac *)priv;
void __iomem *splitter_base = dwmac->splitter_base;
u32 val;
if (!splitter_base)
return;
val = readl(splitter_base + EMAC_SPLITTER_CTRL_REG);
val &= ~EMAC_SPLITTER_CTRL_SPEED_MASK;
switch (speed) {
case 1000:
val |= EMAC_SPLITTER_CTRL_SPEED_1000;
break;
case 100:
val |= EMAC_SPLITTER_CTRL_SPEED_100;
break;
case 10:
val |= EMAC_SPLITTER_CTRL_SPEED_10;
break;
default:
return;
}
writel(val, splitter_base + EMAC_SPLITTER_CTRL_REG);
}
static int socfpga_dwmac_parse_data(struct socfpga_dwmac *dwmac, struct device *dev)
{
struct device_node *np = dev->of_node;
struct regmap *sys_mgr_base_addr;
u32 reg_offset, reg_shift;
int ret;
struct device_node *np_splitter;
struct resource res_splitter;
dwmac->stmmac_rst = devm_reset_control_get(dev,
STMMAC_RESOURCE_NAME);
if (IS_ERR(dwmac->stmmac_rst)) {
dev_info(dev, "Could not get reset control!\n");
return -EINVAL;
}
dwmac->interface = of_get_phy_mode(np);
sys_mgr_base_addr = syscon_regmap_lookup_by_phandle(np, "altr,sysmgr-syscon");
if (IS_ERR(sys_mgr_base_addr)) {
dev_info(dev, "No sysmgr-syscon node found\n");
return PTR_ERR(sys_mgr_base_addr);
}
ret = of_property_read_u32_index(np, "altr,sysmgr-syscon", 1, ®_offset);
if (ret) {
dev_info(dev, "Could not read reg_offset from sysmgr-syscon!\n");
return -EINVAL;
}
ret = of_property_read_u32_index(np, "altr,sysmgr-syscon", 2, ®_shift);
if (ret) {
dev_info(dev, "Could not read reg_shift from sysmgr-syscon!\n");
return -EINVAL;
}
np_splitter = of_parse_phandle(np, "altr,emac-splitter", 0);
if (np_splitter) {
if (of_address_to_resource(np_splitter, 0, &res_splitter)) {
dev_info(dev, "Missing emac splitter address\n");
return -EINVAL;
}
dwmac->splitter_base = devm_ioremap_resource(dev, &res_splitter);
if (IS_ERR(dwmac->splitter_base)) {
dev_info(dev, "Failed to mapping emac splitter\n");
return PTR_ERR(dwmac->splitter_base);
}
}
dwmac->reg_offset = reg_offset;
dwmac->reg_shift = reg_shift;
dwmac->sys_mgr_base_addr = sys_mgr_base_addr;
dwmac->dev = dev;
return 0;
}
static int socfpga_dwmac_setup(struct socfpga_dwmac *dwmac)
{
struct regmap *sys_mgr_base_addr = dwmac->sys_mgr_base_addr;
int phymode = dwmac->interface;
u32 reg_offset = dwmac->reg_offset;
u32 reg_shift = dwmac->reg_shift;
u32 ctrl, val;
switch (phymode) {
case PHY_INTERFACE_MODE_RGMII:
case PHY_INTERFACE_MODE_RGMII_ID:
val = SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_RGMII;
break;
case PHY_INTERFACE_MODE_MII:
case PHY_INTERFACE_MODE_GMII:
val = SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_GMII_MII;
break;
default:
dev_err(dwmac->dev, "bad phy mode %d\n", phymode);
return -EINVAL;
}
/* Overwrite val to GMII if splitter core is enabled. The phymode here
* is the actual phy mode on phy hardware, but phy interface from
* EMAC core is GMII.
*/
if (dwmac->splitter_base)
val = SYSMGR_EMACGRP_CTRL_PHYSEL_ENUM_GMII_MII;
regmap_read(sys_mgr_base_addr, reg_offset, &ctrl);
ctrl &= ~(SYSMGR_EMACGRP_CTRL_PHYSEL_MASK << reg_shift);
ctrl |= val << reg_shift;
regmap_write(sys_mgr_base_addr, reg_offset, ctrl);
return 0;
}
static void *socfpga_dwmac_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
int ret;
struct socfpga_dwmac *dwmac;
dwmac = devm_kzalloc(dev, sizeof(*dwmac), GFP_KERNEL);
if (!dwmac)
return ERR_PTR(-ENOMEM);
ret = socfpga_dwmac_parse_data(dwmac, dev);
if (ret) {
dev_err(dev, "Unable to parse OF data\n");
return ERR_PTR(ret);
}
ret = socfpga_dwmac_setup(dwmac);
if (ret) {
dev_err(dev, "couldn't setup SoC glue (%d)\n", ret);
return ERR_PTR(ret);
}
return dwmac;
}
static void socfpga_dwmac_exit(struct platform_device *pdev, void *priv)
{
struct socfpga_dwmac *dwmac = priv;
/* On socfpga platform exit, assert and hold reset to the
* enet controller - the default state after a hard reset.
*/
if (dwmac->stmmac_rst)
reset_control_assert(dwmac->stmmac_rst);
}
static int socfpga_dwmac_init(struct platform_device *pdev, void *priv)
{
struct socfpga_dwmac *dwmac = priv;
struct net_device *ndev = platform_get_drvdata(pdev);
struct stmmac_priv *stpriv = NULL;
int ret = 0;
if (ndev)
stpriv = netdev_priv(ndev);
/* Assert reset to the enet controller before changing the phy mode */
if (dwmac->stmmac_rst)
reset_control_assert(dwmac->stmmac_rst);
/* Setup the phy mode in the system manager registers according to
* devicetree configuration
*/
ret = socfpga_dwmac_setup(dwmac);
/* Deassert reset for the phy configuration to be sampled by
* the enet controller, and operation to start in requested mode
*/
if (dwmac->stmmac_rst)
reset_control_deassert(dwmac->stmmac_rst);
/* Before the enet controller is suspended, the phy is suspended.
* This causes the phy clock to be gated. The enet controller is
* resumed before the phy, so the clock is still gated "off" when
* the enet controller is resumed. This code makes sure the phy
* is "resumed" before reinitializing the enet controller since
* the enet controller depends on an active phy clock to complete
* a DMA reset. A DMA reset will "time out" if executed
* with no phy clock input on the Synopsys enet controller.
* Verified through Synopsys Case #8000711656.
*
* Note that the phy clock is also gated when the phy is isolated.
* Phy "suspend" and "isolate" controls are located in phy basic
* control register 0, and can be modified by the phy driver
* framework.
*/
if (stpriv && stpriv->phydev)
phy_resume(stpriv->phydev);
return ret;
}
const struct stmmac_of_data socfpga_gmac_data = {
.setup = socfpga_dwmac_probe,
.init = socfpga_dwmac_init,
.exit = socfpga_dwmac_exit,
.fix_mac_speed = socfpga_dwmac_fix_mac_speed,
};
| gpl-2.0 |
etnie/Huawei-Ascend-m860-kernel-source | arch/sh/kernel/cpu/sh4a/clock-sh7785.c | 210 | 3850 | /*
* arch/sh/kernel/cpu/sh4a/clock-sh7785.c
*
* SH7785 support for the clock framework
*
* Copyright (C) 2007 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <asm/clock.h>
#include <asm/freq.h>
#include <asm/io.h>
static int ifc_divisors[] = { 1, 2, 4, 6 };
static int ufc_divisors[] = { 1, 1, 4, 6 };
static int sfc_divisors[] = { 1, 1, 4, 6 };
static int bfc_divisors[] = { 1, 1, 1, 1, 1, 12, 16, 18,
24, 32, 36, 48, 1, 1, 1, 1 };
static int mfc_divisors[] = { 1, 1, 4, 6 };
static int pfc_divisors[] = { 1, 1, 1, 1, 1, 1, 1, 18,
24, 32, 36, 48, 1, 1, 1, 1 };
static void master_clk_init(struct clk *clk)
{
clk->rate *= pfc_divisors[ctrl_inl(FRQMR1) & 0x000f];
}
static struct clk_ops sh7785_master_clk_ops = {
.init = master_clk_init,
};
static void module_clk_recalc(struct clk *clk)
{
int idx = (ctrl_inl(FRQMR1) & 0x000f);
clk->rate = clk->parent->rate / pfc_divisors[idx];
}
static struct clk_ops sh7785_module_clk_ops = {
.recalc = module_clk_recalc,
};
static void bus_clk_recalc(struct clk *clk)
{
int idx = ((ctrl_inl(FRQMR1) >> 16) & 0x000f);
clk->rate = clk->parent->rate / bfc_divisors[idx];
}
static struct clk_ops sh7785_bus_clk_ops = {
.recalc = bus_clk_recalc,
};
static void cpu_clk_recalc(struct clk *clk)
{
int idx = ((ctrl_inl(FRQMR1) >> 28) & 0x0003);
clk->rate = clk->parent->rate / ifc_divisors[idx];
}
static struct clk_ops sh7785_cpu_clk_ops = {
.recalc = cpu_clk_recalc,
};
static struct clk_ops *sh7785_clk_ops[] = {
&sh7785_master_clk_ops,
&sh7785_module_clk_ops,
&sh7785_bus_clk_ops,
&sh7785_cpu_clk_ops,
};
void __init arch_init_clk_ops(struct clk_ops **ops, int idx)
{
if (idx < ARRAY_SIZE(sh7785_clk_ops))
*ops = sh7785_clk_ops[idx];
}
static void shyway_clk_recalc(struct clk *clk)
{
int idx = ((ctrl_inl(FRQMR1) >> 20) & 0x0003);
clk->rate = clk->parent->rate / sfc_divisors[idx];
}
static struct clk_ops sh7785_shyway_clk_ops = {
.recalc = shyway_clk_recalc,
};
static struct clk sh7785_shyway_clk = {
.name = "shyway_clk",
.flags = CLK_ALWAYS_ENABLED,
.ops = &sh7785_shyway_clk_ops,
};
static void ddr_clk_recalc(struct clk *clk)
{
int idx = ((ctrl_inl(FRQMR1) >> 12) & 0x0003);
clk->rate = clk->parent->rate / mfc_divisors[idx];
}
static struct clk_ops sh7785_ddr_clk_ops = {
.recalc = ddr_clk_recalc,
};
static struct clk sh7785_ddr_clk = {
.name = "ddr_clk",
.flags = CLK_ALWAYS_ENABLED,
.ops = &sh7785_ddr_clk_ops,
};
static void ram_clk_recalc(struct clk *clk)
{
int idx = ((ctrl_inl(FRQMR1) >> 24) & 0x0003);
clk->rate = clk->parent->rate / ufc_divisors[idx];
}
static struct clk_ops sh7785_ram_clk_ops = {
.recalc = ram_clk_recalc,
};
static struct clk sh7785_ram_clk = {
.name = "ram_clk",
.flags = CLK_ALWAYS_ENABLED,
.ops = &sh7785_ram_clk_ops,
};
/*
* Additional SH7785-specific on-chip clocks that aren't already part of the
* clock framework
*/
static struct clk *sh7785_onchip_clocks[] = {
&sh7785_shyway_clk,
&sh7785_ddr_clk,
&sh7785_ram_clk,
};
static int __init sh7785_clk_init(void)
{
struct clk *clk = clk_get(NULL, "master_clk");
int i;
for (i = 0; i < ARRAY_SIZE(sh7785_onchip_clocks); i++) {
struct clk *clkp = sh7785_onchip_clocks[i];
clkp->parent = clk;
clk_register(clkp);
clk_enable(clkp);
}
/*
* Now that we have the rest of the clocks registered, we need to
* force the parent clock to propagate so that these clocks will
* automatically figure out their rate. We cheat by handing the
* parent clock its current rate and forcing child propagation.
*/
clk_set_rate(clk, clk_get_rate(clk));
clk_put(clk);
return 0;
}
arch_initcall(sh7785_clk_init);
| gpl-2.0 |
gem5/linux-arm-gem5 | drivers/block/drbd/drbd_state.c | 978 | 58970 | /*
drbd_state.c
This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
Thanks to Carter Burden, Bart Grantham and Gennadiy Nerubayev
from Logicworks, Inc. for making SDP replication support possible.
drbd 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.
drbd 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 drbd; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/drbd_limits.h>
#include "drbd_int.h"
#include "drbd_protocol.h"
#include "drbd_req.h"
struct after_state_chg_work {
struct drbd_work w;
struct drbd_device *device;
union drbd_state os;
union drbd_state ns;
enum chg_state_flags flags;
struct completion *done;
};
enum sanitize_state_warnings {
NO_WARNING,
ABORTED_ONLINE_VERIFY,
ABORTED_RESYNC,
CONNECTION_LOST_NEGOTIATING,
IMPLICITLY_UPGRADED_DISK,
IMPLICITLY_UPGRADED_PDSK,
};
static int w_after_state_ch(struct drbd_work *w, int unused);
static void after_state_ch(struct drbd_device *device, union drbd_state os,
union drbd_state ns, enum chg_state_flags flags);
static enum drbd_state_rv is_valid_state(struct drbd_device *, union drbd_state);
static enum drbd_state_rv is_valid_soft_transition(union drbd_state, union drbd_state, struct drbd_connection *);
static enum drbd_state_rv is_valid_transition(union drbd_state os, union drbd_state ns);
static union drbd_state sanitize_state(struct drbd_device *device, union drbd_state os,
union drbd_state ns, enum sanitize_state_warnings *warn);
static inline bool is_susp(union drbd_state s)
{
return s.susp || s.susp_nod || s.susp_fen;
}
bool conn_all_vols_unconf(struct drbd_connection *connection)
{
struct drbd_peer_device *peer_device;
bool rv = true;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
if (device->state.disk != D_DISKLESS ||
device->state.conn != C_STANDALONE ||
device->state.role != R_SECONDARY) {
rv = false;
break;
}
}
rcu_read_unlock();
return rv;
}
/* Unfortunately the states where not correctly ordered, when
they where defined. therefore can not use max_t() here. */
static enum drbd_role max_role(enum drbd_role role1, enum drbd_role role2)
{
if (role1 == R_PRIMARY || role2 == R_PRIMARY)
return R_PRIMARY;
if (role1 == R_SECONDARY || role2 == R_SECONDARY)
return R_SECONDARY;
return R_UNKNOWN;
}
static enum drbd_role min_role(enum drbd_role role1, enum drbd_role role2)
{
if (role1 == R_UNKNOWN || role2 == R_UNKNOWN)
return R_UNKNOWN;
if (role1 == R_SECONDARY || role2 == R_SECONDARY)
return R_SECONDARY;
return R_PRIMARY;
}
enum drbd_role conn_highest_role(struct drbd_connection *connection)
{
enum drbd_role role = R_UNKNOWN;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
role = max_role(role, device->state.role);
}
rcu_read_unlock();
return role;
}
enum drbd_role conn_highest_peer(struct drbd_connection *connection)
{
enum drbd_role peer = R_UNKNOWN;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
peer = max_role(peer, device->state.peer);
}
rcu_read_unlock();
return peer;
}
enum drbd_disk_state conn_highest_disk(struct drbd_connection *connection)
{
enum drbd_disk_state disk_state = D_DISKLESS;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
disk_state = max_t(enum drbd_disk_state, disk_state, device->state.disk);
}
rcu_read_unlock();
return disk_state;
}
enum drbd_disk_state conn_lowest_disk(struct drbd_connection *connection)
{
enum drbd_disk_state disk_state = D_MASK;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
disk_state = min_t(enum drbd_disk_state, disk_state, device->state.disk);
}
rcu_read_unlock();
return disk_state;
}
enum drbd_disk_state conn_highest_pdsk(struct drbd_connection *connection)
{
enum drbd_disk_state disk_state = D_DISKLESS;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
disk_state = max_t(enum drbd_disk_state, disk_state, device->state.pdsk);
}
rcu_read_unlock();
return disk_state;
}
enum drbd_conns conn_lowest_conn(struct drbd_connection *connection)
{
enum drbd_conns conn = C_MASK;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
conn = min_t(enum drbd_conns, conn, device->state.conn);
}
rcu_read_unlock();
return conn;
}
static bool no_peer_wf_report_params(struct drbd_connection *connection)
{
struct drbd_peer_device *peer_device;
int vnr;
bool rv = true;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr)
if (peer_device->device->state.conn == C_WF_REPORT_PARAMS) {
rv = false;
break;
}
rcu_read_unlock();
return rv;
}
static void wake_up_all_devices(struct drbd_connection *connection)
{
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr)
wake_up(&peer_device->device->state_wait);
rcu_read_unlock();
}
/**
* cl_wide_st_chg() - true if the state change is a cluster wide one
* @device: DRBD device.
* @os: old (current) state.
* @ns: new (wanted) state.
*/
static int cl_wide_st_chg(struct drbd_device *device,
union drbd_state os, union drbd_state ns)
{
return (os.conn >= C_CONNECTED && ns.conn >= C_CONNECTED &&
((os.role != R_PRIMARY && ns.role == R_PRIMARY) ||
(os.conn != C_STARTING_SYNC_T && ns.conn == C_STARTING_SYNC_T) ||
(os.conn != C_STARTING_SYNC_S && ns.conn == C_STARTING_SYNC_S) ||
(os.disk != D_FAILED && ns.disk == D_FAILED))) ||
(os.conn >= C_CONNECTED && ns.conn == C_DISCONNECTING) ||
(os.conn == C_CONNECTED && ns.conn == C_VERIFY_S) ||
(os.conn == C_CONNECTED && ns.conn == C_WF_REPORT_PARAMS);
}
static union drbd_state
apply_mask_val(union drbd_state os, union drbd_state mask, union drbd_state val)
{
union drbd_state ns;
ns.i = (os.i & ~mask.i) | val.i;
return ns;
}
enum drbd_state_rv
drbd_change_state(struct drbd_device *device, enum chg_state_flags f,
union drbd_state mask, union drbd_state val)
{
unsigned long flags;
union drbd_state ns;
enum drbd_state_rv rv;
spin_lock_irqsave(&device->resource->req_lock, flags);
ns = apply_mask_val(drbd_read_state(device), mask, val);
rv = _drbd_set_state(device, ns, f, NULL);
spin_unlock_irqrestore(&device->resource->req_lock, flags);
return rv;
}
/**
* drbd_force_state() - Impose a change which happens outside our control on our state
* @device: DRBD device.
* @mask: mask of state bits to change.
* @val: value of new state bits.
*/
void drbd_force_state(struct drbd_device *device,
union drbd_state mask, union drbd_state val)
{
drbd_change_state(device, CS_HARD, mask, val);
}
static enum drbd_state_rv
_req_st_cond(struct drbd_device *device, union drbd_state mask,
union drbd_state val)
{
union drbd_state os, ns;
unsigned long flags;
enum drbd_state_rv rv;
if (test_and_clear_bit(CL_ST_CHG_SUCCESS, &device->flags))
return SS_CW_SUCCESS;
if (test_and_clear_bit(CL_ST_CHG_FAIL, &device->flags))
return SS_CW_FAILED_BY_PEER;
spin_lock_irqsave(&device->resource->req_lock, flags);
os = drbd_read_state(device);
ns = sanitize_state(device, os, apply_mask_val(os, mask, val), NULL);
rv = is_valid_transition(os, ns);
if (rv >= SS_SUCCESS)
rv = SS_UNKNOWN_ERROR; /* cont waiting, otherwise fail. */
if (!cl_wide_st_chg(device, os, ns))
rv = SS_CW_NO_NEED;
if (rv == SS_UNKNOWN_ERROR) {
rv = is_valid_state(device, ns);
if (rv >= SS_SUCCESS) {
rv = is_valid_soft_transition(os, ns, first_peer_device(device)->connection);
if (rv >= SS_SUCCESS)
rv = SS_UNKNOWN_ERROR; /* cont waiting, otherwise fail. */
}
}
spin_unlock_irqrestore(&device->resource->req_lock, flags);
return rv;
}
/**
* drbd_req_state() - Perform an eventually cluster wide state change
* @device: DRBD device.
* @mask: mask of state bits to change.
* @val: value of new state bits.
* @f: flags
*
* Should not be called directly, use drbd_request_state() or
* _drbd_request_state().
*/
static enum drbd_state_rv
drbd_req_state(struct drbd_device *device, union drbd_state mask,
union drbd_state val, enum chg_state_flags f)
{
struct completion done;
unsigned long flags;
union drbd_state os, ns;
enum drbd_state_rv rv;
init_completion(&done);
if (f & CS_SERIALIZE)
mutex_lock(device->state_mutex);
spin_lock_irqsave(&device->resource->req_lock, flags);
os = drbd_read_state(device);
ns = sanitize_state(device, os, apply_mask_val(os, mask, val), NULL);
rv = is_valid_transition(os, ns);
if (rv < SS_SUCCESS) {
spin_unlock_irqrestore(&device->resource->req_lock, flags);
goto abort;
}
if (cl_wide_st_chg(device, os, ns)) {
rv = is_valid_state(device, ns);
if (rv == SS_SUCCESS)
rv = is_valid_soft_transition(os, ns, first_peer_device(device)->connection);
spin_unlock_irqrestore(&device->resource->req_lock, flags);
if (rv < SS_SUCCESS) {
if (f & CS_VERBOSE)
print_st_err(device, os, ns, rv);
goto abort;
}
if (drbd_send_state_req(first_peer_device(device), mask, val)) {
rv = SS_CW_FAILED_BY_PEER;
if (f & CS_VERBOSE)
print_st_err(device, os, ns, rv);
goto abort;
}
wait_event(device->state_wait,
(rv = _req_st_cond(device, mask, val)));
if (rv < SS_SUCCESS) {
if (f & CS_VERBOSE)
print_st_err(device, os, ns, rv);
goto abort;
}
spin_lock_irqsave(&device->resource->req_lock, flags);
ns = apply_mask_val(drbd_read_state(device), mask, val);
rv = _drbd_set_state(device, ns, f, &done);
} else {
rv = _drbd_set_state(device, ns, f, &done);
}
spin_unlock_irqrestore(&device->resource->req_lock, flags);
if (f & CS_WAIT_COMPLETE && rv == SS_SUCCESS) {
D_ASSERT(device, current != first_peer_device(device)->connection->worker.task);
wait_for_completion(&done);
}
abort:
if (f & CS_SERIALIZE)
mutex_unlock(device->state_mutex);
return rv;
}
/**
* _drbd_request_state() - Request a state change (with flags)
* @device: DRBD device.
* @mask: mask of state bits to change.
* @val: value of new state bits.
* @f: flags
*
* Cousin of drbd_request_state(), useful with the CS_WAIT_COMPLETE
* flag, or when logging of failed state change requests is not desired.
*/
enum drbd_state_rv
_drbd_request_state(struct drbd_device *device, union drbd_state mask,
union drbd_state val, enum chg_state_flags f)
{
enum drbd_state_rv rv;
wait_event(device->state_wait,
(rv = drbd_req_state(device, mask, val, f)) != SS_IN_TRANSIENT_STATE);
return rv;
}
enum drbd_state_rv
_drbd_request_state_holding_state_mutex(struct drbd_device *device, union drbd_state mask,
union drbd_state val, enum chg_state_flags f)
{
enum drbd_state_rv rv;
BUG_ON(f & CS_SERIALIZE);
wait_event_cmd(device->state_wait,
(rv = drbd_req_state(device, mask, val, f)) != SS_IN_TRANSIENT_STATE,
mutex_unlock(device->state_mutex),
mutex_lock(device->state_mutex));
return rv;
}
static void print_st(struct drbd_device *device, const char *name, union drbd_state ns)
{
drbd_err(device, " %s = { cs:%s ro:%s/%s ds:%s/%s %c%c%c%c%c%c }\n",
name,
drbd_conn_str(ns.conn),
drbd_role_str(ns.role),
drbd_role_str(ns.peer),
drbd_disk_str(ns.disk),
drbd_disk_str(ns.pdsk),
is_susp(ns) ? 's' : 'r',
ns.aftr_isp ? 'a' : '-',
ns.peer_isp ? 'p' : '-',
ns.user_isp ? 'u' : '-',
ns.susp_fen ? 'F' : '-',
ns.susp_nod ? 'N' : '-'
);
}
void print_st_err(struct drbd_device *device, union drbd_state os,
union drbd_state ns, enum drbd_state_rv err)
{
if (err == SS_IN_TRANSIENT_STATE)
return;
drbd_err(device, "State change failed: %s\n", drbd_set_st_err_str(err));
print_st(device, " state", os);
print_st(device, "wanted", ns);
}
static long print_state_change(char *pb, union drbd_state os, union drbd_state ns,
enum chg_state_flags flags)
{
char *pbp;
pbp = pb;
*pbp = 0;
if (ns.role != os.role && flags & CS_DC_ROLE)
pbp += sprintf(pbp, "role( %s -> %s ) ",
drbd_role_str(os.role),
drbd_role_str(ns.role));
if (ns.peer != os.peer && flags & CS_DC_PEER)
pbp += sprintf(pbp, "peer( %s -> %s ) ",
drbd_role_str(os.peer),
drbd_role_str(ns.peer));
if (ns.conn != os.conn && flags & CS_DC_CONN)
pbp += sprintf(pbp, "conn( %s -> %s ) ",
drbd_conn_str(os.conn),
drbd_conn_str(ns.conn));
if (ns.disk != os.disk && flags & CS_DC_DISK)
pbp += sprintf(pbp, "disk( %s -> %s ) ",
drbd_disk_str(os.disk),
drbd_disk_str(ns.disk));
if (ns.pdsk != os.pdsk && flags & CS_DC_PDSK)
pbp += sprintf(pbp, "pdsk( %s -> %s ) ",
drbd_disk_str(os.pdsk),
drbd_disk_str(ns.pdsk));
return pbp - pb;
}
static void drbd_pr_state_change(struct drbd_device *device, union drbd_state os, union drbd_state ns,
enum chg_state_flags flags)
{
char pb[300];
char *pbp = pb;
pbp += print_state_change(pbp, os, ns, flags ^ CS_DC_MASK);
if (ns.aftr_isp != os.aftr_isp)
pbp += sprintf(pbp, "aftr_isp( %d -> %d ) ",
os.aftr_isp,
ns.aftr_isp);
if (ns.peer_isp != os.peer_isp)
pbp += sprintf(pbp, "peer_isp( %d -> %d ) ",
os.peer_isp,
ns.peer_isp);
if (ns.user_isp != os.user_isp)
pbp += sprintf(pbp, "user_isp( %d -> %d ) ",
os.user_isp,
ns.user_isp);
if (pbp != pb)
drbd_info(device, "%s\n", pb);
}
static void conn_pr_state_change(struct drbd_connection *connection, union drbd_state os, union drbd_state ns,
enum chg_state_flags flags)
{
char pb[300];
char *pbp = pb;
pbp += print_state_change(pbp, os, ns, flags);
if (is_susp(ns) != is_susp(os) && flags & CS_DC_SUSP)
pbp += sprintf(pbp, "susp( %d -> %d ) ",
is_susp(os),
is_susp(ns));
if (pbp != pb)
drbd_info(connection, "%s\n", pb);
}
/**
* is_valid_state() - Returns an SS_ error code if ns is not valid
* @device: DRBD device.
* @ns: State to consider.
*/
static enum drbd_state_rv
is_valid_state(struct drbd_device *device, union drbd_state ns)
{
/* See drbd_state_sw_errors in drbd_strings.c */
enum drbd_fencing_p fp;
enum drbd_state_rv rv = SS_SUCCESS;
struct net_conf *nc;
rcu_read_lock();
fp = FP_DONT_CARE;
if (get_ldev(device)) {
fp = rcu_dereference(device->ldev->disk_conf)->fencing;
put_ldev(device);
}
nc = rcu_dereference(first_peer_device(device)->connection->net_conf);
if (nc) {
if (!nc->two_primaries && ns.role == R_PRIMARY) {
if (ns.peer == R_PRIMARY)
rv = SS_TWO_PRIMARIES;
else if (conn_highest_peer(first_peer_device(device)->connection) == R_PRIMARY)
rv = SS_O_VOL_PEER_PRI;
}
}
if (rv <= 0)
/* already found a reason to abort */;
else if (ns.role == R_SECONDARY && device->open_cnt)
rv = SS_DEVICE_IN_USE;
else if (ns.role == R_PRIMARY && ns.conn < C_CONNECTED && ns.disk < D_UP_TO_DATE)
rv = SS_NO_UP_TO_DATE_DISK;
else if (fp >= FP_RESOURCE &&
ns.role == R_PRIMARY && ns.conn < C_CONNECTED && ns.pdsk >= D_UNKNOWN)
rv = SS_PRIMARY_NOP;
else if (ns.role == R_PRIMARY && ns.disk <= D_INCONSISTENT && ns.pdsk <= D_INCONSISTENT)
rv = SS_NO_UP_TO_DATE_DISK;
else if (ns.conn > C_CONNECTED && ns.disk < D_INCONSISTENT)
rv = SS_NO_LOCAL_DISK;
else if (ns.conn > C_CONNECTED && ns.pdsk < D_INCONSISTENT)
rv = SS_NO_REMOTE_DISK;
else if (ns.conn > C_CONNECTED && ns.disk < D_UP_TO_DATE && ns.pdsk < D_UP_TO_DATE)
rv = SS_NO_UP_TO_DATE_DISK;
else if ((ns.conn == C_CONNECTED ||
ns.conn == C_WF_BITMAP_S ||
ns.conn == C_SYNC_SOURCE ||
ns.conn == C_PAUSED_SYNC_S) &&
ns.disk == D_OUTDATED)
rv = SS_CONNECTED_OUTDATES;
else if ((ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T) &&
(nc->verify_alg[0] == 0))
rv = SS_NO_VERIFY_ALG;
else if ((ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T) &&
first_peer_device(device)->connection->agreed_pro_version < 88)
rv = SS_NOT_SUPPORTED;
else if (ns.role == R_PRIMARY && ns.disk < D_UP_TO_DATE && ns.pdsk < D_UP_TO_DATE)
rv = SS_NO_UP_TO_DATE_DISK;
else if ((ns.conn == C_STARTING_SYNC_S || ns.conn == C_STARTING_SYNC_T) &&
ns.pdsk == D_UNKNOWN)
rv = SS_NEED_CONNECTION;
else if (ns.conn >= C_CONNECTED && ns.pdsk == D_UNKNOWN)
rv = SS_CONNECTED_OUTDATES;
rcu_read_unlock();
return rv;
}
/**
* is_valid_soft_transition() - Returns an SS_ error code if the state transition is not possible
* This function limits state transitions that may be declined by DRBD. I.e.
* user requests (aka soft transitions).
* @device: DRBD device.
* @ns: new state.
* @os: old state.
*/
static enum drbd_state_rv
is_valid_soft_transition(union drbd_state os, union drbd_state ns, struct drbd_connection *connection)
{
enum drbd_state_rv rv = SS_SUCCESS;
if ((ns.conn == C_STARTING_SYNC_T || ns.conn == C_STARTING_SYNC_S) &&
os.conn > C_CONNECTED)
rv = SS_RESYNC_RUNNING;
if (ns.conn == C_DISCONNECTING && os.conn == C_STANDALONE)
rv = SS_ALREADY_STANDALONE;
if (ns.disk > D_ATTACHING && os.disk == D_DISKLESS)
rv = SS_IS_DISKLESS;
if (ns.conn == C_WF_CONNECTION && os.conn < C_UNCONNECTED)
rv = SS_NO_NET_CONFIG;
if (ns.disk == D_OUTDATED && os.disk < D_OUTDATED && os.disk != D_ATTACHING)
rv = SS_LOWER_THAN_OUTDATED;
if (ns.conn == C_DISCONNECTING && os.conn == C_UNCONNECTED)
rv = SS_IN_TRANSIENT_STATE;
/* While establishing a connection only allow cstate to change.
Delay/refuse role changes, detach attach etc... (they do not touch cstate) */
if (test_bit(STATE_SENT, &connection->flags) &&
!((ns.conn == C_WF_REPORT_PARAMS && os.conn == C_WF_CONNECTION) ||
(ns.conn >= C_CONNECTED && os.conn == C_WF_REPORT_PARAMS)))
rv = SS_IN_TRANSIENT_STATE;
if ((ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T) && os.conn < C_CONNECTED)
rv = SS_NEED_CONNECTION;
if ((ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T) &&
ns.conn != os.conn && os.conn > C_CONNECTED)
rv = SS_RESYNC_RUNNING;
if ((ns.conn == C_STARTING_SYNC_S || ns.conn == C_STARTING_SYNC_T) &&
os.conn < C_CONNECTED)
rv = SS_NEED_CONNECTION;
if ((ns.conn == C_SYNC_TARGET || ns.conn == C_SYNC_SOURCE)
&& os.conn < C_WF_REPORT_PARAMS)
rv = SS_NEED_CONNECTION; /* No NetworkFailure -> SyncTarget etc... */
if (ns.conn == C_DISCONNECTING && ns.pdsk == D_OUTDATED &&
os.conn < C_CONNECTED && os.pdsk > D_OUTDATED)
rv = SS_OUTDATE_WO_CONN;
return rv;
}
static enum drbd_state_rv
is_valid_conn_transition(enum drbd_conns oc, enum drbd_conns nc)
{
/* no change -> nothing to do, at least for the connection part */
if (oc == nc)
return SS_NOTHING_TO_DO;
/* disconnect of an unconfigured connection does not make sense */
if (oc == C_STANDALONE && nc == C_DISCONNECTING)
return SS_ALREADY_STANDALONE;
/* from C_STANDALONE, we start with C_UNCONNECTED */
if (oc == C_STANDALONE && nc != C_UNCONNECTED)
return SS_NEED_CONNECTION;
/* When establishing a connection we need to go through WF_REPORT_PARAMS!
Necessary to do the right thing upon invalidate-remote on a disconnected resource */
if (oc < C_WF_REPORT_PARAMS && nc >= C_CONNECTED)
return SS_NEED_CONNECTION;
/* After a network error only C_UNCONNECTED or C_DISCONNECTING may follow. */
if (oc >= C_TIMEOUT && oc <= C_TEAR_DOWN && nc != C_UNCONNECTED && nc != C_DISCONNECTING)
return SS_IN_TRANSIENT_STATE;
/* After C_DISCONNECTING only C_STANDALONE may follow */
if (oc == C_DISCONNECTING && nc != C_STANDALONE)
return SS_IN_TRANSIENT_STATE;
return SS_SUCCESS;
}
/**
* is_valid_transition() - Returns an SS_ error code if the state transition is not possible
* This limits hard state transitions. Hard state transitions are facts there are
* imposed on DRBD by the environment. E.g. disk broke or network broke down.
* But those hard state transitions are still not allowed to do everything.
* @ns: new state.
* @os: old state.
*/
static enum drbd_state_rv
is_valid_transition(union drbd_state os, union drbd_state ns)
{
enum drbd_state_rv rv;
rv = is_valid_conn_transition(os.conn, ns.conn);
/* we cannot fail (again) if we already detached */
if (ns.disk == D_FAILED && os.disk == D_DISKLESS)
rv = SS_IS_DISKLESS;
return rv;
}
static void print_sanitize_warnings(struct drbd_device *device, enum sanitize_state_warnings warn)
{
static const char *msg_table[] = {
[NO_WARNING] = "",
[ABORTED_ONLINE_VERIFY] = "Online-verify aborted.",
[ABORTED_RESYNC] = "Resync aborted.",
[CONNECTION_LOST_NEGOTIATING] = "Connection lost while negotiating, no data!",
[IMPLICITLY_UPGRADED_DISK] = "Implicitly upgraded disk",
[IMPLICITLY_UPGRADED_PDSK] = "Implicitly upgraded pdsk",
};
if (warn != NO_WARNING)
drbd_warn(device, "%s\n", msg_table[warn]);
}
/**
* sanitize_state() - Resolves implicitly necessary additional changes to a state transition
* @device: DRBD device.
* @os: old state.
* @ns: new state.
* @warn_sync_abort:
*
* When we loose connection, we have to set the state of the peers disk (pdsk)
* to D_UNKNOWN. This rule and many more along those lines are in this function.
*/
static union drbd_state sanitize_state(struct drbd_device *device, union drbd_state os,
union drbd_state ns, enum sanitize_state_warnings *warn)
{
enum drbd_fencing_p fp;
enum drbd_disk_state disk_min, disk_max, pdsk_min, pdsk_max;
if (warn)
*warn = NO_WARNING;
fp = FP_DONT_CARE;
if (get_ldev(device)) {
rcu_read_lock();
fp = rcu_dereference(device->ldev->disk_conf)->fencing;
rcu_read_unlock();
put_ldev(device);
}
/* Implications from connection to peer and peer_isp */
if (ns.conn < C_CONNECTED) {
ns.peer_isp = 0;
ns.peer = R_UNKNOWN;
if (ns.pdsk > D_UNKNOWN || ns.pdsk < D_INCONSISTENT)
ns.pdsk = D_UNKNOWN;
}
/* Clear the aftr_isp when becoming unconfigured */
if (ns.conn == C_STANDALONE && ns.disk == D_DISKLESS && ns.role == R_SECONDARY)
ns.aftr_isp = 0;
/* An implication of the disk states onto the connection state */
/* Abort resync if a disk fails/detaches */
if (ns.conn > C_CONNECTED && (ns.disk <= D_FAILED || ns.pdsk <= D_FAILED)) {
if (warn)
*warn = ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T ?
ABORTED_ONLINE_VERIFY : ABORTED_RESYNC;
ns.conn = C_CONNECTED;
}
/* Connection breaks down before we finished "Negotiating" */
if (ns.conn < C_CONNECTED && ns.disk == D_NEGOTIATING &&
get_ldev_if_state(device, D_NEGOTIATING)) {
if (device->ed_uuid == device->ldev->md.uuid[UI_CURRENT]) {
ns.disk = device->new_state_tmp.disk;
ns.pdsk = device->new_state_tmp.pdsk;
} else {
if (warn)
*warn = CONNECTION_LOST_NEGOTIATING;
ns.disk = D_DISKLESS;
ns.pdsk = D_UNKNOWN;
}
put_ldev(device);
}
/* D_CONSISTENT and D_OUTDATED vanish when we get connected */
if (ns.conn >= C_CONNECTED && ns.conn < C_AHEAD) {
if (ns.disk == D_CONSISTENT || ns.disk == D_OUTDATED)
ns.disk = D_UP_TO_DATE;
if (ns.pdsk == D_CONSISTENT || ns.pdsk == D_OUTDATED)
ns.pdsk = D_UP_TO_DATE;
}
/* Implications of the connection stat on the disk states */
disk_min = D_DISKLESS;
disk_max = D_UP_TO_DATE;
pdsk_min = D_INCONSISTENT;
pdsk_max = D_UNKNOWN;
switch ((enum drbd_conns)ns.conn) {
case C_WF_BITMAP_T:
case C_PAUSED_SYNC_T:
case C_STARTING_SYNC_T:
case C_WF_SYNC_UUID:
case C_BEHIND:
disk_min = D_INCONSISTENT;
disk_max = D_OUTDATED;
pdsk_min = D_UP_TO_DATE;
pdsk_max = D_UP_TO_DATE;
break;
case C_VERIFY_S:
case C_VERIFY_T:
disk_min = D_UP_TO_DATE;
disk_max = D_UP_TO_DATE;
pdsk_min = D_UP_TO_DATE;
pdsk_max = D_UP_TO_DATE;
break;
case C_CONNECTED:
disk_min = D_DISKLESS;
disk_max = D_UP_TO_DATE;
pdsk_min = D_DISKLESS;
pdsk_max = D_UP_TO_DATE;
break;
case C_WF_BITMAP_S:
case C_PAUSED_SYNC_S:
case C_STARTING_SYNC_S:
case C_AHEAD:
disk_min = D_UP_TO_DATE;
disk_max = D_UP_TO_DATE;
pdsk_min = D_INCONSISTENT;
pdsk_max = D_CONSISTENT; /* D_OUTDATED would be nice. But explicit outdate necessary*/
break;
case C_SYNC_TARGET:
disk_min = D_INCONSISTENT;
disk_max = D_INCONSISTENT;
pdsk_min = D_UP_TO_DATE;
pdsk_max = D_UP_TO_DATE;
break;
case C_SYNC_SOURCE:
disk_min = D_UP_TO_DATE;
disk_max = D_UP_TO_DATE;
pdsk_min = D_INCONSISTENT;
pdsk_max = D_INCONSISTENT;
break;
case C_STANDALONE:
case C_DISCONNECTING:
case C_UNCONNECTED:
case C_TIMEOUT:
case C_BROKEN_PIPE:
case C_NETWORK_FAILURE:
case C_PROTOCOL_ERROR:
case C_TEAR_DOWN:
case C_WF_CONNECTION:
case C_WF_REPORT_PARAMS:
case C_MASK:
break;
}
if (ns.disk > disk_max)
ns.disk = disk_max;
if (ns.disk < disk_min) {
if (warn)
*warn = IMPLICITLY_UPGRADED_DISK;
ns.disk = disk_min;
}
if (ns.pdsk > pdsk_max)
ns.pdsk = pdsk_max;
if (ns.pdsk < pdsk_min) {
if (warn)
*warn = IMPLICITLY_UPGRADED_PDSK;
ns.pdsk = pdsk_min;
}
if (fp == FP_STONITH &&
(ns.role == R_PRIMARY && ns.conn < C_CONNECTED && ns.pdsk > D_OUTDATED) &&
!(os.role == R_PRIMARY && os.conn < C_CONNECTED && os.pdsk > D_OUTDATED))
ns.susp_fen = 1; /* Suspend IO while fence-peer handler runs (peer lost) */
if (device->resource->res_opts.on_no_data == OND_SUSPEND_IO &&
(ns.role == R_PRIMARY && ns.disk < D_UP_TO_DATE && ns.pdsk < D_UP_TO_DATE) &&
!(os.role == R_PRIMARY && os.disk < D_UP_TO_DATE && os.pdsk < D_UP_TO_DATE))
ns.susp_nod = 1; /* Suspend IO while no data available (no accessible data available) */
if (ns.aftr_isp || ns.peer_isp || ns.user_isp) {
if (ns.conn == C_SYNC_SOURCE)
ns.conn = C_PAUSED_SYNC_S;
if (ns.conn == C_SYNC_TARGET)
ns.conn = C_PAUSED_SYNC_T;
} else {
if (ns.conn == C_PAUSED_SYNC_S)
ns.conn = C_SYNC_SOURCE;
if (ns.conn == C_PAUSED_SYNC_T)
ns.conn = C_SYNC_TARGET;
}
return ns;
}
void drbd_resume_al(struct drbd_device *device)
{
if (test_and_clear_bit(AL_SUSPENDED, &device->flags))
drbd_info(device, "Resumed AL updates\n");
}
/* helper for __drbd_set_state */
static void set_ov_position(struct drbd_device *device, enum drbd_conns cs)
{
if (first_peer_device(device)->connection->agreed_pro_version < 90)
device->ov_start_sector = 0;
device->rs_total = drbd_bm_bits(device);
device->ov_position = 0;
if (cs == C_VERIFY_T) {
/* starting online verify from an arbitrary position
* does not fit well into the existing protocol.
* on C_VERIFY_T, we initialize ov_left and friends
* implicitly in receive_DataRequest once the
* first P_OV_REQUEST is received */
device->ov_start_sector = ~(sector_t)0;
} else {
unsigned long bit = BM_SECT_TO_BIT(device->ov_start_sector);
if (bit >= device->rs_total) {
device->ov_start_sector =
BM_BIT_TO_SECT(device->rs_total - 1);
device->rs_total = 1;
} else
device->rs_total -= bit;
device->ov_position = device->ov_start_sector;
}
device->ov_left = device->rs_total;
}
/**
* __drbd_set_state() - Set a new DRBD state
* @device: DRBD device.
* @ns: new state.
* @flags: Flags
* @done: Optional completion, that will get completed after the after_state_ch() finished
*
* Caller needs to hold req_lock, and global_state_lock. Do not call directly.
*/
enum drbd_state_rv
__drbd_set_state(struct drbd_device *device, union drbd_state ns,
enum chg_state_flags flags, struct completion *done)
{
struct drbd_peer_device *peer_device = first_peer_device(device);
struct drbd_connection *connection = peer_device ? peer_device->connection : NULL;
union drbd_state os;
enum drbd_state_rv rv = SS_SUCCESS;
enum sanitize_state_warnings ssw;
struct after_state_chg_work *ascw;
os = drbd_read_state(device);
ns = sanitize_state(device, os, ns, &ssw);
if (ns.i == os.i)
return SS_NOTHING_TO_DO;
rv = is_valid_transition(os, ns);
if (rv < SS_SUCCESS)
return rv;
if (!(flags & CS_HARD)) {
/* pre-state-change checks ; only look at ns */
/* See drbd_state_sw_errors in drbd_strings.c */
rv = is_valid_state(device, ns);
if (rv < SS_SUCCESS) {
/* If the old state was illegal as well, then let
this happen...*/
if (is_valid_state(device, os) == rv)
rv = is_valid_soft_transition(os, ns, connection);
} else
rv = is_valid_soft_transition(os, ns, connection);
}
if (rv < SS_SUCCESS) {
if (flags & CS_VERBOSE)
print_st_err(device, os, ns, rv);
return rv;
}
print_sanitize_warnings(device, ssw);
drbd_pr_state_change(device, os, ns, flags);
/* Display changes to the susp* flags that where caused by the call to
sanitize_state(). Only display it here if we where not called from
_conn_request_state() */
if (!(flags & CS_DC_SUSP))
conn_pr_state_change(connection, os, ns,
(flags & ~CS_DC_MASK) | CS_DC_SUSP);
/* if we are going -> D_FAILED or D_DISKLESS, grab one extra reference
* on the ldev here, to be sure the transition -> D_DISKLESS resp.
* drbd_ldev_destroy() won't happen before our corresponding
* after_state_ch works run, where we put_ldev again. */
if ((os.disk != D_FAILED && ns.disk == D_FAILED) ||
(os.disk != D_DISKLESS && ns.disk == D_DISKLESS))
atomic_inc(&device->local_cnt);
if (!is_sync_state(os.conn) && is_sync_state(ns.conn))
clear_bit(RS_DONE, &device->flags);
/* changes to local_cnt and device flags should be visible before
* changes to state, which again should be visible before anything else
* depending on that change happens. */
smp_wmb();
device->state.i = ns.i;
device->resource->susp = ns.susp;
device->resource->susp_nod = ns.susp_nod;
device->resource->susp_fen = ns.susp_fen;
smp_wmb();
/* put replicated vs not-replicated requests in seperate epochs */
if (drbd_should_do_remote((union drbd_dev_state)os.i) !=
drbd_should_do_remote((union drbd_dev_state)ns.i))
start_new_tl_epoch(connection);
if (os.disk == D_ATTACHING && ns.disk >= D_NEGOTIATING)
drbd_print_uuids(device, "attached to UUIDs");
/* Wake up role changes, that were delayed because of connection establishing */
if (os.conn == C_WF_REPORT_PARAMS && ns.conn != C_WF_REPORT_PARAMS &&
no_peer_wf_report_params(connection)) {
clear_bit(STATE_SENT, &connection->flags);
wake_up_all_devices(connection);
}
wake_up(&device->misc_wait);
wake_up(&device->state_wait);
wake_up(&connection->ping_wait);
/* Aborted verify run, or we reached the stop sector.
* Log the last position, unless end-of-device. */
if ((os.conn == C_VERIFY_S || os.conn == C_VERIFY_T) &&
ns.conn <= C_CONNECTED) {
device->ov_start_sector =
BM_BIT_TO_SECT(drbd_bm_bits(device) - device->ov_left);
if (device->ov_left)
drbd_info(device, "Online Verify reached sector %llu\n",
(unsigned long long)device->ov_start_sector);
}
if ((os.conn == C_PAUSED_SYNC_T || os.conn == C_PAUSED_SYNC_S) &&
(ns.conn == C_SYNC_TARGET || ns.conn == C_SYNC_SOURCE)) {
drbd_info(device, "Syncer continues.\n");
device->rs_paused += (long)jiffies
-(long)device->rs_mark_time[device->rs_last_mark];
if (ns.conn == C_SYNC_TARGET)
mod_timer(&device->resync_timer, jiffies);
}
if ((os.conn == C_SYNC_TARGET || os.conn == C_SYNC_SOURCE) &&
(ns.conn == C_PAUSED_SYNC_T || ns.conn == C_PAUSED_SYNC_S)) {
drbd_info(device, "Resync suspended\n");
device->rs_mark_time[device->rs_last_mark] = jiffies;
}
if (os.conn == C_CONNECTED &&
(ns.conn == C_VERIFY_S || ns.conn == C_VERIFY_T)) {
unsigned long now = jiffies;
int i;
set_ov_position(device, ns.conn);
device->rs_start = now;
device->rs_last_sect_ev = 0;
device->ov_last_oos_size = 0;
device->ov_last_oos_start = 0;
for (i = 0; i < DRBD_SYNC_MARKS; i++) {
device->rs_mark_left[i] = device->ov_left;
device->rs_mark_time[i] = now;
}
drbd_rs_controller_reset(device);
if (ns.conn == C_VERIFY_S) {
drbd_info(device, "Starting Online Verify from sector %llu\n",
(unsigned long long)device->ov_position);
mod_timer(&device->resync_timer, jiffies);
}
}
if (get_ldev(device)) {
u32 mdf = device->ldev->md.flags & ~(MDF_CONSISTENT|MDF_PRIMARY_IND|
MDF_CONNECTED_IND|MDF_WAS_UP_TO_DATE|
MDF_PEER_OUT_DATED|MDF_CRASHED_PRIMARY);
mdf &= ~MDF_AL_CLEAN;
if (test_bit(CRASHED_PRIMARY, &device->flags))
mdf |= MDF_CRASHED_PRIMARY;
if (device->state.role == R_PRIMARY ||
(device->state.pdsk < D_INCONSISTENT && device->state.peer == R_PRIMARY))
mdf |= MDF_PRIMARY_IND;
if (device->state.conn > C_WF_REPORT_PARAMS)
mdf |= MDF_CONNECTED_IND;
if (device->state.disk > D_INCONSISTENT)
mdf |= MDF_CONSISTENT;
if (device->state.disk > D_OUTDATED)
mdf |= MDF_WAS_UP_TO_DATE;
if (device->state.pdsk <= D_OUTDATED && device->state.pdsk >= D_INCONSISTENT)
mdf |= MDF_PEER_OUT_DATED;
if (mdf != device->ldev->md.flags) {
device->ldev->md.flags = mdf;
drbd_md_mark_dirty(device);
}
if (os.disk < D_CONSISTENT && ns.disk >= D_CONSISTENT)
drbd_set_ed_uuid(device, device->ldev->md.uuid[UI_CURRENT]);
put_ldev(device);
}
/* Peer was forced D_UP_TO_DATE & R_PRIMARY, consider to resync */
if (os.disk == D_INCONSISTENT && os.pdsk == D_INCONSISTENT &&
os.peer == R_SECONDARY && ns.peer == R_PRIMARY)
set_bit(CONSIDER_RESYNC, &device->flags);
/* Receiver should clean up itself */
if (os.conn != C_DISCONNECTING && ns.conn == C_DISCONNECTING)
drbd_thread_stop_nowait(&connection->receiver);
/* Now the receiver finished cleaning up itself, it should die */
if (os.conn != C_STANDALONE && ns.conn == C_STANDALONE)
drbd_thread_stop_nowait(&connection->receiver);
/* Upon network failure, we need to restart the receiver. */
if (os.conn > C_WF_CONNECTION &&
ns.conn <= C_TEAR_DOWN && ns.conn >= C_TIMEOUT)
drbd_thread_restart_nowait(&connection->receiver);
/* Resume AL writing if we get a connection */
if (os.conn < C_CONNECTED && ns.conn >= C_CONNECTED) {
drbd_resume_al(device);
connection->connect_cnt++;
}
/* remember last attach time so request_timer_fn() won't
* kill newly established sessions while we are still trying to thaw
* previously frozen IO */
if ((os.disk == D_ATTACHING || os.disk == D_NEGOTIATING) &&
ns.disk > D_NEGOTIATING)
device->last_reattach_jif = jiffies;
ascw = kmalloc(sizeof(*ascw), GFP_ATOMIC);
if (ascw) {
ascw->os = os;
ascw->ns = ns;
ascw->flags = flags;
ascw->w.cb = w_after_state_ch;
ascw->device = device;
ascw->done = done;
drbd_queue_work(&connection->sender_work,
&ascw->w);
} else {
drbd_err(device, "Could not kmalloc an ascw\n");
}
return rv;
}
static int w_after_state_ch(struct drbd_work *w, int unused)
{
struct after_state_chg_work *ascw =
container_of(w, struct after_state_chg_work, w);
struct drbd_device *device = ascw->device;
after_state_ch(device, ascw->os, ascw->ns, ascw->flags);
if (ascw->flags & CS_WAIT_COMPLETE)
complete(ascw->done);
kfree(ascw);
return 0;
}
static void abw_start_sync(struct drbd_device *device, int rv)
{
if (rv) {
drbd_err(device, "Writing the bitmap failed not starting resync.\n");
_drbd_request_state(device, NS(conn, C_CONNECTED), CS_VERBOSE);
return;
}
switch (device->state.conn) {
case C_STARTING_SYNC_T:
_drbd_request_state(device, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE);
break;
case C_STARTING_SYNC_S:
drbd_start_resync(device, C_SYNC_SOURCE);
break;
}
}
int drbd_bitmap_io_from_worker(struct drbd_device *device,
int (*io_fn)(struct drbd_device *),
char *why, enum bm_flag flags)
{
int rv;
D_ASSERT(device, current == first_peer_device(device)->connection->worker.task);
/* open coded non-blocking drbd_suspend_io(device); */
set_bit(SUSPEND_IO, &device->flags);
drbd_bm_lock(device, why, flags);
rv = io_fn(device);
drbd_bm_unlock(device);
drbd_resume_io(device);
return rv;
}
/**
* after_state_ch() - Perform after state change actions that may sleep
* @device: DRBD device.
* @os: old state.
* @ns: new state.
* @flags: Flags
*/
static void after_state_ch(struct drbd_device *device, union drbd_state os,
union drbd_state ns, enum chg_state_flags flags)
{
struct drbd_resource *resource = device->resource;
struct drbd_peer_device *peer_device = first_peer_device(device);
struct drbd_connection *connection = peer_device ? peer_device->connection : NULL;
struct sib_info sib;
sib.sib_reason = SIB_STATE_CHANGE;
sib.os = os;
sib.ns = ns;
if ((os.disk != D_UP_TO_DATE || os.pdsk != D_UP_TO_DATE)
&& (ns.disk == D_UP_TO_DATE && ns.pdsk == D_UP_TO_DATE)) {
clear_bit(CRASHED_PRIMARY, &device->flags);
if (device->p_uuid)
device->p_uuid[UI_FLAGS] &= ~((u64)2);
}
/* Inform userspace about the change... */
drbd_bcast_event(device, &sib);
if (!(os.role == R_PRIMARY && os.disk < D_UP_TO_DATE && os.pdsk < D_UP_TO_DATE) &&
(ns.role == R_PRIMARY && ns.disk < D_UP_TO_DATE && ns.pdsk < D_UP_TO_DATE))
drbd_khelper(device, "pri-on-incon-degr");
/* Here we have the actions that are performed after a
state change. This function might sleep */
if (ns.susp_nod) {
enum drbd_req_event what = NOTHING;
spin_lock_irq(&device->resource->req_lock);
if (os.conn < C_CONNECTED && conn_lowest_conn(connection) >= C_CONNECTED)
what = RESEND;
if ((os.disk == D_ATTACHING || os.disk == D_NEGOTIATING) &&
conn_lowest_disk(connection) > D_NEGOTIATING)
what = RESTART_FROZEN_DISK_IO;
if (resource->susp_nod && what != NOTHING) {
_tl_restart(connection, what);
_conn_request_state(connection,
(union drbd_state) { { .susp_nod = 1 } },
(union drbd_state) { { .susp_nod = 0 } },
CS_VERBOSE);
}
spin_unlock_irq(&device->resource->req_lock);
}
if (ns.susp_fen) {
spin_lock_irq(&device->resource->req_lock);
if (resource->susp_fen && conn_lowest_conn(connection) >= C_CONNECTED) {
/* case2: The connection was established again: */
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr)
clear_bit(NEW_CUR_UUID, &peer_device->device->flags);
rcu_read_unlock();
_tl_restart(connection, RESEND);
_conn_request_state(connection,
(union drbd_state) { { .susp_fen = 1 } },
(union drbd_state) { { .susp_fen = 0 } },
CS_VERBOSE);
}
spin_unlock_irq(&device->resource->req_lock);
}
/* Became sync source. With protocol >= 96, we still need to send out
* the sync uuid now. Need to do that before any drbd_send_state, or
* the other side may go "paused sync" before receiving the sync uuids,
* which is unexpected. */
if ((os.conn != C_SYNC_SOURCE && os.conn != C_PAUSED_SYNC_S) &&
(ns.conn == C_SYNC_SOURCE || ns.conn == C_PAUSED_SYNC_S) &&
connection->agreed_pro_version >= 96 && get_ldev(device)) {
drbd_gen_and_send_sync_uuid(peer_device);
put_ldev(device);
}
/* Do not change the order of the if above and the two below... */
if (os.pdsk == D_DISKLESS &&
ns.pdsk > D_DISKLESS && ns.pdsk != D_UNKNOWN) { /* attach on the peer */
/* we probably will start a resync soon.
* make sure those things are properly reset. */
device->rs_total = 0;
device->rs_failed = 0;
atomic_set(&device->rs_pending_cnt, 0);
drbd_rs_cancel_all(device);
drbd_send_uuids(peer_device);
drbd_send_state(peer_device, ns);
}
/* No point in queuing send_bitmap if we don't have a connection
* anymore, so check also the _current_ state, not only the new state
* at the time this work was queued. */
if (os.conn != C_WF_BITMAP_S && ns.conn == C_WF_BITMAP_S &&
device->state.conn == C_WF_BITMAP_S)
drbd_queue_bitmap_io(device, &drbd_send_bitmap, NULL,
"send_bitmap (WFBitMapS)",
BM_LOCKED_TEST_ALLOWED);
/* Lost contact to peer's copy of the data */
if ((os.pdsk >= D_INCONSISTENT &&
os.pdsk != D_UNKNOWN &&
os.pdsk != D_OUTDATED)
&& (ns.pdsk < D_INCONSISTENT ||
ns.pdsk == D_UNKNOWN ||
ns.pdsk == D_OUTDATED)) {
if (get_ldev(device)) {
if ((ns.role == R_PRIMARY || ns.peer == R_PRIMARY) &&
device->ldev->md.uuid[UI_BITMAP] == 0 && ns.disk >= D_UP_TO_DATE) {
if (drbd_suspended(device)) {
set_bit(NEW_CUR_UUID, &device->flags);
} else {
drbd_uuid_new_current(device);
drbd_send_uuids(peer_device);
}
}
put_ldev(device);
}
}
if (ns.pdsk < D_INCONSISTENT && get_ldev(device)) {
if (os.peer == R_SECONDARY && ns.peer == R_PRIMARY &&
device->ldev->md.uuid[UI_BITMAP] == 0 && ns.disk >= D_UP_TO_DATE) {
drbd_uuid_new_current(device);
drbd_send_uuids(peer_device);
}
/* D_DISKLESS Peer becomes secondary */
if (os.peer == R_PRIMARY && ns.peer == R_SECONDARY)
/* We may still be Primary ourselves.
* No harm done if the bitmap still changes,
* redirtied pages will follow later. */
drbd_bitmap_io_from_worker(device, &drbd_bm_write,
"demote diskless peer", BM_LOCKED_SET_ALLOWED);
put_ldev(device);
}
/* Write out all changed bits on demote.
* Though, no need to da that just yet
* if there is a resync going on still */
if (os.role == R_PRIMARY && ns.role == R_SECONDARY &&
device->state.conn <= C_CONNECTED && get_ldev(device)) {
/* No changes to the bitmap expected this time, so assert that,
* even though no harm was done if it did change. */
drbd_bitmap_io_from_worker(device, &drbd_bm_write,
"demote", BM_LOCKED_TEST_ALLOWED);
put_ldev(device);
}
/* Last part of the attaching process ... */
if (ns.conn >= C_CONNECTED &&
os.disk == D_ATTACHING && ns.disk == D_NEGOTIATING) {
drbd_send_sizes(peer_device, 0, 0); /* to start sync... */
drbd_send_uuids(peer_device);
drbd_send_state(peer_device, ns);
}
/* We want to pause/continue resync, tell peer. */
if (ns.conn >= C_CONNECTED &&
((os.aftr_isp != ns.aftr_isp) ||
(os.user_isp != ns.user_isp)))
drbd_send_state(peer_device, ns);
/* In case one of the isp bits got set, suspend other devices. */
if ((!os.aftr_isp && !os.peer_isp && !os.user_isp) &&
(ns.aftr_isp || ns.peer_isp || ns.user_isp))
suspend_other_sg(device);
/* Make sure the peer gets informed about eventual state
changes (ISP bits) while we were in WFReportParams. */
if (os.conn == C_WF_REPORT_PARAMS && ns.conn >= C_CONNECTED)
drbd_send_state(peer_device, ns);
if (os.conn != C_AHEAD && ns.conn == C_AHEAD)
drbd_send_state(peer_device, ns);
/* We are in the progress to start a full sync... */
if ((os.conn != C_STARTING_SYNC_T && ns.conn == C_STARTING_SYNC_T) ||
(os.conn != C_STARTING_SYNC_S && ns.conn == C_STARTING_SYNC_S))
/* no other bitmap changes expected during this phase */
drbd_queue_bitmap_io(device,
&drbd_bmio_set_n_write, &abw_start_sync,
"set_n_write from StartingSync", BM_LOCKED_TEST_ALLOWED);
/* first half of local IO error, failure to attach,
* or administrative detach */
if (os.disk != D_FAILED && ns.disk == D_FAILED) {
enum drbd_io_error_p eh = EP_PASS_ON;
int was_io_error = 0;
/* corresponding get_ldev was in __drbd_set_state, to serialize
* our cleanup here with the transition to D_DISKLESS.
* But is is still not save to dreference ldev here, since
* we might come from an failed Attach before ldev was set. */
if (device->ldev) {
rcu_read_lock();
eh = rcu_dereference(device->ldev->disk_conf)->on_io_error;
rcu_read_unlock();
was_io_error = test_and_clear_bit(WAS_IO_ERROR, &device->flags);
if (was_io_error && eh == EP_CALL_HELPER)
drbd_khelper(device, "local-io-error");
/* Immediately allow completion of all application IO,
* that waits for completion from the local disk,
* if this was a force-detach due to disk_timeout
* or administrator request (drbdsetup detach --force).
* Do NOT abort otherwise.
* Aborting local requests may cause serious problems,
* if requests are completed to upper layers already,
* and then later the already submitted local bio completes.
* This can cause DMA into former bio pages that meanwhile
* have been re-used for other things.
* So aborting local requests may cause crashes,
* or even worse, silent data corruption.
*/
if (test_and_clear_bit(FORCE_DETACH, &device->flags))
tl_abort_disk_io(device);
/* current state still has to be D_FAILED,
* there is only one way out: to D_DISKLESS,
* and that may only happen after our put_ldev below. */
if (device->state.disk != D_FAILED)
drbd_err(device,
"ASSERT FAILED: disk is %s during detach\n",
drbd_disk_str(device->state.disk));
if (ns.conn >= C_CONNECTED)
drbd_send_state(peer_device, ns);
drbd_rs_cancel_all(device);
/* In case we want to get something to stable storage still,
* this may be the last chance.
* Following put_ldev may transition to D_DISKLESS. */
drbd_md_sync(device);
}
put_ldev(device);
}
/* second half of local IO error, failure to attach,
* or administrative detach,
* after local_cnt references have reached zero again */
if (os.disk != D_DISKLESS && ns.disk == D_DISKLESS) {
/* We must still be diskless,
* re-attach has to be serialized with this! */
if (device->state.disk != D_DISKLESS)
drbd_err(device,
"ASSERT FAILED: disk is %s while going diskless\n",
drbd_disk_str(device->state.disk));
if (ns.conn >= C_CONNECTED)
drbd_send_state(peer_device, ns);
/* corresponding get_ldev in __drbd_set_state
* this may finally trigger drbd_ldev_destroy. */
put_ldev(device);
}
/* Notify peer that I had a local IO error, and did not detached.. */
if (os.disk == D_UP_TO_DATE && ns.disk == D_INCONSISTENT && ns.conn >= C_CONNECTED)
drbd_send_state(peer_device, ns);
/* Disks got bigger while they were detached */
if (ns.disk > D_NEGOTIATING && ns.pdsk > D_NEGOTIATING &&
test_and_clear_bit(RESYNC_AFTER_NEG, &device->flags)) {
if (ns.conn == C_CONNECTED)
resync_after_online_grow(device);
}
/* A resync finished or aborted, wake paused devices... */
if ((os.conn > C_CONNECTED && ns.conn <= C_CONNECTED) ||
(os.peer_isp && !ns.peer_isp) ||
(os.user_isp && !ns.user_isp))
resume_next_sg(device);
/* sync target done with resync. Explicitly notify peer, even though
* it should (at least for non-empty resyncs) already know itself. */
if (os.disk < D_UP_TO_DATE && os.conn >= C_SYNC_SOURCE && ns.conn == C_CONNECTED)
drbd_send_state(peer_device, ns);
/* Verify finished, or reached stop sector. Peer did not know about
* the stop sector, and we may even have changed the stop sector during
* verify to interrupt/stop early. Send the new state. */
if (os.conn == C_VERIFY_S && ns.conn == C_CONNECTED
&& verify_can_do_stop_sector(device))
drbd_send_state(peer_device, ns);
/* This triggers bitmap writeout of potentially still unwritten pages
* if the resync finished cleanly, or aborted because of peer disk
* failure, or because of connection loss.
* For resync aborted because of local disk failure, we cannot do
* any bitmap writeout anymore.
* No harm done if some bits change during this phase.
*/
if (os.conn > C_CONNECTED && ns.conn <= C_CONNECTED && get_ldev(device)) {
drbd_queue_bitmap_io(device, &drbd_bm_write_copy_pages, NULL,
"write from resync_finished", BM_LOCKED_CHANGE_ALLOWED);
put_ldev(device);
}
if (ns.disk == D_DISKLESS &&
ns.conn == C_STANDALONE &&
ns.role == R_SECONDARY) {
if (os.aftr_isp != ns.aftr_isp)
resume_next_sg(device);
}
drbd_md_sync(device);
}
struct after_conn_state_chg_work {
struct drbd_work w;
enum drbd_conns oc;
union drbd_state ns_min;
union drbd_state ns_max; /* new, max state, over all devices */
enum chg_state_flags flags;
struct drbd_connection *connection;
};
static int w_after_conn_state_ch(struct drbd_work *w, int unused)
{
struct after_conn_state_chg_work *acscw =
container_of(w, struct after_conn_state_chg_work, w);
struct drbd_connection *connection = acscw->connection;
enum drbd_conns oc = acscw->oc;
union drbd_state ns_max = acscw->ns_max;
struct drbd_peer_device *peer_device;
int vnr;
kfree(acscw);
/* Upon network configuration, we need to start the receiver */
if (oc == C_STANDALONE && ns_max.conn == C_UNCONNECTED)
drbd_thread_start(&connection->receiver);
if (oc == C_DISCONNECTING && ns_max.conn == C_STANDALONE) {
struct net_conf *old_conf;
mutex_lock(&connection->resource->conf_update);
old_conf = connection->net_conf;
connection->my_addr_len = 0;
connection->peer_addr_len = 0;
RCU_INIT_POINTER(connection->net_conf, NULL);
conn_free_crypto(connection);
mutex_unlock(&connection->resource->conf_update);
synchronize_rcu();
kfree(old_conf);
}
if (ns_max.susp_fen) {
/* case1: The outdate peer handler is successful: */
if (ns_max.pdsk <= D_OUTDATED) {
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
if (test_bit(NEW_CUR_UUID, &device->flags)) {
drbd_uuid_new_current(device);
clear_bit(NEW_CUR_UUID, &device->flags);
}
}
rcu_read_unlock();
spin_lock_irq(&connection->resource->req_lock);
_tl_restart(connection, CONNECTION_LOST_WHILE_PENDING);
_conn_request_state(connection,
(union drbd_state) { { .susp_fen = 1 } },
(union drbd_state) { { .susp_fen = 0 } },
CS_VERBOSE);
spin_unlock_irq(&connection->resource->req_lock);
}
}
kref_put(&connection->kref, drbd_destroy_connection);
conn_md_sync(connection);
return 0;
}
static void conn_old_common_state(struct drbd_connection *connection, union drbd_state *pcs, enum chg_state_flags *pf)
{
enum chg_state_flags flags = ~0;
struct drbd_peer_device *peer_device;
int vnr, first_vol = 1;
union drbd_dev_state os, cs = {
{ .role = R_SECONDARY,
.peer = R_UNKNOWN,
.conn = connection->cstate,
.disk = D_DISKLESS,
.pdsk = D_UNKNOWN,
} };
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
os = device->state;
if (first_vol) {
cs = os;
first_vol = 0;
continue;
}
if (cs.role != os.role)
flags &= ~CS_DC_ROLE;
if (cs.peer != os.peer)
flags &= ~CS_DC_PEER;
if (cs.conn != os.conn)
flags &= ~CS_DC_CONN;
if (cs.disk != os.disk)
flags &= ~CS_DC_DISK;
if (cs.pdsk != os.pdsk)
flags &= ~CS_DC_PDSK;
}
rcu_read_unlock();
*pf |= CS_DC_MASK;
*pf &= flags;
(*pcs).i = cs.i;
}
static enum drbd_state_rv
conn_is_valid_transition(struct drbd_connection *connection, union drbd_state mask, union drbd_state val,
enum chg_state_flags flags)
{
enum drbd_state_rv rv = SS_SUCCESS;
union drbd_state ns, os;
struct drbd_peer_device *peer_device;
int vnr;
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
os = drbd_read_state(device);
ns = sanitize_state(device, os, apply_mask_val(os, mask, val), NULL);
if (flags & CS_IGN_OUTD_FAIL && ns.disk == D_OUTDATED && os.disk < D_OUTDATED)
ns.disk = os.disk;
if (ns.i == os.i)
continue;
rv = is_valid_transition(os, ns);
if (rv >= SS_SUCCESS && !(flags & CS_HARD)) {
rv = is_valid_state(device, ns);
if (rv < SS_SUCCESS) {
if (is_valid_state(device, os) == rv)
rv = is_valid_soft_transition(os, ns, connection);
} else
rv = is_valid_soft_transition(os, ns, connection);
}
if (rv < SS_SUCCESS) {
if (flags & CS_VERBOSE)
print_st_err(device, os, ns, rv);
break;
}
}
rcu_read_unlock();
return rv;
}
static void
conn_set_state(struct drbd_connection *connection, union drbd_state mask, union drbd_state val,
union drbd_state *pns_min, union drbd_state *pns_max, enum chg_state_flags flags)
{
union drbd_state ns, os, ns_max = { };
union drbd_state ns_min = {
{ .role = R_MASK,
.peer = R_MASK,
.conn = val.conn,
.disk = D_MASK,
.pdsk = D_MASK
} };
struct drbd_peer_device *peer_device;
enum drbd_state_rv rv;
int vnr, number_of_volumes = 0;
if (mask.conn == C_MASK) {
/* remember last connect time so request_timer_fn() won't
* kill newly established sessions while we are still trying to thaw
* previously frozen IO */
if (connection->cstate != C_WF_REPORT_PARAMS && val.conn == C_WF_REPORT_PARAMS)
connection->last_reconnect_jif = jiffies;
connection->cstate = val.conn;
}
rcu_read_lock();
idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
struct drbd_device *device = peer_device->device;
number_of_volumes++;
os = drbd_read_state(device);
ns = apply_mask_val(os, mask, val);
ns = sanitize_state(device, os, ns, NULL);
if (flags & CS_IGN_OUTD_FAIL && ns.disk == D_OUTDATED && os.disk < D_OUTDATED)
ns.disk = os.disk;
rv = __drbd_set_state(device, ns, flags, NULL);
if (rv < SS_SUCCESS)
BUG();
ns.i = device->state.i;
ns_max.role = max_role(ns.role, ns_max.role);
ns_max.peer = max_role(ns.peer, ns_max.peer);
ns_max.conn = max_t(enum drbd_conns, ns.conn, ns_max.conn);
ns_max.disk = max_t(enum drbd_disk_state, ns.disk, ns_max.disk);
ns_max.pdsk = max_t(enum drbd_disk_state, ns.pdsk, ns_max.pdsk);
ns_min.role = min_role(ns.role, ns_min.role);
ns_min.peer = min_role(ns.peer, ns_min.peer);
ns_min.conn = min_t(enum drbd_conns, ns.conn, ns_min.conn);
ns_min.disk = min_t(enum drbd_disk_state, ns.disk, ns_min.disk);
ns_min.pdsk = min_t(enum drbd_disk_state, ns.pdsk, ns_min.pdsk);
}
rcu_read_unlock();
if (number_of_volumes == 0) {
ns_min = ns_max = (union drbd_state) { {
.role = R_SECONDARY,
.peer = R_UNKNOWN,
.conn = val.conn,
.disk = D_DISKLESS,
.pdsk = D_UNKNOWN
} };
}
ns_min.susp = ns_max.susp = connection->resource->susp;
ns_min.susp_nod = ns_max.susp_nod = connection->resource->susp_nod;
ns_min.susp_fen = ns_max.susp_fen = connection->resource->susp_fen;
*pns_min = ns_min;
*pns_max = ns_max;
}
static enum drbd_state_rv
_conn_rq_cond(struct drbd_connection *connection, union drbd_state mask, union drbd_state val)
{
enum drbd_state_rv err, rv = SS_UNKNOWN_ERROR; /* continue waiting */;
if (test_and_clear_bit(CONN_WD_ST_CHG_OKAY, &connection->flags))
rv = SS_CW_SUCCESS;
if (test_and_clear_bit(CONN_WD_ST_CHG_FAIL, &connection->flags))
rv = SS_CW_FAILED_BY_PEER;
err = conn_is_valid_transition(connection, mask, val, 0);
if (err == SS_SUCCESS && connection->cstate == C_WF_REPORT_PARAMS)
return rv;
return err;
}
enum drbd_state_rv
_conn_request_state(struct drbd_connection *connection, union drbd_state mask, union drbd_state val,
enum chg_state_flags flags)
{
enum drbd_state_rv rv = SS_SUCCESS;
struct after_conn_state_chg_work *acscw;
enum drbd_conns oc = connection->cstate;
union drbd_state ns_max, ns_min, os;
bool have_mutex = false;
if (mask.conn) {
rv = is_valid_conn_transition(oc, val.conn);
if (rv < SS_SUCCESS)
goto abort;
}
rv = conn_is_valid_transition(connection, mask, val, flags);
if (rv < SS_SUCCESS)
goto abort;
if (oc == C_WF_REPORT_PARAMS && val.conn == C_DISCONNECTING &&
!(flags & (CS_LOCAL_ONLY | CS_HARD))) {
/* This will be a cluster-wide state change.
* Need to give up the spinlock, grab the mutex,
* then send the state change request, ... */
spin_unlock_irq(&connection->resource->req_lock);
mutex_lock(&connection->cstate_mutex);
have_mutex = true;
set_bit(CONN_WD_ST_CHG_REQ, &connection->flags);
if (conn_send_state_req(connection, mask, val)) {
/* sending failed. */
clear_bit(CONN_WD_ST_CHG_REQ, &connection->flags);
rv = SS_CW_FAILED_BY_PEER;
/* need to re-aquire the spin lock, though */
goto abort_unlocked;
}
if (val.conn == C_DISCONNECTING)
set_bit(DISCONNECT_SENT, &connection->flags);
/* ... and re-aquire the spinlock.
* If _conn_rq_cond() returned >= SS_SUCCESS, we must call
* conn_set_state() within the same spinlock. */
spin_lock_irq(&connection->resource->req_lock);
wait_event_lock_irq(connection->ping_wait,
(rv = _conn_rq_cond(connection, mask, val)),
connection->resource->req_lock);
clear_bit(CONN_WD_ST_CHG_REQ, &connection->flags);
if (rv < SS_SUCCESS)
goto abort;
}
conn_old_common_state(connection, &os, &flags);
flags |= CS_DC_SUSP;
conn_set_state(connection, mask, val, &ns_min, &ns_max, flags);
conn_pr_state_change(connection, os, ns_max, flags);
acscw = kmalloc(sizeof(*acscw), GFP_ATOMIC);
if (acscw) {
acscw->oc = os.conn;
acscw->ns_min = ns_min;
acscw->ns_max = ns_max;
acscw->flags = flags;
acscw->w.cb = w_after_conn_state_ch;
kref_get(&connection->kref);
acscw->connection = connection;
drbd_queue_work(&connection->sender_work, &acscw->w);
} else {
drbd_err(connection, "Could not kmalloc an acscw\n");
}
abort:
if (have_mutex) {
/* mutex_unlock() "... must not be used in interrupt context.",
* so give up the spinlock, then re-aquire it */
spin_unlock_irq(&connection->resource->req_lock);
abort_unlocked:
mutex_unlock(&connection->cstate_mutex);
spin_lock_irq(&connection->resource->req_lock);
}
if (rv < SS_SUCCESS && flags & CS_VERBOSE) {
drbd_err(connection, "State change failed: %s\n", drbd_set_st_err_str(rv));
drbd_err(connection, " mask = 0x%x val = 0x%x\n", mask.i, val.i);
drbd_err(connection, " old_conn:%s wanted_conn:%s\n", drbd_conn_str(oc), drbd_conn_str(val.conn));
}
return rv;
}
enum drbd_state_rv
conn_request_state(struct drbd_connection *connection, union drbd_state mask, union drbd_state val,
enum chg_state_flags flags)
{
enum drbd_state_rv rv;
spin_lock_irq(&connection->resource->req_lock);
rv = _conn_request_state(connection, mask, val, flags);
spin_unlock_irq(&connection->resource->req_lock);
return rv;
}
| gpl-2.0 |
olafdietsche/linux-accessfs | arch/cris/arch-v32/kernel/fasttimer.c | 978 | 21211 | /*
* linux/arch/cris/kernel/fasttimer.c
*
* Fast timers for ETRAX FS
*
* Copyright (C) 2000-2006 Axis Communications AB, Lund, Sweden
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/vmalloc.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/timer_defs.h>
#include <asm/fasttimer.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
/*
* timer0 is running at 100MHz and generating jiffies timer ticks
* at 100 or 1000 HZ.
* fasttimer gives an API that gives timers that expire "between" the jiffies
* giving microsecond resolution (10 ns).
* fasttimer uses reg_timer_rw_trig register to get interrupt when
* r_time reaches a certain value.
*/
#define DEBUG_LOG_INCLUDED
#define FAST_TIMER_LOG
/* #define FAST_TIMER_TEST */
#define FAST_TIMER_SANITY_CHECKS
#ifdef FAST_TIMER_SANITY_CHECKS
static int sanity_failed;
#endif
#define D1(x)
#define D2(x)
#define DP(x)
static unsigned int fast_timer_running;
static unsigned int fast_timers_added;
static unsigned int fast_timers_started;
static unsigned int fast_timers_expired;
static unsigned int fast_timers_deleted;
static unsigned int fast_timer_is_init;
static unsigned int fast_timer_ints;
struct fast_timer *fast_timer_list = NULL;
#ifdef DEBUG_LOG_INCLUDED
#define DEBUG_LOG_MAX 128
static const char * debug_log_string[DEBUG_LOG_MAX];
static unsigned long debug_log_value[DEBUG_LOG_MAX];
static unsigned int debug_log_cnt;
static unsigned int debug_log_cnt_wrapped;
#define DEBUG_LOG(string, value) \
{ \
unsigned long log_flags; \
local_irq_save(log_flags); \
debug_log_string[debug_log_cnt] = (string); \
debug_log_value[debug_log_cnt] = (unsigned long)(value); \
if (++debug_log_cnt >= DEBUG_LOG_MAX) \
{ \
debug_log_cnt = debug_log_cnt % DEBUG_LOG_MAX; \
debug_log_cnt_wrapped = 1; \
} \
local_irq_restore(log_flags); \
}
#else
#define DEBUG_LOG(string, value)
#endif
#define NUM_TIMER_STATS 16
#ifdef FAST_TIMER_LOG
struct fast_timer timer_added_log[NUM_TIMER_STATS];
struct fast_timer timer_started_log[NUM_TIMER_STATS];
struct fast_timer timer_expired_log[NUM_TIMER_STATS];
#endif
int timer_div_settings[NUM_TIMER_STATS];
int timer_delay_settings[NUM_TIMER_STATS];
struct work_struct fast_work;
static void
timer_trig_handler(struct work_struct *work);
/* Not true gettimeofday, only checks the jiffies (uptime) + useconds */
inline void do_gettimeofday_fast(struct fasttime_t *tv)
{
tv->tv_jiff = jiffies;
tv->tv_usec = GET_JIFFIES_USEC();
}
inline int fasttime_cmp(struct fasttime_t *t0, struct fasttime_t *t1)
{
/* Compare jiffies. Takes care of wrapping */
if (time_before(t0->tv_jiff, t1->tv_jiff))
return -1;
else if (time_after(t0->tv_jiff, t1->tv_jiff))
return 1;
/* Compare us */
if (t0->tv_usec < t1->tv_usec)
return -1;
else if (t0->tv_usec > t1->tv_usec)
return 1;
return 0;
}
/* Called with ints off */
inline void start_timer_trig(unsigned long delay_us)
{
reg_timer_rw_ack_intr ack_intr = { 0 };
reg_timer_rw_intr_mask intr_mask;
reg_timer_rw_trig trig;
reg_timer_rw_trig_cfg trig_cfg = { 0 };
reg_timer_r_time r_time0;
reg_timer_r_time r_time1;
unsigned char trig_wrap;
unsigned char time_wrap;
r_time0 = REG_RD(timer, regi_timer0, r_time);
D1(printk("start_timer_trig : %d us freq: %i div: %i\n",
delay_us, freq_index, div));
/* Clear trig irq */
intr_mask = REG_RD(timer, regi_timer0, rw_intr_mask);
intr_mask.trig = 0;
REG_WR(timer, regi_timer0, rw_intr_mask, intr_mask);
/* Set timer values and check if trigger wraps. */
/* r_time is 100MHz (10 ns resolution) */
trig_wrap = (trig = r_time0 + delay_us*(1000/10)) < r_time0;
timer_div_settings[fast_timers_started % NUM_TIMER_STATS] = trig;
timer_delay_settings[fast_timers_started % NUM_TIMER_STATS] = delay_us;
/* Ack interrupt */
ack_intr.trig = 1;
REG_WR(timer, regi_timer0, rw_ack_intr, ack_intr);
/* Start timer */
REG_WR(timer, regi_timer0, rw_trig, trig);
trig_cfg.tmr = regk_timer_time;
REG_WR(timer, regi_timer0, rw_trig_cfg, trig_cfg);
/* Check if we have already passed the trig time */
r_time1 = REG_RD(timer, regi_timer0, r_time);
time_wrap = r_time1 < r_time0;
if ((trig_wrap && !time_wrap) || (r_time1 < trig)) {
/* No, Enable trig irq */
intr_mask = REG_RD(timer, regi_timer0, rw_intr_mask);
intr_mask.trig = 1;
REG_WR(timer, regi_timer0, rw_intr_mask, intr_mask);
fast_timers_started++;
fast_timer_running = 1;
} else {
/* We have passed the time, disable trig point, ack intr */
trig_cfg.tmr = regk_timer_off;
REG_WR(timer, regi_timer0, rw_trig_cfg, trig_cfg);
REG_WR(timer, regi_timer0, rw_ack_intr, ack_intr);
/* call the int routine */
INIT_WORK(&fast_work, timer_trig_handler);
schedule_work(&fast_work);
}
}
/* In version 1.4 this function takes 27 - 50 us */
void start_one_shot_timer(struct fast_timer *t,
fast_timer_function_type *function,
unsigned long data,
unsigned long delay_us,
const char *name)
{
unsigned long flags;
struct fast_timer *tmp;
D1(printk("sft %s %d us\n", name, delay_us));
local_irq_save(flags);
do_gettimeofday_fast(&t->tv_set);
tmp = fast_timer_list;
#ifdef FAST_TIMER_SANITY_CHECKS
/* Check so this is not in the list already... */
while (tmp != NULL) {
if (tmp == t) {
printk(KERN_DEBUG
"timer name: %s data: 0x%08lX already "
"in list!\n", name, data);
sanity_failed++;
goto done;
} else
tmp = tmp->next;
}
tmp = fast_timer_list;
#endif
t->delay_us = delay_us;
t->function = function;
t->data = data;
t->name = name;
t->tv_expires.tv_usec = t->tv_set.tv_usec + delay_us % 1000000;
t->tv_expires.tv_jiff = t->tv_set.tv_jiff + delay_us / 1000000 / HZ;
if (t->tv_expires.tv_usec > 1000000) {
t->tv_expires.tv_usec -= 1000000;
t->tv_expires.tv_jiff += HZ;
}
#ifdef FAST_TIMER_LOG
timer_added_log[fast_timers_added % NUM_TIMER_STATS] = *t;
#endif
fast_timers_added++;
/* Check if this should timeout before anything else */
if (tmp == NULL || fasttime_cmp(&t->tv_expires, &tmp->tv_expires) < 0) {
/* Put first in list and modify the timer value */
t->prev = NULL;
t->next = fast_timer_list;
if (fast_timer_list)
fast_timer_list->prev = t;
fast_timer_list = t;
#ifdef FAST_TIMER_LOG
timer_started_log[fast_timers_started % NUM_TIMER_STATS] = *t;
#endif
start_timer_trig(delay_us);
} else {
/* Put in correct place in list */
while (tmp->next &&
fasttime_cmp(&t->tv_expires, &tmp->next->tv_expires) > 0)
tmp = tmp->next;
/* Insert t after tmp */
t->prev = tmp;
t->next = tmp->next;
if (tmp->next)
{
tmp->next->prev = t;
}
tmp->next = t;
}
D2(printk("start_one_shot_timer: %d us done\n", delay_us));
done:
local_irq_restore(flags);
} /* start_one_shot_timer */
static inline int fast_timer_pending (const struct fast_timer * t)
{
return (t->next != NULL) || (t->prev != NULL) || (t == fast_timer_list);
}
static inline int detach_fast_timer (struct fast_timer *t)
{
struct fast_timer *next, *prev;
if (!fast_timer_pending(t))
return 0;
next = t->next;
prev = t->prev;
if (next)
next->prev = prev;
if (prev)
prev->next = next;
else
fast_timer_list = next;
fast_timers_deleted++;
return 1;
}
int del_fast_timer(struct fast_timer * t)
{
unsigned long flags;
int ret;
local_irq_save(flags);
ret = detach_fast_timer(t);
t->next = t->prev = NULL;
local_irq_restore(flags);
return ret;
} /* del_fast_timer */
/* Interrupt routines or functions called in interrupt context */
/* Timer interrupt handler for trig interrupts */
static irqreturn_t
timer_trig_interrupt(int irq, void *dev_id)
{
reg_timer_r_masked_intr masked_intr;
/* Check if the timer interrupt is for us (a trig int) */
masked_intr = REG_RD(timer, regi_timer0, r_masked_intr);
if (!masked_intr.trig)
return IRQ_NONE;
timer_trig_handler(NULL);
return IRQ_HANDLED;
}
static void timer_trig_handler(struct work_struct *work)
{
reg_timer_rw_ack_intr ack_intr = { 0 };
reg_timer_rw_intr_mask intr_mask;
reg_timer_rw_trig_cfg trig_cfg = { 0 };
struct fast_timer *t;
unsigned long flags;
/* We keep interrupts disabled not only when we modify the
* fast timer list, but any time we hold a reference to a
* timer in the list, since del_fast_timer may be called
* from (another) interrupt context. Thus, the only time
* when interrupts are enabled is when calling the timer
* callback function.
*/
local_irq_save(flags);
/* Clear timer trig interrupt */
intr_mask = REG_RD(timer, regi_timer0, rw_intr_mask);
intr_mask.trig = 0;
REG_WR(timer, regi_timer0, rw_intr_mask, intr_mask);
/* First stop timer, then ack interrupt */
/* Stop timer */
trig_cfg.tmr = regk_timer_off;
REG_WR(timer, regi_timer0, rw_trig_cfg, trig_cfg);
/* Ack interrupt */
ack_intr.trig = 1;
REG_WR(timer, regi_timer0, rw_ack_intr, ack_intr);
fast_timer_running = 0;
fast_timer_ints++;
fast_timer_function_type *f;
unsigned long d;
t = fast_timer_list;
while (t) {
struct fasttime_t tv;
/* Has it really expired? */
do_gettimeofday_fast(&tv);
D1(printk(KERN_DEBUG
"t: %is %06ius\n", tv.tv_jiff, tv.tv_usec));
if (fasttime_cmp(&t->tv_expires, &tv) <= 0) {
/* Yes it has expired */
#ifdef FAST_TIMER_LOG
timer_expired_log[fast_timers_expired % NUM_TIMER_STATS] = *t;
#endif
fast_timers_expired++;
/* Remove this timer before call, since it may reuse the timer */
if (t->prev)
t->prev->next = t->next;
else
fast_timer_list = t->next;
if (t->next)
t->next->prev = t->prev;
t->prev = NULL;
t->next = NULL;
/* Save function callback data before enabling
* interrupts, since the timer may be removed and we
* don't know how it was allocated (e.g. ->function
* and ->data may become overwritten after deletion
* if the timer was stack-allocated).
*/
f = t->function;
d = t->data;
if (f != NULL) {
/* Run the callback function with interrupts
* enabled. */
local_irq_restore(flags);
f(d);
local_irq_save(flags);
} else
DEBUG_LOG("!trimertrig %i function==NULL!\n", fast_timer_ints);
} else {
/* Timer is to early, let's set it again using the normal routines */
D1(printk(".\n"));
}
t = fast_timer_list;
if (t != NULL) {
/* Start next timer.. */
long us = 0;
struct fasttime_t tv;
do_gettimeofday_fast(&tv);
/* time_after_eq takes care of wrapping */
if (time_after_eq(t->tv_expires.tv_jiff, tv.tv_jiff))
us = ((t->tv_expires.tv_jiff - tv.tv_jiff) *
1000000 / HZ + t->tv_expires.tv_usec -
tv.tv_usec);
if (us > 0) {
if (!fast_timer_running) {
#ifdef FAST_TIMER_LOG
timer_started_log[fast_timers_started % NUM_TIMER_STATS] = *t;
#endif
start_timer_trig(us);
}
break;
} else {
/* Timer already expired, let's handle it better late than never.
* The normal loop handles it
*/
D1(printk("e! %d\n", us));
}
}
}
local_irq_restore(flags);
if (!t)
D1(printk("ttrig stop!\n"));
}
static void wake_up_func(unsigned long data)
{
wait_queue_head_t *sleep_wait_p = (wait_queue_head_t*)data;
wake_up(sleep_wait_p);
}
/* Useful API */
void schedule_usleep(unsigned long us)
{
struct fast_timer t;
wait_queue_head_t sleep_wait;
init_waitqueue_head(&sleep_wait);
D1(printk("schedule_usleep(%d)\n", us));
start_one_shot_timer(&t, wake_up_func, (unsigned long)&sleep_wait, us,
"usleep");
/* Uninterruptible sleep on the fast timer. (The condition is
* somewhat redundant since the timer is what wakes us up.) */
wait_event(sleep_wait, !fast_timer_pending(&t));
D1(printk("done schedule_usleep(%d)\n", us));
}
#ifdef CONFIG_PROC_FS
/* This value is very much based on testing */
#define BIG_BUF_SIZE (500 + NUM_TIMER_STATS * 300)
static int proc_fasttimer_show(struct seq_file *m, void *v)
{
unsigned long flags;
int i = 0;
int num_to_show;
struct fasttime_t tv;
struct fast_timer *t, *nextt;
do_gettimeofday_fast(&tv);
seq_printf(m, "Fast timers added: %i\n", fast_timers_added);
seq_printf(m, "Fast timers started: %i\n", fast_timers_started);
seq_printf(m, "Fast timer interrupts: %i\n", fast_timer_ints);
seq_printf(m, "Fast timers expired: %i\n", fast_timers_expired);
seq_printf(m, "Fast timers deleted: %i\n", fast_timers_deleted);
seq_printf(m, "Fast timer running: %s\n",
fast_timer_running ? "yes" : "no");
seq_printf(m, "Current time: %lu.%06lu\n",
(unsigned long)tv.tv_jiff,
(unsigned long)tv.tv_usec);
#ifdef FAST_TIMER_SANITY_CHECKS
seq_printf(m, "Sanity failed: %i\n", sanity_failed);
#endif
seq_putc(m, '\n');
#ifdef DEBUG_LOG_INCLUDED
{
int end_i = debug_log_cnt;
i = 0;
if (debug_log_cnt_wrapped)
i = debug_log_cnt;
while ((i != end_i || debug_log_cnt_wrapped)) {
if (seq_printf(m, debug_log_string[i], debug_log_value[i]) < 0)
return 0;
i = (i+1) % DEBUG_LOG_MAX;
}
}
seq_putc(m, '\n');
#endif
num_to_show = (fast_timers_started < NUM_TIMER_STATS ? fast_timers_started:
NUM_TIMER_STATS);
seq_printf(m, "Timers started: %i\n", fast_timers_started);
for (i = 0; i < num_to_show; i++) {
int cur = (fast_timers_started - i - 1) % NUM_TIMER_STATS;
#if 1 //ndef FAST_TIMER_LOG
seq_printf(m, "div: %i delay: %i"
"\n",
timer_div_settings[cur],
timer_delay_settings[cur]);
#endif
#ifdef FAST_TIMER_LOG
t = &timer_started_log[cur];
if (seq_printf(m, "%-14s s: %6lu.%06lu e: %6lu.%06lu "
"d: %6li us data: 0x%08lX"
"\n",
t->name,
(unsigned long)t->tv_set.tv_jiff,
(unsigned long)t->tv_set.tv_usec,
(unsigned long)t->tv_expires.tv_jiff,
(unsigned long)t->tv_expires.tv_usec,
t->delay_us,
t->data) < 0)
return 0;
#endif
}
seq_putc(m, '\n');
#ifdef FAST_TIMER_LOG
num_to_show = (fast_timers_added < NUM_TIMER_STATS ? fast_timers_added:
NUM_TIMER_STATS);
seq_printf(m, "Timers added: %i\n", fast_timers_added);
for (i = 0; i < num_to_show; i++) {
t = &timer_added_log[(fast_timers_added - i - 1) % NUM_TIMER_STATS];
if (seq_printf(m, "%-14s s: %6lu.%06lu e: %6lu.%06lu "
"d: %6li us data: 0x%08lX"
"\n",
t->name,
(unsigned long)t->tv_set.tv_jiff,
(unsigned long)t->tv_set.tv_usec,
(unsigned long)t->tv_expires.tv_jiff,
(unsigned long)t->tv_expires.tv_usec,
t->delay_us,
t->data) < 0)
return 0;
}
seq_putc(m, '\n');
num_to_show = (fast_timers_expired < NUM_TIMER_STATS ? fast_timers_expired:
NUM_TIMER_STATS);
seq_printf(m, "Timers expired: %i\n", fast_timers_expired);
for (i = 0; i < num_to_show; i++){
t = &timer_expired_log[(fast_timers_expired - i - 1) % NUM_TIMER_STATS];
if (seq_printf(m, "%-14s s: %6lu.%06lu e: %6lu.%06lu "
"d: %6li us data: 0x%08lX"
"\n",
t->name,
(unsigned long)t->tv_set.tv_jiff,
(unsigned long)t->tv_set.tv_usec,
(unsigned long)t->tv_expires.tv_jiff,
(unsigned long)t->tv_expires.tv_usec,
t->delay_us,
t->data) < 0)
return 0;
}
seq_putc(m, '\n');
#endif
seq_puts(m, "Active timers:\n");
local_irq_save(flags);
t = fast_timer_list;
while (t != NULL){
nextt = t->next;
local_irq_restore(flags);
if (seq_printf(m, "%-14s s: %6lu.%06lu e: %6lu.%06lu "
"d: %6li us data: 0x%08lX"
/* " func: 0x%08lX" */
"\n",
t->name,
(unsigned long)t->tv_set.tv_jiff,
(unsigned long)t->tv_set.tv_usec,
(unsigned long)t->tv_expires.tv_jiff,
(unsigned long)t->tv_expires.tv_usec,
t->delay_us,
t->data
/* , t->function */
) < 0)
return 0;
local_irq_save(flags);
if (t->next != nextt)
printk("timer removed!\n");
t = nextt;
}
local_irq_restore(flags);
return 0;
}
static int proc_fasttimer_open(struct inode *inode, struct file *file)
{
return single_open_size(file, proc_fasttimer_show, PDE_DATA(inode), BIG_BUF_SIZE);
}
static const struct file_operations proc_fasttimer_fops = {
.open = proc_fasttimer_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* PROC_FS */
#ifdef FAST_TIMER_TEST
static volatile unsigned long i = 0;
static volatile int num_test_timeout = 0;
static struct fast_timer tr[10];
static int exp_num[10];
static struct fasttime_t tv_exp[100];
static void test_timeout(unsigned long data)
{
do_gettimeofday_fast(&tv_exp[data]);
exp_num[data] = num_test_timeout;
num_test_timeout++;
}
static void test_timeout1(unsigned long data)
{
do_gettimeofday_fast(&tv_exp[data]);
exp_num[data] = num_test_timeout;
if (data < 7)
{
start_one_shot_timer(&tr[i], test_timeout1, i, 1000, "timeout1");
i++;
}
num_test_timeout++;
}
DP(
static char buf0[2000];
static char buf1[2000];
static char buf2[2000];
static char buf3[2000];
static char buf4[2000];
);
static char buf5[6000];
static int j_u[1000];
static void fast_timer_test(void)
{
int prev_num;
int j;
struct fasttime_t tv, tv0, tv1, tv2;
printk("fast_timer_test() start\n");
do_gettimeofday_fast(&tv);
for (j = 0; j < 1000; j++)
{
j_u[j] = GET_JIFFIES_USEC();
}
for (j = 0; j < 100; j++)
{
do_gettimeofday_fast(&tv_exp[j]);
}
printk(KERN_DEBUG "fast_timer_test() %is %06i\n", tv.tv_jiff, tv.tv_usec);
for (j = 0; j < 1000; j++)
{
printk(KERN_DEBUG "%i %i %i %i %i\n",
j_u[j], j_u[j+1], j_u[j+2], j_u[j+3], j_u[j+4]);
j += 4;
}
for (j = 0; j < 100; j++)
{
printk(KERN_DEBUG "%i.%i %i.%i %i.%i %i.%i %i.%i\n",
tv_exp[j].tv_jiff, tv_exp[j].tv_usec,
tv_exp[j+1].tv_jiff, tv_exp[j+1].tv_usec,
tv_exp[j+2].tv_jiff, tv_exp[j+2].tv_usec,
tv_exp[j+3].tv_jiff, tv_exp[j+3].tv_usec,
tv_exp[j+4].tv_jiff, tv_exp[j+4].tv_usec);
j += 4;
}
do_gettimeofday_fast(&tv0);
start_one_shot_timer(&tr[i], test_timeout, i, 50000, "test0");
DP(proc_fasttimer_read(buf0, NULL, 0, 0, 0));
i++;
start_one_shot_timer(&tr[i], test_timeout, i, 70000, "test1");
DP(proc_fasttimer_read(buf1, NULL, 0, 0, 0));
i++;
start_one_shot_timer(&tr[i], test_timeout, i, 40000, "test2");
DP(proc_fasttimer_read(buf2, NULL, 0, 0, 0));
i++;
start_one_shot_timer(&tr[i], test_timeout, i, 60000, "test3");
DP(proc_fasttimer_read(buf3, NULL, 0, 0, 0));
i++;
start_one_shot_timer(&tr[i], test_timeout1, i, 55000, "test4xx");
DP(proc_fasttimer_read(buf4, NULL, 0, 0, 0));
i++;
do_gettimeofday_fast(&tv1);
proc_fasttimer_read(buf5, NULL, 0, 0, 0);
prev_num = num_test_timeout;
while (num_test_timeout < i)
{
if (num_test_timeout != prev_num)
prev_num = num_test_timeout;
}
do_gettimeofday_fast(&tv2);
printk(KERN_INFO "Timers started %is %06i\n",
tv0.tv_jiff, tv0.tv_usec);
printk(KERN_INFO "Timers started at %is %06i\n",
tv1.tv_jiff, tv1.tv_usec);
printk(KERN_INFO "Timers done %is %06i\n",
tv2.tv_jiff, tv2.tv_usec);
DP(printk("buf0:\n");
printk(buf0);
printk("buf1:\n");
printk(buf1);
printk("buf2:\n");
printk(buf2);
printk("buf3:\n");
printk(buf3);
printk("buf4:\n");
printk(buf4);
);
printk("buf5:\n");
printk(buf5);
printk("timers set:\n");
for(j = 0; j<i; j++)
{
struct fast_timer *t = &tr[j];
printk("%-10s set: %6is %06ius exp: %6is %06ius "
"data: 0x%08X func: 0x%08X\n",
t->name,
t->tv_set.tv_jiff,
t->tv_set.tv_usec,
t->tv_expires.tv_jiff,
t->tv_expires.tv_usec,
t->data,
t->function
);
printk(" del: %6ius did exp: %6is %06ius as #%i error: %6li\n",
t->delay_us,
tv_exp[j].tv_jiff,
tv_exp[j].tv_usec,
exp_num[j],
(tv_exp[j].tv_jiff - t->tv_expires.tv_jiff) *
1000000 + tv_exp[j].tv_usec -
t->tv_expires.tv_usec);
}
proc_fasttimer_read(buf5, NULL, 0, 0, 0);
printk("buf5 after all done:\n");
printk(buf5);
printk("fast_timer_test() done\n");
}
#endif
int fast_timer_init(void)
{
/* For some reason, request_irq() hangs when called froom time_init() */
if (!fast_timer_is_init)
{
printk("fast_timer_init()\n");
#ifdef CONFIG_PROC_FS
proc_create("fasttimer", 0, NULL, &proc_fasttimer_fops);
#endif /* PROC_FS */
if (request_irq(TIMER0_INTR_VECT, timer_trig_interrupt,
IRQF_SHARED,
"fast timer int", &fast_timer_list))
printk(KERN_ERR "err: fasttimer irq\n");
fast_timer_is_init = 1;
#ifdef FAST_TIMER_TEST
printk("do test\n");
fast_timer_test();
#endif
}
return 0;
}
__initcall(fast_timer_init);
| gpl-2.0 |
WFKipper/android_kernel_cyanogen_msm8916 | drivers/usb/gadget/f_phonet.c | 2258 | 15194 | /*
* f_phonet.c -- USB CDC Phonet function
*
* Copyright (C) 2007-2008 Nokia Corporation. All rights reserved.
*
* Author: Rémi Denis-Courmont
*
* 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/mm.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/netdevice.h>
#include <linux/if_ether.h>
#include <linux/if_phonet.h>
#include <linux/if_arp.h>
#include <linux/usb/ch9.h>
#include <linux/usb/cdc.h>
#include <linux/usb/composite.h>
#include "u_phonet.h"
#define PN_MEDIA_USB 0x1B
#define MAXPACKET 512
#if (PAGE_SIZE % MAXPACKET)
#error MAXPACKET must divide PAGE_SIZE!
#endif
/*-------------------------------------------------------------------------*/
struct phonet_port {
struct f_phonet *usb;
spinlock_t lock;
};
struct f_phonet {
struct usb_function function;
struct {
struct sk_buff *skb;
spinlock_t lock;
} rx;
struct net_device *dev;
struct usb_ep *in_ep, *out_ep;
struct usb_request *in_req;
struct usb_request *out_reqv[0];
};
static int phonet_rxq_size = 17;
static inline struct f_phonet *func_to_pn(struct usb_function *f)
{
return container_of(f, struct f_phonet, function);
}
/*-------------------------------------------------------------------------*/
#define USB_CDC_SUBCLASS_PHONET 0xfe
#define USB_CDC_PHONET_TYPE 0xab
static struct usb_interface_descriptor
pn_control_intf_desc = {
.bLength = sizeof pn_control_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_PHONET,
};
static const struct usb_cdc_header_desc
pn_header_desc = {
.bLength = sizeof pn_header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static const struct usb_cdc_header_desc
pn_phonet_desc = {
.bLength = sizeof pn_phonet_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_PHONET_TYPE,
.bcdCDC = cpu_to_le16(0x1505), /* ??? */
};
static struct usb_cdc_union_desc
pn_union_desc = {
.bLength = sizeof pn_union_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC, */
/* .bSlaveInterface0 = DYNAMIC, */
};
static struct usb_interface_descriptor
pn_data_nop_intf_desc = {
.bLength = sizeof pn_data_nop_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_CDC_DATA,
};
static struct usb_interface_descriptor
pn_data_intf_desc = {
.bLength = sizeof pn_data_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
};
static struct usb_endpoint_descriptor
pn_fs_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor
pn_hs_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(MAXPACKET),
};
static struct usb_endpoint_descriptor
pn_fs_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor
pn_hs_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *fs_pn_function[] = {
(struct usb_descriptor_header *) &pn_control_intf_desc,
(struct usb_descriptor_header *) &pn_header_desc,
(struct usb_descriptor_header *) &pn_phonet_desc,
(struct usb_descriptor_header *) &pn_union_desc,
(struct usb_descriptor_header *) &pn_data_nop_intf_desc,
(struct usb_descriptor_header *) &pn_data_intf_desc,
(struct usb_descriptor_header *) &pn_fs_sink_desc,
(struct usb_descriptor_header *) &pn_fs_source_desc,
NULL,
};
static struct usb_descriptor_header *hs_pn_function[] = {
(struct usb_descriptor_header *) &pn_control_intf_desc,
(struct usb_descriptor_header *) &pn_header_desc,
(struct usb_descriptor_header *) &pn_phonet_desc,
(struct usb_descriptor_header *) &pn_union_desc,
(struct usb_descriptor_header *) &pn_data_nop_intf_desc,
(struct usb_descriptor_header *) &pn_data_intf_desc,
(struct usb_descriptor_header *) &pn_hs_sink_desc,
(struct usb_descriptor_header *) &pn_hs_source_desc,
NULL,
};
/*-------------------------------------------------------------------------*/
static int pn_net_open(struct net_device *dev)
{
netif_wake_queue(dev);
return 0;
}
static int pn_net_close(struct net_device *dev)
{
netif_stop_queue(dev);
return 0;
}
static void pn_tx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_phonet *fp = ep->driver_data;
struct net_device *dev = fp->dev;
struct sk_buff *skb = req->context;
switch (req->status) {
case 0:
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
break;
case -ESHUTDOWN: /* disconnected */
case -ECONNRESET: /* disabled */
dev->stats.tx_aborted_errors++;
default:
dev->stats.tx_errors++;
}
dev_kfree_skb_any(skb);
netif_wake_queue(dev);
}
static int pn_net_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct phonet_port *port = netdev_priv(dev);
struct f_phonet *fp;
struct usb_request *req;
unsigned long flags;
if (skb->protocol != htons(ETH_P_PHONET))
goto out;
spin_lock_irqsave(&port->lock, flags);
fp = port->usb;
if (unlikely(!fp)) /* race with carrier loss */
goto out_unlock;
req = fp->in_req;
req->buf = skb->data;
req->length = skb->len;
req->complete = pn_tx_complete;
req->zero = 1;
req->context = skb;
if (unlikely(usb_ep_queue(fp->in_ep, req, GFP_ATOMIC)))
goto out_unlock;
netif_stop_queue(dev);
skb = NULL;
out_unlock:
spin_unlock_irqrestore(&port->lock, flags);
out:
if (unlikely(skb)) {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
}
return NETDEV_TX_OK;
}
static int pn_net_mtu(struct net_device *dev, int new_mtu)
{
if ((new_mtu < PHONET_MIN_MTU) || (new_mtu > PHONET_MAX_MTU))
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static const struct net_device_ops pn_netdev_ops = {
.ndo_open = pn_net_open,
.ndo_stop = pn_net_close,
.ndo_start_xmit = pn_net_xmit,
.ndo_change_mtu = pn_net_mtu,
};
static void pn_net_setup(struct net_device *dev)
{
dev->features = 0;
dev->type = ARPHRD_PHONET;
dev->flags = IFF_POINTOPOINT | IFF_NOARP;
dev->mtu = PHONET_DEV_MTU;
dev->hard_header_len = 1;
dev->dev_addr[0] = PN_MEDIA_USB;
dev->addr_len = 1;
dev->tx_queue_len = 1;
dev->netdev_ops = &pn_netdev_ops;
dev->destructor = free_netdev;
dev->header_ops = &phonet_header_ops;
}
/*-------------------------------------------------------------------------*/
/*
* Queue buffer for data from the host
*/
static int
pn_rx_submit(struct f_phonet *fp, struct usb_request *req, gfp_t gfp_flags)
{
struct page *page;
int err;
page = __skb_alloc_page(gfp_flags | __GFP_NOMEMALLOC, NULL);
if (!page)
return -ENOMEM;
req->buf = page_address(page);
req->length = PAGE_SIZE;
req->context = page;
err = usb_ep_queue(fp->out_ep, req, gfp_flags);
if (unlikely(err))
put_page(page);
return err;
}
static void pn_rx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_phonet *fp = ep->driver_data;
struct net_device *dev = fp->dev;
struct page *page = req->context;
struct sk_buff *skb;
unsigned long flags;
int status = req->status;
switch (status) {
case 0:
spin_lock_irqsave(&fp->rx.lock, flags);
skb = fp->rx.skb;
if (!skb)
skb = fp->rx.skb = netdev_alloc_skb(dev, 12);
if (req->actual < req->length) /* Last fragment */
fp->rx.skb = NULL;
spin_unlock_irqrestore(&fp->rx.lock, flags);
if (unlikely(!skb))
break;
if (skb->len == 0) { /* First fragment */
skb->protocol = htons(ETH_P_PHONET);
skb_reset_mac_header(skb);
/* Can't use pskb_pull() on page in IRQ */
memcpy(skb_put(skb, 1), page_address(page), 1);
}
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page,
skb->len <= 1, req->actual, PAGE_SIZE);
page = NULL;
if (req->actual < req->length) { /* Last fragment */
skb->dev = dev;
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
netif_rx(skb);
}
break;
/* Do not resubmit in these cases: */
case -ESHUTDOWN: /* disconnect */
case -ECONNABORTED: /* hw reset */
case -ECONNRESET: /* dequeued (unlink or netif down) */
req = NULL;
break;
/* Do resubmit in these cases: */
case -EOVERFLOW: /* request buffer overflow */
dev->stats.rx_over_errors++;
default:
dev->stats.rx_errors++;
break;
}
if (page)
put_page(page);
if (req)
pn_rx_submit(fp, req, GFP_ATOMIC | __GFP_COLD);
}
/*-------------------------------------------------------------------------*/
static void __pn_reset(struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
struct net_device *dev = fp->dev;
struct phonet_port *port = netdev_priv(dev);
netif_carrier_off(dev);
port->usb = NULL;
usb_ep_disable(fp->out_ep);
usb_ep_disable(fp->in_ep);
if (fp->rx.skb) {
dev_kfree_skb_irq(fp->rx.skb);
fp->rx.skb = NULL;
}
}
static int pn_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_phonet *fp = func_to_pn(f);
struct usb_gadget *gadget = fp->function.config->cdev->gadget;
if (intf == pn_control_intf_desc.bInterfaceNumber)
/* control interface, no altsetting */
return (alt > 0) ? -EINVAL : 0;
if (intf == pn_data_intf_desc.bInterfaceNumber) {
struct net_device *dev = fp->dev;
struct phonet_port *port = netdev_priv(dev);
/* data intf (0: inactive, 1: active) */
if (alt > 1)
return -EINVAL;
spin_lock(&port->lock);
__pn_reset(f);
if (alt == 1) {
int i;
if (config_ep_by_speed(gadget, f, fp->in_ep) ||
config_ep_by_speed(gadget, f, fp->out_ep)) {
fp->in_ep->desc = NULL;
fp->out_ep->desc = NULL;
spin_unlock(&port->lock);
return -EINVAL;
}
usb_ep_enable(fp->out_ep);
usb_ep_enable(fp->in_ep);
port->usb = fp;
fp->out_ep->driver_data = fp;
fp->in_ep->driver_data = fp;
netif_carrier_on(dev);
for (i = 0; i < phonet_rxq_size; i++)
pn_rx_submit(fp, fp->out_reqv[i], GFP_ATOMIC | __GFP_COLD);
}
spin_unlock(&port->lock);
return 0;
}
return -EINVAL;
}
static int pn_get_alt(struct usb_function *f, unsigned intf)
{
struct f_phonet *fp = func_to_pn(f);
if (intf == pn_control_intf_desc.bInterfaceNumber)
return 0;
if (intf == pn_data_intf_desc.bInterfaceNumber) {
struct phonet_port *port = netdev_priv(fp->dev);
u8 alt;
spin_lock(&port->lock);
alt = port->usb != NULL;
spin_unlock(&port->lock);
return alt;
}
return -EINVAL;
}
static void pn_disconnect(struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
struct phonet_port *port = netdev_priv(fp->dev);
unsigned long flags;
/* remain disabled until set_alt */
spin_lock_irqsave(&port->lock, flags);
__pn_reset(f);
spin_unlock_irqrestore(&port->lock, flags);
}
/*-------------------------------------------------------------------------*/
static __init
int pn_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct usb_gadget *gadget = cdev->gadget;
struct f_phonet *fp = func_to_pn(f);
struct usb_ep *ep;
int status, i;
/* Reserve interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto err;
pn_control_intf_desc.bInterfaceNumber = status;
pn_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto err;
pn_data_nop_intf_desc.bInterfaceNumber = status;
pn_data_intf_desc.bInterfaceNumber = status;
pn_union_desc.bSlaveInterface0 = status;
/* Reserve endpoints */
status = -ENODEV;
ep = usb_ep_autoconfig(gadget, &pn_fs_sink_desc);
if (!ep)
goto err;
fp->out_ep = ep;
ep->driver_data = fp; /* Claim */
ep = usb_ep_autoconfig(gadget, &pn_fs_source_desc);
if (!ep)
goto err;
fp->in_ep = ep;
ep->driver_data = fp; /* Claim */
pn_hs_sink_desc.bEndpointAddress = pn_fs_sink_desc.bEndpointAddress;
pn_hs_source_desc.bEndpointAddress = pn_fs_source_desc.bEndpointAddress;
/* Do not try to bind Phonet twice... */
status = usb_assign_descriptors(f, fs_pn_function, hs_pn_function,
NULL);
if (status)
goto err;
/* Incoming USB requests */
status = -ENOMEM;
for (i = 0; i < phonet_rxq_size; i++) {
struct usb_request *req;
req = usb_ep_alloc_request(fp->out_ep, GFP_KERNEL);
if (!req)
goto err_req;
req->complete = pn_rx_complete;
fp->out_reqv[i] = req;
}
/* Outgoing USB requests */
fp->in_req = usb_ep_alloc_request(fp->in_ep, GFP_KERNEL);
if (!fp->in_req)
goto err_req;
INFO(cdev, "USB CDC Phonet function\n");
INFO(cdev, "using %s, OUT %s, IN %s\n", cdev->gadget->name,
fp->out_ep->name, fp->in_ep->name);
return 0;
err_req:
for (i = 0; i < phonet_rxq_size && fp->out_reqv[i]; i++)
usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
err:
usb_free_all_descriptors(f);
if (fp->out_ep)
fp->out_ep->driver_data = NULL;
if (fp->in_ep)
fp->in_ep->driver_data = NULL;
ERROR(cdev, "USB CDC Phonet: cannot autoconfigure\n");
return status;
}
static void
pn_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
int i;
/* We are already disconnected */
if (fp->in_req)
usb_ep_free_request(fp->in_ep, fp->in_req);
for (i = 0; i < phonet_rxq_size; i++)
if (fp->out_reqv[i])
usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
usb_free_all_descriptors(f);
kfree(fp);
}
/*-------------------------------------------------------------------------*/
static struct net_device *dev;
int __init phonet_bind_config(struct usb_configuration *c)
{
struct f_phonet *fp;
int err, size;
size = sizeof(*fp) + (phonet_rxq_size * sizeof(struct usb_request *));
fp = kzalloc(size, GFP_KERNEL);
if (!fp)
return -ENOMEM;
fp->dev = dev;
fp->function.name = "phonet";
fp->function.bind = pn_bind;
fp->function.unbind = pn_unbind;
fp->function.set_alt = pn_set_alt;
fp->function.get_alt = pn_get_alt;
fp->function.disable = pn_disconnect;
spin_lock_init(&fp->rx.lock);
err = usb_add_function(c, &fp->function);
if (err)
kfree(fp);
return err;
}
int __init gphonet_setup(struct usb_gadget *gadget)
{
struct phonet_port *port;
int err;
/* Create net device */
BUG_ON(dev);
dev = alloc_netdev(sizeof(*port), "upnlink%d", pn_net_setup);
if (!dev)
return -ENOMEM;
port = netdev_priv(dev);
spin_lock_init(&port->lock);
netif_carrier_off(dev);
SET_NETDEV_DEV(dev, &gadget->dev);
err = register_netdev(dev);
if (err)
free_netdev(dev);
return err;
}
void gphonet_cleanup(void)
{
unregister_netdev(dev);
}
| gpl-2.0 |
xhteam/kernel_imx | drivers/mfd/tps65910-irq.c | 2514 | 5725 | /*
* tps65910-irq.c -- TI TPS6591x
*
* Copyright 2010 Texas Instruments Inc.
*
* Author: Graeme Gregory <gg@slimlogic.co.uk>
* Author: Jorge Eduardo Candelaria <jedu@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bug.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <linux/mfd/tps65910.h>
static inline int irq_to_tps65910_irq(struct tps65910 *tps65910,
int irq)
{
return (irq - tps65910->irq_base);
}
/*
* This is a threaded IRQ handler so can access I2C/SPI. Since all
* interrupts are clear on read the IRQ line will be reasserted and
* the physical IRQ will be handled again if another interrupt is
* asserted while we run - in the normal course of events this is a
* rare occurrence so we save I2C/SPI reads. We're also assuming that
* it's rare to get lots of interrupts firing simultaneously so try to
* minimise I/O.
*/
static irqreturn_t tps65910_irq(int irq, void *irq_data)
{
struct tps65910 *tps65910 = irq_data;
u32 irq_sts;
u32 irq_mask;
u8 reg;
int i;
tps65910->read(tps65910, TPS65910_INT_STS, 1, ®);
irq_sts = reg;
tps65910->read(tps65910, TPS65910_INT_STS2, 1, ®);
irq_sts |= reg << 8;
switch (tps65910_chip_id(tps65910)) {
case TPS65911:
tps65910->read(tps65910, TPS65910_INT_STS3, 1, ®);
irq_sts |= reg << 16;
}
tps65910->read(tps65910, TPS65910_INT_MSK, 1, ®);
irq_mask = reg;
tps65910->read(tps65910, TPS65910_INT_MSK2, 1, ®);
irq_mask |= reg << 8;
switch (tps65910_chip_id(tps65910)) {
case TPS65911:
tps65910->read(tps65910, TPS65910_INT_MSK3, 1, ®);
irq_mask |= reg << 16;
}
irq_sts &= ~irq_mask;
if (!irq_sts)
return IRQ_NONE;
for (i = 0; i < tps65910->irq_num; i++) {
if (!(irq_sts & (1 << i)))
continue;
handle_nested_irq(tps65910->irq_base + i);
}
/* Write the STS register back to clear IRQs we handled */
reg = irq_sts & 0xFF;
irq_sts >>= 8;
tps65910->write(tps65910, TPS65910_INT_STS, 1, ®);
reg = irq_sts & 0xFF;
tps65910->write(tps65910, TPS65910_INT_STS2, 1, ®);
switch (tps65910_chip_id(tps65910)) {
case TPS65911:
reg = irq_sts >> 8;
tps65910->write(tps65910, TPS65910_INT_STS3, 1, ®);
}
return IRQ_HANDLED;
}
static void tps65910_irq_lock(struct irq_data *data)
{
struct tps65910 *tps65910 = irq_data_get_irq_chip_data(data);
mutex_lock(&tps65910->irq_lock);
}
static void tps65910_irq_sync_unlock(struct irq_data *data)
{
struct tps65910 *tps65910 = irq_data_get_irq_chip_data(data);
u32 reg_mask;
u8 reg;
tps65910->read(tps65910, TPS65910_INT_MSK, 1, ®);
reg_mask = reg;
tps65910->read(tps65910, TPS65910_INT_MSK2, 1, ®);
reg_mask |= reg << 8;
switch (tps65910_chip_id(tps65910)) {
case TPS65911:
tps65910->read(tps65910, TPS65910_INT_MSK3, 1, ®);
reg_mask |= reg << 16;
}
if (tps65910->irq_mask != reg_mask) {
reg = tps65910->irq_mask & 0xFF;
tps65910->write(tps65910, TPS65910_INT_MSK, 1, ®);
reg = tps65910->irq_mask >> 8 & 0xFF;
tps65910->write(tps65910, TPS65910_INT_MSK2, 1, ®);
switch (tps65910_chip_id(tps65910)) {
case TPS65911:
reg = tps65910->irq_mask >> 16;
tps65910->write(tps65910, TPS65910_INT_MSK3, 1, ®);
}
}
mutex_unlock(&tps65910->irq_lock);
}
static void tps65910_irq_enable(struct irq_data *data)
{
struct tps65910 *tps65910 = irq_data_get_irq_chip_data(data);
tps65910->irq_mask &= ~( 1 << irq_to_tps65910_irq(tps65910, data->irq));
}
static void tps65910_irq_disable(struct irq_data *data)
{
struct tps65910 *tps65910 = irq_data_get_irq_chip_data(data);
tps65910->irq_mask |= ( 1 << irq_to_tps65910_irq(tps65910, data->irq));
}
static struct irq_chip tps65910_irq_chip = {
.name = "tps65910",
.irq_bus_lock = tps65910_irq_lock,
.irq_bus_sync_unlock = tps65910_irq_sync_unlock,
.irq_disable = tps65910_irq_disable,
.irq_enable = tps65910_irq_enable,
};
int tps65910_irq_init(struct tps65910 *tps65910, int irq,
struct tps65910_platform_data *pdata)
{
int ret, cur_irq;
int flags = IRQF_ONESHOT;
if (!irq) {
dev_warn(tps65910->dev, "No interrupt support, no core IRQ\n");
return -EINVAL;
}
if (!pdata || !pdata->irq_base) {
dev_warn(tps65910->dev, "No interrupt support, no IRQ base\n");
return -EINVAL;
}
tps65910->irq_mask = 0xFFFFFF;
mutex_init(&tps65910->irq_lock);
tps65910->chip_irq = irq;
tps65910->irq_base = pdata->irq_base;
switch (tps65910_chip_id(tps65910)) {
case TPS65910:
tps65910->irq_num = TPS65910_NUM_IRQ;
break;
case TPS65911:
tps65910->irq_num = TPS65911_NUM_IRQ;
break;
}
/* Register with genirq */
for (cur_irq = tps65910->irq_base;
cur_irq < tps65910->irq_num + tps65910->irq_base;
cur_irq++) {
irq_set_chip_data(cur_irq, tps65910);
irq_set_chip_and_handler(cur_irq, &tps65910_irq_chip,
handle_edge_irq);
irq_set_nested_thread(cur_irq, 1);
/* ARM needs us to explicitly flag the IRQ as valid
* and will set them noprobe when we do so. */
#ifdef CONFIG_ARM
set_irq_flags(cur_irq, IRQF_VALID);
#else
irq_set_noprobe(cur_irq);
#endif
}
ret = request_threaded_irq(irq, NULL, tps65910_irq, flags,
"tps65910", tps65910);
irq_set_irq_type(irq, IRQ_TYPE_LEVEL_LOW);
if (ret != 0)
dev_err(tps65910->dev, "Failed to request IRQ: %d\n", ret);
return ret;
}
int tps65910_irq_exit(struct tps65910 *tps65910)
{
free_irq(tps65910->chip_irq, tps65910);
return 0;
}
| gpl-2.0 |
TEAM-Gummy/Gummy_kernel_grouper | fs/nilfs2/mdt.c | 3026 | 14729 | /*
* mdt.c - meta data file for NILFS
*
* Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Ryusuke Konishi <ryusuke@osrg.net>
*/
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/mm.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include "nilfs.h"
#include "btnode.h"
#include "segment.h"
#include "page.h"
#include "mdt.h"
#define NILFS_MDT_MAX_RA_BLOCKS (16 - 1)
static int
nilfs_mdt_insert_new_block(struct inode *inode, unsigned long block,
struct buffer_head *bh,
void (*init_block)(struct inode *,
struct buffer_head *, void *))
{
struct nilfs_inode_info *ii = NILFS_I(inode);
void *kaddr;
int ret;
/* Caller exclude read accesses using page lock */
/* set_buffer_new(bh); */
bh->b_blocknr = 0;
ret = nilfs_bmap_insert(ii->i_bmap, block, (unsigned long)bh);
if (unlikely(ret))
return ret;
set_buffer_mapped(bh);
kaddr = kmap_atomic(bh->b_page, KM_USER0);
memset(kaddr + bh_offset(bh), 0, 1 << inode->i_blkbits);
if (init_block)
init_block(inode, bh, kaddr);
flush_dcache_page(bh->b_page);
kunmap_atomic(kaddr, KM_USER0);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(inode);
return 0;
}
static int nilfs_mdt_create_block(struct inode *inode, unsigned long block,
struct buffer_head **out_bh,
void (*init_block)(struct inode *,
struct buffer_head *,
void *))
{
struct super_block *sb = inode->i_sb;
struct nilfs_transaction_info ti;
struct buffer_head *bh;
int err;
nilfs_transaction_begin(sb, &ti, 0);
err = -ENOMEM;
bh = nilfs_grab_buffer(inode, inode->i_mapping, block, 0);
if (unlikely(!bh))
goto failed_unlock;
err = -EEXIST;
if (buffer_uptodate(bh))
goto failed_bh;
wait_on_buffer(bh);
if (buffer_uptodate(bh))
goto failed_bh;
bh->b_bdev = sb->s_bdev;
err = nilfs_mdt_insert_new_block(inode, block, bh, init_block);
if (likely(!err)) {
get_bh(bh);
*out_bh = bh;
}
failed_bh:
unlock_page(bh->b_page);
page_cache_release(bh->b_page);
brelse(bh);
failed_unlock:
if (likely(!err))
err = nilfs_transaction_commit(sb);
else
nilfs_transaction_abort(sb);
return err;
}
static int
nilfs_mdt_submit_block(struct inode *inode, unsigned long blkoff,
int mode, struct buffer_head **out_bh)
{
struct buffer_head *bh;
__u64 blknum = 0;
int ret = -ENOMEM;
bh = nilfs_grab_buffer(inode, inode->i_mapping, blkoff, 0);
if (unlikely(!bh))
goto failed;
ret = -EEXIST; /* internal code */
if (buffer_uptodate(bh))
goto out;
if (mode == READA) {
if (!trylock_buffer(bh)) {
ret = -EBUSY;
goto failed_bh;
}
} else /* mode == READ */
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
goto out;
}
ret = nilfs_bmap_lookup(NILFS_I(inode)->i_bmap, blkoff, &blknum);
if (unlikely(ret)) {
unlock_buffer(bh);
goto failed_bh;
}
map_bh(bh, inode->i_sb, (sector_t)blknum);
bh->b_end_io = end_buffer_read_sync;
get_bh(bh);
submit_bh(mode, bh);
ret = 0;
out:
get_bh(bh);
*out_bh = bh;
failed_bh:
unlock_page(bh->b_page);
page_cache_release(bh->b_page);
brelse(bh);
failed:
return ret;
}
static int nilfs_mdt_read_block(struct inode *inode, unsigned long block,
int readahead, struct buffer_head **out_bh)
{
struct buffer_head *first_bh, *bh;
unsigned long blkoff;
int i, nr_ra_blocks = NILFS_MDT_MAX_RA_BLOCKS;
int err;
err = nilfs_mdt_submit_block(inode, block, READ, &first_bh);
if (err == -EEXIST) /* internal code */
goto out;
if (unlikely(err))
goto failed;
if (readahead) {
blkoff = block + 1;
for (i = 0; i < nr_ra_blocks; i++, blkoff++) {
err = nilfs_mdt_submit_block(inode, blkoff, READA, &bh);
if (likely(!err || err == -EEXIST))
brelse(bh);
else if (err != -EBUSY)
break;
/* abort readahead if bmap lookup failed */
if (!buffer_locked(first_bh))
goto out_no_wait;
}
}
wait_on_buffer(first_bh);
out_no_wait:
err = -EIO;
if (!buffer_uptodate(first_bh))
goto failed_bh;
out:
*out_bh = first_bh;
return 0;
failed_bh:
brelse(first_bh);
failed:
return err;
}
/**
* nilfs_mdt_get_block - read or create a buffer on meta data file.
* @inode: inode of the meta data file
* @blkoff: block offset
* @create: create flag
* @init_block: initializer used for newly allocated block
* @out_bh: output of a pointer to the buffer_head
*
* nilfs_mdt_get_block() looks up the specified buffer and tries to create
* a new buffer if @create is not zero. On success, the returned buffer is
* assured to be either existing or formatted using a buffer lock on success.
* @out_bh is substituted only when zero is returned.
*
* Return Value: On success, it returns 0. On error, the following negative
* error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*
* %-ENOENT - the specified block does not exist (hole block)
*
* %-EROFS - Read only filesystem (for create mode)
*/
int nilfs_mdt_get_block(struct inode *inode, unsigned long blkoff, int create,
void (*init_block)(struct inode *,
struct buffer_head *, void *),
struct buffer_head **out_bh)
{
int ret;
/* Should be rewritten with merging nilfs_mdt_read_block() */
retry:
ret = nilfs_mdt_read_block(inode, blkoff, !create, out_bh);
if (!create || ret != -ENOENT)
return ret;
ret = nilfs_mdt_create_block(inode, blkoff, out_bh, init_block);
if (unlikely(ret == -EEXIST)) {
/* create = 0; */ /* limit read-create loop retries */
goto retry;
}
return ret;
}
/**
* nilfs_mdt_delete_block - make a hole on the meta data file.
* @inode: inode of the meta data file
* @block: block offset
*
* Return Value: On success, zero is returned.
* On error, one of the following negative error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*/
int nilfs_mdt_delete_block(struct inode *inode, unsigned long block)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
int err;
err = nilfs_bmap_delete(ii->i_bmap, block);
if (!err || err == -ENOENT) {
nilfs_mdt_mark_dirty(inode);
nilfs_mdt_forget_block(inode, block);
}
return err;
}
/**
* nilfs_mdt_forget_block - discard dirty state and try to remove the page
* @inode: inode of the meta data file
* @block: block offset
*
* nilfs_mdt_forget_block() clears a dirty flag of the specified buffer, and
* tries to release the page including the buffer from a page cache.
*
* Return Value: On success, 0 is returned. On error, one of the following
* negative error code is returned.
*
* %-EBUSY - page has an active buffer.
*
* %-ENOENT - page cache has no page addressed by the offset.
*/
int nilfs_mdt_forget_block(struct inode *inode, unsigned long block)
{
pgoff_t index = (pgoff_t)block >>
(PAGE_CACHE_SHIFT - inode->i_blkbits);
struct page *page;
unsigned long first_block;
int ret = 0;
int still_dirty;
page = find_lock_page(inode->i_mapping, index);
if (!page)
return -ENOENT;
wait_on_page_writeback(page);
first_block = (unsigned long)index <<
(PAGE_CACHE_SHIFT - inode->i_blkbits);
if (page_has_buffers(page)) {
struct buffer_head *bh;
bh = nilfs_page_get_nth_block(page, block - first_block);
nilfs_forget_buffer(bh);
}
still_dirty = PageDirty(page);
unlock_page(page);
page_cache_release(page);
if (still_dirty ||
invalidate_inode_pages2_range(inode->i_mapping, index, index) != 0)
ret = -EBUSY;
return ret;
}
/**
* nilfs_mdt_mark_block_dirty - mark a block on the meta data file dirty.
* @inode: inode of the meta data file
* @block: block offset
*
* Return Value: On success, it returns 0. On error, the following negative
* error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*
* %-ENOENT - the specified block does not exist (hole block)
*/
int nilfs_mdt_mark_block_dirty(struct inode *inode, unsigned long block)
{
struct buffer_head *bh;
int err;
err = nilfs_mdt_read_block(inode, block, 0, &bh);
if (unlikely(err))
return err;
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(inode);
brelse(bh);
return 0;
}
int nilfs_mdt_fetch_dirty(struct inode *inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
if (nilfs_bmap_test_and_clear_dirty(ii->i_bmap)) {
set_bit(NILFS_I_DIRTY, &ii->i_state);
return 1;
}
return test_bit(NILFS_I_DIRTY, &ii->i_state);
}
static int
nilfs_mdt_write_page(struct page *page, struct writeback_control *wbc)
{
struct inode *inode;
struct super_block *sb;
int err = 0;
redirty_page_for_writepage(wbc, page);
unlock_page(page);
inode = page->mapping->host;
if (!inode)
return 0;
sb = inode->i_sb;
if (wbc->sync_mode == WB_SYNC_ALL)
err = nilfs_construct_segment(sb);
else if (wbc->for_reclaim)
nilfs_flush_segment(sb, inode->i_ino);
return err;
}
static const struct address_space_operations def_mdt_aops = {
.writepage = nilfs_mdt_write_page,
};
static const struct inode_operations def_mdt_iops;
static const struct file_operations def_mdt_fops;
int nilfs_mdt_init(struct inode *inode, gfp_t gfp_mask, size_t objsz)
{
struct nilfs_mdt_info *mi;
mi = kzalloc(max(sizeof(*mi), objsz), GFP_NOFS);
if (!mi)
return -ENOMEM;
init_rwsem(&mi->mi_sem);
inode->i_private = mi;
inode->i_mode = S_IFREG;
mapping_set_gfp_mask(inode->i_mapping, gfp_mask);
inode->i_mapping->backing_dev_info = inode->i_sb->s_bdi;
inode->i_op = &def_mdt_iops;
inode->i_fop = &def_mdt_fops;
inode->i_mapping->a_ops = &def_mdt_aops;
return 0;
}
void nilfs_mdt_set_entry_size(struct inode *inode, unsigned entry_size,
unsigned header_size)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
mi->mi_entry_size = entry_size;
mi->mi_entries_per_block = (1 << inode->i_blkbits) / entry_size;
mi->mi_first_entry_offset = DIV_ROUND_UP(header_size, entry_size);
}
/**
* nilfs_mdt_setup_shadow_map - setup shadow map and bind it to metadata file
* @inode: inode of the metadata file
* @shadow: shadow mapping
*/
int nilfs_mdt_setup_shadow_map(struct inode *inode,
struct nilfs_shadow_map *shadow)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct backing_dev_info *bdi = inode->i_sb->s_bdi;
INIT_LIST_HEAD(&shadow->frozen_buffers);
address_space_init_once(&shadow->frozen_data);
nilfs_mapping_init(&shadow->frozen_data, inode, bdi);
address_space_init_once(&shadow->frozen_btnodes);
nilfs_mapping_init(&shadow->frozen_btnodes, inode, bdi);
mi->mi_shadow = shadow;
return 0;
}
/**
* nilfs_mdt_save_to_shadow_map - copy bmap and dirty pages to shadow map
* @inode: inode of the metadata file
*/
int nilfs_mdt_save_to_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_inode_info *ii = NILFS_I(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
int ret;
ret = nilfs_copy_dirty_pages(&shadow->frozen_data, inode->i_mapping);
if (ret)
goto out;
ret = nilfs_copy_dirty_pages(&shadow->frozen_btnodes,
&ii->i_btnode_cache);
if (ret)
goto out;
nilfs_bmap_save(ii->i_bmap, &shadow->bmap_store);
out:
return ret;
}
int nilfs_mdt_freeze_buffer(struct inode *inode, struct buffer_head *bh)
{
struct nilfs_shadow_map *shadow = NILFS_MDT(inode)->mi_shadow;
struct buffer_head *bh_frozen;
struct page *page;
int blkbits = inode->i_blkbits;
page = grab_cache_page(&shadow->frozen_data, bh->b_page->index);
if (!page)
return -ENOMEM;
if (!page_has_buffers(page))
create_empty_buffers(page, 1 << blkbits, 0);
bh_frozen = nilfs_page_get_nth_block(page, bh_offset(bh) >> blkbits);
if (!buffer_uptodate(bh_frozen))
nilfs_copy_buffer(bh_frozen, bh);
if (list_empty(&bh_frozen->b_assoc_buffers)) {
list_add_tail(&bh_frozen->b_assoc_buffers,
&shadow->frozen_buffers);
set_buffer_nilfs_redirected(bh);
} else {
brelse(bh_frozen); /* already frozen */
}
unlock_page(page);
page_cache_release(page);
return 0;
}
struct buffer_head *
nilfs_mdt_get_frozen_buffer(struct inode *inode, struct buffer_head *bh)
{
struct nilfs_shadow_map *shadow = NILFS_MDT(inode)->mi_shadow;
struct buffer_head *bh_frozen = NULL;
struct page *page;
int n;
page = find_lock_page(&shadow->frozen_data, bh->b_page->index);
if (page) {
if (page_has_buffers(page)) {
n = bh_offset(bh) >> inode->i_blkbits;
bh_frozen = nilfs_page_get_nth_block(page, n);
}
unlock_page(page);
page_cache_release(page);
}
return bh_frozen;
}
static void nilfs_release_frozen_buffers(struct nilfs_shadow_map *shadow)
{
struct list_head *head = &shadow->frozen_buffers;
struct buffer_head *bh;
while (!list_empty(head)) {
bh = list_first_entry(head, struct buffer_head,
b_assoc_buffers);
list_del_init(&bh->b_assoc_buffers);
brelse(bh); /* drop ref-count to make it releasable */
}
}
/**
* nilfs_mdt_restore_from_shadow_map - restore dirty pages and bmap state
* @inode: inode of the metadata file
*/
void nilfs_mdt_restore_from_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_inode_info *ii = NILFS_I(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
down_write(&mi->mi_sem);
if (mi->mi_palloc_cache)
nilfs_palloc_clear_cache(inode);
nilfs_clear_dirty_pages(inode->i_mapping);
nilfs_copy_back_pages(inode->i_mapping, &shadow->frozen_data);
nilfs_clear_dirty_pages(&ii->i_btnode_cache);
nilfs_copy_back_pages(&ii->i_btnode_cache, &shadow->frozen_btnodes);
nilfs_bmap_restore(ii->i_bmap, &shadow->bmap_store);
up_write(&mi->mi_sem);
}
/**
* nilfs_mdt_clear_shadow_map - truncate pages in shadow map caches
* @inode: inode of the metadata file
*/
void nilfs_mdt_clear_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
down_write(&mi->mi_sem);
nilfs_release_frozen_buffers(shadow);
truncate_inode_pages(&shadow->frozen_data, 0);
truncate_inode_pages(&shadow->frozen_btnodes, 0);
up_write(&mi->mi_sem);
}
| gpl-2.0 |
longqzh/chronnOS | drivers/net/sundance.c | 3026 | 57293 | /* sundance.c: A Linux device driver for the Sundance ST201 "Alta". */
/*
Written 1999-2000 by Donald Becker.
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.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Support and updates available at
http://www.scyld.com/network/sundance.html
[link no longer provides useful info -jgarzik]
Archives of the mailing list are still available at
http://www.beowulf.org/pipermail/netdrivers/
*/
#define DRV_NAME "sundance"
#define DRV_VERSION "1.2"
#define DRV_RELDATE "11-Sep-2006"
/* The user-configurable values.
These may be modified when a driver module is loaded.*/
static int debug = 1; /* 1 normal messages, 0 quiet .. 7 verbose. */
/* Maximum number of multicast addresses to filter (vs. rx-all-multicast).
Typical is a 64 element hash table based on the Ethernet CRC. */
static const int multicast_filter_limit = 32;
/* Set the copy breakpoint for the copy-only-tiny-frames scheme.
Setting to > 1518 effectively disables this feature.
This chip can receive into offset buffers, so the Alpha does not
need a copy-align. */
static int rx_copybreak;
static int flowctrl=1;
/* media[] specifies the media type the NIC operates at.
autosense Autosensing active media.
10mbps_hd 10Mbps half duplex.
10mbps_fd 10Mbps full duplex.
100mbps_hd 100Mbps half duplex.
100mbps_fd 100Mbps full duplex.
0 Autosensing active media.
1 10Mbps half duplex.
2 10Mbps full duplex.
3 100Mbps half duplex.
4 100Mbps full duplex.
*/
#define MAX_UNITS 8
static char *media[MAX_UNITS];
/* Operational parameters that are set at compile time. */
/* Keep the ring sizes a power of two for compile efficiency.
The compiler will convert <unsigned>'%'<2^N> into a bit mask.
Making the Tx ring too large decreases the effectiveness of channel
bonding and packet priority, and more than 128 requires modifying the
Tx error recovery.
Large receive rings merely waste memory. */
#define TX_RING_SIZE 32
#define TX_QUEUE_LEN (TX_RING_SIZE - 1) /* Limit ring entries actually used. */
#define RX_RING_SIZE 64
#define RX_BUDGET 32
#define TX_TOTAL_SIZE TX_RING_SIZE*sizeof(struct netdev_desc)
#define RX_TOTAL_SIZE RX_RING_SIZE*sizeof(struct netdev_desc)
/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (4*HZ)
#define PKT_BUF_SZ 1536 /* Size of each temporary Rx buffer.*/
/* Include files, designed to support most kernel versions 2.0.0 and later. */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <asm/uaccess.h>
#include <asm/processor.h> /* Processor type for cache alignment. */
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
/* These identify the driver base version and may not be removed. */
static const char version[] __devinitconst =
KERN_INFO DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE
" Written by Donald Becker\n";
MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
MODULE_DESCRIPTION("Sundance Alta Ethernet driver");
MODULE_LICENSE("GPL");
module_param(debug, int, 0);
module_param(rx_copybreak, int, 0);
module_param_array(media, charp, NULL, 0);
module_param(flowctrl, int, 0);
MODULE_PARM_DESC(debug, "Sundance Alta debug level (0-5)");
MODULE_PARM_DESC(rx_copybreak, "Sundance Alta copy breakpoint for copy-only-tiny-frames");
MODULE_PARM_DESC(flowctrl, "Sundance Alta flow control [0|1]");
/*
Theory of Operation
I. Board Compatibility
This driver is designed for the Sundance Technologies "Alta" ST201 chip.
II. Board-specific settings
III. Driver operation
IIIa. Ring buffers
This driver uses two statically allocated fixed-size descriptor lists
formed into rings by a branch from the final descriptor to the beginning of
the list. The ring sizes are set at compile time by RX/TX_RING_SIZE.
Some chips explicitly use only 2^N sized rings, while others use a
'next descriptor' pointer that the driver forms into rings.
IIIb/c. Transmit/Receive Structure
This driver uses a zero-copy receive and transmit scheme.
The driver allocates full frame size skbuffs for the Rx ring buffers at
open() time and passes the skb->data field to the chip as receive data
buffers. When an incoming frame is less than RX_COPYBREAK bytes long,
a fresh skbuff is allocated and the frame is copied to the new skbuff.
When the incoming frame is larger, the skbuff is passed directly up the
protocol stack. Buffers consumed this way are replaced by newly allocated
skbuffs in a later phase of receives.
The RX_COPYBREAK value is chosen to trade-off the memory wasted by
using a full-sized skbuff for small frames vs. the copying costs of larger
frames. New boards are typically used in generously configured machines
and the underfilled buffers have negligible impact compared to the benefit of
a single allocation size, so the default value of zero results in never
copying packets. When copying is done, the cost is usually mitigated by using
a combined copy/checksum routine. Copying also preloads the cache, which is
most useful with small frames.
A subtle aspect of the operation is that the IP header at offset 14 in an
ethernet frame isn't longword aligned for further processing.
Unaligned buffers are permitted by the Sundance hardware, so
frames are received into the skbuff at an offset of "+2", 16-byte aligning
the IP header.
IIId. Synchronization
The driver runs as two independent, single-threaded flows of control. One
is the send-packet routine, which enforces single-threaded use by the
dev->tbusy flag. The other thread is the interrupt handler, which is single
threaded by the hardware and interrupt handling software.
The send packet thread has partial control over the Tx ring and 'dev->tbusy'
flag. It sets the tbusy flag whenever it's queuing a Tx packet. If the next
queue slot is empty, it clears the tbusy flag when finished otherwise it sets
the 'lp->tx_full' flag.
The interrupt handler has exclusive control over the Rx ring and records stats
from the Tx ring. After reaping the stats, it marks the Tx queue entry as
empty by incrementing the dirty_tx mark. Iff the 'lp->tx_full' flag is set, it
clears both the tx_full and tbusy flags.
IV. Notes
IVb. References
The Sundance ST201 datasheet, preliminary version.
The Kendin KS8723 datasheet, preliminary version.
The ICplus IP100 datasheet, preliminary version.
http://www.scyld.com/expert/100mbps.html
http://www.scyld.com/expert/NWay.html
IVc. Errata
*/
/* Work-around for Kendin chip bugs. */
#ifndef CONFIG_SUNDANCE_MMIO
#define USE_IO_OPS 1
#endif
static DEFINE_PCI_DEVICE_TABLE(sundance_pci_tbl) = {
{ 0x1186, 0x1002, 0x1186, 0x1002, 0, 0, 0 },
{ 0x1186, 0x1002, 0x1186, 0x1003, 0, 0, 1 },
{ 0x1186, 0x1002, 0x1186, 0x1012, 0, 0, 2 },
{ 0x1186, 0x1002, 0x1186, 0x1040, 0, 0, 3 },
{ 0x1186, 0x1002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 4 },
{ 0x13F0, 0x0201, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 5 },
{ 0x13F0, 0x0200, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 6 },
{ }
};
MODULE_DEVICE_TABLE(pci, sundance_pci_tbl);
enum {
netdev_io_size = 128
};
struct pci_id_info {
const char *name;
};
static const struct pci_id_info pci_id_tbl[] __devinitdata = {
{"D-Link DFE-550TX FAST Ethernet Adapter"},
{"D-Link DFE-550FX 100Mbps Fiber-optics Adapter"},
{"D-Link DFE-580TX 4 port Server Adapter"},
{"D-Link DFE-530TXS FAST Ethernet Adapter"},
{"D-Link DL10050-based FAST Ethernet Adapter"},
{"Sundance Technology Alta"},
{"IC Plus Corporation IP100A FAST Ethernet Adapter"},
{ } /* terminate list. */
};
/* This driver was written to use PCI memory space, however x86-oriented
hardware often uses I/O space accesses. */
/* Offsets to the device registers.
Unlike software-only systems, device drivers interact with complex hardware.
It's not useful to define symbolic names for every register bit in the
device. The name can only partially document the semantics and make
the driver longer and more difficult to read.
In general, only the important configuration values or bits changed
multiple times should be defined symbolically.
*/
enum alta_offsets {
DMACtrl = 0x00,
TxListPtr = 0x04,
TxDMABurstThresh = 0x08,
TxDMAUrgentThresh = 0x09,
TxDMAPollPeriod = 0x0a,
RxDMAStatus = 0x0c,
RxListPtr = 0x10,
DebugCtrl0 = 0x1a,
DebugCtrl1 = 0x1c,
RxDMABurstThresh = 0x14,
RxDMAUrgentThresh = 0x15,
RxDMAPollPeriod = 0x16,
LEDCtrl = 0x1a,
ASICCtrl = 0x30,
EEData = 0x34,
EECtrl = 0x36,
FlashAddr = 0x40,
FlashData = 0x44,
TxStatus = 0x46,
TxFrameId = 0x47,
DownCounter = 0x18,
IntrClear = 0x4a,
IntrEnable = 0x4c,
IntrStatus = 0x4e,
MACCtrl0 = 0x50,
MACCtrl1 = 0x52,
StationAddr = 0x54,
MaxFrameSize = 0x5A,
RxMode = 0x5c,
MIICtrl = 0x5e,
MulticastFilter0 = 0x60,
MulticastFilter1 = 0x64,
RxOctetsLow = 0x68,
RxOctetsHigh = 0x6a,
TxOctetsLow = 0x6c,
TxOctetsHigh = 0x6e,
TxFramesOK = 0x70,
RxFramesOK = 0x72,
StatsCarrierError = 0x74,
StatsLateColl = 0x75,
StatsMultiColl = 0x76,
StatsOneColl = 0x77,
StatsTxDefer = 0x78,
RxMissed = 0x79,
StatsTxXSDefer = 0x7a,
StatsTxAbort = 0x7b,
StatsBcastTx = 0x7c,
StatsBcastRx = 0x7d,
StatsMcastTx = 0x7e,
StatsMcastRx = 0x7f,
/* Aliased and bogus values! */
RxStatus = 0x0c,
};
#define ASIC_HI_WORD(x) ((x) + 2)
enum ASICCtrl_HiWord_bit {
GlobalReset = 0x0001,
RxReset = 0x0002,
TxReset = 0x0004,
DMAReset = 0x0008,
FIFOReset = 0x0010,
NetworkReset = 0x0020,
HostReset = 0x0040,
ResetBusy = 0x0400,
};
/* Bits in the interrupt status/mask registers. */
enum intr_status_bits {
IntrSummary=0x0001, IntrPCIErr=0x0002, IntrMACCtrl=0x0008,
IntrTxDone=0x0004, IntrRxDone=0x0010, IntrRxStart=0x0020,
IntrDrvRqst=0x0040,
StatsMax=0x0080, LinkChange=0x0100,
IntrTxDMADone=0x0200, IntrRxDMADone=0x0400,
};
/* Bits in the RxMode register. */
enum rx_mode_bits {
AcceptAllIPMulti=0x20, AcceptMultiHash=0x10, AcceptAll=0x08,
AcceptBroadcast=0x04, AcceptMulticast=0x02, AcceptMyPhys=0x01,
};
/* Bits in MACCtrl. */
enum mac_ctrl0_bits {
EnbFullDuplex=0x20, EnbRcvLargeFrame=0x40,
EnbFlowCtrl=0x100, EnbPassRxCRC=0x200,
};
enum mac_ctrl1_bits {
StatsEnable=0x0020, StatsDisable=0x0040, StatsEnabled=0x0080,
TxEnable=0x0100, TxDisable=0x0200, TxEnabled=0x0400,
RxEnable=0x0800, RxDisable=0x1000, RxEnabled=0x2000,
};
/* The Rx and Tx buffer descriptors. */
/* Note that using only 32 bit fields simplifies conversion to big-endian
architectures. */
struct netdev_desc {
__le32 next_desc;
__le32 status;
struct desc_frag { __le32 addr, length; } frag[1];
};
/* Bits in netdev_desc.status */
enum desc_status_bits {
DescOwn=0x8000,
DescEndPacket=0x4000,
DescEndRing=0x2000,
LastFrag=0x80000000,
DescIntrOnTx=0x8000,
DescIntrOnDMADone=0x80000000,
DisableAlign = 0x00000001,
};
#define PRIV_ALIGN 15 /* Required alignment mask */
/* Use __attribute__((aligned (L1_CACHE_BYTES))) to maintain alignment
within the structure. */
#define MII_CNT 4
struct netdev_private {
/* Descriptor rings first for alignment. */
struct netdev_desc *rx_ring;
struct netdev_desc *tx_ring;
struct sk_buff* rx_skbuff[RX_RING_SIZE];
struct sk_buff* tx_skbuff[TX_RING_SIZE];
dma_addr_t tx_ring_dma;
dma_addr_t rx_ring_dma;
struct timer_list timer; /* Media monitoring timer. */
/* ethtool extra stats */
struct {
u64 tx_multiple_collisions;
u64 tx_single_collisions;
u64 tx_late_collisions;
u64 tx_deferred;
u64 tx_deferred_excessive;
u64 tx_aborted;
u64 tx_bcasts;
u64 rx_bcasts;
u64 tx_mcasts;
u64 rx_mcasts;
} xstats;
/* Frequently used values: keep some adjacent for cache effect. */
spinlock_t lock;
int msg_enable;
int chip_id;
unsigned int cur_rx, dirty_rx; /* Producer/consumer ring indices */
unsigned int rx_buf_sz; /* Based on MTU+slack. */
struct netdev_desc *last_tx; /* Last Tx descriptor used. */
unsigned int cur_tx, dirty_tx;
/* These values are keep track of the transceiver/media in use. */
unsigned int flowctrl:1;
unsigned int default_port:4; /* Last dev->if_port value. */
unsigned int an_enable:1;
unsigned int speed;
struct tasklet_struct rx_tasklet;
struct tasklet_struct tx_tasklet;
int budget;
int cur_task;
/* Multicast and receive mode. */
spinlock_t mcastlock; /* SMP lock multicast updates. */
u16 mcast_filter[4];
/* MII transceiver section. */
struct mii_if_info mii_if;
int mii_preamble_required;
unsigned char phys[MII_CNT]; /* MII device addresses, only first one used. */
struct pci_dev *pci_dev;
void __iomem *base;
spinlock_t statlock;
};
/* The station address location in the EEPROM. */
#define EEPROM_SA_OFFSET 0x10
#define DEFAULT_INTR (IntrRxDMADone | IntrPCIErr | \
IntrDrvRqst | IntrTxDone | StatsMax | \
LinkChange)
static int change_mtu(struct net_device *dev, int new_mtu);
static int eeprom_read(void __iomem *ioaddr, int location);
static int mdio_read(struct net_device *dev, int phy_id, int location);
static void mdio_write(struct net_device *dev, int phy_id, int location, int value);
static int mdio_wait_link(struct net_device *dev, int wait);
static int netdev_open(struct net_device *dev);
static void check_duplex(struct net_device *dev);
static void netdev_timer(unsigned long data);
static void tx_timeout(struct net_device *dev);
static void init_ring(struct net_device *dev);
static netdev_tx_t start_tx(struct sk_buff *skb, struct net_device *dev);
static int reset_tx (struct net_device *dev);
static irqreturn_t intr_handler(int irq, void *dev_instance);
static void rx_poll(unsigned long data);
static void tx_poll(unsigned long data);
static void refill_rx (struct net_device *dev);
static void netdev_error(struct net_device *dev, int intr_status);
static void netdev_error(struct net_device *dev, int intr_status);
static void set_rx_mode(struct net_device *dev);
static int __set_mac_addr(struct net_device *dev);
static int sundance_set_mac_addr(struct net_device *dev, void *data);
static struct net_device_stats *get_stats(struct net_device *dev);
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static int netdev_close(struct net_device *dev);
static const struct ethtool_ops ethtool_ops;
static void sundance_reset(struct net_device *dev, unsigned long reset_cmd)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base + ASICCtrl;
int countdown;
/* ST201 documentation states ASICCtrl is a 32bit register */
iowrite32 (reset_cmd | ioread32 (ioaddr), ioaddr);
/* ST201 documentation states reset can take up to 1 ms */
countdown = 10 + 1;
while (ioread32 (ioaddr) & (ResetBusy << 16)) {
if (--countdown == 0) {
printk(KERN_WARNING "%s : reset not completed !!\n", dev->name);
break;
}
udelay(100);
}
}
static const struct net_device_ops netdev_ops = {
.ndo_open = netdev_open,
.ndo_stop = netdev_close,
.ndo_start_xmit = start_tx,
.ndo_get_stats = get_stats,
.ndo_set_multicast_list = set_rx_mode,
.ndo_do_ioctl = netdev_ioctl,
.ndo_tx_timeout = tx_timeout,
.ndo_change_mtu = change_mtu,
.ndo_set_mac_address = sundance_set_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int __devinit sundance_probe1 (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
struct netdev_private *np;
static int card_idx;
int chip_idx = ent->driver_data;
int irq;
int i;
void __iomem *ioaddr;
u16 mii_ctl;
void *ring_space;
dma_addr_t ring_dma;
#ifdef USE_IO_OPS
int bar = 0;
#else
int bar = 1;
#endif
int phy, phy_end, phy_idx = 0;
/* when built into the kernel, we only print version if device is found */
#ifndef MODULE
static int printed_version;
if (!printed_version++)
printk(version);
#endif
if (pci_enable_device(pdev))
return -EIO;
pci_set_master(pdev);
irq = pdev->irq;
dev = alloc_etherdev(sizeof(*np));
if (!dev)
return -ENOMEM;
SET_NETDEV_DEV(dev, &pdev->dev);
if (pci_request_regions(pdev, DRV_NAME))
goto err_out_netdev;
ioaddr = pci_iomap(pdev, bar, netdev_io_size);
if (!ioaddr)
goto err_out_res;
for (i = 0; i < 3; i++)
((__le16 *)dev->dev_addr)[i] =
cpu_to_le16(eeprom_read(ioaddr, i + EEPROM_SA_OFFSET));
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
dev->base_addr = (unsigned long)ioaddr;
dev->irq = irq;
np = netdev_priv(dev);
np->base = ioaddr;
np->pci_dev = pdev;
np->chip_id = chip_idx;
np->msg_enable = (1 << debug) - 1;
spin_lock_init(&np->lock);
spin_lock_init(&np->statlock);
tasklet_init(&np->rx_tasklet, rx_poll, (unsigned long)dev);
tasklet_init(&np->tx_tasklet, tx_poll, (unsigned long)dev);
ring_space = dma_alloc_coherent(&pdev->dev, TX_TOTAL_SIZE,
&ring_dma, GFP_KERNEL);
if (!ring_space)
goto err_out_cleardev;
np->tx_ring = (struct netdev_desc *)ring_space;
np->tx_ring_dma = ring_dma;
ring_space = dma_alloc_coherent(&pdev->dev, RX_TOTAL_SIZE,
&ring_dma, GFP_KERNEL);
if (!ring_space)
goto err_out_unmap_tx;
np->rx_ring = (struct netdev_desc *)ring_space;
np->rx_ring_dma = ring_dma;
np->mii_if.dev = dev;
np->mii_if.mdio_read = mdio_read;
np->mii_if.mdio_write = mdio_write;
np->mii_if.phy_id_mask = 0x1f;
np->mii_if.reg_num_mask = 0x1f;
/* The chip-specific entries in the device structure. */
dev->netdev_ops = &netdev_ops;
SET_ETHTOOL_OPS(dev, ðtool_ops);
dev->watchdog_timeo = TX_TIMEOUT;
pci_set_drvdata(pdev, dev);
i = register_netdev(dev);
if (i)
goto err_out_unmap_rx;
printk(KERN_INFO "%s: %s at %p, %pM, IRQ %d.\n",
dev->name, pci_id_tbl[chip_idx].name, ioaddr,
dev->dev_addr, irq);
np->phys[0] = 1; /* Default setting */
np->mii_preamble_required++;
/*
* It seems some phys doesn't deal well with address 0 being accessed
* first
*/
if (sundance_pci_tbl[np->chip_id].device == 0x0200) {
phy = 0;
phy_end = 31;
} else {
phy = 1;
phy_end = 32; /* wraps to zero, due to 'phy & 0x1f' */
}
for (; phy <= phy_end && phy_idx < MII_CNT; phy++) {
int phyx = phy & 0x1f;
int mii_status = mdio_read(dev, phyx, MII_BMSR);
if (mii_status != 0xffff && mii_status != 0x0000) {
np->phys[phy_idx++] = phyx;
np->mii_if.advertising = mdio_read(dev, phyx, MII_ADVERTISE);
if ((mii_status & 0x0040) == 0)
np->mii_preamble_required++;
printk(KERN_INFO "%s: MII PHY found at address %d, status "
"0x%4.4x advertising %4.4x.\n",
dev->name, phyx, mii_status, np->mii_if.advertising);
}
}
np->mii_preamble_required--;
if (phy_idx == 0) {
printk(KERN_INFO "%s: No MII transceiver found, aborting. ASIC status %x\n",
dev->name, ioread32(ioaddr + ASICCtrl));
goto err_out_unregister;
}
np->mii_if.phy_id = np->phys[0];
/* Parse override configuration */
np->an_enable = 1;
if (card_idx < MAX_UNITS) {
if (media[card_idx] != NULL) {
np->an_enable = 0;
if (strcmp (media[card_idx], "100mbps_fd") == 0 ||
strcmp (media[card_idx], "4") == 0) {
np->speed = 100;
np->mii_if.full_duplex = 1;
} else if (strcmp (media[card_idx], "100mbps_hd") == 0 ||
strcmp (media[card_idx], "3") == 0) {
np->speed = 100;
np->mii_if.full_duplex = 0;
} else if (strcmp (media[card_idx], "10mbps_fd") == 0 ||
strcmp (media[card_idx], "2") == 0) {
np->speed = 10;
np->mii_if.full_duplex = 1;
} else if (strcmp (media[card_idx], "10mbps_hd") == 0 ||
strcmp (media[card_idx], "1") == 0) {
np->speed = 10;
np->mii_if.full_duplex = 0;
} else {
np->an_enable = 1;
}
}
if (flowctrl == 1)
np->flowctrl = 1;
}
/* Fibre PHY? */
if (ioread32 (ioaddr + ASICCtrl) & 0x80) {
/* Default 100Mbps Full */
if (np->an_enable) {
np->speed = 100;
np->mii_if.full_duplex = 1;
np->an_enable = 0;
}
}
/* Reset PHY */
mdio_write (dev, np->phys[0], MII_BMCR, BMCR_RESET);
mdelay (300);
/* If flow control enabled, we need to advertise it.*/
if (np->flowctrl)
mdio_write (dev, np->phys[0], MII_ADVERTISE, np->mii_if.advertising | 0x0400);
mdio_write (dev, np->phys[0], MII_BMCR, BMCR_ANENABLE|BMCR_ANRESTART);
/* Force media type */
if (!np->an_enable) {
mii_ctl = 0;
mii_ctl |= (np->speed == 100) ? BMCR_SPEED100 : 0;
mii_ctl |= (np->mii_if.full_duplex) ? BMCR_FULLDPLX : 0;
mdio_write (dev, np->phys[0], MII_BMCR, mii_ctl);
printk (KERN_INFO "Override speed=%d, %s duplex\n",
np->speed, np->mii_if.full_duplex ? "Full" : "Half");
}
/* Perhaps move the reset here? */
/* Reset the chip to erase previous misconfiguration. */
if (netif_msg_hw(np))
printk("ASIC Control is %x.\n", ioread32(ioaddr + ASICCtrl));
sundance_reset(dev, 0x00ff << 16);
if (netif_msg_hw(np))
printk("ASIC Control is now %x.\n", ioread32(ioaddr + ASICCtrl));
card_idx++;
return 0;
err_out_unregister:
unregister_netdev(dev);
err_out_unmap_rx:
dma_free_coherent(&pdev->dev, RX_TOTAL_SIZE,
np->rx_ring, np->rx_ring_dma);
err_out_unmap_tx:
dma_free_coherent(&pdev->dev, TX_TOTAL_SIZE,
np->tx_ring, np->tx_ring_dma);
err_out_cleardev:
pci_set_drvdata(pdev, NULL);
pci_iounmap(pdev, ioaddr);
err_out_res:
pci_release_regions(pdev);
err_out_netdev:
free_netdev (dev);
return -ENODEV;
}
static int change_mtu(struct net_device *dev, int new_mtu)
{
if ((new_mtu < 68) || (new_mtu > 8191)) /* Set by RxDMAFrameLen */
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
dev->mtu = new_mtu;
return 0;
}
#define eeprom_delay(ee_addr) ioread32(ee_addr)
/* Read the EEPROM and MII Management Data I/O (MDIO) interfaces. */
static int __devinit eeprom_read(void __iomem *ioaddr, int location)
{
int boguscnt = 10000; /* Typical 1900 ticks. */
iowrite16(0x0200 | (location & 0xff), ioaddr + EECtrl);
do {
eeprom_delay(ioaddr + EECtrl);
if (! (ioread16(ioaddr + EECtrl) & 0x8000)) {
return ioread16(ioaddr + EEData);
}
} while (--boguscnt > 0);
return 0;
}
/* MII transceiver control section.
Read and write the MII registers using software-generated serial
MDIO protocol. See the MII specifications or DP83840A data sheet
for details.
The maximum data clock rate is 2.5 Mhz. The minimum timing is usually
met by back-to-back 33Mhz PCI cycles. */
#define mdio_delay() ioread8(mdio_addr)
enum mii_reg_bits {
MDIO_ShiftClk=0x0001, MDIO_Data=0x0002, MDIO_EnbOutput=0x0004,
};
#define MDIO_EnbIn (0)
#define MDIO_WRITE0 (MDIO_EnbOutput)
#define MDIO_WRITE1 (MDIO_Data | MDIO_EnbOutput)
/* Generate the preamble required for initial synchronization and
a few older transceivers. */
static void mdio_sync(void __iomem *mdio_addr)
{
int bits = 32;
/* Establish sync by sending at least 32 logic ones. */
while (--bits >= 0) {
iowrite8(MDIO_WRITE1, mdio_addr);
mdio_delay();
iowrite8(MDIO_WRITE1 | MDIO_ShiftClk, mdio_addr);
mdio_delay();
}
}
static int mdio_read(struct net_device *dev, int phy_id, int location)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *mdio_addr = np->base + MIICtrl;
int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
int i, retval = 0;
if (np->mii_preamble_required)
mdio_sync(mdio_addr);
/* Shift the read command bits out. */
for (i = 15; i >= 0; i--) {
int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
iowrite8(dataval, mdio_addr);
mdio_delay();
iowrite8(dataval | MDIO_ShiftClk, mdio_addr);
mdio_delay();
}
/* Read the two transition, 16 data, and wire-idle bits. */
for (i = 19; i > 0; i--) {
iowrite8(MDIO_EnbIn, mdio_addr);
mdio_delay();
retval = (retval << 1) | ((ioread8(mdio_addr) & MDIO_Data) ? 1 : 0);
iowrite8(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
mdio_delay();
}
return (retval>>1) & 0xffff;
}
static void mdio_write(struct net_device *dev, int phy_id, int location, int value)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *mdio_addr = np->base + MIICtrl;
int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location<<18) | value;
int i;
if (np->mii_preamble_required)
mdio_sync(mdio_addr);
/* Shift the command bits out. */
for (i = 31; i >= 0; i--) {
int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
iowrite8(dataval, mdio_addr);
mdio_delay();
iowrite8(dataval | MDIO_ShiftClk, mdio_addr);
mdio_delay();
}
/* Clear out extra bits. */
for (i = 2; i > 0; i--) {
iowrite8(MDIO_EnbIn, mdio_addr);
mdio_delay();
iowrite8(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
mdio_delay();
}
}
static int mdio_wait_link(struct net_device *dev, int wait)
{
int bmsr;
int phy_id;
struct netdev_private *np;
np = netdev_priv(dev);
phy_id = np->phys[0];
do {
bmsr = mdio_read(dev, phy_id, MII_BMSR);
if (bmsr & 0x0004)
return 0;
mdelay(1);
} while (--wait > 0);
return -1;
}
static int netdev_open(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
unsigned long flags;
int i;
/* Do we need to reset the chip??? */
i = request_irq(dev->irq, intr_handler, IRQF_SHARED, dev->name, dev);
if (i)
return i;
if (netif_msg_ifup(np))
printk(KERN_DEBUG "%s: netdev_open() irq %d.\n",
dev->name, dev->irq);
init_ring(dev);
iowrite32(np->rx_ring_dma, ioaddr + RxListPtr);
/* The Tx list pointer is written as packets are queued. */
/* Initialize other registers. */
__set_mac_addr(dev);
#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
iowrite16(dev->mtu + 18, ioaddr + MaxFrameSize);
#else
iowrite16(dev->mtu + 14, ioaddr + MaxFrameSize);
#endif
if (dev->mtu > 2047)
iowrite32(ioread32(ioaddr + ASICCtrl) | 0x0C, ioaddr + ASICCtrl);
/* Configure the PCI bus bursts and FIFO thresholds. */
if (dev->if_port == 0)
dev->if_port = np->default_port;
spin_lock_init(&np->mcastlock);
set_rx_mode(dev);
iowrite16(0, ioaddr + IntrEnable);
iowrite16(0, ioaddr + DownCounter);
/* Set the chip to poll every N*320nsec. */
iowrite8(100, ioaddr + RxDMAPollPeriod);
iowrite8(127, ioaddr + TxDMAPollPeriod);
/* Fix DFE-580TX packet drop issue */
if (np->pci_dev->revision >= 0x14)
iowrite8(0x01, ioaddr + DebugCtrl1);
netif_start_queue(dev);
spin_lock_irqsave(&np->lock, flags);
reset_tx(dev);
spin_unlock_irqrestore(&np->lock, flags);
iowrite16 (StatsEnable | RxEnable | TxEnable, ioaddr + MACCtrl1);
if (netif_msg_ifup(np))
printk(KERN_DEBUG "%s: Done netdev_open(), status: Rx %x Tx %x "
"MAC Control %x, %4.4x %4.4x.\n",
dev->name, ioread32(ioaddr + RxStatus), ioread8(ioaddr + TxStatus),
ioread32(ioaddr + MACCtrl0),
ioread16(ioaddr + MACCtrl1), ioread16(ioaddr + MACCtrl0));
/* Set the timer to check for link beat. */
init_timer(&np->timer);
np->timer.expires = jiffies + 3*HZ;
np->timer.data = (unsigned long)dev;
np->timer.function = netdev_timer; /* timer handler */
add_timer(&np->timer);
/* Enable interrupts by setting the interrupt mask. */
iowrite16(DEFAULT_INTR, ioaddr + IntrEnable);
return 0;
}
static void check_duplex(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
int mii_lpa = mdio_read(dev, np->phys[0], MII_LPA);
int negotiated = mii_lpa & np->mii_if.advertising;
int duplex;
/* Force media */
if (!np->an_enable || mii_lpa == 0xffff) {
if (np->mii_if.full_duplex)
iowrite16 (ioread16 (ioaddr + MACCtrl0) | EnbFullDuplex,
ioaddr + MACCtrl0);
return;
}
/* Autonegotiation */
duplex = (negotiated & 0x0100) || (negotiated & 0x01C0) == 0x0040;
if (np->mii_if.full_duplex != duplex) {
np->mii_if.full_duplex = duplex;
if (netif_msg_link(np))
printk(KERN_INFO "%s: Setting %s-duplex based on MII #%d "
"negotiated capability %4.4x.\n", dev->name,
duplex ? "full" : "half", np->phys[0], negotiated);
iowrite16(ioread16(ioaddr + MACCtrl0) | (duplex ? 0x20 : 0), ioaddr + MACCtrl0);
}
}
static void netdev_timer(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
int next_tick = 10*HZ;
if (netif_msg_timer(np)) {
printk(KERN_DEBUG "%s: Media selection timer tick, intr status %4.4x, "
"Tx %x Rx %x.\n",
dev->name, ioread16(ioaddr + IntrEnable),
ioread8(ioaddr + TxStatus), ioread32(ioaddr + RxStatus));
}
check_duplex(dev);
np->timer.expires = jiffies + next_tick;
add_timer(&np->timer);
}
static void tx_timeout(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
unsigned long flag;
netif_stop_queue(dev);
tasklet_disable(&np->tx_tasklet);
iowrite16(0, ioaddr + IntrEnable);
printk(KERN_WARNING "%s: Transmit timed out, TxStatus %2.2x "
"TxFrameId %2.2x,"
" resetting...\n", dev->name, ioread8(ioaddr + TxStatus),
ioread8(ioaddr + TxFrameId));
{
int i;
for (i=0; i<TX_RING_SIZE; i++) {
printk(KERN_DEBUG "%02x %08llx %08x %08x(%02x) %08x %08x\n", i,
(unsigned long long)(np->tx_ring_dma + i*sizeof(*np->tx_ring)),
le32_to_cpu(np->tx_ring[i].next_desc),
le32_to_cpu(np->tx_ring[i].status),
(le32_to_cpu(np->tx_ring[i].status) >> 2) & 0xff,
le32_to_cpu(np->tx_ring[i].frag[0].addr),
le32_to_cpu(np->tx_ring[i].frag[0].length));
}
printk(KERN_DEBUG "TxListPtr=%08x netif_queue_stopped=%d\n",
ioread32(np->base + TxListPtr),
netif_queue_stopped(dev));
printk(KERN_DEBUG "cur_tx=%d(%02x) dirty_tx=%d(%02x)\n",
np->cur_tx, np->cur_tx % TX_RING_SIZE,
np->dirty_tx, np->dirty_tx % TX_RING_SIZE);
printk(KERN_DEBUG "cur_rx=%d dirty_rx=%d\n", np->cur_rx, np->dirty_rx);
printk(KERN_DEBUG "cur_task=%d\n", np->cur_task);
}
spin_lock_irqsave(&np->lock, flag);
/* Stop and restart the chip's Tx processes . */
reset_tx(dev);
spin_unlock_irqrestore(&np->lock, flag);
dev->if_port = 0;
dev->trans_start = jiffies; /* prevent tx timeout */
dev->stats.tx_errors++;
if (np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
netif_wake_queue(dev);
}
iowrite16(DEFAULT_INTR, ioaddr + IntrEnable);
tasklet_enable(&np->tx_tasklet);
}
/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void init_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int i;
np->cur_rx = np->cur_tx = 0;
np->dirty_rx = np->dirty_tx = 0;
np->cur_task = 0;
np->rx_buf_sz = (dev->mtu <= 1520 ? PKT_BUF_SZ : dev->mtu + 16);
/* Initialize all Rx descriptors. */
for (i = 0; i < RX_RING_SIZE; i++) {
np->rx_ring[i].next_desc = cpu_to_le32(np->rx_ring_dma +
((i+1)%RX_RING_SIZE)*sizeof(*np->rx_ring));
np->rx_ring[i].status = 0;
np->rx_ring[i].frag[0].length = 0;
np->rx_skbuff[i] = NULL;
}
/* Fill in the Rx buffers. Handle allocation failure gracefully. */
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb = dev_alloc_skb(np->rx_buf_sz + 2);
np->rx_skbuff[i] = skb;
if (skb == NULL)
break;
skb->dev = dev; /* Mark as being used by this device. */
skb_reserve(skb, 2); /* 16 byte align the IP header. */
np->rx_ring[i].frag[0].addr = cpu_to_le32(
dma_map_single(&np->pci_dev->dev, skb->data,
np->rx_buf_sz, DMA_FROM_DEVICE));
if (dma_mapping_error(&np->pci_dev->dev,
np->rx_ring[i].frag[0].addr)) {
dev_kfree_skb(skb);
np->rx_skbuff[i] = NULL;
break;
}
np->rx_ring[i].frag[0].length = cpu_to_le32(np->rx_buf_sz | LastFrag);
}
np->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
for (i = 0; i < TX_RING_SIZE; i++) {
np->tx_skbuff[i] = NULL;
np->tx_ring[i].status = 0;
}
}
static void tx_poll (unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct netdev_private *np = netdev_priv(dev);
unsigned head = np->cur_task % TX_RING_SIZE;
struct netdev_desc *txdesc =
&np->tx_ring[(np->cur_tx - 1) % TX_RING_SIZE];
/* Chain the next pointer */
for (; np->cur_tx - np->cur_task > 0; np->cur_task++) {
int entry = np->cur_task % TX_RING_SIZE;
txdesc = &np->tx_ring[entry];
if (np->last_tx) {
np->last_tx->next_desc = cpu_to_le32(np->tx_ring_dma +
entry*sizeof(struct netdev_desc));
}
np->last_tx = txdesc;
}
/* Indicate the latest descriptor of tx ring */
txdesc->status |= cpu_to_le32(DescIntrOnTx);
if (ioread32 (np->base + TxListPtr) == 0)
iowrite32 (np->tx_ring_dma + head * sizeof(struct netdev_desc),
np->base + TxListPtr);
}
static netdev_tx_t
start_tx (struct sk_buff *skb, struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
struct netdev_desc *txdesc;
unsigned entry;
/* Calculate the next Tx descriptor entry. */
entry = np->cur_tx % TX_RING_SIZE;
np->tx_skbuff[entry] = skb;
txdesc = &np->tx_ring[entry];
txdesc->next_desc = 0;
txdesc->status = cpu_to_le32 ((entry << 2) | DisableAlign);
txdesc->frag[0].addr = cpu_to_le32(dma_map_single(&np->pci_dev->dev,
skb->data, skb->len, DMA_TO_DEVICE));
if (dma_mapping_error(&np->pci_dev->dev,
txdesc->frag[0].addr))
goto drop_frame;
txdesc->frag[0].length = cpu_to_le32 (skb->len | LastFrag);
/* Increment cur_tx before tasklet_schedule() */
np->cur_tx++;
mb();
/* Schedule a tx_poll() task */
tasklet_schedule(&np->tx_tasklet);
/* On some architectures: explicitly flush cache lines here. */
if (np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 1 &&
!netif_queue_stopped(dev)) {
/* do nothing */
} else {
netif_stop_queue (dev);
}
if (netif_msg_tx_queued(np)) {
printk (KERN_DEBUG
"%s: Transmit frame #%d queued in slot %d.\n",
dev->name, np->cur_tx, entry);
}
return NETDEV_TX_OK;
drop_frame:
dev_kfree_skb(skb);
np->tx_skbuff[entry] = NULL;
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
/* Reset hardware tx and free all of tx buffers */
static int
reset_tx (struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
struct sk_buff *skb;
int i;
/* Reset tx logic, TxListPtr will be cleaned */
iowrite16 (TxDisable, ioaddr + MACCtrl1);
sundance_reset(dev, (NetworkReset|FIFOReset|DMAReset|TxReset) << 16);
/* free all tx skbuff */
for (i = 0; i < TX_RING_SIZE; i++) {
np->tx_ring[i].next_desc = 0;
skb = np->tx_skbuff[i];
if (skb) {
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(np->tx_ring[i].frag[0].addr),
skb->len, DMA_TO_DEVICE);
dev_kfree_skb_any(skb);
np->tx_skbuff[i] = NULL;
dev->stats.tx_dropped++;
}
}
np->cur_tx = np->dirty_tx = 0;
np->cur_task = 0;
np->last_tx = NULL;
iowrite8(127, ioaddr + TxDMAPollPeriod);
iowrite16 (StatsEnable | RxEnable | TxEnable, ioaddr + MACCtrl1);
return 0;
}
/* The interrupt handler cleans up after the Tx thread,
and schedule a Rx thread work */
static irqreturn_t intr_handler(int irq, void *dev_instance)
{
struct net_device *dev = (struct net_device *)dev_instance;
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
int hw_frame_id;
int tx_cnt;
int tx_status;
int handled = 0;
int i;
do {
int intr_status = ioread16(ioaddr + IntrStatus);
iowrite16(intr_status, ioaddr + IntrStatus);
if (netif_msg_intr(np))
printk(KERN_DEBUG "%s: Interrupt, status %4.4x.\n",
dev->name, intr_status);
if (!(intr_status & DEFAULT_INTR))
break;
handled = 1;
if (intr_status & (IntrRxDMADone)) {
iowrite16(DEFAULT_INTR & ~(IntrRxDone|IntrRxDMADone),
ioaddr + IntrEnable);
if (np->budget < 0)
np->budget = RX_BUDGET;
tasklet_schedule(&np->rx_tasklet);
}
if (intr_status & (IntrTxDone | IntrDrvRqst)) {
tx_status = ioread16 (ioaddr + TxStatus);
for (tx_cnt=32; tx_status & 0x80; --tx_cnt) {
if (netif_msg_tx_done(np))
printk
("%s: Transmit status is %2.2x.\n",
dev->name, tx_status);
if (tx_status & 0x1e) {
if (netif_msg_tx_err(np))
printk("%s: Transmit error status %4.4x.\n",
dev->name, tx_status);
dev->stats.tx_errors++;
if (tx_status & 0x10)
dev->stats.tx_fifo_errors++;
if (tx_status & 0x08)
dev->stats.collisions++;
if (tx_status & 0x04)
dev->stats.tx_fifo_errors++;
if (tx_status & 0x02)
dev->stats.tx_window_errors++;
/*
** This reset has been verified on
** DFE-580TX boards ! phdm@macqel.be.
*/
if (tx_status & 0x10) { /* TxUnderrun */
/* Restart Tx FIFO and transmitter */
sundance_reset(dev, (NetworkReset|FIFOReset|TxReset) << 16);
/* No need to reset the Tx pointer here */
}
/* Restart the Tx. Need to make sure tx enabled */
i = 10;
do {
iowrite16(ioread16(ioaddr + MACCtrl1) | TxEnable, ioaddr + MACCtrl1);
if (ioread16(ioaddr + MACCtrl1) & TxEnabled)
break;
mdelay(1);
} while (--i);
}
/* Yup, this is a documentation bug. It cost me *hours*. */
iowrite16 (0, ioaddr + TxStatus);
if (tx_cnt < 0) {
iowrite32(5000, ioaddr + DownCounter);
break;
}
tx_status = ioread16 (ioaddr + TxStatus);
}
hw_frame_id = (tx_status >> 8) & 0xff;
} else {
hw_frame_id = ioread8(ioaddr + TxFrameId);
}
if (np->pci_dev->revision >= 0x14) {
spin_lock(&np->lock);
for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
int entry = np->dirty_tx % TX_RING_SIZE;
struct sk_buff *skb;
int sw_frame_id;
sw_frame_id = (le32_to_cpu(
np->tx_ring[entry].status) >> 2) & 0xff;
if (sw_frame_id == hw_frame_id &&
!(le32_to_cpu(np->tx_ring[entry].status)
& 0x00010000))
break;
if (sw_frame_id == (hw_frame_id + 1) %
TX_RING_SIZE)
break;
skb = np->tx_skbuff[entry];
/* Free the original skb. */
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(np->tx_ring[entry].frag[0].addr),
skb->len, DMA_TO_DEVICE);
dev_kfree_skb_irq (np->tx_skbuff[entry]);
np->tx_skbuff[entry] = NULL;
np->tx_ring[entry].frag[0].addr = 0;
np->tx_ring[entry].frag[0].length = 0;
}
spin_unlock(&np->lock);
} else {
spin_lock(&np->lock);
for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
int entry = np->dirty_tx % TX_RING_SIZE;
struct sk_buff *skb;
if (!(le32_to_cpu(np->tx_ring[entry].status)
& 0x00010000))
break;
skb = np->tx_skbuff[entry];
/* Free the original skb. */
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(np->tx_ring[entry].frag[0].addr),
skb->len, DMA_TO_DEVICE);
dev_kfree_skb_irq (np->tx_skbuff[entry]);
np->tx_skbuff[entry] = NULL;
np->tx_ring[entry].frag[0].addr = 0;
np->tx_ring[entry].frag[0].length = 0;
}
spin_unlock(&np->lock);
}
if (netif_queue_stopped(dev) &&
np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
/* The ring is no longer full, clear busy flag. */
netif_wake_queue (dev);
}
/* Abnormal error summary/uncommon events handlers. */
if (intr_status & (IntrPCIErr | LinkChange | StatsMax))
netdev_error(dev, intr_status);
} while (0);
if (netif_msg_intr(np))
printk(KERN_DEBUG "%s: exiting interrupt, status=%#4.4x.\n",
dev->name, ioread16(ioaddr + IntrStatus));
return IRQ_RETVAL(handled);
}
static void rx_poll(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct netdev_private *np = netdev_priv(dev);
int entry = np->cur_rx % RX_RING_SIZE;
int boguscnt = np->budget;
void __iomem *ioaddr = np->base;
int received = 0;
/* If EOP is set on the next entry, it's a new packet. Send it up. */
while (1) {
struct netdev_desc *desc = &(np->rx_ring[entry]);
u32 frame_status = le32_to_cpu(desc->status);
int pkt_len;
if (--boguscnt < 0) {
goto not_done;
}
if (!(frame_status & DescOwn))
break;
pkt_len = frame_status & 0x1fff; /* Chip omits the CRC. */
if (netif_msg_rx_status(np))
printk(KERN_DEBUG " netdev_rx() status was %8.8x.\n",
frame_status);
if (frame_status & 0x001f4000) {
/* There was a error. */
if (netif_msg_rx_err(np))
printk(KERN_DEBUG " netdev_rx() Rx error was %8.8x.\n",
frame_status);
dev->stats.rx_errors++;
if (frame_status & 0x00100000)
dev->stats.rx_length_errors++;
if (frame_status & 0x00010000)
dev->stats.rx_fifo_errors++;
if (frame_status & 0x00060000)
dev->stats.rx_frame_errors++;
if (frame_status & 0x00080000)
dev->stats.rx_crc_errors++;
if (frame_status & 0x00100000) {
printk(KERN_WARNING "%s: Oversized Ethernet frame,"
" status %8.8x.\n",
dev->name, frame_status);
}
} else {
struct sk_buff *skb;
#ifndef final_version
if (netif_msg_rx_status(np))
printk(KERN_DEBUG " netdev_rx() normal Rx pkt length %d"
", bogus_cnt %d.\n",
pkt_len, boguscnt);
#endif
/* Check if the packet is long enough to accept without copying
to a minimally-sized skbuff. */
if (pkt_len < rx_copybreak &&
(skb = dev_alloc_skb(pkt_len + 2)) != NULL) {
skb_reserve(skb, 2); /* 16 byte align the IP header */
dma_sync_single_for_cpu(&np->pci_dev->dev,
le32_to_cpu(desc->frag[0].addr),
np->rx_buf_sz, DMA_FROM_DEVICE);
skb_copy_to_linear_data(skb, np->rx_skbuff[entry]->data, pkt_len);
dma_sync_single_for_device(&np->pci_dev->dev,
le32_to_cpu(desc->frag[0].addr),
np->rx_buf_sz, DMA_FROM_DEVICE);
skb_put(skb, pkt_len);
} else {
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(desc->frag[0].addr),
np->rx_buf_sz, DMA_FROM_DEVICE);
skb_put(skb = np->rx_skbuff[entry], pkt_len);
np->rx_skbuff[entry] = NULL;
}
skb->protocol = eth_type_trans(skb, dev);
/* Note: checksum -> skb->ip_summed = CHECKSUM_UNNECESSARY; */
netif_rx(skb);
}
entry = (entry + 1) % RX_RING_SIZE;
received++;
}
np->cur_rx = entry;
refill_rx (dev);
np->budget -= received;
iowrite16(DEFAULT_INTR, ioaddr + IntrEnable);
return;
not_done:
np->cur_rx = entry;
refill_rx (dev);
if (!received)
received = 1;
np->budget -= received;
if (np->budget <= 0)
np->budget = RX_BUDGET;
tasklet_schedule(&np->rx_tasklet);
}
static void refill_rx (struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int entry;
int cnt = 0;
/* Refill the Rx ring buffers. */
for (;(np->cur_rx - np->dirty_rx + RX_RING_SIZE) % RX_RING_SIZE > 0;
np->dirty_rx = (np->dirty_rx + 1) % RX_RING_SIZE) {
struct sk_buff *skb;
entry = np->dirty_rx % RX_RING_SIZE;
if (np->rx_skbuff[entry] == NULL) {
skb = dev_alloc_skb(np->rx_buf_sz + 2);
np->rx_skbuff[entry] = skb;
if (skb == NULL)
break; /* Better luck next round. */
skb->dev = dev; /* Mark as being used by this device. */
skb_reserve(skb, 2); /* Align IP on 16 byte boundaries */
np->rx_ring[entry].frag[0].addr = cpu_to_le32(
dma_map_single(&np->pci_dev->dev, skb->data,
np->rx_buf_sz, DMA_FROM_DEVICE));
if (dma_mapping_error(&np->pci_dev->dev,
np->rx_ring[entry].frag[0].addr)) {
dev_kfree_skb_irq(skb);
np->rx_skbuff[entry] = NULL;
break;
}
}
/* Perhaps we need not reset this field. */
np->rx_ring[entry].frag[0].length =
cpu_to_le32(np->rx_buf_sz | LastFrag);
np->rx_ring[entry].status = 0;
cnt++;
}
}
static void netdev_error(struct net_device *dev, int intr_status)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
u16 mii_ctl, mii_advertise, mii_lpa;
int speed;
if (intr_status & LinkChange) {
if (mdio_wait_link(dev, 10) == 0) {
printk(KERN_INFO "%s: Link up\n", dev->name);
if (np->an_enable) {
mii_advertise = mdio_read(dev, np->phys[0],
MII_ADVERTISE);
mii_lpa = mdio_read(dev, np->phys[0], MII_LPA);
mii_advertise &= mii_lpa;
printk(KERN_INFO "%s: Link changed: ",
dev->name);
if (mii_advertise & ADVERTISE_100FULL) {
np->speed = 100;
printk("100Mbps, full duplex\n");
} else if (mii_advertise & ADVERTISE_100HALF) {
np->speed = 100;
printk("100Mbps, half duplex\n");
} else if (mii_advertise & ADVERTISE_10FULL) {
np->speed = 10;
printk("10Mbps, full duplex\n");
} else if (mii_advertise & ADVERTISE_10HALF) {
np->speed = 10;
printk("10Mbps, half duplex\n");
} else
printk("\n");
} else {
mii_ctl = mdio_read(dev, np->phys[0], MII_BMCR);
speed = (mii_ctl & BMCR_SPEED100) ? 100 : 10;
np->speed = speed;
printk(KERN_INFO "%s: Link changed: %dMbps ,",
dev->name, speed);
printk("%s duplex.\n",
(mii_ctl & BMCR_FULLDPLX) ?
"full" : "half");
}
check_duplex(dev);
if (np->flowctrl && np->mii_if.full_duplex) {
iowrite16(ioread16(ioaddr + MulticastFilter1+2) | 0x0200,
ioaddr + MulticastFilter1+2);
iowrite16(ioread16(ioaddr + MACCtrl0) | EnbFlowCtrl,
ioaddr + MACCtrl0);
}
netif_carrier_on(dev);
} else {
printk(KERN_INFO "%s: Link down\n", dev->name);
netif_carrier_off(dev);
}
}
if (intr_status & StatsMax) {
get_stats(dev);
}
if (intr_status & IntrPCIErr) {
printk(KERN_ERR "%s: Something Wicked happened! %4.4x.\n",
dev->name, intr_status);
/* We must do a global reset of DMA to continue. */
}
}
static struct net_device_stats *get_stats(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
unsigned long flags;
u8 late_coll, single_coll, mult_coll;
spin_lock_irqsave(&np->statlock, flags);
/* The chip only need report frame silently dropped. */
dev->stats.rx_missed_errors += ioread8(ioaddr + RxMissed);
dev->stats.tx_packets += ioread16(ioaddr + TxFramesOK);
dev->stats.rx_packets += ioread16(ioaddr + RxFramesOK);
dev->stats.tx_carrier_errors += ioread8(ioaddr + StatsCarrierError);
mult_coll = ioread8(ioaddr + StatsMultiColl);
np->xstats.tx_multiple_collisions += mult_coll;
single_coll = ioread8(ioaddr + StatsOneColl);
np->xstats.tx_single_collisions += single_coll;
late_coll = ioread8(ioaddr + StatsLateColl);
np->xstats.tx_late_collisions += late_coll;
dev->stats.collisions += mult_coll
+ single_coll
+ late_coll;
np->xstats.tx_deferred += ioread8(ioaddr + StatsTxDefer);
np->xstats.tx_deferred_excessive += ioread8(ioaddr + StatsTxXSDefer);
np->xstats.tx_aborted += ioread8(ioaddr + StatsTxAbort);
np->xstats.tx_bcasts += ioread8(ioaddr + StatsBcastTx);
np->xstats.rx_bcasts += ioread8(ioaddr + StatsBcastRx);
np->xstats.tx_mcasts += ioread8(ioaddr + StatsMcastTx);
np->xstats.rx_mcasts += ioread8(ioaddr + StatsMcastRx);
dev->stats.tx_bytes += ioread16(ioaddr + TxOctetsLow);
dev->stats.tx_bytes += ioread16(ioaddr + TxOctetsHigh) << 16;
dev->stats.rx_bytes += ioread16(ioaddr + RxOctetsLow);
dev->stats.rx_bytes += ioread16(ioaddr + RxOctetsHigh) << 16;
spin_unlock_irqrestore(&np->statlock, flags);
return &dev->stats;
}
static void set_rx_mode(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
u16 mc_filter[4]; /* Multicast hash filter */
u32 rx_mode;
int i;
if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
memset(mc_filter, 0xff, sizeof(mc_filter));
rx_mode = AcceptBroadcast | AcceptMulticast | AcceptAll | AcceptMyPhys;
} else if ((netdev_mc_count(dev) > multicast_filter_limit) ||
(dev->flags & IFF_ALLMULTI)) {
/* Too many to match, or accept all multicasts. */
memset(mc_filter, 0xff, sizeof(mc_filter));
rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
} else if (!netdev_mc_empty(dev)) {
struct netdev_hw_addr *ha;
int bit;
int index;
int crc;
memset (mc_filter, 0, sizeof (mc_filter));
netdev_for_each_mc_addr(ha, dev) {
crc = ether_crc_le(ETH_ALEN, ha->addr);
for (index=0, bit=0; bit < 6; bit++, crc <<= 1)
if (crc & 0x80000000) index |= 1 << bit;
mc_filter[index/16] |= (1 << (index % 16));
}
rx_mode = AcceptBroadcast | AcceptMultiHash | AcceptMyPhys;
} else {
iowrite8(AcceptBroadcast | AcceptMyPhys, ioaddr + RxMode);
return;
}
if (np->mii_if.full_duplex && np->flowctrl)
mc_filter[3] |= 0x0200;
for (i = 0; i < 4; i++)
iowrite16(mc_filter[i], ioaddr + MulticastFilter0 + i*2);
iowrite8(rx_mode, ioaddr + RxMode);
}
static int __set_mac_addr(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
u16 addr16;
addr16 = (dev->dev_addr[0] | (dev->dev_addr[1] << 8));
iowrite16(addr16, np->base + StationAddr);
addr16 = (dev->dev_addr[2] | (dev->dev_addr[3] << 8));
iowrite16(addr16, np->base + StationAddr+2);
addr16 = (dev->dev_addr[4] | (dev->dev_addr[5] << 8));
iowrite16(addr16, np->base + StationAddr+4);
return 0;
}
/* Invoked with rtnl_lock held */
static int sundance_set_mac_addr(struct net_device *dev, void *data)
{
const struct sockaddr *addr = data;
if (!is_valid_ether_addr(addr->sa_data))
return -EINVAL;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
__set_mac_addr(dev);
return 0;
}
static const struct {
const char name[ETH_GSTRING_LEN];
} sundance_stats[] = {
{ "tx_multiple_collisions" },
{ "tx_single_collisions" },
{ "tx_late_collisions" },
{ "tx_deferred" },
{ "tx_deferred_excessive" },
{ "tx_aborted" },
{ "tx_bcasts" },
{ "rx_bcasts" },
{ "tx_mcasts" },
{ "rx_mcasts" },
};
static int check_if_running(struct net_device *dev)
{
if (!netif_running(dev))
return -EINVAL;
return 0;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct netdev_private *np = netdev_priv(dev);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(np->pci_dev));
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
spin_lock_irq(&np->lock);
mii_ethtool_gset(&np->mii_if, ecmd);
spin_unlock_irq(&np->lock);
return 0;
}
static int set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
int res;
spin_lock_irq(&np->lock);
res = mii_ethtool_sset(&np->mii_if, ecmd);
spin_unlock_irq(&np->lock);
return res;
}
static int nway_reset(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
return mii_nway_restart(&np->mii_if);
}
static u32 get_link(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
return mii_link_ok(&np->mii_if);
}
static u32 get_msglevel(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
return np->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct netdev_private *np = netdev_priv(dev);
np->msg_enable = val;
}
static void get_strings(struct net_device *dev, u32 stringset,
u8 *data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, sundance_stats, sizeof(sundance_stats));
}
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(sundance_stats);
default:
return -EOPNOTSUPP;
}
}
static void get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *data)
{
struct netdev_private *np = netdev_priv(dev);
int i = 0;
get_stats(dev);
data[i++] = np->xstats.tx_multiple_collisions;
data[i++] = np->xstats.tx_single_collisions;
data[i++] = np->xstats.tx_late_collisions;
data[i++] = np->xstats.tx_deferred;
data[i++] = np->xstats.tx_deferred_excessive;
data[i++] = np->xstats.tx_aborted;
data[i++] = np->xstats.tx_bcasts;
data[i++] = np->xstats.rx_bcasts;
data[i++] = np->xstats.tx_mcasts;
data[i++] = np->xstats.rx_mcasts;
}
static const struct ethtool_ops ethtool_ops = {
.begin = check_if_running,
.get_drvinfo = get_drvinfo,
.get_settings = get_settings,
.set_settings = set_settings,
.nway_reset = nway_reset,
.get_link = get_link,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_strings = get_strings,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_ethtool_stats,
};
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct netdev_private *np = netdev_priv(dev);
int rc;
if (!netif_running(dev))
return -EINVAL;
spin_lock_irq(&np->lock);
rc = generic_mii_ioctl(&np->mii_if, if_mii(rq), cmd, NULL);
spin_unlock_irq(&np->lock);
return rc;
}
static int netdev_close(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->base;
struct sk_buff *skb;
int i;
/* Wait and kill tasklet */
tasklet_kill(&np->rx_tasklet);
tasklet_kill(&np->tx_tasklet);
np->cur_tx = 0;
np->dirty_tx = 0;
np->cur_task = 0;
np->last_tx = NULL;
netif_stop_queue(dev);
if (netif_msg_ifdown(np)) {
printk(KERN_DEBUG "%s: Shutting down ethercard, status was Tx %2.2x "
"Rx %4.4x Int %2.2x.\n",
dev->name, ioread8(ioaddr + TxStatus),
ioread32(ioaddr + RxStatus), ioread16(ioaddr + IntrStatus));
printk(KERN_DEBUG "%s: Queue pointers were Tx %d / %d, Rx %d / %d.\n",
dev->name, np->cur_tx, np->dirty_tx, np->cur_rx, np->dirty_rx);
}
/* Disable interrupts by clearing the interrupt mask. */
iowrite16(0x0000, ioaddr + IntrEnable);
/* Disable Rx and Tx DMA for safely release resource */
iowrite32(0x500, ioaddr + DMACtrl);
/* Stop the chip's Tx and Rx processes. */
iowrite16(TxDisable | RxDisable | StatsDisable, ioaddr + MACCtrl1);
for (i = 2000; i > 0; i--) {
if ((ioread32(ioaddr + DMACtrl) & 0xc000) == 0)
break;
mdelay(1);
}
iowrite16(GlobalReset | DMAReset | FIFOReset | NetworkReset,
ioaddr + ASIC_HI_WORD(ASICCtrl));
for (i = 2000; i > 0; i--) {
if ((ioread16(ioaddr + ASIC_HI_WORD(ASICCtrl)) & ResetBusy) == 0)
break;
mdelay(1);
}
#ifdef __i386__
if (netif_msg_hw(np)) {
printk(KERN_DEBUG " Tx ring at %8.8x:\n",
(int)(np->tx_ring_dma));
for (i = 0; i < TX_RING_SIZE; i++)
printk(KERN_DEBUG " #%d desc. %4.4x %8.8x %8.8x.\n",
i, np->tx_ring[i].status, np->tx_ring[i].frag[0].addr,
np->tx_ring[i].frag[0].length);
printk(KERN_DEBUG " Rx ring %8.8x:\n",
(int)(np->rx_ring_dma));
for (i = 0; i < /*RX_RING_SIZE*/4 ; i++) {
printk(KERN_DEBUG " #%d desc. %4.4x %4.4x %8.8x\n",
i, np->rx_ring[i].status, np->rx_ring[i].frag[0].addr,
np->rx_ring[i].frag[0].length);
}
}
#endif /* __i386__ debugging only */
free_irq(dev->irq, dev);
del_timer_sync(&np->timer);
/* Free all the skbuffs in the Rx queue. */
for (i = 0; i < RX_RING_SIZE; i++) {
np->rx_ring[i].status = 0;
skb = np->rx_skbuff[i];
if (skb) {
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(np->rx_ring[i].frag[0].addr),
np->rx_buf_sz, DMA_FROM_DEVICE);
dev_kfree_skb(skb);
np->rx_skbuff[i] = NULL;
}
np->rx_ring[i].frag[0].addr = cpu_to_le32(0xBADF00D0); /* poison */
}
for (i = 0; i < TX_RING_SIZE; i++) {
np->tx_ring[i].next_desc = 0;
skb = np->tx_skbuff[i];
if (skb) {
dma_unmap_single(&np->pci_dev->dev,
le32_to_cpu(np->tx_ring[i].frag[0].addr),
skb->len, DMA_TO_DEVICE);
dev_kfree_skb(skb);
np->tx_skbuff[i] = NULL;
}
}
return 0;
}
static void __devexit sundance_remove1 (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev) {
struct netdev_private *np = netdev_priv(dev);
unregister_netdev(dev);
dma_free_coherent(&pdev->dev, RX_TOTAL_SIZE,
np->rx_ring, np->rx_ring_dma);
dma_free_coherent(&pdev->dev, TX_TOTAL_SIZE,
np->tx_ring, np->tx_ring_dma);
pci_iounmap(pdev, np->base);
pci_release_regions(pdev);
free_netdev(dev);
pci_set_drvdata(pdev, NULL);
}
}
#ifdef CONFIG_PM
static int sundance_suspend(struct pci_dev *pci_dev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
if (!netif_running(dev))
return 0;
netdev_close(dev);
netif_device_detach(dev);
pci_save_state(pci_dev);
pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state));
return 0;
}
static int sundance_resume(struct pci_dev *pci_dev)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
int err = 0;
if (!netif_running(dev))
return 0;
pci_set_power_state(pci_dev, PCI_D0);
pci_restore_state(pci_dev);
err = netdev_open(dev);
if (err) {
printk(KERN_ERR "%s: Can't resume interface!\n",
dev->name);
goto out;
}
netif_device_attach(dev);
out:
return err;
}
#endif /* CONFIG_PM */
static struct pci_driver sundance_driver = {
.name = DRV_NAME,
.id_table = sundance_pci_tbl,
.probe = sundance_probe1,
.remove = __devexit_p(sundance_remove1),
#ifdef CONFIG_PM
.suspend = sundance_suspend,
.resume = sundance_resume,
#endif /* CONFIG_PM */
};
static int __init sundance_init(void)
{
/* when a module, this is printed whether or not devices are found in probe */
#ifdef MODULE
printk(version);
#endif
return pci_register_driver(&sundance_driver);
}
static void __exit sundance_exit(void)
{
pci_unregister_driver(&sundance_driver);
}
module_init(sundance_init);
module_exit(sundance_exit);
| gpl-2.0 |
sloanyang/android_kernel_huawei_mediapad10fhd | fs/nilfs2/ifile.c | 3026 | 5338 | /*
* ifile.c - NILFS inode file
*
* Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Amagai Yoshiji <amagai@osrg.net>.
* Revised by Ryusuke Konishi <ryusuke@osrg.net>.
*
*/
#include <linux/types.h>
#include <linux/buffer_head.h>
#include "nilfs.h"
#include "mdt.h"
#include "alloc.h"
#include "ifile.h"
struct nilfs_ifile_info {
struct nilfs_mdt_info mi;
struct nilfs_palloc_cache palloc_cache;
};
static inline struct nilfs_ifile_info *NILFS_IFILE_I(struct inode *ifile)
{
return (struct nilfs_ifile_info *)NILFS_MDT(ifile);
}
/**
* nilfs_ifile_create_inode - create a new disk inode
* @ifile: ifile inode
* @out_ino: pointer to a variable to store inode number
* @out_bh: buffer_head contains newly allocated disk inode
*
* Return Value: On success, 0 is returned and the newly allocated inode
* number is stored in the place pointed by @ino, and buffer_head pointer
* that contains newly allocated disk inode structure is stored in the
* place pointed by @out_bh
* On error, one of the following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOSPC - No inode left.
*/
int nilfs_ifile_create_inode(struct inode *ifile, ino_t *out_ino,
struct buffer_head **out_bh)
{
struct nilfs_palloc_req req;
int ret;
req.pr_entry_nr = 0; /* 0 says find free inode from beginning of
a group. dull code!! */
req.pr_entry_bh = NULL;
ret = nilfs_palloc_prepare_alloc_entry(ifile, &req);
if (!ret) {
ret = nilfs_palloc_get_entry_block(ifile, req.pr_entry_nr, 1,
&req.pr_entry_bh);
if (ret < 0)
nilfs_palloc_abort_alloc_entry(ifile, &req);
}
if (ret < 0) {
brelse(req.pr_entry_bh);
return ret;
}
nilfs_palloc_commit_alloc_entry(ifile, &req);
mark_buffer_dirty(req.pr_entry_bh);
nilfs_mdt_mark_dirty(ifile);
*out_ino = (ino_t)req.pr_entry_nr;
*out_bh = req.pr_entry_bh;
return 0;
}
/**
* nilfs_ifile_delete_inode - delete a disk inode
* @ifile: ifile inode
* @ino: inode number
*
* Return Value: On success, 0 is returned. On error, one of the following
* negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOENT - The inode number @ino have not been allocated.
*/
int nilfs_ifile_delete_inode(struct inode *ifile, ino_t ino)
{
struct nilfs_palloc_req req = {
.pr_entry_nr = ino, .pr_entry_bh = NULL
};
struct nilfs_inode *raw_inode;
void *kaddr;
int ret;
ret = nilfs_palloc_prepare_free_entry(ifile, &req);
if (!ret) {
ret = nilfs_palloc_get_entry_block(ifile, req.pr_entry_nr, 0,
&req.pr_entry_bh);
if (ret < 0)
nilfs_palloc_abort_free_entry(ifile, &req);
}
if (ret < 0) {
brelse(req.pr_entry_bh);
return ret;
}
kaddr = kmap_atomic(req.pr_entry_bh->b_page, KM_USER0);
raw_inode = nilfs_palloc_block_get_entry(ifile, req.pr_entry_nr,
req.pr_entry_bh, kaddr);
raw_inode->i_flags = 0;
kunmap_atomic(kaddr, KM_USER0);
mark_buffer_dirty(req.pr_entry_bh);
brelse(req.pr_entry_bh);
nilfs_palloc_commit_free_entry(ifile, &req);
return 0;
}
int nilfs_ifile_get_inode_block(struct inode *ifile, ino_t ino,
struct buffer_head **out_bh)
{
struct super_block *sb = ifile->i_sb;
int err;
if (unlikely(!NILFS_VALID_INODE(sb, ino))) {
nilfs_error(sb, __func__, "bad inode number: %lu",
(unsigned long) ino);
return -EINVAL;
}
err = nilfs_palloc_get_entry_block(ifile, ino, 0, out_bh);
if (unlikely(err))
nilfs_warning(sb, __func__, "unable to read inode: %lu",
(unsigned long) ino);
return err;
}
/**
* nilfs_ifile_read - read or get ifile inode
* @sb: super block instance
* @root: root object
* @inode_size: size of an inode
* @raw_inode: on-disk ifile inode
* @inodep: buffer to store the inode
*/
int nilfs_ifile_read(struct super_block *sb, struct nilfs_root *root,
size_t inode_size, struct nilfs_inode *raw_inode,
struct inode **inodep)
{
struct inode *ifile;
int err;
ifile = nilfs_iget_locked(sb, root, NILFS_IFILE_INO);
if (unlikely(!ifile))
return -ENOMEM;
if (!(ifile->i_state & I_NEW))
goto out;
err = nilfs_mdt_init(ifile, NILFS_MDT_GFP,
sizeof(struct nilfs_ifile_info));
if (err)
goto failed;
err = nilfs_palloc_init_blockgroup(ifile, inode_size);
if (err)
goto failed;
nilfs_palloc_setup_cache(ifile, &NILFS_IFILE_I(ifile)->palloc_cache);
err = nilfs_read_inode_common(ifile, raw_inode);
if (err)
goto failed;
unlock_new_inode(ifile);
out:
*inodep = ifile;
return 0;
failed:
iget_failed(ifile);
return err;
}
| gpl-2.0 |
whdghks913/android_kernel_samsung_c1ktt | drivers/gpu/drm/vmwgfx/vmwgfx_fence.c | 3794 | 31629 | /**************************************************************************
*
* Copyright © 2011 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#include "drmP.h"
#include "vmwgfx_drv.h"
#define VMW_FENCE_WRAP (1 << 31)
struct vmw_fence_manager {
int num_fence_objects;
struct vmw_private *dev_priv;
spinlock_t lock;
struct list_head fence_list;
struct work_struct work;
u32 user_fence_size;
u32 fence_size;
u32 event_fence_action_size;
bool fifo_down;
struct list_head cleanup_list;
uint32_t pending_actions[VMW_ACTION_MAX];
struct mutex goal_irq_mutex;
bool goal_irq_on; /* Protected by @goal_irq_mutex */
bool seqno_valid; /* Protected by @lock, and may not be set to true
without the @goal_irq_mutex held. */
};
struct vmw_user_fence {
struct ttm_base_object base;
struct vmw_fence_obj fence;
};
/**
* struct vmw_event_fence_action - fence action that delivers a drm event.
*
* @e: A struct drm_pending_event that controls the event delivery.
* @action: A struct vmw_fence_action to hook up to a fence.
* @fence: A referenced pointer to the fence to keep it alive while @action
* hangs on it.
* @dev: Pointer to a struct drm_device so we can access the event stuff.
* @kref: Both @e and @action has destructors, so we need to refcount.
* @size: Size accounted for this object.
* @tv_sec: If non-null, the variable pointed to will be assigned
* current time tv_sec val when the fence signals.
* @tv_usec: Must be set if @tv_sec is set, and the variable pointed to will
* be assigned the current time tv_usec val when the fence signals.
*/
struct vmw_event_fence_action {
struct vmw_fence_action action;
struct list_head fpriv_head;
struct drm_pending_event *event;
struct vmw_fence_obj *fence;
struct drm_device *dev;
uint32_t *tv_sec;
uint32_t *tv_usec;
};
/**
* Note on fencing subsystem usage of irqs:
* Typically the vmw_fences_update function is called
*
* a) When a new fence seqno has been submitted by the fifo code.
* b) On-demand when we have waiters. Sleeping waiters will switch on the
* ANY_FENCE irq and call vmw_fences_update function each time an ANY_FENCE
* irq is received. When the last fence waiter is gone, that IRQ is masked
* away.
*
* In situations where there are no waiters and we don't submit any new fences,
* fence objects may not be signaled. This is perfectly OK, since there are
* no consumers of the signaled data, but that is NOT ok when there are fence
* actions attached to a fence. The fencing subsystem then makes use of the
* FENCE_GOAL irq and sets the fence goal seqno to that of the next fence
* which has an action attached, and each time vmw_fences_update is called,
* the subsystem makes sure the fence goal seqno is updated.
*
* The fence goal seqno irq is on as long as there are unsignaled fence
* objects with actions attached to them.
*/
static void vmw_fence_obj_destroy_locked(struct kref *kref)
{
struct vmw_fence_obj *fence =
container_of(kref, struct vmw_fence_obj, kref);
struct vmw_fence_manager *fman = fence->fman;
unsigned int num_fences;
list_del_init(&fence->head);
num_fences = --fman->num_fence_objects;
spin_unlock_irq(&fman->lock);
if (fence->destroy)
fence->destroy(fence);
else
kfree(fence);
spin_lock_irq(&fman->lock);
}
/**
* Execute signal actions on fences recently signaled.
* This is done from a workqueue so we don't have to execute
* signal actions from atomic context.
*/
static void vmw_fence_work_func(struct work_struct *work)
{
struct vmw_fence_manager *fman =
container_of(work, struct vmw_fence_manager, work);
struct list_head list;
struct vmw_fence_action *action, *next_action;
bool seqno_valid;
do {
INIT_LIST_HEAD(&list);
mutex_lock(&fman->goal_irq_mutex);
spin_lock_irq(&fman->lock);
list_splice_init(&fman->cleanup_list, &list);
seqno_valid = fman->seqno_valid;
spin_unlock_irq(&fman->lock);
if (!seqno_valid && fman->goal_irq_on) {
fman->goal_irq_on = false;
vmw_goal_waiter_remove(fman->dev_priv);
}
mutex_unlock(&fman->goal_irq_mutex);
if (list_empty(&list))
return;
/*
* At this point, only we should be able to manipulate the
* list heads of the actions we have on the private list.
* hence fman::lock not held.
*/
list_for_each_entry_safe(action, next_action, &list, head) {
list_del_init(&action->head);
if (action->cleanup)
action->cleanup(action);
}
} while (1);
}
struct vmw_fence_manager *vmw_fence_manager_init(struct vmw_private *dev_priv)
{
struct vmw_fence_manager *fman = kzalloc(sizeof(*fman), GFP_KERNEL);
if (unlikely(fman == NULL))
return NULL;
fman->dev_priv = dev_priv;
spin_lock_init(&fman->lock);
INIT_LIST_HEAD(&fman->fence_list);
INIT_LIST_HEAD(&fman->cleanup_list);
INIT_WORK(&fman->work, &vmw_fence_work_func);
fman->fifo_down = true;
fman->user_fence_size = ttm_round_pot(sizeof(struct vmw_user_fence));
fman->fence_size = ttm_round_pot(sizeof(struct vmw_fence_obj));
fman->event_fence_action_size =
ttm_round_pot(sizeof(struct vmw_event_fence_action));
mutex_init(&fman->goal_irq_mutex);
return fman;
}
void vmw_fence_manager_takedown(struct vmw_fence_manager *fman)
{
unsigned long irq_flags;
bool lists_empty;
(void) cancel_work_sync(&fman->work);
spin_lock_irqsave(&fman->lock, irq_flags);
lists_empty = list_empty(&fman->fence_list) &&
list_empty(&fman->cleanup_list);
spin_unlock_irqrestore(&fman->lock, irq_flags);
BUG_ON(!lists_empty);
kfree(fman);
}
static int vmw_fence_obj_init(struct vmw_fence_manager *fman,
struct vmw_fence_obj *fence,
u32 seqno,
uint32_t mask,
void (*destroy) (struct vmw_fence_obj *fence))
{
unsigned long irq_flags;
unsigned int num_fences;
int ret = 0;
fence->seqno = seqno;
INIT_LIST_HEAD(&fence->seq_passed_actions);
fence->fman = fman;
fence->signaled = 0;
fence->signal_mask = mask;
kref_init(&fence->kref);
fence->destroy = destroy;
init_waitqueue_head(&fence->queue);
spin_lock_irqsave(&fman->lock, irq_flags);
if (unlikely(fman->fifo_down)) {
ret = -EBUSY;
goto out_unlock;
}
list_add_tail(&fence->head, &fman->fence_list);
num_fences = ++fman->num_fence_objects;
out_unlock:
spin_unlock_irqrestore(&fman->lock, irq_flags);
return ret;
}
struct vmw_fence_obj *vmw_fence_obj_reference(struct vmw_fence_obj *fence)
{
if (unlikely(fence == NULL))
return NULL;
kref_get(&fence->kref);
return fence;
}
/**
* vmw_fence_obj_unreference
*
* Note that this function may not be entered with disabled irqs since
* it may re-enable them in the destroy function.
*
*/
void vmw_fence_obj_unreference(struct vmw_fence_obj **fence_p)
{
struct vmw_fence_obj *fence = *fence_p;
struct vmw_fence_manager *fman;
if (unlikely(fence == NULL))
return;
fman = fence->fman;
*fence_p = NULL;
spin_lock_irq(&fman->lock);
BUG_ON(atomic_read(&fence->kref.refcount) == 0);
kref_put(&fence->kref, vmw_fence_obj_destroy_locked);
spin_unlock_irq(&fman->lock);
}
void vmw_fences_perform_actions(struct vmw_fence_manager *fman,
struct list_head *list)
{
struct vmw_fence_action *action, *next_action;
list_for_each_entry_safe(action, next_action, list, head) {
list_del_init(&action->head);
fman->pending_actions[action->type]--;
if (action->seq_passed != NULL)
action->seq_passed(action);
/*
* Add the cleanup action to the cleanup list so that
* it will be performed by a worker task.
*/
list_add_tail(&action->head, &fman->cleanup_list);
}
}
/**
* vmw_fence_goal_new_locked - Figure out a new device fence goal
* seqno if needed.
*
* @fman: Pointer to a fence manager.
* @passed_seqno: The seqno the device currently signals as passed.
*
* This function should be called with the fence manager lock held.
* It is typically called when we have a new passed_seqno, and
* we might need to update the fence goal. It checks to see whether
* the current fence goal has already passed, and, in that case,
* scans through all unsignaled fences to get the next fence object with an
* action attached, and sets the seqno of that fence as a new fence goal.
*
* returns true if the device goal seqno was updated. False otherwise.
*/
static bool vmw_fence_goal_new_locked(struct vmw_fence_manager *fman,
u32 passed_seqno)
{
u32 goal_seqno;
__le32 __iomem *fifo_mem;
struct vmw_fence_obj *fence;
if (likely(!fman->seqno_valid))
return false;
fifo_mem = fman->dev_priv->mmio_virt;
goal_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE_GOAL);
if (likely(passed_seqno - goal_seqno >= VMW_FENCE_WRAP))
return false;
fman->seqno_valid = false;
list_for_each_entry(fence, &fman->fence_list, head) {
if (!list_empty(&fence->seq_passed_actions)) {
fman->seqno_valid = true;
iowrite32(fence->seqno,
fifo_mem + SVGA_FIFO_FENCE_GOAL);
break;
}
}
return true;
}
/**
* vmw_fence_goal_check_locked - Replace the device fence goal seqno if
* needed.
*
* @fence: Pointer to a struct vmw_fence_obj the seqno of which should be
* considered as a device fence goal.
*
* This function should be called with the fence manager lock held.
* It is typically called when an action has been attached to a fence to
* check whether the seqno of that fence should be used for a fence
* goal interrupt. This is typically needed if the current fence goal is
* invalid, or has a higher seqno than that of the current fence object.
*
* returns true if the device goal seqno was updated. False otherwise.
*/
static bool vmw_fence_goal_check_locked(struct vmw_fence_obj *fence)
{
u32 goal_seqno;
__le32 __iomem *fifo_mem;
if (fence->signaled & DRM_VMW_FENCE_FLAG_EXEC)
return false;
fifo_mem = fence->fman->dev_priv->mmio_virt;
goal_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE_GOAL);
if (likely(fence->fman->seqno_valid &&
goal_seqno - fence->seqno < VMW_FENCE_WRAP))
return false;
iowrite32(fence->seqno, fifo_mem + SVGA_FIFO_FENCE_GOAL);
fence->fman->seqno_valid = true;
return true;
}
void vmw_fences_update(struct vmw_fence_manager *fman)
{
unsigned long flags;
struct vmw_fence_obj *fence, *next_fence;
struct list_head action_list;
bool needs_rerun;
uint32_t seqno, new_seqno;
__le32 __iomem *fifo_mem = fman->dev_priv->mmio_virt;
seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE);
rerun:
spin_lock_irqsave(&fman->lock, flags);
list_for_each_entry_safe(fence, next_fence, &fman->fence_list, head) {
if (seqno - fence->seqno < VMW_FENCE_WRAP) {
list_del_init(&fence->head);
fence->signaled |= DRM_VMW_FENCE_FLAG_EXEC;
INIT_LIST_HEAD(&action_list);
list_splice_init(&fence->seq_passed_actions,
&action_list);
vmw_fences_perform_actions(fman, &action_list);
wake_up_all(&fence->queue);
} else
break;
}
needs_rerun = vmw_fence_goal_new_locked(fman, seqno);
if (!list_empty(&fman->cleanup_list))
(void) schedule_work(&fman->work);
spin_unlock_irqrestore(&fman->lock, flags);
/*
* Rerun if the fence goal seqno was updated, and the
* hardware might have raced with that update, so that
* we missed a fence_goal irq.
*/
if (unlikely(needs_rerun)) {
new_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE);
if (new_seqno != seqno) {
seqno = new_seqno;
goto rerun;
}
}
}
bool vmw_fence_obj_signaled(struct vmw_fence_obj *fence,
uint32_t flags)
{
struct vmw_fence_manager *fman = fence->fman;
unsigned long irq_flags;
uint32_t signaled;
spin_lock_irqsave(&fman->lock, irq_flags);
signaled = fence->signaled;
spin_unlock_irqrestore(&fman->lock, irq_flags);
flags &= fence->signal_mask;
if ((signaled & flags) == flags)
return 1;
if ((signaled & DRM_VMW_FENCE_FLAG_EXEC) == 0)
vmw_fences_update(fman);
spin_lock_irqsave(&fman->lock, irq_flags);
signaled = fence->signaled;
spin_unlock_irqrestore(&fman->lock, irq_flags);
return ((signaled & flags) == flags);
}
int vmw_fence_obj_wait(struct vmw_fence_obj *fence,
uint32_t flags, bool lazy,
bool interruptible, unsigned long timeout)
{
struct vmw_private *dev_priv = fence->fman->dev_priv;
long ret;
if (likely(vmw_fence_obj_signaled(fence, flags)))
return 0;
vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
vmw_seqno_waiter_add(dev_priv);
if (interruptible)
ret = wait_event_interruptible_timeout
(fence->queue,
vmw_fence_obj_signaled(fence, flags),
timeout);
else
ret = wait_event_timeout
(fence->queue,
vmw_fence_obj_signaled(fence, flags),
timeout);
vmw_seqno_waiter_remove(dev_priv);
if (unlikely(ret == 0))
ret = -EBUSY;
else if (likely(ret > 0))
ret = 0;
return ret;
}
void vmw_fence_obj_flush(struct vmw_fence_obj *fence)
{
struct vmw_private *dev_priv = fence->fman->dev_priv;
vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
}
static void vmw_fence_destroy(struct vmw_fence_obj *fence)
{
struct vmw_fence_manager *fman = fence->fman;
kfree(fence);
/*
* Free kernel space accounting.
*/
ttm_mem_global_free(vmw_mem_glob(fman->dev_priv),
fman->fence_size);
}
int vmw_fence_create(struct vmw_fence_manager *fman,
uint32_t seqno,
uint32_t mask,
struct vmw_fence_obj **p_fence)
{
struct ttm_mem_global *mem_glob = vmw_mem_glob(fman->dev_priv);
struct vmw_fence_obj *fence;
int ret;
ret = ttm_mem_global_alloc(mem_glob, fman->fence_size,
false, false);
if (unlikely(ret != 0))
return ret;
fence = kzalloc(sizeof(*fence), GFP_KERNEL);
if (unlikely(fence == NULL)) {
ret = -ENOMEM;
goto out_no_object;
}
ret = vmw_fence_obj_init(fman, fence, seqno, mask,
vmw_fence_destroy);
if (unlikely(ret != 0))
goto out_err_init;
*p_fence = fence;
return 0;
out_err_init:
kfree(fence);
out_no_object:
ttm_mem_global_free(mem_glob, fman->fence_size);
return ret;
}
static void vmw_user_fence_destroy(struct vmw_fence_obj *fence)
{
struct vmw_user_fence *ufence =
container_of(fence, struct vmw_user_fence, fence);
struct vmw_fence_manager *fman = fence->fman;
kfree(ufence);
/*
* Free kernel space accounting.
*/
ttm_mem_global_free(vmw_mem_glob(fman->dev_priv),
fman->user_fence_size);
}
static void vmw_user_fence_base_release(struct ttm_base_object **p_base)
{
struct ttm_base_object *base = *p_base;
struct vmw_user_fence *ufence =
container_of(base, struct vmw_user_fence, base);
struct vmw_fence_obj *fence = &ufence->fence;
*p_base = NULL;
vmw_fence_obj_unreference(&fence);
}
int vmw_user_fence_create(struct drm_file *file_priv,
struct vmw_fence_manager *fman,
uint32_t seqno,
uint32_t mask,
struct vmw_fence_obj **p_fence,
uint32_t *p_handle)
{
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_user_fence *ufence;
struct vmw_fence_obj *tmp;
struct ttm_mem_global *mem_glob = vmw_mem_glob(fman->dev_priv);
int ret;
/*
* Kernel memory space accounting, since this object may
* be created by a user-space request.
*/
ret = ttm_mem_global_alloc(mem_glob, fman->user_fence_size,
false, false);
if (unlikely(ret != 0))
return ret;
ufence = kzalloc(sizeof(*ufence), GFP_KERNEL);
if (unlikely(ufence == NULL)) {
ret = -ENOMEM;
goto out_no_object;
}
ret = vmw_fence_obj_init(fman, &ufence->fence, seqno,
mask, vmw_user_fence_destroy);
if (unlikely(ret != 0)) {
kfree(ufence);
goto out_no_object;
}
/*
* The base object holds a reference which is freed in
* vmw_user_fence_base_release.
*/
tmp = vmw_fence_obj_reference(&ufence->fence);
ret = ttm_base_object_init(tfile, &ufence->base, false,
VMW_RES_FENCE,
&vmw_user_fence_base_release, NULL);
if (unlikely(ret != 0)) {
/*
* Free the base object's reference
*/
vmw_fence_obj_unreference(&tmp);
goto out_err;
}
*p_fence = &ufence->fence;
*p_handle = ufence->base.hash.key;
return 0;
out_err:
tmp = &ufence->fence;
vmw_fence_obj_unreference(&tmp);
out_no_object:
ttm_mem_global_free(mem_glob, fman->user_fence_size);
return ret;
}
/**
* vmw_fence_fifo_down - signal all unsignaled fence objects.
*/
void vmw_fence_fifo_down(struct vmw_fence_manager *fman)
{
unsigned long irq_flags;
struct list_head action_list;
int ret;
/*
* The list may be altered while we traverse it, so always
* restart when we've released the fman->lock.
*/
spin_lock_irqsave(&fman->lock, irq_flags);
fman->fifo_down = true;
while (!list_empty(&fman->fence_list)) {
struct vmw_fence_obj *fence =
list_entry(fman->fence_list.prev, struct vmw_fence_obj,
head);
kref_get(&fence->kref);
spin_unlock_irq(&fman->lock);
ret = vmw_fence_obj_wait(fence, fence->signal_mask,
false, false,
VMW_FENCE_WAIT_TIMEOUT);
if (unlikely(ret != 0)) {
list_del_init(&fence->head);
fence->signaled |= DRM_VMW_FENCE_FLAG_EXEC;
INIT_LIST_HEAD(&action_list);
list_splice_init(&fence->seq_passed_actions,
&action_list);
vmw_fences_perform_actions(fman, &action_list);
wake_up_all(&fence->queue);
}
spin_lock_irq(&fman->lock);
BUG_ON(!list_empty(&fence->head));
kref_put(&fence->kref, vmw_fence_obj_destroy_locked);
}
spin_unlock_irqrestore(&fman->lock, irq_flags);
}
void vmw_fence_fifo_up(struct vmw_fence_manager *fman)
{
unsigned long irq_flags;
spin_lock_irqsave(&fman->lock, irq_flags);
fman->fifo_down = false;
spin_unlock_irqrestore(&fman->lock, irq_flags);
}
int vmw_fence_obj_wait_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vmw_fence_wait_arg *arg =
(struct drm_vmw_fence_wait_arg *)data;
unsigned long timeout;
struct ttm_base_object *base;
struct vmw_fence_obj *fence;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
uint64_t wait_timeout = ((uint64_t)arg->timeout_us * HZ);
/*
* 64-bit division not present on 32-bit systems, so do an
* approximation. (Divide by 1000000).
*/
wait_timeout = (wait_timeout >> 20) + (wait_timeout >> 24) -
(wait_timeout >> 26);
if (!arg->cookie_valid) {
arg->cookie_valid = 1;
arg->kernel_cookie = jiffies + wait_timeout;
}
base = ttm_base_object_lookup(tfile, arg->handle);
if (unlikely(base == NULL)) {
printk(KERN_ERR "Wait invalid fence object handle "
"0x%08lx.\n",
(unsigned long)arg->handle);
return -EINVAL;
}
fence = &(container_of(base, struct vmw_user_fence, base)->fence);
timeout = jiffies;
if (time_after_eq(timeout, (unsigned long)arg->kernel_cookie)) {
ret = ((vmw_fence_obj_signaled(fence, arg->flags)) ?
0 : -EBUSY);
goto out;
}
timeout = (unsigned long)arg->kernel_cookie - timeout;
ret = vmw_fence_obj_wait(fence, arg->flags, arg->lazy, true, timeout);
out:
ttm_base_object_unref(&base);
/*
* Optionally unref the fence object.
*/
if (ret == 0 && (arg->wait_options & DRM_VMW_WAIT_OPTION_UNREF))
return ttm_ref_object_base_unref(tfile, arg->handle,
TTM_REF_USAGE);
return ret;
}
int vmw_fence_obj_signaled_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vmw_fence_signaled_arg *arg =
(struct drm_vmw_fence_signaled_arg *) data;
struct ttm_base_object *base;
struct vmw_fence_obj *fence;
struct vmw_fence_manager *fman;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_private *dev_priv = vmw_priv(dev);
base = ttm_base_object_lookup(tfile, arg->handle);
if (unlikely(base == NULL)) {
printk(KERN_ERR "Fence signaled invalid fence object handle "
"0x%08lx.\n",
(unsigned long)arg->handle);
return -EINVAL;
}
fence = &(container_of(base, struct vmw_user_fence, base)->fence);
fman = fence->fman;
arg->signaled = vmw_fence_obj_signaled(fence, arg->flags);
spin_lock_irq(&fman->lock);
arg->signaled_flags = fence->signaled;
arg->passed_seqno = dev_priv->last_read_seqno;
spin_unlock_irq(&fman->lock);
ttm_base_object_unref(&base);
return 0;
}
int vmw_fence_obj_unref_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vmw_fence_arg *arg =
(struct drm_vmw_fence_arg *) data;
return ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
arg->handle,
TTM_REF_USAGE);
}
/**
* vmw_event_fence_fpriv_gone - Remove references to struct drm_file objects
*
* @fman: Pointer to a struct vmw_fence_manager
* @event_list: Pointer to linked list of struct vmw_event_fence_action objects
* with pointers to a struct drm_file object about to be closed.
*
* This function removes all pending fence events with references to a
* specific struct drm_file object about to be closed. The caller is required
* to pass a list of all struct vmw_event_fence_action objects with such
* events attached. This function is typically called before the
* struct drm_file object's event management is taken down.
*/
void vmw_event_fence_fpriv_gone(struct vmw_fence_manager *fman,
struct list_head *event_list)
{
struct vmw_event_fence_action *eaction;
struct drm_pending_event *event;
unsigned long irq_flags;
while (1) {
spin_lock_irqsave(&fman->lock, irq_flags);
if (list_empty(event_list))
goto out_unlock;
eaction = list_first_entry(event_list,
struct vmw_event_fence_action,
fpriv_head);
list_del_init(&eaction->fpriv_head);
event = eaction->event;
eaction->event = NULL;
spin_unlock_irqrestore(&fman->lock, irq_flags);
event->destroy(event);
}
out_unlock:
spin_unlock_irqrestore(&fman->lock, irq_flags);
}
/**
* vmw_event_fence_action_seq_passed
*
* @action: The struct vmw_fence_action embedded in a struct
* vmw_event_fence_action.
*
* This function is called when the seqno of the fence where @action is
* attached has passed. It queues the event on the submitter's event list.
* This function is always called from atomic context, and may be called
* from irq context.
*/
static void vmw_event_fence_action_seq_passed(struct vmw_fence_action *action)
{
struct vmw_event_fence_action *eaction =
container_of(action, struct vmw_event_fence_action, action);
struct drm_device *dev = eaction->dev;
struct drm_pending_event *event = eaction->event;
struct drm_file *file_priv;
unsigned long irq_flags;
if (unlikely(event == NULL))
return;
file_priv = event->file_priv;
spin_lock_irqsave(&dev->event_lock, irq_flags);
if (likely(eaction->tv_sec != NULL)) {
struct timeval tv;
do_gettimeofday(&tv);
*eaction->tv_sec = tv.tv_sec;
*eaction->tv_usec = tv.tv_usec;
}
list_del_init(&eaction->fpriv_head);
list_add_tail(&eaction->event->link, &file_priv->event_list);
eaction->event = NULL;
wake_up_all(&file_priv->event_wait);
spin_unlock_irqrestore(&dev->event_lock, irq_flags);
}
/**
* vmw_event_fence_action_cleanup
*
* @action: The struct vmw_fence_action embedded in a struct
* vmw_event_fence_action.
*
* This function is the struct vmw_fence_action destructor. It's typically
* called from a workqueue.
*/
static void vmw_event_fence_action_cleanup(struct vmw_fence_action *action)
{
struct vmw_event_fence_action *eaction =
container_of(action, struct vmw_event_fence_action, action);
struct vmw_fence_manager *fman = eaction->fence->fman;
unsigned long irq_flags;
spin_lock_irqsave(&fman->lock, irq_flags);
list_del(&eaction->fpriv_head);
spin_unlock_irqrestore(&fman->lock, irq_flags);
vmw_fence_obj_unreference(&eaction->fence);
kfree(eaction);
}
/**
* vmw_fence_obj_add_action - Add an action to a fence object.
*
* @fence - The fence object.
* @action - The action to add.
*
* Note that the action callbacks may be executed before this function
* returns.
*/
void vmw_fence_obj_add_action(struct vmw_fence_obj *fence,
struct vmw_fence_action *action)
{
struct vmw_fence_manager *fman = fence->fman;
unsigned long irq_flags;
bool run_update = false;
mutex_lock(&fman->goal_irq_mutex);
spin_lock_irqsave(&fman->lock, irq_flags);
fman->pending_actions[action->type]++;
if (fence->signaled & DRM_VMW_FENCE_FLAG_EXEC) {
struct list_head action_list;
INIT_LIST_HEAD(&action_list);
list_add_tail(&action->head, &action_list);
vmw_fences_perform_actions(fman, &action_list);
} else {
list_add_tail(&action->head, &fence->seq_passed_actions);
/*
* This function may set fman::seqno_valid, so it must
* be run with the goal_irq_mutex held.
*/
run_update = vmw_fence_goal_check_locked(fence);
}
spin_unlock_irqrestore(&fman->lock, irq_flags);
if (run_update) {
if (!fman->goal_irq_on) {
fman->goal_irq_on = true;
vmw_goal_waiter_add(fman->dev_priv);
}
vmw_fences_update(fman);
}
mutex_unlock(&fman->goal_irq_mutex);
}
/**
* vmw_event_fence_action_create - Post an event for sending when a fence
* object seqno has passed.
*
* @file_priv: The file connection on which the event should be posted.
* @fence: The fence object on which to post the event.
* @event: Event to be posted. This event should've been alloced
* using k[mz]alloc, and should've been completely initialized.
* @interruptible: Interruptible waits if possible.
*
* As a side effect, the object pointed to by @event may have been
* freed when this function returns. If this function returns with
* an error code, the caller needs to free that object.
*/
int vmw_event_fence_action_queue(struct drm_file *file_priv,
struct vmw_fence_obj *fence,
struct drm_pending_event *event,
uint32_t *tv_sec,
uint32_t *tv_usec,
bool interruptible)
{
struct vmw_event_fence_action *eaction;
struct vmw_fence_manager *fman = fence->fman;
struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
unsigned long irq_flags;
eaction = kzalloc(sizeof(*eaction), GFP_KERNEL);
if (unlikely(eaction == NULL))
return -ENOMEM;
eaction->event = event;
eaction->action.seq_passed = vmw_event_fence_action_seq_passed;
eaction->action.cleanup = vmw_event_fence_action_cleanup;
eaction->action.type = VMW_ACTION_EVENT;
eaction->fence = vmw_fence_obj_reference(fence);
eaction->dev = fman->dev_priv->dev;
eaction->tv_sec = tv_sec;
eaction->tv_usec = tv_usec;
spin_lock_irqsave(&fman->lock, irq_flags);
list_add_tail(&eaction->fpriv_head, &vmw_fp->fence_events);
spin_unlock_irqrestore(&fman->lock, irq_flags);
vmw_fence_obj_add_action(fence, &eaction->action);
return 0;
}
struct vmw_event_fence_pending {
struct drm_pending_event base;
struct drm_vmw_event_fence event;
};
int vmw_event_fence_action_create(struct drm_file *file_priv,
struct vmw_fence_obj *fence,
uint32_t flags,
uint64_t user_data,
bool interruptible)
{
struct vmw_event_fence_pending *event;
struct drm_device *dev = fence->fman->dev_priv->dev;
unsigned long irq_flags;
int ret;
spin_lock_irqsave(&dev->event_lock, irq_flags);
ret = (file_priv->event_space < sizeof(event->event)) ? -EBUSY : 0;
if (likely(ret == 0))
file_priv->event_space -= sizeof(event->event);
spin_unlock_irqrestore(&dev->event_lock, irq_flags);
if (unlikely(ret != 0)) {
DRM_ERROR("Failed to allocate event space for this file.\n");
goto out_no_space;
}
event = kzalloc(sizeof(event->event), GFP_KERNEL);
if (unlikely(event == NULL)) {
DRM_ERROR("Failed to allocate an event.\n");
ret = -ENOMEM;
goto out_no_event;
}
event->event.base.type = DRM_VMW_EVENT_FENCE_SIGNALED;
event->event.base.length = sizeof(*event);
event->event.user_data = user_data;
event->base.event = &event->event.base;
event->base.file_priv = file_priv;
event->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
if (flags & DRM_VMW_FE_FLAG_REQ_TIME)
ret = vmw_event_fence_action_queue(file_priv, fence,
&event->base,
&event->event.tv_sec,
&event->event.tv_usec,
interruptible);
else
ret = vmw_event_fence_action_queue(file_priv, fence,
&event->base,
NULL,
NULL,
interruptible);
if (ret != 0)
goto out_no_queue;
out_no_queue:
event->base.destroy(&event->base);
out_no_event:
spin_lock_irqsave(&dev->event_lock, irq_flags);
file_priv->event_space += sizeof(*event);
spin_unlock_irqrestore(&dev->event_lock, irq_flags);
out_no_space:
return ret;
}
int vmw_fence_event_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct drm_vmw_fence_event_arg *arg =
(struct drm_vmw_fence_event_arg *) data;
struct vmw_fence_obj *fence = NULL;
struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
struct drm_vmw_fence_rep __user *user_fence_rep =
(struct drm_vmw_fence_rep __user *)(unsigned long)
arg->fence_rep;
uint32_t handle;
int ret;
/*
* Look up an existing fence object,
* and if user-space wants a new reference,
* add one.
*/
if (arg->handle) {
struct ttm_base_object *base =
ttm_base_object_lookup(vmw_fp->tfile, arg->handle);
if (unlikely(base == NULL)) {
DRM_ERROR("Fence event invalid fence object handle "
"0x%08lx.\n",
(unsigned long)arg->handle);
return -EINVAL;
}
fence = &(container_of(base, struct vmw_user_fence,
base)->fence);
(void) vmw_fence_obj_reference(fence);
if (user_fence_rep != NULL) {
bool existed;
ret = ttm_ref_object_add(vmw_fp->tfile, base,
TTM_REF_USAGE, &existed);
if (unlikely(ret != 0)) {
DRM_ERROR("Failed to reference a fence "
"object.\n");
goto out_no_ref_obj;
}
handle = base->hash.key;
}
ttm_base_object_unref(&base);
}
/*
* Create a new fence object.
*/
if (!fence) {
ret = vmw_execbuf_fence_commands(file_priv, dev_priv,
&fence,
(user_fence_rep) ?
&handle : NULL);
if (unlikely(ret != 0)) {
DRM_ERROR("Fence event failed to create fence.\n");
return ret;
}
}
BUG_ON(fence == NULL);
if (arg->flags & DRM_VMW_FE_FLAG_REQ_TIME)
ret = vmw_event_fence_action_create(file_priv, fence,
arg->flags,
arg->user_data,
true);
else
ret = vmw_event_fence_action_create(file_priv, fence,
arg->flags,
arg->user_data,
true);
if (unlikely(ret != 0)) {
if (ret != -ERESTARTSYS)
DRM_ERROR("Failed to attach event to fence.\n");
goto out_no_create;
}
vmw_execbuf_copy_fence_user(dev_priv, vmw_fp, 0, user_fence_rep, fence,
handle);
vmw_fence_obj_unreference(&fence);
return 0;
out_no_create:
if (user_fence_rep != NULL)
ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
handle, TTM_REF_USAGE);
out_no_ref_obj:
vmw_fence_obj_unreference(&fence);
return ret;
}
| gpl-2.0 |
Cryptoo/kernel | drivers/gpu/drm/i2c/sil164_drv.c | 4306 | 12180 | /*
* Copyright (C) 2010 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/module.h>
#include <drm/drmP.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_encoder_slave.h>
#include <drm/i2c/sil164.h>
struct sil164_priv {
struct sil164_encoder_params config;
struct i2c_client *duallink_slave;
uint8_t saved_state[0x10];
uint8_t saved_slave_state[0x10];
};
#define to_sil164_priv(x) \
((struct sil164_priv *)to_encoder_slave(x)->slave_priv)
#define sil164_dbg(client, format, ...) do { \
if (drm_debug & DRM_UT_KMS) \
dev_printk(KERN_DEBUG, &client->dev, \
"%s: " format, __func__, ## __VA_ARGS__); \
} while (0)
#define sil164_info(client, format, ...) \
dev_info(&client->dev, format, __VA_ARGS__)
#define sil164_err(client, format, ...) \
dev_err(&client->dev, format, __VA_ARGS__)
#define SIL164_I2C_ADDR_MASTER 0x38
#define SIL164_I2C_ADDR_SLAVE 0x39
/* HW register definitions */
#define SIL164_VENDOR_LO 0x0
#define SIL164_VENDOR_HI 0x1
#define SIL164_DEVICE_LO 0x2
#define SIL164_DEVICE_HI 0x3
#define SIL164_REVISION 0x4
#define SIL164_FREQ_MIN 0x6
#define SIL164_FREQ_MAX 0x7
#define SIL164_CONTROL0 0x8
# define SIL164_CONTROL0_POWER_ON 0x01
# define SIL164_CONTROL0_EDGE_RISING 0x02
# define SIL164_CONTROL0_INPUT_24BIT 0x04
# define SIL164_CONTROL0_DUAL_EDGE 0x08
# define SIL164_CONTROL0_HSYNC_ON 0x10
# define SIL164_CONTROL0_VSYNC_ON 0x20
#define SIL164_DETECT 0x9
# define SIL164_DETECT_INTR_STAT 0x01
# define SIL164_DETECT_HOTPLUG_STAT 0x02
# define SIL164_DETECT_RECEIVER_STAT 0x04
# define SIL164_DETECT_INTR_MODE_RECEIVER 0x00
# define SIL164_DETECT_INTR_MODE_HOTPLUG 0x08
# define SIL164_DETECT_OUT_MODE_HIGH 0x00
# define SIL164_DETECT_OUT_MODE_INTR 0x10
# define SIL164_DETECT_OUT_MODE_RECEIVER 0x20
# define SIL164_DETECT_OUT_MODE_HOTPLUG 0x30
# define SIL164_DETECT_VSWING_STAT 0x80
#define SIL164_CONTROL1 0xa
# define SIL164_CONTROL1_DESKEW_ENABLE 0x10
# define SIL164_CONTROL1_DESKEW_INCR_SHIFT 5
#define SIL164_GPIO 0xb
#define SIL164_CONTROL2 0xc
# define SIL164_CONTROL2_FILTER_ENABLE 0x01
# define SIL164_CONTROL2_FILTER_SETTING_SHIFT 1
# define SIL164_CONTROL2_DUALLINK_MASTER 0x40
# define SIL164_CONTROL2_SYNC_CONT 0x80
#define SIL164_DUALLINK 0xd
# define SIL164_DUALLINK_ENABLE 0x10
# define SIL164_DUALLINK_SKEW_SHIFT 5
#define SIL164_PLLZONE 0xe
# define SIL164_PLLZONE_STAT 0x08
# define SIL164_PLLZONE_FORCE_ON 0x10
# define SIL164_PLLZONE_FORCE_HIGH 0x20
/* HW access functions */
static void
sil164_write(struct i2c_client *client, uint8_t addr, uint8_t val)
{
uint8_t buf[] = {addr, val};
int ret;
ret = i2c_master_send(client, buf, ARRAY_SIZE(buf));
if (ret < 0)
sil164_err(client, "Error %d writing to subaddress 0x%x\n",
ret, addr);
}
static uint8_t
sil164_read(struct i2c_client *client, uint8_t addr)
{
uint8_t val;
int ret;
ret = i2c_master_send(client, &addr, sizeof(addr));
if (ret < 0)
goto fail;
ret = i2c_master_recv(client, &val, sizeof(val));
if (ret < 0)
goto fail;
return val;
fail:
sil164_err(client, "Error %d reading from subaddress 0x%x\n",
ret, addr);
return 0;
}
static void
sil164_save_state(struct i2c_client *client, uint8_t *state)
{
int i;
for (i = 0x8; i <= 0xe; i++)
state[i] = sil164_read(client, i);
}
static void
sil164_restore_state(struct i2c_client *client, uint8_t *state)
{
int i;
for (i = 0x8; i <= 0xe; i++)
sil164_write(client, i, state[i]);
}
static void
sil164_set_power_state(struct i2c_client *client, bool on)
{
uint8_t control0 = sil164_read(client, SIL164_CONTROL0);
if (on)
control0 |= SIL164_CONTROL0_POWER_ON;
else
control0 &= ~SIL164_CONTROL0_POWER_ON;
sil164_write(client, SIL164_CONTROL0, control0);
}
static void
sil164_init_state(struct i2c_client *client,
struct sil164_encoder_params *config,
bool duallink)
{
sil164_write(client, SIL164_CONTROL0,
SIL164_CONTROL0_HSYNC_ON |
SIL164_CONTROL0_VSYNC_ON |
(config->input_edge ? SIL164_CONTROL0_EDGE_RISING : 0) |
(config->input_width ? SIL164_CONTROL0_INPUT_24BIT : 0) |
(config->input_dual ? SIL164_CONTROL0_DUAL_EDGE : 0));
sil164_write(client, SIL164_DETECT,
SIL164_DETECT_INTR_STAT |
SIL164_DETECT_OUT_MODE_RECEIVER);
sil164_write(client, SIL164_CONTROL1,
(config->input_skew ? SIL164_CONTROL1_DESKEW_ENABLE : 0) |
(((config->input_skew + 4) & 0x7)
<< SIL164_CONTROL1_DESKEW_INCR_SHIFT));
sil164_write(client, SIL164_CONTROL2,
SIL164_CONTROL2_SYNC_CONT |
(config->pll_filter ? 0 : SIL164_CONTROL2_FILTER_ENABLE) |
(4 << SIL164_CONTROL2_FILTER_SETTING_SHIFT));
sil164_write(client, SIL164_PLLZONE, 0);
if (duallink)
sil164_write(client, SIL164_DUALLINK,
SIL164_DUALLINK_ENABLE |
(((config->duallink_skew + 4) & 0x7)
<< SIL164_DUALLINK_SKEW_SHIFT));
else
sil164_write(client, SIL164_DUALLINK, 0);
}
/* DRM encoder functions */
static void
sil164_encoder_set_config(struct drm_encoder *encoder, void *params)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
priv->config = *(struct sil164_encoder_params *)params;
}
static void
sil164_encoder_dpms(struct drm_encoder *encoder, int mode)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
bool on = (mode == DRM_MODE_DPMS_ON);
bool duallink = (on && encoder->crtc->mode.clock > 165000);
sil164_set_power_state(drm_i2c_encoder_get_client(encoder), on);
if (priv->duallink_slave)
sil164_set_power_state(priv->duallink_slave, duallink);
}
static void
sil164_encoder_save(struct drm_encoder *encoder)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
sil164_save_state(drm_i2c_encoder_get_client(encoder),
priv->saved_state);
if (priv->duallink_slave)
sil164_save_state(priv->duallink_slave,
priv->saved_slave_state);
}
static void
sil164_encoder_restore(struct drm_encoder *encoder)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
sil164_restore_state(drm_i2c_encoder_get_client(encoder),
priv->saved_state);
if (priv->duallink_slave)
sil164_restore_state(priv->duallink_slave,
priv->saved_slave_state);
}
static bool
sil164_encoder_mode_fixup(struct drm_encoder *encoder,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
return true;
}
static int
sil164_encoder_mode_valid(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
if (mode->clock < 32000)
return MODE_CLOCK_LOW;
if (mode->clock > 330000 ||
(mode->clock > 165000 && !priv->duallink_slave))
return MODE_CLOCK_HIGH;
return MODE_OK;
}
static void
sil164_encoder_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
bool duallink = adjusted_mode->clock > 165000;
sil164_init_state(drm_i2c_encoder_get_client(encoder),
&priv->config, duallink);
if (priv->duallink_slave)
sil164_init_state(priv->duallink_slave,
&priv->config, duallink);
sil164_encoder_dpms(encoder, DRM_MODE_DPMS_ON);
}
static enum drm_connector_status
sil164_encoder_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct i2c_client *client = drm_i2c_encoder_get_client(encoder);
if (sil164_read(client, SIL164_DETECT) & SIL164_DETECT_HOTPLUG_STAT)
return connector_status_connected;
else
return connector_status_disconnected;
}
static int
sil164_encoder_get_modes(struct drm_encoder *encoder,
struct drm_connector *connector)
{
return 0;
}
static int
sil164_encoder_create_resources(struct drm_encoder *encoder,
struct drm_connector *connector)
{
return 0;
}
static int
sil164_encoder_set_property(struct drm_encoder *encoder,
struct drm_connector *connector,
struct drm_property *property,
uint64_t val)
{
return 0;
}
static void
sil164_encoder_destroy(struct drm_encoder *encoder)
{
struct sil164_priv *priv = to_sil164_priv(encoder);
if (priv->duallink_slave)
i2c_unregister_device(priv->duallink_slave);
kfree(priv);
drm_i2c_encoder_destroy(encoder);
}
static struct drm_encoder_slave_funcs sil164_encoder_funcs = {
.set_config = sil164_encoder_set_config,
.destroy = sil164_encoder_destroy,
.dpms = sil164_encoder_dpms,
.save = sil164_encoder_save,
.restore = sil164_encoder_restore,
.mode_fixup = sil164_encoder_mode_fixup,
.mode_valid = sil164_encoder_mode_valid,
.mode_set = sil164_encoder_mode_set,
.detect = sil164_encoder_detect,
.get_modes = sil164_encoder_get_modes,
.create_resources = sil164_encoder_create_resources,
.set_property = sil164_encoder_set_property,
};
/* I2C driver functions */
static int
sil164_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
int vendor = sil164_read(client, SIL164_VENDOR_HI) << 8 |
sil164_read(client, SIL164_VENDOR_LO);
int device = sil164_read(client, SIL164_DEVICE_HI) << 8 |
sil164_read(client, SIL164_DEVICE_LO);
int rev = sil164_read(client, SIL164_REVISION);
if (vendor != 0x1 || device != 0x6) {
sil164_dbg(client, "Unknown device %x:%x.%x\n",
vendor, device, rev);
return -ENODEV;
}
sil164_info(client, "Detected device %x:%x.%x\n",
vendor, device, rev);
return 0;
}
static int
sil164_remove(struct i2c_client *client)
{
return 0;
}
static struct i2c_client *
sil164_detect_slave(struct i2c_client *client)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_msg msg = {
.addr = SIL164_I2C_ADDR_SLAVE,
.len = 0,
};
const struct i2c_board_info info = {
I2C_BOARD_INFO("sil164", SIL164_I2C_ADDR_SLAVE)
};
if (i2c_transfer(adap, &msg, 1) != 1) {
sil164_dbg(adap, "No dual-link slave found.");
return NULL;
}
return i2c_new_device(adap, &info);
}
static int
sil164_encoder_init(struct i2c_client *client,
struct drm_device *dev,
struct drm_encoder_slave *encoder)
{
struct sil164_priv *priv;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
encoder->slave_priv = priv;
encoder->slave_funcs = &sil164_encoder_funcs;
priv->duallink_slave = sil164_detect_slave(client);
return 0;
}
static struct i2c_device_id sil164_ids[] = {
{ "sil164", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, sil164_ids);
static struct drm_i2c_encoder_driver sil164_driver = {
.i2c_driver = {
.probe = sil164_probe,
.remove = sil164_remove,
.driver = {
.name = "sil164",
},
.id_table = sil164_ids,
},
.encoder_init = sil164_encoder_init,
};
/* Module initialization */
static int __init
sil164_init(void)
{
return drm_i2c_encoder_register(THIS_MODULE, &sil164_driver);
}
static void __exit
sil164_exit(void)
{
drm_i2c_encoder_unregister(&sil164_driver);
}
MODULE_AUTHOR("Francisco Jerez <currojerez@riseup.net>");
MODULE_DESCRIPTION("Silicon Image sil164 TMDS transmitter driver");
MODULE_LICENSE("GPL and additional rights");
module_init(sil164_init);
module_exit(sil164_exit);
| gpl-2.0 |
h-a-c-k-42/hack42-kernel | arch/arm/mach-iop32x/iq80321.c | 4818 | 4523 | /*
* arch/arm/mach-iop32x/iq80321.c
*
* Board support code for the Intel IQ80321 platform.
*
* Author: Rory Bolt <rorybolt@pacbell.net>
* Copyright (C) 2002 Rory Bolt
* Copyright (C) 2004 Intel Corp.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/string.h>
#include <linux/serial_core.h>
#include <linux/serial_8250.h>
#include <linux/mtd/physmap.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/pci.h>
#include <asm/mach/time.h>
#include <asm/mach-types.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <mach/time.h>
/*
* IQ80321 timer tick configuration.
*/
static void __init iq80321_timer_init(void)
{
/* 33.333 MHz crystal. */
iop_init_time(200000000);
}
static struct sys_timer iq80321_timer = {
.init = iq80321_timer_init,
};
/*
* IQ80321 I/O.
*/
static struct map_desc iq80321_io_desc[] __initdata = {
{ /* on-board devices */
.virtual = IQ80321_UART,
.pfn = __phys_to_pfn(IQ80321_UART),
.length = 0x00100000,
.type = MT_DEVICE,
},
};
void __init iq80321_map_io(void)
{
iop3xx_map_io();
iotable_init(iq80321_io_desc, ARRAY_SIZE(iq80321_io_desc));
}
/*
* IQ80321 PCI.
*/
static int __init
iq80321_pci_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int irq;
if ((slot == 2 || slot == 6) && pin == 1) {
/* PCI-X Slot INTA */
irq = IRQ_IOP32X_XINT2;
} else if ((slot == 2 || slot == 6) && pin == 2) {
/* PCI-X Slot INTA */
irq = IRQ_IOP32X_XINT3;
} else if ((slot == 2 || slot == 6) && pin == 3) {
/* PCI-X Slot INTA */
irq = IRQ_IOP32X_XINT0;
} else if ((slot == 2 || slot == 6) && pin == 4) {
/* PCI-X Slot INTA */
irq = IRQ_IOP32X_XINT1;
} else if (slot == 4 || slot == 8) {
/* Gig-E */
irq = IRQ_IOP32X_XINT0;
} else {
printk(KERN_ERR "iq80321_pci_map_irq() called for unknown "
"device PCI:%d:%d:%d\n", dev->bus->number,
PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn));
irq = -1;
}
return irq;
}
static struct hw_pci iq80321_pci __initdata = {
.swizzle = pci_std_swizzle,
.nr_controllers = 1,
.setup = iop3xx_pci_setup,
.preinit = iop3xx_pci_preinit_cond,
.scan = iop3xx_pci_scan_bus,
.map_irq = iq80321_pci_map_irq,
};
static int __init iq80321_pci_init(void)
{
if ((iop3xx_get_init_atu() == IOP3XX_INIT_ATU_ENABLE) &&
machine_is_iq80321())
pci_common_init(&iq80321_pci);
return 0;
}
subsys_initcall(iq80321_pci_init);
/*
* IQ80321 machine initialisation.
*/
static struct physmap_flash_data iq80321_flash_data = {
.width = 1,
};
static struct resource iq80321_flash_resource = {
.start = 0xf0000000,
.end = 0xf07fffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device iq80321_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &iq80321_flash_data,
},
.num_resources = 1,
.resource = &iq80321_flash_resource,
};
static struct plat_serial8250_port iq80321_serial_port[] = {
{
.mapbase = IQ80321_UART,
.membase = (char *)IQ80321_UART,
.irq = IRQ_IOP32X_XINT1,
.flags = UPF_SKIP_TEST,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = 1843200,
},
{ },
};
static struct resource iq80321_uart_resource = {
.start = IQ80321_UART,
.end = IQ80321_UART + 7,
.flags = IORESOURCE_MEM,
};
static struct platform_device iq80321_serial_device = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = iq80321_serial_port,
},
.num_resources = 1,
.resource = &iq80321_uart_resource,
};
static void __init iq80321_init_machine(void)
{
platform_device_register(&iop3xx_i2c0_device);
platform_device_register(&iop3xx_i2c1_device);
platform_device_register(&iq80321_flash_device);
platform_device_register(&iq80321_serial_device);
platform_device_register(&iop3xx_dma_0_channel);
platform_device_register(&iop3xx_dma_1_channel);
platform_device_register(&iop3xx_aau_channel);
}
MACHINE_START(IQ80321, "Intel IQ80321")
/* Maintainer: Intel Corp. */
.atag_offset = 0x100,
.map_io = iq80321_map_io,
.init_irq = iop32x_init_irq,
.timer = &iq80321_timer,
.init_machine = iq80321_init_machine,
.restart = iop3xx_restart,
MACHINE_END
| gpl-2.0 |
schqiushui/kernel_lollipop_sense_m8ace | sound/soc/nuc900/nuc900-ac97.c | 5074 | 10060 | /*
* Copyright (c) 2009-2010 Nuvoton technology corporation.
*
* Wan ZongShun <mcuos.com@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;version 2 of the License.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/suspend.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <linux/clk.h>
#include <mach/mfp.h>
#include "nuc900-audio.h"
static DEFINE_MUTEX(ac97_mutex);
struct nuc900_audio *nuc900_ac97_data;
static int nuc900_checkready(void)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
if (!(AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS0) & CODEC_READY))
return -EPERM;
return 0;
}
/* AC97 controller reads codec register */
static unsigned short nuc900_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long timeout = 0x10000, val;
mutex_lock(&ac97_mutex);
val = nuc900_checkready();
if (val) {
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
goto out;
}
/* set the R_WB bit and write register index */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS1, R_WB | reg);
/* set the valid frame bit and valid slots */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
val |= (VALID_FRAME | SLOT1_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, val);
udelay(100);
/* polling the AC_R_FINISH */
while (!(AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON) & AC_R_FINISH)
&& timeout--)
mdelay(1);
if (!timeout) {
dev_err(nuc900_audio->dev, "AC97 read register time out !\n");
val = -EPERM;
goto out;
}
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0) ;
val &= ~SLOT1_VALID;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, val);
if (AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS1) >> 2 != reg) {
dev_err(nuc900_audio->dev,
"R_INDEX of REG_ACTL_ACIS1 not match!\n");
}
udelay(100);
val = (AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS2) & 0xFFFF);
out:
mutex_unlock(&ac97_mutex);
return val;
}
/* AC97 controller writes to codec register */
static void nuc900_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long tmp, timeout = 0x10000;
mutex_lock(&ac97_mutex);
tmp = nuc900_checkready();
if (tmp)
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
/* clear the R_WB bit and write register index */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS1, reg);
/* write register value */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS2, val);
/* set the valid frame bit and valid slots */
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp |= SLOT1_VALID | SLOT2_VALID | VALID_FRAME;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
udelay(100);
/* polling the AC_W_FINISH */
while ((AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON) & AC_W_FINISH)
&& timeout--)
mdelay(1);
if (!timeout)
dev_err(nuc900_audio->dev, "AC97 write register time out !\n");
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp &= ~(SLOT1_VALID | SLOT2_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
mutex_unlock(&ac97_mutex);
}
static void nuc900_ac97_warm_reset(struct snd_ac97 *ac97)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* warm reset AC 97 */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val |= AC_W_RES;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
udelay(100);
val = nuc900_checkready();
if (val)
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
mutex_unlock(&ac97_mutex);
}
static void nuc900_ac97_cold_reset(struct snd_ac97 *ac97)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* reset Audio Controller */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val |= ACTL_RESET_BIT;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val &= (~ACTL_RESET_BIT);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
/* reset AC-link interface */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val |= AC_RESET;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val &= ~AC_RESET;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
/* cold reset AC 97 */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val |= AC_C_RES;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val &= (~AC_C_RES);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
udelay(100);
mutex_unlock(&ac97_mutex);
}
/* AC97 controller operations */
struct snd_ac97_bus_ops soc_ac97_ops = {
.read = nuc900_ac97_read,
.write = nuc900_ac97_write,
.reset = nuc900_ac97_cold_reset,
.warm_reset = nuc900_ac97_warm_reset,
}
EXPORT_SYMBOL_GPL(soc_ac97_ops);
static int nuc900_ac97_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
int ret;
unsigned long val, tmp;
ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp |= (SLOT3_VALID | SLOT4_VALID | VALID_FRAME);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_PSR);
tmp |= (P_DMA_END_IRQ | P_DMA_MIDDLE_IRQ);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_PSR, tmp);
val |= AC_PLAY;
} else {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_RSR);
tmp |= (R_DMA_END_IRQ | R_DMA_MIDDLE_IRQ);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RSR, tmp);
val |= AC_RECORD;
}
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp &= ~(SLOT3_VALID | SLOT4_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_PSR, RESET_PRSR);
val &= ~AC_PLAY;
} else {
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RSR, RESET_PRSR);
val &= ~AC_RECORD;
}
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int nuc900_ac97_probe(struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* enable unit clock */
clk_enable(nuc900_audio->clk);
/* enable audio controller and AC-link interface */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_CON);
val |= (IIS_AC_PIN_SEL | ACLINK_EN);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_CON, val);
mutex_unlock(&ac97_mutex);
return 0;
}
static int nuc900_ac97_remove(struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
clk_disable(nuc900_audio->clk);
return 0;
}
static const struct snd_soc_dai_ops nuc900_ac97_dai_ops = {
.trigger = nuc900_ac97_trigger,
};
static struct snd_soc_dai_driver nuc900_ac97_dai = {
.probe = nuc900_ac97_probe,
.remove = nuc900_ac97_remove,
.ac97_control = 1,
.playback = {
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
},
.capture = {
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
},
.ops = &nuc900_ac97_dai_ops,
};
static int __devinit nuc900_ac97_drvprobe(struct platform_device *pdev)
{
struct nuc900_audio *nuc900_audio;
int ret;
if (nuc900_ac97_data)
return -EBUSY;
nuc900_audio = kzalloc(sizeof(struct nuc900_audio), GFP_KERNEL);
if (!nuc900_audio)
return -ENOMEM;
spin_lock_init(&nuc900_audio->lock);
nuc900_audio->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!nuc900_audio->res) {
ret = -ENODEV;
goto out0;
}
if (!request_mem_region(nuc900_audio->res->start,
resource_size(nuc900_audio->res), pdev->name)) {
ret = -EBUSY;
goto out0;
}
nuc900_audio->mmio = ioremap(nuc900_audio->res->start,
resource_size(nuc900_audio->res));
if (!nuc900_audio->mmio) {
ret = -ENOMEM;
goto out1;
}
nuc900_audio->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(nuc900_audio->clk)) {
ret = PTR_ERR(nuc900_audio->clk);
goto out2;
}
nuc900_audio->irq_num = platform_get_irq(pdev, 0);
if (!nuc900_audio->irq_num) {
ret = -EBUSY;
goto out3;
}
nuc900_ac97_data = nuc900_audio;
ret = snd_soc_register_dai(&pdev->dev, &nuc900_ac97_dai);
if (ret)
goto out3;
/* enbale ac97 multifunction pin */
mfp_set_groupg(nuc900_audio->dev, NULL);
return 0;
out3:
clk_put(nuc900_audio->clk);
out2:
iounmap(nuc900_audio->mmio);
out1:
release_mem_region(nuc900_audio->res->start,
resource_size(nuc900_audio->res));
out0:
kfree(nuc900_audio);
return ret;
}
static int __devexit nuc900_ac97_drvremove(struct platform_device *pdev)
{
snd_soc_unregister_dai(&pdev->dev);
clk_put(nuc900_ac97_data->clk);
iounmap(nuc900_ac97_data->mmio);
release_mem_region(nuc900_ac97_data->res->start,
resource_size(nuc900_ac97_data->res));
kfree(nuc900_ac97_data);
nuc900_ac97_data = NULL;
return 0;
}
static struct platform_driver nuc900_ac97_driver = {
.driver = {
.name = "nuc900-ac97",
.owner = THIS_MODULE,
},
.probe = nuc900_ac97_drvprobe,
.remove = __devexit_p(nuc900_ac97_drvremove),
};
module_platform_driver(nuc900_ac97_driver);
MODULE_AUTHOR("Wan ZongShun <mcuos.com@gmail.com>");
MODULE_DESCRIPTION("NUC900 AC97 SoC driver!");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:nuc900-ac97");
| gpl-2.0 |
nighthawk149/xpenology-4.2-kernel | drivers/isdn/mISDN/dsp_blowfish.c | 5074 | 23738 | /*
* Blowfish encryption/decryption for mISDN_dsp.
*
* Copyright Andreas Eversberg (jolly@eversberg.eu)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include "core.h"
#include "dsp.h"
/*
* how to encode a sample stream to 64-bit blocks that will be encryped
*
* first of all, data is collected until a block of 9 samples are received.
* of course, a packet may have much more than 9 sample, but is may have
* not excacly the multiple of 9 samples. if there is a rest, the next
* received data will complete the block.
*
* the block is then converted to 9 uLAW samples without the least sigificant
* bit. the result is a 7-bit encoded sample.
*
* the samples will be reoganised to form 8 bytes of data:
* (5(6) means: encoded sample no. 5, bit 6)
*
* 0(6) 0(5) 0(4) 0(3) 0(2) 0(1) 0(0) 1(6)
* 1(5) 1(4) 1(3) 1(2) 1(1) 1(0) 2(6) 2(5)
* 2(4) 2(3) 2(2) 2(1) 2(0) 3(6) 3(5) 3(4)
* 3(3) 3(2) 3(1) 3(0) 4(6) 4(5) 4(4) 4(3)
* 4(2) 4(1) 4(0) 5(6) 5(5) 5(4) 5(3) 5(2)
* 5(1) 5(0) 6(6) 6(5) 6(4) 6(3) 6(2) 6(1)
* 6(0) 7(6) 7(5) 7(4) 7(3) 7(2) 7(1) 7(0)
* 8(6) 8(5) 8(4) 8(3) 8(2) 8(1) 8(0)
*
* the missing bit 0 of the last byte is filled with some
* random noise, to fill all 8 bytes.
*
* the 8 bytes will be encrypted using blowfish.
*
* the result will be converted into 9 bytes. the bit 7 is used for
* checksumme (CS) for sync (0, 1) and for the last bit:
* (5(6) means: crypted byte 5, bit 6)
*
* 1 0(7) 0(6) 0(5) 0(4) 0(3) 0(2) 0(1)
* 0 0(0) 1(7) 1(6) 1(5) 1(4) 1(3) 1(2)
* 0 1(1) 1(0) 2(7) 2(6) 2(5) 2(4) 2(3)
* 0 2(2) 2(1) 2(0) 3(7) 3(6) 3(5) 3(4)
* 0 3(3) 3(2) 3(1) 3(0) 4(7) 4(6) 4(5)
* CS 4(4) 4(3) 4(2) 4(1) 4(0) 5(7) 5(6)
* CS 5(5) 5(4) 5(3) 5(2) 5(1) 5(0) 6(7)
* CS 6(6) 6(5) 6(4) 6(3) 6(2) 6(1) 6(0)
* 7(0) 7(6) 7(5) 7(4) 7(3) 7(2) 7(1) 7(0)
*
* the checksum is used to detect transmission errors and frame drops.
*
* synchronisation of received block is done by shifting the upper bit of each
* byte (bit 7) to a shift register. if the rigister has the first five bits
* (10000), this is used to find the sync. only if sync has been found, the
* current block of 9 received bytes are decrypted. before that the check
* sum is calculated. if it is incorrect the block is dropped.
* this will avoid loud noise due to corrupt encrypted data.
*
* if the last block is corrupt, the current decoded block is repeated
* until a valid block has been received.
*/
/*
* some blowfish parts are taken from the
* crypto-api for faster implementation
*/
struct bf_ctx {
u32 p[18];
u32 s[1024];
};
static const u32 bf_pbox[16 + 2] = {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b,
};
static const u32 bf_sbox[256 * 4] = {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
};
/*
* Round loop unrolling macros, S is a pointer to a S-Box array
* organized in 4 unsigned longs at a row.
*/
#define GET32_3(x) (((x) & 0xff))
#define GET32_2(x) (((x) >> (8)) & (0xff))
#define GET32_1(x) (((x) >> (16)) & (0xff))
#define GET32_0(x) (((x) >> (24)) & (0xff))
#define bf_F(x) (((S[GET32_0(x)] + S[256 + GET32_1(x)]) ^ \
S[512 + GET32_2(x)]) + S[768 + GET32_3(x)])
#define EROUND(a, b, n) do { b ^= P[n]; a ^= bf_F(b); } while (0)
#define DROUND(a, b, n) do { a ^= bf_F(b); b ^= P[n]; } while (0)
/*
* encrypt isdn data frame
* every block with 9 samples is encrypted
*/
void
dsp_bf_encrypt(struct dsp *dsp, u8 *data, int len)
{
int i = 0, j = dsp->bf_crypt_pos;
u8 *bf_data_in = dsp->bf_data_in;
u8 *bf_crypt_out = dsp->bf_crypt_out;
u32 *P = dsp->bf_p;
u32 *S = dsp->bf_s;
u32 yl, yr;
u32 cs;
u8 nibble;
while (i < len) {
/* collect a block of 9 samples */
if (j < 9) {
bf_data_in[j] = *data;
*data++ = bf_crypt_out[j++];
i++;
continue;
}
j = 0;
/* transcode 9 samples xlaw to 8 bytes */
yl = dsp_audio_law2seven[bf_data_in[0]];
yl = (yl<<7) | dsp_audio_law2seven[bf_data_in[1]];
yl = (yl<<7) | dsp_audio_law2seven[bf_data_in[2]];
yl = (yl<<7) | dsp_audio_law2seven[bf_data_in[3]];
nibble = dsp_audio_law2seven[bf_data_in[4]];
yr = nibble;
yl = (yl<<4) | (nibble>>3);
yr = (yr<<7) | dsp_audio_law2seven[bf_data_in[5]];
yr = (yr<<7) | dsp_audio_law2seven[bf_data_in[6]];
yr = (yr<<7) | dsp_audio_law2seven[bf_data_in[7]];
yr = (yr<<7) | dsp_audio_law2seven[bf_data_in[8]];
yr = (yr<<1) | (bf_data_in[0] & 1);
/* fill unused bit with random noise of audio input */
/* encrypt */
EROUND(yr, yl, 0);
EROUND(yl, yr, 1);
EROUND(yr, yl, 2);
EROUND(yl, yr, 3);
EROUND(yr, yl, 4);
EROUND(yl, yr, 5);
EROUND(yr, yl, 6);
EROUND(yl, yr, 7);
EROUND(yr, yl, 8);
EROUND(yl, yr, 9);
EROUND(yr, yl, 10);
EROUND(yl, yr, 11);
EROUND(yr, yl, 12);
EROUND(yl, yr, 13);
EROUND(yr, yl, 14);
EROUND(yl, yr, 15);
yl ^= P[16];
yr ^= P[17];
/* calculate 3-bit checksumme */
cs = yl ^ (yl>>3) ^ (yl>>6) ^ (yl>>9) ^ (yl>>12) ^ (yl>>15)
^ (yl>>18) ^ (yl>>21) ^ (yl>>24) ^ (yl>>27) ^ (yl>>30)
^ (yr<<2) ^ (yr>>1) ^ (yr>>4) ^ (yr>>7) ^ (yr>>10)
^ (yr>>13) ^ (yr>>16) ^ (yr>>19) ^ (yr>>22) ^ (yr>>25)
^ (yr>>28) ^ (yr>>31);
/*
* transcode 8 crypted bytes to 9 data bytes with sync
* and checksum information
*/
bf_crypt_out[0] = (yl>>25) | 0x80;
bf_crypt_out[1] = (yl>>18) & 0x7f;
bf_crypt_out[2] = (yl>>11) & 0x7f;
bf_crypt_out[3] = (yl>>4) & 0x7f;
bf_crypt_out[4] = ((yl<<3) & 0x78) | ((yr>>29) & 0x07);
bf_crypt_out[5] = ((yr>>22) & 0x7f) | ((cs<<5) & 0x80);
bf_crypt_out[6] = ((yr>>15) & 0x7f) | ((cs<<6) & 0x80);
bf_crypt_out[7] = ((yr>>8) & 0x7f) | (cs<<7);
bf_crypt_out[8] = yr;
}
/* write current count */
dsp->bf_crypt_pos = j;
}
/*
* decrypt isdn data frame
* every block with 9 bytes is decrypted
*/
void
dsp_bf_decrypt(struct dsp *dsp, u8 *data, int len)
{
int i = 0;
u8 j = dsp->bf_decrypt_in_pos;
u8 k = dsp->bf_decrypt_out_pos;
u8 *bf_crypt_inring = dsp->bf_crypt_inring;
u8 *bf_data_out = dsp->bf_data_out;
u16 sync = dsp->bf_sync;
u32 *P = dsp->bf_p;
u32 *S = dsp->bf_s;
u32 yl, yr;
u8 nibble;
u8 cs, cs0, cs1, cs2;
while (i < len) {
/*
* shift upper bit and rotate data to buffer ring
* send current decrypted data
*/
sync = (sync<<1) | ((*data)>>7);
bf_crypt_inring[j++ & 15] = *data;
*data++ = bf_data_out[k++];
i++;
if (k == 9)
k = 0; /* repeat if no sync has been found */
/* check if not in sync */
if ((sync&0x1f0) != 0x100)
continue;
j -= 9;
/* transcode receive data to 64 bit block of encrypted data */
yl = bf_crypt_inring[j++ & 15];
yl = (yl<<7) | bf_crypt_inring[j++ & 15]; /* bit7 = 0 */
yl = (yl<<7) | bf_crypt_inring[j++ & 15]; /* bit7 = 0 */
yl = (yl<<7) | bf_crypt_inring[j++ & 15]; /* bit7 = 0 */
nibble = bf_crypt_inring[j++ & 15]; /* bit7 = 0 */
yr = nibble;
yl = (yl<<4) | (nibble>>3);
cs2 = bf_crypt_inring[j++ & 15];
yr = (yr<<7) | (cs2 & 0x7f);
cs1 = bf_crypt_inring[j++ & 15];
yr = (yr<<7) | (cs1 & 0x7f);
cs0 = bf_crypt_inring[j++ & 15];
yr = (yr<<7) | (cs0 & 0x7f);
yr = (yr<<8) | bf_crypt_inring[j++ & 15];
/* calculate 3-bit checksumme */
cs = yl ^ (yl>>3) ^ (yl>>6) ^ (yl>>9) ^ (yl>>12) ^ (yl>>15)
^ (yl>>18) ^ (yl>>21) ^ (yl>>24) ^ (yl>>27) ^ (yl>>30)
^ (yr<<2) ^ (yr>>1) ^ (yr>>4) ^ (yr>>7) ^ (yr>>10)
^ (yr>>13) ^ (yr>>16) ^ (yr>>19) ^ (yr>>22) ^ (yr>>25)
^ (yr>>28) ^ (yr>>31);
/* check if frame is valid */
if ((cs&0x7) != (((cs2>>5)&4) | ((cs1>>6)&2) | (cs0 >> 7))) {
if (dsp_debug & DEBUG_DSP_BLOWFISH)
printk(KERN_DEBUG
"DSP BLOWFISH: received corrupt frame, "
"checksumme is not correct\n");
continue;
}
/* decrypt */
yr ^= P[17];
yl ^= P[16];
DROUND(yl, yr, 15);
DROUND(yr, yl, 14);
DROUND(yl, yr, 13);
DROUND(yr, yl, 12);
DROUND(yl, yr, 11);
DROUND(yr, yl, 10);
DROUND(yl, yr, 9);
DROUND(yr, yl, 8);
DROUND(yl, yr, 7);
DROUND(yr, yl, 6);
DROUND(yl, yr, 5);
DROUND(yr, yl, 4);
DROUND(yl, yr, 3);
DROUND(yr, yl, 2);
DROUND(yl, yr, 1);
DROUND(yr, yl, 0);
/* transcode 8 crypted bytes to 9 sample bytes */
bf_data_out[0] = dsp_audio_seven2law[(yl>>25) & 0x7f];
bf_data_out[1] = dsp_audio_seven2law[(yl>>18) & 0x7f];
bf_data_out[2] = dsp_audio_seven2law[(yl>>11) & 0x7f];
bf_data_out[3] = dsp_audio_seven2law[(yl>>4) & 0x7f];
bf_data_out[4] = dsp_audio_seven2law[((yl<<3) & 0x78) |
((yr>>29) & 0x07)];
bf_data_out[5] = dsp_audio_seven2law[(yr>>22) & 0x7f];
bf_data_out[6] = dsp_audio_seven2law[(yr>>15) & 0x7f];
bf_data_out[7] = dsp_audio_seven2law[(yr>>8) & 0x7f];
bf_data_out[8] = dsp_audio_seven2law[(yr>>1) & 0x7f];
k = 0; /* start with new decoded frame */
}
/* write current count and sync */
dsp->bf_decrypt_in_pos = j;
dsp->bf_decrypt_out_pos = k;
dsp->bf_sync = sync;
}
/* used to encrypt S and P boxes */
static inline void
encrypt_block(const u32 *P, const u32 *S, u32 *dst, u32 *src)
{
u32 yl = src[0];
u32 yr = src[1];
EROUND(yr, yl, 0);
EROUND(yl, yr, 1);
EROUND(yr, yl, 2);
EROUND(yl, yr, 3);
EROUND(yr, yl, 4);
EROUND(yl, yr, 5);
EROUND(yr, yl, 6);
EROUND(yl, yr, 7);
EROUND(yr, yl, 8);
EROUND(yl, yr, 9);
EROUND(yr, yl, 10);
EROUND(yl, yr, 11);
EROUND(yr, yl, 12);
EROUND(yl, yr, 13);
EROUND(yr, yl, 14);
EROUND(yl, yr, 15);
yl ^= P[16];
yr ^= P[17];
dst[0] = yr;
dst[1] = yl;
}
/*
* initialize the dsp for encryption and decryption using the same key
* Calculates the blowfish S and P boxes for encryption and decryption.
* The margin of keylen must be 4-56 bytes.
* returns 0 if ok.
*/
int
dsp_bf_init(struct dsp *dsp, const u8 *key, uint keylen)
{
short i, j, count;
u32 data[2], temp;
u32 *P = (u32 *)dsp->bf_p;
u32 *S = (u32 *)dsp->bf_s;
if (keylen < 4 || keylen > 56)
return 1;
/* Set dsp states */
i = 0;
while (i < 9) {
dsp->bf_crypt_out[i] = 0xff;
dsp->bf_data_out[i] = dsp_silence;
i++;
}
dsp->bf_crypt_pos = 0;
dsp->bf_decrypt_in_pos = 0;
dsp->bf_decrypt_out_pos = 0;
dsp->bf_sync = 0x1ff;
dsp->bf_enable = 1;
/* Copy the initialization s-boxes */
for (i = 0, count = 0; i < 256; i++)
for (j = 0; j < 4; j++, count++)
S[count] = bf_sbox[count];
/* Set the p-boxes */
for (i = 0; i < 16 + 2; i++)
P[i] = bf_pbox[i];
/* Actual subkey generation */
for (j = 0, i = 0; i < 16 + 2; i++) {
temp = (((u32)key[j] << 24) |
((u32)key[(j + 1) % keylen] << 16) |
((u32)key[(j + 2) % keylen] << 8) |
((u32)key[(j + 3) % keylen]));
P[i] = P[i] ^ temp;
j = (j + 4) % keylen;
}
data[0] = 0x00000000;
data[1] = 0x00000000;
for (i = 0; i < 16 + 2; i += 2) {
encrypt_block(P, S, data, data);
P[i] = data[0];
P[i + 1] = data[1];
}
for (i = 0; i < 4; i++) {
for (j = 0, count = i * 256; j < 256; j += 2, count += 2) {
encrypt_block(P, S, data, data);
S[count] = data[0];
S[count + 1] = data[1];
}
}
return 0;
}
/*
* turn encryption off
*/
void
dsp_bf_cleanup(struct dsp *dsp)
{
dsp->bf_enable = 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_oppo_n1 | drivers/rtc/rtc-ds1742.c | 5074 | 7391 | /*
* An rtc driver for the Dallas DS1742
*
* 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.
*
* Copyright (C) 2006 Torsten Ertbjerg Rasmussen <tr@newtec.dk>
* - nvram size determined from resource
* - this ds1742 driver now supports ds1743.
*/
#include <linux/bcd.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/module.h>
#define DRV_VERSION "0.4"
#define RTC_SIZE 8
#define RTC_CONTROL 0
#define RTC_CENTURY 0
#define RTC_SECONDS 1
#define RTC_MINUTES 2
#define RTC_HOURS 3
#define RTC_DAY 4
#define RTC_DATE 5
#define RTC_MONTH 6
#define RTC_YEAR 7
#define RTC_CENTURY_MASK 0x3f
#define RTC_SECONDS_MASK 0x7f
#define RTC_DAY_MASK 0x07
/* Bits in the Control/Century register */
#define RTC_WRITE 0x80
#define RTC_READ 0x40
/* Bits in the Seconds register */
#define RTC_STOP 0x80
/* Bits in the Day register */
#define RTC_BATT_FLAG 0x80
struct rtc_plat_data {
struct rtc_device *rtc;
void __iomem *ioaddr_nvram;
void __iomem *ioaddr_rtc;
size_t size_nvram;
size_t size;
unsigned long last_jiffies;
struct bin_attribute nvram_attr;
};
static int ds1742_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr_rtc;
u8 century;
century = bin2bcd((tm->tm_year + 1900) / 100);
writeb(RTC_WRITE, ioaddr + RTC_CONTROL);
writeb(bin2bcd(tm->tm_year % 100), ioaddr + RTC_YEAR);
writeb(bin2bcd(tm->tm_mon + 1), ioaddr + RTC_MONTH);
writeb(bin2bcd(tm->tm_wday) & RTC_DAY_MASK, ioaddr + RTC_DAY);
writeb(bin2bcd(tm->tm_mday), ioaddr + RTC_DATE);
writeb(bin2bcd(tm->tm_hour), ioaddr + RTC_HOURS);
writeb(bin2bcd(tm->tm_min), ioaddr + RTC_MINUTES);
writeb(bin2bcd(tm->tm_sec) & RTC_SECONDS_MASK, ioaddr + RTC_SECONDS);
/* RTC_CENTURY and RTC_CONTROL share same register */
writeb(RTC_WRITE | (century & RTC_CENTURY_MASK), ioaddr + RTC_CENTURY);
writeb(century & RTC_CENTURY_MASK, ioaddr + RTC_CONTROL);
return 0;
}
static int ds1742_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr_rtc;
unsigned int year, month, day, hour, minute, second, week;
unsigned int century;
/* give enough time to update RTC in case of continuous read */
if (pdata->last_jiffies == jiffies)
msleep(1);
pdata->last_jiffies = jiffies;
writeb(RTC_READ, ioaddr + RTC_CONTROL);
second = readb(ioaddr + RTC_SECONDS) & RTC_SECONDS_MASK;
minute = readb(ioaddr + RTC_MINUTES);
hour = readb(ioaddr + RTC_HOURS);
day = readb(ioaddr + RTC_DATE);
week = readb(ioaddr + RTC_DAY) & RTC_DAY_MASK;
month = readb(ioaddr + RTC_MONTH);
year = readb(ioaddr + RTC_YEAR);
century = readb(ioaddr + RTC_CENTURY) & RTC_CENTURY_MASK;
writeb(0, ioaddr + RTC_CONTROL);
tm->tm_sec = bcd2bin(second);
tm->tm_min = bcd2bin(minute);
tm->tm_hour = bcd2bin(hour);
tm->tm_mday = bcd2bin(day);
tm->tm_wday = bcd2bin(week);
tm->tm_mon = bcd2bin(month) - 1;
/* year is 1900 + tm->tm_year */
tm->tm_year = bcd2bin(year) + bcd2bin(century) * 100 - 1900;
if (rtc_valid_tm(tm) < 0) {
dev_err(dev, "retrieved date/time is not valid.\n");
rtc_time_to_tm(0, tm);
}
return 0;
}
static const struct rtc_class_ops ds1742_rtc_ops = {
.read_time = ds1742_rtc_read_time,
.set_time = ds1742_rtc_set_time,
};
static ssize_t ds1742_nvram_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr_nvram;
ssize_t count;
for (count = 0; size > 0 && pos < pdata->size_nvram; count++, size--)
*buf++ = readb(ioaddr + pos++);
return count;
}
static ssize_t ds1742_nvram_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr_nvram;
ssize_t count;
for (count = 0; size > 0 && pos < pdata->size_nvram; count++, size--)
writeb(*buf++, ioaddr + pos++);
return count;
}
static int __devinit ds1742_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
struct resource *res;
unsigned int cen, sec;
struct rtc_plat_data *pdata;
void __iomem *ioaddr;
int ret = 0;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
pdata->size = resource_size(res);
if (!devm_request_mem_region(&pdev->dev, res->start, pdata->size,
pdev->name))
return -EBUSY;
ioaddr = devm_ioremap(&pdev->dev, res->start, pdata->size);
if (!ioaddr)
return -ENOMEM;
pdata->ioaddr_nvram = ioaddr;
pdata->size_nvram = pdata->size - RTC_SIZE;
pdata->ioaddr_rtc = ioaddr + pdata->size_nvram;
sysfs_bin_attr_init(&pdata->nvram_attr);
pdata->nvram_attr.attr.name = "nvram";
pdata->nvram_attr.attr.mode = S_IRUGO | S_IWUSR;
pdata->nvram_attr.read = ds1742_nvram_read;
pdata->nvram_attr.write = ds1742_nvram_write;
pdata->nvram_attr.size = pdata->size_nvram;
/* turn RTC on if it was not on */
ioaddr = pdata->ioaddr_rtc;
sec = readb(ioaddr + RTC_SECONDS);
if (sec & RTC_STOP) {
sec &= RTC_SECONDS_MASK;
cen = readb(ioaddr + RTC_CENTURY) & RTC_CENTURY_MASK;
writeb(RTC_WRITE, ioaddr + RTC_CONTROL);
writeb(sec, ioaddr + RTC_SECONDS);
writeb(cen & RTC_CENTURY_MASK, ioaddr + RTC_CONTROL);
}
if (!(readb(ioaddr + RTC_DAY) & RTC_BATT_FLAG))
dev_warn(&pdev->dev, "voltage-low detected.\n");
pdata->last_jiffies = jiffies;
platform_set_drvdata(pdev, pdata);
rtc = rtc_device_register(pdev->name, &pdev->dev,
&ds1742_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
pdata->rtc = rtc;
ret = sysfs_create_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
if (ret) {
dev_err(&pdev->dev, "creating nvram file in sysfs failed\n");
rtc_device_unregister(rtc);
}
return ret;
}
static int __devexit ds1742_rtc_remove(struct platform_device *pdev)
{
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
sysfs_remove_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
rtc_device_unregister(pdata->rtc);
return 0;
}
static struct platform_driver ds1742_rtc_driver = {
.probe = ds1742_rtc_probe,
.remove = __devexit_p(ds1742_rtc_remove),
.driver = {
.name = "rtc-ds1742",
.owner = THIS_MODULE,
},
};
module_platform_driver(ds1742_rtc_driver);
MODULE_AUTHOR("Atsushi Nemoto <anemo@mba.ocn.ne.jp>");
MODULE_DESCRIPTION("Dallas DS1742 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_ALIAS("platform:rtc-ds1742");
| gpl-2.0 |
MasterChief87/android_kernel_zte_draconis | drivers/rtc/rtc-dm355evm.c | 5074 | 4165 | /*
* rtc-dm355evm.c - access battery-backed counter in MSP430 firmware
*
* Copyright (c) 2008 by David Brownell
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <linux/i2c/dm355evm_msp.h>
#include <linux/module.h>
/*
* The MSP430 firmware on the DM355 EVM uses a watch crystal to feed
* a 1 Hz counter. When a backup battery is supplied, that makes a
* reasonable RTC for applications where alarms and non-NTP drift
* compensation aren't important.
*
* The only real glitch is the inability to read or write all four
* counter bytes atomically: the count may increment in the middle
* of an operation, causing trouble when the LSB rolls over.
*
* This driver was tested with firmware revision A4.
*/
union evm_time {
u8 bytes[4];
u32 value;
};
static int dm355evm_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
union evm_time time;
int status;
int tries = 0;
do {
/*
* Read LSB(0) to MSB(3) bytes. Defend against the counter
* rolling over by re-reading until the value is stable,
* and assuming the four reads take at most a few seconds.
*/
status = dm355evm_msp_read(DM355EVM_MSP_RTC_0);
if (status < 0)
return status;
if (tries && time.bytes[0] == status)
break;
time.bytes[0] = status;
status = dm355evm_msp_read(DM355EVM_MSP_RTC_1);
if (status < 0)
return status;
if (tries && time.bytes[1] == status)
break;
time.bytes[1] = status;
status = dm355evm_msp_read(DM355EVM_MSP_RTC_2);
if (status < 0)
return status;
if (tries && time.bytes[2] == status)
break;
time.bytes[2] = status;
status = dm355evm_msp_read(DM355EVM_MSP_RTC_3);
if (status < 0)
return status;
if (tries && time.bytes[3] == status)
break;
time.bytes[3] = status;
} while (++tries < 5);
dev_dbg(dev, "read timestamp %08x\n", time.value);
rtc_time_to_tm(le32_to_cpu(time.value), tm);
return 0;
}
static int dm355evm_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
union evm_time time;
unsigned long value;
int status;
rtc_tm_to_time(tm, &value);
time.value = cpu_to_le32(value);
dev_dbg(dev, "write timestamp %08x\n", time.value);
/*
* REVISIT handle non-atomic writes ... maybe just retry until
* byte[1] sticks (no rollover)?
*/
status = dm355evm_msp_write(time.bytes[0], DM355EVM_MSP_RTC_0);
if (status < 0)
return status;
status = dm355evm_msp_write(time.bytes[1], DM355EVM_MSP_RTC_1);
if (status < 0)
return status;
status = dm355evm_msp_write(time.bytes[2], DM355EVM_MSP_RTC_2);
if (status < 0)
return status;
status = dm355evm_msp_write(time.bytes[3], DM355EVM_MSP_RTC_3);
if (status < 0)
return status;
return 0;
}
static struct rtc_class_ops dm355evm_rtc_ops = {
.read_time = dm355evm_rtc_read_time,
.set_time = dm355evm_rtc_set_time,
};
/*----------------------------------------------------------------------*/
static int __devinit dm355evm_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
rtc = rtc_device_register(pdev->name,
&pdev->dev, &dm355evm_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc)) {
dev_err(&pdev->dev, "can't register RTC device, err %ld\n",
PTR_ERR(rtc));
return PTR_ERR(rtc);
}
platform_set_drvdata(pdev, rtc);
return 0;
}
static int __devexit dm355evm_rtc_remove(struct platform_device *pdev)
{
struct rtc_device *rtc = platform_get_drvdata(pdev);
rtc_device_unregister(rtc);
platform_set_drvdata(pdev, NULL);
return 0;
}
/*
* I2C is used to talk to the MSP430, but this platform device is
* exposed by an MFD driver that manages I2C communications.
*/
static struct platform_driver rtc_dm355evm_driver = {
.probe = dm355evm_rtc_probe,
.remove = __devexit_p(dm355evm_rtc_remove),
.driver = {
.owner = THIS_MODULE,
.name = "rtc-dm355evm",
},
};
module_platform_driver(rtc_dm355evm_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
ElectryDev/android_kernel_kingdom_row | drivers/uio/uio_pruss.c | 5074 | 6475 | /*
* Programmable Real-Time Unit Sub System (PRUSS) UIO driver (uio_pruss)
*
* This driver exports PRUSS host event out interrupts and PRUSS, L3 RAM,
* and DDR RAM to user space for applications interacting with PRUSS firmware
*
* Copyright (C) 2010-11 Texas Instruments Incorporated - http://www.ti.com/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <linux/uio_driver.h>
#include <linux/platform_data/uio_pruss.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <mach/sram.h>
#define DRV_NAME "pruss_uio"
#define DRV_VERSION "1.0"
static int sram_pool_sz = SZ_16K;
module_param(sram_pool_sz, int, 0);
MODULE_PARM_DESC(sram_pool_sz, "sram pool size to allocate ");
static int extram_pool_sz = SZ_256K;
module_param(extram_pool_sz, int, 0);
MODULE_PARM_DESC(extram_pool_sz, "external ram pool size to allocate");
/*
* Host event IRQ numbers from PRUSS - PRUSS can generate up to 8 interrupt
* events to AINTC of ARM host processor - which can be used for IPC b/w PRUSS
* firmware and user space application, async notification from PRU firmware
* to user space application
* 3 PRU_EVTOUT0
* 4 PRU_EVTOUT1
* 5 PRU_EVTOUT2
* 6 PRU_EVTOUT3
* 7 PRU_EVTOUT4
* 8 PRU_EVTOUT5
* 9 PRU_EVTOUT6
* 10 PRU_EVTOUT7
*/
#define MAX_PRUSS_EVT 8
#define PINTC_HIDISR 0x0038
#define PINTC_HIPIR 0x0900
#define HIPIR_NOPEND 0x80000000
#define PINTC_HIER 0x1500
struct uio_pruss_dev {
struct uio_info *info;
struct clk *pruss_clk;
dma_addr_t sram_paddr;
dma_addr_t ddr_paddr;
void __iomem *prussio_vaddr;
void *sram_vaddr;
void *ddr_vaddr;
unsigned int hostirq_start;
unsigned int pintc_base;
};
static irqreturn_t pruss_handler(int irq, struct uio_info *info)
{
struct uio_pruss_dev *gdev = info->priv;
int intr_bit = (irq - gdev->hostirq_start + 2);
int val, intr_mask = (1 << intr_bit);
void __iomem *base = gdev->prussio_vaddr + gdev->pintc_base;
void __iomem *intren_reg = base + PINTC_HIER;
void __iomem *intrdis_reg = base + PINTC_HIDISR;
void __iomem *intrstat_reg = base + PINTC_HIPIR + (intr_bit << 2);
val = ioread32(intren_reg);
/* Is interrupt enabled and active ? */
if (!(val & intr_mask) && (ioread32(intrstat_reg) & HIPIR_NOPEND))
return IRQ_NONE;
/* Disable interrupt */
iowrite32(intr_bit, intrdis_reg);
return IRQ_HANDLED;
}
static void pruss_cleanup(struct platform_device *dev,
struct uio_pruss_dev *gdev)
{
int cnt;
struct uio_info *p = gdev->info;
for (cnt = 0; cnt < MAX_PRUSS_EVT; cnt++, p++) {
uio_unregister_device(p);
kfree(p->name);
}
iounmap(gdev->prussio_vaddr);
if (gdev->ddr_vaddr) {
dma_free_coherent(&dev->dev, extram_pool_sz, gdev->ddr_vaddr,
gdev->ddr_paddr);
}
if (gdev->sram_vaddr)
sram_free(gdev->sram_vaddr, sram_pool_sz);
kfree(gdev->info);
clk_put(gdev->pruss_clk);
kfree(gdev);
}
static int __devinit pruss_probe(struct platform_device *dev)
{
struct uio_info *p;
struct uio_pruss_dev *gdev;
struct resource *regs_prussio;
int ret = -ENODEV, cnt = 0, len;
struct uio_pruss_pdata *pdata = dev->dev.platform_data;
gdev = kzalloc(sizeof(struct uio_pruss_dev), GFP_KERNEL);
if (!gdev)
return -ENOMEM;
gdev->info = kzalloc(sizeof(*p) * MAX_PRUSS_EVT, GFP_KERNEL);
if (!gdev->info) {
kfree(gdev);
return -ENOMEM;
}
/* Power on PRU in case its not done as part of boot-loader */
gdev->pruss_clk = clk_get(&dev->dev, "pruss");
if (IS_ERR(gdev->pruss_clk)) {
dev_err(&dev->dev, "Failed to get clock\n");
kfree(gdev->info);
kfree(gdev);
ret = PTR_ERR(gdev->pruss_clk);
return ret;
} else {
clk_enable(gdev->pruss_clk);
}
regs_prussio = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!regs_prussio) {
dev_err(&dev->dev, "No PRUSS I/O resource specified\n");
goto out_free;
}
if (!regs_prussio->start) {
dev_err(&dev->dev, "Invalid memory resource\n");
goto out_free;
}
gdev->sram_vaddr = sram_alloc(sram_pool_sz, &(gdev->sram_paddr));
if (!gdev->sram_vaddr) {
dev_err(&dev->dev, "Could not allocate SRAM pool\n");
goto out_free;
}
gdev->ddr_vaddr = dma_alloc_coherent(&dev->dev, extram_pool_sz,
&(gdev->ddr_paddr), GFP_KERNEL | GFP_DMA);
if (!gdev->ddr_vaddr) {
dev_err(&dev->dev, "Could not allocate external memory\n");
goto out_free;
}
len = resource_size(regs_prussio);
gdev->prussio_vaddr = ioremap(regs_prussio->start, len);
if (!gdev->prussio_vaddr) {
dev_err(&dev->dev, "Can't remap PRUSS I/O address range\n");
goto out_free;
}
gdev->pintc_base = pdata->pintc_base;
gdev->hostirq_start = platform_get_irq(dev, 0);
for (cnt = 0, p = gdev->info; cnt < MAX_PRUSS_EVT; cnt++, p++) {
p->mem[0].addr = regs_prussio->start;
p->mem[0].size = resource_size(regs_prussio);
p->mem[0].memtype = UIO_MEM_PHYS;
p->mem[1].addr = gdev->sram_paddr;
p->mem[1].size = sram_pool_sz;
p->mem[1].memtype = UIO_MEM_PHYS;
p->mem[2].addr = gdev->ddr_paddr;
p->mem[2].size = extram_pool_sz;
p->mem[2].memtype = UIO_MEM_PHYS;
p->name = kasprintf(GFP_KERNEL, "pruss_evt%d", cnt);
p->version = DRV_VERSION;
/* Register PRUSS IRQ lines */
p->irq = gdev->hostirq_start + cnt;
p->handler = pruss_handler;
p->priv = gdev;
ret = uio_register_device(&dev->dev, p);
if (ret < 0)
goto out_free;
}
platform_set_drvdata(dev, gdev);
return 0;
out_free:
pruss_cleanup(dev, gdev);
return ret;
}
static int __devexit pruss_remove(struct platform_device *dev)
{
struct uio_pruss_dev *gdev = platform_get_drvdata(dev);
pruss_cleanup(dev, gdev);
platform_set_drvdata(dev, NULL);
return 0;
}
static struct platform_driver pruss_driver = {
.probe = pruss_probe,
.remove = __devexit_p(pruss_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(pruss_driver);
MODULE_LICENSE("GPL v2");
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR("Amit Chatterjee <amit.chatterjee@ti.com>");
MODULE_AUTHOR("Pratheesh Gangadhar <pratheesh@ti.com>");
| gpl-2.0 |
gmm001/android_kernel_zte_nx503a-1 | arch/hexagon/mm/uaccess.c | 7378 | 1838 | /*
* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Support for user memory access from kernel. This will
* probably be inlined for performance at some point, but
* for ease of debug, and to a lesser degree for code size,
* we implement here as subroutines.
*/
#include <linux/types.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
/*
* For clear_user(), exploit previously defined copy_to_user function
* and the fact that we've got a handy zero page defined in kernel/head.S
*
* dczero here would be even faster.
*/
__kernel_size_t __clear_user_hexagon(void __user *dest, unsigned long count)
{
long uncleared;
while (count > PAGE_SIZE) {
uncleared = __copy_to_user_hexagon(dest, &empty_zero_page,
PAGE_SIZE);
if (uncleared)
return count - (PAGE_SIZE - uncleared);
count -= PAGE_SIZE;
dest += PAGE_SIZE;
}
if (count)
count = __copy_to_user_hexagon(dest, &empty_zero_page, count);
return count;
}
unsigned long clear_user_hexagon(void __user *dest, unsigned long count)
{
if (!access_ok(VERIFY_WRITE, dest, count))
return count;
else
return __clear_user_hexagon(dest, count);
}
| gpl-2.0 |
nquest/kernel_dns_s4502m | fs/jffs2/compr_rtime.c | 8402 | 2895 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2001-2007 Red Hat, Inc.
* Copyright © 2004-2010 David Woodhouse <dwmw2@infradead.org>
*
* Created by Arjan van de Ven <arjanv@redhat.com>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*
*
* Very simple lz77-ish encoder.
*
* Theory of operation: Both encoder and decoder have a list of "last
* occurrences" for every possible source-value; after sending the
* first source-byte, the second byte indicated the "run" length of
* matches
*
* The algorithm is intended to only send "whole bytes", no bit-messing.
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/jffs2.h>
#include "compr.h"
/* _compress returns the compressed size, -1 if bigger */
static int jffs2_rtime_compress(unsigned char *data_in,
unsigned char *cpage_out,
uint32_t *sourcelen, uint32_t *dstlen)
{
short positions[256];
int outpos = 0;
int pos=0;
memset(positions,0,sizeof(positions));
while (pos < (*sourcelen) && outpos <= (*dstlen)-2) {
int backpos, runlen=0;
unsigned char value;
value = data_in[pos];
cpage_out[outpos++] = data_in[pos++];
backpos = positions[value];
positions[value]=pos;
while ((backpos < pos) && (pos < (*sourcelen)) &&
(data_in[pos]==data_in[backpos++]) && (runlen<255)) {
pos++;
runlen++;
}
cpage_out[outpos++] = runlen;
}
if (outpos >= pos) {
/* We failed */
return -1;
}
/* Tell the caller how much we managed to compress, and how much space it took */
*sourcelen = pos;
*dstlen = outpos;
return 0;
}
static int jffs2_rtime_decompress(unsigned char *data_in,
unsigned char *cpage_out,
uint32_t srclen, uint32_t destlen)
{
short positions[256];
int outpos = 0;
int pos=0;
memset(positions,0,sizeof(positions));
while (outpos<destlen) {
unsigned char value;
int backoffs;
int repeat;
value = data_in[pos++];
cpage_out[outpos++] = value; /* first the verbatim copied byte */
repeat = data_in[pos++];
backoffs = positions[value];
positions[value]=outpos;
if (repeat) {
if (backoffs + repeat >= outpos) {
while(repeat) {
cpage_out[outpos++] = cpage_out[backoffs++];
repeat--;
}
} else {
memcpy(&cpage_out[outpos],&cpage_out[backoffs],repeat);
outpos+=repeat;
}
}
}
return 0;
}
static struct jffs2_compressor jffs2_rtime_comp = {
.priority = JFFS2_RTIME_PRIORITY,
.name = "rtime",
.compr = JFFS2_COMPR_RTIME,
.compress = &jffs2_rtime_compress,
.decompress = &jffs2_rtime_decompress,
#ifdef JFFS2_RTIME_DISABLED
.disabled = 1,
#else
.disabled = 0,
#endif
};
int jffs2_rtime_init(void)
{
return jffs2_register_compressor(&jffs2_rtime_comp);
}
void jffs2_rtime_exit(void)
{
jffs2_unregister_compressor(&jffs2_rtime_comp);
}
| gpl-2.0 |
jdkernel/mecha_aosp_2.6.35 | drivers/ide/cmd64x.c | 9170 | 12315 | /*
* cmd64x.c: Enable interrupts at initialization time on Ultra/PCI machines.
* Due to massive hardware bugs, UltraDMA is only supported
* on the 646U2 and not on the 646U.
*
* Copyright (C) 1998 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1998 David S. Miller (davem@redhat.com)
*
* Copyright (C) 1999-2002 Andre Hedrick <andre@linux-ide.org>
* Copyright (C) 2007-2010 Bartlomiej Zolnierkiewicz
* Copyright (C) 2007,2009 MontaVista Software, Inc. <source@mvista.com>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <asm/io.h>
#define DRV_NAME "cmd64x"
/*
* CMD64x specific registers definition.
*/
#define CFR 0x50
#define CFR_INTR_CH0 0x04
#define CMDTIM 0x52
#define ARTTIM0 0x53
#define DRWTIM0 0x54
#define ARTTIM1 0x55
#define DRWTIM1 0x56
#define ARTTIM23 0x57
#define ARTTIM23_DIS_RA2 0x04
#define ARTTIM23_DIS_RA3 0x08
#define ARTTIM23_INTR_CH1 0x10
#define DRWTIM2 0x58
#define BRST 0x59
#define DRWTIM3 0x5b
#define BMIDECR0 0x70
#define MRDMODE 0x71
#define MRDMODE_INTR_CH0 0x04
#define MRDMODE_INTR_CH1 0x08
#define UDIDETCR0 0x73
#define DTPR0 0x74
#define BMIDECR1 0x78
#define BMIDECSR 0x79
#define UDIDETCR1 0x7B
#define DTPR1 0x7C
static void cmd64x_program_timings(ide_drive_t *drive, u8 mode)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
int bus_speed = ide_pci_clk ? ide_pci_clk : 33;
const unsigned long T = 1000000 / bus_speed;
static const u8 recovery_values[] =
{15, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0};
static const u8 setup_values[] = {0x40, 0x40, 0x40, 0x80, 0, 0xc0};
static const u8 arttim_regs[4] = {ARTTIM0, ARTTIM1, ARTTIM23, ARTTIM23};
static const u8 drwtim_regs[4] = {DRWTIM0, DRWTIM1, DRWTIM2, DRWTIM3};
struct ide_timing t;
u8 arttim = 0;
ide_timing_compute(drive, mode, &t, T, 0);
/*
* In case we've got too long recovery phase, try to lengthen
* the active phase
*/
if (t.recover > 16) {
t.active += t.recover - 16;
t.recover = 16;
}
if (t.active > 16) /* shouldn't actually happen... */
t.active = 16;
/*
* Convert values to internal chipset representation
*/
t.recover = recovery_values[t.recover];
t.active &= 0x0f;
/* Program the active/recovery counts into the DRWTIM register */
pci_write_config_byte(dev, drwtim_regs[drive->dn],
(t.active << 4) | t.recover);
/*
* The primary channel has individual address setup timing registers
* for each drive and the hardware selects the slowest timing itself.
* The secondary channel has one common register and we have to select
* the slowest address setup timing ourselves.
*/
if (hwif->channel) {
ide_drive_t *pair = ide_get_pair_dev(drive);
if (pair) {
struct ide_timing tp;
ide_timing_compute(pair, pair->pio_mode, &tp, T, 0);
ide_timing_merge(&t, &tp, &t, IDE_TIMING_SETUP);
if (pair->dma_mode) {
ide_timing_compute(pair, pair->dma_mode,
&tp, T, 0);
ide_timing_merge(&tp, &t, &t, IDE_TIMING_SETUP);
}
}
}
if (t.setup > 5) /* shouldn't actually happen... */
t.setup = 5;
/*
* Program the address setup clocks into the ARTTIM registers.
* Avoid clearing the secondary channel's interrupt bit.
*/
(void) pci_read_config_byte (dev, arttim_regs[drive->dn], &arttim);
if (hwif->channel)
arttim &= ~ARTTIM23_INTR_CH1;
arttim &= ~0xc0;
arttim |= setup_values[t.setup];
(void) pci_write_config_byte(dev, arttim_regs[drive->dn], arttim);
}
/*
* Attempts to set drive's PIO mode.
* Special cases are 8: prefetch off, 9: prefetch on (both never worked)
*/
static void cmd64x_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
const u8 pio = drive->pio_mode - XFER_PIO_0;
/*
* Filter out the prefetch control values
* to prevent PIO5 from being programmed
*/
if (pio == 8 || pio == 9)
return;
cmd64x_program_timings(drive, XFER_PIO_0 + pio);
}
static void cmd64x_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 unit = drive->dn & 0x01;
u8 regU = 0, pciU = hwif->channel ? UDIDETCR1 : UDIDETCR0;
const u8 speed = drive->dma_mode;
pci_read_config_byte(dev, pciU, ®U);
regU &= ~(unit ? 0xCA : 0x35);
switch(speed) {
case XFER_UDMA_5:
regU |= unit ? 0x0A : 0x05;
break;
case XFER_UDMA_4:
regU |= unit ? 0x4A : 0x15;
break;
case XFER_UDMA_3:
regU |= unit ? 0x8A : 0x25;
break;
case XFER_UDMA_2:
regU |= unit ? 0x42 : 0x11;
break;
case XFER_UDMA_1:
regU |= unit ? 0x82 : 0x21;
break;
case XFER_UDMA_0:
regU |= unit ? 0xC2 : 0x31;
break;
case XFER_MW_DMA_2:
case XFER_MW_DMA_1:
case XFER_MW_DMA_0:
cmd64x_program_timings(drive, speed);
break;
}
pci_write_config_byte(dev, pciU, regU);
}
static void cmd648_clear_irq(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
unsigned long base = pci_resource_start(dev, 4);
u8 irq_mask = hwif->channel ? MRDMODE_INTR_CH1 :
MRDMODE_INTR_CH0;
u8 mrdmode = inb(base + 1);
/* clear the interrupt bit */
outb((mrdmode & ~(MRDMODE_INTR_CH0 | MRDMODE_INTR_CH1)) | irq_mask,
base + 1);
}
static void cmd64x_clear_irq(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
int irq_reg = hwif->channel ? ARTTIM23 : CFR;
u8 irq_mask = hwif->channel ? ARTTIM23_INTR_CH1 :
CFR_INTR_CH0;
u8 irq_stat = 0;
(void) pci_read_config_byte(dev, irq_reg, &irq_stat);
/* clear the interrupt bit */
(void) pci_write_config_byte(dev, irq_reg, irq_stat | irq_mask);
}
static int cmd648_test_irq(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
unsigned long base = pci_resource_start(dev, 4);
u8 irq_mask = hwif->channel ? MRDMODE_INTR_CH1 :
MRDMODE_INTR_CH0;
u8 mrdmode = inb(base + 1);
pr_debug("%s: mrdmode: 0x%02x irq_mask: 0x%02x\n",
hwif->name, mrdmode, irq_mask);
return (mrdmode & irq_mask) ? 1 : 0;
}
static int cmd64x_test_irq(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
int irq_reg = hwif->channel ? ARTTIM23 : CFR;
u8 irq_mask = hwif->channel ? ARTTIM23_INTR_CH1 :
CFR_INTR_CH0;
u8 irq_stat = 0;
(void) pci_read_config_byte(dev, irq_reg, &irq_stat);
pr_debug("%s: irq_stat: 0x%02x irq_mask: 0x%02x\n",
hwif->name, irq_stat, irq_mask);
return (irq_stat & irq_mask) ? 1 : 0;
}
/*
* ASUS P55T2P4D with CMD646 chipset revision 0x01 requires the old
* event order for DMA transfers.
*/
static int cmd646_1_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u8 dma_stat = 0, dma_cmd = 0;
/* get DMA status */
dma_stat = inb(hwif->dma_base + ATA_DMA_STATUS);
/* read DMA command state */
dma_cmd = inb(hwif->dma_base + ATA_DMA_CMD);
/* stop DMA */
outb(dma_cmd & ~1, hwif->dma_base + ATA_DMA_CMD);
/* clear the INTR & ERROR bits */
outb(dma_stat | 6, hwif->dma_base + ATA_DMA_STATUS);
/* verify good DMA status */
return (dma_stat & 7) != 4;
}
static int init_chipset_cmd64x(struct pci_dev *dev)
{
u8 mrdmode = 0;
/* Set a good latency timer and cache line size value. */
(void) pci_write_config_byte(dev, PCI_LATENCY_TIMER, 64);
/* FIXME: pci_set_master() to ensure a good latency timer value */
/*
* Enable interrupts, select MEMORY READ LINE for reads.
*
* NOTE: although not mentioned in the PCI0646U specs,
* bits 0-1 are write only and won't be read back as
* set or not -- PCI0646U2 specs clarify this point.
*/
(void) pci_read_config_byte (dev, MRDMODE, &mrdmode);
mrdmode &= ~0x30;
(void) pci_write_config_byte(dev, MRDMODE, (mrdmode | 0x02));
return 0;
}
static u8 cmd64x_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 bmidecsr = 0, mask = hwif->channel ? 0x02 : 0x01;
switch (dev->device) {
case PCI_DEVICE_ID_CMD_648:
case PCI_DEVICE_ID_CMD_649:
pci_read_config_byte(dev, BMIDECSR, &bmidecsr);
return (bmidecsr & mask) ? ATA_CBL_PATA80 : ATA_CBL_PATA40;
default:
return ATA_CBL_PATA40;
}
}
static const struct ide_port_ops cmd64x_port_ops = {
.set_pio_mode = cmd64x_set_pio_mode,
.set_dma_mode = cmd64x_set_dma_mode,
.clear_irq = cmd64x_clear_irq,
.test_irq = cmd64x_test_irq,
.cable_detect = cmd64x_cable_detect,
};
static const struct ide_port_ops cmd648_port_ops = {
.set_pio_mode = cmd64x_set_pio_mode,
.set_dma_mode = cmd64x_set_dma_mode,
.clear_irq = cmd648_clear_irq,
.test_irq = cmd648_test_irq,
.cable_detect = cmd64x_cable_detect,
};
static const struct ide_dma_ops cmd646_rev1_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = ide_dma_start,
.dma_end = cmd646_1_dma_end,
.dma_test_irq = ide_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = ide_dma_sff_read_status,
};
static const struct ide_port_info cmd64x_chipsets[] __devinitdata = {
{ /* 0: CMD643 */
.name = DRV_NAME,
.init_chipset = init_chipset_cmd64x,
.enablebits = {{0x00,0x00,0x00}, {0x51,0x08,0x08}},
.port_ops = &cmd64x_port_ops,
.host_flags = IDE_HFLAG_CLEAR_SIMPLEX |
IDE_HFLAG_ABUSE_PREFETCH |
IDE_HFLAG_SERIALIZE,
.pio_mask = ATA_PIO5,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = 0x00, /* no udma */
},
{ /* 1: CMD646 */
.name = DRV_NAME,
.init_chipset = init_chipset_cmd64x,
.enablebits = {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
.port_ops = &cmd648_port_ops,
.host_flags = IDE_HFLAG_ABUSE_PREFETCH |
IDE_HFLAG_SERIALIZE,
.pio_mask = ATA_PIO5,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA2,
},
{ /* 2: CMD648 */
.name = DRV_NAME,
.init_chipset = init_chipset_cmd64x,
.enablebits = {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
.port_ops = &cmd648_port_ops,
.host_flags = IDE_HFLAG_ABUSE_PREFETCH,
.pio_mask = ATA_PIO5,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
},
{ /* 3: CMD649 */
.name = DRV_NAME,
.init_chipset = init_chipset_cmd64x,
.enablebits = {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
.port_ops = &cmd648_port_ops,
.host_flags = IDE_HFLAG_ABUSE_PREFETCH,
.pio_mask = ATA_PIO5,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
}
};
static int __devinit cmd64x_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct ide_port_info d;
u8 idx = id->driver_data;
d = cmd64x_chipsets[idx];
if (idx == 1) {
/*
* UltraDMA only supported on PCI646U and PCI646U2, which
* correspond to revisions 0x03, 0x05 and 0x07 respectively.
* Actually, although the CMD tech support people won't
* tell me the details, the 0x03 revision cannot support
* UDMA correctly without hardware modifications, and even
* then it only works with Quantum disks due to some
* hold time assumptions in the 646U part which are fixed
* in the 646U2.
*
* So we only do UltraDMA on revision 0x05 and 0x07 chipsets.
*/
if (dev->revision < 5) {
d.udma_mask = 0x00;
/*
* The original PCI0646 didn't have the primary
* channel enable bit, it appeared starting with
* PCI0646U (i.e. revision ID 3).
*/
if (dev->revision < 3) {
d.enablebits[0].reg = 0;
d.port_ops = &cmd64x_port_ops;
if (dev->revision == 1)
d.dma_ops = &cmd646_rev1_dma_ops;
}
}
}
return ide_pci_init_one(dev, &d, NULL);
}
static const struct pci_device_id cmd64x_pci_tbl[] = {
{ PCI_VDEVICE(CMD, PCI_DEVICE_ID_CMD_643), 0 },
{ PCI_VDEVICE(CMD, PCI_DEVICE_ID_CMD_646), 1 },
{ PCI_VDEVICE(CMD, PCI_DEVICE_ID_CMD_648), 2 },
{ PCI_VDEVICE(CMD, PCI_DEVICE_ID_CMD_649), 3 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, cmd64x_pci_tbl);
static struct pci_driver cmd64x_pci_driver = {
.name = "CMD64x_IDE",
.id_table = cmd64x_pci_tbl,
.probe = cmd64x_init_one,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init cmd64x_ide_init(void)
{
return ide_pci_register_driver(&cmd64x_pci_driver);
}
static void __exit cmd64x_ide_exit(void)
{
pci_unregister_driver(&cmd64x_pci_driver);
}
module_init(cmd64x_ide_init);
module_exit(cmd64x_ide_exit);
MODULE_AUTHOR("Eddie Dost, David Miller, Andre Hedrick, Bartlomiej Zolnierkiewicz");
MODULE_DESCRIPTION("PCI driver module for CMD64x IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mozilla-b2g/codeaurora_kernel_msm | drivers/video/n411.c | 14290 | 4883 | /*
* linux/drivers/video/n411.c -- Platform device for N411 EPD kit
*
* Copyright (C) 2008, Jaya Kumar
*
* 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.
*
* Layout is based on skeletonfb.c by James Simmons and Geert Uytterhoeven.
*
* This driver is written to be used with the Hecuba display controller
* board, and tested with the EInk 800x600 display in 1 bit mode.
* The interface between Hecuba and the host is TTL based GPIO. The
* GPIO requirements are 8 writable data lines and 6 lines for control.
* Only 4 of the controls are actually used here but 6 for future use.
* The driver requires the IO addresses for data and control GPIO at
* load time. It is also possible to use this display with a standard
* PC parallel port.
*
* General notes:
* - User must set dio_addr=0xIOADDR cio_addr=0xIOADDR c2io_addr=0xIOADDR
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/irq.h>
#include <video/hecubafb.h>
static unsigned long dio_addr;
static unsigned long cio_addr;
static unsigned long c2io_addr;
static unsigned long splashval;
static unsigned int nosplash;
static unsigned char ctl;
static void n411_set_ctl(struct hecubafb_par *par, unsigned char bit, unsigned
char state)
{
switch (bit) {
case HCB_CD_BIT:
if (state)
ctl &= ~(HCB_CD_BIT);
else
ctl |= HCB_CD_BIT;
break;
case HCB_DS_BIT:
if (state)
ctl &= ~(HCB_DS_BIT);
else
ctl |= HCB_DS_BIT;
break;
}
outb(ctl, cio_addr);
}
static unsigned char n411_get_ctl(struct hecubafb_par *par)
{
return inb(c2io_addr);
}
static void n411_set_data(struct hecubafb_par *par, unsigned char value)
{
outb(value, dio_addr);
}
static void n411_wait_for_ack(struct hecubafb_par *par, int clear)
{
int timeout;
unsigned char tmp;
timeout = 500;
do {
tmp = n411_get_ctl(par);
if ((tmp & HCB_ACK_BIT) && (!clear))
return;
else if (!(tmp & HCB_ACK_BIT) && (clear))
return;
udelay(1);
} while (timeout--);
printk(KERN_ERR "timed out waiting for ack\n");
}
static int n411_init_control(struct hecubafb_par *par)
{
unsigned char tmp;
/* for init, we want the following setup to be set:
WUP = lo
ACK = hi
DS = hi
RW = hi
CD = lo
*/
/* write WUP to lo, DS to hi, RW to hi, CD to lo */
ctl = HCB_WUP_BIT | HCB_RW_BIT | HCB_CD_BIT ;
n411_set_ctl(par, HCB_DS_BIT, 1);
/* check ACK is not lo */
tmp = n411_get_ctl(par);
if (tmp & HCB_ACK_BIT) {
printk(KERN_ERR "Fail because ACK is already low\n");
return -ENXIO;
}
return 0;
}
static int n411_init_board(struct hecubafb_par *par)
{
int retval;
retval = n411_init_control(par);
if (retval)
return retval;
par->send_command(par, APOLLO_INIT_DISPLAY);
par->send_data(par, 0x81);
/* have to wait while display resets */
udelay(1000);
/* if we were told to splash the screen, we just clear it */
if (!nosplash) {
par->send_command(par, APOLLO_ERASE_DISPLAY);
par->send_data(par, splashval);
}
return 0;
}
static struct hecuba_board n411_board = {
.owner = THIS_MODULE,
.init = n411_init_board,
.set_ctl = n411_set_ctl,
.set_data = n411_set_data,
.wait_for_ack = n411_wait_for_ack,
};
static struct platform_device *n411_device;
static int __init n411_init(void)
{
int ret;
if (!dio_addr || !cio_addr || !c2io_addr) {
printk(KERN_WARNING "no IO addresses supplied\n");
return -EINVAL;
}
/* request our platform independent driver */
request_module("hecubafb");
n411_device = platform_device_alloc("hecubafb", -1);
if (!n411_device)
return -ENOMEM;
platform_device_add_data(n411_device, &n411_board, sizeof(n411_board));
/* this _add binds hecubafb to n411. hecubafb refcounts n411 */
ret = platform_device_add(n411_device);
if (ret)
platform_device_put(n411_device);
return ret;
}
static void __exit n411_exit(void)
{
platform_device_unregister(n411_device);
}
module_init(n411_init);
module_exit(n411_exit);
module_param(nosplash, uint, 0);
MODULE_PARM_DESC(nosplash, "Disable doing the splash screen");
module_param(dio_addr, ulong, 0);
MODULE_PARM_DESC(dio_addr, "IO address for data, eg: 0x480");
module_param(cio_addr, ulong, 0);
MODULE_PARM_DESC(cio_addr, "IO address for control, eg: 0x400");
module_param(c2io_addr, ulong, 0);
MODULE_PARM_DESC(c2io_addr, "IO address for secondary control, eg: 0x408");
module_param(splashval, ulong, 0);
MODULE_PARM_DESC(splashval, "Splash pattern: 0x00 is black, 0x01 is white");
MODULE_DESCRIPTION("board driver for n411 hecuba/apollo epd kit");
MODULE_AUTHOR("Jaya Kumar");
MODULE_LICENSE("GPL");
| gpl-2.0 |
chapuni/gcc | gcc/testsuite/gcc.dg/builtins-48.c | 211 | 3216 | /* { dg-do run } */
/* { dg-options "-O2" } */
extern double fabs(double);
extern float fabsf(float);
extern void abort(void);
double test1(double x)
{
return (-x)*(-x);
}
float test1f(float x)
{
return (-x)*(-x);
}
double test2(double x)
{
return fabs(x)*fabs(x);
}
float test2f(float x)
{
return fabsf(x)*fabsf(x);
}
double test3(double x, double y)
{
return (x*-y)*(x*-y);
}
float test3f(float x, float y)
{
return (x*-y)*(x*-y);
}
double test4(double x, double y)
{
return (x/-y)*(x/-y);
}
float test4f(float x, float y)
{
return (x/-y)*(x/-y);
}
int main()
{
if (test1(1.0) != 1.0)
abort();
if (test1(2.0) != 4.0)
abort();
if (test1(0.0) != 0.0)
abort();
if (test1(-1.0) != 1.0)
abort();
if (test1(-2.0) != 4.0)
abort();
if (test1f(1.0f) != 1.0f)
abort();
if (test1f(2.0f) != 4.0f)
abort();
if (test1f(0.0f) != 0.0f)
abort();
if (test1f(-1.0f) != 1.0f)
abort();
if (test1f(-2.0f) != 4.0f)
abort();
if (test2(1.0) != 1.0)
abort();
if (test2(2.0) != 4.0)
abort();
if (test2(0.0) != 0.0)
abort();
if (test2(-1.0) != 1.0)
abort();
if (test2(-2.0) != 4.0)
abort();
if (test2f(1.0f) != 1.0f)
abort();
if (test2f(2.0f) != 4.0f)
abort();
if (test2f(0.0f) != 0.0f)
abort();
if (test2f(-1.0f) != 1.0f)
abort();
if (test2f(-2.0f) != 4.0f)
abort();
if (test3(1.0,1.0) != 1.0)
abort();
if (test3(1.0,-1.0) != 1.0)
abort();
if (test3(1.0,2.0) != 4.0)
abort();
if (test3(1.0,-2.0) != 4.0)
abort();
if (test3(2.0,1.0) != 4.0)
abort();
if (test3(2.0,-1.0) != 4.0)
abort();
if (test3(2.0,2.0) != 16.0)
abort();
if (test3(2.0,-2.0) != 16.0)
abort();
if (test3(-2.0,1.0) != 4.0)
abort();
if (test3(-2.0,-1.0) != 4.0)
abort();
if (test3(-2.0,2.0) != 16.0)
abort();
if (test3(-2.0,-2.0) != 16.0)
abort();
if (test3f(1.0f,1.0f) != 1.0f)
abort();
if (test3f(1.0f,-1.0f) != 1.0f)
abort();
if (test3f(1.0f,2.0f) != 4.0f)
abort();
if (test3f(1.0f,-2.0f) != 4.0f)
abort();
if (test3f(2.0f,1.0f) != 4.0f)
abort();
if (test3f(2.0f,-1.0f) != 4.0f)
abort();
if (test3f(2.0f,2.0f) != 16.0f)
abort();
if (test3f(2.0f,-2.0f) != 16.0f)
abort();
if (test3f(-2.0f,1.0f) != 4.0f)
abort();
if (test3f(-2.0f,-1.0f) != 4.0f)
abort();
if (test3f(-2.0f,2.0f) != 16.0f)
abort();
if (test3f(-2.0f,-2.0f) != 16.0f)
abort();
if (test4(1.0,1.0) != 1.0)
abort();
if (test4(1.0,-1.0) != 1.0)
abort();
if (test4(-1.0,1.0) != 1.0)
abort();
if (test4(-1.0,-1.0) != 1.0)
abort();
if (test4(6.0,3.0) != 4.0)
abort();
if (test4(6.0,-3.0) != 4.0)
abort();
if (test4(-6.0,3.0) != 4.0)
abort();
if (test4(-6.0,-3.0) != 4.0)
abort();
if (test4f(1.0f,1.0f) != 1.0f)
abort();
if (test4f(1.0f,-1.0f) != 1.0f)
abort();
if (test4f(-1.0f,1.0f) != 1.0f)
abort();
if (test4f(-1.0f,-1.0f) != 1.0f)
abort();
if (test4f(6.0f,3.0f) != 4.0f)
abort();
if (test4f(6.0f,-3.0f) != 4.0f)
abort();
if (test4f(-6.0f,3.0f) != 4.0f)
abort();
if (test4f(-6.0f,-3.0f) != 4.0f)
abort();
return 0;
}
| gpl-2.0 |
hikerockies/linux | net/mac80211/rc80211_minstrel_ht.c | 211 | 37604 | /*
* Copyright (C) 2010-2013 Felix Fietkau <nbd@openwrt.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/netdevice.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/debugfs.h>
#include <linux/random.h>
#include <linux/moduleparam.h>
#include <linux/ieee80211.h>
#include <net/mac80211.h>
#include "rate.h"
#include "rc80211_minstrel.h"
#include "rc80211_minstrel_ht.h"
#define AVG_PKT_SIZE 1200
/* Number of bits for an average sized packet */
#define MCS_NBITS (AVG_PKT_SIZE << 3)
/* Number of symbols for a packet with (bps) bits per symbol */
#define MCS_NSYMS(bps) DIV_ROUND_UP(MCS_NBITS, (bps))
/* Transmission time (nanoseconds) for a packet containing (syms) symbols */
#define MCS_SYMBOL_TIME(sgi, syms) \
(sgi ? \
((syms) * 18000 + 4000) / 5 : /* syms * 3.6 us */ \
((syms) * 1000) << 2 /* syms * 4 us */ \
)
/* Transmit duration for the raw data part of an average sized packet */
#define MCS_DURATION(streams, sgi, bps) MCS_SYMBOL_TIME(sgi, MCS_NSYMS((streams) * (bps)))
#define BW_20 0
#define BW_40 1
#define BW_80 2
/*
* Define group sort order: HT40 -> SGI -> #streams
*/
#define GROUP_IDX(_streams, _sgi, _ht40) \
MINSTREL_HT_GROUP_0 + \
MINSTREL_MAX_STREAMS * 2 * _ht40 + \
MINSTREL_MAX_STREAMS * _sgi + \
_streams - 1
/* MCS rate information for an MCS group */
#define MCS_GROUP(_streams, _sgi, _ht40) \
[GROUP_IDX(_streams, _sgi, _ht40)] = { \
.streams = _streams, \
.flags = \
IEEE80211_TX_RC_MCS | \
(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) | \
(_ht40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0), \
.duration = { \
MCS_DURATION(_streams, _sgi, _ht40 ? 54 : 26), \
MCS_DURATION(_streams, _sgi, _ht40 ? 108 : 52), \
MCS_DURATION(_streams, _sgi, _ht40 ? 162 : 78), \
MCS_DURATION(_streams, _sgi, _ht40 ? 216 : 104), \
MCS_DURATION(_streams, _sgi, _ht40 ? 324 : 156), \
MCS_DURATION(_streams, _sgi, _ht40 ? 432 : 208), \
MCS_DURATION(_streams, _sgi, _ht40 ? 486 : 234), \
MCS_DURATION(_streams, _sgi, _ht40 ? 540 : 260) \
} \
}
#define VHT_GROUP_IDX(_streams, _sgi, _bw) \
(MINSTREL_VHT_GROUP_0 + \
MINSTREL_MAX_STREAMS * 2 * (_bw) + \
MINSTREL_MAX_STREAMS * (_sgi) + \
(_streams) - 1)
#define BW2VBPS(_bw, r3, r2, r1) \
(_bw == BW_80 ? r3 : _bw == BW_40 ? r2 : r1)
#define VHT_GROUP(_streams, _sgi, _bw) \
[VHT_GROUP_IDX(_streams, _sgi, _bw)] = { \
.streams = _streams, \
.flags = \
IEEE80211_TX_RC_VHT_MCS | \
(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) | \
(_bw == BW_80 ? IEEE80211_TX_RC_80_MHZ_WIDTH : \
_bw == BW_40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0), \
.duration = { \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 117, 54, 26)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 234, 108, 52)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 351, 162, 78)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 468, 216, 104)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 702, 324, 156)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 936, 432, 208)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 1053, 486, 234)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 1170, 540, 260)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 1404, 648, 312)), \
MCS_DURATION(_streams, _sgi, \
BW2VBPS(_bw, 1560, 720, 346)) \
} \
}
#define CCK_DURATION(_bitrate, _short, _len) \
(1000 * (10 /* SIFS */ + \
(_short ? 72 + 24 : 144 + 48) + \
(8 * (_len + 4) * 10) / (_bitrate)))
#define CCK_ACK_DURATION(_bitrate, _short) \
(CCK_DURATION((_bitrate > 10 ? 20 : 10), false, 60) + \
CCK_DURATION(_bitrate, _short, AVG_PKT_SIZE))
#define CCK_DURATION_LIST(_short) \
CCK_ACK_DURATION(10, _short), \
CCK_ACK_DURATION(20, _short), \
CCK_ACK_DURATION(55, _short), \
CCK_ACK_DURATION(110, _short)
#define CCK_GROUP \
[MINSTREL_CCK_GROUP] = { \
.streams = 0, \
.flags = 0, \
.duration = { \
CCK_DURATION_LIST(false), \
CCK_DURATION_LIST(true) \
} \
}
#ifdef CONFIG_MAC80211_RC_MINSTREL_VHT
static bool minstrel_vht_only = true;
module_param(minstrel_vht_only, bool, 0644);
MODULE_PARM_DESC(minstrel_vht_only,
"Use only VHT rates when VHT is supported by sta.");
#endif
/*
* To enable sufficiently targeted rate sampling, MCS rates are divided into
* groups, based on the number of streams and flags (HT40, SGI) that they
* use.
*
* Sortorder has to be fixed for GROUP_IDX macro to be applicable:
* BW -> SGI -> #streams
*/
const struct mcs_group minstrel_mcs_groups[] = {
MCS_GROUP(1, 0, BW_20),
MCS_GROUP(2, 0, BW_20),
#if MINSTREL_MAX_STREAMS >= 3
MCS_GROUP(3, 0, BW_20),
#endif
MCS_GROUP(1, 1, BW_20),
MCS_GROUP(2, 1, BW_20),
#if MINSTREL_MAX_STREAMS >= 3
MCS_GROUP(3, 1, BW_20),
#endif
MCS_GROUP(1, 0, BW_40),
MCS_GROUP(2, 0, BW_40),
#if MINSTREL_MAX_STREAMS >= 3
MCS_GROUP(3, 0, BW_40),
#endif
MCS_GROUP(1, 1, BW_40),
MCS_GROUP(2, 1, BW_40),
#if MINSTREL_MAX_STREAMS >= 3
MCS_GROUP(3, 1, BW_40),
#endif
CCK_GROUP,
#ifdef CONFIG_MAC80211_RC_MINSTREL_VHT
VHT_GROUP(1, 0, BW_20),
VHT_GROUP(2, 0, BW_20),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 0, BW_20),
#endif
VHT_GROUP(1, 1, BW_20),
VHT_GROUP(2, 1, BW_20),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 1, BW_20),
#endif
VHT_GROUP(1, 0, BW_40),
VHT_GROUP(2, 0, BW_40),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 0, BW_40),
#endif
VHT_GROUP(1, 1, BW_40),
VHT_GROUP(2, 1, BW_40),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 1, BW_40),
#endif
VHT_GROUP(1, 0, BW_80),
VHT_GROUP(2, 0, BW_80),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 0, BW_80),
#endif
VHT_GROUP(1, 1, BW_80),
VHT_GROUP(2, 1, BW_80),
#if MINSTREL_MAX_STREAMS >= 3
VHT_GROUP(3, 1, BW_80),
#endif
#endif
};
static u8 sample_table[SAMPLE_COLUMNS][MCS_GROUP_RATES] __read_mostly;
static void
minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi);
/*
* Some VHT MCSes are invalid (when Ndbps / Nes is not an integer)
* e.g for MCS9@20MHzx1Nss: Ndbps=8x52*(5/6) Nes=1
*
* Returns the valid mcs map for struct minstrel_mcs_group_data.supported
*/
static u16
minstrel_get_valid_vht_rates(int bw, int nss, __le16 mcs_map)
{
u16 mask = 0;
if (bw == BW_20) {
if (nss != 3 && nss != 6)
mask = BIT(9);
} else if (bw == BW_80) {
if (nss == 3 || nss == 7)
mask = BIT(6);
else if (nss == 6)
mask = BIT(9);
} else {
WARN_ON(bw != BW_40);
}
switch ((le16_to_cpu(mcs_map) >> (2 * (nss - 1))) & 3) {
case IEEE80211_VHT_MCS_SUPPORT_0_7:
mask |= 0x300;
break;
case IEEE80211_VHT_MCS_SUPPORT_0_8:
mask |= 0x200;
break;
case IEEE80211_VHT_MCS_SUPPORT_0_9:
break;
default:
mask = 0x3ff;
}
return 0x3ff & ~mask;
}
/*
* Look up an MCS group index based on mac80211 rate information
*/
static int
minstrel_ht_get_group_idx(struct ieee80211_tx_rate *rate)
{
return GROUP_IDX((rate->idx / 8) + 1,
!!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
!!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH));
}
static int
minstrel_vht_get_group_idx(struct ieee80211_tx_rate *rate)
{
return VHT_GROUP_IDX(ieee80211_rate_get_vht_nss(rate),
!!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
!!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH) +
2*!!(rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH));
}
static struct minstrel_rate_stats *
minstrel_ht_get_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
struct ieee80211_tx_rate *rate)
{
int group, idx;
if (rate->flags & IEEE80211_TX_RC_MCS) {
group = minstrel_ht_get_group_idx(rate);
idx = rate->idx % 8;
} else if (rate->flags & IEEE80211_TX_RC_VHT_MCS) {
group = minstrel_vht_get_group_idx(rate);
idx = ieee80211_rate_get_vht_mcs(rate);
} else {
group = MINSTREL_CCK_GROUP;
for (idx = 0; idx < ARRAY_SIZE(mp->cck_rates); idx++)
if (rate->idx == mp->cck_rates[idx])
break;
/* short preamble */
if (!(mi->groups[group].supported & BIT(idx)))
idx += 4;
}
return &mi->groups[group].rates[idx];
}
static inline struct minstrel_rate_stats *
minstrel_get_ratestats(struct minstrel_ht_sta *mi, int index)
{
return &mi->groups[index / MCS_GROUP_RATES].rates[index % MCS_GROUP_RATES];
}
/*
* Recalculate success probabilities and counters for a rate using EWMA
*/
static void
minstrel_calc_rate_ewma(struct minstrel_rate_stats *mr)
{
if (unlikely(mr->attempts > 0)) {
mr->sample_skipped = 0;
mr->cur_prob = MINSTREL_FRAC(mr->success, mr->attempts);
if (!mr->att_hist)
mr->probability = mr->cur_prob;
else
mr->probability = minstrel_ewma(mr->probability,
mr->cur_prob, EWMA_LEVEL);
mr->att_hist += mr->attempts;
mr->succ_hist += mr->success;
} else {
mr->sample_skipped++;
}
mr->last_success = mr->success;
mr->last_attempts = mr->attempts;
mr->success = 0;
mr->attempts = 0;
}
/*
* Calculate throughput based on the average A-MPDU length, taking into account
* the expected number of retransmissions and their expected length
*/
static void
minstrel_ht_calc_tp(struct minstrel_ht_sta *mi, int group, int rate)
{
struct minstrel_rate_stats *mr;
unsigned int nsecs = 0;
unsigned int tp;
unsigned int prob;
mr = &mi->groups[group].rates[rate];
prob = mr->probability;
if (prob < MINSTREL_FRAC(1, 10)) {
mr->cur_tp = 0;
return;
}
/*
* For the throughput calculation, limit the probability value to 90% to
* account for collision related packet error rate fluctuation
*/
if (prob > MINSTREL_FRAC(9, 10))
prob = MINSTREL_FRAC(9, 10);
if (group != MINSTREL_CCK_GROUP)
nsecs = 1000 * mi->overhead / MINSTREL_TRUNC(mi->avg_ampdu_len);
nsecs += minstrel_mcs_groups[group].duration[rate];
/* prob is scaled - see MINSTREL_FRAC above */
tp = 1000000 * ((prob * 1000) / nsecs);
mr->cur_tp = MINSTREL_TRUNC(tp);
}
/*
* Find & sort topmost throughput rates
*
* If multiple rates provide equal throughput the sorting is based on their
* current success probability. Higher success probability is preferred among
* MCS groups, CCK rates do not provide aggregation and are therefore at last.
*/
static void
minstrel_ht_sort_best_tp_rates(struct minstrel_ht_sta *mi, u16 index,
u16 *tp_list)
{
int cur_group, cur_idx, cur_thr, cur_prob;
int tmp_group, tmp_idx, tmp_thr, tmp_prob;
int j = MAX_THR_RATES;
cur_group = index / MCS_GROUP_RATES;
cur_idx = index % MCS_GROUP_RATES;
cur_thr = mi->groups[cur_group].rates[cur_idx].cur_tp;
cur_prob = mi->groups[cur_group].rates[cur_idx].probability;
do {
tmp_group = tp_list[j - 1] / MCS_GROUP_RATES;
tmp_idx = tp_list[j - 1] % MCS_GROUP_RATES;
tmp_thr = mi->groups[tmp_group].rates[tmp_idx].cur_tp;
tmp_prob = mi->groups[tmp_group].rates[tmp_idx].probability;
if (cur_thr < tmp_thr ||
(cur_thr == tmp_thr && cur_prob <= tmp_prob))
break;
j--;
} while (j > 0);
if (j < MAX_THR_RATES - 1) {
memmove(&tp_list[j + 1], &tp_list[j], (sizeof(*tp_list) *
(MAX_THR_RATES - (j + 1))));
}
if (j < MAX_THR_RATES)
tp_list[j] = index;
}
/*
* Find and set the topmost probability rate per sta and per group
*/
static void
minstrel_ht_set_best_prob_rate(struct minstrel_ht_sta *mi, u16 index)
{
struct minstrel_mcs_group_data *mg;
struct minstrel_rate_stats *mr;
int tmp_group, tmp_idx, tmp_tp, tmp_prob, max_tp_group;
mg = &mi->groups[index / MCS_GROUP_RATES];
mr = &mg->rates[index % MCS_GROUP_RATES];
tmp_group = mi->max_prob_rate / MCS_GROUP_RATES;
tmp_idx = mi->max_prob_rate % MCS_GROUP_RATES;
tmp_tp = mi->groups[tmp_group].rates[tmp_idx].cur_tp;
tmp_prob = mi->groups[tmp_group].rates[tmp_idx].probability;
/* if max_tp_rate[0] is from MCS_GROUP max_prob_rate get selected from
* MCS_GROUP as well as CCK_GROUP rates do not allow aggregation */
max_tp_group = mi->max_tp_rate[0] / MCS_GROUP_RATES;
if((index / MCS_GROUP_RATES == MINSTREL_CCK_GROUP) &&
(max_tp_group != MINSTREL_CCK_GROUP))
return;
if (mr->probability > MINSTREL_FRAC(75, 100)) {
if (mr->cur_tp > tmp_tp)
mi->max_prob_rate = index;
if (mr->cur_tp > mg->rates[mg->max_group_prob_rate].cur_tp)
mg->max_group_prob_rate = index;
} else {
if (mr->probability > tmp_prob)
mi->max_prob_rate = index;
if (mr->probability > mg->rates[mg->max_group_prob_rate].probability)
mg->max_group_prob_rate = index;
}
}
/*
* Assign new rate set per sta and use CCK rates only if the fastest
* rate (max_tp_rate[0]) is from CCK group. This prohibits such sorted
* rate sets where MCS and CCK rates are mixed, because CCK rates can
* not use aggregation.
*/
static void
minstrel_ht_assign_best_tp_rates(struct minstrel_ht_sta *mi,
u16 tmp_mcs_tp_rate[MAX_THR_RATES],
u16 tmp_cck_tp_rate[MAX_THR_RATES])
{
unsigned int tmp_group, tmp_idx, tmp_cck_tp, tmp_mcs_tp;
int i;
tmp_group = tmp_cck_tp_rate[0] / MCS_GROUP_RATES;
tmp_idx = tmp_cck_tp_rate[0] % MCS_GROUP_RATES;
tmp_cck_tp = mi->groups[tmp_group].rates[tmp_idx].cur_tp;
tmp_group = tmp_mcs_tp_rate[0] / MCS_GROUP_RATES;
tmp_idx = tmp_mcs_tp_rate[0] % MCS_GROUP_RATES;
tmp_mcs_tp = mi->groups[tmp_group].rates[tmp_idx].cur_tp;
if (tmp_cck_tp > tmp_mcs_tp) {
for(i = 0; i < MAX_THR_RATES; i++) {
minstrel_ht_sort_best_tp_rates(mi, tmp_cck_tp_rate[i],
tmp_mcs_tp_rate);
}
}
}
/*
* Try to increase robustness of max_prob rate by decrease number of
* streams if possible.
*/
static inline void
minstrel_ht_prob_rate_reduce_streams(struct minstrel_ht_sta *mi)
{
struct minstrel_mcs_group_data *mg;
struct minstrel_rate_stats *mr;
int tmp_max_streams, group;
int tmp_tp = 0;
tmp_max_streams = minstrel_mcs_groups[mi->max_tp_rate[0] /
MCS_GROUP_RATES].streams;
for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
mg = &mi->groups[group];
if (!mg->supported || group == MINSTREL_CCK_GROUP)
continue;
mr = minstrel_get_ratestats(mi, mg->max_group_prob_rate);
if (tmp_tp < mr->cur_tp &&
(minstrel_mcs_groups[group].streams < tmp_max_streams)) {
mi->max_prob_rate = mg->max_group_prob_rate;
tmp_tp = mr->cur_tp;
}
}
}
/*
* Update rate statistics and select new primary rates
*
* Rules for rate selection:
* - max_prob_rate must use only one stream, as a tradeoff between delivery
* probability and throughput during strong fluctuations
* - as long as the max prob rate has a probability of more than 75%, pick
* higher throughput rates, even if the probablity is a bit lower
*/
static void
minstrel_ht_update_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
{
struct minstrel_mcs_group_data *mg;
struct minstrel_rate_stats *mr;
int group, i, j;
u16 tmp_mcs_tp_rate[MAX_THR_RATES], tmp_group_tp_rate[MAX_THR_RATES];
u16 tmp_cck_tp_rate[MAX_THR_RATES], index;
if (mi->ampdu_packets > 0) {
mi->avg_ampdu_len = minstrel_ewma(mi->avg_ampdu_len,
MINSTREL_FRAC(mi->ampdu_len, mi->ampdu_packets), EWMA_LEVEL);
mi->ampdu_len = 0;
mi->ampdu_packets = 0;
}
mi->sample_slow = 0;
mi->sample_count = 0;
/* Initialize global rate indexes */
for(j = 0; j < MAX_THR_RATES; j++){
tmp_mcs_tp_rate[j] = 0;
tmp_cck_tp_rate[j] = 0;
}
/* Find best rate sets within all MCS groups*/
for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
mg = &mi->groups[group];
if (!mg->supported)
continue;
mi->sample_count++;
/* (re)Initialize group rate indexes */
for(j = 0; j < MAX_THR_RATES; j++)
tmp_group_tp_rate[j] = group;
for (i = 0; i < MCS_GROUP_RATES; i++) {
if (!(mg->supported & BIT(i)))
continue;
index = MCS_GROUP_RATES * group + i;
mr = &mg->rates[i];
mr->retry_updated = false;
minstrel_calc_rate_ewma(mr);
minstrel_ht_calc_tp(mi, group, i);
if (!mr->cur_tp)
continue;
/* Find max throughput rate set */
if (group != MINSTREL_CCK_GROUP) {
minstrel_ht_sort_best_tp_rates(mi, index,
tmp_mcs_tp_rate);
} else if (group == MINSTREL_CCK_GROUP) {
minstrel_ht_sort_best_tp_rates(mi, index,
tmp_cck_tp_rate);
}
/* Find max throughput rate set within a group */
minstrel_ht_sort_best_tp_rates(mi, index,
tmp_group_tp_rate);
/* Find max probability rate per group and global */
minstrel_ht_set_best_prob_rate(mi, index);
}
memcpy(mg->max_group_tp_rate, tmp_group_tp_rate,
sizeof(mg->max_group_tp_rate));
}
/* Assign new rate set per sta */
minstrel_ht_assign_best_tp_rates(mi, tmp_mcs_tp_rate, tmp_cck_tp_rate);
memcpy(mi->max_tp_rate, tmp_mcs_tp_rate, sizeof(mi->max_tp_rate));
/* Try to increase robustness of max_prob_rate*/
minstrel_ht_prob_rate_reduce_streams(mi);
/* try to sample all available rates during each interval */
mi->sample_count *= 8;
#ifdef CONFIG_MAC80211_DEBUGFS
/* use fixed index if set */
if (mp->fixed_rate_idx != -1) {
for (i = 0; i < 4; i++)
mi->max_tp_rate[i] = mp->fixed_rate_idx;
mi->max_prob_rate = mp->fixed_rate_idx;
}
#endif
/* Reset update timer */
mi->stats_update = jiffies;
}
static bool
minstrel_ht_txstat_valid(struct minstrel_priv *mp, struct ieee80211_tx_rate *rate)
{
if (rate->idx < 0)
return false;
if (!rate->count)
return false;
if (rate->flags & IEEE80211_TX_RC_MCS ||
rate->flags & IEEE80211_TX_RC_VHT_MCS)
return true;
return rate->idx == mp->cck_rates[0] ||
rate->idx == mp->cck_rates[1] ||
rate->idx == mp->cck_rates[2] ||
rate->idx == mp->cck_rates[3];
}
static void
minstrel_next_sample_idx(struct minstrel_ht_sta *mi)
{
struct minstrel_mcs_group_data *mg;
for (;;) {
mi->sample_group++;
mi->sample_group %= ARRAY_SIZE(minstrel_mcs_groups);
mg = &mi->groups[mi->sample_group];
if (!mg->supported)
continue;
if (++mg->index >= MCS_GROUP_RATES) {
mg->index = 0;
if (++mg->column >= ARRAY_SIZE(sample_table))
mg->column = 0;
}
break;
}
}
static void
minstrel_downgrade_rate(struct minstrel_ht_sta *mi, u16 *idx, bool primary)
{
int group, orig_group;
orig_group = group = *idx / MCS_GROUP_RATES;
while (group > 0) {
group--;
if (!mi->groups[group].supported)
continue;
if (minstrel_mcs_groups[group].streams >
minstrel_mcs_groups[orig_group].streams)
continue;
if (primary)
*idx = mi->groups[group].max_group_tp_rate[0];
else
*idx = mi->groups[group].max_group_tp_rate[1];
break;
}
}
static void
minstrel_aggr_check(struct ieee80211_sta *pubsta, struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
u16 tid;
if (skb_get_queue_mapping(skb) == IEEE80211_AC_VO)
return;
if (unlikely(!ieee80211_is_data_qos(hdr->frame_control)))
return;
if (unlikely(skb->protocol == cpu_to_be16(ETH_P_PAE)))
return;
tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK;
if (likely(sta->ampdu_mlme.tid_tx[tid]))
return;
ieee80211_start_tx_ba_session(pubsta, tid, 5000);
}
static void
minstrel_ht_tx_status(void *priv, struct ieee80211_supported_band *sband,
struct ieee80211_sta *sta, void *priv_sta,
struct ieee80211_tx_info *info)
{
struct minstrel_ht_sta_priv *msp = priv_sta;
struct minstrel_ht_sta *mi = &msp->ht;
struct ieee80211_tx_rate *ar = info->status.rates;
struct minstrel_rate_stats *rate, *rate2;
struct minstrel_priv *mp = priv;
bool last, update = false;
int i;
if (!msp->is_ht)
return mac80211_minstrel.tx_status_noskb(priv, sband, sta,
&msp->legacy, info);
/* This packet was aggregated but doesn't carry status info */
if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
!(info->flags & IEEE80211_TX_STAT_AMPDU))
return;
if (!(info->flags & IEEE80211_TX_STAT_AMPDU)) {
info->status.ampdu_ack_len =
(info->flags & IEEE80211_TX_STAT_ACK ? 1 : 0);
info->status.ampdu_len = 1;
}
mi->ampdu_packets++;
mi->ampdu_len += info->status.ampdu_len;
if (!mi->sample_wait && !mi->sample_tries && mi->sample_count > 0) {
mi->sample_wait = 16 + 2 * MINSTREL_TRUNC(mi->avg_ampdu_len);
mi->sample_tries = 1;
mi->sample_count--;
}
if (info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE)
mi->sample_packets += info->status.ampdu_len;
last = !minstrel_ht_txstat_valid(mp, &ar[0]);
for (i = 0; !last; i++) {
last = (i == IEEE80211_TX_MAX_RATES - 1) ||
!minstrel_ht_txstat_valid(mp, &ar[i + 1]);
rate = minstrel_ht_get_stats(mp, mi, &ar[i]);
if (last)
rate->success += info->status.ampdu_ack_len;
rate->attempts += ar[i].count * info->status.ampdu_len;
}
/*
* check for sudden death of spatial multiplexing,
* downgrade to a lower number of streams if necessary.
*/
rate = minstrel_get_ratestats(mi, mi->max_tp_rate[0]);
if (rate->attempts > 30 &&
MINSTREL_FRAC(rate->success, rate->attempts) <
MINSTREL_FRAC(20, 100)) {
minstrel_downgrade_rate(mi, &mi->max_tp_rate[0], true);
update = true;
}
rate2 = minstrel_get_ratestats(mi, mi->max_tp_rate[1]);
if (rate2->attempts > 30 &&
MINSTREL_FRAC(rate2->success, rate2->attempts) <
MINSTREL_FRAC(20, 100)) {
minstrel_downgrade_rate(mi, &mi->max_tp_rate[1], false);
update = true;
}
if (time_after(jiffies, mi->stats_update + (mp->update_interval / 2 * HZ) / 1000)) {
update = true;
minstrel_ht_update_stats(mp, mi);
}
if (update)
minstrel_ht_update_rates(mp, mi);
}
static void
minstrel_calc_retransmit(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
int index)
{
struct minstrel_rate_stats *mr;
const struct mcs_group *group;
unsigned int tx_time, tx_time_rtscts, tx_time_data;
unsigned int cw = mp->cw_min;
unsigned int ctime = 0;
unsigned int t_slot = 9; /* FIXME */
unsigned int ampdu_len = MINSTREL_TRUNC(mi->avg_ampdu_len);
unsigned int overhead = 0, overhead_rtscts = 0;
mr = minstrel_get_ratestats(mi, index);
if (mr->probability < MINSTREL_FRAC(1, 10)) {
mr->retry_count = 1;
mr->retry_count_rtscts = 1;
return;
}
mr->retry_count = 2;
mr->retry_count_rtscts = 2;
mr->retry_updated = true;
group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
tx_time_data = group->duration[index % MCS_GROUP_RATES] * ampdu_len / 1000;
/* Contention time for first 2 tries */
ctime = (t_slot * cw) >> 1;
cw = min((cw << 1) | 1, mp->cw_max);
ctime += (t_slot * cw) >> 1;
cw = min((cw << 1) | 1, mp->cw_max);
if (index / MCS_GROUP_RATES != MINSTREL_CCK_GROUP) {
overhead = mi->overhead;
overhead_rtscts = mi->overhead_rtscts;
}
/* Total TX time for data and Contention after first 2 tries */
tx_time = ctime + 2 * (overhead + tx_time_data);
tx_time_rtscts = ctime + 2 * (overhead_rtscts + tx_time_data);
/* See how many more tries we can fit inside segment size */
do {
/* Contention time for this try */
ctime = (t_slot * cw) >> 1;
cw = min((cw << 1) | 1, mp->cw_max);
/* Total TX time after this try */
tx_time += ctime + overhead + tx_time_data;
tx_time_rtscts += ctime + overhead_rtscts + tx_time_data;
if (tx_time_rtscts < mp->segment_size)
mr->retry_count_rtscts++;
} while ((tx_time < mp->segment_size) &&
(++mr->retry_count < mp->max_retry));
}
static void
minstrel_ht_set_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
struct ieee80211_sta_rates *ratetbl, int offset, int index)
{
const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
struct minstrel_rate_stats *mr;
u8 idx;
u16 flags = group->flags;
mr = minstrel_get_ratestats(mi, index);
if (!mr->retry_updated)
minstrel_calc_retransmit(mp, mi, index);
if (mr->probability < MINSTREL_FRAC(20, 100) || !mr->retry_count) {
ratetbl->rate[offset].count = 2;
ratetbl->rate[offset].count_rts = 2;
ratetbl->rate[offset].count_cts = 2;
} else {
ratetbl->rate[offset].count = mr->retry_count;
ratetbl->rate[offset].count_cts = mr->retry_count;
ratetbl->rate[offset].count_rts = mr->retry_count_rtscts;
}
if (index / MCS_GROUP_RATES == MINSTREL_CCK_GROUP)
idx = mp->cck_rates[index % ARRAY_SIZE(mp->cck_rates)];
else if (flags & IEEE80211_TX_RC_VHT_MCS)
idx = ((group->streams - 1) << 4) |
((index % MCS_GROUP_RATES) & 0xF);
else
idx = index % MCS_GROUP_RATES + (group->streams - 1) * 8;
if (offset > 0) {
ratetbl->rate[offset].count = ratetbl->rate[offset].count_rts;
flags |= IEEE80211_TX_RC_USE_RTS_CTS;
}
ratetbl->rate[offset].idx = idx;
ratetbl->rate[offset].flags = flags;
}
static void
minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
{
struct ieee80211_sta_rates *rates;
int i = 0;
rates = kzalloc(sizeof(*rates), GFP_ATOMIC);
if (!rates)
return;
/* Start with max_tp_rate[0] */
minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_tp_rate[0]);
if (mp->hw->max_rates >= 3) {
/* At least 3 tx rates supported, use max_tp_rate[1] next */
minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_tp_rate[1]);
}
if (mp->hw->max_rates >= 2) {
/*
* At least 2 tx rates supported, use max_prob_rate next */
minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_prob_rate);
}
rates->rate[i].idx = -1;
rate_control_set_rates(mp->hw, mi->sta, rates);
}
static inline int
minstrel_get_duration(int index)
{
const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
return group->duration[index % MCS_GROUP_RATES];
}
static int
minstrel_get_sample_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
{
struct minstrel_rate_stats *mr;
struct minstrel_mcs_group_data *mg;
unsigned int sample_dur, sample_group, cur_max_tp_streams;
int sample_idx = 0;
if (mi->sample_wait > 0) {
mi->sample_wait--;
return -1;
}
if (!mi->sample_tries)
return -1;
sample_group = mi->sample_group;
mg = &mi->groups[sample_group];
sample_idx = sample_table[mg->column][mg->index];
minstrel_next_sample_idx(mi);
if (!(mg->supported & BIT(sample_idx)))
return -1;
mr = &mg->rates[sample_idx];
sample_idx += sample_group * MCS_GROUP_RATES;
/*
* Sampling might add some overhead (RTS, no aggregation)
* to the frame. Hence, don't use sampling for the currently
* used rates.
*/
if (sample_idx == mi->max_tp_rate[0] ||
sample_idx == mi->max_tp_rate[1] ||
sample_idx == mi->max_prob_rate)
return -1;
/*
* Do not sample if the probability is already higher than 95%
* to avoid wasting airtime.
*/
if (mr->probability > MINSTREL_FRAC(95, 100))
return -1;
/*
* Make sure that lower rates get sampled only occasionally,
* if the link is working perfectly.
*/
cur_max_tp_streams = minstrel_mcs_groups[mi->max_tp_rate[0] /
MCS_GROUP_RATES].streams;
sample_dur = minstrel_get_duration(sample_idx);
if (sample_dur >= minstrel_get_duration(mi->max_tp_rate[1]) &&
(cur_max_tp_streams - 1 <
minstrel_mcs_groups[sample_group].streams ||
sample_dur >= minstrel_get_duration(mi->max_prob_rate))) {
if (mr->sample_skipped < 20)
return -1;
if (mi->sample_slow++ > 2)
return -1;
}
mi->sample_tries--;
return sample_idx;
}
static void
minstrel_ht_check_cck_shortpreamble(struct minstrel_priv *mp,
struct minstrel_ht_sta *mi, bool val)
{
u8 supported = mi->groups[MINSTREL_CCK_GROUP].supported;
if (!supported || !mi->cck_supported_short)
return;
if (supported & (mi->cck_supported_short << (val * 4)))
return;
supported ^= mi->cck_supported_short | (mi->cck_supported_short << 4);
mi->groups[MINSTREL_CCK_GROUP].supported = supported;
}
static void
minstrel_ht_get_rate(void *priv, struct ieee80211_sta *sta, void *priv_sta,
struct ieee80211_tx_rate_control *txrc)
{
const struct mcs_group *sample_group;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(txrc->skb);
struct ieee80211_tx_rate *rate = &info->status.rates[0];
struct minstrel_ht_sta_priv *msp = priv_sta;
struct minstrel_ht_sta *mi = &msp->ht;
struct minstrel_priv *mp = priv;
int sample_idx;
if (rate_control_send_low(sta, priv_sta, txrc))
return;
if (!msp->is_ht)
return mac80211_minstrel.get_rate(priv, sta, &msp->legacy, txrc);
if (!(info->flags & IEEE80211_TX_CTL_AMPDU) &&
mi->max_prob_rate / MCS_GROUP_RATES != MINSTREL_CCK_GROUP)
minstrel_aggr_check(sta, txrc->skb);
info->flags |= mi->tx_flags;
minstrel_ht_check_cck_shortpreamble(mp, mi, txrc->short_preamble);
#ifdef CONFIG_MAC80211_DEBUGFS
if (mp->fixed_rate_idx != -1)
return;
#endif
/* Don't use EAPOL frames for sampling on non-mrr hw */
if (mp->hw->max_rates == 1 &&
(info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO))
sample_idx = -1;
else
sample_idx = minstrel_get_sample_rate(mp, mi);
mi->total_packets++;
/* wraparound */
if (mi->total_packets == ~0) {
mi->total_packets = 0;
mi->sample_packets = 0;
}
if (sample_idx < 0)
return;
sample_group = &minstrel_mcs_groups[sample_idx / MCS_GROUP_RATES];
info->flags |= IEEE80211_TX_CTL_RATE_CTRL_PROBE;
rate->count = 1;
if (sample_idx / MCS_GROUP_RATES == MINSTREL_CCK_GROUP) {
int idx = sample_idx % ARRAY_SIZE(mp->cck_rates);
rate->idx = mp->cck_rates[idx];
} else if (sample_group->flags & IEEE80211_TX_RC_VHT_MCS) {
ieee80211_rate_set_vht(rate, sample_idx % MCS_GROUP_RATES,
sample_group->streams);
} else {
rate->idx = sample_idx % MCS_GROUP_RATES +
(sample_group->streams - 1) * 8;
}
rate->flags = sample_group->flags;
}
static void
minstrel_ht_update_cck(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
struct ieee80211_supported_band *sband,
struct ieee80211_sta *sta)
{
int i;
if (sband->band != IEEE80211_BAND_2GHZ)
return;
if (!(mp->hw->flags & IEEE80211_HW_SUPPORTS_HT_CCK_RATES))
return;
mi->cck_supported = 0;
mi->cck_supported_short = 0;
for (i = 0; i < 4; i++) {
if (!rate_supported(sta, sband->band, mp->cck_rates[i]))
continue;
mi->cck_supported |= BIT(i);
if (sband->bitrates[i].flags & IEEE80211_RATE_SHORT_PREAMBLE)
mi->cck_supported_short |= BIT(i);
}
mi->groups[MINSTREL_CCK_GROUP].supported = mi->cck_supported;
}
static void
minstrel_ht_update_caps(void *priv, struct ieee80211_supported_band *sband,
struct cfg80211_chan_def *chandef,
struct ieee80211_sta *sta, void *priv_sta)
{
struct minstrel_priv *mp = priv;
struct minstrel_ht_sta_priv *msp = priv_sta;
struct minstrel_ht_sta *mi = &msp->ht;
struct ieee80211_mcs_info *mcs = &sta->ht_cap.mcs;
u16 sta_cap = sta->ht_cap.cap;
struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
int use_vht;
int n_supported = 0;
int ack_dur;
int stbc;
int i;
/* fall back to the old minstrel for legacy stations */
if (!sta->ht_cap.ht_supported)
goto use_legacy;
BUILD_BUG_ON(ARRAY_SIZE(minstrel_mcs_groups) != MINSTREL_GROUPS_NB);
#ifdef CONFIG_MAC80211_RC_MINSTREL_VHT
if (vht_cap->vht_supported)
use_vht = vht_cap->vht_mcs.tx_mcs_map != cpu_to_le16(~0);
else
#endif
use_vht = 0;
msp->is_ht = true;
memset(mi, 0, sizeof(*mi));
mi->sta = sta;
mi->stats_update = jiffies;
ack_dur = ieee80211_frame_duration(sband->band, 10, 60, 1, 1, 0);
mi->overhead = ieee80211_frame_duration(sband->band, 0, 60, 1, 1, 0);
mi->overhead += ack_dur;
mi->overhead_rtscts = mi->overhead + 2 * ack_dur;
mi->avg_ampdu_len = MINSTREL_FRAC(1, 1);
/* When using MRR, sample more on the first attempt, without delay */
if (mp->has_mrr) {
mi->sample_count = 16;
mi->sample_wait = 0;
} else {
mi->sample_count = 8;
mi->sample_wait = 8;
}
mi->sample_tries = 4;
/* TODO tx_flags for vht - ATM the RC API is not fine-grained enough */
if (!use_vht) {
stbc = (sta_cap & IEEE80211_HT_CAP_RX_STBC) >>
IEEE80211_HT_CAP_RX_STBC_SHIFT;
mi->tx_flags |= stbc << IEEE80211_TX_CTL_STBC_SHIFT;
if (sta_cap & IEEE80211_HT_CAP_LDPC_CODING)
mi->tx_flags |= IEEE80211_TX_CTL_LDPC;
}
for (i = 0; i < ARRAY_SIZE(mi->groups); i++) {
u32 gflags = minstrel_mcs_groups[i].flags;
int bw, nss;
mi->groups[i].supported = 0;
if (i == MINSTREL_CCK_GROUP) {
minstrel_ht_update_cck(mp, mi, sband, sta);
continue;
}
if (gflags & IEEE80211_TX_RC_SHORT_GI) {
if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH) {
if (!(sta_cap & IEEE80211_HT_CAP_SGI_40))
continue;
} else {
if (!(sta_cap & IEEE80211_HT_CAP_SGI_20))
continue;
}
}
if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH &&
sta->bandwidth < IEEE80211_STA_RX_BW_40)
continue;
nss = minstrel_mcs_groups[i].streams;
/* Mark MCS > 7 as unsupported if STA is in static SMPS mode */
if (sta->smps_mode == IEEE80211_SMPS_STATIC && nss > 1)
continue;
/* HT rate */
if (gflags & IEEE80211_TX_RC_MCS) {
#ifdef CONFIG_MAC80211_RC_MINSTREL_VHT
if (use_vht && minstrel_vht_only)
continue;
#endif
mi->groups[i].supported = mcs->rx_mask[nss - 1];
if (mi->groups[i].supported)
n_supported++;
continue;
}
/* VHT rate */
if (!vht_cap->vht_supported ||
WARN_ON(!(gflags & IEEE80211_TX_RC_VHT_MCS)) ||
WARN_ON(gflags & IEEE80211_TX_RC_160_MHZ_WIDTH))
continue;
if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH) {
if (sta->bandwidth < IEEE80211_STA_RX_BW_80 ||
((gflags & IEEE80211_TX_RC_SHORT_GI) &&
!(vht_cap->cap & IEEE80211_VHT_CAP_SHORT_GI_80))) {
continue;
}
}
if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH)
bw = BW_40;
else if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH)
bw = BW_80;
else
bw = BW_20;
mi->groups[i].supported = minstrel_get_valid_vht_rates(bw, nss,
vht_cap->vht_mcs.tx_mcs_map);
if (mi->groups[i].supported)
n_supported++;
}
if (!n_supported)
goto use_legacy;
/* create an initial rate table with the lowest supported rates */
minstrel_ht_update_stats(mp, mi);
minstrel_ht_update_rates(mp, mi);
return;
use_legacy:
msp->is_ht = false;
memset(&msp->legacy, 0, sizeof(msp->legacy));
msp->legacy.r = msp->ratelist;
msp->legacy.sample_table = msp->sample_table;
return mac80211_minstrel.rate_init(priv, sband, chandef, sta,
&msp->legacy);
}
static void
minstrel_ht_rate_init(void *priv, struct ieee80211_supported_band *sband,
struct cfg80211_chan_def *chandef,
struct ieee80211_sta *sta, void *priv_sta)
{
minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
}
static void
minstrel_ht_rate_update(void *priv, struct ieee80211_supported_band *sband,
struct cfg80211_chan_def *chandef,
struct ieee80211_sta *sta, void *priv_sta,
u32 changed)
{
minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
}
static void *
minstrel_ht_alloc_sta(void *priv, struct ieee80211_sta *sta, gfp_t gfp)
{
struct ieee80211_supported_band *sband;
struct minstrel_ht_sta_priv *msp;
struct minstrel_priv *mp = priv;
struct ieee80211_hw *hw = mp->hw;
int max_rates = 0;
int i;
for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
sband = hw->wiphy->bands[i];
if (sband && sband->n_bitrates > max_rates)
max_rates = sband->n_bitrates;
}
msp = kzalloc(sizeof(*msp), gfp);
if (!msp)
return NULL;
msp->ratelist = kzalloc(sizeof(struct minstrel_rate) * max_rates, gfp);
if (!msp->ratelist)
goto error;
msp->sample_table = kmalloc(SAMPLE_COLUMNS * max_rates, gfp);
if (!msp->sample_table)
goto error1;
return msp;
error1:
kfree(msp->ratelist);
error:
kfree(msp);
return NULL;
}
static void
minstrel_ht_free_sta(void *priv, struct ieee80211_sta *sta, void *priv_sta)
{
struct minstrel_ht_sta_priv *msp = priv_sta;
kfree(msp->sample_table);
kfree(msp->ratelist);
kfree(msp);
}
static void *
minstrel_ht_alloc(struct ieee80211_hw *hw, struct dentry *debugfsdir)
{
return mac80211_minstrel.alloc(hw, debugfsdir);
}
static void
minstrel_ht_free(void *priv)
{
mac80211_minstrel.free(priv);
}
static u32 minstrel_ht_get_expected_throughput(void *priv_sta)
{
struct minstrel_ht_sta_priv *msp = priv_sta;
struct minstrel_ht_sta *mi = &msp->ht;
int i, j;
if (!msp->is_ht)
return mac80211_minstrel.get_expected_throughput(priv_sta);
i = mi->max_tp_rate[0] / MCS_GROUP_RATES;
j = mi->max_tp_rate[0] % MCS_GROUP_RATES;
/* convert cur_tp from pkt per second in kbps */
return mi->groups[i].rates[j].cur_tp * AVG_PKT_SIZE * 8 / 1024;
}
static const struct rate_control_ops mac80211_minstrel_ht = {
.name = "minstrel_ht",
.tx_status_noskb = minstrel_ht_tx_status,
.get_rate = minstrel_ht_get_rate,
.rate_init = minstrel_ht_rate_init,
.rate_update = minstrel_ht_rate_update,
.alloc_sta = minstrel_ht_alloc_sta,
.free_sta = minstrel_ht_free_sta,
.alloc = minstrel_ht_alloc,
.free = minstrel_ht_free,
#ifdef CONFIG_MAC80211_DEBUGFS
.add_sta_debugfs = minstrel_ht_add_sta_debugfs,
.remove_sta_debugfs = minstrel_ht_remove_sta_debugfs,
#endif
.get_expected_throughput = minstrel_ht_get_expected_throughput,
};
static void __init init_sample_table(void)
{
int col, i, new_idx;
u8 rnd[MCS_GROUP_RATES];
memset(sample_table, 0xff, sizeof(sample_table));
for (col = 0; col < SAMPLE_COLUMNS; col++) {
prandom_bytes(rnd, sizeof(rnd));
for (i = 0; i < MCS_GROUP_RATES; i++) {
new_idx = (i + rnd[i]) % MCS_GROUP_RATES;
while (sample_table[col][new_idx] != 0xff)
new_idx = (new_idx + 1) % MCS_GROUP_RATES;
sample_table[col][new_idx] = i;
}
}
}
int __init
rc80211_minstrel_ht_init(void)
{
init_sample_table();
return ieee80211_rate_control_register(&mac80211_minstrel_ht);
}
void
rc80211_minstrel_ht_exit(void)
{
ieee80211_rate_control_unregister(&mac80211_minstrel_ht);
}
| gpl-2.0 |
RodolfoSilva/linux | drivers/scsi/cxlflash/superpipe.c | 211 | 57798 | /*
* CXL Flash Device Driver
*
* Written by: Manoj N. Kumar <manoj@linux.vnet.ibm.com>, IBM Corporation
* Matthew R. Ochs <mrochs@linux.vnet.ibm.com>, IBM Corporation
*
* Copyright (C) 2015 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.
*/
#include <linux/delay.h>
#include <linux/file.h>
#include <linux/syscalls.h>
#include <misc/cxl.h>
#include <asm/unaligned.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <uapi/scsi/cxlflash_ioctl.h>
#include "sislite.h"
#include "common.h"
#include "vlun.h"
#include "superpipe.h"
struct cxlflash_global global;
/**
* marshal_rele_to_resize() - translate release to resize structure
* @rele: Source structure from which to translate/copy.
* @resize: Destination structure for the translate/copy.
*/
static void marshal_rele_to_resize(struct dk_cxlflash_release *release,
struct dk_cxlflash_resize *resize)
{
resize->hdr = release->hdr;
resize->context_id = release->context_id;
resize->rsrc_handle = release->rsrc_handle;
}
/**
* marshal_det_to_rele() - translate detach to release structure
* @detach: Destination structure for the translate/copy.
* @rele: Source structure from which to translate/copy.
*/
static void marshal_det_to_rele(struct dk_cxlflash_detach *detach,
struct dk_cxlflash_release *release)
{
release->hdr = detach->hdr;
release->context_id = detach->context_id;
}
/**
* cxlflash_free_errpage() - frees resources associated with global error page
*/
void cxlflash_free_errpage(void)
{
mutex_lock(&global.mutex);
if (global.err_page) {
__free_page(global.err_page);
global.err_page = NULL;
}
mutex_unlock(&global.mutex);
}
/**
* cxlflash_stop_term_user_contexts() - stops/terminates known user contexts
* @cfg: Internal structure associated with the host.
*
* When the host needs to go down, all users must be quiesced and their
* memory freed. This is accomplished by putting the contexts in error
* state which will notify the user and let them 'drive' the tear-down.
* Meanwhile, this routine camps until all user contexts have been removed.
*/
void cxlflash_stop_term_user_contexts(struct cxlflash_cfg *cfg)
{
struct device *dev = &cfg->dev->dev;
int i, found;
cxlflash_mark_contexts_error(cfg);
while (true) {
found = false;
for (i = 0; i < MAX_CONTEXT; i++)
if (cfg->ctx_tbl[i]) {
found = true;
break;
}
if (!found && list_empty(&cfg->ctx_err_recovery))
return;
dev_dbg(dev, "%s: Wait for user contexts to quiesce...\n",
__func__);
wake_up_all(&cfg->limbo_waitq);
ssleep(1);
}
}
/**
* find_error_context() - locates a context by cookie on the error recovery list
* @cfg: Internal structure associated with the host.
* @rctxid: Desired context by id.
* @file: Desired context by file.
*
* Return: Found context on success, NULL on failure
*/
static struct ctx_info *find_error_context(struct cxlflash_cfg *cfg, u64 rctxid,
struct file *file)
{
struct ctx_info *ctxi;
list_for_each_entry(ctxi, &cfg->ctx_err_recovery, list)
if ((ctxi->ctxid == rctxid) || (ctxi->file == file))
return ctxi;
return NULL;
}
/**
* get_context() - obtains a validated and locked context reference
* @cfg: Internal structure associated with the host.
* @rctxid: Desired context (raw, un-decoded format).
* @arg: LUN information or file associated with request.
* @ctx_ctrl: Control information to 'steer' desired lookup.
*
* NOTE: despite the name pid, in linux, current->pid actually refers
* to the lightweight process id (tid) and can change if the process is
* multi threaded. The tgid remains constant for the process and only changes
* when the process of fork. For all intents and purposes, think of tgid
* as a pid in the traditional sense.
*
* Return: Validated context on success, NULL on failure
*/
struct ctx_info *get_context(struct cxlflash_cfg *cfg, u64 rctxid,
void *arg, enum ctx_ctrl ctx_ctrl)
{
struct device *dev = &cfg->dev->dev;
struct ctx_info *ctxi = NULL;
struct lun_access *lun_access = NULL;
struct file *file = NULL;
struct llun_info *lli = arg;
u64 ctxid = DECODE_CTXID(rctxid);
int rc;
pid_t pid = current->tgid, ctxpid = 0;
if (ctx_ctrl & CTX_CTRL_FILE) {
lli = NULL;
file = (struct file *)arg;
}
if (ctx_ctrl & CTX_CTRL_CLONE)
pid = current->parent->tgid;
if (likely(ctxid < MAX_CONTEXT)) {
while (true) {
rc = mutex_lock_interruptible(&cfg->ctx_tbl_list_mutex);
if (rc)
goto out;
ctxi = cfg->ctx_tbl[ctxid];
if (ctxi)
if ((file && (ctxi->file != file)) ||
(!file && (ctxi->ctxid != rctxid)))
ctxi = NULL;
if ((ctx_ctrl & CTX_CTRL_ERR) ||
(!ctxi && (ctx_ctrl & CTX_CTRL_ERR_FALLBACK)))
ctxi = find_error_context(cfg, rctxid, file);
if (!ctxi) {
mutex_unlock(&cfg->ctx_tbl_list_mutex);
goto out;
}
/*
* Need to acquire ownership of the context while still
* under the table/list lock to serialize with a remove
* thread. Use the 'try' to avoid stalling the
* table/list lock for a single context.
*
* Note that the lock order is:
*
* cfg->ctx_tbl_list_mutex -> ctxi->mutex
*
* Therefore release ctx_tbl_list_mutex before retrying.
*/
rc = mutex_trylock(&ctxi->mutex);
mutex_unlock(&cfg->ctx_tbl_list_mutex);
if (rc)
break; /* got the context's lock! */
}
if (ctxi->unavail)
goto denied;
ctxpid = ctxi->pid;
if (likely(!(ctx_ctrl & CTX_CTRL_NOPID)))
if (pid != ctxpid)
goto denied;
if (lli) {
list_for_each_entry(lun_access, &ctxi->luns, list)
if (lun_access->lli == lli)
goto out;
goto denied;
}
}
out:
dev_dbg(dev, "%s: rctxid=%016llX ctxinfo=%p ctxpid=%u pid=%u "
"ctx_ctrl=%u\n", __func__, rctxid, ctxi, ctxpid, pid,
ctx_ctrl);
return ctxi;
denied:
mutex_unlock(&ctxi->mutex);
ctxi = NULL;
goto out;
}
/**
* put_context() - release a context that was retrieved from get_context()
* @ctxi: Context to release.
*
* For now, releasing the context equates to unlocking it's mutex.
*/
void put_context(struct ctx_info *ctxi)
{
mutex_unlock(&ctxi->mutex);
}
/**
* afu_attach() - attach a context to the AFU
* @cfg: Internal structure associated with the host.
* @ctxi: Context to attach.
*
* Upon setting the context capabilities, they must be confirmed with
* a read back operation as the context might have been closed since
* the mailbox was unlocked. When this occurs, registration is failed.
*
* Return: 0 on success, -errno on failure
*/
static int afu_attach(struct cxlflash_cfg *cfg, struct ctx_info *ctxi)
{
struct device *dev = &cfg->dev->dev;
struct afu *afu = cfg->afu;
struct sisl_ctrl_map *ctrl_map = ctxi->ctrl_map;
int rc = 0;
u64 val;
/* Unlock cap and restrict user to read/write cmds in translated mode */
readq_be(&ctrl_map->mbox_r);
val = (SISL_CTX_CAP_READ_CMD | SISL_CTX_CAP_WRITE_CMD);
writeq_be(val, &ctrl_map->ctx_cap);
val = readq_be(&ctrl_map->ctx_cap);
if (val != (SISL_CTX_CAP_READ_CMD | SISL_CTX_CAP_WRITE_CMD)) {
dev_err(dev, "%s: ctx may be closed val=%016llX\n",
__func__, val);
rc = -EAGAIN;
goto out;
}
/* Set up MMIO registers pointing to the RHT */
writeq_be((u64)ctxi->rht_start, &ctrl_map->rht_start);
val = SISL_RHT_CNT_ID((u64)MAX_RHT_PER_CONTEXT, (u64)(afu->ctx_hndl));
writeq_be(val, &ctrl_map->rht_cnt_id);
out:
dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
return rc;
}
/**
* read_cap16() - issues a SCSI READ_CAP16 command
* @sdev: SCSI device associated with LUN.
* @lli: LUN destined for capacity request.
*
* Return: 0 on success, -errno on failure
*/
static int read_cap16(struct scsi_device *sdev, struct llun_info *lli)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct glun_info *gli = lli->parent;
u8 *cmd_buf = NULL;
u8 *scsi_cmd = NULL;
u8 *sense_buf = NULL;
int rc = 0;
int result = 0;
int retry_cnt = 0;
u32 tout = (MC_DISCOVERY_TIMEOUT * HZ);
retry:
cmd_buf = kzalloc(CMD_BUFSIZE, GFP_KERNEL);
scsi_cmd = kzalloc(MAX_COMMAND_SIZE, GFP_KERNEL);
sense_buf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
if (unlikely(!cmd_buf || !scsi_cmd || !sense_buf)) {
rc = -ENOMEM;
goto out;
}
scsi_cmd[0] = SERVICE_ACTION_IN_16; /* read cap(16) */
scsi_cmd[1] = SAI_READ_CAPACITY_16; /* service action */
put_unaligned_be32(CMD_BUFSIZE, &scsi_cmd[10]);
dev_dbg(dev, "%s: %ssending cmd(0x%x)\n", __func__,
retry_cnt ? "re" : "", scsi_cmd[0]);
result = scsi_execute(sdev, scsi_cmd, DMA_FROM_DEVICE, cmd_buf,
CMD_BUFSIZE, sense_buf, tout, 5, 0, NULL);
if (driver_byte(result) == DRIVER_SENSE) {
result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
if (result & SAM_STAT_CHECK_CONDITION) {
struct scsi_sense_hdr sshdr;
scsi_normalize_sense(sense_buf, SCSI_SENSE_BUFFERSIZE,
&sshdr);
switch (sshdr.sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
/* fall through */
case NOT_READY:
result &= ~SAM_STAT_CHECK_CONDITION;
break;
case UNIT_ATTENTION:
switch (sshdr.asc) {
case 0x29: /* Power on Reset or Device Reset */
/* fall through */
case 0x2A: /* Device capacity changed */
case 0x3F: /* Report LUNs changed */
/* Retry the command once more */
if (retry_cnt++ < 1) {
kfree(cmd_buf);
kfree(scsi_cmd);
kfree(sense_buf);
goto retry;
}
}
break;
default:
break;
}
}
}
if (result) {
dev_err(dev, "%s: command failed, result=0x%x\n",
__func__, result);
rc = -EIO;
goto out;
}
/*
* Read cap was successful, grab values from the buffer;
* note that we don't need to worry about unaligned access
* as the buffer is allocated on an aligned boundary.
*/
mutex_lock(&gli->mutex);
gli->max_lba = be64_to_cpu(*((u64 *)&cmd_buf[0]));
gli->blk_len = be32_to_cpu(*((u32 *)&cmd_buf[8]));
mutex_unlock(&gli->mutex);
out:
kfree(cmd_buf);
kfree(scsi_cmd);
kfree(sense_buf);
dev_dbg(dev, "%s: maxlba=%lld blklen=%d rc=%d\n",
__func__, gli->max_lba, gli->blk_len, rc);
return rc;
}
/**
* get_rhte() - obtains validated resource handle table entry reference
* @ctxi: Context owning the resource handle.
* @rhndl: Resource handle associated with entry.
* @lli: LUN associated with request.
*
* Return: Validated RHTE on success, NULL on failure
*/
struct sisl_rht_entry *get_rhte(struct ctx_info *ctxi, res_hndl_t rhndl,
struct llun_info *lli)
{
struct sisl_rht_entry *rhte = NULL;
if (unlikely(!ctxi->rht_start)) {
pr_debug("%s: Context does not have allocated RHT!\n",
__func__);
goto out;
}
if (unlikely(rhndl >= MAX_RHT_PER_CONTEXT)) {
pr_debug("%s: Bad resource handle! (%d)\n", __func__, rhndl);
goto out;
}
if (unlikely(ctxi->rht_lun[rhndl] != lli)) {
pr_debug("%s: Bad resource handle LUN! (%d)\n",
__func__, rhndl);
goto out;
}
rhte = &ctxi->rht_start[rhndl];
if (unlikely(rhte->nmask == 0)) {
pr_debug("%s: Unopened resource handle! (%d)\n",
__func__, rhndl);
rhte = NULL;
goto out;
}
out:
return rhte;
}
/**
* rhte_checkout() - obtains free/empty resource handle table entry
* @ctxi: Context owning the resource handle.
* @lli: LUN associated with request.
*
* Return: Free RHTE on success, NULL on failure
*/
struct sisl_rht_entry *rhte_checkout(struct ctx_info *ctxi,
struct llun_info *lli)
{
struct sisl_rht_entry *rhte = NULL;
int i;
/* Find a free RHT entry */
for (i = 0; i < MAX_RHT_PER_CONTEXT; i++)
if (ctxi->rht_start[i].nmask == 0) {
rhte = &ctxi->rht_start[i];
ctxi->rht_out++;
break;
}
if (likely(rhte))
ctxi->rht_lun[i] = lli;
pr_debug("%s: returning rhte=%p (%d)\n", __func__, rhte, i);
return rhte;
}
/**
* rhte_checkin() - releases a resource handle table entry
* @ctxi: Context owning the resource handle.
* @rhte: RHTE to release.
*/
void rhte_checkin(struct ctx_info *ctxi,
struct sisl_rht_entry *rhte)
{
u32 rsrc_handle = rhte - ctxi->rht_start;
rhte->nmask = 0;
rhte->fp = 0;
ctxi->rht_out--;
ctxi->rht_lun[rsrc_handle] = NULL;
ctxi->rht_needs_ws[rsrc_handle] = false;
}
/**
* rhte_format1() - populates a RHTE for format 1
* @rhte: RHTE to populate.
* @lun_id: LUN ID of LUN associated with RHTE.
* @perm: Desired permissions for RHTE.
* @port_sel: Port selection mask
*/
static void rht_format1(struct sisl_rht_entry *rhte, u64 lun_id, u32 perm,
u32 port_sel)
{
/*
* Populate the Format 1 RHT entry for direct access (physical
* LUN) using the synchronization sequence defined in the
* SISLite specification.
*/
struct sisl_rht_entry_f1 dummy = { 0 };
struct sisl_rht_entry_f1 *rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
memset(rhte_f1, 0, sizeof(*rhte_f1));
rhte_f1->fp = SISL_RHT_FP(1U, 0);
dma_wmb(); /* Make setting of format bit visible */
rhte_f1->lun_id = lun_id;
dma_wmb(); /* Make setting of LUN id visible */
/*
* Use a dummy RHT Format 1 entry to build the second dword
* of the entry that must be populated in a single write when
* enabled (valid bit set to TRUE).
*/
dummy.valid = 0x80;
dummy.fp = SISL_RHT_FP(1U, perm);
dummy.port_sel = port_sel;
rhte_f1->dw = dummy.dw;
dma_wmb(); /* Make remaining RHT entry fields visible */
}
/**
* cxlflash_lun_attach() - attaches a user to a LUN and manages the LUN's mode
* @gli: LUN to attach.
* @mode: Desired mode of the LUN.
* @locked: Mutex status on current thread.
*
* Return: 0 on success, -errno on failure
*/
int cxlflash_lun_attach(struct glun_info *gli, enum lun_mode mode, bool locked)
{
int rc = 0;
if (!locked)
mutex_lock(&gli->mutex);
if (gli->mode == MODE_NONE)
gli->mode = mode;
else if (gli->mode != mode) {
pr_debug("%s: LUN operating in mode %d, requested mode %d\n",
__func__, gli->mode, mode);
rc = -EINVAL;
goto out;
}
gli->users++;
WARN_ON(gli->users <= 0);
out:
pr_debug("%s: Returning rc=%d gli->mode=%u gli->users=%u\n",
__func__, rc, gli->mode, gli->users);
if (!locked)
mutex_unlock(&gli->mutex);
return rc;
}
/**
* cxlflash_lun_detach() - detaches a user from a LUN and resets the LUN's mode
* @gli: LUN to detach.
*
* When resetting the mode, terminate block allocation resources as they
* are no longer required (service is safe to call even when block allocation
* resources were not present - such as when transitioning from physical mode).
* These resources will be reallocated when needed (subsequent transition to
* virtual mode).
*/
void cxlflash_lun_detach(struct glun_info *gli)
{
mutex_lock(&gli->mutex);
WARN_ON(gli->mode == MODE_NONE);
if (--gli->users == 0) {
gli->mode = MODE_NONE;
cxlflash_ba_terminate(&gli->blka.ba_lun);
}
pr_debug("%s: gli->users=%u\n", __func__, gli->users);
WARN_ON(gli->users < 0);
mutex_unlock(&gli->mutex);
}
/**
* _cxlflash_disk_release() - releases the specified resource entry
* @sdev: SCSI device associated with LUN.
* @ctxi: Context owning resources.
* @release: Release ioctl data structure.
*
* For LUNs in virtual mode, the virtual LUN associated with the specified
* resource handle is resized to 0 prior to releasing the RHTE. Note that the
* AFU sync should _not_ be performed when the context is sitting on the error
* recovery list. A context on the error recovery list is not known to the AFU
* due to reset. When the context is recovered, it will be reattached and made
* known again to the AFU.
*
* Return: 0 on success, -errno on failure
*/
int _cxlflash_disk_release(struct scsi_device *sdev,
struct ctx_info *ctxi,
struct dk_cxlflash_release *release)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
struct glun_info *gli = lli->parent;
struct afu *afu = cfg->afu;
bool put_ctx = false;
struct dk_cxlflash_resize size;
res_hndl_t rhndl = release->rsrc_handle;
int rc = 0;
u64 ctxid = DECODE_CTXID(release->context_id),
rctxid = release->context_id;
struct sisl_rht_entry *rhte;
struct sisl_rht_entry_f1 *rhte_f1;
dev_dbg(dev, "%s: ctxid=%llu rhndl=0x%llx gli->mode=%u gli->users=%u\n",
__func__, ctxid, release->rsrc_handle, gli->mode, gli->users);
if (!ctxi) {
ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%llu)\n",
__func__, ctxid);
rc = -EINVAL;
goto out;
}
put_ctx = true;
}
rhte = get_rhte(ctxi, rhndl, lli);
if (unlikely(!rhte)) {
dev_dbg(dev, "%s: Bad resource handle! (%d)\n",
__func__, rhndl);
rc = -EINVAL;
goto out;
}
/*
* Resize to 0 for virtual LUNS by setting the size
* to 0. This will clear LXT_START and LXT_CNT fields
* in the RHT entry and properly sync with the AFU.
*
* Afterwards we clear the remaining fields.
*/
switch (gli->mode) {
case MODE_VIRTUAL:
marshal_rele_to_resize(release, &size);
size.req_size = 0;
rc = _cxlflash_vlun_resize(sdev, ctxi, &size);
if (rc) {
dev_dbg(dev, "%s: resize failed rc %d\n", __func__, rc);
goto out;
}
break;
case MODE_PHYSICAL:
/*
* Clear the Format 1 RHT entry for direct access
* (physical LUN) using the synchronization sequence
* defined in the SISLite specification.
*/
rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
rhte_f1->valid = 0;
dma_wmb(); /* Make revocation of RHT entry visible */
rhte_f1->lun_id = 0;
dma_wmb(); /* Make clearing of LUN id visible */
rhte_f1->dw = 0;
dma_wmb(); /* Make RHT entry bottom-half clearing visible */
if (!ctxi->err_recovery_active)
cxlflash_afu_sync(afu, ctxid, rhndl, AFU_HW_SYNC);
break;
default:
WARN(1, "Unsupported LUN mode!");
goto out;
}
rhte_checkin(ctxi, rhte);
cxlflash_lun_detach(gli);
out:
if (put_ctx)
put_context(ctxi);
dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
return rc;
}
int cxlflash_disk_release(struct scsi_device *sdev,
struct dk_cxlflash_release *release)
{
return _cxlflash_disk_release(sdev, NULL, release);
}
/**
* destroy_context() - releases a context
* @cfg: Internal structure associated with the host.
* @ctxi: Context to release.
*
* Note that the rht_lun member of the context was cut from a single
* allocation when the context was created and therefore does not need
* to be explicitly freed. Also note that we conditionally check for the
* existence of the context control map before clearing the RHT registers
* and context capabilities because it is possible to destroy a context
* while the context is in the error state (previous mapping was removed
* [so we don't have to worry about clearing] and context is waiting for
* a new mapping).
*/
static void destroy_context(struct cxlflash_cfg *cfg,
struct ctx_info *ctxi)
{
struct afu *afu = cfg->afu;
WARN_ON(!list_empty(&ctxi->luns));
/* Clear RHT registers and drop all capabilities for this context */
if (afu->afu_map && ctxi->ctrl_map) {
writeq_be(0, &ctxi->ctrl_map->rht_start);
writeq_be(0, &ctxi->ctrl_map->rht_cnt_id);
writeq_be(0, &ctxi->ctrl_map->ctx_cap);
}
/* Free memory associated with context */
free_page((ulong)ctxi->rht_start);
kfree(ctxi->rht_needs_ws);
kfree(ctxi->rht_lun);
kfree(ctxi);
atomic_dec_if_positive(&cfg->num_user_contexts);
}
/**
* create_context() - allocates and initializes a context
* @cfg: Internal structure associated with the host.
* @ctx: Previously obtained CXL context reference.
* @ctxid: Previously obtained process element associated with CXL context.
* @adap_fd: Previously obtained adapter fd associated with CXL context.
* @file: Previously obtained file associated with CXL context.
* @perms: User-specified permissions.
*
* The context's mutex is locked when an allocated context is returned.
*
* Return: Allocated context on success, NULL on failure
*/
static struct ctx_info *create_context(struct cxlflash_cfg *cfg,
struct cxl_context *ctx, int ctxid,
int adap_fd, struct file *file,
u32 perms)
{
struct device *dev = &cfg->dev->dev;
struct afu *afu = cfg->afu;
struct ctx_info *ctxi = NULL;
struct llun_info **lli = NULL;
bool *ws = NULL;
struct sisl_rht_entry *rhte;
ctxi = kzalloc(sizeof(*ctxi), GFP_KERNEL);
lli = kzalloc((MAX_RHT_PER_CONTEXT * sizeof(*lli)), GFP_KERNEL);
ws = kzalloc((MAX_RHT_PER_CONTEXT * sizeof(*ws)), GFP_KERNEL);
if (unlikely(!ctxi || !lli || !ws)) {
dev_err(dev, "%s: Unable to allocate context!\n", __func__);
goto err;
}
rhte = (struct sisl_rht_entry *)get_zeroed_page(GFP_KERNEL);
if (unlikely(!rhte)) {
dev_err(dev, "%s: Unable to allocate RHT!\n", __func__);
goto err;
}
ctxi->rht_lun = lli;
ctxi->rht_needs_ws = ws;
ctxi->rht_start = rhte;
ctxi->rht_perms = perms;
ctxi->ctrl_map = &afu->afu_map->ctrls[ctxid].ctrl;
ctxi->ctxid = ENCODE_CTXID(ctxi, ctxid);
ctxi->lfd = adap_fd;
ctxi->pid = current->tgid; /* tgid = pid */
ctxi->ctx = ctx;
ctxi->file = file;
mutex_init(&ctxi->mutex);
INIT_LIST_HEAD(&ctxi->luns);
INIT_LIST_HEAD(&ctxi->list); /* initialize for list_empty() */
atomic_inc(&cfg->num_user_contexts);
mutex_lock(&ctxi->mutex);
out:
return ctxi;
err:
kfree(ws);
kfree(lli);
kfree(ctxi);
ctxi = NULL;
goto out;
}
/**
* _cxlflash_disk_detach() - detaches a LUN from a context
* @sdev: SCSI device associated with LUN.
* @ctxi: Context owning resources.
* @detach: Detach ioctl data structure.
*
* As part of the detach, all per-context resources associated with the LUN
* are cleaned up. When detaching the last LUN for a context, the context
* itself is cleaned up and released.
*
* Return: 0 on success, -errno on failure
*/
static int _cxlflash_disk_detach(struct scsi_device *sdev,
struct ctx_info *ctxi,
struct dk_cxlflash_detach *detach)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
struct lun_access *lun_access, *t;
struct dk_cxlflash_release rel;
bool put_ctx = false;
int i;
int rc = 0;
int lfd;
u64 ctxid = DECODE_CTXID(detach->context_id),
rctxid = detach->context_id;
dev_dbg(dev, "%s: ctxid=%llu\n", __func__, ctxid);
if (!ctxi) {
ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%llu)\n",
__func__, ctxid);
rc = -EINVAL;
goto out;
}
put_ctx = true;
}
/* Cleanup outstanding resources tied to this LUN */
if (ctxi->rht_out) {
marshal_det_to_rele(detach, &rel);
for (i = 0; i < MAX_RHT_PER_CONTEXT; i++) {
if (ctxi->rht_lun[i] == lli) {
rel.rsrc_handle = i;
_cxlflash_disk_release(sdev, ctxi, &rel);
}
/* No need to loop further if we're done */
if (ctxi->rht_out == 0)
break;
}
}
/* Take our LUN out of context, free the node */
list_for_each_entry_safe(lun_access, t, &ctxi->luns, list)
if (lun_access->lli == lli) {
list_del(&lun_access->list);
kfree(lun_access);
lun_access = NULL;
break;
}
/* Tear down context following last LUN cleanup */
if (list_empty(&ctxi->luns)) {
ctxi->unavail = true;
mutex_unlock(&ctxi->mutex);
mutex_lock(&cfg->ctx_tbl_list_mutex);
mutex_lock(&ctxi->mutex);
/* Might not have been in error list so conditionally remove */
if (!list_empty(&ctxi->list))
list_del(&ctxi->list);
cfg->ctx_tbl[ctxid] = NULL;
mutex_unlock(&cfg->ctx_tbl_list_mutex);
mutex_unlock(&ctxi->mutex);
lfd = ctxi->lfd;
destroy_context(cfg, ctxi);
ctxi = NULL;
put_ctx = false;
/*
* As a last step, clean up external resources when not
* already on an external cleanup thread, i.e.: close(adap_fd).
*
* NOTE: this will free up the context from the CXL services,
* allowing it to dole out the same context_id on a future
* (or even currently in-flight) disk_attach operation.
*/
if (lfd != -1)
sys_close(lfd);
}
out:
if (put_ctx)
put_context(ctxi);
dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
return rc;
}
static int cxlflash_disk_detach(struct scsi_device *sdev,
struct dk_cxlflash_detach *detach)
{
return _cxlflash_disk_detach(sdev, NULL, detach);
}
/**
* cxlflash_cxl_release() - release handler for adapter file descriptor
* @inode: File-system inode associated with fd.
* @file: File installed with adapter file descriptor.
*
* This routine is the release handler for the fops registered with
* the CXL services on an initial attach for a context. It is called
* when a close is performed on the adapter file descriptor returned
* to the user. Programmatically, the user is not required to perform
* the close, as it is handled internally via the detach ioctl when
* a context is being removed. Note that nothing prevents the user
* from performing a close, but the user should be aware that doing
* so is considered catastrophic and subsequent usage of the superpipe
* API with previously saved off tokens will fail.
*
* When initiated from an external close (either by the user or via
* a process tear down), the routine derives the context reference
* and calls detach for each LUN associated with the context. The
* final detach operation will cause the context itself to be freed.
* Note that the saved off lfd is reset prior to calling detach to
* signify that the final detach should not perform a close.
*
* When initiated from a detach operation as part of the tear down
* of a context, the context is first completely freed and then the
* close is performed. This routine will fail to derive the context
* reference (due to the context having already been freed) and then
* call into the CXL release entry point.
*
* Thus, with exception to when the CXL process element (context id)
* lookup fails (a case that should theoretically never occur), every
* call into this routine results in a complete freeing of a context.
*
* As part of the detach, all per-context resources associated with the LUN
* are cleaned up. When detaching the last LUN for a context, the context
* itself is cleaned up and released.
*
* Return: 0 on success
*/
static int cxlflash_cxl_release(struct inode *inode, struct file *file)
{
struct cxl_context *ctx = cxl_fops_get_context(file);
struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
cxl_fops);
struct device *dev = &cfg->dev->dev;
struct ctx_info *ctxi = NULL;
struct dk_cxlflash_detach detach = { { 0 }, 0 };
struct lun_access *lun_access, *t;
enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
int ctxid;
ctxid = cxl_process_element(ctx);
if (unlikely(ctxid < 0)) {
dev_err(dev, "%s: Context %p was closed! (%d)\n",
__func__, ctx, ctxid);
goto out;
}
ctxi = get_context(cfg, ctxid, file, ctrl);
if (unlikely(!ctxi)) {
ctxi = get_context(cfg, ctxid, file, ctrl | CTX_CTRL_CLONE);
if (!ctxi) {
dev_dbg(dev, "%s: Context %d already free!\n",
__func__, ctxid);
goto out_release;
}
dev_dbg(dev, "%s: Another process owns context %d!\n",
__func__, ctxid);
put_context(ctxi);
goto out;
}
dev_dbg(dev, "%s: close(%d) for context %d\n",
__func__, ctxi->lfd, ctxid);
/* Reset the file descriptor to indicate we're on a close() thread */
ctxi->lfd = -1;
detach.context_id = ctxi->ctxid;
list_for_each_entry_safe(lun_access, t, &ctxi->luns, list)
_cxlflash_disk_detach(lun_access->sdev, ctxi, &detach);
out_release:
cxl_fd_release(inode, file);
out:
dev_dbg(dev, "%s: returning\n", __func__);
return 0;
}
/**
* unmap_context() - clears a previously established mapping
* @ctxi: Context owning the mapping.
*
* This routine is used to switch between the error notification page
* (dummy page of all 1's) and the real mapping (established by the CXL
* fault handler).
*/
static void unmap_context(struct ctx_info *ctxi)
{
unmap_mapping_range(ctxi->file->f_mapping, 0, 0, 1);
}
/**
* get_err_page() - obtains and allocates the error notification page
*
* Return: error notification page on success, NULL on failure
*/
static struct page *get_err_page(void)
{
struct page *err_page = global.err_page;
if (unlikely(!err_page)) {
err_page = alloc_page(GFP_KERNEL);
if (unlikely(!err_page)) {
pr_err("%s: Unable to allocate err_page!\n", __func__);
goto out;
}
memset(page_address(err_page), -1, PAGE_SIZE);
/* Serialize update w/ other threads to avoid a leak */
mutex_lock(&global.mutex);
if (likely(!global.err_page))
global.err_page = err_page;
else {
__free_page(err_page);
err_page = global.err_page;
}
mutex_unlock(&global.mutex);
}
out:
pr_debug("%s: returning err_page=%p\n", __func__, err_page);
return err_page;
}
/**
* cxlflash_mmap_fault() - mmap fault handler for adapter file descriptor
* @vma: VM area associated with mapping.
* @vmf: VM fault associated with current fault.
*
* To support error notification via MMIO, faults are 'caught' by this routine
* that was inserted before passing back the adapter file descriptor on attach.
* When a fault occurs, this routine evaluates if error recovery is active and
* if so, installs the error page to 'notify' the user about the error state.
* During normal operation, the fault is simply handled by the original fault
* handler that was installed by CXL services as part of initializing the
* adapter file descriptor. The VMA's page protection bits are toggled to
* indicate cached/not-cached depending on the memory backing the fault.
*
* Return: 0 on success, VM_FAULT_SIGBUS on failure
*/
static int cxlflash_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct file *file = vma->vm_file;
struct cxl_context *ctx = cxl_fops_get_context(file);
struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
cxl_fops);
struct device *dev = &cfg->dev->dev;
struct ctx_info *ctxi = NULL;
struct page *err_page = NULL;
enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
int rc = 0;
int ctxid;
ctxid = cxl_process_element(ctx);
if (unlikely(ctxid < 0)) {
dev_err(dev, "%s: Context %p was closed! (%d)\n",
__func__, ctx, ctxid);
goto err;
}
ctxi = get_context(cfg, ctxid, file, ctrl);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%d)\n", __func__, ctxid);
goto err;
}
dev_dbg(dev, "%s: fault(%d) for context %d\n",
__func__, ctxi->lfd, ctxid);
if (likely(!ctxi->err_recovery_active)) {
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
rc = ctxi->cxl_mmap_vmops->fault(vma, vmf);
} else {
dev_dbg(dev, "%s: err recovery active, use err_page!\n",
__func__);
err_page = get_err_page();
if (unlikely(!err_page)) {
dev_err(dev, "%s: Could not obtain error page!\n",
__func__);
rc = VM_FAULT_RETRY;
goto out;
}
get_page(err_page);
vmf->page = err_page;
vma->vm_page_prot = pgprot_cached(vma->vm_page_prot);
}
out:
if (likely(ctxi))
put_context(ctxi);
dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
return rc;
err:
rc = VM_FAULT_SIGBUS;
goto out;
}
/*
* Local MMAP vmops to 'catch' faults
*/
static const struct vm_operations_struct cxlflash_mmap_vmops = {
.fault = cxlflash_mmap_fault,
};
/**
* cxlflash_cxl_mmap() - mmap handler for adapter file descriptor
* @file: File installed with adapter file descriptor.
* @vma: VM area associated with mapping.
*
* Installs local mmap vmops to 'catch' faults for error notification support.
*
* Return: 0 on success, -errno on failure
*/
static int cxlflash_cxl_mmap(struct file *file, struct vm_area_struct *vma)
{
struct cxl_context *ctx = cxl_fops_get_context(file);
struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
cxl_fops);
struct device *dev = &cfg->dev->dev;
struct ctx_info *ctxi = NULL;
enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
int ctxid;
int rc = 0;
ctxid = cxl_process_element(ctx);
if (unlikely(ctxid < 0)) {
dev_err(dev, "%s: Context %p was closed! (%d)\n",
__func__, ctx, ctxid);
rc = -EIO;
goto out;
}
ctxi = get_context(cfg, ctxid, file, ctrl);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%d)\n", __func__, ctxid);
rc = -EIO;
goto out;
}
dev_dbg(dev, "%s: mmap(%d) for context %d\n",
__func__, ctxi->lfd, ctxid);
rc = cxl_fd_mmap(file, vma);
if (likely(!rc)) {
/* Insert ourself in the mmap fault handler path */
ctxi->cxl_mmap_vmops = vma->vm_ops;
vma->vm_ops = &cxlflash_mmap_vmops;
}
out:
if (likely(ctxi))
put_context(ctxi);
return rc;
}
/*
* Local fops for adapter file descriptor
*/
static const struct file_operations cxlflash_cxl_fops = {
.owner = THIS_MODULE,
.mmap = cxlflash_cxl_mmap,
.release = cxlflash_cxl_release,
};
/**
* cxlflash_mark_contexts_error() - move contexts to error state and list
* @cfg: Internal structure associated with the host.
*
* A context is only moved over to the error list when there are no outstanding
* references to it. This ensures that a running operation has completed.
*
* Return: 0 on success, -errno on failure
*/
int cxlflash_mark_contexts_error(struct cxlflash_cfg *cfg)
{
int i, rc = 0;
struct ctx_info *ctxi = NULL;
mutex_lock(&cfg->ctx_tbl_list_mutex);
for (i = 0; i < MAX_CONTEXT; i++) {
ctxi = cfg->ctx_tbl[i];
if (ctxi) {
mutex_lock(&ctxi->mutex);
cfg->ctx_tbl[i] = NULL;
list_add(&ctxi->list, &cfg->ctx_err_recovery);
ctxi->err_recovery_active = true;
ctxi->ctrl_map = NULL;
unmap_context(ctxi);
mutex_unlock(&ctxi->mutex);
}
}
mutex_unlock(&cfg->ctx_tbl_list_mutex);
return rc;
}
/*
* Dummy NULL fops
*/
static const struct file_operations null_fops = {
.owner = THIS_MODULE,
};
/**
* cxlflash_disk_attach() - attach a LUN to a context
* @sdev: SCSI device associated with LUN.
* @attach: Attach ioctl data structure.
*
* Creates a context and attaches LUN to it. A LUN can only be attached
* one time to a context (subsequent attaches for the same context/LUN pair
* are not supported). Additional LUNs can be attached to a context by
* specifying the 'reuse' flag defined in the cxlflash_ioctl.h header.
*
* Return: 0 on success, -errno on failure
*/
static int cxlflash_disk_attach(struct scsi_device *sdev,
struct dk_cxlflash_attach *attach)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct afu *afu = cfg->afu;
struct llun_info *lli = sdev->hostdata;
struct glun_info *gli = lli->parent;
struct cxl_ioctl_start_work *work;
struct ctx_info *ctxi = NULL;
struct lun_access *lun_access = NULL;
int rc = 0;
u32 perms;
int ctxid = -1;
u64 rctxid = 0UL;
struct file *file;
struct cxl_context *ctx;
int fd = -1;
/* On first attach set fileops */
if (atomic_read(&cfg->num_user_contexts) == 0)
cfg->cxl_fops = cxlflash_cxl_fops;
if (attach->num_interrupts > 4) {
dev_dbg(dev, "%s: Cannot support this many interrupts %llu\n",
__func__, attach->num_interrupts);
rc = -EINVAL;
goto out;
}
if (gli->max_lba == 0) {
dev_dbg(dev, "%s: No capacity info for this LUN (%016llX)\n",
__func__, lli->lun_id[sdev->channel]);
rc = read_cap16(sdev, lli);
if (rc) {
dev_err(dev, "%s: Invalid device! (%d)\n",
__func__, rc);
rc = -ENODEV;
goto out;
}
dev_dbg(dev, "%s: LBA = %016llX\n", __func__, gli->max_lba);
dev_dbg(dev, "%s: BLK_LEN = %08X\n", __func__, gli->blk_len);
}
if (attach->hdr.flags & DK_CXLFLASH_ATTACH_REUSE_CONTEXT) {
rctxid = attach->context_id;
ctxi = get_context(cfg, rctxid, NULL, 0);
if (!ctxi) {
dev_dbg(dev, "%s: Bad context! (%016llX)\n",
__func__, rctxid);
rc = -EINVAL;
goto out;
}
list_for_each_entry(lun_access, &ctxi->luns, list)
if (lun_access->lli == lli) {
dev_dbg(dev, "%s: Already attached!\n",
__func__);
rc = -EINVAL;
goto out;
}
}
lun_access = kzalloc(sizeof(*lun_access), GFP_KERNEL);
if (unlikely(!lun_access)) {
dev_err(dev, "%s: Unable to allocate lun_access!\n", __func__);
rc = -ENOMEM;
goto out;
}
lun_access->lli = lli;
lun_access->sdev = sdev;
/* Non-NULL context indicates reuse */
if (ctxi) {
dev_dbg(dev, "%s: Reusing context for LUN! (%016llX)\n",
__func__, rctxid);
list_add(&lun_access->list, &ctxi->luns);
fd = ctxi->lfd;
goto out_attach;
}
ctx = cxl_dev_context_init(cfg->dev);
if (unlikely(IS_ERR_OR_NULL(ctx))) {
dev_err(dev, "%s: Could not initialize context %p\n",
__func__, ctx);
rc = -ENODEV;
goto err0;
}
ctxid = cxl_process_element(ctx);
if (unlikely((ctxid > MAX_CONTEXT) || (ctxid < 0))) {
dev_err(dev, "%s: ctxid (%d) invalid!\n", __func__, ctxid);
rc = -EPERM;
goto err1;
}
file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
if (unlikely(fd < 0)) {
rc = -ENODEV;
dev_err(dev, "%s: Could not get file descriptor\n", __func__);
goto err1;
}
/* Translate read/write O_* flags from fcntl.h to AFU permission bits */
perms = SISL_RHT_PERM(attach->hdr.flags + 1);
ctxi = create_context(cfg, ctx, ctxid, fd, file, perms);
if (unlikely(!ctxi)) {
dev_err(dev, "%s: Failed to create context! (%d)\n",
__func__, ctxid);
goto err2;
}
work = &ctxi->work;
work->num_interrupts = attach->num_interrupts;
work->flags = CXL_START_WORK_NUM_IRQS;
rc = cxl_start_work(ctx, work);
if (unlikely(rc)) {
dev_dbg(dev, "%s: Could not start context rc=%d\n",
__func__, rc);
goto err3;
}
rc = afu_attach(cfg, ctxi);
if (unlikely(rc)) {
dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
goto err4;
}
/*
* No error paths after this point. Once the fd is installed it's
* visible to user space and can't be undone safely on this thread.
* There is no need to worry about a deadlock here because no one
* knows about us yet; we can be the only one holding our mutex.
*/
list_add(&lun_access->list, &ctxi->luns);
mutex_unlock(&ctxi->mutex);
mutex_lock(&cfg->ctx_tbl_list_mutex);
mutex_lock(&ctxi->mutex);
cfg->ctx_tbl[ctxid] = ctxi;
mutex_unlock(&cfg->ctx_tbl_list_mutex);
fd_install(fd, file);
out_attach:
attach->hdr.return_flags = 0;
attach->context_id = ctxi->ctxid;
attach->block_size = gli->blk_len;
attach->mmio_size = sizeof(afu->afu_map->hosts[0].harea);
attach->last_lba = gli->max_lba;
attach->max_xfer = (sdev->host->max_sectors * 512) / gli->blk_len;
out:
attach->adap_fd = fd;
if (ctxi)
put_context(ctxi);
dev_dbg(dev, "%s: returning ctxid=%d fd=%d bs=%lld rc=%d llba=%lld\n",
__func__, ctxid, fd, attach->block_size, rc, attach->last_lba);
return rc;
err4:
cxl_stop_context(ctx);
err3:
put_context(ctxi);
destroy_context(cfg, ctxi);
ctxi = NULL;
err2:
/*
* Here, we're overriding the fops with a dummy all-NULL fops because
* fput() calls the release fop, which will cause us to mistakenly
* call into the CXL code. Rather than try to add yet more complexity
* to that routine (cxlflash_cxl_release) we should try to fix the
* issue here.
*/
file->f_op = &null_fops;
fput(file);
put_unused_fd(fd);
fd = -1;
err1:
cxl_release_context(ctx);
err0:
kfree(lun_access);
goto out;
}
/**
* recover_context() - recovers a context in error
* @cfg: Internal structure associated with the host.
* @ctxi: Context to release.
*
* Restablishes the state for a context-in-error.
*
* Return: 0 on success, -errno on failure
*/
static int recover_context(struct cxlflash_cfg *cfg, struct ctx_info *ctxi)
{
struct device *dev = &cfg->dev->dev;
int rc = 0;
int old_fd, fd = -1;
int ctxid = -1;
struct file *file;
struct cxl_context *ctx;
struct afu *afu = cfg->afu;
ctx = cxl_dev_context_init(cfg->dev);
if (unlikely(IS_ERR_OR_NULL(ctx))) {
dev_err(dev, "%s: Could not initialize context %p\n",
__func__, ctx);
rc = -ENODEV;
goto out;
}
ctxid = cxl_process_element(ctx);
if (unlikely((ctxid > MAX_CONTEXT) || (ctxid < 0))) {
dev_err(dev, "%s: ctxid (%d) invalid!\n", __func__, ctxid);
rc = -EPERM;
goto err1;
}
file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
if (unlikely(fd < 0)) {
rc = -ENODEV;
dev_err(dev, "%s: Could not get file descriptor\n", __func__);
goto err1;
}
rc = cxl_start_work(ctx, &ctxi->work);
if (unlikely(rc)) {
dev_dbg(dev, "%s: Could not start context rc=%d\n",
__func__, rc);
goto err2;
}
/* Update with new MMIO area based on updated context id */
ctxi->ctrl_map = &afu->afu_map->ctrls[ctxid].ctrl;
rc = afu_attach(cfg, ctxi);
if (rc) {
dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
goto err3;
}
/*
* No error paths after this point. Once the fd is installed it's
* visible to user space and can't be undone safely on this thread.
*/
old_fd = ctxi->lfd;
ctxi->ctxid = ENCODE_CTXID(ctxi, ctxid);
ctxi->lfd = fd;
ctxi->ctx = ctx;
ctxi->file = file;
/*
* Put context back in table (note the reinit of the context list);
* we must first drop the context's mutex and then acquire it in
* order with the table/list mutex to avoid a deadlock - safe to do
* here because no one can find us at this moment in time.
*/
mutex_unlock(&ctxi->mutex);
mutex_lock(&cfg->ctx_tbl_list_mutex);
mutex_lock(&ctxi->mutex);
list_del_init(&ctxi->list);
cfg->ctx_tbl[ctxid] = ctxi;
mutex_unlock(&cfg->ctx_tbl_list_mutex);
fd_install(fd, file);
/* Release the original adapter fd and associated CXL resources */
sys_close(old_fd);
out:
dev_dbg(dev, "%s: returning ctxid=%d fd=%d rc=%d\n",
__func__, ctxid, fd, rc);
return rc;
err3:
cxl_stop_context(ctx);
err2:
fput(file);
put_unused_fd(fd);
err1:
cxl_release_context(ctx);
goto out;
}
/**
* check_state() - checks and responds to the current adapter state
* @cfg: Internal structure associated with the host.
*
* This routine can block and should only be used on process context.
* Note that when waking up from waiting in limbo, the state is unknown
* and must be checked again before proceeding.
*
* Return: 0 on success, -errno on failure
*/
static int check_state(struct cxlflash_cfg *cfg)
{
struct device *dev = &cfg->dev->dev;
int rc = 0;
retry:
switch (cfg->state) {
case STATE_LIMBO:
dev_dbg(dev, "%s: Limbo, going to wait...\n", __func__);
rc = wait_event_interruptible(cfg->limbo_waitq,
cfg->state != STATE_LIMBO);
if (unlikely(rc))
break;
goto retry;
case STATE_FAILTERM:
dev_dbg(dev, "%s: Failed/Terminating!\n", __func__);
rc = -ENODEV;
break;
default:
break;
}
return rc;
}
/**
* cxlflash_afu_recover() - initiates AFU recovery
* @sdev: SCSI device associated with LUN.
* @recover: Recover ioctl data structure.
*
* Only a single recovery is allowed at a time to avoid exhausting CXL
* resources (leading to recovery failure) in the event that we're up
* against the maximum number of contexts limit. For similar reasons,
* a context recovery is retried if there are multiple recoveries taking
* place at the same time and the failure was due to CXL services being
* unable to keep up.
*
* Because a user can detect an error condition before the kernel, it is
* quite possible for this routine to act as the kernel's EEH detection
* source (MMIO read of mbox_r). Because of this, there is a window of
* time where an EEH might have been detected but not yet 'serviced'
* (callback invoked, causing the device to enter limbo state). To avoid
* looping in this routine during that window, a 1 second sleep is in place
* between the time the MMIO failure is detected and the time a wait on the
* limbo wait queue is attempted via check_state().
*
* Return: 0 on success, -errno on failure
*/
static int cxlflash_afu_recover(struct scsi_device *sdev,
struct dk_cxlflash_recover_afu *recover)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
struct afu *afu = cfg->afu;
struct ctx_info *ctxi = NULL;
struct mutex *mutex = &cfg->ctx_recovery_mutex;
u64 ctxid = DECODE_CTXID(recover->context_id),
rctxid = recover->context_id;
long reg;
int lretry = 20; /* up to 2 seconds */
int rc = 0;
atomic_inc(&cfg->recovery_threads);
rc = mutex_lock_interruptible(mutex);
if (rc)
goto out;
dev_dbg(dev, "%s: reason 0x%016llX rctxid=%016llX\n",
__func__, recover->reason, rctxid);
retry:
/* Ensure that this process is attached to the context */
ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%llu)\n", __func__, ctxid);
rc = -EINVAL;
goto out;
}
if (ctxi->err_recovery_active) {
retry_recover:
rc = recover_context(cfg, ctxi);
if (unlikely(rc)) {
dev_err(dev, "%s: Recovery failed for context %llu (rc=%d)\n",
__func__, ctxid, rc);
if ((rc == -ENODEV) &&
((atomic_read(&cfg->recovery_threads) > 1) ||
(lretry--))) {
dev_dbg(dev, "%s: Going to try again!\n",
__func__);
mutex_unlock(mutex);
msleep(100);
rc = mutex_lock_interruptible(mutex);
if (rc)
goto out;
goto retry_recover;
}
goto out;
}
ctxi->err_recovery_active = false;
recover->context_id = ctxi->ctxid;
recover->adap_fd = ctxi->lfd;
recover->mmio_size = sizeof(afu->afu_map->hosts[0].harea);
recover->hdr.return_flags |=
DK_CXLFLASH_RECOVER_AFU_CONTEXT_RESET;
goto out;
}
/* Test if in error state */
reg = readq_be(&afu->ctrl_map->mbox_r);
if (reg == -1) {
dev_dbg(dev, "%s: MMIO read fail! Wait for recovery...\n",
__func__);
mutex_unlock(&ctxi->mutex);
ctxi = NULL;
ssleep(1);
rc = check_state(cfg);
if (unlikely(rc))
goto out;
goto retry;
}
dev_dbg(dev, "%s: MMIO working, no recovery required!\n", __func__);
out:
if (likely(ctxi))
put_context(ctxi);
mutex_unlock(mutex);
atomic_dec_if_positive(&cfg->recovery_threads);
return rc;
}
/**
* process_sense() - evaluates and processes sense data
* @sdev: SCSI device associated with LUN.
* @verify: Verify ioctl data structure.
*
* Return: 0 on success, -errno on failure
*/
static int process_sense(struct scsi_device *sdev,
struct dk_cxlflash_verify *verify)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
struct glun_info *gli = lli->parent;
u64 prev_lba = gli->max_lba;
struct scsi_sense_hdr sshdr = { 0 };
int rc = 0;
rc = scsi_normalize_sense((const u8 *)&verify->sense_data,
DK_CXLFLASH_VERIFY_SENSE_LEN, &sshdr);
if (!rc) {
dev_err(dev, "%s: Failed to normalize sense data!\n", __func__);
rc = -EINVAL;
goto out;
}
switch (sshdr.sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
/* fall through */
case NOT_READY:
break;
case UNIT_ATTENTION:
switch (sshdr.asc) {
case 0x29: /* Power on Reset or Device Reset */
/* fall through */
case 0x2A: /* Device settings/capacity changed */
rc = read_cap16(sdev, lli);
if (rc) {
rc = -ENODEV;
break;
}
if (prev_lba != gli->max_lba)
dev_dbg(dev, "%s: Capacity changed old=%lld "
"new=%lld\n", __func__, prev_lba,
gli->max_lba);
break;
case 0x3F: /* Report LUNs changed, Rescan. */
scsi_scan_host(cfg->host);
break;
default:
rc = -EIO;
break;
}
break;
default:
rc = -EIO;
break;
}
out:
dev_dbg(dev, "%s: sense_key %x asc %x ascq %x rc %d\n", __func__,
sshdr.sense_key, sshdr.asc, sshdr.ascq, rc);
return rc;
}
/**
* cxlflash_disk_verify() - verifies a LUN is the same and handle size changes
* @sdev: SCSI device associated with LUN.
* @verify: Verify ioctl data structure.
*
* Return: 0 on success, -errno on failure
*/
static int cxlflash_disk_verify(struct scsi_device *sdev,
struct dk_cxlflash_verify *verify)
{
int rc = 0;
struct ctx_info *ctxi = NULL;
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
struct glun_info *gli = lli->parent;
struct sisl_rht_entry *rhte = NULL;
res_hndl_t rhndl = verify->rsrc_handle;
u64 ctxid = DECODE_CTXID(verify->context_id),
rctxid = verify->context_id;
u64 last_lba = 0;
dev_dbg(dev, "%s: ctxid=%llu rhndl=%016llX, hint=%016llX, "
"flags=%016llX\n", __func__, ctxid, verify->rsrc_handle,
verify->hint, verify->hdr.flags);
ctxi = get_context(cfg, rctxid, lli, 0);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%llu)\n", __func__, ctxid);
rc = -EINVAL;
goto out;
}
rhte = get_rhte(ctxi, rhndl, lli);
if (unlikely(!rhte)) {
dev_dbg(dev, "%s: Bad resource handle! (%d)\n",
__func__, rhndl);
rc = -EINVAL;
goto out;
}
/*
* Look at the hint/sense to see if it requires us to redrive
* inquiry (i.e. the Unit attention is due to the WWN changing).
*/
if (verify->hint & DK_CXLFLASH_VERIFY_HINT_SENSE) {
rc = process_sense(sdev, verify);
if (unlikely(rc)) {
dev_err(dev, "%s: Failed to validate sense data (%d)\n",
__func__, rc);
goto out;
}
}
switch (gli->mode) {
case MODE_PHYSICAL:
last_lba = gli->max_lba;
break;
case MODE_VIRTUAL:
/* Cast lxt_cnt to u64 for multiply to be treated as 64bit op */
last_lba = ((u64)rhte->lxt_cnt * MC_CHUNK_SIZE * gli->blk_len);
last_lba /= CXLFLASH_BLOCK_SIZE;
last_lba--;
break;
default:
WARN(1, "Unsupported LUN mode!");
}
verify->last_lba = last_lba;
out:
if (likely(ctxi))
put_context(ctxi);
dev_dbg(dev, "%s: returning rc=%d llba=%llX\n",
__func__, rc, verify->last_lba);
return rc;
}
/**
* decode_ioctl() - translates an encoded ioctl to an easily identifiable string
* @cmd: The ioctl command to decode.
*
* Return: A string identifying the decoded ioctl.
*/
static char *decode_ioctl(int cmd)
{
switch (cmd) {
case DK_CXLFLASH_ATTACH:
return __stringify_1(DK_CXLFLASH_ATTACH);
case DK_CXLFLASH_USER_DIRECT:
return __stringify_1(DK_CXLFLASH_USER_DIRECT);
case DK_CXLFLASH_USER_VIRTUAL:
return __stringify_1(DK_CXLFLASH_USER_VIRTUAL);
case DK_CXLFLASH_VLUN_RESIZE:
return __stringify_1(DK_CXLFLASH_VLUN_RESIZE);
case DK_CXLFLASH_RELEASE:
return __stringify_1(DK_CXLFLASH_RELEASE);
case DK_CXLFLASH_DETACH:
return __stringify_1(DK_CXLFLASH_DETACH);
case DK_CXLFLASH_VERIFY:
return __stringify_1(DK_CXLFLASH_VERIFY);
case DK_CXLFLASH_VLUN_CLONE:
return __stringify_1(DK_CXLFLASH_VLUN_CLONE);
case DK_CXLFLASH_RECOVER_AFU:
return __stringify_1(DK_CXLFLASH_RECOVER_AFU);
case DK_CXLFLASH_MANAGE_LUN:
return __stringify_1(DK_CXLFLASH_MANAGE_LUN);
}
return "UNKNOWN";
}
/**
* cxlflash_disk_direct_open() - opens a direct (physical) disk
* @sdev: SCSI device associated with LUN.
* @arg: UDirect ioctl data structure.
*
* On successful return, the user is informed of the resource handle
* to be used to identify the direct lun and the size (in blocks) of
* the direct lun in last LBA format.
*
* Return: 0 on success, -errno on failure
*/
static int cxlflash_disk_direct_open(struct scsi_device *sdev, void *arg)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct afu *afu = cfg->afu;
struct llun_info *lli = sdev->hostdata;
struct glun_info *gli = lli->parent;
struct dk_cxlflash_udirect *pphys = (struct dk_cxlflash_udirect *)arg;
u64 ctxid = DECODE_CTXID(pphys->context_id),
rctxid = pphys->context_id;
u64 lun_size = 0;
u64 last_lba = 0;
u64 rsrc_handle = -1;
u32 port = CHAN2PORT(sdev->channel);
int rc = 0;
struct ctx_info *ctxi = NULL;
struct sisl_rht_entry *rhte = NULL;
pr_debug("%s: ctxid=%llu ls=0x%llx\n", __func__, ctxid, lun_size);
rc = cxlflash_lun_attach(gli, MODE_PHYSICAL, false);
if (unlikely(rc)) {
dev_dbg(dev, "%s: Failed to attach to LUN! (PHYSICAL)\n",
__func__);
goto out;
}
ctxi = get_context(cfg, rctxid, lli, 0);
if (unlikely(!ctxi)) {
dev_dbg(dev, "%s: Bad context! (%llu)\n", __func__, ctxid);
rc = -EINVAL;
goto err1;
}
rhte = rhte_checkout(ctxi, lli);
if (unlikely(!rhte)) {
dev_dbg(dev, "%s: too many opens for this context\n", __func__);
rc = -EMFILE; /* too many opens */
goto err1;
}
rsrc_handle = (rhte - ctxi->rht_start);
rht_format1(rhte, lli->lun_id[sdev->channel], ctxi->rht_perms, port);
cxlflash_afu_sync(afu, ctxid, rsrc_handle, AFU_LW_SYNC);
last_lba = gli->max_lba;
pphys->hdr.return_flags = 0;
pphys->last_lba = last_lba;
pphys->rsrc_handle = rsrc_handle;
out:
if (likely(ctxi))
put_context(ctxi);
dev_dbg(dev, "%s: returning handle 0x%llx rc=%d llba %lld\n",
__func__, rsrc_handle, rc, last_lba);
return rc;
err1:
cxlflash_lun_detach(gli);
goto out;
}
/**
* ioctl_common() - common IOCTL handler for driver
* @sdev: SCSI device associated with LUN.
* @cmd: IOCTL command.
*
* Handles common fencing operations that are valid for multiple ioctls. Always
* allow through ioctls that are cleanup oriented in nature, even when operating
* in a failed/terminating state.
*
* Return: 0 on success, -errno on failure
*/
static int ioctl_common(struct scsi_device *sdev, int cmd)
{
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct llun_info *lli = sdev->hostdata;
int rc = 0;
if (unlikely(!lli)) {
dev_dbg(dev, "%s: Unknown LUN\n", __func__);
rc = -EINVAL;
goto out;
}
rc = check_state(cfg);
if (unlikely(rc) && (cfg->state == STATE_FAILTERM)) {
switch (cmd) {
case DK_CXLFLASH_VLUN_RESIZE:
case DK_CXLFLASH_RELEASE:
case DK_CXLFLASH_DETACH:
dev_dbg(dev, "%s: Command override! (%d)\n",
__func__, rc);
rc = 0;
break;
}
}
out:
return rc;
}
/**
* cxlflash_ioctl() - IOCTL handler for driver
* @sdev: SCSI device associated with LUN.
* @cmd: IOCTL command.
* @arg: Userspace ioctl data structure.
*
* Return: 0 on success, -errno on failure
*/
int cxlflash_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
typedef int (*sioctl) (struct scsi_device *, void *);
struct cxlflash_cfg *cfg = (struct cxlflash_cfg *)sdev->host->hostdata;
struct device *dev = &cfg->dev->dev;
struct afu *afu = cfg->afu;
struct dk_cxlflash_hdr *hdr;
char buf[sizeof(union cxlflash_ioctls)];
size_t size = 0;
bool known_ioctl = false;
int idx;
int rc = 0;
struct Scsi_Host *shost = sdev->host;
sioctl do_ioctl = NULL;
static const struct {
size_t size;
sioctl ioctl;
} ioctl_tbl[] = { /* NOTE: order matters here */
{sizeof(struct dk_cxlflash_attach), (sioctl)cxlflash_disk_attach},
{sizeof(struct dk_cxlflash_udirect), cxlflash_disk_direct_open},
{sizeof(struct dk_cxlflash_release), (sioctl)cxlflash_disk_release},
{sizeof(struct dk_cxlflash_detach), (sioctl)cxlflash_disk_detach},
{sizeof(struct dk_cxlflash_verify), (sioctl)cxlflash_disk_verify},
{sizeof(struct dk_cxlflash_recover_afu), (sioctl)cxlflash_afu_recover},
{sizeof(struct dk_cxlflash_manage_lun), (sioctl)cxlflash_manage_lun},
{sizeof(struct dk_cxlflash_uvirtual), cxlflash_disk_virtual_open},
{sizeof(struct dk_cxlflash_resize), (sioctl)cxlflash_vlun_resize},
{sizeof(struct dk_cxlflash_clone), (sioctl)cxlflash_disk_clone},
};
/* Restrict command set to physical support only for internal LUN */
if (afu->internal_lun)
switch (cmd) {
case DK_CXLFLASH_RELEASE:
case DK_CXLFLASH_USER_VIRTUAL:
case DK_CXLFLASH_VLUN_RESIZE:
case DK_CXLFLASH_VLUN_CLONE:
dev_dbg(dev, "%s: %s not supported for lun_mode=%d\n",
__func__, decode_ioctl(cmd), afu->internal_lun);
rc = -EINVAL;
goto cxlflash_ioctl_exit;
}
switch (cmd) {
case DK_CXLFLASH_ATTACH:
case DK_CXLFLASH_USER_DIRECT:
case DK_CXLFLASH_RELEASE:
case DK_CXLFLASH_DETACH:
case DK_CXLFLASH_VERIFY:
case DK_CXLFLASH_RECOVER_AFU:
case DK_CXLFLASH_USER_VIRTUAL:
case DK_CXLFLASH_VLUN_RESIZE:
case DK_CXLFLASH_VLUN_CLONE:
dev_dbg(dev, "%s: %s (%08X) on dev(%d/%d/%d/%llu)\n",
__func__, decode_ioctl(cmd), cmd, shost->host_no,
sdev->channel, sdev->id, sdev->lun);
rc = ioctl_common(sdev, cmd);
if (unlikely(rc))
goto cxlflash_ioctl_exit;
/* fall through */
case DK_CXLFLASH_MANAGE_LUN:
known_ioctl = true;
idx = _IOC_NR(cmd) - _IOC_NR(DK_CXLFLASH_ATTACH);
size = ioctl_tbl[idx].size;
do_ioctl = ioctl_tbl[idx].ioctl;
if (likely(do_ioctl))
break;
/* fall through */
default:
rc = -EINVAL;
goto cxlflash_ioctl_exit;
}
if (unlikely(copy_from_user(&buf, arg, size))) {
dev_err(dev, "%s: copy_from_user() fail! "
"size=%lu cmd=%d (%s) arg=%p\n",
__func__, size, cmd, decode_ioctl(cmd), arg);
rc = -EFAULT;
goto cxlflash_ioctl_exit;
}
hdr = (struct dk_cxlflash_hdr *)&buf;
if (hdr->version != DK_CXLFLASH_VERSION_0) {
dev_dbg(dev, "%s: Version %u not supported for %s\n",
__func__, hdr->version, decode_ioctl(cmd));
rc = -EINVAL;
goto cxlflash_ioctl_exit;
}
if (hdr->rsvd[0] || hdr->rsvd[1] || hdr->rsvd[2] || hdr->return_flags) {
dev_dbg(dev, "%s: Reserved/rflags populated!\n", __func__);
rc = -EINVAL;
goto cxlflash_ioctl_exit;
}
rc = do_ioctl(sdev, (void *)&buf);
if (likely(!rc))
if (unlikely(copy_to_user(arg, &buf, size))) {
dev_err(dev, "%s: copy_to_user() fail! "
"size=%lu cmd=%d (%s) arg=%p\n",
__func__, size, cmd, decode_ioctl(cmd), arg);
rc = -EFAULT;
}
/* fall through to exit */
cxlflash_ioctl_exit:
if (unlikely(rc && known_ioctl))
dev_err(dev, "%s: ioctl %s (%08X) on dev(%d/%d/%d/%llu) "
"returned rc %d\n", __func__,
decode_ioctl(cmd), cmd, shost->host_no,
sdev->channel, sdev->id, sdev->lun, rc);
else
dev_dbg(dev, "%s: ioctl %s (%08X) on dev(%d/%d/%d/%llu) "
"returned rc %d\n", __func__, decode_ioctl(cmd),
cmd, shost->host_no, sdev->channel, sdev->id,
sdev->lun, rc);
return rc;
}
| gpl-2.0 |
MoKee/android_kernel_motorola_olympus | init/main.c | 211 | 20728 | /*
* linux/init/main.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* GK 2/5/95 - Changed to support mounting root fs via NFS
* Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96
* Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96
* Simplified starting of init: Michael A. Griffith <grif@acm.org>
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/stackprotector.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/initrd.h>
#include <linux/bootmem.h>
#include <linux/acpi.h>
#include <linux/tty.h>
#include <linux/percpu.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/kernel_stat.h>
#include <linux/start_kernel.h>
#include <linux/security.h>
#include <linux/smp.h>
#include <linux/profile.h>
#include <linux/rcupdate.h>
#include <linux/moduleparam.h>
#include <linux/kallsyms.h>
#include <linux/writeback.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/cgroup.h>
#include <linux/efi.h>
#include <linux/tick.h>
#include <linux/interrupt.h>
#include <linux/taskstats_kern.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/rmap.h>
#include <linux/mempolicy.h>
#include <linux/key.h>
#include <linux/buffer_head.h>
#include <linux/page_cgroup.h>
#include <linux/debug_locks.h>
#include <linux/debugobjects.h>
#include <linux/lockdep.h>
#include <linux/kmemleak.h>
#include <linux/pid_namespace.h>
#include <linux/device.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/idr.h>
#include <linux/kgdb.h>
#include <linux/ftrace.h>
#include <linux/async.h>
#include <linux/kmemcheck.h>
#include <linux/sfi.h>
#include <linux/shmem_fs.h>
#include <linux/slab.h>
#include <linux/perf_event.h>
#include <asm/io.h>
#include <asm/bugs.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_X86_LOCAL_APIC
#include <asm/smp.h>
#endif
static int kernel_init(void *);
extern void init_IRQ(void);
extern void fork_init(unsigned long);
extern void mca_init(void);
extern void sbus_init(void);
extern void prio_tree_init(void);
extern void radix_tree_init(void);
extern void free_initmem(void);
#ifndef CONFIG_DEBUG_RODATA
static inline void mark_rodata_ro(void) { }
#endif
#ifdef CONFIG_TC
extern void tc_init(void);
#endif
/*
* Debug helper: via this flag we know that we are in 'early bootup code'
* where only the boot processor is running with IRQ disabled. This means
* two things - IRQ must not be enabled before the flag is cleared and some
* operations which are not allowed with IRQ disabled are allowed while the
* flag is set.
*/
bool early_boot_irqs_disabled __read_mostly;
enum system_states system_state __read_mostly;
EXPORT_SYMBOL(system_state);
/*
* Boot command-line arguments
*/
#define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT
#define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT
extern void time_init(void);
/* Default late time init is NULL. archs can override this later. */
void (*__initdata late_time_init)(void);
extern void softirq_init(void);
/* Untouched command line saved by arch-specific code. */
char __initdata boot_command_line[COMMAND_LINE_SIZE];
/* Untouched saved command line (eg. for /proc) */
char *saved_command_line;
/* Command line for parameter parsing */
static char *static_command_line;
static char *execute_command;
static char *ramdisk_execute_command;
/*
* If set, this is an indication to the drivers that reset the underlying
* device before going ahead with the initialization otherwise driver might
* rely on the BIOS and skip the reset operation.
*
* This is useful if kernel is booting in an unreliable environment.
* For ex. kdump situaiton where previous kernel has crashed, BIOS has been
* skipped and devices will be in unknown state.
*/
unsigned int reset_devices;
EXPORT_SYMBOL(reset_devices);
static int __init set_reset_devices(char *str)
{
reset_devices = 1;
return 1;
}
__setup("reset_devices", set_reset_devices);
static const char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
const char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
static const char *panic_later, *panic_param;
extern const struct obs_kernel_param __setup_start[], __setup_end[];
static int __init obsolete_checksetup(char *line)
{
const struct obs_kernel_param *p;
int had_early_param = 0;
p = __setup_start;
do {
int n = strlen(p->str);
if (!strncmp(line, p->str, n)) {
if (p->early) {
/* Already done in parse_early_param?
* (Needs exact match on param part).
* Keep iterating, as we can have early
* params and __setups of same names 8( */
if (line[n] == '\0' || line[n] == '=')
had_early_param = 1;
} else if (!p->setup_func) {
printk(KERN_WARNING "Parameter %s is obsolete,"
" ignored\n", p->str);
return 1;
} else if (p->setup_func(line + n))
return 1;
}
p++;
} while (p < __setup_end);
return had_early_param;
}
/*
* This should be approx 2 Bo*oMips to start (note initial shift), and will
* still work even if initially too large, it will just take slightly longer
*/
unsigned long loops_per_jiffy = (1<<12);
EXPORT_SYMBOL(loops_per_jiffy);
static int __init debug_kernel(char *str)
{
console_loglevel = 10;
return 0;
}
static int __init quiet_kernel(char *str)
{
console_loglevel = 4;
return 0;
}
early_param("debug", debug_kernel);
early_param("quiet", quiet_kernel);
static int __init loglevel(char *str)
{
int newlevel;
/*
* Only update loglevel value when a correct setting was passed,
* to prevent blind crashes (when loglevel being set to 0) that
* are quite hard to debug
*/
if (get_option(&str, &newlevel)) {
console_loglevel = newlevel;
return 0;
}
return -EINVAL;
}
early_param("loglevel", loglevel);
/*
* Unknown boot options get handed to init, unless they look like
* unused parameters (modprobe will find them in /proc/cmdline).
*/
static int __init unknown_bootoption(char *param, char *val)
{
/* Change NUL term back to "=", to make "param" the whole string. */
if (val) {
/* param=val or param="val"? */
if (val == param+strlen(param)+1)
val[-1] = '=';
else if (val == param+strlen(param)+2) {
val[-2] = '=';
memmove(val-1, val, strlen(val)+1);
val--;
} else
BUG();
}
/* Handle obsolete-style parameters */
if (obsolete_checksetup(param))
return 0;
/* Unused module parameter. */
if (strchr(param, '.') && (!val || strchr(param, '.') < val))
return 0;
if (panic_later)
return 0;
if (val) {
/* Environment option */
unsigned int i;
for (i = 0; envp_init[i]; i++) {
if (i == MAX_INIT_ENVS) {
panic_later = "Too many boot env vars at `%s'";
panic_param = param;
}
if (!strncmp(param, envp_init[i], val - param))
break;
}
envp_init[i] = param;
} else {
/* Command line option */
unsigned int i;
for (i = 0; argv_init[i]; i++) {
if (i == MAX_INIT_ARGS) {
panic_later = "Too many boot init vars at `%s'";
panic_param = param;
}
}
argv_init[i] = param;
}
return 0;
}
#ifdef CONFIG_DEBUG_PAGEALLOC
int __read_mostly debug_pagealloc_enabled = 0;
#endif
static int __init init_setup(char *str)
{
unsigned int i;
execute_command = str;
/*
* In case LILO is going to boot us with default command line,
* it prepends "auto" before the whole cmdline which makes
* the shell think it should execute a script with such name.
* So we ignore all arguments entered _before_ init=... [MJ]
*/
for (i = 1; i < MAX_INIT_ARGS; i++)
argv_init[i] = NULL;
return 1;
}
__setup("init=", init_setup);
static int __init rdinit_setup(char *str)
{
unsigned int i;
ramdisk_execute_command = str;
/* See "auto" comment in init_setup */
for (i = 1; i < MAX_INIT_ARGS; i++)
argv_init[i] = NULL;
return 1;
}
__setup("rdinit=", rdinit_setup);
#ifndef CONFIG_SMP
static const unsigned int setup_max_cpus = NR_CPUS;
#ifdef CONFIG_X86_LOCAL_APIC
static void __init smp_init(void)
{
APIC_init_uniprocessor();
}
#else
#define smp_init() do { } while (0)
#endif
static inline void setup_nr_cpu_ids(void) { }
static inline void smp_prepare_cpus(unsigned int maxcpus) { }
#endif
/*
* We need to store the untouched command line for future reference.
* We also need to store the touched command line since the parameter
* parsing is performed in place, and we should allow a component to
* store reference of name/value for future reference.
*/
static void __init setup_command_line(char *command_line)
{
saved_command_line = alloc_bootmem(strlen (boot_command_line)+1);
static_command_line = alloc_bootmem(strlen (command_line)+1);
strcpy (saved_command_line, boot_command_line);
strcpy (static_command_line, command_line);
}
/*
* We need to finalize in a non-__init function or else race conditions
* between the root thread and the init thread may cause start_kernel to
* be reaped by free_initmem before the root thread has proceeded to
* cpu_idle.
*
* gcc-3.4 accidentally inlines this function, so use noinline.
*/
static __initdata DECLARE_COMPLETION(kthreadd_done);
static noinline void __init_refok rest_init(void)
{
int pid;
rcu_scheduler_starting();
/*
* We need to spawn init first so that it obtains pid 1, however
* the init task will end up wanting to create kthreads, which, if
* we schedule it before we create kthreadd, will OOPS.
*/
kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND);
numa_default_policy();
pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
rcu_read_lock();
kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
rcu_read_unlock();
complete(&kthreadd_done);
/*
* The boot idle thread must execute schedule()
* at least once to get things moving:
*/
init_idle_bootup_task(current);
preempt_enable_no_resched();
schedule();
/* Call into cpu_idle with preempt disabled */
preempt_disable();
cpu_idle();
}
/* Check for early params. */
static int __init do_early_param(char *param, char *val)
{
const struct obs_kernel_param *p;
for (p = __setup_start; p < __setup_end; p++) {
if ((p->early && strcmp(param, p->str) == 0) ||
(strcmp(param, "console") == 0 &&
strcmp(p->str, "earlycon") == 0)
) {
if (p->setup_func(val) != 0)
printk(KERN_WARNING
"Malformed early option '%s'\n", param);
}
}
/* We accept everything at this stage. */
return 0;
}
void __init parse_early_options(char *cmdline)
{
parse_args("early options", cmdline, NULL, 0, do_early_param);
}
/* Arch code calls this early on, or if not, just before other parsing. */
void __init parse_early_param(void)
{
static __initdata int done = 0;
static __initdata char tmp_cmdline[COMMAND_LINE_SIZE];
if (done)
return;
/* All fall through to do_early_param. */
strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
parse_early_options(tmp_cmdline);
done = 1;
}
/*
* Activate the first processor.
*/
static void __init boot_cpu_init(void)
{
int cpu = smp_processor_id();
/* Mark the boot cpu "present", "online" etc for SMP and UP case */
set_cpu_online(cpu, true);
set_cpu_active(cpu, true);
set_cpu_present(cpu, true);
set_cpu_possible(cpu, true);
}
void __init __weak smp_setup_processor_id(void)
{
}
void __init __weak thread_info_cache_init(void)
{
}
/*
* Set up kernel memory allocators
*/
static void __init mm_init(void)
{
/*
* page_cgroup requires countinous pages as memmap
* and it's bigger than MAX_ORDER unless SPARSEMEM.
*/
page_cgroup_init_flatmem();
mem_init();
kmem_cache_init();
percpu_init_late();
pgtable_cache_init();
vmalloc_init();
}
asmlinkage void __init start_kernel(void)
{
char * command_line;
extern const struct kernel_param __start___param[], __stop___param[];
smp_setup_processor_id();
/*
* Need to run as early as possible, to initialize the
* lockdep hash:
*/
lockdep_init();
debug_objects_early_init();
/*
* Set up the the initial canary ASAP:
*/
boot_init_stack_canary();
cgroup_init_early();
local_irq_disable();
early_boot_irqs_disabled = true;
/*
* Interrupts are still disabled. Do necessary setups, then
* enable them
*/
tick_init();
boot_cpu_init();
page_address_init();
printk(KERN_NOTICE "%s", linux_banner);
setup_arch(&command_line);
mm_init_owner(&init_mm, &init_task);
mm_init_cpumask(&init_mm);
setup_command_line(command_line);
setup_nr_cpu_ids();
setup_per_cpu_areas();
smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */
build_all_zonelists(NULL);
page_alloc_init();
printk(KERN_NOTICE "Kernel command line: %s\n", boot_command_line);
parse_early_param();
parse_args("Booting kernel", static_command_line, __start___param,
__stop___param - __start___param,
&unknown_bootoption);
/*
* These use large bootmem allocations and must precede
* kmem_cache_init()
*/
setup_log_buf(0);
pidhash_init();
vfs_caches_init_early();
sort_main_extable();
trap_init();
mm_init();
/*
* Set up the scheduler prior starting any interrupts (such as the
* timer interrupt). Full topology setup happens at smp_init()
* time - but meanwhile we still have a functioning scheduler.
*/
sched_init();
/*
* Disable preemption - early bootup scheduling is extremely
* fragile until we cpu_idle() for the first time.
*/
preempt_disable();
if (!irqs_disabled()) {
printk(KERN_WARNING "start_kernel(): bug: interrupts were "
"enabled *very* early, fixing it\n");
local_irq_disable();
}
idr_init_cache();
perf_event_init();
rcu_init();
radix_tree_init();
/* init some links before init_ISA_irqs() */
early_irq_init();
init_IRQ();
prio_tree_init();
init_timers();
hrtimers_init();
softirq_init();
timekeeping_init();
time_init();
profile_init();
call_function_init();
if (!irqs_disabled())
printk(KERN_CRIT "start_kernel(): bug: interrupts were "
"enabled early\n");
early_boot_irqs_disabled = false;
local_irq_enable();
/* Interrupts are enabled now so all GFP allocations are safe. */
gfp_allowed_mask = __GFP_BITS_MASK;
kmem_cache_init_late();
/*
* HACK ALERT! This is early. We're enabling the console before
* we've done PCI setups etc, and console_init() must be aware of
* this. But we do want output early, in case something goes wrong.
*/
console_init();
if (panic_later)
panic(panic_later, panic_param);
lockdep_info();
/*
* Need to run this when irqs are enabled, because it wants
* to self-test [hard/soft]-irqs on/off lock inversion bugs
* too:
*/
locking_selftest();
#ifdef CONFIG_BLK_DEV_INITRD
if (initrd_start && !initrd_below_start_ok &&
page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - "
"disabling it.\n",
page_to_pfn(virt_to_page((void *)initrd_start)),
min_low_pfn);
initrd_start = 0;
}
#endif
page_cgroup_init();
enable_debug_pagealloc();
debug_objects_mem_init();
kmemleak_init();
setup_per_cpu_pageset();
numa_policy_init();
if (late_time_init)
late_time_init();
sched_clock_init();
calibrate_delay();
pidmap_init();
anon_vma_init();
#ifdef CONFIG_X86
if (efi_enabled)
efi_enter_virtual_mode();
#endif
thread_info_cache_init();
cred_init();
fork_init(totalram_pages);
proc_caches_init();
buffer_init();
key_init();
security_init();
dbg_late_init();
vfs_caches_init(totalram_pages);
signals_init();
/* rootfs populating might need page-writeback */
page_writeback_init();
#ifdef CONFIG_PROC_FS
proc_root_init();
#endif
cgroup_init();
cpuset_init();
taskstats_init_early();
delayacct_init();
check_bugs();
acpi_early_init(); /* before LAPIC and SMP init */
sfi_init_late();
ftrace_init();
/* Do the rest non-__init'ed, we're now alive */
rest_init();
}
/* Call all constructor functions linked into the kernel. */
static void __init do_ctors(void)
{
#ifdef CONFIG_CONSTRUCTORS
ctor_fn_t *fn = (ctor_fn_t *) __ctors_start;
for (; fn < (ctor_fn_t *) __ctors_end; fn++)
(*fn)();
#endif
}
int initcall_debug;
core_param(initcall_debug, initcall_debug, bool, 0644);
static char msgbuf[64];
static int __init_or_module do_one_initcall_debug(initcall_t fn)
{
ktime_t calltime, delta, rettime;
unsigned long long duration;
int ret;
printk(KERN_DEBUG "calling %pF @ %i\n", fn, task_pid_nr(current));
calltime = ktime_get();
ret = fn();
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
duration = (unsigned long long) ktime_to_ns(delta) >> 10;
printk(KERN_DEBUG "initcall %pF returned %d after %lld usecs\n", fn,
ret, duration);
return ret;
}
int __init_or_module do_one_initcall(initcall_t fn)
{
int count = preempt_count();
int ret;
if (initcall_debug)
ret = do_one_initcall_debug(fn);
else
ret = fn();
msgbuf[0] = 0;
if (ret && ret != -ENODEV && initcall_debug)
sprintf(msgbuf, "error code %d ", ret);
if (preempt_count() != count) {
strlcat(msgbuf, "preemption imbalance ", sizeof(msgbuf));
preempt_count() = count;
}
if (irqs_disabled()) {
strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
local_irq_enable();
}
if (msgbuf[0]) {
printk("initcall %pF returned with %s\n", fn, msgbuf);
}
return ret;
}
extern initcall_t __initcall_start[], __initcall_end[], __early_initcall_end[];
static void __init do_initcalls(void)
{
initcall_t *fn;
for (fn = __early_initcall_end; fn < __initcall_end; fn++)
do_one_initcall(*fn);
}
/*
* Ok, the machine is now initialized. None of the devices
* have been touched yet, but the CPU subsystem is up and
* running, and memory and process management works.
*
* Now we can finally start doing some real work..
*/
static void __init do_basic_setup(void)
{
cpuset_init_smp();
usermodehelper_init();
shmem_init();
driver_init();
init_irq_proc();
do_ctors();
usermodehelper_enable();
do_initcalls();
}
static void __init do_pre_smp_initcalls(void)
{
initcall_t *fn;
for (fn = __initcall_start; fn < __early_initcall_end; fn++)
do_one_initcall(*fn);
}
static void run_init_process(const char *init_filename)
{
argv_init[0] = init_filename;
kernel_execve(init_filename, argv_init, envp_init);
}
/* This is a non __init function. Force it to be noinline otherwise gcc
* makes it inline to init() and it becomes part of init.text section
*/
static noinline int init_post(void)
{
/* need to finish all async __init code before freeing the memory */
async_synchronize_full();
free_initmem();
mark_rodata_ro();
system_state = SYSTEM_RUNNING;
numa_default_policy();
current->signal->flags |= SIGNAL_UNKILLABLE;
if (ramdisk_execute_command) {
run_init_process(ramdisk_execute_command);
printk(KERN_WARNING "Failed to execute %s\n",
ramdisk_execute_command);
}
/*
* We try each of these until one succeeds.
*
* The Bourne shell can be used instead of init if we are
* trying to recover a really broken machine.
*/
if (execute_command) {
run_init_process(execute_command);
printk(KERN_WARNING "Failed to execute %s. Attempting "
"defaults...\n", execute_command);
}
run_init_process("/sbin/init");
run_init_process("/etc/init");
run_init_process("/bin/init");
run_init_process("/bin/sh");
panic("No init found. Try passing init= option to kernel. "
"See Linux Documentation/init.txt for guidance.");
}
static int __init kernel_init(void * unused)
{
/*
* Wait until kthreadd is all set-up.
*/
wait_for_completion(&kthreadd_done);
/*
* init can allocate pages on any node
*/
set_mems_allowed(node_states[N_HIGH_MEMORY]);
/*
* init can run on any cpu.
*/
set_cpus_allowed_ptr(current, cpu_all_mask);
cad_pid = task_pid(current);
smp_prepare_cpus(setup_max_cpus);
do_pre_smp_initcalls();
lockup_detector_init();
smp_init();
sched_init_smp();
do_basic_setup();
/* Open the /dev/console on the rootfs, this should never fail */
if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
printk(KERN_WARNING "Warning: unable to open an initial console.\n");
(void) sys_dup(0);
(void) sys_dup(0);
/*
* check if there is an early userspace init. If yes, let it do all
* the work
*/
if (!ramdisk_execute_command)
ramdisk_execute_command = "/init";
if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {
ramdisk_execute_command = NULL;
prepare_namespace();
}
/*
* Ok, we have completed the initial bootup, and
* we're essentially up and running. Get rid of the
* initmem segments and start the user-mode stuff..
*/
init_post();
return 0;
}
| gpl-2.0 |
sricharanaz/venus | block/t10-pi.c | 467 | 4964 | /*
* t10_pi.c - Functions for generating and verifying T10 Protection
* Information.
*
* Copyright (C) 2007, 2008, 2014 Oracle Corporation
* Written by: Martin K. Petersen <martin.petersen@oracle.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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139,
* USA.
*
*/
#include <linux/t10-pi.h>
#include <linux/blkdev.h>
#include <linux/crc-t10dif.h>
#include <net/checksum.h>
typedef __be16 (csum_fn) (void *, unsigned int);
static const __be16 APP_ESCAPE = (__force __be16) 0xffff;
static const __be32 REF_ESCAPE = (__force __be32) 0xffffffff;
static __be16 t10_pi_crc_fn(void *data, unsigned int len)
{
return cpu_to_be16(crc_t10dif(data, len));
}
static __be16 t10_pi_ip_fn(void *data, unsigned int len)
{
return (__force __be16)ip_compute_csum(data, len);
}
/*
* Type 1 and Type 2 protection use the same format: 16 bit guard tag,
* 16 bit app tag, 32 bit reference tag. Type 3 does not define the ref
* tag.
*/
static int t10_pi_generate(struct blk_integrity_iter *iter, csum_fn *fn,
unsigned int type)
{
unsigned int i;
for (i = 0 ; i < iter->data_size ; i += iter->interval) {
struct t10_pi_tuple *pi = iter->prot_buf;
pi->guard_tag = fn(iter->data_buf, iter->interval);
pi->app_tag = 0;
if (type == 1)
pi->ref_tag = cpu_to_be32(lower_32_bits(iter->seed));
else
pi->ref_tag = 0;
iter->data_buf += iter->interval;
iter->prot_buf += sizeof(struct t10_pi_tuple);
iter->seed++;
}
return 0;
}
static int t10_pi_verify(struct blk_integrity_iter *iter, csum_fn *fn,
unsigned int type)
{
unsigned int i;
for (i = 0 ; i < iter->data_size ; i += iter->interval) {
struct t10_pi_tuple *pi = iter->prot_buf;
__be16 csum;
switch (type) {
case 1:
case 2:
if (pi->app_tag == APP_ESCAPE)
goto next;
if (be32_to_cpu(pi->ref_tag) !=
lower_32_bits(iter->seed)) {
pr_err("%s: ref tag error at location %llu " \
"(rcvd %u)\n", iter->disk_name,
(unsigned long long)
iter->seed, be32_to_cpu(pi->ref_tag));
return -EILSEQ;
}
break;
case 3:
if (pi->app_tag == APP_ESCAPE &&
pi->ref_tag == REF_ESCAPE)
goto next;
break;
}
csum = fn(iter->data_buf, iter->interval);
if (pi->guard_tag != csum) {
pr_err("%s: guard tag error at sector %llu " \
"(rcvd %04x, want %04x)\n", iter->disk_name,
(unsigned long long)iter->seed,
be16_to_cpu(pi->guard_tag), be16_to_cpu(csum));
return -EILSEQ;
}
next:
iter->data_buf += iter->interval;
iter->prot_buf += sizeof(struct t10_pi_tuple);
iter->seed++;
}
return 0;
}
static int t10_pi_type1_generate_crc(struct blk_integrity_iter *iter)
{
return t10_pi_generate(iter, t10_pi_crc_fn, 1);
}
static int t10_pi_type1_generate_ip(struct blk_integrity_iter *iter)
{
return t10_pi_generate(iter, t10_pi_ip_fn, 1);
}
static int t10_pi_type1_verify_crc(struct blk_integrity_iter *iter)
{
return t10_pi_verify(iter, t10_pi_crc_fn, 1);
}
static int t10_pi_type1_verify_ip(struct blk_integrity_iter *iter)
{
return t10_pi_verify(iter, t10_pi_ip_fn, 1);
}
static int t10_pi_type3_generate_crc(struct blk_integrity_iter *iter)
{
return t10_pi_generate(iter, t10_pi_crc_fn, 3);
}
static int t10_pi_type3_generate_ip(struct blk_integrity_iter *iter)
{
return t10_pi_generate(iter, t10_pi_ip_fn, 3);
}
static int t10_pi_type3_verify_crc(struct blk_integrity_iter *iter)
{
return t10_pi_verify(iter, t10_pi_crc_fn, 3);
}
static int t10_pi_type3_verify_ip(struct blk_integrity_iter *iter)
{
return t10_pi_verify(iter, t10_pi_ip_fn, 3);
}
struct blk_integrity_profile t10_pi_type1_crc = {
.name = "T10-DIF-TYPE1-CRC",
.generate_fn = t10_pi_type1_generate_crc,
.verify_fn = t10_pi_type1_verify_crc,
};
EXPORT_SYMBOL(t10_pi_type1_crc);
struct blk_integrity_profile t10_pi_type1_ip = {
.name = "T10-DIF-TYPE1-IP",
.generate_fn = t10_pi_type1_generate_ip,
.verify_fn = t10_pi_type1_verify_ip,
};
EXPORT_SYMBOL(t10_pi_type1_ip);
struct blk_integrity_profile t10_pi_type3_crc = {
.name = "T10-DIF-TYPE3-CRC",
.generate_fn = t10_pi_type3_generate_crc,
.verify_fn = t10_pi_type3_verify_crc,
};
EXPORT_SYMBOL(t10_pi_type3_crc);
struct blk_integrity_profile t10_pi_type3_ip = {
.name = "T10-DIF-TYPE3-IP",
.generate_fn = t10_pi_type3_generate_ip,
.verify_fn = t10_pi_type3_verify_ip,
};
EXPORT_SYMBOL(t10_pi_type3_ip);
| gpl-2.0 |
denzfarid/rndc-kernel | arch/x86/pci/visws.c | 723 | 2591 | /*
* Low-Level PCI Support for SGI Visual Workstation
*
* (c) 1999--2000 Martin Mares <mj@ucw.cz>
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/setup.h>
#include <asm/pci_x86.h>
#include <asm/visws/cobalt.h>
#include <asm/visws/lithium.h>
static int pci_visws_enable_irq(struct pci_dev *dev) { return 0; }
static void pci_visws_disable_irq(struct pci_dev *dev) { }
/* int (*pcibios_enable_irq)(struct pci_dev *dev) = &pci_visws_enable_irq; */
/* void (*pcibios_disable_irq)(struct pci_dev *dev) = &pci_visws_disable_irq; */
/* void __init pcibios_penalize_isa_irq(int irq, int active) {} */
unsigned int pci_bus0, pci_bus1;
static int __init visws_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
int irq, bus = dev->bus->number;
pin--;
/* Nothing useful at PIIX4 pin 1 */
if (bus == pci_bus0 && slot == 4 && pin == 0)
return -1;
/* PIIX4 USB is on Bus 0, Slot 4, Line 3 */
if (bus == pci_bus0 && slot == 4 && pin == 3) {
irq = CO_IRQ(CO_APIC_PIIX4_USB);
goto out;
}
/* First pin spread down 1 APIC entry per slot */
if (pin == 0) {
irq = CO_IRQ((bus == pci_bus0 ? CO_APIC_PCIB_BASE0 :
CO_APIC_PCIA_BASE0) + slot);
goto out;
}
/* lines 1,2,3 from any slot is shared in this twirly pattern */
if (bus == pci_bus1) {
/* lines 1-3 from devices 0 1 rotate over 2 apic entries */
irq = CO_IRQ(CO_APIC_PCIA_BASE123 + ((slot + (pin - 1)) % 2));
} else { /* bus == pci_bus0 */
/* lines 1-3 from devices 0-3 rotate over 3 apic entries */
if (slot == 0)
slot = 3; /* same pattern */
irq = CO_IRQ(CO_APIC_PCIA_BASE123 + ((3 - slot) + (pin - 1) % 3));
}
out:
printk(KERN_DEBUG "PCI: Bus %d Slot %d Line %d -> IRQ %d\n", bus, slot, pin, irq);
return irq;
}
void __init pcibios_update_irq(struct pci_dev *dev, int irq)
{
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, irq);
}
int __init pci_visws_init(void)
{
if (!is_visws_box())
return -1;
pcibios_enable_irq = &pci_visws_enable_irq;
pcibios_disable_irq = &pci_visws_disable_irq;
/* The VISWS supports configuration access type 1 only */
pci_probe = (pci_probe | PCI_PROBE_CONF1) &
~(PCI_PROBE_BIOS | PCI_PROBE_CONF2);
pci_bus0 = li_pcib_read16(LI_PCI_BUSNUM) & 0xff;
pci_bus1 = li_pcia_read16(LI_PCI_BUSNUM) & 0xff;
printk(KERN_INFO "PCI: Lithium bridge A bus: %u, "
"bridge B (PIIX4) bus: %u\n", pci_bus1, pci_bus0);
raw_pci_ops = &pci_direct_conf1;
pci_scan_bus_with_sysdata(pci_bus0);
pci_scan_bus_with_sysdata(pci_bus1);
pci_fixup_irqs(pci_common_swizzle, visws_map_irq);
pcibios_resource_survey();
return 0;
}
| gpl-2.0 |
zparallax/amplitude-kk-tw | drivers/media/platform/msm/vidc/vidc_hfi.c | 723 | 1957 | /* Copyright (c) 2012-2013, 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/slab.h>
#include "msm_vidc_debug.h"
#include "vidc_hfi_api.h"
#include "venus_hfi.h"
#include "q6_hfi.h"
void *vidc_hfi_initialize(enum msm_vidc_hfi_type hfi_type, u32 device_id,
struct msm_vidc_platform_resources *res,
hfi_cmd_response_callback callback)
{
struct hfi_device *hdev = NULL;
int rc = 0;
hdev = (struct hfi_device *)
kzalloc(sizeof(struct hfi_device), GFP_KERNEL);
if (!hdev) {
dprintk(VIDC_ERR, "%s: failed to allocate hdev\n", __func__);
return NULL;
}
switch (hfi_type) {
case VIDC_HFI_VENUS:
rc = venus_hfi_initialize(hdev, device_id, res, callback);
break;
case VIDC_HFI_Q6:
rc = q6_hfi_initialize(hdev, device_id, res, callback);
break;
default:
dprintk(VIDC_ERR, "Unsupported host-firmware interface\n");
goto err_hfi_init;
}
if (rc) {
dprintk(VIDC_ERR, "%s device init failed rc = %d",
__func__, rc);
goto err_hfi_init;
}
return hdev;
err_hfi_init:
kfree(hdev);
return NULL;
}
void vidc_hfi_deinitialize(enum msm_vidc_hfi_type hfi_type,
struct hfi_device *hdev)
{
if (!hdev) {
dprintk(VIDC_ERR, "%s invalid device %p", __func__, hdev);
return;
}
switch (hfi_type) {
case VIDC_HFI_VENUS:
venus_hfi_delete_device(hdev->hfi_device_data);
break;
case VIDC_HFI_Q6:
q6_hfi_delete_device(hdev->hfi_device_data);
break;
default:
dprintk(VIDC_ERR, "Unsupported host-firmware interface\n");
}
kfree(hdev);
}
| gpl-2.0 |
GustavoRD78/78Kernel-ZL-283 | drivers/video/msm/mdss/mdss_mdp_util.c | 979 | 8228 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/android_pmem.h>
#include <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/msm_ion.h>
#include <linux/msm_kgsl.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include "mdss_fb.h"
#include "mdss_mdp.h"
#include "mdss_mdp_formats.h"
enum {
MDP_INTR_VSYNC_INTF_0,
MDP_INTR_VSYNC_INTF_1,
MDP_INTR_VSYNC_INTF_2,
MDP_INTR_VSYNC_INTF_3,
MDP_INTR_PING_PONG_0,
MDP_INTR_PING_PONG_1,
MDP_INTR_PING_PONG_2,
MDP_INTR_WB_0,
MDP_INTR_WB_1,
MDP_INTR_WB_2,
MDP_INTR_MAX,
};
struct intr_callback {
void (*func)(void *);
void *arg;
};
struct intr_callback mdp_intr_cb[MDP_INTR_MAX];
static DEFINE_SPINLOCK(mdss_mdp_intr_lock);
static int mdss_mdp_intr2index(u32 intr_type, u32 intf_num)
{
int index = -1;
switch (intr_type) {
case MDSS_MDP_IRQ_INTF_VSYNC:
index = MDP_INTR_VSYNC_INTF_0 + (intf_num - MDSS_MDP_INTF0);
break;
case MDSS_MDP_IRQ_PING_PONG_COMP:
index = MDP_INTR_PING_PONG_0 + intf_num;
break;
case MDSS_MDP_IRQ_WB_ROT_COMP:
index = MDP_INTR_WB_0 + intf_num;
break;
case MDSS_MDP_IRQ_WB_WFD:
index = MDP_INTR_WB_2 + intf_num;
break;
}
return index;
}
int mdss_mdp_set_intr_callback(u32 intr_type, u32 intf_num,
void (*fnc_ptr)(void *), void *arg)
{
unsigned long flags;
int index, ret;
index = mdss_mdp_intr2index(intr_type, intf_num);
if (index < 0) {
pr_warn("invalid intr type=%u intf_num=%u\n",
intr_type, intf_num);
return -EINVAL;
}
spin_lock_irqsave(&mdss_mdp_intr_lock, flags);
if (!mdp_intr_cb[index].func) {
mdp_intr_cb[index].func = fnc_ptr;
mdp_intr_cb[index].arg = arg;
ret = 0;
} else {
ret = -EBUSY;
}
spin_unlock_irqrestore(&mdss_mdp_intr_lock, flags);
return ret;
}
static inline void mdss_mdp_intr_done(int index)
{
void (*fnc)(void *);
void *arg;
spin_lock(&mdss_mdp_intr_lock);
fnc = mdp_intr_cb[index].func;
arg = mdp_intr_cb[index].arg;
if (fnc != NULL)
mdp_intr_cb[index].func = NULL;
spin_unlock(&mdss_mdp_intr_lock);
if (fnc)
fnc(arg);
}
irqreturn_t mdss_mdp_isr(int irq, void *ptr)
{
u32 isr, mask;
isr = MDSS_MDP_REG_READ(MDSS_MDP_REG_INTR_STATUS);
pr_debug("isr=%x\n", isr);
if (isr == 0)
goto done;
mask = MDSS_MDP_REG_READ(MDSS_MDP_REG_INTR_EN);
MDSS_MDP_REG_WRITE(MDSS_MDP_REG_INTR_CLEAR, isr);
isr &= mask;
if (isr == 0)
goto done;
if (isr & MDSS_MDP_INTR_PING_PONG_0_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_0);
if (isr & MDSS_MDP_INTR_PING_PONG_1_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_1);
if (isr & MDSS_MDP_INTR_PING_PONG_2_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_2);
if (isr & MDSS_MDP_INTR_INTF_0_VSYNC)
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_0);
if (isr & MDSS_MDP_INTR_INTF_1_VSYNC)
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_1);
if (isr & MDSS_MDP_INTR_INTF_2_VSYNC)
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_2);
if (isr & MDSS_MDP_INTR_INTF_3_VSYNC)
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_3);
if (isr & MDSS_MDP_INTR_WB_0_DONE)
mdss_mdp_intr_done(MDP_INTR_WB_0);
if (isr & MDSS_MDP_INTR_WB_1_DONE)
mdss_mdp_intr_done(MDP_INTR_WB_1);
if (isr & MDSS_MDP_INTR_WB_2_DONE)
mdss_mdp_intr_done(MDP_INTR_WB_2);
done:
return IRQ_HANDLED;
}
struct mdss_mdp_format_params *mdss_mdp_get_format_params(u32 format)
{
struct mdss_mdp_format_params *fmt = NULL;
if (format < MDP_IMGTYPE_LIMIT) {
fmt = &mdss_mdp_format_map[format];
if (fmt->format != format)
fmt = NULL;
}
return fmt;
}
int mdss_mdp_get_plane_sizes(u32 format, u32 w, u32 h,
struct mdss_mdp_plane_sizes *ps)
{
struct mdss_mdp_format_params *fmt;
int i;
if (ps == NULL)
return -EINVAL;
if ((w > MAX_IMG_WIDTH) || (h > MAX_IMG_HEIGHT))
return -ERANGE;
fmt = mdss_mdp_get_format_params(format);
if (!fmt)
return -EINVAL;
memset(ps, 0, sizeof(struct mdss_mdp_plane_sizes));
if (fmt->fetch_planes == MDSS_MDP_PLANE_INTERLEAVED) {
u32 bpp = fmt->bpp + 1;
ps->num_planes = 1;
ps->plane_size[0] = w * h * bpp;
ps->ystride[0] = w * bpp;
} else {
u8 hmap[] = { 1, 2, 1, 2 };
u8 vmap[] = { 1, 1, 2, 2 };
u8 horiz, vert;
horiz = hmap[fmt->chroma_sample];
vert = vmap[fmt->chroma_sample];
if (format == MDP_Y_CR_CB_GH2V2) {
ps->plane_size[0] = ALIGN(w, 16) * h;
ps->plane_size[1] = ALIGN(w / horiz, 16) * (h / vert);
ps->ystride[0] = ALIGN(w, 16);
ps->ystride[1] = ALIGN(w / horiz, 16);
} else {
ps->plane_size[0] = w * h;
ps->plane_size[1] = (w / horiz) * (h / vert);
ps->ystride[0] = w;
ps->ystride[1] = (w / horiz);
}
if (fmt->fetch_planes == MDSS_MDP_PLANE_PSEUDO_PLANAR) {
ps->num_planes = 2;
ps->plane_size[1] *= 2;
ps->ystride[1] *= 2;
} else { /* planar */
ps->num_planes = 3;
ps->plane_size[2] = ps->plane_size[1];
ps->ystride[2] = ps->ystride[1];
}
}
for (i = 0; i < ps->num_planes; i++)
ps->total_size += ps->plane_size[i];
return 0;
}
int mdss_mdp_data_check(struct mdss_mdp_data *data,
struct mdss_mdp_plane_sizes *ps)
{
if (!ps)
return 0;
if (!data || data->num_planes == 0)
return -ENOMEM;
if (data->bwc_enabled) {
return -EPERM; /* not supported */
} else {
struct mdss_mdp_img_data *prev, *curr;
int i;
pr_debug("srcp0=%x len=%u frame_size=%u\n", data->p[0].addr,
data->p[0].len, ps->total_size);
for (i = 0; i < ps->num_planes; i++) {
curr = &data->p[i];
if (i >= data->num_planes) {
u32 psize = ps->plane_size[i-1];
prev = &data->p[i-1];
if (prev->len > psize) {
curr->len = prev->len - psize;
prev->len = psize;
}
curr->addr = prev->addr + psize;
}
if (curr->len < ps->plane_size[i]) {
pr_err("insufficient mem=%u p=%d len=%u\n",
curr->len, i, ps->plane_size[i]);
return -ENOMEM;
}
pr_debug("plane[%d] addr=%x len=%u\n", i,
curr->addr, curr->len);
}
data->num_planes = ps->num_planes;
}
return 0;
}
int mdss_mdp_put_img(struct mdss_mdp_img_data *data)
{
/* only source may use frame buffer */
if (data->flags & MDP_MEMORY_ID_TYPE_FB) {
fput_light(data->srcp_file, data->p_need);
return 0;
}
if (data->srcp_file) {
put_pmem_file(data->srcp_file);
data->srcp_file = NULL;
return 0;
}
if (!IS_ERR_OR_NULL(data->srcp_ihdl)) {
ion_free(data->iclient, data->srcp_ihdl);
data->iclient = NULL;
data->srcp_ihdl = NULL;
return 0;
}
return -ENOMEM;
}
int mdss_mdp_get_img(struct ion_client *iclient, struct msmfb_data *img,
struct mdss_mdp_img_data *data)
{
struct file *file;
int ret = -EINVAL;
int fb_num;
unsigned long *start, *len;
start = (unsigned long *) &data->addr;
len = (unsigned long *) &data->len;
data->flags = img->flags;
data->p_need = 0;
if (img->flags & MDP_BLIT_SRC_GEM) {
data->srcp_file = NULL;
ret = kgsl_gem_obj_addr(img->memory_id, (int) img->priv,
start, len);
} else if (img->flags & MDP_MEMORY_ID_TYPE_FB) {
file = fget_light(img->memory_id, &data->p_need);
if (file && FB_MAJOR ==
MAJOR(file->f_dentry->d_inode->i_rdev)) {
data->srcp_file = file;
fb_num = MINOR(file->f_dentry->d_inode->i_rdev);
ret = mdss_fb_get_phys_info(start, len, fb_num);
}
} else if (iclient) {
data->iclient = iclient;
data->srcp_ihdl = ion_import_dma_buf(iclient, img->memory_id);
if (IS_ERR_OR_NULL(data->srcp_ihdl))
return PTR_ERR(data->srcp_ihdl);
ret = ion_phys(iclient, data->srcp_ihdl,
start, (size_t *) len);
} else {
unsigned long vstart;
ret = get_pmem_file(img->memory_id, start, &vstart, len,
&data->srcp_file);
}
if (!ret && (img->offset < data->len)) {
data->addr += img->offset;
data->len -= img->offset;
} else {
mdss_mdp_put_img(data);
ret = -EINVAL;
}
return ret;
}
| gpl-2.0 |
Dm47021/Linux-kernel_4.1.15-rt17_MusicOS | drivers/clk/spear/clk-frac-synth.c | 1235 | 3877 | /*
* Copyright (C) 2012 ST Microelectronics
* Viresh Kumar <viresh.linux@gmail.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*
* Fractional Synthesizer clock implementation
*/
#define pr_fmt(fmt) "clk-frac-synth: " fmt
#include <linux/clk-provider.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/err.h>
#include "clk.h"
#define DIV_FACTOR_MASK 0x1FFFF
/*
* DOC: Fractional Synthesizer clock
*
* Fout from synthesizer can be given from below equation:
*
* Fout= Fin/2*div (division factor)
* div is 17 bits:-
* 0-13 (fractional part)
* 14-16 (integer part)
* div is (16-14 bits).(13-0 bits) (in binary)
*
* Fout = Fin/(2 * div)
* Fout = ((Fin / 10000)/(2 * div)) * 10000
* Fout = (2^14 * (Fin / 10000)/(2^14 * (2 * div))) * 10000
* Fout = (((Fin / 10000) << 14)/(2 * (div << 14))) * 10000
*
* div << 14 simply 17 bit value written at register.
* Max error due to scaling down by 10000 is 10 KHz
*/
#define to_clk_frac(_hw) container_of(_hw, struct clk_frac, hw)
static unsigned long frac_calc_rate(struct clk_hw *hw, unsigned long prate,
int index)
{
struct clk_frac *frac = to_clk_frac(hw);
struct frac_rate_tbl *rtbl = frac->rtbl;
prate /= 10000;
prate <<= 14;
prate /= (2 * rtbl[index].div);
prate *= 10000;
return prate;
}
static long clk_frac_round_rate(struct clk_hw *hw, unsigned long drate,
unsigned long *prate)
{
struct clk_frac *frac = to_clk_frac(hw);
int unused;
return clk_round_rate_index(hw, drate, *prate, frac_calc_rate,
frac->rtbl_cnt, &unused);
}
static unsigned long clk_frac_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct clk_frac *frac = to_clk_frac(hw);
unsigned long flags = 0;
unsigned int div = 1, val;
if (frac->lock)
spin_lock_irqsave(frac->lock, flags);
val = readl_relaxed(frac->reg);
if (frac->lock)
spin_unlock_irqrestore(frac->lock, flags);
div = val & DIV_FACTOR_MASK;
if (!div)
return 0;
parent_rate = parent_rate / 10000;
parent_rate = (parent_rate << 14) / (2 * div);
return parent_rate * 10000;
}
/* Configures new clock rate of frac */
static int clk_frac_set_rate(struct clk_hw *hw, unsigned long drate,
unsigned long prate)
{
struct clk_frac *frac = to_clk_frac(hw);
struct frac_rate_tbl *rtbl = frac->rtbl;
unsigned long flags = 0, val;
int i;
clk_round_rate_index(hw, drate, prate, frac_calc_rate, frac->rtbl_cnt,
&i);
if (frac->lock)
spin_lock_irqsave(frac->lock, flags);
val = readl_relaxed(frac->reg) & ~DIV_FACTOR_MASK;
val |= rtbl[i].div & DIV_FACTOR_MASK;
writel_relaxed(val, frac->reg);
if (frac->lock)
spin_unlock_irqrestore(frac->lock, flags);
return 0;
}
static struct clk_ops clk_frac_ops = {
.recalc_rate = clk_frac_recalc_rate,
.round_rate = clk_frac_round_rate,
.set_rate = clk_frac_set_rate,
};
struct clk *clk_register_frac(const char *name, const char *parent_name,
unsigned long flags, void __iomem *reg,
struct frac_rate_tbl *rtbl, u8 rtbl_cnt, spinlock_t *lock)
{
struct clk_init_data init;
struct clk_frac *frac;
struct clk *clk;
if (!name || !parent_name || !reg || !rtbl || !rtbl_cnt) {
pr_err("Invalid arguments passed");
return ERR_PTR(-EINVAL);
}
frac = kzalloc(sizeof(*frac), GFP_KERNEL);
if (!frac) {
pr_err("could not allocate frac clk\n");
return ERR_PTR(-ENOMEM);
}
/* struct clk_frac assignments */
frac->reg = reg;
frac->rtbl = rtbl;
frac->rtbl_cnt = rtbl_cnt;
frac->lock = lock;
frac->hw.init = &init;
init.name = name;
init.ops = &clk_frac_ops;
init.flags = flags;
init.parent_names = &parent_name;
init.num_parents = 1;
clk = clk_register(NULL, &frac->hw);
if (!IS_ERR_OR_NULL(clk))
return clk;
pr_err("clk register failed\n");
kfree(frac);
return NULL;
}
| gpl-2.0 |
geoffret/litmus-rt | arch/mips/sgi-ip22/ip22-gio.c | 1235 | 9590 | #include <linux/export.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <asm/addrspace.h>
#include <asm/paccess.h>
#include <asm/gio_device.h>
#include <asm/sgi/gio.h>
#include <asm/sgi/hpc3.h>
#include <asm/sgi/mc.h>
#include <asm/sgi/ip22.h>
static struct bus_type gio_bus_type;
static struct {
const char *name;
__u8 id;
} gio_name_table[] = {
{ .name = "SGI Impact", .id = 0x10 },
{ .name = "Phobos G160", .id = 0x35 },
{ .name = "Phobos G130", .id = 0x36 },
{ .name = "Phobos G100", .id = 0x37 },
{ .name = "Set Engineering GFE", .id = 0x38 },
/* fake IDs */
{ .name = "SGI Newport", .id = 0x7e },
{ .name = "SGI GR2/GR3", .id = 0x7f },
};
static void gio_bus_release(struct device *dev)
{
kfree(dev);
}
static struct device gio_bus = {
.init_name = "gio",
.release = &gio_bus_release,
};
/**
* gio_match_device - Tell if an of_device structure has a matching
* gio_match structure
* @ids: array of of device match structures to search in
* @dev: the of device structure to match against
*
* Used by a driver to check whether an of_device present in the
* system is in its list of supported devices.
*/
const struct gio_device_id *gio_match_device(const struct gio_device_id *match,
const struct gio_device *dev)
{
const struct gio_device_id *ids;
for (ids = match; ids->id != 0xff; ids++)
if (ids->id == dev->id.id)
return ids;
return NULL;
}
EXPORT_SYMBOL_GPL(gio_match_device);
struct gio_device *gio_dev_get(struct gio_device *dev)
{
struct device *tmp;
if (!dev)
return NULL;
tmp = get_device(&dev->dev);
if (tmp)
return to_gio_device(tmp);
else
return NULL;
}
EXPORT_SYMBOL_GPL(gio_dev_get);
void gio_dev_put(struct gio_device *dev)
{
if (dev)
put_device(&dev->dev);
}
EXPORT_SYMBOL_GPL(gio_dev_put);
/**
* gio_release_dev - free an gio device structure when all users of it are finished.
* @dev: device that's been disconnected
*
* Will be called only by the device core when all users of this gio device are
* done.
*/
void gio_release_dev(struct device *dev)
{
struct gio_device *giodev;
giodev = to_gio_device(dev);
kfree(giodev);
}
EXPORT_SYMBOL_GPL(gio_release_dev);
int gio_device_register(struct gio_device *giodev)
{
giodev->dev.bus = &gio_bus_type;
giodev->dev.parent = &gio_bus;
return device_register(&giodev->dev);
}
EXPORT_SYMBOL_GPL(gio_device_register);
void gio_device_unregister(struct gio_device *giodev)
{
device_unregister(&giodev->dev);
}
EXPORT_SYMBOL_GPL(gio_device_unregister);
static int gio_bus_match(struct device *dev, struct device_driver *drv)
{
struct gio_device *gio_dev = to_gio_device(dev);
struct gio_driver *gio_drv = to_gio_driver(drv);
return gio_match_device(gio_drv->id_table, gio_dev) != NULL;
}
static int gio_device_probe(struct device *dev)
{
int error = -ENODEV;
struct gio_driver *drv;
struct gio_device *gio_dev;
const struct gio_device_id *match;
drv = to_gio_driver(dev->driver);
gio_dev = to_gio_device(dev);
if (!drv->probe)
return error;
gio_dev_get(gio_dev);
match = gio_match_device(drv->id_table, gio_dev);
if (match)
error = drv->probe(gio_dev, match);
if (error)
gio_dev_put(gio_dev);
return error;
}
static int gio_device_remove(struct device *dev)
{
struct gio_device *gio_dev = to_gio_device(dev);
struct gio_driver *drv = to_gio_driver(dev->driver);
if (dev->driver && drv->remove)
drv->remove(gio_dev);
return 0;
}
static void gio_device_shutdown(struct device *dev)
{
struct gio_device *gio_dev = to_gio_device(dev);
struct gio_driver *drv = to_gio_driver(dev->driver);
if (dev->driver && drv->shutdown)
drv->shutdown(gio_dev);
}
static ssize_t modalias_show(struct device *dev, struct device_attribute *a,
char *buf)
{
struct gio_device *gio_dev = to_gio_device(dev);
int len = snprintf(buf, PAGE_SIZE, "gio:%x\n", gio_dev->id.id);
return (len >= PAGE_SIZE) ? (PAGE_SIZE - 1) : len;
}
static ssize_t name_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gio_device *giodev;
giodev = to_gio_device(dev);
return sprintf(buf, "%s", giodev->name);
}
static ssize_t id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gio_device *giodev;
giodev = to_gio_device(dev);
return sprintf(buf, "%x", giodev->id.id);
}
static struct device_attribute gio_dev_attrs[] = {
__ATTR_RO(modalias),
__ATTR_RO(name),
__ATTR_RO(id),
__ATTR_NULL,
};
static int gio_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct gio_device *gio_dev = to_gio_device(dev);
add_uevent_var(env, "MODALIAS=gio:%x", gio_dev->id.id);
return 0;
}
int gio_register_driver(struct gio_driver *drv)
{
/* initialize common driver fields */
if (!drv->driver.name)
drv->driver.name = drv->name;
if (!drv->driver.owner)
drv->driver.owner = drv->owner;
drv->driver.bus = &gio_bus_type;
/* register with core */
return driver_register(&drv->driver);
}
EXPORT_SYMBOL_GPL(gio_register_driver);
void gio_unregister_driver(struct gio_driver *drv)
{
driver_unregister(&drv->driver);
}
EXPORT_SYMBOL_GPL(gio_unregister_driver);
void gio_set_master(struct gio_device *dev)
{
u32 tmp = sgimc->giopar;
switch (dev->slotno) {
case 0:
tmp |= SGIMC_GIOPAR_MASTERGFX;
break;
case 1:
tmp |= SGIMC_GIOPAR_MASTEREXP0;
break;
case 2:
tmp |= SGIMC_GIOPAR_MASTEREXP1;
break;
}
sgimc->giopar = tmp;
}
EXPORT_SYMBOL_GPL(gio_set_master);
void ip22_gio_set_64bit(int slotno)
{
u32 tmp = sgimc->giopar;
switch (slotno) {
case 0:
tmp |= SGIMC_GIOPAR_GFX64;
break;
case 1:
tmp |= SGIMC_GIOPAR_EXP064;
break;
case 2:
tmp |= SGIMC_GIOPAR_EXP164;
break;
}
sgimc->giopar = tmp;
}
static int ip22_gio_id(unsigned long addr, u32 *res)
{
u8 tmp8;
u8 tmp16;
u32 tmp32;
u8 *ptr8;
u16 *ptr16;
u32 *ptr32;
ptr32 = (void *)CKSEG1ADDR(addr);
if (!get_dbe(tmp32, ptr32)) {
/*
* We got no DBE, but this doesn't mean anything.
* If GIO is pipelined (which can't be disabled
* for GFX slot) we don't get a DBE, but we see
* the transfer size as data. So we do an 8bit
* and a 16bit access and check whether the common
* data matches
*/
ptr8 = (void *)CKSEG1ADDR(addr + 3);
if (get_dbe(tmp8, ptr8)) {
/*
* 32bit access worked, but 8bit doesn't
* so we don't see phantom reads on
* a pipelined bus, but a real card which
* doesn't support 8 bit reads
*/
*res = tmp32;
return 1;
}
ptr16 = (void *)CKSEG1ADDR(addr + 2);
get_dbe(tmp16, ptr16);
if (tmp8 == (tmp16 & 0xff) &&
tmp8 == (tmp32 & 0xff) &&
tmp16 == (tmp32 & 0xffff)) {
*res = tmp32;
return 1;
}
}
return 0; /* nothing here */
}
#define HQ2_MYSTERY_OFFS 0x6A07C
#define NEWPORT_USTATUS_OFFS 0xF133C
static int ip22_is_gr2(unsigned long addr)
{
u32 tmp;
u32 *ptr;
/* HQ2 only allows 32bit accesses */
ptr = (void *)CKSEG1ADDR(addr + HQ2_MYSTERY_OFFS);
if (!get_dbe(tmp, ptr)) {
if (tmp == 0xdeadbeef)
return 1;
}
return 0;
}
static void ip22_check_gio(int slotno, unsigned long addr, int irq)
{
const char *name = "Unknown";
struct gio_device *gio_dev;
u32 tmp;
__u8 id;
int i;
/* first look for GR2/GR3 by checking mystery register */
if (ip22_is_gr2(addr))
tmp = 0x7f;
else {
if (!ip22_gio_id(addr, &tmp)) {
/*
* no GIO signature at start address of slot
* since Newport doesn't have one, we check if
* user status register is readable
*/
if (ip22_gio_id(addr + NEWPORT_USTATUS_OFFS, &tmp))
tmp = 0x7e;
else
tmp = 0;
}
}
if (tmp) {
id = GIO_ID(tmp);
if (tmp & GIO_32BIT_ID) {
if (tmp & GIO_64BIT_IFACE)
ip22_gio_set_64bit(slotno);
}
for (i = 0; i < ARRAY_SIZE(gio_name_table); i++) {
if (id == gio_name_table[i].id) {
name = gio_name_table[i].name;
break;
}
}
printk(KERN_INFO "GIO: slot %d : %s (id %x)\n",
slotno, name, id);
gio_dev = kzalloc(sizeof *gio_dev, GFP_KERNEL);
gio_dev->name = name;
gio_dev->slotno = slotno;
gio_dev->id.id = id;
gio_dev->resource.start = addr;
gio_dev->resource.end = addr + 0x3fffff;
gio_dev->resource.flags = IORESOURCE_MEM;
gio_dev->irq = irq;
dev_set_name(&gio_dev->dev, "%d", slotno);
gio_device_register(gio_dev);
} else
printk(KERN_INFO "GIO: slot %d : Empty\n", slotno);
}
static struct bus_type gio_bus_type = {
.name = "gio",
.dev_attrs = gio_dev_attrs,
.match = gio_bus_match,
.probe = gio_device_probe,
.remove = gio_device_remove,
.shutdown = gio_device_shutdown,
.uevent = gio_device_uevent,
};
static struct resource gio_bus_resource = {
.start = GIO_SLOT_GFX_BASE,
.end = GIO_SLOT_GFX_BASE + 0x9fffff,
.name = "GIO Bus",
.flags = IORESOURCE_MEM,
};
int __init ip22_gio_init(void)
{
unsigned int pbdma __maybe_unused;
int ret;
ret = device_register(&gio_bus);
if (ret) {
put_device(&gio_bus);
return ret;
}
ret = bus_register(&gio_bus_type);
if (!ret) {
request_resource(&iomem_resource, &gio_bus_resource);
printk(KERN_INFO "GIO: Probing bus...\n");
if (ip22_is_fullhouse()) {
/* Indigo2 */
ip22_check_gio(0, GIO_SLOT_GFX_BASE, SGI_GIO_1_IRQ);
ip22_check_gio(1, GIO_SLOT_EXP0_BASE, SGI_GIO_1_IRQ);
} else {
/* Indy/Challenge S */
if (get_dbe(pbdma, (unsigned int *)&hpc3c1->pbdma[1]))
ip22_check_gio(0, GIO_SLOT_GFX_BASE,
SGI_GIO_0_IRQ);
ip22_check_gio(1, GIO_SLOT_EXP0_BASE, SGI_GIOEXP0_IRQ);
ip22_check_gio(2, GIO_SLOT_EXP1_BASE, SGI_GIOEXP1_IRQ);
}
} else
device_unregister(&gio_bus);
return ret;
}
subsys_initcall(ip22_gio_init);
| gpl-2.0 |
siminles/hw01e_cm10_kernel | drivers/hwmon/pmbus.c | 2515 | 6017 | /*
* Hardware monitoring driver for PMBus devices
*
* Copyright (c) 2010, 2011 Ericsson AB.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/i2c.h>
#include "pmbus.h"
/*
* Find sensor groups and status registers on each page.
*/
static void pmbus_find_sensor_groups(struct i2c_client *client,
struct pmbus_driver_info *info)
{
int page;
/* Sensors detected on page 0 only */
if (pmbus_check_word_register(client, 0, PMBUS_READ_VIN))
info->func[0] |= PMBUS_HAVE_VIN;
if (pmbus_check_word_register(client, 0, PMBUS_READ_VCAP))
info->func[0] |= PMBUS_HAVE_VCAP;
if (pmbus_check_word_register(client, 0, PMBUS_READ_IIN))
info->func[0] |= PMBUS_HAVE_IIN;
if (pmbus_check_word_register(client, 0, PMBUS_READ_PIN))
info->func[0] |= PMBUS_HAVE_PIN;
if (info->func[0]
&& pmbus_check_byte_register(client, 0, PMBUS_STATUS_INPUT))
info->func[0] |= PMBUS_HAVE_STATUS_INPUT;
if (pmbus_check_byte_register(client, 0, PMBUS_FAN_CONFIG_12) &&
pmbus_check_word_register(client, 0, PMBUS_READ_FAN_SPEED_1)) {
info->func[0] |= PMBUS_HAVE_FAN12;
if (pmbus_check_byte_register(client, 0, PMBUS_STATUS_FAN_12))
info->func[0] |= PMBUS_HAVE_STATUS_FAN12;
}
if (pmbus_check_byte_register(client, 0, PMBUS_FAN_CONFIG_34) &&
pmbus_check_word_register(client, 0, PMBUS_READ_FAN_SPEED_3)) {
info->func[0] |= PMBUS_HAVE_FAN34;
if (pmbus_check_byte_register(client, 0, PMBUS_STATUS_FAN_34))
info->func[0] |= PMBUS_HAVE_STATUS_FAN34;
}
if (pmbus_check_word_register(client, 0, PMBUS_READ_TEMPERATURE_1))
info->func[0] |= PMBUS_HAVE_TEMP;
if (pmbus_check_word_register(client, 0, PMBUS_READ_TEMPERATURE_2))
info->func[0] |= PMBUS_HAVE_TEMP2;
if (pmbus_check_word_register(client, 0, PMBUS_READ_TEMPERATURE_3))
info->func[0] |= PMBUS_HAVE_TEMP3;
if (info->func[0] & (PMBUS_HAVE_TEMP | PMBUS_HAVE_TEMP2
| PMBUS_HAVE_TEMP3)
&& pmbus_check_byte_register(client, 0,
PMBUS_STATUS_TEMPERATURE))
info->func[0] |= PMBUS_HAVE_STATUS_TEMP;
/* Sensors detected on all pages */
for (page = 0; page < info->pages; page++) {
if (pmbus_check_word_register(client, page, PMBUS_READ_VOUT)) {
info->func[page] |= PMBUS_HAVE_VOUT;
if (pmbus_check_byte_register(client, page,
PMBUS_STATUS_VOUT))
info->func[page] |= PMBUS_HAVE_STATUS_VOUT;
}
if (pmbus_check_word_register(client, page, PMBUS_READ_IOUT)) {
info->func[page] |= PMBUS_HAVE_IOUT;
if (pmbus_check_byte_register(client, 0,
PMBUS_STATUS_IOUT))
info->func[page] |= PMBUS_HAVE_STATUS_IOUT;
}
if (pmbus_check_word_register(client, page, PMBUS_READ_POUT))
info->func[page] |= PMBUS_HAVE_POUT;
}
}
/*
* Identify chip parameters.
*/
static int pmbus_identify(struct i2c_client *client,
struct pmbus_driver_info *info)
{
if (!info->pages) {
/*
* Check if the PAGE command is supported. If it is,
* keep setting the page number until it fails or until the
* maximum number of pages has been reached. Assume that
* this is the number of pages supported by the chip.
*/
if (pmbus_check_byte_register(client, 0, PMBUS_PAGE)) {
int page;
for (page = 1; page < PMBUS_PAGES; page++) {
if (pmbus_set_page(client, page) < 0)
break;
}
pmbus_set_page(client, 0);
info->pages = page;
} else {
info->pages = 1;
}
}
/*
* We should check if the COEFFICIENTS register is supported.
* If it is, and the chip is configured for direct mode, we can read
* the coefficients from the chip, one set per group of sensor
* registers.
*
* To do this, we will need access to a chip which actually supports the
* COEFFICIENTS command, since the command is too complex to implement
* without testing it.
*/
/* Try to find sensor groups */
pmbus_find_sensor_groups(client, info);
return 0;
}
static int pmbus_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pmbus_driver_info *info;
int ret;
info = kzalloc(sizeof(struct pmbus_driver_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->pages = id->driver_data;
info->identify = pmbus_identify;
ret = pmbus_do_probe(client, id, info);
if (ret < 0)
goto out;
return 0;
out:
kfree(info);
return ret;
}
static int pmbus_remove(struct i2c_client *client)
{
int ret;
const struct pmbus_driver_info *info;
info = pmbus_get_driver_info(client);
ret = pmbus_do_remove(client);
kfree(info);
return ret;
}
/*
* Use driver_data to set the number of pages supported by the chip.
*/
static const struct i2c_device_id pmbus_id[] = {
{"bmr450", 1},
{"bmr451", 1},
{"bmr453", 1},
{"bmr454", 1},
{"ltc2978", 8},
{"pmbus", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, pmbus_id);
/* This is the driver that will be inserted */
static struct i2c_driver pmbus_driver = {
.driver = {
.name = "pmbus",
},
.probe = pmbus_probe,
.remove = pmbus_remove,
.id_table = pmbus_id,
};
static int __init pmbus_init(void)
{
return i2c_add_driver(&pmbus_driver);
}
static void __exit pmbus_exit(void)
{
i2c_del_driver(&pmbus_driver);
}
MODULE_AUTHOR("Guenter Roeck");
MODULE_DESCRIPTION("Generic PMBus driver");
MODULE_LICENSE("GPL");
module_init(pmbus_init);
module_exit(pmbus_exit);
| gpl-2.0 |
blindi/LameSung-Kernel | drivers/net/wireless/ath/carl9170/led.c | 2771 | 4989 | /*
* Atheros CARL9170 driver
*
* LED handling
*
* Copyright 2008, Johannes Berg <johannes@sipsolutions.net>
* Copyright 2009, 2010, Christian Lamparer <chunkeey@googlemail.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; see the file COPYING. If not, see
* http://www.gnu.org/licenses/.
*
* This file incorporates work covered by the following copyright and
* permission notice:
* Copyright (c) 2007-2008 Atheros Communications, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "carl9170.h"
#include "cmd.h"
int carl9170_led_set_state(struct ar9170 *ar, const u32 led_state)
{
return carl9170_write_reg(ar, AR9170_GPIO_REG_PORT_DATA, led_state);
}
int carl9170_led_init(struct ar9170 *ar)
{
int err;
/* disable LEDs */
/* GPIO [0/1 mode: output, 2/3: input] */
err = carl9170_write_reg(ar, AR9170_GPIO_REG_PORT_TYPE, 3);
if (err)
goto out;
/* GPIO 0/1 value: off */
err = carl9170_led_set_state(ar, 0);
out:
return err;
}
#ifdef CONFIG_CARL9170_LEDS
static void carl9170_led_update(struct work_struct *work)
{
struct ar9170 *ar = container_of(work, struct ar9170, led_work.work);
int i, tmp = 300, blink_delay = 1000;
u32 led_val = 0;
bool rerun = false;
if (!IS_ACCEPTING_CMD(ar))
return;
mutex_lock(&ar->mutex);
for (i = 0; i < AR9170_NUM_LEDS; i++) {
if (ar->leds[i].registered) {
if (ar->leds[i].last_state ||
ar->leds[i].toggled) {
if (ar->leds[i].toggled)
tmp = 70 + 200 / (ar->leds[i].toggled);
if (tmp < blink_delay)
blink_delay = tmp;
led_val |= 1 << i;
ar->leds[i].toggled = 0;
rerun = true;
}
}
}
carl9170_led_set_state(ar, led_val);
mutex_unlock(&ar->mutex);
if (!rerun)
return;
ieee80211_queue_delayed_work(ar->hw,
&ar->led_work,
msecs_to_jiffies(blink_delay));
}
static void carl9170_led_set_brightness(struct led_classdev *led,
enum led_brightness brightness)
{
struct carl9170_led *arl = container_of(led, struct carl9170_led, l);
struct ar9170 *ar = arl->ar;
if (!arl->registered)
return;
if (arl->last_state != !!brightness) {
arl->toggled++;
arl->last_state = !!brightness;
}
if (likely(IS_ACCEPTING_CMD(ar) && arl->toggled))
ieee80211_queue_delayed_work(ar->hw, &ar->led_work, HZ/10);
}
static int carl9170_led_register_led(struct ar9170 *ar, int i, char *name,
char *trigger)
{
int err;
snprintf(ar->leds[i].name, sizeof(ar->leds[i].name),
"carl9170-%s::%s", wiphy_name(ar->hw->wiphy), name);
ar->leds[i].ar = ar;
ar->leds[i].l.name = ar->leds[i].name;
ar->leds[i].l.brightness_set = carl9170_led_set_brightness;
ar->leds[i].l.brightness = 0;
ar->leds[i].l.default_trigger = trigger;
err = led_classdev_register(wiphy_dev(ar->hw->wiphy),
&ar->leds[i].l);
if (err) {
wiphy_err(ar->hw->wiphy, "failed to register %s LED (%d).\n",
ar->leds[i].name, err);
} else {
ar->leds[i].registered = true;
}
return err;
}
void carl9170_led_unregister(struct ar9170 *ar)
{
int i;
for (i = 0; i < AR9170_NUM_LEDS; i++)
if (ar->leds[i].registered) {
led_classdev_unregister(&ar->leds[i].l);
ar->leds[i].registered = false;
ar->leds[i].toggled = 0;
}
cancel_delayed_work_sync(&ar->led_work);
}
int carl9170_led_register(struct ar9170 *ar)
{
int err;
INIT_DELAYED_WORK(&ar->led_work, carl9170_led_update);
err = carl9170_led_register_led(ar, 0, "tx",
ieee80211_get_tx_led_name(ar->hw));
if (err)
goto fail;
if (ar->features & CARL9170_ONE_LED)
return 0;
err = carl9170_led_register_led(ar, 1, "assoc",
ieee80211_get_assoc_led_name(ar->hw));
if (err)
goto fail;
return 0;
fail:
carl9170_led_unregister(ar);
return err;
}
#endif /* CONFIG_CARL9170_LEDS */
| gpl-2.0 |
stariver/qt210-kernel | drivers/net/wireless/ath/carl9170/led.c | 2771 | 4989 | /*
* Atheros CARL9170 driver
*
* LED handling
*
* Copyright 2008, Johannes Berg <johannes@sipsolutions.net>
* Copyright 2009, 2010, Christian Lamparer <chunkeey@googlemail.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; see the file COPYING. If not, see
* http://www.gnu.org/licenses/.
*
* This file incorporates work covered by the following copyright and
* permission notice:
* Copyright (c) 2007-2008 Atheros Communications, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "carl9170.h"
#include "cmd.h"
int carl9170_led_set_state(struct ar9170 *ar, const u32 led_state)
{
return carl9170_write_reg(ar, AR9170_GPIO_REG_PORT_DATA, led_state);
}
int carl9170_led_init(struct ar9170 *ar)
{
int err;
/* disable LEDs */
/* GPIO [0/1 mode: output, 2/3: input] */
err = carl9170_write_reg(ar, AR9170_GPIO_REG_PORT_TYPE, 3);
if (err)
goto out;
/* GPIO 0/1 value: off */
err = carl9170_led_set_state(ar, 0);
out:
return err;
}
#ifdef CONFIG_CARL9170_LEDS
static void carl9170_led_update(struct work_struct *work)
{
struct ar9170 *ar = container_of(work, struct ar9170, led_work.work);
int i, tmp = 300, blink_delay = 1000;
u32 led_val = 0;
bool rerun = false;
if (!IS_ACCEPTING_CMD(ar))
return;
mutex_lock(&ar->mutex);
for (i = 0; i < AR9170_NUM_LEDS; i++) {
if (ar->leds[i].registered) {
if (ar->leds[i].last_state ||
ar->leds[i].toggled) {
if (ar->leds[i].toggled)
tmp = 70 + 200 / (ar->leds[i].toggled);
if (tmp < blink_delay)
blink_delay = tmp;
led_val |= 1 << i;
ar->leds[i].toggled = 0;
rerun = true;
}
}
}
carl9170_led_set_state(ar, led_val);
mutex_unlock(&ar->mutex);
if (!rerun)
return;
ieee80211_queue_delayed_work(ar->hw,
&ar->led_work,
msecs_to_jiffies(blink_delay));
}
static void carl9170_led_set_brightness(struct led_classdev *led,
enum led_brightness brightness)
{
struct carl9170_led *arl = container_of(led, struct carl9170_led, l);
struct ar9170 *ar = arl->ar;
if (!arl->registered)
return;
if (arl->last_state != !!brightness) {
arl->toggled++;
arl->last_state = !!brightness;
}
if (likely(IS_ACCEPTING_CMD(ar) && arl->toggled))
ieee80211_queue_delayed_work(ar->hw, &ar->led_work, HZ/10);
}
static int carl9170_led_register_led(struct ar9170 *ar, int i, char *name,
char *trigger)
{
int err;
snprintf(ar->leds[i].name, sizeof(ar->leds[i].name),
"carl9170-%s::%s", wiphy_name(ar->hw->wiphy), name);
ar->leds[i].ar = ar;
ar->leds[i].l.name = ar->leds[i].name;
ar->leds[i].l.brightness_set = carl9170_led_set_brightness;
ar->leds[i].l.brightness = 0;
ar->leds[i].l.default_trigger = trigger;
err = led_classdev_register(wiphy_dev(ar->hw->wiphy),
&ar->leds[i].l);
if (err) {
wiphy_err(ar->hw->wiphy, "failed to register %s LED (%d).\n",
ar->leds[i].name, err);
} else {
ar->leds[i].registered = true;
}
return err;
}
void carl9170_led_unregister(struct ar9170 *ar)
{
int i;
for (i = 0; i < AR9170_NUM_LEDS; i++)
if (ar->leds[i].registered) {
led_classdev_unregister(&ar->leds[i].l);
ar->leds[i].registered = false;
ar->leds[i].toggled = 0;
}
cancel_delayed_work_sync(&ar->led_work);
}
int carl9170_led_register(struct ar9170 *ar)
{
int err;
INIT_DELAYED_WORK(&ar->led_work, carl9170_led_update);
err = carl9170_led_register_led(ar, 0, "tx",
ieee80211_get_tx_led_name(ar->hw));
if (err)
goto fail;
if (ar->features & CARL9170_ONE_LED)
return 0;
err = carl9170_led_register_led(ar, 1, "assoc",
ieee80211_get_assoc_led_name(ar->hw));
if (err)
goto fail;
return 0;
fail:
carl9170_led_unregister(ar);
return err;
}
#endif /* CONFIG_CARL9170_LEDS */
| gpl-2.0 |
sorinstanila/kernel_msm_kk | drivers/net/wireless/mwifiex/sta_ioctl.c | 3283 | 41766 | /*
* Marvell Wireless LAN device driver: functions for station ioctl
*
* 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 "cfg80211.h"
/*
* Copies the multicast address list from device to driver.
*
* This function does not validate the destination memory for
* size, and the calling function must ensure enough memory is
* available.
*/
int mwifiex_copy_mcast_addr(struct mwifiex_multicast_list *mlist,
struct net_device *dev)
{
int i = 0;
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, dev)
memcpy(&mlist->mac_list[i++], ha->addr, ETH_ALEN);
return i;
}
/*
* Wait queue completion handler.
*
* This function waits on a cmd wait queue. It also cancels the pending
* request after waking up, in case of errors.
*/
int mwifiex_wait_queue_complete(struct mwifiex_adapter *adapter)
{
bool cancel_flag = false;
int status;
struct cmd_ctrl_node *cmd_queued;
if (!adapter->cmd_queued)
return 0;
cmd_queued = adapter->cmd_queued;
adapter->cmd_queued = NULL;
dev_dbg(adapter->dev, "cmd pending\n");
atomic_inc(&adapter->cmd_pending);
/* Status pending, wake up main process */
queue_work(adapter->workqueue, &adapter->main_work);
/* Wait for completion */
wait_event_interruptible(adapter->cmd_wait_q.wait,
*(cmd_queued->condition));
if (!*(cmd_queued->condition))
cancel_flag = true;
if (cancel_flag) {
mwifiex_cancel_pending_ioctl(adapter);
dev_dbg(adapter->dev, "cmd cancel\n");
}
status = adapter->cmd_wait_q.status;
adapter->cmd_wait_q.status = 0;
return status;
}
/*
* This function prepares the correct firmware command and
* issues it to set the multicast list.
*
* This function can be used to enable promiscuous mode, or enable all
* multicast packets, or to enable selective multicast.
*/
int mwifiex_request_set_multicast_list(struct mwifiex_private *priv,
struct mwifiex_multicast_list *mcast_list)
{
int ret = 0;
u16 old_pkt_filter;
old_pkt_filter = priv->curr_pkt_filter;
if (mcast_list->mode == MWIFIEX_PROMISC_MODE) {
dev_dbg(priv->adapter->dev, "info: Enable Promiscuous mode\n");
priv->curr_pkt_filter |= HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
/* Multicast */
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
if (mcast_list->mode == MWIFIEX_MULTICAST_MODE) {
dev_dbg(priv->adapter->dev,
"info: Enabling All Multicast!\n");
priv->curr_pkt_filter |=
HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
if (mcast_list->num_multicast_addr) {
dev_dbg(priv->adapter->dev,
"info: Set multicast list=%d\n",
mcast_list->num_multicast_addr);
/* Set multicast addresses to firmware */
if (old_pkt_filter == priv->curr_pkt_filter) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
} else {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
}
}
}
}
dev_dbg(priv->adapter->dev,
"info: old_pkt_filter=%#x, curr_pkt_filter=%#x\n",
old_pkt_filter, priv->curr_pkt_filter);
if (old_pkt_filter != priv->curr_pkt_filter) {
ret = mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET,
0, &priv->curr_pkt_filter);
}
return ret;
}
/*
* This function fills bss descriptor structure using provided
* information.
*/
int mwifiex_fill_new_bss_desc(struct mwifiex_private *priv,
u8 *bssid, s32 rssi, u8 *ie_buf,
size_t ie_len, u16 beacon_period,
u16 cap_info_bitmap, u8 band,
struct mwifiex_bssdescriptor *bss_desc)
{
int ret;
memcpy(bss_desc->mac_address, bssid, ETH_ALEN);
bss_desc->rssi = rssi;
bss_desc->beacon_buf = ie_buf;
bss_desc->beacon_buf_size = ie_len;
bss_desc->beacon_period = beacon_period;
bss_desc->cap_info_bitmap = cap_info_bitmap;
bss_desc->bss_band = band;
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_PRIVACY) {
dev_dbg(priv->adapter->dev, "info: InterpretIE: AP WEP enabled\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;
} else {
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;
}
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_IBSS)
bss_desc->bss_mode = NL80211_IFTYPE_ADHOC;
else
bss_desc->bss_mode = NL80211_IFTYPE_STATION;
ret = mwifiex_update_bss_desc_with_ie(priv->adapter, bss_desc,
ie_buf, ie_len);
return ret;
}
/*
* In Ad-Hoc mode, the IBSS is created if not found in scan list.
* In both Ad-Hoc and infra mode, an deauthentication is performed
* first.
*/
int mwifiex_bss_start(struct mwifiex_private *priv, struct cfg80211_bss *bss,
struct cfg80211_ssid *req_ssid)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc = NULL;
u8 *beacon_ie = NULL;
priv->scan_block = false;
if (bss) {
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor),
GFP_KERNEL);
if (!bss_desc) {
dev_err(priv->adapter->dev, " failed to alloc bss_desc\n");
return -ENOMEM;
}
beacon_ie = kmemdup(bss->information_elements,
bss->len_beacon_ies, GFP_KERNEL);
if (!beacon_ie) {
kfree(bss_desc);
dev_err(priv->adapter->dev, " failed to alloc beacon_ie\n");
return -ENOMEM;
}
ret = mwifiex_fill_new_bss_desc(priv, bss->bssid, bss->signal,
beacon_ie, bss->len_beacon_ies,
bss->beacon_interval,
bss->capability,
*(u8 *)bss->priv, bss_desc);
if (ret)
goto done;
}
if (priv->bss_mode == NL80211_IFTYPE_STATION) {
/* Infra mode */
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (ret)
goto done;
dev_dbg(adapter->dev, "info: SSID found in scan list ... "
"associating...\n");
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
/* Clear any past association response stored for
* application retrieval */
priv->assoc_rsp_size = 0;
ret = mwifiex_associate(priv, bss_desc);
/* If auth type is auto and association fails using open mode,
* try to connect using shared mode */
if (ret == WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG &&
priv->sec_info.is_authtype_auto &&
priv->sec_info.wep_enabled) {
priv->sec_info.authentication_mode =
NL80211_AUTHTYPE_SHARED_KEY;
ret = mwifiex_associate(priv, bss_desc);
}
if (bss)
cfg80211_put_bss(bss);
} else {
/* Adhoc mode */
/* If the requested SSID matches current SSID, return */
if (bss_desc && bss_desc->ssid.ssid_len &&
(!mwifiex_ssid_cmp(&priv->curr_bss_params.bss_descriptor.
ssid, &bss_desc->ssid))) {
kfree(bss_desc);
kfree(beacon_ie);
return 0;
}
/* Exit Adhoc mode first */
dev_dbg(adapter->dev, "info: Sending Adhoc Stop\n");
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
priv->adhoc_is_link_sensed = false;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
if (!ret) {
dev_dbg(adapter->dev, "info: network found in scan"
" list. Joining...\n");
ret = mwifiex_adhoc_join(priv, bss_desc);
if (bss)
cfg80211_put_bss(bss);
} else {
dev_dbg(adapter->dev, "info: Network not found in "
"the list, creating adhoc with ssid = %s\n",
req_ssid->ssid);
ret = mwifiex_adhoc_start(priv, req_ssid);
}
}
done:
kfree(bss_desc);
kfree(beacon_ie);
return ret;
}
/*
* IOCTL request handler to set host sleep configuration.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_set_hs_params(struct mwifiex_private *priv, u16 action,
int cmd_type, struct mwifiex_ds_hs_cfg *hs_cfg)
{
struct mwifiex_adapter *adapter = priv->adapter;
int status = 0;
u32 prev_cond = 0;
if (!hs_cfg)
return -ENOMEM;
switch (action) {
case HostCmd_ACT_GEN_SET:
if (adapter->pps_uapsd_mode) {
dev_dbg(adapter->dev, "info: Host Sleep IOCTL"
" is blocked in UAPSD/PPS mode\n");
status = -1;
break;
}
if (hs_cfg->is_invoke_hostcmd) {
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL) {
if (!adapter->is_hs_configured)
/* Already cancelled */
break;
/* Save previous condition */
prev_cond = le32_to_cpu(adapter->hs_cfg
.conditions);
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
} else if (hs_cfg->conditions) {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
if (hs_cfg->gap)
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
} else if (adapter->hs_cfg.conditions
== cpu_to_le32(HOST_SLEEP_CFG_CANCEL)) {
/* Return failure if no parameters for HS
enable */
status = -1;
break;
}
if (cmd_type == MWIFIEX_SYNC_CMD)
status = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
else
status = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL)
/* Restore previous condition */
adapter->hs_cfg.conditions =
cpu_to_le32(prev_cond);
} else {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
}
break;
case HostCmd_ACT_GEN_GET:
hs_cfg->conditions = le32_to_cpu(adapter->hs_cfg.conditions);
hs_cfg->gpio = adapter->hs_cfg.gpio;
hs_cfg->gap = adapter->hs_cfg.gap;
break;
default:
status = -1;
break;
}
return status;
}
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_cancel_hs(struct mwifiex_private *priv, int cmd_type)
{
struct mwifiex_ds_hs_cfg hscfg;
hscfg.conditions = HOST_SLEEP_CFG_CANCEL;
hscfg.is_invoke_hostcmd = true;
return mwifiex_set_hs_params(priv, HostCmd_ACT_GEN_SET,
cmd_type, &hscfg);
}
EXPORT_SYMBOL_GPL(mwifiex_cancel_hs);
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_enable_hs(struct mwifiex_adapter *adapter)
{
struct mwifiex_ds_hs_cfg hscfg;
if (adapter->hs_activated) {
dev_dbg(adapter->dev, "cmd: HS Already actived\n");
return true;
}
adapter->hs_activate_wait_q_woken = false;
memset(&hscfg, 0, sizeof(struct mwifiex_ds_hs_cfg));
hscfg.is_invoke_hostcmd = true;
if (mwifiex_set_hs_params(mwifiex_get_priv(adapter,
MWIFIEX_BSS_ROLE_STA),
HostCmd_ACT_GEN_SET, MWIFIEX_SYNC_CMD,
&hscfg)) {
dev_err(adapter->dev, "IOCTL request HS enable failed\n");
return false;
}
wait_event_interruptible(adapter->hs_activate_wait_q,
adapter->hs_activate_wait_q_woken);
return true;
}
EXPORT_SYMBOL_GPL(mwifiex_enable_hs);
/*
* IOCTL request handler to get BSS information.
*
* This function collates the information from different driver structures
* to send to the user.
*/
int mwifiex_get_bss_info(struct mwifiex_private *priv,
struct mwifiex_bss_info *info)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc;
if (!info)
return -1;
bss_desc = &priv->curr_bss_params.bss_descriptor;
info->bss_mode = priv->bss_mode;
memcpy(&info->ssid, &bss_desc->ssid, sizeof(struct cfg80211_ssid));
memcpy(&info->bssid, &bss_desc->mac_address, ETH_ALEN);
info->bss_chan = bss_desc->channel;
info->region_code = adapter->region_code;
info->media_connected = priv->media_connected;
info->max_power_level = priv->max_tx_power_level;
info->min_power_level = priv->min_tx_power_level;
info->adhoc_state = priv->adhoc_state;
info->bcn_nf_last = priv->bcn_nf_last;
if (priv->sec_info.wep_enabled)
info->wep_status = true;
else
info->wep_status = false;
info->is_hs_configured = adapter->is_hs_configured;
info->is_deep_sleep = adapter->is_deep_sleep;
return 0;
}
/*
* The function disables auto deep sleep mode.
*/
int mwifiex_disable_auto_ds(struct mwifiex_private *priv)
{
struct mwifiex_ds_auto_ds auto_ds;
auto_ds.auto_ds = DEEP_SLEEP_OFF;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
DIS_AUTO_PS, BITMAP_AUTO_DS, &auto_ds);
}
EXPORT_SYMBOL_GPL(mwifiex_disable_auto_ds);
/*
* IOCTL request handler to set/get active channel.
*
* This function performs validity checking on channel/frequency
* compatibility and returns failure if not valid.
*/
int mwifiex_bss_set_channel(struct mwifiex_private *priv,
struct mwifiex_chan_freq_power *chan)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_chan_freq_power *cfp = NULL;
if (!chan)
return -1;
if (!chan->channel && !chan->freq)
return -1;
if (adapter->adhoc_start_band & BAND_AN)
adapter->adhoc_start_band = BAND_G | BAND_B | BAND_GN;
else if (adapter->adhoc_start_band & BAND_A)
adapter->adhoc_start_band = BAND_G | BAND_B;
if (chan->channel) {
if (chan->channel <= MAX_CHANNEL_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, (u16) chan->channel, 0);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A,
(u16) chan->channel, 0);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
} else {
if (chan->freq <= MAX_FREQUENCY_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, 0, chan->freq);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A, 0, chan->freq);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
}
if (!cfp || !cfp->channel) {
dev_err(adapter->dev, "invalid channel/freq\n");
return -1;
}
priv->adhoc_channel = (u8) cfp->channel;
chan->channel = cfp->channel;
chan->freq = cfp->freq;
return 0;
}
/*
* IOCTL request handler to set/get Ad-Hoc channel.
*
* This function prepares the correct firmware command and
* issues it to set or get the ad-hoc channel.
*/
static int mwifiex_bss_ioctl_ibss_channel(struct mwifiex_private *priv,
u16 action, u16 *channel)
{
if (action == HostCmd_ACT_GEN_GET) {
if (!priv->media_connected) {
*channel = priv->adhoc_channel;
return 0;
}
} else {
priv->adhoc_channel = (u8) *channel;
}
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_RF_CHANNEL,
action, 0, channel);
}
/*
* IOCTL request handler to change Ad-Hoc channel.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*
* The function follows the following steps to perform the change -
* - Get current IBSS information
* - Get current channel
* - If no change is required, return
* - If not connected, change channel and return
* - If connected,
* - Disconnect
* - Change channel
* - Perform specific SSID scan with same SSID
* - Start/Join the IBSS
*/
int
mwifiex_drv_change_adhoc_chan(struct mwifiex_private *priv, u16 channel)
{
int ret;
struct mwifiex_bss_info bss_info;
struct mwifiex_ssid_bssid ssid_bssid;
u16 curr_chan = 0;
struct cfg80211_bss *bss = NULL;
struct ieee80211_channel *chan;
enum ieee80211_band band;
memset(&bss_info, 0, sizeof(bss_info));
/* Get BSS information */
if (mwifiex_get_bss_info(priv, &bss_info))
return -1;
/* Get current channel */
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_GET,
&curr_chan);
if (curr_chan == channel) {
ret = 0;
goto done;
}
dev_dbg(priv->adapter->dev, "cmd: updating channel from %d to %d\n",
curr_chan, channel);
if (!bss_info.media_connected) {
ret = 0;
goto done;
}
/* Do disonnect */
memset(&ssid_bssid, 0, ETH_ALEN);
ret = mwifiex_deauthenticate(priv, ssid_bssid.bssid);
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_SET,
&channel);
/* Do specific SSID scanning */
if (mwifiex_request_scan(priv, &bss_info.ssid)) {
ret = -1;
goto done;
}
band = mwifiex_band_to_radio_type(priv->curr_bss_params.band);
chan = __ieee80211_get_channel(priv->wdev->wiphy,
ieee80211_channel_to_frequency(channel,
band));
/* Find the BSS we want using available scan results */
bss = cfg80211_get_bss(priv->wdev->wiphy, chan, bss_info.bssid,
bss_info.ssid.ssid, bss_info.ssid.ssid_len,
WLAN_CAPABILITY_ESS, WLAN_CAPABILITY_ESS);
if (!bss)
wiphy_warn(priv->wdev->wiphy, "assoc: bss %pM not in scan results\n",
bss_info.bssid);
ret = mwifiex_bss_start(priv, bss, &bss_info.ssid);
done:
return ret;
}
/*
* IOCTL request handler to get rate.
*
* This function prepares the correct firmware command and
* issues it to get the current rate if it is connected,
* otherwise, the function returns the lowest supported rate
* for the band.
*/
static int mwifiex_rate_ioctl_get_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
rate_cfg->is_rate_auto = priv->is_data_rate_auto;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_TX_RATE_QUERY,
HostCmd_ACT_GEN_GET, 0, NULL);
}
/*
* IOCTL request handler to set rate.
*
* This function prepares the correct firmware command and
* issues it to set the current rate.
*
* The function also performs validation checking on the supplied value.
*/
static int mwifiex_rate_ioctl_set_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
u8 rates[MWIFIEX_SUPPORTED_RATES];
u8 *rate;
int rate_index, ret;
u16 bitmap_rates[MAX_BITMAP_RATES_SIZE];
u32 i;
struct mwifiex_adapter *adapter = priv->adapter;
if (rate_cfg->is_rate_auto) {
memset(bitmap_rates, 0, sizeof(bitmap_rates));
/* Support all HR/DSSS rates */
bitmap_rates[0] = 0x000F;
/* Support all OFDM rates */
bitmap_rates[1] = 0x00FF;
/* Support all HT-MCSs rate */
for (i = 0; i < ARRAY_SIZE(priv->bitmap_rates) - 3; i++)
bitmap_rates[i + 2] = 0xFFFF;
bitmap_rates[9] = 0x3FFF;
} else {
memset(rates, 0, sizeof(rates));
mwifiex_get_active_data_rates(priv, rates);
rate = rates;
for (i = 0; (rate[i] && i < MWIFIEX_SUPPORTED_RATES); i++) {
dev_dbg(adapter->dev, "info: rate=%#x wanted=%#x\n",
rate[i], rate_cfg->rate);
if ((rate[i] & 0x7f) == (rate_cfg->rate & 0x7f))
break;
}
if ((i == MWIFIEX_SUPPORTED_RATES) || !rate[i]) {
dev_err(adapter->dev, "fixed data rate %#x is out "
"of range\n", rate_cfg->rate);
return -1;
}
memset(bitmap_rates, 0, sizeof(bitmap_rates));
rate_index = mwifiex_data_rate_to_index(rate_cfg->rate);
/* Only allow b/g rates to be set */
if (rate_index >= MWIFIEX_RATE_INDEX_HRDSSS0 &&
rate_index <= MWIFIEX_RATE_INDEX_HRDSSS3) {
bitmap_rates[0] = 1 << rate_index;
} else {
rate_index -= 1; /* There is a 0x00 in the table */
if (rate_index >= MWIFIEX_RATE_INDEX_OFDM0 &&
rate_index <= MWIFIEX_RATE_INDEX_OFDM7)
bitmap_rates[1] = 1 << (rate_index -
MWIFIEX_RATE_INDEX_OFDM0);
}
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TX_RATE_CFG,
HostCmd_ACT_GEN_SET, 0, bitmap_rates);
return ret;
}
/*
* IOCTL request handler to set/get rate.
*
* This function can be used to set/get either the rate value or the
* rate index.
*/
static int mwifiex_rate_ioctl_cfg(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
int status;
if (!rate_cfg)
return -1;
if (rate_cfg->action == HostCmd_ACT_GEN_GET)
status = mwifiex_rate_ioctl_get_rate_value(priv, rate_cfg);
else
status = mwifiex_rate_ioctl_set_rate_value(priv, rate_cfg);
return status;
}
/*
* Sends IOCTL request to get the data rate.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_drv_get_data_rate(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate)
{
int ret;
memset(rate, 0, sizeof(struct mwifiex_rate_cfg));
rate->action = HostCmd_ACT_GEN_GET;
ret = mwifiex_rate_ioctl_cfg(priv, rate);
if (!ret) {
if (rate->is_rate_auto)
rate->rate = mwifiex_index_to_data_rate(priv,
priv->tx_rate,
priv->tx_htinfo
);
else
rate->rate = priv->data_rate;
} else {
ret = -1;
}
return ret;
}
/*
* IOCTL request handler to set tx power configuration.
*
* This function prepares the correct firmware command and
* issues it.
*
* For non-auto power mode, all the following power groups are set -
* - Modulation class HR/DSSS
* - Modulation class OFDM
* - Modulation class HTBW20
* - Modulation class HTBW40
*/
int mwifiex_set_tx_power(struct mwifiex_private *priv,
struct mwifiex_power_cfg *power_cfg)
{
int ret;
struct host_cmd_ds_txpwr_cfg *txp_cfg;
struct mwifiex_types_power_group *pg_tlv;
struct mwifiex_power_group *pg;
u8 *buf;
u16 dbm = 0;
if (!power_cfg->is_power_auto) {
dbm = (u16) power_cfg->power_level;
if ((dbm < priv->min_tx_power_level) ||
(dbm > priv->max_tx_power_level)) {
dev_err(priv->adapter->dev, "txpower value %d dBm"
" is out of range (%d dBm-%d dBm)\n",
dbm, priv->min_tx_power_level,
priv->max_tx_power_level);
return -1;
}
}
buf = kzalloc(MWIFIEX_SIZE_OF_CMD_BUFFER, GFP_KERNEL);
if (!buf) {
dev_err(priv->adapter->dev, "%s: failed to alloc cmd buffer\n",
__func__);
return -ENOMEM;
}
txp_cfg = (struct host_cmd_ds_txpwr_cfg *) buf;
txp_cfg->action = cpu_to_le16(HostCmd_ACT_GEN_SET);
if (!power_cfg->is_power_auto) {
txp_cfg->mode = cpu_to_le32(1);
pg_tlv = (struct mwifiex_types_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg));
pg_tlv->type = TLV_TYPE_POWER_GROUP;
pg_tlv->length = 4 * sizeof(struct mwifiex_power_group);
pg = (struct mwifiex_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg)
+ sizeof(struct mwifiex_types_power_group));
/* Power group for modulation class HR/DSSS */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x03;
pg->modulation_class = MOD_CLASS_HR_DSSS;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class OFDM */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x07;
pg->modulation_class = MOD_CLASS_OFDM;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class HTBW20 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_20;
pg++;
/* Power group for modulation class HTBW40 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_40;
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TXPWR_CFG,
HostCmd_ACT_GEN_SET, 0, buf);
kfree(buf);
return ret;
}
/*
* IOCTL request handler to get power save mode.
*
* This function prepares the correct firmware command and
* issues it.
*/
int mwifiex_drv_set_power(struct mwifiex_private *priv, u32 *ps_mode)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
u16 sub_cmd;
if (*ps_mode)
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_PSP;
else
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_CAM;
sub_cmd = (*ps_mode) ? EN_AUTO_PS : DIS_AUTO_PS;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
sub_cmd, BITMAP_STA_PS, NULL);
if ((!ret) && (sub_cmd == DIS_AUTO_PS))
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_PS_MODE_ENH,
GET_PS, 0, NULL);
return ret;
}
/*
* IOCTL request handler to set/reset WPA IE.
*
* The supplied WPA IE is treated as a opaque buffer. Only the first field
* is checked to determine WPA version. If buffer length is zero, the existing
* WPA IE is reset.
*/
static int mwifiex_set_wpa_ie_helper(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wpa_ie)) {
dev_err(priv->adapter->dev,
"failed to copy WPA IE, too big\n");
return -1;
}
memcpy(priv->wpa_ie, ie_data_ptr, ie_len);
priv->wpa_ie_len = (u8) ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set Wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
if (priv->wpa_ie[0] == WLAN_EID_WPA) {
priv->sec_info.wpa_enabled = true;
} else if (priv->wpa_ie[0] == WLAN_EID_RSN) {
priv->sec_info.wpa2_enabled = true;
} else {
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
} else {
memset(priv->wpa_ie, 0, sizeof(priv->wpa_ie));
priv->wpa_ie_len = 0;
dev_dbg(priv->adapter->dev, "info: reset wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set/reset WAPI IE.
*
* The supplied WAPI IE is treated as a opaque buffer. Only the first field
* is checked to internally enable WAPI. If buffer length is zero, the existing
* WAPI IE is reset.
*/
static int mwifiex_set_wapi_ie(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wapi_ie)) {
dev_dbg(priv->adapter->dev,
"info: failed to copy WAPI IE, too big\n");
return -1;
}
memcpy(priv->wapi_ie, ie_data_ptr, ie_len);
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
if (priv->wapi_ie[0] == WLAN_EID_BSS_AC_ACCESS_DELAY)
priv->sec_info.wapi_enabled = true;
} else {
memset(priv->wapi_ie, 0, sizeof(priv->wapi_ie));
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev,
"info: Reset wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
priv->sec_info.wapi_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set WAPI key.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_sec_ioctl_set_wapi_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, KEY_INFO_ENABLED,
encrypt_key);
}
/*
* IOCTL request handler to set WEP network key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*/
static int mwifiex_sec_ioctl_set_wep_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
struct mwifiex_wep_key *wep_key;
int index;
if (priv->wep_key_curr_index >= NUM_WEP_KEYS)
priv->wep_key_curr_index = 0;
wep_key = &priv->wep_key[priv->wep_key_curr_index];
index = encrypt_key->key_index;
if (encrypt_key->key_disable) {
priv->sec_info.wep_enabled = 0;
} else if (!encrypt_key->key_len) {
/* Copy the required key as the current key */
wep_key = &priv->wep_key[index];
if (!wep_key->key_length) {
dev_err(priv->adapter->dev,
"key not set, so cannot enable it\n");
return -1;
}
priv->wep_key_curr_index = (u16) index;
priv->sec_info.wep_enabled = 1;
} else {
wep_key = &priv->wep_key[index];
memset(wep_key, 0, sizeof(struct mwifiex_wep_key));
/* Copy the key in the driver */
memcpy(wep_key->key_material,
encrypt_key->key_material,
encrypt_key->key_len);
wep_key->key_index = index;
wep_key->key_length = encrypt_key->key_len;
priv->sec_info.wep_enabled = 1;
}
if (wep_key->key_length) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, 0, NULL);
if (ret)
return ret;
}
if (priv->sec_info.wep_enabled)
priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE;
else
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&priv->curr_pkt_filter);
return ret;
}
/*
* IOCTL request handler to set WPA key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*
* Current driver only supports key length of up to 32 bytes.
*
* This function can also be used to disable a currently set key.
*/
static int mwifiex_sec_ioctl_set_wpa_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
u8 remove_key = false;
struct host_cmd_ds_802_11_key_material *ibss_key;
/* Current driver only supports key length of up to 32 bytes */
if (encrypt_key->key_len > WLAN_MAX_KEY_LEN) {
dev_err(priv->adapter->dev, "key length too long\n");
return -1;
}
if (priv->bss_mode == NL80211_IFTYPE_ADHOC) {
/*
* IBSS/WPA-None uses only one key (Group) for both receiving
* and sending unicast and multicast packets.
*/
/* Send the key as PTK to firmware */
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
if (ret)
return ret;
ibss_key = &priv->aes_key;
memset(ibss_key, 0,
sizeof(struct host_cmd_ds_802_11_key_material));
/* Copy the key in the driver */
memcpy(ibss_key->key_param_set.key, encrypt_key->key_material,
encrypt_key->key_len);
memcpy(&ibss_key->key_param_set.key_len, &encrypt_key->key_len,
sizeof(ibss_key->key_param_set.key_len));
ibss_key->key_param_set.key_type_id
= cpu_to_le16(KEY_TYPE_ID_TKIP);
ibss_key->key_param_set.key_info = cpu_to_le16(KEY_ENABLED);
/* Send the key as GTK to firmware */
encrypt_key->key_index = ~MWIFIEX_KEY_INDEX_UNICAST;
}
if (!encrypt_key->key_index)
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
if (remove_key)
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
!KEY_INFO_ENABLED, encrypt_key);
else
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
return ret;
}
/*
* IOCTL request handler to set/get network keys.
*
* This is a generic key handling function which supports WEP, WPA
* and WAPI.
*/
static int
mwifiex_sec_ioctl_encrypt_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int status;
if (encrypt_key->is_wapi_key)
status = mwifiex_sec_ioctl_set_wapi_key(priv, encrypt_key);
else if (encrypt_key->key_len > WLAN_KEY_LEN_WEP104)
status = mwifiex_sec_ioctl_set_wpa_key(priv, encrypt_key);
else
status = mwifiex_sec_ioctl_set_wep_key(priv, encrypt_key);
return status;
}
/*
* This function returns the driver version.
*/
int
mwifiex_drv_get_driver_version(struct mwifiex_adapter *adapter, char *version,
int max_len)
{
union {
u32 l;
u8 c[4];
} ver;
char fw_ver[32];
ver.l = adapter->fw_release_number;
sprintf(fw_ver, "%u.%u.%u.p%u", ver.c[2], ver.c[1], ver.c[0], ver.c[3]);
snprintf(version, max_len, driver_version, fw_ver);
dev_dbg(adapter->dev, "info: MWIFIEX VERSION: %s\n", version);
return 0;
}
/*
* Sends IOCTL request to get signal information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_get_signal_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_signal *signal)
{
int status;
signal->selector = ALL_RSSI_INFO_MASK;
/* Signal info can be obtained only if connected */
if (!priv->media_connected) {
dev_dbg(priv->adapter->dev,
"info: Can not get signal in disconnected state\n");
return -1;
}
status = mwifiex_send_cmd_sync(priv, HostCmd_CMD_RSSI_INFO,
HostCmd_ACT_GEN_GET, 0, signal);
if (!status) {
if (signal->selector & BCN_RSSI_AVG_MASK)
priv->qual_level = signal->bcn_rssi_avg;
if (signal->selector & BCN_NF_AVG_MASK)
priv->qual_noise = signal->bcn_nf_avg;
}
return status;
}
/*
* Sends IOCTL request to set encoding parameters.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_set_encode(struct mwifiex_private *priv, const u8 *key,
int key_len, u8 key_index, int disable)
{
struct mwifiex_ds_encrypt_key encrypt_key;
memset(&encrypt_key, 0, sizeof(struct mwifiex_ds_encrypt_key));
encrypt_key.key_len = key_len;
if (!disable) {
encrypt_key.key_index = key_index;
if (key_len)
memcpy(encrypt_key.key_material, key, key_len);
} else {
encrypt_key.key_disable = true;
}
return mwifiex_sec_ioctl_encrypt_key(priv, &encrypt_key);
}
/*
* Sends IOCTL request to get extended version.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_ver_ext(struct mwifiex_private *priv)
{
struct mwifiex_ver_ext ver_ext;
memset(&ver_ext, 0, sizeof(struct host_cmd_ds_version_ext));
if (mwifiex_send_cmd_sync(priv, HostCmd_CMD_VERSION_EXT,
HostCmd_ACT_GEN_GET, 0, &ver_ext))
return -1;
return 0;
}
/*
* Sends IOCTL request to get statistics information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_stats_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_stats *log)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_GET_LOG,
HostCmd_ACT_GEN_GET, 0, log);
}
/*
* IOCTL request handler to read/write register.
*
* This function prepares the correct firmware command and
* issues it.
*
* Access to the following registers are supported -
* - MAC
* - BBP
* - RF
* - PMIC
* - CAU
*/
static int mwifiex_reg_mem_ioctl_reg_rw(struct mwifiex_private *priv,
struct mwifiex_ds_reg_rw *reg_rw,
u16 action)
{
u16 cmd_no;
switch (le32_to_cpu(reg_rw->type)) {
case MWIFIEX_REG_MAC:
cmd_no = HostCmd_CMD_MAC_REG_ACCESS;
break;
case MWIFIEX_REG_BBP:
cmd_no = HostCmd_CMD_BBP_REG_ACCESS;
break;
case MWIFIEX_REG_RF:
cmd_no = HostCmd_CMD_RF_REG_ACCESS;
break;
case MWIFIEX_REG_PMIC:
cmd_no = HostCmd_CMD_PMIC_REG_ACCESS;
break;
case MWIFIEX_REG_CAU:
cmd_no = HostCmd_CMD_CAU_REG_ACCESS;
break;
default:
return -1;
}
return mwifiex_send_cmd_sync(priv, cmd_no, action, 0, reg_rw);
}
/*
* Sends IOCTL request to write to a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_write(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 reg_value)
{
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
reg_rw.value = cpu_to_le32(reg_value);
return mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_SET);
}
/*
* Sends IOCTL request to read from a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_read(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 *value)
{
int ret;
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
ret = mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_GET);
if (ret)
goto done;
*value = le32_to_cpu(reg_rw.value);
done:
return ret;
}
/*
* Sends IOCTL request to read from EEPROM.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_eeprom_read(struct mwifiex_private *priv, u16 offset, u16 bytes,
u8 *value)
{
int ret;
struct mwifiex_ds_read_eeprom rd_eeprom;
rd_eeprom.offset = cpu_to_le16((u16) offset);
rd_eeprom.byte_count = cpu_to_le16((u16) bytes);
/* Send request to firmware */
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_EEPROM_ACCESS,
HostCmd_ACT_GEN_GET, 0, &rd_eeprom);
if (!ret)
memcpy(value, rd_eeprom.value, MAX_EEPROM_DATA);
return ret;
}
/*
* This function sets a generic IE. In addition to generic IE, it can
* also handle WPA, WPA2 and WAPI IEs.
*/
static int
mwifiex_set_gen_ie_helper(struct mwifiex_private *priv, u8 *ie_data_ptr,
u16 ie_len)
{
int ret = 0;
struct ieee_types_vendor_header *pvendor_ie;
const u8 wpa_oui[] = { 0x00, 0x50, 0xf2, 0x01 };
const u8 wps_oui[] = { 0x00, 0x50, 0xf2, 0x04 };
/* If the passed length is zero, reset the buffer */
if (!ie_len) {
priv->gen_ie_buf_len = 0;
priv->wps.session_enable = false;
return 0;
} else if (!ie_data_ptr) {
return -1;
}
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
/* Test to see if it is a WPA IE, if not, then it is a gen IE */
if (((pvendor_ie->element_id == WLAN_EID_WPA) &&
(!memcmp(pvendor_ie->oui, wpa_oui, sizeof(wpa_oui)))) ||
(pvendor_ie->element_id == WLAN_EID_RSN)) {
/* IE is a WPA/WPA2 IE so call set_wpa function */
ret = mwifiex_set_wpa_ie_helper(priv, ie_data_ptr, ie_len);
priv->wps.session_enable = false;
return ret;
} else if (pvendor_ie->element_id == WLAN_EID_BSS_AC_ACCESS_DELAY) {
/* IE is a WAPI IE so call set_wapi function */
ret = mwifiex_set_wapi_ie(priv, ie_data_ptr, ie_len);
return ret;
}
/*
* Verify that the passed length is not larger than the
* available space remaining in the buffer
*/
if (ie_len < (sizeof(priv->gen_ie_buf) - priv->gen_ie_buf_len)) {
/* Test to see if it is a WPS IE, if so, enable
* wps session flag
*/
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
if ((pvendor_ie->element_id == WLAN_EID_VENDOR_SPECIFIC) &&
(!memcmp(pvendor_ie->oui, wps_oui, sizeof(wps_oui)))) {
priv->wps.session_enable = true;
dev_dbg(priv->adapter->dev,
"info: WPS Session Enabled.\n");
}
/* Append the passed data to the end of the
genIeBuffer */
memcpy(priv->gen_ie_buf + priv->gen_ie_buf_len, ie_data_ptr,
ie_len);
/* Increment the stored buffer length by the
size passed */
priv->gen_ie_buf_len += ie_len;
} else {
/* Passed data does not fit in the remaining
buffer space */
ret = -1;
}
/* Return 0, or -1 for error case */
return ret;
}
/*
* IOCTL request handler to set/get generic IE.
*
* In addition to various generic IEs, this function can also be
* used to set the ARP filter.
*/
static int mwifiex_misc_ioctl_gen_ie(struct mwifiex_private *priv,
struct mwifiex_ds_misc_gen_ie *gen_ie,
u16 action)
{
struct mwifiex_adapter *adapter = priv->adapter;
switch (gen_ie->type) {
case MWIFIEX_IE_TYPE_GEN_IE:
if (action == HostCmd_ACT_GEN_GET) {
gen_ie->len = priv->wpa_ie_len;
memcpy(gen_ie->ie_data, priv->wpa_ie, gen_ie->len);
} else {
mwifiex_set_gen_ie_helper(priv, gen_ie->ie_data,
(u16) gen_ie->len);
}
break;
case MWIFIEX_IE_TYPE_ARP_FILTER:
memset(adapter->arp_filter, 0, sizeof(adapter->arp_filter));
if (gen_ie->len > ARP_FILTER_MAX_BUF_SIZE) {
adapter->arp_filter_size = 0;
dev_err(adapter->dev, "invalid ARP filter size\n");
return -1;
} else {
memcpy(adapter->arp_filter, gen_ie->ie_data,
gen_ie->len);
adapter->arp_filter_size = gen_ie->len;
}
break;
default:
dev_err(adapter->dev, "invalid IE type\n");
return -1;
}
return 0;
}
/*
* Sends IOCTL request to set a generic IE.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_set_gen_ie(struct mwifiex_private *priv, u8 *ie, int ie_len)
{
struct mwifiex_ds_misc_gen_ie gen_ie;
if (ie_len > IEEE_MAX_IE_SIZE)
return -EFAULT;
gen_ie.type = MWIFIEX_IE_TYPE_GEN_IE;
gen_ie.len = ie_len;
memcpy(gen_ie.ie_data, ie, ie_len);
if (mwifiex_misc_ioctl_gen_ie(priv, &gen_ie, HostCmd_ACT_GEN_SET))
return -EFAULT;
return 0;
}
| gpl-2.0 |
ivanich/senny_kernel-3.4 | fs/ocfs2/extent_map.c | 3795 | 23792 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* extent_map.c
*
* Block/Cluster mapping functions
*
* Copyright (C) 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License, version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/fiemap.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "inode.h"
#include "super.h"
#include "symlink.h"
#include "ocfs2_trace.h"
#include "buffer_head_io.h"
/*
* The extent caching implementation is intentionally trivial.
*
* We only cache a small number of extents stored directly on the
* inode, so linear order operations are acceptable. If we ever want
* to increase the size of the extent map, then these algorithms must
* get smarter.
*/
void ocfs2_extent_map_init(struct inode *inode)
{
struct ocfs2_inode_info *oi = OCFS2_I(inode);
oi->ip_extent_map.em_num_items = 0;
INIT_LIST_HEAD(&oi->ip_extent_map.em_list);
}
static void __ocfs2_extent_map_lookup(struct ocfs2_extent_map *em,
unsigned int cpos,
struct ocfs2_extent_map_item **ret_emi)
{
unsigned int range;
struct ocfs2_extent_map_item *emi;
*ret_emi = NULL;
list_for_each_entry(emi, &em->em_list, ei_list) {
range = emi->ei_cpos + emi->ei_clusters;
if (cpos >= emi->ei_cpos && cpos < range) {
list_move(&emi->ei_list, &em->em_list);
*ret_emi = emi;
break;
}
}
}
static int ocfs2_extent_map_lookup(struct inode *inode, unsigned int cpos,
unsigned int *phys, unsigned int *len,
unsigned int *flags)
{
unsigned int coff;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_extent_map_item *emi;
spin_lock(&oi->ip_lock);
__ocfs2_extent_map_lookup(&oi->ip_extent_map, cpos, &emi);
if (emi) {
coff = cpos - emi->ei_cpos;
*phys = emi->ei_phys + coff;
if (len)
*len = emi->ei_clusters - coff;
if (flags)
*flags = emi->ei_flags;
}
spin_unlock(&oi->ip_lock);
if (emi == NULL)
return -ENOENT;
return 0;
}
/*
* Forget about all clusters equal to or greater than cpos.
*/
void ocfs2_extent_map_trunc(struct inode *inode, unsigned int cpos)
{
struct ocfs2_extent_map_item *emi, *n;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_extent_map *em = &oi->ip_extent_map;
LIST_HEAD(tmp_list);
unsigned int range;
spin_lock(&oi->ip_lock);
list_for_each_entry_safe(emi, n, &em->em_list, ei_list) {
if (emi->ei_cpos >= cpos) {
/* Full truncate of this record. */
list_move(&emi->ei_list, &tmp_list);
BUG_ON(em->em_num_items == 0);
em->em_num_items--;
continue;
}
range = emi->ei_cpos + emi->ei_clusters;
if (range > cpos) {
/* Partial truncate */
emi->ei_clusters = cpos - emi->ei_cpos;
}
}
spin_unlock(&oi->ip_lock);
list_for_each_entry_safe(emi, n, &tmp_list, ei_list) {
list_del(&emi->ei_list);
kfree(emi);
}
}
/*
* Is any part of emi2 contained within emi1
*/
static int ocfs2_ei_is_contained(struct ocfs2_extent_map_item *emi1,
struct ocfs2_extent_map_item *emi2)
{
unsigned int range1, range2;
/*
* Check if logical start of emi2 is inside emi1
*/
range1 = emi1->ei_cpos + emi1->ei_clusters;
if (emi2->ei_cpos >= emi1->ei_cpos && emi2->ei_cpos < range1)
return 1;
/*
* Check if logical end of emi2 is inside emi1
*/
range2 = emi2->ei_cpos + emi2->ei_clusters;
if (range2 > emi1->ei_cpos && range2 <= range1)
return 1;
return 0;
}
static void ocfs2_copy_emi_fields(struct ocfs2_extent_map_item *dest,
struct ocfs2_extent_map_item *src)
{
dest->ei_cpos = src->ei_cpos;
dest->ei_phys = src->ei_phys;
dest->ei_clusters = src->ei_clusters;
dest->ei_flags = src->ei_flags;
}
/*
* Try to merge emi with ins. Returns 1 if merge succeeds, zero
* otherwise.
*/
static int ocfs2_try_to_merge_extent_map(struct ocfs2_extent_map_item *emi,
struct ocfs2_extent_map_item *ins)
{
/*
* Handle contiguousness
*/
if (ins->ei_phys == (emi->ei_phys + emi->ei_clusters) &&
ins->ei_cpos == (emi->ei_cpos + emi->ei_clusters) &&
ins->ei_flags == emi->ei_flags) {
emi->ei_clusters += ins->ei_clusters;
return 1;
} else if ((ins->ei_phys + ins->ei_clusters) == emi->ei_phys &&
(ins->ei_cpos + ins->ei_clusters) == emi->ei_cpos &&
ins->ei_flags == emi->ei_flags) {
emi->ei_phys = ins->ei_phys;
emi->ei_cpos = ins->ei_cpos;
emi->ei_clusters += ins->ei_clusters;
return 1;
}
/*
* Overlapping extents - this shouldn't happen unless we've
* split an extent to change it's flags. That is exceedingly
* rare, so there's no sense in trying to optimize it yet.
*/
if (ocfs2_ei_is_contained(emi, ins) ||
ocfs2_ei_is_contained(ins, emi)) {
ocfs2_copy_emi_fields(emi, ins);
return 1;
}
/* No merge was possible. */
return 0;
}
/*
* In order to reduce complexity on the caller, this insert function
* is intentionally liberal in what it will accept.
*
* The only rule is that the truncate call *must* be used whenever
* records have been deleted. This avoids inserting overlapping
* records with different physical mappings.
*/
void ocfs2_extent_map_insert_rec(struct inode *inode,
struct ocfs2_extent_rec *rec)
{
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_extent_map *em = &oi->ip_extent_map;
struct ocfs2_extent_map_item *emi, *new_emi = NULL;
struct ocfs2_extent_map_item ins;
ins.ei_cpos = le32_to_cpu(rec->e_cpos);
ins.ei_phys = ocfs2_blocks_to_clusters(inode->i_sb,
le64_to_cpu(rec->e_blkno));
ins.ei_clusters = le16_to_cpu(rec->e_leaf_clusters);
ins.ei_flags = rec->e_flags;
search:
spin_lock(&oi->ip_lock);
list_for_each_entry(emi, &em->em_list, ei_list) {
if (ocfs2_try_to_merge_extent_map(emi, &ins)) {
list_move(&emi->ei_list, &em->em_list);
spin_unlock(&oi->ip_lock);
goto out;
}
}
/*
* No item could be merged.
*
* Either allocate and add a new item, or overwrite the last recently
* inserted.
*/
if (em->em_num_items < OCFS2_MAX_EXTENT_MAP_ITEMS) {
if (new_emi == NULL) {
spin_unlock(&oi->ip_lock);
new_emi = kmalloc(sizeof(*new_emi), GFP_NOFS);
if (new_emi == NULL)
goto out;
goto search;
}
ocfs2_copy_emi_fields(new_emi, &ins);
list_add(&new_emi->ei_list, &em->em_list);
em->em_num_items++;
new_emi = NULL;
} else {
BUG_ON(list_empty(&em->em_list) || em->em_num_items == 0);
emi = list_entry(em->em_list.prev,
struct ocfs2_extent_map_item, ei_list);
list_move(&emi->ei_list, &em->em_list);
ocfs2_copy_emi_fields(emi, &ins);
}
spin_unlock(&oi->ip_lock);
out:
if (new_emi)
kfree(new_emi);
}
static int ocfs2_last_eb_is_empty(struct inode *inode,
struct ocfs2_dinode *di)
{
int ret, next_free;
u64 last_eb_blk = le64_to_cpu(di->i_last_eb_blk);
struct buffer_head *eb_bh = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
ret = ocfs2_read_extent_block(INODE_CACHE(inode), last_eb_blk, &eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
if (el->l_tree_depth) {
ocfs2_error(inode->i_sb,
"Inode %lu has non zero tree depth in "
"leaf block %llu\n", inode->i_ino,
(unsigned long long)eb_bh->b_blocknr);
ret = -EROFS;
goto out;
}
next_free = le16_to_cpu(el->l_next_free_rec);
if (next_free == 0 ||
(next_free == 1 && ocfs2_is_empty_extent(&el->l_recs[0])))
ret = 1;
out:
brelse(eb_bh);
return ret;
}
/*
* Return the 1st index within el which contains an extent start
* larger than v_cluster.
*/
static int ocfs2_search_for_hole_index(struct ocfs2_extent_list *el,
u32 v_cluster)
{
int i;
struct ocfs2_extent_rec *rec;
for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
rec = &el->l_recs[i];
if (v_cluster < le32_to_cpu(rec->e_cpos))
break;
}
return i;
}
/*
* Figure out the size of a hole which starts at v_cluster within the given
* extent list.
*
* If there is no more allocation past v_cluster, we return the maximum
* cluster size minus v_cluster.
*
* If we have in-inode extents, then el points to the dinode list and
* eb_bh is NULL. Otherwise, eb_bh should point to the extent block
* containing el.
*/
int ocfs2_figure_hole_clusters(struct ocfs2_caching_info *ci,
struct ocfs2_extent_list *el,
struct buffer_head *eb_bh,
u32 v_cluster,
u32 *num_clusters)
{
int ret, i;
struct buffer_head *next_eb_bh = NULL;
struct ocfs2_extent_block *eb, *next_eb;
i = ocfs2_search_for_hole_index(el, v_cluster);
if (i == le16_to_cpu(el->l_next_free_rec) && eb_bh) {
eb = (struct ocfs2_extent_block *)eb_bh->b_data;
/*
* Check the next leaf for any extents.
*/
if (le64_to_cpu(eb->h_next_leaf_blk) == 0ULL)
goto no_more_extents;
ret = ocfs2_read_extent_block(ci,
le64_to_cpu(eb->h_next_leaf_blk),
&next_eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
next_eb = (struct ocfs2_extent_block *)next_eb_bh->b_data;
el = &next_eb->h_list;
i = ocfs2_search_for_hole_index(el, v_cluster);
}
no_more_extents:
if (i == le16_to_cpu(el->l_next_free_rec)) {
/*
* We're at the end of our existing allocation. Just
* return the maximum number of clusters we could
* possibly allocate.
*/
*num_clusters = UINT_MAX - v_cluster;
} else {
*num_clusters = le32_to_cpu(el->l_recs[i].e_cpos) - v_cluster;
}
ret = 0;
out:
brelse(next_eb_bh);
return ret;
}
static int ocfs2_get_clusters_nocache(struct inode *inode,
struct buffer_head *di_bh,
u32 v_cluster, unsigned int *hole_len,
struct ocfs2_extent_rec *ret_rec,
unsigned int *is_last)
{
int i, ret, tree_height, len;
struct ocfs2_dinode *di;
struct ocfs2_extent_block *uninitialized_var(eb);
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
struct buffer_head *eb_bh = NULL;
memset(ret_rec, 0, sizeof(*ret_rec));
if (is_last)
*is_last = 0;
di = (struct ocfs2_dinode *) di_bh->b_data;
el = &di->id2.i_list;
tree_height = le16_to_cpu(el->l_tree_depth);
if (tree_height > 0) {
ret = ocfs2_find_leaf(INODE_CACHE(inode), el, v_cluster,
&eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
if (el->l_tree_depth) {
ocfs2_error(inode->i_sb,
"Inode %lu has non zero tree depth in "
"leaf block %llu\n", inode->i_ino,
(unsigned long long)eb_bh->b_blocknr);
ret = -EROFS;
goto out;
}
}
i = ocfs2_search_extent_list(el, v_cluster);
if (i == -1) {
/*
* Holes can be larger than the maximum size of an
* extent, so we return their lengths in a separate
* field.
*/
if (hole_len) {
ret = ocfs2_figure_hole_clusters(INODE_CACHE(inode),
el, eb_bh,
v_cluster, &len);
if (ret) {
mlog_errno(ret);
goto out;
}
*hole_len = len;
}
goto out_hole;
}
rec = &el->l_recs[i];
BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos));
if (!rec->e_blkno) {
ocfs2_error(inode->i_sb, "Inode %lu has bad extent "
"record (%u, %u, 0)", inode->i_ino,
le32_to_cpu(rec->e_cpos),
ocfs2_rec_clusters(el, rec));
ret = -EROFS;
goto out;
}
*ret_rec = *rec;
/*
* Checking for last extent is potentially expensive - we
* might have to look at the next leaf over to see if it's
* empty.
*
* The first two checks are to see whether the caller even
* cares for this information, and if the extent is at least
* the last in it's list.
*
* If those hold true, then the extent is last if any of the
* additional conditions hold true:
* - Extent list is in-inode
* - Extent list is right-most
* - Extent list is 2nd to rightmost, with empty right-most
*/
if (is_last) {
if (i == (le16_to_cpu(el->l_next_free_rec) - 1)) {
if (tree_height == 0)
*is_last = 1;
else if (eb->h_blkno == di->i_last_eb_blk)
*is_last = 1;
else if (eb->h_next_leaf_blk == di->i_last_eb_blk) {
ret = ocfs2_last_eb_is_empty(inode, di);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
if (ret == 1)
*is_last = 1;
}
}
}
out_hole:
ret = 0;
out:
brelse(eb_bh);
return ret;
}
static void ocfs2_relative_extent_offsets(struct super_block *sb,
u32 v_cluster,
struct ocfs2_extent_rec *rec,
u32 *p_cluster, u32 *num_clusters)
{
u32 coff = v_cluster - le32_to_cpu(rec->e_cpos);
*p_cluster = ocfs2_blocks_to_clusters(sb, le64_to_cpu(rec->e_blkno));
*p_cluster = *p_cluster + coff;
if (num_clusters)
*num_clusters = le16_to_cpu(rec->e_leaf_clusters) - coff;
}
int ocfs2_xattr_get_clusters(struct inode *inode, u32 v_cluster,
u32 *p_cluster, u32 *num_clusters,
struct ocfs2_extent_list *el,
unsigned int *extent_flags)
{
int ret = 0, i;
struct buffer_head *eb_bh = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_rec *rec;
u32 coff;
if (el->l_tree_depth) {
ret = ocfs2_find_leaf(INODE_CACHE(inode), el, v_cluster,
&eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
if (el->l_tree_depth) {
ocfs2_error(inode->i_sb,
"Inode %lu has non zero tree depth in "
"xattr leaf block %llu\n", inode->i_ino,
(unsigned long long)eb_bh->b_blocknr);
ret = -EROFS;
goto out;
}
}
i = ocfs2_search_extent_list(el, v_cluster);
if (i == -1) {
ret = -EROFS;
mlog_errno(ret);
goto out;
} else {
rec = &el->l_recs[i];
BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos));
if (!rec->e_blkno) {
ocfs2_error(inode->i_sb, "Inode %lu has bad extent "
"record (%u, %u, 0) in xattr", inode->i_ino,
le32_to_cpu(rec->e_cpos),
ocfs2_rec_clusters(el, rec));
ret = -EROFS;
goto out;
}
coff = v_cluster - le32_to_cpu(rec->e_cpos);
*p_cluster = ocfs2_blocks_to_clusters(inode->i_sb,
le64_to_cpu(rec->e_blkno));
*p_cluster = *p_cluster + coff;
if (num_clusters)
*num_clusters = ocfs2_rec_clusters(el, rec) - coff;
if (extent_flags)
*extent_flags = rec->e_flags;
}
out:
if (eb_bh)
brelse(eb_bh);
return ret;
}
int ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
u32 *p_cluster, u32 *num_clusters,
unsigned int *extent_flags)
{
int ret;
unsigned int uninitialized_var(hole_len), flags = 0;
struct buffer_head *di_bh = NULL;
struct ocfs2_extent_rec rec;
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
ret = -ERANGE;
mlog_errno(ret);
goto out;
}
ret = ocfs2_extent_map_lookup(inode, v_cluster, p_cluster,
num_clusters, extent_flags);
if (ret == 0)
goto out;
ret = ocfs2_read_inode_block(inode, &di_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_get_clusters_nocache(inode, di_bh, v_cluster, &hole_len,
&rec, NULL);
if (ret) {
mlog_errno(ret);
goto out;
}
if (rec.e_blkno == 0ULL) {
/*
* A hole was found. Return some canned values that
* callers can key on. If asked for, num_clusters will
* be populated with the size of the hole.
*/
*p_cluster = 0;
if (num_clusters) {
*num_clusters = hole_len;
}
} else {
ocfs2_relative_extent_offsets(inode->i_sb, v_cluster, &rec,
p_cluster, num_clusters);
flags = rec.e_flags;
ocfs2_extent_map_insert_rec(inode, &rec);
}
if (extent_flags)
*extent_flags = flags;
out:
brelse(di_bh);
return ret;
}
/*
* This expects alloc_sem to be held. The allocation cannot change at
* all while the map is in the process of being updated.
*/
int ocfs2_extent_map_get_blocks(struct inode *inode, u64 v_blkno, u64 *p_blkno,
u64 *ret_count, unsigned int *extent_flags)
{
int ret;
int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
u32 cpos, num_clusters, p_cluster;
u64 boff = 0;
cpos = ocfs2_blocks_to_clusters(inode->i_sb, v_blkno);
ret = ocfs2_get_clusters(inode, cpos, &p_cluster, &num_clusters,
extent_flags);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* p_cluster == 0 indicates a hole.
*/
if (p_cluster) {
boff = ocfs2_clusters_to_blocks(inode->i_sb, p_cluster);
boff += (v_blkno & (u64)(bpc - 1));
}
*p_blkno = boff;
if (ret_count) {
*ret_count = ocfs2_clusters_to_blocks(inode->i_sb, num_clusters);
*ret_count -= v_blkno & (u64)(bpc - 1);
}
out:
return ret;
}
/*
* The ocfs2_fiemap_inline() may be a little bit misleading, since
* it not only handles the fiemap for inlined files, but also deals
* with the fast symlink, cause they have no difference for extent
* mapping per se.
*/
static int ocfs2_fiemap_inline(struct inode *inode, struct buffer_head *di_bh,
struct fiemap_extent_info *fieinfo,
u64 map_start)
{
int ret;
unsigned int id_count;
struct ocfs2_dinode *di;
u64 phys;
u32 flags = FIEMAP_EXTENT_DATA_INLINE|FIEMAP_EXTENT_LAST;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
di = (struct ocfs2_dinode *)di_bh->b_data;
if (ocfs2_inode_is_fast_symlink(inode))
id_count = ocfs2_fast_symlink_chars(inode->i_sb);
else
id_count = le16_to_cpu(di->id2.i_data.id_count);
if (map_start < id_count) {
phys = oi->ip_blkno << inode->i_sb->s_blocksize_bits;
if (ocfs2_inode_is_fast_symlink(inode))
phys += offsetof(struct ocfs2_dinode, id2.i_symlink);
else
phys += offsetof(struct ocfs2_dinode,
id2.i_data.id_data);
ret = fiemap_fill_next_extent(fieinfo, 0, phys, id_count,
flags);
if (ret < 0)
return ret;
}
return 0;
}
#define OCFS2_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
int ocfs2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 map_start, u64 map_len)
{
int ret, is_last;
u32 mapping_end, cpos;
unsigned int hole_size;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
u64 len_bytes, phys_bytes, virt_bytes;
struct buffer_head *di_bh = NULL;
struct ocfs2_extent_rec rec;
ret = fiemap_check_flags(fieinfo, OCFS2_FIEMAP_FLAGS);
if (ret)
return ret;
ret = ocfs2_inode_lock(inode, &di_bh, 0);
if (ret) {
mlog_errno(ret);
goto out;
}
down_read(&OCFS2_I(inode)->ip_alloc_sem);
/*
* Handle inline-data and fast symlink separately.
*/
if ((OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) ||
ocfs2_inode_is_fast_symlink(inode)) {
ret = ocfs2_fiemap_inline(inode, di_bh, fieinfo, map_start);
goto out_unlock;
}
cpos = map_start >> osb->s_clustersize_bits;
mapping_end = ocfs2_clusters_for_bytes(inode->i_sb,
map_start + map_len);
mapping_end -= cpos;
is_last = 0;
while (cpos < mapping_end && !is_last) {
u32 fe_flags;
ret = ocfs2_get_clusters_nocache(inode, di_bh, cpos,
&hole_size, &rec, &is_last);
if (ret) {
mlog_errno(ret);
goto out;
}
if (rec.e_blkno == 0ULL) {
cpos += hole_size;
continue;
}
fe_flags = 0;
if (rec.e_flags & OCFS2_EXT_UNWRITTEN)
fe_flags |= FIEMAP_EXTENT_UNWRITTEN;
if (rec.e_flags & OCFS2_EXT_REFCOUNTED)
fe_flags |= FIEMAP_EXTENT_SHARED;
if (is_last)
fe_flags |= FIEMAP_EXTENT_LAST;
len_bytes = (u64)le16_to_cpu(rec.e_leaf_clusters) << osb->s_clustersize_bits;
phys_bytes = le64_to_cpu(rec.e_blkno) << osb->sb->s_blocksize_bits;
virt_bytes = (u64)le32_to_cpu(rec.e_cpos) << osb->s_clustersize_bits;
ret = fiemap_fill_next_extent(fieinfo, virt_bytes, phys_bytes,
len_bytes, fe_flags);
if (ret)
break;
cpos = le32_to_cpu(rec.e_cpos)+ le16_to_cpu(rec.e_leaf_clusters);
}
if (ret > 0)
ret = 0;
out_unlock:
brelse(di_bh);
up_read(&OCFS2_I(inode)->ip_alloc_sem);
ocfs2_inode_unlock(inode, 0);
out:
return ret;
}
int ocfs2_seek_data_hole_offset(struct file *file, loff_t *offset, int origin)
{
struct inode *inode = file->f_mapping->host;
int ret;
unsigned int is_last = 0, is_data = 0;
u16 cs_bits = OCFS2_SB(inode->i_sb)->s_clustersize_bits;
u32 cpos, cend, clen, hole_size;
u64 extoff, extlen;
struct buffer_head *di_bh = NULL;
struct ocfs2_extent_rec rec;
BUG_ON(origin != SEEK_DATA && origin != SEEK_HOLE);
ret = ocfs2_inode_lock(inode, &di_bh, 0);
if (ret) {
mlog_errno(ret);
goto out;
}
down_read(&OCFS2_I(inode)->ip_alloc_sem);
if (*offset >= inode->i_size) {
ret = -ENXIO;
goto out_unlock;
}
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
if (origin == SEEK_HOLE)
*offset = inode->i_size;
goto out_unlock;
}
clen = 0;
cpos = *offset >> cs_bits;
cend = ocfs2_clusters_for_bytes(inode->i_sb, inode->i_size);
while (cpos < cend && !is_last) {
ret = ocfs2_get_clusters_nocache(inode, di_bh, cpos, &hole_size,
&rec, &is_last);
if (ret) {
mlog_errno(ret);
goto out_unlock;
}
extoff = cpos;
extoff <<= cs_bits;
if (rec.e_blkno == 0ULL) {
clen = hole_size;
is_data = 0;
} else {
clen = le16_to_cpu(rec.e_leaf_clusters) -
(cpos - le32_to_cpu(rec.e_cpos));
is_data = (rec.e_flags & OCFS2_EXT_UNWRITTEN) ? 0 : 1;
}
if ((!is_data && origin == SEEK_HOLE) ||
(is_data && origin == SEEK_DATA)) {
if (extoff > *offset)
*offset = extoff;
goto out_unlock;
}
if (!is_last)
cpos += clen;
}
if (origin == SEEK_HOLE) {
extoff = cpos;
extoff <<= cs_bits;
extlen = clen;
extlen <<= cs_bits;
if ((extoff + extlen) > inode->i_size)
extlen = inode->i_size - extoff;
extoff += extlen;
if (extoff > *offset)
*offset = extoff;
goto out_unlock;
}
ret = -ENXIO;
out_unlock:
brelse(di_bh);
up_read(&OCFS2_I(inode)->ip_alloc_sem);
ocfs2_inode_unlock(inode, 0);
out:
if (ret && ret != -ENXIO)
ret = -ENXIO;
return ret;
}
int ocfs2_read_virt_blocks(struct inode *inode, u64 v_block, int nr,
struct buffer_head *bhs[], int flags,
int (*validate)(struct super_block *sb,
struct buffer_head *bh))
{
int rc = 0;
u64 p_block, p_count;
int i, count, done = 0;
trace_ocfs2_read_virt_blocks(
inode, (unsigned long long)v_block, nr, bhs, flags,
validate);
if (((v_block + nr - 1) << inode->i_sb->s_blocksize_bits) >=
i_size_read(inode)) {
BUG_ON(!(flags & OCFS2_BH_READAHEAD));
goto out;
}
while (done < nr) {
down_read(&OCFS2_I(inode)->ip_alloc_sem);
rc = ocfs2_extent_map_get_blocks(inode, v_block + done,
&p_block, &p_count, NULL);
up_read(&OCFS2_I(inode)->ip_alloc_sem);
if (rc) {
mlog_errno(rc);
break;
}
if (!p_block) {
rc = -EIO;
mlog(ML_ERROR,
"Inode #%llu contains a hole at offset %llu\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno,
(unsigned long long)(v_block + done) <<
inode->i_sb->s_blocksize_bits);
break;
}
count = nr - done;
if (p_count < count)
count = p_count;
/*
* If the caller passed us bhs, they should have come
* from a previous readahead call to this function. Thus,
* they should have the right b_blocknr.
*/
for (i = 0; i < count; i++) {
if (!bhs[done + i])
continue;
BUG_ON(bhs[done + i]->b_blocknr != (p_block + i));
}
rc = ocfs2_read_blocks(INODE_CACHE(inode), p_block, count,
bhs + done, flags, validate);
if (rc) {
mlog_errno(rc);
break;
}
done += count;
}
out:
return rc;
}
| gpl-2.0 |
zaclimon/Quanta-Flo | arch/mips/sgi-ip27/ip27-smp.c | 4563 | 6109 | /*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file "COPYING" in the main directory of this
* archive for more details.
*
* Copyright (C) 2000 - 2001 by Kanoj Sarcar (kanoj@sgi.com)
* Copyright (C) 2000 - 2001 by Silicon Graphics, Inc.
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/nodemask.h>
#include <asm/page.h>
#include <asm/processor.h>
#include <asm/sn/arch.h>
#include <asm/sn/gda.h>
#include <asm/sn/intr.h>
#include <asm/sn/klconfig.h>
#include <asm/sn/launch.h>
#include <asm/sn/mapped_kernel.h>
#include <asm/sn/sn_private.h>
#include <asm/sn/types.h>
#include <asm/sn/sn0/hubpi.h>
#include <asm/sn/sn0/hubio.h>
#include <asm/sn/sn0/ip27.h>
/*
* Takes as first input the PROM assigned cpu id, and the kernel
* assigned cpu id as the second.
*/
static void alloc_cpupda(cpuid_t cpu, int cpunum)
{
cnodeid_t node = get_cpu_cnode(cpu);
nasid_t nasid = COMPACT_TO_NASID_NODEID(node);
cputonasid(cpunum) = nasid;
sn_cpu_info[cpunum].p_nodeid = node;
cputoslice(cpunum) = get_cpu_slice(cpu);
}
static nasid_t get_actual_nasid(lboard_t *brd)
{
klhub_t *hub;
if (!brd)
return INVALID_NASID;
/* find out if we are a completely disabled brd. */
hub = (klhub_t *)find_first_component(brd, KLSTRUCT_HUB);
if (!hub)
return INVALID_NASID;
if (!(hub->hub_info.flags & KLINFO_ENABLE)) /* disabled node brd */
return hub->hub_info.physid;
else
return brd->brd_nasid;
}
static int do_cpumask(cnodeid_t cnode, nasid_t nasid, int highest)
{
static int tot_cpus_found = 0;
lboard_t *brd;
klcpu_t *acpu;
int cpus_found = 0;
cpuid_t cpuid;
brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_IP27);
do {
acpu = (klcpu_t *)find_first_component(brd, KLSTRUCT_CPU);
while (acpu) {
cpuid = acpu->cpu_info.virtid;
/* cnode is not valid for completely disabled brds */
if (get_actual_nasid(brd) == brd->brd_nasid)
cpuid_to_compact_node[cpuid] = cnode;
if (cpuid > highest)
highest = cpuid;
/* Only let it join in if it's marked enabled */
if ((acpu->cpu_info.flags & KLINFO_ENABLE) &&
(tot_cpus_found != NR_CPUS)) {
set_cpu_possible(cpuid, true);
alloc_cpupda(cpuid, tot_cpus_found);
cpus_found++;
tot_cpus_found++;
}
acpu = (klcpu_t *)find_component(brd, (klinfo_t *)acpu,
KLSTRUCT_CPU);
}
brd = KLCF_NEXT(brd);
if (!brd)
break;
brd = find_lboard(brd, KLTYPE_IP27);
} while (brd);
return highest;
}
void cpu_node_probe(void)
{
int i, highest = 0;
gda_t *gdap = GDA;
/*
* Initialize the arrays to invalid nodeid (-1)
*/
for (i = 0; i < MAX_COMPACT_NODES; i++)
compact_to_nasid_node[i] = INVALID_NASID;
for (i = 0; i < MAX_NASIDS; i++)
nasid_to_compact_node[i] = INVALID_CNODEID;
for (i = 0; i < MAXCPUS; i++)
cpuid_to_compact_node[i] = INVALID_CNODEID;
/*
* MCD - this whole "compact node" stuff can probably be dropped,
* as we can handle sparse numbering now
*/
nodes_clear(node_online_map);
for (i = 0; i < MAX_COMPACT_NODES; i++) {
nasid_t nasid = gdap->g_nasidtable[i];
if (nasid == INVALID_NASID)
break;
compact_to_nasid_node[i] = nasid;
nasid_to_compact_node[nasid] = i;
node_set_online(num_online_nodes());
highest = do_cpumask(i, nasid, highest);
}
printk("Discovered %d cpus on %d nodes\n", highest + 1, num_online_nodes());
}
static __init void intr_clear_all(nasid_t nasid)
{
int i;
REMOTE_HUB_S(nasid, PI_INT_MASK0_A, 0);
REMOTE_HUB_S(nasid, PI_INT_MASK0_B, 0);
REMOTE_HUB_S(nasid, PI_INT_MASK1_A, 0);
REMOTE_HUB_S(nasid, PI_INT_MASK1_B, 0);
for (i = 0; i < 128; i++)
REMOTE_HUB_CLR_INTR(nasid, i);
}
static void ip27_send_ipi_single(int destid, unsigned int action)
{
int irq;
switch (action) {
case SMP_RESCHEDULE_YOURSELF:
irq = CPU_RESCHED_A_IRQ;
break;
case SMP_CALL_FUNCTION:
irq = CPU_CALL_A_IRQ;
break;
default:
panic("sendintr");
}
irq += cputoslice(destid);
/*
* Convert the compact hub number to the NASID to get the correct
* part of the address space. Then set the interrupt bit associated
* with the CPU we want to send the interrupt to.
*/
REMOTE_HUB_SEND_INTR(COMPACT_TO_NASID_NODEID(cpu_to_node(destid)), irq);
}
static void ip27_send_ipi_mask(const struct cpumask *mask, unsigned int action)
{
unsigned int i;
for_each_cpu(i, mask)
ip27_send_ipi_single(i, action);
}
static void __cpuinit ip27_init_secondary(void)
{
per_cpu_init();
}
static void __cpuinit ip27_smp_finish(void)
{
extern void hub_rt_clock_event_init(void);
hub_rt_clock_event_init();
local_irq_enable();
}
static void __init ip27_cpus_done(void)
{
}
/*
* Launch a slave into smp_bootstrap(). It doesn't take an argument, and we
* set sp to the kernel stack of the newly created idle process, gp to the proc
* struct so that current_thread_info() will work.
*/
static void __cpuinit ip27_boot_secondary(int cpu, struct task_struct *idle)
{
unsigned long gp = (unsigned long)task_thread_info(idle);
unsigned long sp = __KSTK_TOS(idle);
LAUNCH_SLAVE(cputonasid(cpu), cputoslice(cpu),
(launch_proc_t)MAPPED_KERN_RW_TO_K0(smp_bootstrap),
0, (void *) sp, (void *) gp);
}
static void __init ip27_smp_setup(void)
{
cnodeid_t cnode;
for_each_online_node(cnode) {
if (cnode == 0)
continue;
intr_clear_all(COMPACT_TO_NASID_NODEID(cnode));
}
replicate_kernel_text();
/*
* Assumption to be fixed: we're always booted on logical / physical
* processor 0. While we're always running on logical processor 0
* this still means this is physical processor zero; it might for
* example be disabled in the firmware.
*/
alloc_cpupda(0, 0);
}
static void __init ip27_prepare_cpus(unsigned int max_cpus)
{
/* We already did everything necessary earlier */
}
struct plat_smp_ops ip27_smp_ops = {
.send_ipi_single = ip27_send_ipi_single,
.send_ipi_mask = ip27_send_ipi_mask,
.init_secondary = ip27_init_secondary,
.smp_finish = ip27_smp_finish,
.cpus_done = ip27_cpus_done,
.boot_secondary = ip27_boot_secondary,
.smp_setup = ip27_smp_setup,
.prepare_cpus = ip27_prepare_cpus,
};
| gpl-2.0 |
NooNameR/Dirty | sound/core/seq/seq_midi_emul.c | 4819 | 19908 | /*
* GM/GS/XG midi module.
*
* Copyright (C) 1999 Steve Ratcliffe
*
* Based on awe_wave.c by Takashi Iwai
*
* 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
*
*/
/*
* This module is used to keep track of the current midi state.
* It can be used for drivers that are required to emulate midi when
* the hardware doesn't.
*
* It was written for a AWE64 driver, but there should be no AWE specific
* code in here. If there is it should be reported as a bug.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <sound/core.h>
#include <sound/seq_kernel.h>
#include <sound/seq_midi_emul.h>
#include <sound/initval.h>
#include <sound/asoundef.h>
MODULE_AUTHOR("Takashi Iwai / Steve Ratcliffe");
MODULE_DESCRIPTION("Advanced Linux Sound Architecture sequencer MIDI emulation.");
MODULE_LICENSE("GPL");
/* Prototypes for static functions */
static void note_off(struct snd_midi_op *ops, void *drv,
struct snd_midi_channel *chan,
int note, int vel);
static void do_control(struct snd_midi_op *ops, void *private,
struct snd_midi_channel_set *chset,
struct snd_midi_channel *chan,
int control, int value);
static void rpn(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan,
struct snd_midi_channel_set *chset);
static void nrpn(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan,
struct snd_midi_channel_set *chset);
static void sysex(struct snd_midi_op *ops, void *private, unsigned char *sysex,
int len, struct snd_midi_channel_set *chset);
static void all_sounds_off(struct snd_midi_op *ops, void *private,
struct snd_midi_channel *chan);
static void all_notes_off(struct snd_midi_op *ops, void *private,
struct snd_midi_channel *chan);
static void snd_midi_reset_controllers(struct snd_midi_channel *chan);
static void reset_all_channels(struct snd_midi_channel_set *chset);
/*
* Process an event in a driver independent way. This means dealing
* with RPN, NRPN, SysEx etc that are defined for common midi applications
* such as GM, GS and XG.
* There modes that this module will run in are:
* Generic MIDI - no interpretation at all, it will just save current values
* of controllers etc.
* GM - You can use all gm_ prefixed elements of chan. Controls, RPN, NRPN,
* SysEx will be interpreded as defined in General Midi.
* GS - You can use all gs_ prefixed elements of chan. Codes for GS will be
* interpreted.
* XG - You can use all xg_ prefixed elements of chan. Codes for XG will
* be interpreted.
*/
void
snd_midi_process_event(struct snd_midi_op *ops,
struct snd_seq_event *ev,
struct snd_midi_channel_set *chanset)
{
struct snd_midi_channel *chan;
void *drv;
int dest_channel = 0;
if (ev == NULL || chanset == NULL) {
snd_printd("ev or chanbase NULL (snd_midi_process_event)\n");
return;
}
if (chanset->channels == NULL)
return;
if (snd_seq_ev_is_channel_type(ev)) {
dest_channel = ev->data.note.channel;
if (dest_channel >= chanset->max_channels) {
snd_printd("dest channel is %d, max is %d\n",
dest_channel, chanset->max_channels);
return;
}
}
chan = chanset->channels + dest_channel;
drv = chanset->private_data;
/* EVENT_NOTE should be processed before queued */
if (ev->type == SNDRV_SEQ_EVENT_NOTE)
return;
/* Make sure that we don't have a note on that should really be
* a note off */
if (ev->type == SNDRV_SEQ_EVENT_NOTEON && ev->data.note.velocity == 0)
ev->type = SNDRV_SEQ_EVENT_NOTEOFF;
/* Make sure the note is within array range */
if (ev->type == SNDRV_SEQ_EVENT_NOTEON ||
ev->type == SNDRV_SEQ_EVENT_NOTEOFF ||
ev->type == SNDRV_SEQ_EVENT_KEYPRESS) {
if (ev->data.note.note >= 128)
return;
}
switch (ev->type) {
case SNDRV_SEQ_EVENT_NOTEON:
if (chan->note[ev->data.note.note] & SNDRV_MIDI_NOTE_ON) {
if (ops->note_off)
ops->note_off(drv, ev->data.note.note, 0, chan);
}
chan->note[ev->data.note.note] = SNDRV_MIDI_NOTE_ON;
if (ops->note_on)
ops->note_on(drv, ev->data.note.note, ev->data.note.velocity, chan);
break;
case SNDRV_SEQ_EVENT_NOTEOFF:
if (! (chan->note[ev->data.note.note] & SNDRV_MIDI_NOTE_ON))
break;
if (ops->note_off)
note_off(ops, drv, chan, ev->data.note.note, ev->data.note.velocity);
break;
case SNDRV_SEQ_EVENT_KEYPRESS:
if (ops->key_press)
ops->key_press(drv, ev->data.note.note, ev->data.note.velocity, chan);
break;
case SNDRV_SEQ_EVENT_CONTROLLER:
do_control(ops, drv, chanset, chan,
ev->data.control.param, ev->data.control.value);
break;
case SNDRV_SEQ_EVENT_PGMCHANGE:
chan->midi_program = ev->data.control.value;
break;
case SNDRV_SEQ_EVENT_PITCHBEND:
chan->midi_pitchbend = ev->data.control.value;
if (ops->control)
ops->control(drv, MIDI_CTL_PITCHBEND, chan);
break;
case SNDRV_SEQ_EVENT_CHANPRESS:
chan->midi_pressure = ev->data.control.value;
if (ops->control)
ops->control(drv, MIDI_CTL_CHAN_PRESSURE, chan);
break;
case SNDRV_SEQ_EVENT_CONTROL14:
/* Best guess is that this is any of the 14 bit controller values */
if (ev->data.control.param < 32) {
/* set low part first */
chan->control[ev->data.control.param + 32] =
ev->data.control.value & 0x7f;
do_control(ops, drv, chanset, chan,
ev->data.control.param,
((ev->data.control.value>>7) & 0x7f));
} else
do_control(ops, drv, chanset, chan,
ev->data.control.param,
ev->data.control.value);
break;
case SNDRV_SEQ_EVENT_NONREGPARAM:
/* Break it back into its controller values */
chan->param_type = SNDRV_MIDI_PARAM_TYPE_NONREGISTERED;
chan->control[MIDI_CTL_MSB_DATA_ENTRY]
= (ev->data.control.value >> 7) & 0x7f;
chan->control[MIDI_CTL_LSB_DATA_ENTRY]
= ev->data.control.value & 0x7f;
chan->control[MIDI_CTL_NONREG_PARM_NUM_MSB]
= (ev->data.control.param >> 7) & 0x7f;
chan->control[MIDI_CTL_NONREG_PARM_NUM_LSB]
= ev->data.control.param & 0x7f;
nrpn(ops, drv, chan, chanset);
break;
case SNDRV_SEQ_EVENT_REGPARAM:
/* Break it back into its controller values */
chan->param_type = SNDRV_MIDI_PARAM_TYPE_REGISTERED;
chan->control[MIDI_CTL_MSB_DATA_ENTRY]
= (ev->data.control.value >> 7) & 0x7f;
chan->control[MIDI_CTL_LSB_DATA_ENTRY]
= ev->data.control.value & 0x7f;
chan->control[MIDI_CTL_REGIST_PARM_NUM_MSB]
= (ev->data.control.param >> 7) & 0x7f;
chan->control[MIDI_CTL_REGIST_PARM_NUM_LSB]
= ev->data.control.param & 0x7f;
rpn(ops, drv, chan, chanset);
break;
case SNDRV_SEQ_EVENT_SYSEX:
if ((ev->flags & SNDRV_SEQ_EVENT_LENGTH_MASK) == SNDRV_SEQ_EVENT_LENGTH_VARIABLE) {
unsigned char sysexbuf[64];
int len;
len = snd_seq_expand_var_event(ev, sizeof(sysexbuf), sysexbuf, 1, 0);
if (len > 0)
sysex(ops, drv, sysexbuf, len, chanset);
}
break;
case SNDRV_SEQ_EVENT_SONGPOS:
case SNDRV_SEQ_EVENT_SONGSEL:
case SNDRV_SEQ_EVENT_CLOCK:
case SNDRV_SEQ_EVENT_START:
case SNDRV_SEQ_EVENT_CONTINUE:
case SNDRV_SEQ_EVENT_STOP:
case SNDRV_SEQ_EVENT_QFRAME:
case SNDRV_SEQ_EVENT_TEMPO:
case SNDRV_SEQ_EVENT_TIMESIGN:
case SNDRV_SEQ_EVENT_KEYSIGN:
goto not_yet;
case SNDRV_SEQ_EVENT_SENSING:
break;
case SNDRV_SEQ_EVENT_CLIENT_START:
case SNDRV_SEQ_EVENT_CLIENT_EXIT:
case SNDRV_SEQ_EVENT_CLIENT_CHANGE:
case SNDRV_SEQ_EVENT_PORT_START:
case SNDRV_SEQ_EVENT_PORT_EXIT:
case SNDRV_SEQ_EVENT_PORT_CHANGE:
case SNDRV_SEQ_EVENT_ECHO:
not_yet:
default:
/*snd_printd("Unimplemented event %d\n", ev->type);*/
break;
}
}
/*
* release note
*/
static void
note_off(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan,
int note, int vel)
{
if (chan->gm_hold) {
/* Hold this note until pedal is turned off */
chan->note[note] |= SNDRV_MIDI_NOTE_RELEASED;
} else if (chan->note[note] & SNDRV_MIDI_NOTE_SOSTENUTO) {
/* Mark this note as release; it will be turned off when sostenuto
* is turned off */
chan->note[note] |= SNDRV_MIDI_NOTE_RELEASED;
} else {
chan->note[note] = 0;
if (ops->note_off)
ops->note_off(drv, note, vel, chan);
}
}
/*
* Do all driver independent operations for this controller and pass
* events that need to take place immediately to the driver.
*/
static void
do_control(struct snd_midi_op *ops, void *drv, struct snd_midi_channel_set *chset,
struct snd_midi_channel *chan, int control, int value)
{
int i;
/* Switches */
if ((control >=64 && control <=69) || (control >= 80 && control <= 83)) {
/* These are all switches; either off or on so set to 0 or 127 */
value = (value >= 64)? 127: 0;
}
chan->control[control] = value;
switch (control) {
case MIDI_CTL_SUSTAIN:
if (value == 0) {
/* Sustain has been released, turn off held notes */
for (i = 0; i < 128; i++) {
if (chan->note[i] & SNDRV_MIDI_NOTE_RELEASED) {
chan->note[i] = SNDRV_MIDI_NOTE_OFF;
if (ops->note_off)
ops->note_off(drv, i, 0, chan);
}
}
}
break;
case MIDI_CTL_PORTAMENTO:
break;
case MIDI_CTL_SOSTENUTO:
if (value) {
/* Mark each note that is currently held down */
for (i = 0; i < 128; i++) {
if (chan->note[i] & SNDRV_MIDI_NOTE_ON)
chan->note[i] |= SNDRV_MIDI_NOTE_SOSTENUTO;
}
} else {
/* release all notes that were held */
for (i = 0; i < 128; i++) {
if (chan->note[i] & SNDRV_MIDI_NOTE_SOSTENUTO) {
chan->note[i] &= ~SNDRV_MIDI_NOTE_SOSTENUTO;
if (chan->note[i] & SNDRV_MIDI_NOTE_RELEASED) {
chan->note[i] = SNDRV_MIDI_NOTE_OFF;
if (ops->note_off)
ops->note_off(drv, i, 0, chan);
}
}
}
}
break;
case MIDI_CTL_MSB_DATA_ENTRY:
chan->control[MIDI_CTL_LSB_DATA_ENTRY] = 0;
/* go through here */
case MIDI_CTL_LSB_DATA_ENTRY:
if (chan->param_type == SNDRV_MIDI_PARAM_TYPE_REGISTERED)
rpn(ops, drv, chan, chset);
else
nrpn(ops, drv, chan, chset);
break;
case MIDI_CTL_REGIST_PARM_NUM_LSB:
case MIDI_CTL_REGIST_PARM_NUM_MSB:
chan->param_type = SNDRV_MIDI_PARAM_TYPE_REGISTERED;
break;
case MIDI_CTL_NONREG_PARM_NUM_LSB:
case MIDI_CTL_NONREG_PARM_NUM_MSB:
chan->param_type = SNDRV_MIDI_PARAM_TYPE_NONREGISTERED;
break;
case MIDI_CTL_ALL_SOUNDS_OFF:
all_sounds_off(ops, drv, chan);
break;
case MIDI_CTL_ALL_NOTES_OFF:
all_notes_off(ops, drv, chan);
break;
case MIDI_CTL_MSB_BANK:
if (chset->midi_mode == SNDRV_MIDI_MODE_XG) {
if (value == 127)
chan->drum_channel = 1;
else
chan->drum_channel = 0;
}
break;
case MIDI_CTL_LSB_BANK:
break;
case MIDI_CTL_RESET_CONTROLLERS:
snd_midi_reset_controllers(chan);
break;
case MIDI_CTL_SOFT_PEDAL:
case MIDI_CTL_LEGATO_FOOTSWITCH:
case MIDI_CTL_HOLD2:
case MIDI_CTL_SC1_SOUND_VARIATION:
case MIDI_CTL_SC2_TIMBRE:
case MIDI_CTL_SC3_RELEASE_TIME:
case MIDI_CTL_SC4_ATTACK_TIME:
case MIDI_CTL_SC5_BRIGHTNESS:
case MIDI_CTL_E1_REVERB_DEPTH:
case MIDI_CTL_E2_TREMOLO_DEPTH:
case MIDI_CTL_E3_CHORUS_DEPTH:
case MIDI_CTL_E4_DETUNE_DEPTH:
case MIDI_CTL_E5_PHASER_DEPTH:
goto notyet;
notyet:
default:
if (ops->control)
ops->control(drv, control, chan);
break;
}
}
/*
* initialize the MIDI status
*/
void
snd_midi_channel_set_clear(struct snd_midi_channel_set *chset)
{
int i;
chset->midi_mode = SNDRV_MIDI_MODE_GM;
chset->gs_master_volume = 127;
for (i = 0; i < chset->max_channels; i++) {
struct snd_midi_channel *chan = chset->channels + i;
memset(chan->note, 0, sizeof(chan->note));
chan->midi_aftertouch = 0;
chan->midi_pressure = 0;
chan->midi_program = 0;
chan->midi_pitchbend = 0;
snd_midi_reset_controllers(chan);
chan->gm_rpn_pitch_bend_range = 256; /* 2 semitones */
chan->gm_rpn_fine_tuning = 0;
chan->gm_rpn_coarse_tuning = 0;
if (i == 9)
chan->drum_channel = 1;
else
chan->drum_channel = 0;
}
}
/*
* Process a rpn message.
*/
static void
rpn(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan,
struct snd_midi_channel_set *chset)
{
int type;
int val;
if (chset->midi_mode != SNDRV_MIDI_MODE_NONE) {
type = (chan->control[MIDI_CTL_REGIST_PARM_NUM_MSB] << 8) |
chan->control[MIDI_CTL_REGIST_PARM_NUM_LSB];
val = (chan->control[MIDI_CTL_MSB_DATA_ENTRY] << 7) |
chan->control[MIDI_CTL_LSB_DATA_ENTRY];
switch (type) {
case 0x0000: /* Pitch bend sensitivity */
/* MSB only / 1 semitone per 128 */
chan->gm_rpn_pitch_bend_range = val;
break;
case 0x0001: /* fine tuning: */
/* MSB/LSB, 8192=center, 100/8192 cent step */
chan->gm_rpn_fine_tuning = val - 8192;
break;
case 0x0002: /* coarse tuning */
/* MSB only / 8192=center, 1 semitone per 128 */
chan->gm_rpn_coarse_tuning = val - 8192;
break;
case 0x7F7F: /* "lock-in" RPN */
/* ignored */
break;
}
}
/* should call nrpn or rpn callback here.. */
}
/*
* Process an nrpn message.
*/
static void
nrpn(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan,
struct snd_midi_channel_set *chset)
{
/* parse XG NRPNs here if possible */
if (ops->nrpn)
ops->nrpn(drv, chan, chset);
}
/*
* convert channel parameter in GS sysex
*/
static int
get_channel(unsigned char cmd)
{
int p = cmd & 0x0f;
if (p == 0)
p = 9;
else if (p < 10)
p--;
return p;
}
/*
* Process a sysex message.
*/
static void
sysex(struct snd_midi_op *ops, void *private, unsigned char *buf, int len,
struct snd_midi_channel_set *chset)
{
/* GM on */
static unsigned char gm_on_macro[] = {
0x7e,0x7f,0x09,0x01,
};
/* XG on */
static unsigned char xg_on_macro[] = {
0x43,0x10,0x4c,0x00,0x00,0x7e,0x00,
};
/* GS prefix
* drum channel: XX=0x1?(channel), YY=0x15, ZZ=on/off
* reverb mode: XX=0x01, YY=0x30, ZZ=0-7
* chorus mode: XX=0x01, YY=0x38, ZZ=0-7
* master vol: XX=0x00, YY=0x04, ZZ=0-127
*/
static unsigned char gs_pfx_macro[] = {
0x41,0x10,0x42,0x12,0x40,/*XX,YY,ZZ*/
};
int parsed = SNDRV_MIDI_SYSEX_NOT_PARSED;
if (len <= 0 || buf[0] != 0xf0)
return;
/* skip first byte */
buf++;
len--;
/* GM on */
if (len >= (int)sizeof(gm_on_macro) &&
memcmp(buf, gm_on_macro, sizeof(gm_on_macro)) == 0) {
if (chset->midi_mode != SNDRV_MIDI_MODE_GS &&
chset->midi_mode != SNDRV_MIDI_MODE_XG) {
chset->midi_mode = SNDRV_MIDI_MODE_GM;
reset_all_channels(chset);
parsed = SNDRV_MIDI_SYSEX_GM_ON;
}
}
/* GS macros */
else if (len >= 8 &&
memcmp(buf, gs_pfx_macro, sizeof(gs_pfx_macro)) == 0) {
if (chset->midi_mode != SNDRV_MIDI_MODE_GS &&
chset->midi_mode != SNDRV_MIDI_MODE_XG)
chset->midi_mode = SNDRV_MIDI_MODE_GS;
if (buf[5] == 0x00 && buf[6] == 0x7f && buf[7] == 0x00) {
/* GS reset */
parsed = SNDRV_MIDI_SYSEX_GS_RESET;
reset_all_channels(chset);
}
else if ((buf[5] & 0xf0) == 0x10 && buf[6] == 0x15) {
/* drum pattern */
int p = get_channel(buf[5]);
if (p < chset->max_channels) {
parsed = SNDRV_MIDI_SYSEX_GS_DRUM_CHANNEL;
if (buf[7])
chset->channels[p].drum_channel = 1;
else
chset->channels[p].drum_channel = 0;
}
} else if ((buf[5] & 0xf0) == 0x10 && buf[6] == 0x21) {
/* program */
int p = get_channel(buf[5]);
if (p < chset->max_channels &&
! chset->channels[p].drum_channel) {
parsed = SNDRV_MIDI_SYSEX_GS_DRUM_CHANNEL;
chset->channels[p].midi_program = buf[7];
}
} else if (buf[5] == 0x01 && buf[6] == 0x30) {
/* reverb mode */
parsed = SNDRV_MIDI_SYSEX_GS_REVERB_MODE;
chset->gs_reverb_mode = buf[7];
} else if (buf[5] == 0x01 && buf[6] == 0x38) {
/* chorus mode */
parsed = SNDRV_MIDI_SYSEX_GS_CHORUS_MODE;
chset->gs_chorus_mode = buf[7];
} else if (buf[5] == 0x00 && buf[6] == 0x04) {
/* master volume */
parsed = SNDRV_MIDI_SYSEX_GS_MASTER_VOLUME;
chset->gs_master_volume = buf[7];
}
}
/* XG on */
else if (len >= (int)sizeof(xg_on_macro) &&
memcmp(buf, xg_on_macro, sizeof(xg_on_macro)) == 0) {
int i;
chset->midi_mode = SNDRV_MIDI_MODE_XG;
parsed = SNDRV_MIDI_SYSEX_XG_ON;
/* reset CC#0 for drums */
for (i = 0; i < chset->max_channels; i++) {
if (chset->channels[i].drum_channel)
chset->channels[i].control[MIDI_CTL_MSB_BANK] = 127;
else
chset->channels[i].control[MIDI_CTL_MSB_BANK] = 0;
}
}
if (ops->sysex)
ops->sysex(private, buf - 1, len + 1, parsed, chset);
}
/*
* all sound off
*/
static void
all_sounds_off(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan)
{
int n;
if (! ops->note_terminate)
return;
for (n = 0; n < 128; n++) {
if (chan->note[n]) {
ops->note_terminate(drv, n, chan);
chan->note[n] = 0;
}
}
}
/*
* all notes off
*/
static void
all_notes_off(struct snd_midi_op *ops, void *drv, struct snd_midi_channel *chan)
{
int n;
if (! ops->note_off)
return;
for (n = 0; n < 128; n++) {
if (chan->note[n] == SNDRV_MIDI_NOTE_ON)
note_off(ops, drv, chan, n, 0);
}
}
/*
* Initialise a single midi channel control block.
*/
static void snd_midi_channel_init(struct snd_midi_channel *p, int n)
{
if (p == NULL)
return;
memset(p, 0, sizeof(struct snd_midi_channel));
p->private = NULL;
p->number = n;
snd_midi_reset_controllers(p);
p->gm_rpn_pitch_bend_range = 256; /* 2 semitones */
p->gm_rpn_fine_tuning = 0;
p->gm_rpn_coarse_tuning = 0;
if (n == 9)
p->drum_channel = 1; /* Default ch 10 as drums */
}
/*
* Allocate and initialise a set of midi channel control blocks.
*/
static struct snd_midi_channel *snd_midi_channel_init_set(int n)
{
struct snd_midi_channel *chan;
int i;
chan = kmalloc(n * sizeof(struct snd_midi_channel), GFP_KERNEL);
if (chan) {
for (i = 0; i < n; i++)
snd_midi_channel_init(chan+i, i);
}
return chan;
}
/*
* reset all midi channels
*/
static void
reset_all_channels(struct snd_midi_channel_set *chset)
{
int ch;
for (ch = 0; ch < chset->max_channels; ch++) {
struct snd_midi_channel *chan = chset->channels + ch;
snd_midi_reset_controllers(chan);
chan->gm_rpn_pitch_bend_range = 256; /* 2 semitones */
chan->gm_rpn_fine_tuning = 0;
chan->gm_rpn_coarse_tuning = 0;
if (ch == 9)
chan->drum_channel = 1;
else
chan->drum_channel = 0;
}
}
/*
* Allocate and initialise a midi channel set.
*/
struct snd_midi_channel_set *snd_midi_channel_alloc_set(int n)
{
struct snd_midi_channel_set *chset;
chset = kmalloc(sizeof(*chset), GFP_KERNEL);
if (chset) {
chset->channels = snd_midi_channel_init_set(n);
chset->private_data = NULL;
chset->max_channels = n;
}
return chset;
}
/*
* Reset the midi controllers on a particular channel to default values.
*/
static void snd_midi_reset_controllers(struct snd_midi_channel *chan)
{
memset(chan->control, 0, sizeof(chan->control));
chan->gm_volume = 127;
chan->gm_expression = 127;
chan->gm_pan = 64;
}
/*
* Free a midi channel set.
*/
void snd_midi_channel_free_set(struct snd_midi_channel_set *chset)
{
if (chset == NULL)
return;
kfree(chset->channels);
kfree(chset);
}
static int __init alsa_seq_midi_emul_init(void)
{
return 0;
}
static void __exit alsa_seq_midi_emul_exit(void)
{
}
module_init(alsa_seq_midi_emul_init)
module_exit(alsa_seq_midi_emul_exit)
EXPORT_SYMBOL(snd_midi_process_event);
EXPORT_SYMBOL(snd_midi_channel_set_clear);
EXPORT_SYMBOL(snd_midi_channel_alloc_set);
EXPORT_SYMBOL(snd_midi_channel_free_set);
| gpl-2.0 |
HRTKernel/Hacker_Kernel_SM-G92X | drivers/firewire/core-iso.c | 4819 | 10521 | /*
* Isochronous I/O functionality:
* - Isochronous DMA context management
* - Isochronous bus resource management (channels, bandwidth), client side
*
* Copyright (C) 2006 Kristian Hoegsberg <krh@bitplanet.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/export.h>
#include <asm/byteorder.h>
#include "core.h"
/*
* Isochronous DMA context management
*/
int fw_iso_buffer_alloc(struct fw_iso_buffer *buffer, int page_count)
{
int i;
buffer->page_count = 0;
buffer->page_count_mapped = 0;
buffer->pages = kmalloc(page_count * sizeof(buffer->pages[0]),
GFP_KERNEL);
if (buffer->pages == NULL)
return -ENOMEM;
for (i = 0; i < page_count; i++) {
buffer->pages[i] = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
if (buffer->pages[i] == NULL)
break;
}
buffer->page_count = i;
if (i < page_count) {
fw_iso_buffer_destroy(buffer, NULL);
return -ENOMEM;
}
return 0;
}
int fw_iso_buffer_map_dma(struct fw_iso_buffer *buffer, struct fw_card *card,
enum dma_data_direction direction)
{
dma_addr_t address;
int i;
buffer->direction = direction;
for (i = 0; i < buffer->page_count; i++) {
address = dma_map_page(card->device, buffer->pages[i],
0, PAGE_SIZE, direction);
if (dma_mapping_error(card->device, address))
break;
set_page_private(buffer->pages[i], address);
}
buffer->page_count_mapped = i;
if (i < buffer->page_count)
return -ENOMEM;
return 0;
}
int fw_iso_buffer_init(struct fw_iso_buffer *buffer, struct fw_card *card,
int page_count, enum dma_data_direction direction)
{
int ret;
ret = fw_iso_buffer_alloc(buffer, page_count);
if (ret < 0)
return ret;
ret = fw_iso_buffer_map_dma(buffer, card, direction);
if (ret < 0)
fw_iso_buffer_destroy(buffer, card);
return ret;
}
EXPORT_SYMBOL(fw_iso_buffer_init);
int fw_iso_buffer_map_vma(struct fw_iso_buffer *buffer,
struct vm_area_struct *vma)
{
unsigned long uaddr;
int i, err;
uaddr = vma->vm_start;
for (i = 0; i < buffer->page_count; i++) {
err = vm_insert_page(vma, uaddr, buffer->pages[i]);
if (err)
return err;
uaddr += PAGE_SIZE;
}
return 0;
}
void fw_iso_buffer_destroy(struct fw_iso_buffer *buffer,
struct fw_card *card)
{
int i;
dma_addr_t address;
for (i = 0; i < buffer->page_count_mapped; i++) {
address = page_private(buffer->pages[i]);
dma_unmap_page(card->device, address,
PAGE_SIZE, buffer->direction);
}
for (i = 0; i < buffer->page_count; i++)
__free_page(buffer->pages[i]);
kfree(buffer->pages);
buffer->pages = NULL;
buffer->page_count = 0;
buffer->page_count_mapped = 0;
}
EXPORT_SYMBOL(fw_iso_buffer_destroy);
/* Convert DMA address to offset into virtually contiguous buffer. */
size_t fw_iso_buffer_lookup(struct fw_iso_buffer *buffer, dma_addr_t completed)
{
size_t i;
dma_addr_t address;
ssize_t offset;
for (i = 0; i < buffer->page_count; i++) {
address = page_private(buffer->pages[i]);
offset = (ssize_t)completed - (ssize_t)address;
if (offset > 0 && offset <= PAGE_SIZE)
return (i << PAGE_SHIFT) + offset;
}
return 0;
}
struct fw_iso_context *fw_iso_context_create(struct fw_card *card,
int type, int channel, int speed, size_t header_size,
fw_iso_callback_t callback, void *callback_data)
{
struct fw_iso_context *ctx;
ctx = card->driver->allocate_iso_context(card,
type, channel, header_size);
if (IS_ERR(ctx))
return ctx;
ctx->card = card;
ctx->type = type;
ctx->channel = channel;
ctx->speed = speed;
ctx->header_size = header_size;
ctx->callback.sc = callback;
ctx->callback_data = callback_data;
return ctx;
}
EXPORT_SYMBOL(fw_iso_context_create);
void fw_iso_context_destroy(struct fw_iso_context *ctx)
{
ctx->card->driver->free_iso_context(ctx);
}
EXPORT_SYMBOL(fw_iso_context_destroy);
int fw_iso_context_start(struct fw_iso_context *ctx,
int cycle, int sync, int tags)
{
return ctx->card->driver->start_iso(ctx, cycle, sync, tags);
}
EXPORT_SYMBOL(fw_iso_context_start);
int fw_iso_context_set_channels(struct fw_iso_context *ctx, u64 *channels)
{
return ctx->card->driver->set_iso_channels(ctx, channels);
}
int fw_iso_context_queue(struct fw_iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
return ctx->card->driver->queue_iso(ctx, packet, buffer, payload);
}
EXPORT_SYMBOL(fw_iso_context_queue);
void fw_iso_context_queue_flush(struct fw_iso_context *ctx)
{
ctx->card->driver->flush_queue_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_queue_flush);
int fw_iso_context_flush_completions(struct fw_iso_context *ctx)
{
return ctx->card->driver->flush_iso_completions(ctx);
}
EXPORT_SYMBOL(fw_iso_context_flush_completions);
int fw_iso_context_stop(struct fw_iso_context *ctx)
{
return ctx->card->driver->stop_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_stop);
/*
* Isochronous bus resource management (channels, bandwidth), client side
*/
static int manage_bandwidth(struct fw_card *card, int irm_id, int generation,
int bandwidth, bool allocate)
{
int try, new, old = allocate ? BANDWIDTH_AVAILABLE_INITIAL : 0;
__be32 data[2];
/*
* On a 1394a IRM with low contention, try < 1 is enough.
* On a 1394-1995 IRM, we need at least try < 2.
* Let's just do try < 5.
*/
for (try = 0; try < 5; try++) {
new = allocate ? old - bandwidth : old + bandwidth;
if (new < 0 || new > BANDWIDTH_AVAILABLE_INITIAL)
return -EBUSY;
data[0] = cpu_to_be32(old);
data[1] = cpu_to_be32(new);
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
CSR_REGISTER_BASE + CSR_BANDWIDTH_AVAILABLE,
data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all bandwidth. */
return allocate ? -EAGAIN : bandwidth;
case RCODE_COMPLETE:
if (be32_to_cpup(data) == old)
return bandwidth;
old = be32_to_cpup(data);
/* Fall through. */
}
}
return -EIO;
}
static int manage_channel(struct fw_card *card, int irm_id, int generation,
u32 channels_mask, u64 offset, bool allocate)
{
__be32 bit, all, old;
__be32 data[2];
int channel, ret = -EIO, retry = 5;
old = all = allocate ? cpu_to_be32(~0) : 0;
for (channel = 0; channel < 32; channel++) {
if (!(channels_mask & 1 << channel))
continue;
ret = -EBUSY;
bit = cpu_to_be32(1 << (31 - channel));
if ((old & bit) != (all & bit))
continue;
data[0] = old;
data[1] = old ^ bit;
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
offset, data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all channels. */
return allocate ? -EAGAIN : channel;
case RCODE_COMPLETE:
if (data[0] == old)
return channel;
old = data[0];
/* Is the IRM 1394a-2000 compliant? */
if ((data[0] & bit) == (data[1] & bit))
continue;
/* 1394-1995 IRM, fall through to retry. */
default:
if (retry) {
retry--;
channel--;
} else {
ret = -EIO;
}
}
}
return ret;
}
static void deallocate_channel(struct fw_card *card, int irm_id,
int generation, int channel)
{
u32 mask;
u64 offset;
mask = channel < 32 ? 1 << channel : 1 << (channel - 32);
offset = channel < 32 ? CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI :
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO;
manage_channel(card, irm_id, generation, mask, offset, false);
}
/**
* fw_iso_resource_manage() - Allocate or deallocate a channel and/or bandwidth
*
* In parameters: card, generation, channels_mask, bandwidth, allocate
* Out parameters: channel, bandwidth
* This function blocks (sleeps) during communication with the IRM.
*
* Allocates or deallocates at most one channel out of channels_mask.
* channels_mask is a bitfield with MSB for channel 63 and LSB for channel 0.
* (Note, the IRM's CHANNELS_AVAILABLE is a big-endian bitfield with MSB for
* channel 0 and LSB for channel 63.)
* Allocates or deallocates as many bandwidth allocation units as specified.
*
* Returns channel < 0 if no channel was allocated or deallocated.
* Returns bandwidth = 0 if no bandwidth was allocated or deallocated.
*
* If generation is stale, deallocations succeed but allocations fail with
* channel = -EAGAIN.
*
* If channel allocation fails, no bandwidth will be allocated either.
* If bandwidth allocation fails, no channel will be allocated either.
* But deallocations of channel and bandwidth are tried independently
* of each other's success.
*/
void fw_iso_resource_manage(struct fw_card *card, int generation,
u64 channels_mask, int *channel, int *bandwidth,
bool allocate)
{
u32 channels_hi = channels_mask; /* channels 31...0 */
u32 channels_lo = channels_mask >> 32; /* channels 63...32 */
int irm_id, ret, c = -EINVAL;
spin_lock_irq(&card->lock);
irm_id = card->irm_node->node_id;
spin_unlock_irq(&card->lock);
if (channels_hi)
c = manage_channel(card, irm_id, generation, channels_hi,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI,
allocate);
if (channels_lo && c < 0) {
c = manage_channel(card, irm_id, generation, channels_lo,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO,
allocate);
if (c >= 0)
c += 32;
}
*channel = c;
if (allocate && channels_mask != 0 && c < 0)
*bandwidth = 0;
if (*bandwidth == 0)
return;
ret = manage_bandwidth(card, irm_id, generation, *bandwidth, allocate);
if (ret < 0)
*bandwidth = 0;
if (allocate && ret < 0) {
if (c >= 0)
deallocate_channel(card, irm_id, generation, c);
*channel = ret;
}
}
EXPORT_SYMBOL(fw_iso_resource_manage);
| gpl-2.0 |
mifl/android_kernel_pantech_im-860s | drivers/media/rc/keymaps/rc-msi-tvanywhere-plus.c | 7635 | 3619 | /* msi-tvanywhere-plus.h - Keytable for msi_tvanywhere_plus Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
/*
Keycodes for remote on the MSI TV@nywhere Plus. The controller IC on the card
is marked "KS003". The controller is I2C at address 0x30, but does not seem
to respond to probes until a read is performed from a valid device.
I don't know why...
Note: This remote may be of similar or identical design to the
Pixelview remote (?). The raw codes and duplicate button codes
appear to be the same.
Henry Wong <henry@stuffedcow.net>
Some changes to formatting and keycodes by Mark Schultz <n9xmj@yahoo.com>
*/
static struct rc_map_table msi_tvanywhere_plus[] = {
/* ---- Remote Button Layout ----
POWER SOURCE SCAN MUTE
TV/FM 1 2 3
|> 4 5 6
<| 7 8 9
^^UP 0 + RECALL
vvDN RECORD STOP PLAY
MINIMIZE ZOOM
CH+
VOL- VOL+
CH-
SNAPSHOT MTS
<< FUNC >> RESET
*/
{ 0x01, KEY_1 }, /* 1 */
{ 0x0b, KEY_2 }, /* 2 */
{ 0x1b, KEY_3 }, /* 3 */
{ 0x05, KEY_4 }, /* 4 */
{ 0x09, KEY_5 }, /* 5 */
{ 0x15, KEY_6 }, /* 6 */
{ 0x06, KEY_7 }, /* 7 */
{ 0x0a, KEY_8 }, /* 8 */
{ 0x12, KEY_9 }, /* 9 */
{ 0x02, KEY_0 }, /* 0 */
{ 0x10, KEY_KPPLUS }, /* + */
{ 0x13, KEY_AGAIN }, /* Recall */
{ 0x1e, KEY_POWER }, /* Power */
{ 0x07, KEY_VIDEO }, /* Source */
{ 0x1c, KEY_SEARCH }, /* Scan */
{ 0x18, KEY_MUTE }, /* Mute */
{ 0x03, KEY_RADIO }, /* TV/FM */
/* The next four keys are duplicates that appear to send the
same IR code as Ch+, Ch-, >>, and << . The raw code assigned
to them is the actual code + 0x20 - they will never be
detected as such unless some way is discovered to distinguish
these buttons from those that have the same code. */
{ 0x3f, KEY_RIGHT }, /* |> and Ch+ */
{ 0x37, KEY_LEFT }, /* <| and Ch- */
{ 0x2c, KEY_UP }, /* ^^Up and >> */
{ 0x24, KEY_DOWN }, /* vvDn and << */
{ 0x00, KEY_RECORD }, /* Record */
{ 0x08, KEY_STOP }, /* Stop */
{ 0x11, KEY_PLAY }, /* Play */
{ 0x0f, KEY_CLOSE }, /* Minimize */
{ 0x19, KEY_ZOOM }, /* Zoom */
{ 0x1a, KEY_CAMERA }, /* Snapshot */
{ 0x0d, KEY_LANGUAGE }, /* MTS */
{ 0x14, KEY_VOLUMEDOWN }, /* Vol- */
{ 0x16, KEY_VOLUMEUP }, /* Vol+ */
{ 0x17, KEY_CHANNELDOWN }, /* Ch- */
{ 0x1f, KEY_CHANNELUP }, /* Ch+ */
{ 0x04, KEY_REWIND }, /* << */
{ 0x0e, KEY_MENU }, /* Function */
{ 0x0c, KEY_FASTFORWARD }, /* >> */
{ 0x1d, KEY_RESTART }, /* Reset */
};
static struct rc_map_list msi_tvanywhere_plus_map = {
.map = {
.scan = msi_tvanywhere_plus,
.size = ARRAY_SIZE(msi_tvanywhere_plus),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_MSI_TVANYWHERE_PLUS,
}
};
static int __init init_rc_map_msi_tvanywhere_plus(void)
{
return rc_map_register(&msi_tvanywhere_plus_map);
}
static void __exit exit_rc_map_msi_tvanywhere_plus(void)
{
rc_map_unregister(&msi_tvanywhere_plus_map);
}
module_init(init_rc_map_msi_tvanywhere_plus)
module_exit(exit_rc_map_msi_tvanywhere_plus)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Oct-mm/kraken_kernel_samsung_d2 | drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.c | 8147 | 35561 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.com
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-------------------------------+---------------------------------------+
| Project : APCI-1710 | Compiler : GCC |
| Module name : hwdrv_apci1710.c| Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-------------------------------+---------------------------------------+
| Description : Hardware Layer Access For APCI-1710 |
+-----------------------------------------------------------------------+
| UPDATES |
+----------+-----------+------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| | | |
| | | |
| | | |
+----------+-----------+------------------------------------------------+
*/
#include "hwdrv_APCI1710.h"
#include "APCI1710_Inp_cpt.c"
#include "APCI1710_Ssi.c"
#include "APCI1710_Tor.c"
#include "APCI1710_Ttl.c"
#include "APCI1710_Dig_io.c"
#include "APCI1710_82x54.c"
#include "APCI1710_Chrono.c"
#include "APCI1710_Pwm.c"
#include "APCI1710_INCCPT.c"
void i_ADDI_AttachPCI1710(struct comedi_device *dev)
{
struct comedi_subdevice *s;
int ret = 0;
int n_subdevices = 9;
/* Update-0.7.57->0.7.68dev->n_subdevices = 9; */
ret = alloc_subdevices(dev, n_subdevices);
if (ret < 0)
return;
/* Allocate and Initialise Timer Subdevice Structures */
s = dev->subdevices + 0;
s->type = COMEDI_SUBD_TIMER;
s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 3;
s->maxdata = 0;
s->len_chanlist = 3;
s->range_table = &range_digital;
s->insn_write = i_APCI1710_InsnWriteEnableDisableTimer;
s->insn_read = i_APCI1710_InsnReadAllTimerValue;
s->insn_config = i_APCI1710_InsnConfigInitTimer;
s->insn_bits = i_APCI1710_InsnBitsTimer;
/* Allocate and Initialise DIO Subdevice Structures */
s = dev->subdevices + 1;
s->type = COMEDI_SUBD_DIO;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 7;
s->maxdata = 1;
s->len_chanlist = 7;
s->range_table = &range_digital;
s->insn_config = i_APCI1710_InsnConfigDigitalIO;
s->insn_read = i_APCI1710_InsnReadDigitalIOChlValue;
s->insn_bits = i_APCI1710_InsnBitsDigitalIOPortOnOff;
s->insn_write = i_APCI1710_InsnWriteDigitalIOChlOnOff;
/* Allocate and Initialise Chrono Subdevice Structures */
s = dev->subdevices + 2;
s->type = COMEDI_SUBD_CHRONO;
s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 4;
s->maxdata = 0;
s->len_chanlist = 4;
s->range_table = &range_digital;
s->insn_write = i_APCI1710_InsnWriteEnableDisableChrono;
s->insn_read = i_APCI1710_InsnReadChrono;
s->insn_config = i_APCI1710_InsnConfigInitChrono;
s->insn_bits = i_APCI1710_InsnBitsChronoDigitalIO;
/* Allocate and Initialise PWM Subdevice Structures */
s = dev->subdevices + 3;
s->type = COMEDI_SUBD_PWM;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 3;
s->maxdata = 1;
s->len_chanlist = 3;
s->range_table = &range_digital;
s->io_bits = 0; /* all bits input */
s->insn_config = i_APCI1710_InsnConfigPWM;
s->insn_read = i_APCI1710_InsnReadGetPWMStatus;
s->insn_write = i_APCI1710_InsnWritePWM;
s->insn_bits = i_APCI1710_InsnBitsReadPWMInterrupt;
/* Allocate and Initialise TTLIO Subdevice Structures */
s = dev->subdevices + 4;
s->type = COMEDI_SUBD_TTLIO;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 8;
s->maxdata = 1;
s->len_chanlist = 8;
s->range_table = &range_apci1710_ttl; /* to pass arguments in range */
s->insn_config = i_APCI1710_InsnConfigInitTTLIO;
s->insn_bits = i_APCI1710_InsnBitsReadTTLIO;
s->insn_write = i_APCI1710_InsnWriteSetTTLIOChlOnOff;
s->insn_read = i_APCI1710_InsnReadTTLIOAllPortValue;
/* Allocate and Initialise TOR Subdevice Structures */
s = dev->subdevices + 5;
s->type = COMEDI_SUBD_TOR;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 8;
s->maxdata = 1;
s->len_chanlist = 8;
s->range_table = &range_digital;
s->io_bits = 0; /* all bits input */
s->insn_config = i_APCI1710_InsnConfigInitTorCounter;
s->insn_read = i_APCI1710_InsnReadGetTorCounterInitialisation;
s->insn_write = i_APCI1710_InsnWriteEnableDisableTorCounter;
s->insn_bits = i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue;
/* Allocate and Initialise SSI Subdevice Structures */
s = dev->subdevices + 6;
s->type = COMEDI_SUBD_SSI;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 4;
s->maxdata = 1;
s->len_chanlist = 4;
s->range_table = &range_apci1710_ssi;
s->insn_config = i_APCI1710_InsnConfigInitSSI;
s->insn_read = i_APCI1710_InsnReadSSIValue;
s->insn_bits = i_APCI1710_InsnBitsSSIDigitalIO;
/* Allocate and Initialise PULSEENCODER Subdevice Structures */
s = dev->subdevices + 7;
s->type = COMEDI_SUBD_PULSEENCODER;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 4;
s->maxdata = 1;
s->len_chanlist = 4;
s->range_table = &range_digital;
s->insn_config = i_APCI1710_InsnConfigInitPulseEncoder;
s->insn_write = i_APCI1710_InsnWriteEnableDisablePulseEncoder;
s->insn_bits = i_APCI1710_InsnBitsReadWritePulseEncoder;
s->insn_read = i_APCI1710_InsnReadInterruptPulseEncoder;
/* Allocate and Initialise INCREMENTALCOUNTER Subdevice Structures */
s = dev->subdevices + 8;
s->type = COMEDI_SUBD_INCREMENTALCOUNTER;
s->subdev_flags =
SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = 500;
s->maxdata = 1;
s->len_chanlist = 500;
s->range_table = &range_apci1710_inccpt;
s->insn_config = i_APCI1710_InsnConfigINCCPT;
s->insn_write = i_APCI1710_InsnWriteINCCPT;
s->insn_read = i_APCI1710_InsnReadINCCPT;
s->insn_bits = i_APCI1710_InsnBitsINCCPT;
}
int i_APCI1710_Reset(struct comedi_device *dev);
void v_APCI1710_Interrupt(int irq, void *d);
/* for 1710 */
int i_APCI1710_Reset(struct comedi_device *dev)
{
int ret;
unsigned int dw_Dummy;
/*********************************/
/* Read all module configuration */
/*********************************/
ret = inl(devpriv->s_BoardInfos.ui_Address + 60);
devpriv->s_BoardInfos.dw_MolduleConfiguration[0] = ret;
ret = inl(devpriv->s_BoardInfos.ui_Address + 124);
devpriv->s_BoardInfos.dw_MolduleConfiguration[1] = ret;
ret = inl(devpriv->s_BoardInfos.ui_Address + 188);
devpriv->s_BoardInfos.dw_MolduleConfiguration[2] = ret;
ret = inl(devpriv->s_BoardInfos.ui_Address + 252);
devpriv->s_BoardInfos.dw_MolduleConfiguration[3] = ret;
/* outl(0x80808082,devpriv->s_BoardInfos.ui_Address+0x60); */
outl(0x83838383, devpriv->s_BoardInfos.ui_Address + 0x60);
devpriv->s_BoardInfos.b_BoardVersion = 1;
/* Enable the interrupt for the controller */
dw_Dummy = inl(devpriv->s_BoardInfos.ui_Address + 0x38);
outl(dw_Dummy | 0x2000, devpriv->s_BoardInfos.ui_Address + 0x38);
return 0;
}
/*
+----------------------------------------------------------------------------+
| Function's Name : __void__ v_APCI1710_InterruptFunction |
| (unsigned char b_Interrupt, __CPPARGS) |
+----------------------------------------------------------------------------+
| Task : APCI-1710 interrupt function |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char b_Interrupt : Interrupt number |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0 : OK |
| -1 : Error |
+----------------------------------------------------------------------------+
*/
void v_APCI1710_Interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
unsigned char b_ModuleCpt = 0;
unsigned char b_InterruptFlag = 0;
unsigned char b_PWMCpt = 0;
unsigned char b_TorCounterCpt = 0;
unsigned char b_PulseIncoderCpt = 0;
unsigned int ui_16BitValue;
unsigned int ul_InterruptLatchReg = 0;
unsigned int ul_LatchRegisterValue = 0;
unsigned int ul_82X54InterruptStatus;
unsigned int ul_StatusRegister;
union str_ModuleInfo *ps_ModuleInfo;
printk("APCI1710 Interrupt\n");
for (b_ModuleCpt = 0; b_ModuleCpt < 4; b_ModuleCpt++, ps_ModuleInfo++) {
/**************************/
/* 1199/0225 to 0100/0226 */
/**************************/
ps_ModuleInfo = &devpriv->s_ModuleInfo[b_ModuleCpt];
/***********************/
/* Test if 82X54 timer */
/***********************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_82X54_TIMER) {
/* printk("TIMER Interrupt Occurred\n"); */
ul_82X54InterruptStatus = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (64 * b_ModuleCpt));
/***************************/
/* Test if interrupt occur */
/***************************/
if ((ul_82X54InterruptStatus & ps_ModuleInfo->
s_82X54ModuleInfo.
b_InterruptMask) != 0) {
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldInterruptMask =
(ul_82X54InterruptStatus &
ps_ModuleInfo->s_82X54ModuleInfo.
b_InterruptMask) << 4;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].
b_OldModuleMask = 1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].ul_OldCounterLatchValue = 0;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write + 1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current, 0);
} /* if ((ul_82X54InterruptStatus & 0x7) != 0) */
} /* 82X54 timer */
/***************************/
/* Test if increm. counter */
/***************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_INCREMENTAL_COUNTER) {
ul_InterruptLatchReg = inl(devpriv->s_BoardInfos.
ui_Address + (64 * b_ModuleCpt));
/*********************/
/* Test if interrupt */
/*********************/
if ((ul_InterruptLatchReg & 0x22) && (ps_ModuleInfo->
s_SiemensCounterInfo.
s_ModeRegister.
s_ByteModeRegister.
b_ModeRegister2 & 0x80)) {
/************************************/
/* Test if strobe latch I interrupt */
/************************************/
if (ul_InterruptLatchReg & 2) {
ul_LatchRegisterValue =
inl(devpriv->s_BoardInfos.
ui_Address + 4 +
(64 * b_ModuleCpt));
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
1UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
}
/*************************************/
/* Test if strobe latch II interrupt */
/*************************************/
if (ul_InterruptLatchReg & 0x20) {
ul_LatchRegisterValue =
inl(devpriv->s_BoardInfos.
ui_Address + 8 +
(64 * b_ModuleCpt));
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
2UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
}
}
ul_InterruptLatchReg = inl(devpriv->s_BoardInfos.
ui_Address + 24 + (64 * b_ModuleCpt));
/***************************/
/* Test if index interrupt */
/***************************/
if (ul_InterruptLatchReg & 0x8) {
ps_ModuleInfo->
s_SiemensCounterInfo.
s_InitFlag.b_IndexInterruptOccur = 1;
if (ps_ModuleInfo->
s_SiemensCounterInfo.
s_ModeRegister.
s_ByteModeRegister.
b_ModeRegister2 &
APCI1710_INDEX_AUTO_MODE) {
outl(ps_ModuleInfo->
s_SiemensCounterInfo.
s_ModeRegister.
dw_ModeRegister1_2_3_4,
devpriv->s_BoardInfos.
ui_Address + 20 +
(64 * b_ModuleCpt));
}
/*****************************/
/* Test if interrupt enabled */
/*****************************/
if ((ps_ModuleInfo->
s_SiemensCounterInfo.
s_ModeRegister.
s_ByteModeRegister.
b_ModeRegister3 &
APCI1710_ENABLE_INDEX_INT) ==
APCI1710_ENABLE_INDEX_INT) {
devpriv->s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
4UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
}
}
/*****************************/
/* Test if compare interrupt */
/*****************************/
if (ul_InterruptLatchReg & 0x10) {
/*****************************/
/* Test if interrupt enabled */
/*****************************/
if ((ps_ModuleInfo->
s_SiemensCounterInfo.
s_ModeRegister.
s_ByteModeRegister.
b_ModeRegister3 &
APCI1710_ENABLE_COMPARE_INT) ==
APCI1710_ENABLE_COMPARE_INT) {
devpriv->s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
8UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
}
}
/*******************************************/
/* Test if frequency measurement interrupt */
/*******************************************/
if (ul_InterruptLatchReg & 0x20) {
/*******************/
/* Read the status */
/*******************/
ul_StatusRegister = inl(devpriv->s_BoardInfos.
ui_Address + 32 + (64 * b_ModuleCpt));
/******************/
/* Read the value */
/******************/
ul_LatchRegisterValue =
inl(devpriv->s_BoardInfos.ui_Address +
28 + (64 * b_ModuleCpt));
switch ((ul_StatusRegister >> 1) & 3) {
case 0:
/*************************/
/* Test the counter mode */
/*************************/
if ((devpriv->s_ModuleInfo[b_ModuleCpt].
s_SiemensCounterInfo.
s_ModeRegister.
s_ByteModeRegister.
b_ModeRegister1 &
APCI1710_16BIT_COUNTER)
== APCI1710_16BIT_COUNTER) {
/****************************************/
/* Test if 16-bit counter 1 pulse occur */
/****************************************/
if ((ul_LatchRegisterValue &
0xFFFFU) != 0) {
ui_16BitValue =
(unsigned int)
ul_LatchRegisterValue
& 0xFFFFU;
ul_LatchRegisterValue =
(ul_LatchRegisterValue
& 0xFFFF0000UL)
| (0xFFFFU -
ui_16BitValue);
}
/****************************************/
/* Test if 16-bit counter 2 pulse occur */
/****************************************/
if ((ul_LatchRegisterValue &
0xFFFF0000UL) !=
0) {
ui_16BitValue =
(unsigned int) (
(ul_LatchRegisterValue
>> 16) &
0xFFFFU);
ul_LatchRegisterValue =
(ul_LatchRegisterValue
& 0xFFFFUL) |
((0xFFFFU -
ui_16BitValue)
<< 16);
}
} else {
if (ul_LatchRegisterValue != 0) {
ul_LatchRegisterValue =
0xFFFFFFFFUL -
ul_LatchRegisterValue;
}
}
break;
case 1:
/****************************************/
/* Test if 16-bit counter 2 pulse occur */
/****************************************/
if ((ul_LatchRegisterValue &
0xFFFF0000UL) != 0) {
ui_16BitValue =
(unsigned int) (
(ul_LatchRegisterValue
>> 16) &
0xFFFFU);
ul_LatchRegisterValue =
(ul_LatchRegisterValue &
0xFFFFUL) | ((0xFFFFU -
ui_16BitValue)
<< 16);
}
break;
case 2:
/****************************************/
/* Test if 16-bit counter 1 pulse occur */
/****************************************/
if ((ul_LatchRegisterValue & 0xFFFFU) !=
0) {
ui_16BitValue =
(unsigned int)
ul_LatchRegisterValue &
0xFFFFU;
ul_LatchRegisterValue =
(ul_LatchRegisterValue &
0xFFFF0000UL) | (0xFFFFU
- ui_16BitValue);
}
break;
}
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldInterruptMask = 0x10000UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].
b_OldModuleMask = 1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write + 1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current, 0);
}
} /* Incremental counter */
/***************/
/* Test if CDA */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_CDA) {
/******************************************/
/* Test if CDA enable and functionality 0 */
/******************************************/
if ((devpriv->s_ModuleInfo[b_ModuleCpt].
s_CDAModuleInfo.
b_CDAEnable == APCI1710_ENABLE)
&& (devpriv->s_ModuleInfo[b_ModuleCpt].
s_CDAModuleInfo.b_FctSelection == 0)) {
/****************************/
/* Get the interrupt status */
/****************************/
ul_StatusRegister = inl(devpriv->s_BoardInfos.
ui_Address + 16 + (64 * b_ModuleCpt));
/***************************/
/* Test if interrupt occur */
/***************************/
if (ul_StatusRegister & 1) {
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
0x80000UL;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue = 0;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
} /* if (ul_StatusRegister & 1) */
}
} /* CDA */
/***********************/
/* Test if PWM counter */
/***********************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_PWM) {
for (b_PWMCpt = 0; b_PWMCpt < 2; b_PWMCpt++) {
/*************************************/
/* Test if PWM interrupt initialised */
/*************************************/
if (devpriv->
s_ModuleInfo[b_ModuleCpt].
s_PWMModuleInfo.
s_PWMInfo[b_PWMCpt].
b_InterruptEnable == APCI1710_ENABLE) {
/*****************************/
/* Read the interrupt status */
/*****************************/
ul_StatusRegister =
inl(devpriv->s_BoardInfos.
ui_Address + 16 +
(20 * b_PWMCpt) +
(64 * b_ModuleCpt));
/***************************/
/* Test if interrupt occur */
/***************************/
if (ul_StatusRegister & 0x1) {
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldInterruptMask =
0x4000UL << b_PWMCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) %
APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO,
devpriv->tsk_Current,
0);
} /* if (ul_StatusRegister & 0x1) */
} /* if (APCI1710_ENABLE) */
} /* for (b_PWMCpt == 0; b_PWMCpt < 0; b_PWMCpt ++) */
} /* PWM counter */
/***********************/
/* Test if tor counter */
/***********************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_TOR_COUNTER) {
for (b_TorCounterCpt = 0; b_TorCounterCpt < 2;
b_TorCounterCpt++) {
/*************************************/
/* Test if tor interrupt initialised */
/*************************************/
if (devpriv->
s_ModuleInfo[b_ModuleCpt].
s_TorCounterModuleInfo.
s_TorCounterInfo[b_TorCounterCpt].
b_InterruptEnable == APCI1710_ENABLE) {
/*****************************/
/* Read the interrupt status */
/*****************************/
ul_StatusRegister =
inl(devpriv->s_BoardInfos.
ui_Address + 12 +
(16 * b_TorCounterCpt) +
(64 * b_ModuleCpt));
/***************************/
/* Test if interrupt occur */
/***************************/
if (ul_StatusRegister & 0x1) {
/******************************/
/* Read the tor counter value */
/******************************/
ul_LatchRegisterValue =
inl(devpriv->
s_BoardInfos.
ui_Address + 0 +
(16 * b_TorCounterCpt) +
(64 * b_ModuleCpt));
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldInterruptMask =
0x1000UL <<
b_TorCounterCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue
= ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) %
APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO,
devpriv->tsk_Current,
0);
} /* if (ul_StatusRegister & 0x1) */
} /* if (APCI1710_ENABLE) */
} /* for (b_TorCounterCpt == 0; b_TorCounterCpt < 0; b_TorCounterCpt ++) */
} /* Tor counter */
/***********************/
/* Test if chronometer */
/***********************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_CHRONOMETER) {
/* printk("APCI1710 Chrono Interrupt\n"); */
/*****************************/
/* Read the interrupt status */
/*****************************/
ul_InterruptLatchReg = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (64 * b_ModuleCpt));
/***************************/
/* Test if interrupt occur */
/***************************/
if ((ul_InterruptLatchReg & 0x8) == 0x8) {
/****************************/
/* Clear the interrupt flag */
/****************************/
outl(0, devpriv->s_BoardInfos.
ui_Address + 32 + (64 * b_ModuleCpt));
/***************************/
/* Test if continuous mode */
/***************************/
if (ps_ModuleInfo->
s_ChronoModuleInfo.
b_CycleMode == APCI1710_ENABLE) {
/********************/
/* Clear the status */
/********************/
outl(0, devpriv->s_BoardInfos.
ui_Address + 36 +
(64 * b_ModuleCpt));
}
/*************************/
/* Read the timing value */
/*************************/
ul_LatchRegisterValue =
inl(devpriv->s_BoardInfos.ui_Address +
4 + (64 * b_ModuleCpt));
/*****************************/
/* Test if interrupt enabled */
/*****************************/
if (ps_ModuleInfo->
s_ChronoModuleInfo.b_InterruptMask) {
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].ul_OldInterruptMask =
0x80;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue =
ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) % APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current,
0);
}
}
} /* Chronometer */
/*************************/
/* Test if pulse encoder */
/*************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModuleCpt] &
0xFFFF0000UL) == APCI1710_PULSE_ENCODER) {
/****************************/
/* Read the status register */
/****************************/
ul_StatusRegister = inl(devpriv->s_BoardInfos.
ui_Address + 20 + (64 * b_ModuleCpt));
if (ul_StatusRegister & 0xF) {
for (b_PulseIncoderCpt = 0;
b_PulseIncoderCpt < 4;
b_PulseIncoderCpt++) {
/*************************************/
/* Test if pulse encoder initialised */
/*************************************/
if ((ps_ModuleInfo->
s_PulseEncoderModuleInfo.
s_PulseEncoderInfo
[b_PulseIncoderCpt].
b_PulseEncoderInit == 1)
&& (((ps_ModuleInfo->s_PulseEncoderModuleInfo.dw_SetRegister >> b_PulseIncoderCpt) & 1) == 1) && (((ul_StatusRegister >> (b_PulseIncoderCpt)) & 1) == 1)) {
devpriv->s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldInterruptMask =
0x100UL <<
b_PulseIncoderCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
b_OldModuleMask =
1 << b_ModuleCpt;
devpriv->
s_InterruptParameters.
s_FIFOInterruptParameters
[devpriv->
s_InterruptParameters.
ui_Write].
ul_OldCounterLatchValue
= ul_LatchRegisterValue;
devpriv->
s_InterruptParameters.
ul_InterruptOccur++;
/****************************/
/* 0899/0224 to 1199/0225 */
/****************************/
/* Increment the write FIFO */
/****************************/
devpriv->
s_InterruptParameters.
ui_Write = (devpriv->
s_InterruptParameters.
ui_Write +
1) %
APCI1710_SAVE_INTERRUPT;
b_InterruptFlag = 1;
/**********************/
/* Call user function */
/**********************/
/* Send a signal to from kernel to user space */
send_sig(SIGIO,
devpriv->tsk_Current,
0);
}
}
}
} /* pulse encoder */
}
return;
}
| gpl-2.0 |
wuby986/Sixty-4Stroke-kernel | arch/tile/kernel/messaging.c | 9683 | 3162 | /*
* Copyright 2010 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.
*/
#include <linux/percpu.h>
#include <linux/smp.h>
#include <linux/hardirq.h>
#include <linux/ptrace.h>
#include <asm/hv_driver.h>
#include <asm/irq_regs.h>
#include <asm/traps.h>
#include <hv/hypervisor.h>
#include <arch/interrupts.h>
/* All messages are stored here */
static DEFINE_PER_CPU(HV_MsgState, msg_state);
void __cpuinit init_messaging(void)
{
/* Allocate storage for messages in kernel space */
HV_MsgState *state = &__get_cpu_var(msg_state);
int rc = hv_register_message_state(state);
if (rc != HV_OK)
panic("hv_register_message_state: error %d", rc);
/* Make sure downcall interrupts will be enabled. */
arch_local_irq_unmask(INT_INTCTRL_K);
}
void hv_message_intr(struct pt_regs *regs, int intnum)
{
/*
* We enter with interrupts disabled and leave them disabled,
* to match expectations of called functions (e.g.
* do_ccupdate_local() in mm/slab.c). This is also consistent
* with normal call entry for device interrupts.
*/
int message[HV_MAX_MESSAGE_SIZE/sizeof(int)];
HV_RcvMsgInfo rmi;
int nmsgs = 0;
/* Track time spent here in an interrupt context */
struct pt_regs *old_regs = set_irq_regs(regs);
irq_enter();
#ifdef CONFIG_DEBUG_STACKOVERFLOW
/* Debugging check for stack overflow: less than 1/8th stack free? */
{
long sp = stack_pointer - (long) current_thread_info();
if (unlikely(sp < (sizeof(struct thread_info) + STACK_WARN))) {
pr_emerg("hv_message_intr: "
"stack overflow: %ld\n",
sp - sizeof(struct thread_info));
dump_stack();
}
}
#endif
while (1) {
rmi = hv_receive_message(__get_cpu_var(msg_state),
(HV_VirtAddr) message,
sizeof(message));
if (rmi.msglen == 0)
break;
if (rmi.msglen < 0)
panic("hv_receive_message failed: %d", rmi.msglen);
++nmsgs;
if (rmi.source == HV_MSG_TILE) {
int tag;
/* we just send tags for now */
BUG_ON(rmi.msglen != sizeof(int));
tag = message[0];
#ifdef CONFIG_SMP
evaluate_message(message[0]);
#else
panic("Received IPI message %d in UP mode", tag);
#endif
} else if (rmi.source == HV_MSG_INTR) {
HV_IntrMsg *him = (HV_IntrMsg *)message;
struct hv_driver_cb *cb =
(struct hv_driver_cb *)him->intarg;
cb->callback(cb, him->intdata);
__get_cpu_var(irq_stat).irq_hv_msg_count++;
}
}
/*
* We shouldn't have gotten a message downcall with no
* messages available.
*/
if (nmsgs == 0)
panic("Message downcall invoked with no messages!");
/*
* Track time spent against the current process again and
* process any softirqs if they are waiting.
*/
irq_exit();
set_irq_regs(old_regs);
}
| gpl-2.0 |
Ca1ne/Underworld-Sense-Kernel-old | arch/x86/math-emu/errors.c | 12243 | 18106 | /*---------------------------------------------------------------------------+
| errors.c |
| |
| The error handling functions for wm-FPU-emu |
| |
| Copyright (C) 1992,1993,1994,1996 |
| W. Metzenthen, 22 Parker St, Ormond, Vic 3163, Australia |
| E-mail billm@jacobi.maths.monash.edu.au |
| |
| |
+---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------+
| Note: |
| The file contains code which accesses user memory. |
| Emulator static data may change when user memory is accessed, due to |
| other processes using the emulator while swapping is in progress. |
+---------------------------------------------------------------------------*/
#include <linux/signal.h>
#include <asm/uaccess.h>
#include "fpu_emu.h"
#include "fpu_system.h"
#include "exception.h"
#include "status_w.h"
#include "control_w.h"
#include "reg_constant.h"
#include "version.h"
/* */
#undef PRINT_MESSAGES
/* */
#if 0
void Un_impl(void)
{
u_char byte1, FPU_modrm;
unsigned long address = FPU_ORIG_EIP;
RE_ENTRANT_CHECK_OFF;
/* No need to check access_ok(), we have previously fetched these bytes. */
printk("Unimplemented FPU Opcode at eip=%p : ", (void __user *)address);
if (FPU_CS == __USER_CS) {
while (1) {
FPU_get_user(byte1, (u_char __user *) address);
if ((byte1 & 0xf8) == 0xd8)
break;
printk("[%02x]", byte1);
address++;
}
printk("%02x ", byte1);
FPU_get_user(FPU_modrm, 1 + (u_char __user *) address);
if (FPU_modrm >= 0300)
printk("%02x (%02x+%d)\n", FPU_modrm, FPU_modrm & 0xf8,
FPU_modrm & 7);
else
printk("/%d\n", (FPU_modrm >> 3) & 7);
} else {
printk("cs selector = %04x\n", FPU_CS);
}
RE_ENTRANT_CHECK_ON;
EXCEPTION(EX_Invalid);
}
#endif /* 0 */
/*
Called for opcodes which are illegal and which are known to result in a
SIGILL with a real 80486.
*/
void FPU_illegal(void)
{
math_abort(FPU_info, SIGILL);
}
void FPU_printall(void)
{
int i;
static const char *tag_desc[] = { "Valid", "Zero", "ERROR", "Empty",
"DeNorm", "Inf", "NaN"
};
u_char byte1, FPU_modrm;
unsigned long address = FPU_ORIG_EIP;
RE_ENTRANT_CHECK_OFF;
/* No need to check access_ok(), we have previously fetched these bytes. */
printk("At %p:", (void *)address);
if (FPU_CS == __USER_CS) {
#define MAX_PRINTED_BYTES 20
for (i = 0; i < MAX_PRINTED_BYTES; i++) {
FPU_get_user(byte1, (u_char __user *) address);
if ((byte1 & 0xf8) == 0xd8) {
printk(" %02x", byte1);
break;
}
printk(" [%02x]", byte1);
address++;
}
if (i == MAX_PRINTED_BYTES)
printk(" [more..]\n");
else {
FPU_get_user(FPU_modrm, 1 + (u_char __user *) address);
if (FPU_modrm >= 0300)
printk(" %02x (%02x+%d)\n", FPU_modrm,
FPU_modrm & 0xf8, FPU_modrm & 7);
else
printk(" /%d, mod=%d rm=%d\n",
(FPU_modrm >> 3) & 7,
(FPU_modrm >> 6) & 3, FPU_modrm & 7);
}
} else {
printk("%04x\n", FPU_CS);
}
partial_status = status_word();
#ifdef DEBUGGING
if (partial_status & SW_Backward)
printk("SW: backward compatibility\n");
if (partial_status & SW_C3)
printk("SW: condition bit 3\n");
if (partial_status & SW_C2)
printk("SW: condition bit 2\n");
if (partial_status & SW_C1)
printk("SW: condition bit 1\n");
if (partial_status & SW_C0)
printk("SW: condition bit 0\n");
if (partial_status & SW_Summary)
printk("SW: exception summary\n");
if (partial_status & SW_Stack_Fault)
printk("SW: stack fault\n");
if (partial_status & SW_Precision)
printk("SW: loss of precision\n");
if (partial_status & SW_Underflow)
printk("SW: underflow\n");
if (partial_status & SW_Overflow)
printk("SW: overflow\n");
if (partial_status & SW_Zero_Div)
printk("SW: divide by zero\n");
if (partial_status & SW_Denorm_Op)
printk("SW: denormalized operand\n");
if (partial_status & SW_Invalid)
printk("SW: invalid operation\n");
#endif /* DEBUGGING */
printk(" SW: b=%d st=%d es=%d sf=%d cc=%d%d%d%d ef=%d%d%d%d%d%d\n", partial_status & 0x8000 ? 1 : 0, /* busy */
(partial_status & 0x3800) >> 11, /* stack top pointer */
partial_status & 0x80 ? 1 : 0, /* Error summary status */
partial_status & 0x40 ? 1 : 0, /* Stack flag */
partial_status & SW_C3 ? 1 : 0, partial_status & SW_C2 ? 1 : 0, /* cc */
partial_status & SW_C1 ? 1 : 0, partial_status & SW_C0 ? 1 : 0, /* cc */
partial_status & SW_Precision ? 1 : 0,
partial_status & SW_Underflow ? 1 : 0,
partial_status & SW_Overflow ? 1 : 0,
partial_status & SW_Zero_Div ? 1 : 0,
partial_status & SW_Denorm_Op ? 1 : 0,
partial_status & SW_Invalid ? 1 : 0);
printk(" CW: ic=%d rc=%d%d pc=%d%d iem=%d ef=%d%d%d%d%d%d\n",
control_word & 0x1000 ? 1 : 0,
(control_word & 0x800) >> 11, (control_word & 0x400) >> 10,
(control_word & 0x200) >> 9, (control_word & 0x100) >> 8,
control_word & 0x80 ? 1 : 0,
control_word & SW_Precision ? 1 : 0,
control_word & SW_Underflow ? 1 : 0,
control_word & SW_Overflow ? 1 : 0,
control_word & SW_Zero_Div ? 1 : 0,
control_word & SW_Denorm_Op ? 1 : 0,
control_word & SW_Invalid ? 1 : 0);
for (i = 0; i < 8; i++) {
FPU_REG *r = &st(i);
u_char tagi = FPU_gettagi(i);
switch (tagi) {
case TAG_Empty:
continue;
break;
case TAG_Zero:
case TAG_Special:
tagi = FPU_Special(r);
case TAG_Valid:
printk("st(%d) %c .%04lx %04lx %04lx %04lx e%+-6d ", i,
getsign(r) ? '-' : '+',
(long)(r->sigh >> 16),
(long)(r->sigh & 0xFFFF),
(long)(r->sigl >> 16),
(long)(r->sigl & 0xFFFF),
exponent(r) - EXP_BIAS + 1);
break;
default:
printk("Whoops! Error in errors.c: tag%d is %d ", i,
tagi);
continue;
break;
}
printk("%s\n", tag_desc[(int)(unsigned)tagi]);
}
RE_ENTRANT_CHECK_ON;
}
static struct {
int type;
const char *name;
} exception_names[] = {
{
EX_StackOver, "stack overflow"}, {
EX_StackUnder, "stack underflow"}, {
EX_Precision, "loss of precision"}, {
EX_Underflow, "underflow"}, {
EX_Overflow, "overflow"}, {
EX_ZeroDiv, "divide by zero"}, {
EX_Denormal, "denormalized operand"}, {
EX_Invalid, "invalid operation"}, {
EX_INTERNAL, "INTERNAL BUG in " FPU_VERSION}, {
0, NULL}
};
/*
EX_INTERNAL is always given with a code which indicates where the
error was detected.
Internal error types:
0x14 in fpu_etc.c
0x1nn in a *.c file:
0x101 in reg_add_sub.c
0x102 in reg_mul.c
0x104 in poly_atan.c
0x105 in reg_mul.c
0x107 in fpu_trig.c
0x108 in reg_compare.c
0x109 in reg_compare.c
0x110 in reg_add_sub.c
0x111 in fpe_entry.c
0x112 in fpu_trig.c
0x113 in errors.c
0x115 in fpu_trig.c
0x116 in fpu_trig.c
0x117 in fpu_trig.c
0x118 in fpu_trig.c
0x119 in fpu_trig.c
0x120 in poly_atan.c
0x121 in reg_compare.c
0x122 in reg_compare.c
0x123 in reg_compare.c
0x125 in fpu_trig.c
0x126 in fpu_entry.c
0x127 in poly_2xm1.c
0x128 in fpu_entry.c
0x129 in fpu_entry.c
0x130 in get_address.c
0x131 in get_address.c
0x132 in get_address.c
0x133 in get_address.c
0x140 in load_store.c
0x141 in load_store.c
0x150 in poly_sin.c
0x151 in poly_sin.c
0x160 in reg_ld_str.c
0x161 in reg_ld_str.c
0x162 in reg_ld_str.c
0x163 in reg_ld_str.c
0x164 in reg_ld_str.c
0x170 in fpu_tags.c
0x171 in fpu_tags.c
0x172 in fpu_tags.c
0x180 in reg_convert.c
0x2nn in an *.S file:
0x201 in reg_u_add.S
0x202 in reg_u_div.S
0x203 in reg_u_div.S
0x204 in reg_u_div.S
0x205 in reg_u_mul.S
0x206 in reg_u_sub.S
0x207 in wm_sqrt.S
0x208 in reg_div.S
0x209 in reg_u_sub.S
0x210 in reg_u_sub.S
0x211 in reg_u_sub.S
0x212 in reg_u_sub.S
0x213 in wm_sqrt.S
0x214 in wm_sqrt.S
0x215 in wm_sqrt.S
0x220 in reg_norm.S
0x221 in reg_norm.S
0x230 in reg_round.S
0x231 in reg_round.S
0x232 in reg_round.S
0x233 in reg_round.S
0x234 in reg_round.S
0x235 in reg_round.S
0x236 in reg_round.S
0x240 in div_Xsig.S
0x241 in div_Xsig.S
0x242 in div_Xsig.S
*/
asmlinkage void FPU_exception(int n)
{
int i, int_type;
int_type = 0; /* Needed only to stop compiler warnings */
if (n & EX_INTERNAL) {
int_type = n - EX_INTERNAL;
n = EX_INTERNAL;
/* Set lots of exception bits! */
partial_status |= (SW_Exc_Mask | SW_Summary | SW_Backward);
} else {
/* Extract only the bits which we use to set the status word */
n &= (SW_Exc_Mask);
/* Set the corresponding exception bit */
partial_status |= n;
/* Set summary bits iff exception isn't masked */
if (partial_status & ~control_word & CW_Exceptions)
partial_status |= (SW_Summary | SW_Backward);
if (n & (SW_Stack_Fault | EX_Precision)) {
if (!(n & SW_C1))
/* This bit distinguishes over- from underflow for a stack fault,
and roundup from round-down for precision loss. */
partial_status &= ~SW_C1;
}
}
RE_ENTRANT_CHECK_OFF;
if ((~control_word & n & CW_Exceptions) || (n == EX_INTERNAL)) {
#ifdef PRINT_MESSAGES
/* My message from the sponsor */
printk(FPU_VERSION " " __DATE__ " (C) W. Metzenthen.\n");
#endif /* PRINT_MESSAGES */
/* Get a name string for error reporting */
for (i = 0; exception_names[i].type; i++)
if ((exception_names[i].type & n) ==
exception_names[i].type)
break;
if (exception_names[i].type) {
#ifdef PRINT_MESSAGES
printk("FP Exception: %s!\n", exception_names[i].name);
#endif /* PRINT_MESSAGES */
} else
printk("FPU emulator: Unknown Exception: 0x%04x!\n", n);
if (n == EX_INTERNAL) {
printk("FPU emulator: Internal error type 0x%04x\n",
int_type);
FPU_printall();
}
#ifdef PRINT_MESSAGES
else
FPU_printall();
#endif /* PRINT_MESSAGES */
/*
* The 80486 generates an interrupt on the next non-control FPU
* instruction. So we need some means of flagging it.
* We use the ES (Error Summary) bit for this.
*/
}
RE_ENTRANT_CHECK_ON;
#ifdef __DEBUG__
math_abort(FPU_info, SIGFPE);
#endif /* __DEBUG__ */
}
/* Real operation attempted on a NaN. */
/* Returns < 0 if the exception is unmasked */
int real_1op_NaN(FPU_REG *a)
{
int signalling, isNaN;
isNaN = (exponent(a) == EXP_OVER) && (a->sigh & 0x80000000);
/* The default result for the case of two "equal" NaNs (signs may
differ) is chosen to reproduce 80486 behaviour */
signalling = isNaN && !(a->sigh & 0x40000000);
if (!signalling) {
if (!isNaN) { /* pseudo-NaN, or other unsupported? */
if (control_word & CW_Invalid) {
/* Masked response */
reg_copy(&CONST_QNaN, a);
}
EXCEPTION(EX_Invalid);
return (!(control_word & CW_Invalid) ? FPU_Exception :
0) | TAG_Special;
}
return TAG_Special;
}
if (control_word & CW_Invalid) {
/* The masked response */
if (!(a->sigh & 0x80000000)) { /* pseudo-NaN ? */
reg_copy(&CONST_QNaN, a);
}
/* ensure a Quiet NaN */
a->sigh |= 0x40000000;
}
EXCEPTION(EX_Invalid);
return (!(control_word & CW_Invalid) ? FPU_Exception : 0) | TAG_Special;
}
/* Real operation attempted on two operands, one a NaN. */
/* Returns < 0 if the exception is unmasked */
int real_2op_NaN(FPU_REG const *b, u_char tagb,
int deststnr, FPU_REG const *defaultNaN)
{
FPU_REG *dest = &st(deststnr);
FPU_REG const *a = dest;
u_char taga = FPU_gettagi(deststnr);
FPU_REG const *x;
int signalling, unsupported;
if (taga == TAG_Special)
taga = FPU_Special(a);
if (tagb == TAG_Special)
tagb = FPU_Special(b);
/* TW_NaN is also used for unsupported data types. */
unsupported = ((taga == TW_NaN)
&& !((exponent(a) == EXP_OVER)
&& (a->sigh & 0x80000000)))
|| ((tagb == TW_NaN)
&& !((exponent(b) == EXP_OVER) && (b->sigh & 0x80000000)));
if (unsupported) {
if (control_word & CW_Invalid) {
/* Masked response */
FPU_copy_to_regi(&CONST_QNaN, TAG_Special, deststnr);
}
EXCEPTION(EX_Invalid);
return (!(control_word & CW_Invalid) ? FPU_Exception : 0) |
TAG_Special;
}
if (taga == TW_NaN) {
x = a;
if (tagb == TW_NaN) {
signalling = !(a->sigh & b->sigh & 0x40000000);
if (significand(b) > significand(a))
x = b;
else if (significand(b) == significand(a)) {
/* The default result for the case of two "equal" NaNs (signs may
differ) is chosen to reproduce 80486 behaviour */
x = defaultNaN;
}
} else {
/* return the quiet version of the NaN in a */
signalling = !(a->sigh & 0x40000000);
}
} else
#ifdef PARANOID
if (tagb == TW_NaN)
#endif /* PARANOID */
{
signalling = !(b->sigh & 0x40000000);
x = b;
}
#ifdef PARANOID
else {
signalling = 0;
EXCEPTION(EX_INTERNAL | 0x113);
x = &CONST_QNaN;
}
#endif /* PARANOID */
if ((!signalling) || (control_word & CW_Invalid)) {
if (!x)
x = b;
if (!(x->sigh & 0x80000000)) /* pseudo-NaN ? */
x = &CONST_QNaN;
FPU_copy_to_regi(x, TAG_Special, deststnr);
if (!signalling)
return TAG_Special;
/* ensure a Quiet NaN */
dest->sigh |= 0x40000000;
}
EXCEPTION(EX_Invalid);
return (!(control_word & CW_Invalid) ? FPU_Exception : 0) | TAG_Special;
}
/* Invalid arith operation on Valid registers */
/* Returns < 0 if the exception is unmasked */
asmlinkage int arith_invalid(int deststnr)
{
EXCEPTION(EX_Invalid);
if (control_word & CW_Invalid) {
/* The masked response */
FPU_copy_to_regi(&CONST_QNaN, TAG_Special, deststnr);
}
return (!(control_word & CW_Invalid) ? FPU_Exception : 0) | TAG_Valid;
}
/* Divide a finite number by zero */
asmlinkage int FPU_divide_by_zero(int deststnr, u_char sign)
{
FPU_REG *dest = &st(deststnr);
int tag = TAG_Valid;
if (control_word & CW_ZeroDiv) {
/* The masked response */
FPU_copy_to_regi(&CONST_INF, TAG_Special, deststnr);
setsign(dest, sign);
tag = TAG_Special;
}
EXCEPTION(EX_ZeroDiv);
return (!(control_word & CW_ZeroDiv) ? FPU_Exception : 0) | tag;
}
/* This may be called often, so keep it lean */
int set_precision_flag(int flags)
{
if (control_word & CW_Precision) {
partial_status &= ~(SW_C1 & flags);
partial_status |= flags; /* The masked response */
return 0;
} else {
EXCEPTION(flags);
return 1;
}
}
/* This may be called often, so keep it lean */
asmlinkage void set_precision_flag_up(void)
{
if (control_word & CW_Precision)
partial_status |= (SW_Precision | SW_C1); /* The masked response */
else
EXCEPTION(EX_Precision | SW_C1);
}
/* This may be called often, so keep it lean */
asmlinkage void set_precision_flag_down(void)
{
if (control_word & CW_Precision) { /* The masked response */
partial_status &= ~SW_C1;
partial_status |= SW_Precision;
} else
EXCEPTION(EX_Precision);
}
asmlinkage int denormal_operand(void)
{
if (control_word & CW_Denormal) { /* The masked response */
partial_status |= SW_Denorm_Op;
return TAG_Special;
} else {
EXCEPTION(EX_Denormal);
return TAG_Special | FPU_Exception;
}
}
asmlinkage int arith_overflow(FPU_REG *dest)
{
int tag = TAG_Valid;
if (control_word & CW_Overflow) {
/* The masked response */
/* ###### The response here depends upon the rounding mode */
reg_copy(&CONST_INF, dest);
tag = TAG_Special;
} else {
/* Subtract the magic number from the exponent */
addexponent(dest, (-3 * (1 << 13)));
}
EXCEPTION(EX_Overflow);
if (control_word & CW_Overflow) {
/* The overflow exception is masked. */
/* By definition, precision is lost.
The roundup bit (C1) is also set because we have
"rounded" upwards to Infinity. */
EXCEPTION(EX_Precision | SW_C1);
return tag;
}
return tag;
}
asmlinkage int arith_underflow(FPU_REG *dest)
{
int tag = TAG_Valid;
if (control_word & CW_Underflow) {
/* The masked response */
if (exponent16(dest) <= EXP_UNDER - 63) {
reg_copy(&CONST_Z, dest);
partial_status &= ~SW_C1; /* Round down. */
tag = TAG_Zero;
} else {
stdexp(dest);
}
} else {
/* Add the magic number to the exponent. */
addexponent(dest, (3 * (1 << 13)) + EXTENDED_Ebias);
}
EXCEPTION(EX_Underflow);
if (control_word & CW_Underflow) {
/* The underflow exception is masked. */
EXCEPTION(EX_Precision);
return tag;
}
return tag;
}
void FPU_stack_overflow(void)
{
if (control_word & CW_Invalid) {
/* The masked response */
top--;
FPU_copy_to_reg0(&CONST_QNaN, TAG_Special);
}
EXCEPTION(EX_StackOver);
return;
}
void FPU_stack_underflow(void)
{
if (control_word & CW_Invalid) {
/* The masked response */
FPU_copy_to_reg0(&CONST_QNaN, TAG_Special);
}
EXCEPTION(EX_StackUnder);
return;
}
void FPU_stack_underflow_i(int i)
{
if (control_word & CW_Invalid) {
/* The masked response */
FPU_copy_to_regi(&CONST_QNaN, TAG_Special, i);
}
EXCEPTION(EX_StackUnder);
return;
}
void FPU_stack_underflow_pop(int i)
{
if (control_word & CW_Invalid) {
/* The masked response */
FPU_copy_to_regi(&CONST_QNaN, TAG_Special, i);
FPU_pop();
}
EXCEPTION(EX_StackUnder);
return;
}
| gpl-2.0 |
PaoloW8/android_kernel_nubia_nx505j | arch/blackfin/kernel/flat.c | 13523 | 2088 | /*
* Copyright 2007 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/flat.h>
#define FLAT_BFIN_RELOC_TYPE_16_BIT 0
#define FLAT_BFIN_RELOC_TYPE_16H_BIT 1
#define FLAT_BFIN_RELOC_TYPE_32_BIT 2
unsigned long bfin_get_addr_from_rp(unsigned long *ptr,
unsigned long relval,
unsigned long flags,
unsigned long *persistent)
{
unsigned short *usptr = (unsigned short *)ptr;
int type = (relval >> 26) & 7;
unsigned long val;
switch (type) {
case FLAT_BFIN_RELOC_TYPE_16_BIT:
case FLAT_BFIN_RELOC_TYPE_16H_BIT:
usptr = (unsigned short *)ptr;
pr_debug("*usptr = %x", get_unaligned(usptr));
val = get_unaligned(usptr);
val += *persistent;
break;
case FLAT_BFIN_RELOC_TYPE_32_BIT:
pr_debug("*ptr = %lx", get_unaligned(ptr));
val = get_unaligned(ptr);
break;
default:
pr_debug("BINFMT_FLAT: Unknown relocation type %x\n", type);
return 0;
}
/*
* Stack-relative relocs contain the offset into the stack, we
* have to add the stack's start address here and return 1 from
* flat_addr_absolute to prevent the normal address calculations
*/
if (relval & (1 << 29))
return val + current->mm->context.end_brk;
if ((flags & FLAT_FLAG_GOTPIC) == 0)
val = htonl(val);
return val;
}
EXPORT_SYMBOL(bfin_get_addr_from_rp);
/*
* Insert the address ADDR into the symbol reference at RP;
* RELVAL is the raw relocation-table entry from which RP is derived
*/
void bfin_put_addr_at_rp(unsigned long *ptr, unsigned long addr,
unsigned long relval)
{
unsigned short *usptr = (unsigned short *)ptr;
int type = (relval >> 26) & 7;
switch (type) {
case FLAT_BFIN_RELOC_TYPE_16_BIT:
put_unaligned(addr, usptr);
pr_debug("new value %x at %p", get_unaligned(usptr), usptr);
break;
case FLAT_BFIN_RELOC_TYPE_16H_BIT:
put_unaligned(addr >> 16, usptr);
pr_debug("new value %x", get_unaligned(usptr));
break;
case FLAT_BFIN_RELOC_TYPE_32_BIT:
put_unaligned(addr, ptr);
pr_debug("new ptr =%lx", get_unaligned(ptr));
break;
}
}
EXPORT_SYMBOL(bfin_put_addr_at_rp);
| gpl-2.0 |
CallMeAldy/kernel_lge_mako | net/netfilter/nf_conntrack_h323_types.c | 14547 | 89907 | /* Generated by Jing Min Zhao's ASN.1 parser, May 16 2007
*
* Copyright (c) 2006 Jing Min Zhao <zhaojingmin@users.sourceforge.net>
*
* This source code is licensed under General Public License version 2.
*/
static const struct field_t _TransportAddress_ipAddress[] = { /* SEQUENCE */
{FNAME("ip") OCTSTR, FIXD, 4, 0, DECODE,
offsetof(TransportAddress_ipAddress, ip), NULL},
{FNAME("port") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _TransportAddress_ipSourceRoute_route[] = { /* SEQUENCE OF */
{FNAME("item") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
};
static const struct field_t _TransportAddress_ipSourceRoute_routing[] = { /* CHOICE */
{FNAME("strict") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("loose") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _TransportAddress_ipSourceRoute[] = { /* SEQUENCE */
{FNAME("ip") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
{FNAME("port") INT, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("route") SEQOF, SEMI, 0, 0, SKIP, 0,
_TransportAddress_ipSourceRoute_route},
{FNAME("routing") CHOICE, 1, 2, 2, SKIP | EXT, 0,
_TransportAddress_ipSourceRoute_routing},
};
static const struct field_t _TransportAddress_ipxAddress[] = { /* SEQUENCE */
{FNAME("node") OCTSTR, FIXD, 6, 0, SKIP, 0, NULL},
{FNAME("netnum") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
{FNAME("port") OCTSTR, FIXD, 2, 0, SKIP, 0, NULL},
};
static const struct field_t _TransportAddress_ip6Address[] = { /* SEQUENCE */
{FNAME("ip") OCTSTR, FIXD, 16, 0, DECODE,
offsetof(TransportAddress_ip6Address, ip), NULL},
{FNAME("port") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H221NonStandard[] = { /* SEQUENCE */
{FNAME("t35CountryCode") INT, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("t35Extension") INT, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("manufacturerCode") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _NonStandardIdentifier[] = { /* CHOICE */
{FNAME("object") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("h221NonStandard") SEQ, 0, 3, 3, SKIP | EXT, 0,
_H221NonStandard},
};
static const struct field_t _NonStandardParameter[] = { /* SEQUENCE */
{FNAME("nonStandardIdentifier") CHOICE, 1, 2, 2, SKIP | EXT, 0,
_NonStandardIdentifier},
{FNAME("data") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _TransportAddress[] = { /* CHOICE */
{FNAME("ipAddress") SEQ, 0, 2, 2, DECODE,
offsetof(TransportAddress, ipAddress), _TransportAddress_ipAddress},
{FNAME("ipSourceRoute") SEQ, 0, 4, 4, SKIP | EXT, 0,
_TransportAddress_ipSourceRoute},
{FNAME("ipxAddress") SEQ, 0, 3, 3, SKIP, 0,
_TransportAddress_ipxAddress},
{FNAME("ip6Address") SEQ, 0, 2, 2, DECODE | EXT,
offsetof(TransportAddress, ip6Address),
_TransportAddress_ip6Address},
{FNAME("netBios") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
{FNAME("nsap") OCTSTR, 5, 1, 0, SKIP, 0, NULL},
{FNAME("nonStandardAddress") SEQ, 0, 2, 2, SKIP, 0,
_NonStandardParameter},
};
static const struct field_t _AliasAddress[] = { /* CHOICE */
{FNAME("dialedDigits") NUMDGT, 7, 1, 0, SKIP, 0, NULL},
{FNAME("h323-ID") BMPSTR, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("url-ID") IA5STR, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("transportID") CHOICE, 3, 7, 7, SKIP | EXT, 0, NULL},
{FNAME("email-ID") IA5STR, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("partyNumber") CHOICE, 3, 5, 5, SKIP | EXT, 0, NULL},
{FNAME("mobileUIM") CHOICE, 1, 2, 2, SKIP | EXT, 0, NULL},
};
static const struct field_t _Setup_UUIE_sourceAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _VendorIdentifier[] = { /* SEQUENCE */
{FNAME("vendor") SEQ, 0, 3, 3, SKIP | EXT, 0, _H221NonStandard},
{FNAME("productId") OCTSTR, BYTE, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("versionId") OCTSTR, BYTE, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _GatekeeperInfo[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
};
static const struct field_t _H310Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H320Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H321Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H322Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H323Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H324Caps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _VoiceCaps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _T120OnlyCaps[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("dataRatesSupported") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _SupportedProtocols[] = { /* CHOICE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP, 0,
_NonStandardParameter},
{FNAME("h310") SEQ, 1, 1, 3, SKIP | EXT, 0, _H310Caps},
{FNAME("h320") SEQ, 1, 1, 3, SKIP | EXT, 0, _H320Caps},
{FNAME("h321") SEQ, 1, 1, 3, SKIP | EXT, 0, _H321Caps},
{FNAME("h322") SEQ, 1, 1, 3, SKIP | EXT, 0, _H322Caps},
{FNAME("h323") SEQ, 1, 1, 3, SKIP | EXT, 0, _H323Caps},
{FNAME("h324") SEQ, 1, 1, 3, SKIP | EXT, 0, _H324Caps},
{FNAME("voice") SEQ, 1, 1, 3, SKIP | EXT, 0, _VoiceCaps},
{FNAME("t120-only") SEQ, 1, 1, 3, SKIP | EXT, 0, _T120OnlyCaps},
{FNAME("nonStandardProtocol") SEQ, 2, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("t38FaxAnnexbOnly") SEQ, 2, 5, 5, SKIP | EXT, 0, NULL},
};
static const struct field_t _GatewayInfo_protocol[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 4, 9, 11, SKIP | EXT, 0, _SupportedProtocols},
};
static const struct field_t _GatewayInfo[] = { /* SEQUENCE */
{FNAME("protocol") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_GatewayInfo_protocol},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
};
static const struct field_t _McuInfo[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("protocol") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _TerminalInfo[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
};
static const struct field_t _EndpointType[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("vendor") SEQ, 2, 3, 3, SKIP | EXT | OPT, 0,
_VendorIdentifier},
{FNAME("gatekeeper") SEQ, 1, 1, 1, SKIP | EXT | OPT, 0,
_GatekeeperInfo},
{FNAME("gateway") SEQ, 2, 2, 2, SKIP | EXT | OPT, 0, _GatewayInfo},
{FNAME("mcu") SEQ, 1, 1, 2, SKIP | EXT | OPT, 0, _McuInfo},
{FNAME("terminal") SEQ, 1, 1, 1, SKIP | EXT | OPT, 0, _TerminalInfo},
{FNAME("mc") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("undefinedNode") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("set") BITSTR, FIXD, 32, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedTunnelledProtocols") SEQOF, SEMI, 0, 0, SKIP | OPT,
0, NULL},
};
static const struct field_t _Setup_UUIE_destinationAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _Setup_UUIE_destExtraCallInfo[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _Setup_UUIE_destExtraCRV[] = { /* SEQUENCE OF */
{FNAME("item") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _Setup_UUIE_conferenceGoal[] = { /* CHOICE */
{FNAME("create") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("join") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("invite") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("capability-negotiation") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("callIndependentSupplementaryService") NUL, FIXD, 0, 0, SKIP,
0, NULL},
};
static const struct field_t _Q954Details[] = { /* SEQUENCE */
{FNAME("conferenceCalling") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("threePartyService") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _QseriesOptions[] = { /* SEQUENCE */
{FNAME("q932Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q951Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q952Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q953Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q955Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q956Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q957Full") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("q954Info") SEQ, 0, 2, 2, SKIP | EXT, 0, _Q954Details},
};
static const struct field_t _CallType[] = { /* CHOICE */
{FNAME("pointToPoint") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("oneToN") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("nToOne") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("nToN") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H245_NonStandardIdentifier_h221NonStandard[] = { /* SEQUENCE */
{FNAME("t35CountryCode") INT, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("t35Extension") INT, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("manufacturerCode") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H245_NonStandardIdentifier[] = { /* CHOICE */
{FNAME("object") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("h221NonStandard") SEQ, 0, 3, 3, SKIP, 0,
_H245_NonStandardIdentifier_h221NonStandard},
};
static const struct field_t _H245_NonStandardParameter[] = { /* SEQUENCE */
{FNAME("nonStandardIdentifier") CHOICE, 1, 2, 2, SKIP, 0,
_H245_NonStandardIdentifier},
{FNAME("data") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H261VideoCapability[] = { /* SEQUENCE */
{FNAME("qcifMPI") INT, 2, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("cifMPI") INT, 2, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("temporalSpatialTradeOffCapability") BOOL, FIXD, 0, 0, SKIP, 0,
NULL},
{FNAME("maxBitRate") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("stillImageTransmission") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("videoBadMBsCap") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H262VideoCapability[] = { /* SEQUENCE */
{FNAME("profileAndLevel-SPatML") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-MPatLL") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-MPatML") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-MPatH-14") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-MPatHL") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-SNRatLL") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-SNRatML") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-SpatialatH-14") BOOL, FIXD, 0, 0, SKIP, 0,
NULL},
{FNAME("profileAndLevel-HPatML") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-HPatH-14") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("profileAndLevel-HPatHL") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("videoBitRate") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("vbvBufferSize") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("samplesPerLine") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("linesPerFrame") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("framesPerSecond") INT, 4, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("luminanceSampleRate") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("videoBadMBsCap") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H263VideoCapability[] = { /* SEQUENCE */
{FNAME("sqcifMPI") INT, 5, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("qcifMPI") INT, 5, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("cifMPI") INT, 5, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("cif4MPI") INT, 5, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("cif16MPI") INT, 5, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("maxBitRate") INT, CONS, 1, 0, SKIP, 0, NULL},
{FNAME("unrestrictedVector") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("arithmeticCoding") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("advancedPrediction") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("pbFrames") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("temporalSpatialTradeOffCapability") BOOL, FIXD, 0, 0, SKIP, 0,
NULL},
{FNAME("hrd-B") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("bppMaxKb") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("slowSqcifMPI") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("slowQcifMPI") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("slowCifMPI") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("slowCif4MPI") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("slowCif16MPI") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("errorCompensation") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("enhancementLayerInfo") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0,
NULL},
{FNAME("h263Options") SEQ, 5, 29, 31, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _IS11172VideoCapability[] = { /* SEQUENCE */
{FNAME("constrainedBitstream") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("videoBitRate") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("vbvBufferSize") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("samplesPerLine") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("linesPerFrame") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("pictureRate") INT, 4, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("luminanceSampleRate") INT, CONS, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("videoBadMBsCap") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _VideoCapability[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("h261VideoCapability") SEQ, 2, 5, 6, SKIP | EXT, 0,
_H261VideoCapability},
{FNAME("h262VideoCapability") SEQ, 6, 17, 18, SKIP | EXT, 0,
_H262VideoCapability},
{FNAME("h263VideoCapability") SEQ, 7, 13, 21, SKIP | EXT, 0,
_H263VideoCapability},
{FNAME("is11172VideoCapability") SEQ, 6, 7, 8, SKIP | EXT, 0,
_IS11172VideoCapability},
{FNAME("genericVideoCapability") SEQ, 5, 6, 6, SKIP | EXT, 0, NULL},
};
static const struct field_t _AudioCapability_g7231[] = { /* SEQUENCE */
{FNAME("maxAl-sduAudioFrames") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("silenceSuppression") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _IS11172AudioCapability[] = { /* SEQUENCE */
{FNAME("audioLayer1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioLayer2") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioLayer3") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling32k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling44k1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling48k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("singleChannel") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("twoChannels") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("bitRate") INT, WORD, 1, 0, SKIP, 0, NULL},
};
static const struct field_t _IS13818AudioCapability[] = { /* SEQUENCE */
{FNAME("audioLayer1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioLayer2") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioLayer3") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling16k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling22k05") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling24k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling32k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling44k1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("audioSampling48k") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("singleChannel") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("twoChannels") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("threeChannels2-1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("threeChannels3-0") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fourChannels2-0-2-0") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fourChannels2-2") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fourChannels3-1") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fiveChannels3-0-2-0") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fiveChannels3-2") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("lowFrequencyEnhancement") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("multilingual") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("bitRate") INT, WORD, 1, 0, SKIP, 0, NULL},
};
static const struct field_t _AudioCapability[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("g711Alaw64k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g711Alaw56k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g711Ulaw64k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g711Ulaw56k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g722-64k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g722-56k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g722-48k") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g7231") SEQ, 0, 2, 2, SKIP, 0, _AudioCapability_g7231},
{FNAME("g728") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g729") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g729AnnexA") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("is11172AudioCapability") SEQ, 0, 9, 9, SKIP | EXT, 0,
_IS11172AudioCapability},
{FNAME("is13818AudioCapability") SEQ, 0, 21, 21, SKIP | EXT, 0,
_IS13818AudioCapability},
{FNAME("g729wAnnexB") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g729AnnexAwAnnexB") INT, BYTE, 1, 0, SKIP, 0, NULL},
{FNAME("g7231AnnexCCapability") SEQ, 1, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("gsmFullRate") SEQ, 0, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("gsmHalfRate") SEQ, 0, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("gsmEnhancedFullRate") SEQ, 0, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("genericAudioCapability") SEQ, 5, 6, 6, SKIP | EXT, 0, NULL},
{FNAME("g729Extensions") SEQ, 1, 8, 8, SKIP | EXT, 0, NULL},
};
static const struct field_t _DataProtocolCapability[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("v14buffered") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("v42lapm") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("hdlcFrameTunnelling") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("h310SeparateVCStack") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("h310SingleVCStack") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("transparent") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("segmentationAndReassembly") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("hdlcFrameTunnelingwSAR") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("v120") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("separateLANStack") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("v76wCompression") CHOICE, 2, 3, 3, SKIP | EXT, 0, NULL},
{FNAME("tcp") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("udp") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _T84Profile_t84Restricted[] = { /* SEQUENCE */
{FNAME("qcif") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("cif") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("ccir601Seq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("ccir601Prog") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("hdtvSeq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("hdtvProg") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("g3FacsMH200x100") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("g3FacsMH200x200") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("g4FacsMMR200x100") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("g4FacsMMR200x200") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("jbig200x200Seq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("jbig200x200Prog") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("jbig300x300Seq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("jbig300x300Prog") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("digPhotoLow") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("digPhotoMedSeq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("digPhotoMedProg") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("digPhotoHighSeq") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("digPhotoHighProg") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _T84Profile[] = { /* CHOICE */
{FNAME("t84Unrestricted") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("t84Restricted") SEQ, 0, 19, 19, SKIP | EXT, 0,
_T84Profile_t84Restricted},
};
static const struct field_t _DataApplicationCapability_application_t84[] = { /* SEQUENCE */
{FNAME("t84Protocol") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("t84Profile") CHOICE, 1, 2, 2, SKIP, 0, _T84Profile},
};
static const struct field_t _DataApplicationCapability_application_nlpid[] = { /* SEQUENCE */
{FNAME("nlpidProtocol") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("nlpidData") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _DataApplicationCapability_application[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("t120") CHOICE, 3, 7, 14, DECODE | EXT,
offsetof(DataApplicationCapability_application, t120),
_DataProtocolCapability},
{FNAME("dsm-cc") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("userData") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("t84") SEQ, 0, 2, 2, SKIP, 0,
_DataApplicationCapability_application_t84},
{FNAME("t434") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("h224") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("nlpid") SEQ, 0, 2, 2, SKIP, 0,
_DataApplicationCapability_application_nlpid},
{FNAME("dsvdControl") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("h222DataPartitioning") CHOICE, 3, 7, 14, SKIP | EXT, 0,
_DataProtocolCapability},
{FNAME("t30fax") CHOICE, 3, 7, 14, SKIP | EXT, 0, NULL},
{FNAME("t140") CHOICE, 3, 7, 14, SKIP | EXT, 0, NULL},
{FNAME("t38fax") SEQ, 0, 2, 2, SKIP, 0, NULL},
{FNAME("genericDataCapability") SEQ, 5, 6, 6, SKIP | EXT, 0, NULL},
};
static const struct field_t _DataApplicationCapability[] = { /* SEQUENCE */
{FNAME("application") CHOICE, 4, 10, 14, DECODE | EXT,
offsetof(DataApplicationCapability, application),
_DataApplicationCapability_application},
{FNAME("maxBitRate") INT, CONS, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _EncryptionMode[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("h233Encryption") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _DataType[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("nullData") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("videoData") CHOICE, 3, 5, 6, SKIP | EXT, 0, _VideoCapability},
{FNAME("audioData") CHOICE, 4, 14, 22, SKIP | EXT, 0,
_AudioCapability},
{FNAME("data") SEQ, 0, 2, 2, DECODE | EXT, offsetof(DataType, data),
_DataApplicationCapability},
{FNAME("encryptionData") CHOICE, 1, 2, 2, SKIP | EXT, 0,
_EncryptionMode},
{FNAME("h235Control") SEQ, 0, 2, 2, SKIP, 0, NULL},
{FNAME("h235Media") SEQ, 0, 2, 2, SKIP | EXT, 0, NULL},
{FNAME("multiplexedStream") SEQ, 0, 2, 2, SKIP | EXT, 0, NULL},
};
static const struct field_t _H222LogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("resourceID") INT, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("subChannelID") INT, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("pcr-pid") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("programDescriptors") OCTSTR, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("streamDescriptors") OCTSTR, SEMI, 0, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _H223LogicalChannelParameters_adaptationLayerType_al3[] = { /* SEQUENCE */
{FNAME("controlFieldOctets") INT, 2, 0, 0, SKIP, 0, NULL},
{FNAME("sendBufferSize") INT, CONS, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H223LogicalChannelParameters_adaptationLayerType[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0,
_H245_NonStandardParameter},
{FNAME("al1Framed") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("al1NotFramed") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("al2WithoutSequenceNumbers") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("al2WithSequenceNumbers") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("al3") SEQ, 0, 2, 2, SKIP, 0,
_H223LogicalChannelParameters_adaptationLayerType_al3},
{FNAME("al1M") SEQ, 0, 7, 8, SKIP | EXT, 0, NULL},
{FNAME("al2M") SEQ, 0, 2, 2, SKIP | EXT, 0, NULL},
{FNAME("al3M") SEQ, 0, 5, 6, SKIP | EXT, 0, NULL},
};
static const struct field_t _H223LogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("adaptationLayerType") CHOICE, 3, 6, 9, SKIP | EXT, 0,
_H223LogicalChannelParameters_adaptationLayerType},
{FNAME("segmentableFlag") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CRCLength[] = { /* CHOICE */
{FNAME("crc8bit") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("crc16bit") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("crc32bit") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V76HDLCParameters[] = { /* SEQUENCE */
{FNAME("crcLength") CHOICE, 2, 3, 3, SKIP | EXT, 0, _CRCLength},
{FNAME("n401") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("loopbackTestProcedure") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V76LogicalChannelParameters_suspendResume[] = { /* CHOICE */
{FNAME("noSuspendResume") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("suspendResumewAddress") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("suspendResumewoAddress") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V76LogicalChannelParameters_mode_eRM_recovery[] = { /* CHOICE */
{FNAME("rej") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("sREJ") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("mSREJ") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V76LogicalChannelParameters_mode_eRM[] = { /* SEQUENCE */
{FNAME("windowSize") INT, 7, 1, 0, SKIP, 0, NULL},
{FNAME("recovery") CHOICE, 2, 3, 3, SKIP | EXT, 0,
_V76LogicalChannelParameters_mode_eRM_recovery},
};
static const struct field_t _V76LogicalChannelParameters_mode[] = { /* CHOICE */
{FNAME("eRM") SEQ, 0, 2, 2, SKIP | EXT, 0,
_V76LogicalChannelParameters_mode_eRM},
{FNAME("uNERM") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V75Parameters[] = { /* SEQUENCE */
{FNAME("audioHeaderPresent") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _V76LogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("hdlcParameters") SEQ, 0, 3, 3, SKIP | EXT, 0,
_V76HDLCParameters},
{FNAME("suspendResume") CHOICE, 2, 3, 3, SKIP | EXT, 0,
_V76LogicalChannelParameters_suspendResume},
{FNAME("uIH") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("mode") CHOICE, 1, 2, 2, SKIP | EXT, 0,
_V76LogicalChannelParameters_mode},
{FNAME("v75Parameters") SEQ, 0, 1, 1, SKIP | EXT, 0, _V75Parameters},
};
static const struct field_t _H2250LogicalChannelParameters_nonStandard[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 0, 2, 2, SKIP, 0, _H245_NonStandardParameter},
};
static const struct field_t _UnicastAddress_iPAddress[] = { /* SEQUENCE */
{FNAME("network") OCTSTR, FIXD, 4, 0, DECODE,
offsetof(UnicastAddress_iPAddress, network), NULL},
{FNAME("tsapIdentifier") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _UnicastAddress_iPXAddress[] = { /* SEQUENCE */
{FNAME("node") OCTSTR, FIXD, 6, 0, SKIP, 0, NULL},
{FNAME("netnum") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
{FNAME("tsapIdentifier") OCTSTR, FIXD, 2, 0, SKIP, 0, NULL},
};
static const struct field_t _UnicastAddress_iP6Address[] = { /* SEQUENCE */
{FNAME("network") OCTSTR, FIXD, 16, 0, DECODE,
offsetof(UnicastAddress_iP6Address, network), NULL},
{FNAME("tsapIdentifier") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _UnicastAddress_iPSourceRouteAddress_routing[] = { /* CHOICE */
{FNAME("strict") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("loose") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _UnicastAddress_iPSourceRouteAddress_route[] = { /* SEQUENCE OF */
{FNAME("item") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
};
static const struct field_t _UnicastAddress_iPSourceRouteAddress[] = { /* SEQUENCE */
{FNAME("routing") CHOICE, 1, 2, 2, SKIP, 0,
_UnicastAddress_iPSourceRouteAddress_routing},
{FNAME("network") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
{FNAME("tsapIdentifier") INT, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("route") SEQOF, SEMI, 0, 0, SKIP, 0,
_UnicastAddress_iPSourceRouteAddress_route},
};
static const struct field_t _UnicastAddress[] = { /* CHOICE */
{FNAME("iPAddress") SEQ, 0, 2, 2, DECODE | EXT,
offsetof(UnicastAddress, iPAddress), _UnicastAddress_iPAddress},
{FNAME("iPXAddress") SEQ, 0, 3, 3, SKIP | EXT, 0,
_UnicastAddress_iPXAddress},
{FNAME("iP6Address") SEQ, 0, 2, 2, DECODE | EXT,
offsetof(UnicastAddress, iP6Address), _UnicastAddress_iP6Address},
{FNAME("netBios") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
{FNAME("iPSourceRouteAddress") SEQ, 0, 4, 4, SKIP | EXT, 0,
_UnicastAddress_iPSourceRouteAddress},
{FNAME("nsap") OCTSTR, 5, 1, 0, SKIP, 0, NULL},
{FNAME("nonStandardAddress") SEQ, 0, 2, 2, SKIP, 0, NULL},
};
static const struct field_t _MulticastAddress_iPAddress[] = { /* SEQUENCE */
{FNAME("network") OCTSTR, FIXD, 4, 0, SKIP, 0, NULL},
{FNAME("tsapIdentifier") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _MulticastAddress_iP6Address[] = { /* SEQUENCE */
{FNAME("network") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
{FNAME("tsapIdentifier") INT, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _MulticastAddress[] = { /* CHOICE */
{FNAME("iPAddress") SEQ, 0, 2, 2, SKIP | EXT, 0,
_MulticastAddress_iPAddress},
{FNAME("iP6Address") SEQ, 0, 2, 2, SKIP | EXT, 0,
_MulticastAddress_iP6Address},
{FNAME("nsap") OCTSTR, 5, 1, 0, SKIP, 0, NULL},
{FNAME("nonStandardAddress") SEQ, 0, 2, 2, SKIP, 0, NULL},
};
static const struct field_t _H245_TransportAddress[] = { /* CHOICE */
{FNAME("unicastAddress") CHOICE, 3, 5, 7, DECODE | EXT,
offsetof(H245_TransportAddress, unicastAddress), _UnicastAddress},
{FNAME("multicastAddress") CHOICE, 1, 2, 4, SKIP | EXT, 0,
_MulticastAddress},
};
static const struct field_t _H2250LogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("nonStandard") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_H2250LogicalChannelParameters_nonStandard},
{FNAME("sessionID") INT, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("associatedSessionID") INT, 8, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("mediaChannel") CHOICE, 1, 2, 2, DECODE | EXT | OPT,
offsetof(H2250LogicalChannelParameters, mediaChannel),
_H245_TransportAddress},
{FNAME("mediaGuaranteedDelivery") BOOL, FIXD, 0, 0, SKIP | OPT, 0,
NULL},
{FNAME("mediaControlChannel") CHOICE, 1, 2, 2, DECODE | EXT | OPT,
offsetof(H2250LogicalChannelParameters, mediaControlChannel),
_H245_TransportAddress},
{FNAME("mediaControlGuaranteedDelivery") BOOL, FIXD, 0, 0, STOP | OPT,
0, NULL},
{FNAME("silenceSuppression") BOOL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destination") SEQ, 0, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("dynamicRTPPayloadType") INT, 5, 96, 0, STOP | OPT, 0, NULL},
{FNAME("mediaPacketization") CHOICE, 0, 1, 2, STOP | EXT | OPT, 0,
NULL},
{FNAME("transportCapability") SEQ, 3, 3, 3, STOP | EXT | OPT, 0,
NULL},
{FNAME("redundancyEncoding") SEQ, 1, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("source") SEQ, 0, 2, 2, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _OpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters[] = { /* CHOICE */
{FNAME("h222LogicalChannelParameters") SEQ, 3, 5, 5, SKIP | EXT, 0,
_H222LogicalChannelParameters},
{FNAME("h223LogicalChannelParameters") SEQ, 0, 2, 2, SKIP | EXT, 0,
_H223LogicalChannelParameters},
{FNAME("v76LogicalChannelParameters") SEQ, 0, 5, 5, SKIP | EXT, 0,
_V76LogicalChannelParameters},
{FNAME("h2250LogicalChannelParameters") SEQ, 10, 11, 14, DECODE | EXT,
offsetof
(OpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters,
h2250LogicalChannelParameters), _H2250LogicalChannelParameters},
{FNAME("none") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _OpenLogicalChannel_forwardLogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("portNumber") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("dataType") CHOICE, 3, 6, 9, DECODE | EXT,
offsetof(OpenLogicalChannel_forwardLogicalChannelParameters,
dataType), _DataType},
{FNAME("multiplexParameters") CHOICE, 2, 3, 5, DECODE | EXT,
offsetof(OpenLogicalChannel_forwardLogicalChannelParameters,
multiplexParameters),
_OpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters},
{FNAME("forwardLogicalChannelDependency") INT, WORD, 1, 0, SKIP | OPT,
0, NULL},
{FNAME("replacementFor") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _OpenLogicalChannel_reverseLogicalChannelParameters_multiplexParameters[] = { /* CHOICE */
{FNAME("h223LogicalChannelParameters") SEQ, 0, 2, 2, SKIP | EXT, 0,
_H223LogicalChannelParameters},
{FNAME("v76LogicalChannelParameters") SEQ, 0, 5, 5, SKIP | EXT, 0,
_V76LogicalChannelParameters},
{FNAME("h2250LogicalChannelParameters") SEQ, 10, 11, 14, DECODE | EXT,
offsetof
(OpenLogicalChannel_reverseLogicalChannelParameters_multiplexParameters,
h2250LogicalChannelParameters), _H2250LogicalChannelParameters},
};
static const struct field_t _OpenLogicalChannel_reverseLogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("dataType") CHOICE, 3, 6, 9, SKIP | EXT, 0, _DataType},
{FNAME("multiplexParameters") CHOICE, 1, 2, 3, DECODE | EXT | OPT,
offsetof(OpenLogicalChannel_reverseLogicalChannelParameters,
multiplexParameters),
_OpenLogicalChannel_reverseLogicalChannelParameters_multiplexParameters},
{FNAME("reverseLogicalChannelDependency") INT, WORD, 1, 0, SKIP | OPT,
0, NULL},
{FNAME("replacementFor") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _NetworkAccessParameters_distribution[] = { /* CHOICE */
{FNAME("unicast") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("multicast") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _Q2931Address_address[] = { /* CHOICE */
{FNAME("internationalNumber") NUMSTR, 4, 1, 0, SKIP, 0, NULL},
{FNAME("nsapAddress") OCTSTR, 5, 1, 0, SKIP, 0, NULL},
};
static const struct field_t _Q2931Address[] = { /* SEQUENCE */
{FNAME("address") CHOICE, 1, 2, 2, SKIP | EXT, 0,
_Q2931Address_address},
{FNAME("subaddress") OCTSTR, 5, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _NetworkAccessParameters_networkAddress[] = { /* CHOICE */
{FNAME("q2931Address") SEQ, 1, 2, 2, SKIP | EXT, 0, _Q2931Address},
{FNAME("e164Address") NUMDGT, 7, 1, 0, SKIP, 0, NULL},
{FNAME("localAreaAddress") CHOICE, 1, 2, 2, DECODE | EXT,
offsetof(NetworkAccessParameters_networkAddress, localAreaAddress),
_H245_TransportAddress},
};
static const struct field_t _NetworkAccessParameters[] = { /* SEQUENCE */
{FNAME("distribution") CHOICE, 1, 2, 2, SKIP | EXT | OPT, 0,
_NetworkAccessParameters_distribution},
{FNAME("networkAddress") CHOICE, 2, 3, 3, DECODE | EXT,
offsetof(NetworkAccessParameters, networkAddress),
_NetworkAccessParameters_networkAddress},
{FNAME("associateConference") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("externalReference") OCTSTR, 8, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("t120SetupProcedure") CHOICE, 2, 3, 3, SKIP | EXT | OPT, 0,
NULL},
};
static const struct field_t _OpenLogicalChannel[] = { /* SEQUENCE */
{FNAME("forwardLogicalChannelNumber") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("forwardLogicalChannelParameters") SEQ, 1, 3, 5, DECODE | EXT,
offsetof(OpenLogicalChannel, forwardLogicalChannelParameters),
_OpenLogicalChannel_forwardLogicalChannelParameters},
{FNAME("reverseLogicalChannelParameters") SEQ, 1, 2, 4,
DECODE | EXT | OPT, offsetof(OpenLogicalChannel,
reverseLogicalChannelParameters),
_OpenLogicalChannel_reverseLogicalChannelParameters},
{FNAME("separateStack") SEQ, 2, 4, 5, DECODE | EXT | OPT,
offsetof(OpenLogicalChannel, separateStack),
_NetworkAccessParameters},
{FNAME("encryptionSync") SEQ, 2, 4, 4, STOP | EXT | OPT, 0, NULL},
};
static const struct field_t _Setup_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _Setup_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Setup_UUIE, h245Address), _TransportAddress},
{FNAME("sourceAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Setup_UUIE_sourceAddress},
{FNAME("sourceInfo") SEQ, 6, 8, 10, SKIP | EXT, 0, _EndpointType},
{FNAME("destinationAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Setup_UUIE_destinationAddress},
{FNAME("destCallSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Setup_UUIE, destCallSignalAddress), _TransportAddress},
{FNAME("destExtraCallInfo") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Setup_UUIE_destExtraCallInfo},
{FNAME("destExtraCRV") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Setup_UUIE_destExtraCRV},
{FNAME("activeMC") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("conferenceID") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
{FNAME("conferenceGoal") CHOICE, 2, 3, 5, SKIP | EXT, 0,
_Setup_UUIE_conferenceGoal},
{FNAME("callServices") SEQ, 0, 8, 8, SKIP | EXT | OPT, 0,
_QseriesOptions},
{FNAME("callType") CHOICE, 2, 4, 4, SKIP | EXT, 0, _CallType},
{FNAME("sourceCallSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Setup_UUIE, sourceCallSignalAddress), _TransportAddress},
{FNAME("remoteExtensionAddress") CHOICE, 1, 2, 7, SKIP | EXT | OPT, 0,
NULL},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("h245SecurityCapability") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(Setup_UUIE, fastStart), _Setup_UUIE_fastStart},
{FNAME("mediaWaitForConnect") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("canOverlapSend") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("connectionParameters") SEQ, 0, 3, 3, SKIP | EXT | OPT, 0,
NULL},
{FNAME("language") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("presentationIndicator") CHOICE, 2, 3, 3, SKIP | EXT | OPT, 0,
NULL},
{FNAME("screeningIndicator") ENUM, 2, 0, 0, SKIP | EXT | OPT, 0,
NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("symmetricOperationRequired") NUL, FIXD, 0, 0, SKIP | OPT, 0,
NULL},
{FNAME("capacity") SEQ, 2, 2, 2, SKIP | EXT | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, SKIP | EXT | OPT, 0, NULL},
{FNAME("desiredProtocols") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("neededFeatures") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("desiredFeatures") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("supportedFeatures") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("parallelH245Control") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("additionalSourceAddresses") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
NULL},
};
static const struct field_t _CallProceeding_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _CallProceeding_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("destinationInfo") SEQ, 6, 8, 10, SKIP | EXT, 0,
_EndpointType},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(CallProceeding_UUIE, h245Address), _TransportAddress},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("h245SecurityMode") CHOICE, 2, 4, 4, SKIP | EXT | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(CallProceeding_UUIE, fastStart),
_CallProceeding_UUIE_fastStart},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _Connect_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _Connect_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Connect_UUIE, h245Address), _TransportAddress},
{FNAME("destinationInfo") SEQ, 6, 8, 10, SKIP | EXT, 0,
_EndpointType},
{FNAME("conferenceID") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("h245SecurityMode") CHOICE, 2, 4, 4, SKIP | EXT | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(Connect_UUIE, fastStart), _Connect_UUIE_fastStart},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("language") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("connectedAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("presentationIndicator") CHOICE, 2, 3, 3, SKIP | EXT | OPT, 0,
NULL},
{FNAME("screeningIndicator") ENUM, 2, 0, 0, SKIP | EXT | OPT, 0,
NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("capacity") SEQ, 2, 2, 2, SKIP | EXT | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _Alerting_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _Alerting_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("destinationInfo") SEQ, 6, 8, 10, SKIP | EXT, 0,
_EndpointType},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Alerting_UUIE, h245Address), _TransportAddress},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("h245SecurityMode") CHOICE, 2, 4, 4, SKIP | EXT | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(Alerting_UUIE, fastStart), _Alerting_UUIE_fastStart},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("alertingAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("presentationIndicator") CHOICE, 2, 3, 3, SKIP | EXT | OPT, 0,
NULL},
{FNAME("screeningIndicator") ENUM, 2, 0, 0, SKIP | EXT | OPT, 0,
NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("capacity") SEQ, 2, 2, 2, SKIP | EXT | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _Information_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, SKIP | OPT, 0, NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _ReleaseCompleteReason[] = { /* CHOICE */
{FNAME("noBandwidth") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("gatekeeperResources") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("unreachableDestination") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("destinationRejection") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("invalidRevision") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("noPermission") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("unreachableGatekeeper") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("gatewayResources") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("badFormatAddress") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("adaptiveBusy") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("inConf") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("undefinedReason") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("facilityCallDeflection") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("securityDenied") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("calledPartyNotRegistered") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("callerNotRegistered") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("newConnectionNeeded") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("nonStandardReason") SEQ, 0, 2, 2, SKIP, 0, NULL},
{FNAME("replaceWithConferenceInvite") OCTSTR, FIXD, 16, 0, SKIP, 0,
NULL},
{FNAME("genericDataReason") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("neededFeatureNotSupported") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("tunnelledSignallingRejected") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _ReleaseComplete_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("reason") CHOICE, 4, 12, 22, SKIP | EXT | OPT, 0,
_ReleaseCompleteReason},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("busyAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("presentationIndicator") CHOICE, 2, 3, 3, SKIP | EXT | OPT, 0,
NULL},
{FNAME("screeningIndicator") ENUM, 2, 0, 0, SKIP | EXT | OPT, 0,
NULL},
{FNAME("capacity") SEQ, 2, 2, 2, SKIP | EXT | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0, NULL},
};
static const struct field_t _Facility_UUIE_alternativeAliasAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _FacilityReason[] = { /* CHOICE */
{FNAME("routeCallToGatekeeper") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("callForwarded") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("routeCallToMC") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("undefinedReason") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("conferenceListChoice") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("startH245") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("noH245") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("newTokens") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("featureSetUpdate") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("forwardedElements") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("transportedInformation") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _Facility_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _Facility_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("alternativeAddress") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Facility_UUIE, alternativeAddress), _TransportAddress},
{FNAME("alternativeAliasAddress") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Facility_UUIE_alternativeAliasAddress},
{FNAME("conferenceID") OCTSTR, FIXD, 16, 0, SKIP | OPT, 0, NULL},
{FNAME("reason") CHOICE, 2, 4, 11, DECODE | EXT,
offsetof(Facility_UUIE, reason), _FacilityReason},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0, NULL},
{FNAME("destExtraCallInfo") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("remoteExtensionAddress") CHOICE, 1, 2, 7, SKIP | EXT | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("conferences") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Facility_UUIE, h245Address), _TransportAddress},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(Facility_UUIE, fastStart), _Facility_UUIE_fastStart},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, SKIP | EXT | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, SKIP | EXT | OPT, 0, NULL},
{FNAME("destinationInfo") SEQ, 6, 8, 10, SKIP | EXT | OPT, 0, NULL},
{FNAME("h245SecurityMode") CHOICE, 2, 4, 4, SKIP | EXT | OPT, 0,
NULL},
};
static const struct field_t _CallIdentifier[] = { /* SEQUENCE */
{FNAME("guid") OCTSTR, FIXD, 16, 0, SKIP, 0, NULL},
};
static const struct field_t _SecurityServiceMode[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0, _NonStandardParameter},
{FNAME("none") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("default") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _SecurityCapabilities[] = { /* SEQUENCE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("encryption") CHOICE, 2, 3, 3, SKIP | EXT, 0,
_SecurityServiceMode},
{FNAME("authenticaton") CHOICE, 2, 3, 3, SKIP | EXT, 0,
_SecurityServiceMode},
{FNAME("integrity") CHOICE, 2, 3, 3, SKIP | EXT, 0,
_SecurityServiceMode},
};
static const struct field_t _H245Security[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP, 0, _NonStandardParameter},
{FNAME("noSecurity") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("tls") SEQ, 1, 4, 4, SKIP | EXT, 0, _SecurityCapabilities},
{FNAME("ipsec") SEQ, 1, 4, 4, SKIP | EXT, 0, _SecurityCapabilities},
};
static const struct field_t _DHset[] = { /* SEQUENCE */
{FNAME("halfkey") BITSTR, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("modSize") BITSTR, WORD, 0, 0, SKIP, 0, NULL},
{FNAME("generator") BITSTR, WORD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _TypedCertificate[] = { /* SEQUENCE */
{FNAME("type") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("certificate") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _H235_NonStandardParameter[] = { /* SEQUENCE */
{FNAME("nonStandardIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("data") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _ClearToken[] = { /* SEQUENCE */
{FNAME("tokenOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("timeStamp") INT, CONS, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("password") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("dhkey") SEQ, 0, 3, 3, SKIP | EXT | OPT, 0, _DHset},
{FNAME("challenge") OCTSTR, 7, 8, 0, SKIP | OPT, 0, NULL},
{FNAME("random") INT, UNCO, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("certificate") SEQ, 0, 2, 2, SKIP | EXT | OPT, 0,
_TypedCertificate},
{FNAME("generalID") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("nonStandard") SEQ, 0, 2, 2, SKIP | OPT, 0,
_H235_NonStandardParameter},
{FNAME("eckasdhkey") CHOICE, 1, 2, 2, SKIP | EXT | OPT, 0, NULL},
{FNAME("sendersID") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _Progress_UUIE_tokens[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 8, 9, 11, SKIP | EXT, 0, _ClearToken},
};
static const struct field_t _Params[] = { /* SEQUENCE */
{FNAME("ranInt") INT, UNCO, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("iv8") OCTSTR, FIXD, 8, 0, SKIP | OPT, 0, NULL},
{FNAME("iv16") OCTSTR, FIXD, 16, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoEPPwdHash_token[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("hash") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoEPPwdHash[] = { /* SEQUENCE */
{FNAME("alias") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
{FNAME("timeStamp") INT, CONS, 1, 0, SKIP, 0, NULL},
{FNAME("token") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoEPPwdHash_token},
};
static const struct field_t _CryptoH323Token_cryptoGKPwdHash_token[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("hash") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoGKPwdHash[] = { /* SEQUENCE */
{FNAME("gatekeeperId") BMPSTR, 7, 1, 0, SKIP, 0, NULL},
{FNAME("timeStamp") INT, CONS, 1, 0, SKIP, 0, NULL},
{FNAME("token") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoGKPwdHash_token},
};
static const struct field_t _CryptoH323Token_cryptoEPPwdEncr[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("encryptedData") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoGKPwdEncr[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("encryptedData") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoEPCert[] = { /* SEQUENCE */
{FNAME("toBeSigned") SEQ, 8, 9, 11, SKIP | OPEN | EXT, 0, NULL},
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("signature") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoGKCert[] = { /* SEQUENCE */
{FNAME("toBeSigned") SEQ, 8, 9, 11, SKIP | OPEN | EXT, 0, NULL},
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("signature") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoH323Token_cryptoFastStart[] = { /* SEQUENCE */
{FNAME("toBeSigned") SEQ, 8, 9, 11, SKIP | OPEN | EXT, 0, NULL},
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("signature") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoToken_cryptoEncryptedToken_token[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("encryptedData") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoToken_cryptoEncryptedToken[] = { /* SEQUENCE */
{FNAME("tokenOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("token") SEQ, 0, 3, 3, SKIP, 0,
_CryptoToken_cryptoEncryptedToken_token},
};
static const struct field_t _CryptoToken_cryptoSignedToken_token[] = { /* SEQUENCE */
{FNAME("toBeSigned") SEQ, 8, 9, 11, SKIP | OPEN | EXT, 0, NULL},
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("signature") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoToken_cryptoSignedToken[] = { /* SEQUENCE */
{FNAME("tokenOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("token") SEQ, 0, 4, 4, SKIP, 0,
_CryptoToken_cryptoSignedToken_token},
};
static const struct field_t _CryptoToken_cryptoHashedToken_token[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("hash") BITSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoToken_cryptoHashedToken[] = { /* SEQUENCE */
{FNAME("tokenOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("hashedVals") SEQ, 8, 9, 11, SKIP | EXT, 0, _ClearToken},
{FNAME("token") SEQ, 0, 3, 3, SKIP, 0,
_CryptoToken_cryptoHashedToken_token},
};
static const struct field_t _CryptoToken_cryptoPwdEncr[] = { /* SEQUENCE */
{FNAME("algorithmOID") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("paramS") SEQ, 2, 2, 3, SKIP | EXT, 0, _Params},
{FNAME("encryptedData") OCTSTR, SEMI, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _CryptoToken[] = { /* CHOICE */
{FNAME("cryptoEncryptedToken") SEQ, 0, 2, 2, SKIP, 0,
_CryptoToken_cryptoEncryptedToken},
{FNAME("cryptoSignedToken") SEQ, 0, 2, 2, SKIP, 0,
_CryptoToken_cryptoSignedToken},
{FNAME("cryptoHashedToken") SEQ, 0, 3, 3, SKIP, 0,
_CryptoToken_cryptoHashedToken},
{FNAME("cryptoPwdEncr") SEQ, 0, 3, 3, SKIP, 0,
_CryptoToken_cryptoPwdEncr},
};
static const struct field_t _CryptoH323Token[] = { /* CHOICE */
{FNAME("cryptoEPPwdHash") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoEPPwdHash},
{FNAME("cryptoGKPwdHash") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoGKPwdHash},
{FNAME("cryptoEPPwdEncr") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoEPPwdEncr},
{FNAME("cryptoGKPwdEncr") SEQ, 0, 3, 3, SKIP, 0,
_CryptoH323Token_cryptoGKPwdEncr},
{FNAME("cryptoEPCert") SEQ, 0, 4, 4, SKIP, 0,
_CryptoH323Token_cryptoEPCert},
{FNAME("cryptoGKCert") SEQ, 0, 4, 4, SKIP, 0,
_CryptoH323Token_cryptoGKCert},
{FNAME("cryptoFastStart") SEQ, 0, 4, 4, SKIP, 0,
_CryptoH323Token_cryptoFastStart},
{FNAME("nestedcryptoToken") CHOICE, 2, 4, 4, SKIP | EXT, 0,
_CryptoToken},
};
static const struct field_t _Progress_UUIE_cryptoTokens[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 8, 8, SKIP | EXT, 0, _CryptoH323Token},
};
static const struct field_t _Progress_UUIE_fastStart[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 1, 3, 5, DECODE | OPEN | EXT,
sizeof(OpenLogicalChannel), _OpenLogicalChannel}
,
};
static const struct field_t _Progress_UUIE[] = { /* SEQUENCE */
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("destinationInfo") SEQ, 6, 8, 10, SKIP | EXT, 0,
_EndpointType},
{FNAME("h245Address") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(Progress_UUIE, h245Address), _TransportAddress},
{FNAME("callIdentifier") SEQ, 0, 1, 1, SKIP | EXT, 0,
_CallIdentifier},
{FNAME("h245SecurityMode") CHOICE, 2, 4, 4, SKIP | EXT | OPT, 0,
_H245Security},
{FNAME("tokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Progress_UUIE_tokens},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_Progress_UUIE_cryptoTokens},
{FNAME("fastStart") SEQOF, SEMI, 0, 30, DECODE | OPT,
offsetof(Progress_UUIE, fastStart), _Progress_UUIE_fastStart},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("fastConnectRefused") NUL, FIXD, 0, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _H323_UU_PDU_h323_message_body[] = { /* CHOICE */
{FNAME("setup") SEQ, 7, 13, 39, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, setup), _Setup_UUIE},
{FNAME("callProceeding") SEQ, 1, 3, 12, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, callProceeding),
_CallProceeding_UUIE},
{FNAME("connect") SEQ, 1, 4, 19, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, connect), _Connect_UUIE},
{FNAME("alerting") SEQ, 1, 3, 17, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, alerting), _Alerting_UUIE},
{FNAME("information") SEQ, 0, 1, 7, SKIP | EXT, 0, _Information_UUIE},
{FNAME("releaseComplete") SEQ, 1, 2, 11, SKIP | EXT, 0,
_ReleaseComplete_UUIE},
{FNAME("facility") SEQ, 3, 5, 21, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, facility), _Facility_UUIE},
{FNAME("progress") SEQ, 5, 8, 11, DECODE | EXT,
offsetof(H323_UU_PDU_h323_message_body, progress), _Progress_UUIE},
{FNAME("empty") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("status") SEQ, 2, 4, 4, SKIP | EXT, 0, NULL},
{FNAME("statusInquiry") SEQ, 2, 4, 4, SKIP | EXT, 0, NULL},
{FNAME("setupAcknowledge") SEQ, 2, 4, 4, SKIP | EXT, 0, NULL},
{FNAME("notify") SEQ, 2, 4, 4, SKIP | EXT, 0, NULL},
};
static const struct field_t _RequestMessage[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("masterSlaveDetermination") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("terminalCapabilitySet") SEQ, 3, 5, 5, STOP | EXT, 0, NULL},
{FNAME("openLogicalChannel") SEQ, 1, 3, 5, DECODE | EXT,
offsetof(RequestMessage, openLogicalChannel), _OpenLogicalChannel},
{FNAME("closeLogicalChannel") SEQ, 0, 2, 3, STOP | EXT, 0, NULL},
{FNAME("requestChannelClose") SEQ, 0, 1, 3, STOP | EXT, 0, NULL},
{FNAME("multiplexEntrySend") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("requestMultiplexEntry") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("requestMode") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("roundTripDelayRequest") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("maintenanceLoopRequest") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("communicationModeRequest") SEQ, 0, 0, 0, STOP | EXT, 0, NULL},
{FNAME("conferenceRequest") CHOICE, 3, 8, 16, STOP | EXT, 0, NULL},
{FNAME("multilinkRequest") CHOICE, 3, 5, 5, STOP | EXT, 0, NULL},
{FNAME("logicalChannelRateRequest") SEQ, 0, 3, 3, STOP | EXT, 0,
NULL},
};
static const struct field_t _OpenLogicalChannelAck_reverseLogicalChannelParameters_multiplexParameters[] = { /* CHOICE */
{FNAME("h222LogicalChannelParameters") SEQ, 3, 5, 5, SKIP | EXT, 0,
_H222LogicalChannelParameters},
{FNAME("h2250LogicalChannelParameters") SEQ, 10, 11, 14, DECODE | EXT,
offsetof
(OpenLogicalChannelAck_reverseLogicalChannelParameters_multiplexParameters,
h2250LogicalChannelParameters), _H2250LogicalChannelParameters},
};
static const struct field_t _OpenLogicalChannelAck_reverseLogicalChannelParameters[] = { /* SEQUENCE */
{FNAME("reverseLogicalChannelNumber") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("portNumber") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("multiplexParameters") CHOICE, 0, 1, 2, DECODE | EXT | OPT,
offsetof(OpenLogicalChannelAck_reverseLogicalChannelParameters,
multiplexParameters),
_OpenLogicalChannelAck_reverseLogicalChannelParameters_multiplexParameters},
{FNAME("replacementFor") INT, WORD, 1, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _H2250LogicalChannelAckParameters_nonStandard[] = { /* SEQUENCE OF */
{FNAME("item") SEQ, 0, 2, 2, SKIP, 0, _H245_NonStandardParameter},
};
static const struct field_t _H2250LogicalChannelAckParameters[] = { /* SEQUENCE */
{FNAME("nonStandard") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_H2250LogicalChannelAckParameters_nonStandard},
{FNAME("sessionID") INT, 8, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("mediaChannel") CHOICE, 1, 2, 2, DECODE | EXT | OPT,
offsetof(H2250LogicalChannelAckParameters, mediaChannel),
_H245_TransportAddress},
{FNAME("mediaControlChannel") CHOICE, 1, 2, 2, DECODE | EXT | OPT,
offsetof(H2250LogicalChannelAckParameters, mediaControlChannel),
_H245_TransportAddress},
{FNAME("dynamicRTPPayloadType") INT, 5, 96, 0, SKIP | OPT, 0, NULL},
{FNAME("flowControlToZero") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("portNumber") INT, WORD, 0, 0, SKIP | OPT, 0, NULL},
};
static const struct field_t _OpenLogicalChannelAck_forwardMultiplexAckParameters[] = { /* CHOICE */
{FNAME("h2250LogicalChannelAckParameters") SEQ, 5, 5, 7, DECODE | EXT,
offsetof(OpenLogicalChannelAck_forwardMultiplexAckParameters,
h2250LogicalChannelAckParameters),
_H2250LogicalChannelAckParameters},
};
static const struct field_t _OpenLogicalChannelAck[] = { /* SEQUENCE */
{FNAME("forwardLogicalChannelNumber") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("reverseLogicalChannelParameters") SEQ, 2, 3, 4,
DECODE | EXT | OPT, offsetof(OpenLogicalChannelAck,
reverseLogicalChannelParameters),
_OpenLogicalChannelAck_reverseLogicalChannelParameters},
{FNAME("separateStack") SEQ, 2, 4, 5, DECODE | EXT | OPT,
offsetof(OpenLogicalChannelAck, separateStack),
_NetworkAccessParameters},
{FNAME("forwardMultiplexAckParameters") CHOICE, 0, 1, 1,
DECODE | EXT | OPT, offsetof(OpenLogicalChannelAck,
forwardMultiplexAckParameters),
_OpenLogicalChannelAck_forwardMultiplexAckParameters},
{FNAME("encryptionSync") SEQ, 2, 4, 4, STOP | EXT | OPT, 0, NULL},
};
static const struct field_t _ResponseMessage[] = { /* CHOICE */
{FNAME("nonStandard") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("masterSlaveDeterminationAck") SEQ, 0, 1, 1, STOP | EXT, 0,
NULL},
{FNAME("masterSlaveDeterminationReject") SEQ, 0, 1, 1, STOP | EXT, 0,
NULL},
{FNAME("terminalCapabilitySetAck") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("terminalCapabilitySetReject") SEQ, 0, 2, 2, STOP | EXT, 0,
NULL},
{FNAME("openLogicalChannelAck") SEQ, 1, 2, 5, DECODE | EXT,
offsetof(ResponseMessage, openLogicalChannelAck),
_OpenLogicalChannelAck},
{FNAME("openLogicalChannelReject") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("closeLogicalChannelAck") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("requestChannelCloseAck") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("requestChannelCloseReject") SEQ, 0, 2, 2, STOP | EXT, 0,
NULL},
{FNAME("multiplexEntrySendAck") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("multiplexEntrySendReject") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("requestMultiplexEntryAck") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("requestMultiplexEntryReject") SEQ, 0, 2, 2, STOP | EXT, 0,
NULL},
{FNAME("requestModeAck") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("requestModeReject") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("roundTripDelayResponse") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("maintenanceLoopAck") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("maintenanceLoopReject") SEQ, 0, 2, 2, STOP | EXT, 0, NULL},
{FNAME("communicationModeResponse") CHOICE, 0, 1, 1, STOP | EXT, 0,
NULL},
{FNAME("conferenceResponse") CHOICE, 3, 8, 16, STOP | EXT, 0, NULL},
{FNAME("multilinkResponse") CHOICE, 3, 5, 5, STOP | EXT, 0, NULL},
{FNAME("logicalChannelRateAcknowledge") SEQ, 0, 3, 3, STOP | EXT, 0,
NULL},
{FNAME("logicalChannelRateReject") SEQ, 1, 4, 4, STOP | EXT, 0, NULL},
};
static const struct field_t _MultimediaSystemControlMessage[] = { /* CHOICE */
{FNAME("request") CHOICE, 4, 11, 15, DECODE | EXT,
offsetof(MultimediaSystemControlMessage, request), _RequestMessage},
{FNAME("response") CHOICE, 5, 19, 24, DECODE | EXT,
offsetof(MultimediaSystemControlMessage, response),
_ResponseMessage},
{FNAME("command") CHOICE, 3, 7, 12, STOP | EXT, 0, NULL},
{FNAME("indication") CHOICE, 4, 14, 23, STOP | EXT, 0, NULL},
};
static const struct field_t _H323_UU_PDU_h245Control[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 2, 4, 4, DECODE | OPEN | EXT,
sizeof(MultimediaSystemControlMessage),
_MultimediaSystemControlMessage}
,
};
static const struct field_t _H323_UU_PDU[] = { /* SEQUENCE */
{FNAME("h323-message-body") CHOICE, 3, 7, 13, DECODE | EXT,
offsetof(H323_UU_PDU, h323_message_body),
_H323_UU_PDU_h323_message_body},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("h4501SupplementaryService") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
NULL},
{FNAME("h245Tunneling") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("h245Control") SEQOF, SEMI, 0, 4, DECODE | OPT,
offsetof(H323_UU_PDU, h245Control), _H323_UU_PDU_h245Control},
{FNAME("nonStandardControl") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("callLinkage") SEQ, 2, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("tunnelledSignallingMessage") SEQ, 2, 4, 4, STOP | EXT | OPT,
0, NULL},
{FNAME("provisionalRespToH245Tunneling") NUL, FIXD, 0, 0, STOP | OPT,
0, NULL},
{FNAME("stimulusControl") SEQ, 3, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _H323_UserInformation[] = { /* SEQUENCE */
{FNAME("h323-uu-pdu") SEQ, 1, 2, 11, DECODE | EXT,
offsetof(H323_UserInformation, h323_uu_pdu), _H323_UU_PDU},
{FNAME("user-data") SEQ, 0, 2, 2, STOP | EXT | OPT, 0, NULL},
};
static const struct field_t _GatekeeperRequest[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("rasAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(GatekeeperRequest, rasAddress), _TransportAddress},
{FNAME("endpointType") SEQ, 6, 8, 10, STOP | EXT, 0, NULL},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("callServices") SEQ, 0, 8, 8, STOP | EXT | OPT, 0, NULL},
{FNAME("endpointAlias") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("alternateEndpoints") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("authenticationCapability") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("algorithmOIDs") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrity") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("supportsAltGK") NUL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _GatekeeperConfirm[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("rasAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(GatekeeperConfirm, rasAddress), _TransportAddress},
{FNAME("alternateGatekeeper") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("authenticationMode") CHOICE, 3, 7, 8, STOP | EXT | OPT, 0,
NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("algorithmOID") OID, BYTE, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrity") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _RegistrationRequest_callSignalAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 7, 7, DECODE | EXT,
sizeof(TransportAddress), _TransportAddress}
,
};
static const struct field_t _RegistrationRequest_rasAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 7, 7, DECODE | EXT,
sizeof(TransportAddress), _TransportAddress}
,
};
static const struct field_t _RegistrationRequest_terminalAlias[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _RegistrationRequest[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("discoveryComplete") BOOL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("callSignalAddress") SEQOF, SEMI, 0, 10, DECODE,
offsetof(RegistrationRequest, callSignalAddress),
_RegistrationRequest_callSignalAddress},
{FNAME("rasAddress") SEQOF, SEMI, 0, 10, DECODE,
offsetof(RegistrationRequest, rasAddress),
_RegistrationRequest_rasAddress},
{FNAME("terminalType") SEQ, 6, 8, 10, SKIP | EXT, 0, _EndpointType},
{FNAME("terminalAlias") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_RegistrationRequest_terminalAlias},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("endpointVendor") SEQ, 2, 3, 3, SKIP | EXT, 0,
_VendorIdentifier},
{FNAME("alternateEndpoints") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("timeToLive") INT, CONS, 1, 0, DECODE | OPT,
offsetof(RegistrationRequest, timeToLive), NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("keepAlive") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("willSupplyUUIEs") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("alternateTransportAddresses") SEQ, 1, 1, 1, STOP | EXT | OPT,
0, NULL},
{FNAME("additiveRegistration") NUL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("terminalAliasPattern") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("supportsAltGK") NUL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("usageReportingCapability") SEQ, 3, 4, 4, STOP | EXT | OPT, 0,
NULL},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("supportedH248Packages") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("callCreditCapability") SEQ, 2, 2, 2, STOP | EXT | OPT, 0,
NULL},
{FNAME("capacityReportingCapability") SEQ, 0, 1, 1, STOP | EXT | OPT,
0, NULL},
{FNAME("capacity") SEQ, 2, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _RegistrationConfirm_callSignalAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 7, 7, DECODE | EXT,
sizeof(TransportAddress), _TransportAddress}
,
};
static const struct field_t _RegistrationConfirm_terminalAlias[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _RegistrationConfirm[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("protocolIdentifier") OID, BYTE, 0, 0, SKIP, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("callSignalAddress") SEQOF, SEMI, 0, 10, DECODE,
offsetof(RegistrationConfirm, callSignalAddress),
_RegistrationConfirm_callSignalAddress},
{FNAME("terminalAlias") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_RegistrationConfirm_terminalAlias},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, SKIP, 0, NULL},
{FNAME("alternateGatekeeper") SEQOF, SEMI, 0, 0, SKIP | OPT, 0, NULL},
{FNAME("timeToLive") INT, CONS, 1, 0, DECODE | OPT,
offsetof(RegistrationConfirm, timeToLive), NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("willRespondToIRR") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("preGrantedARQ") SEQ, 0, 4, 8, STOP | EXT | OPT, 0, NULL},
{FNAME("maintainConnection") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("supportsAdditiveRegistration") NUL, FIXD, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("terminalAliasPattern") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("usageSpec") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("featureServerAlias") CHOICE, 1, 2, 7, STOP | EXT | OPT, 0,
NULL},
{FNAME("capacityReportingSpec") SEQ, 0, 1, 1, STOP | EXT | OPT, 0,
NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _UnregistrationRequest_callSignalAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 7, 7, DECODE | EXT,
sizeof(TransportAddress), _TransportAddress}
,
};
static const struct field_t _UnregistrationRequest[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("callSignalAddress") SEQOF, SEMI, 0, 10, DECODE,
offsetof(UnregistrationRequest, callSignalAddress),
_UnregistrationRequest_callSignalAddress},
{FNAME("endpointAlias") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("alternateEndpoints") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("reason") CHOICE, 2, 4, 5, STOP | EXT | OPT, 0, NULL},
{FNAME("endpointAliasPattern") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("supportedPrefixes") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("alternateGatekeeper") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _CallModel[] = { /* CHOICE */
{FNAME("direct") NUL, FIXD, 0, 0, SKIP, 0, NULL},
{FNAME("gatekeeperRouted") NUL, FIXD, 0, 0, SKIP, 0, NULL},
};
static const struct field_t _AdmissionRequest_destinationInfo[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _AdmissionRequest_destExtraCallInfo[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _AdmissionRequest_srcInfo[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _AdmissionRequest[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("callType") CHOICE, 2, 4, 4, SKIP | EXT, 0, _CallType},
{FNAME("callModel") CHOICE, 1, 2, 2, SKIP | EXT | OPT, 0, _CallModel},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, SKIP, 0, NULL},
{FNAME("destinationInfo") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_AdmissionRequest_destinationInfo},
{FNAME("destCallSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(AdmissionRequest, destCallSignalAddress),
_TransportAddress},
{FNAME("destExtraCallInfo") SEQOF, SEMI, 0, 0, SKIP | OPT, 0,
_AdmissionRequest_destExtraCallInfo},
{FNAME("srcInfo") SEQOF, SEMI, 0, 0, SKIP, 0,
_AdmissionRequest_srcInfo},
{FNAME("srcCallSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT | OPT,
offsetof(AdmissionRequest, srcCallSignalAddress), _TransportAddress},
{FNAME("bandWidth") INT, CONS, 0, 0, STOP, 0, NULL},
{FNAME("callReferenceValue") INT, WORD, 0, 0, STOP, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("callServices") SEQ, 0, 8, 8, STOP | EXT | OPT, 0, NULL},
{FNAME("conferenceID") OCTSTR, FIXD, 16, 0, STOP, 0, NULL},
{FNAME("activeMC") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("answerCall") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("canMapAlias") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("callIdentifier") SEQ, 0, 1, 1, STOP | EXT, 0, NULL},
{FNAME("srcAlternatives") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destAlternatives") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("transportQOS") CHOICE, 2, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("willSupplyUUIEs") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("callLinkage") SEQ, 2, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("gatewayDataRate") SEQ, 2, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("capacity") SEQ, 2, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("desiredProtocols") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("desiredTunnelledProtocol") SEQ, 1, 2, 2, STOP | EXT | OPT, 0,
NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _AdmissionConfirm[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("bandWidth") INT, CONS, 0, 0, SKIP, 0, NULL},
{FNAME("callModel") CHOICE, 1, 2, 2, SKIP | EXT, 0, _CallModel},
{FNAME("destCallSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(AdmissionConfirm, destCallSignalAddress),
_TransportAddress},
{FNAME("irrFrequency") INT, WORD, 1, 0, STOP | OPT, 0, NULL},
{FNAME("nonStandardData") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("destinationInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destExtraCallInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destinationType") SEQ, 6, 8, 10, STOP | EXT | OPT, 0, NULL},
{FNAME("remoteExtensionAddress") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("alternateEndpoints") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("transportQOS") CHOICE, 2, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("willRespondToIRR") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("uuiesRequested") SEQ, 0, 9, 13, STOP | EXT, 0, NULL},
{FNAME("language") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("alternateTransportAddresses") SEQ, 1, 1, 1, STOP | EXT | OPT,
0, NULL},
{FNAME("useSpecifiedTransport") CHOICE, 1, 2, 2, STOP | EXT | OPT, 0,
NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("usageSpec") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("supportedProtocols") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _LocationRequest_destinationInfo[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 1, 2, 7, SKIP | EXT, 0, _AliasAddress},
};
static const struct field_t _LocationRequest[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, SKIP | OPT, 0, NULL},
{FNAME("destinationInfo") SEQOF, SEMI, 0, 0, SKIP, 0,
_LocationRequest_destinationInfo},
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("replyAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(LocationRequest, replyAddress), _TransportAddress},
{FNAME("sourceInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("canMapAlias") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("gatekeeperIdentifier") BMPSTR, 7, 1, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("desiredProtocols") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("desiredTunnelledProtocol") SEQ, 1, 2, 2, STOP | EXT | OPT, 0,
NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("hopCount") INT, 8, 1, 0, STOP | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, STOP | EXT | OPT, 0, NULL},
};
static const struct field_t _LocationConfirm[] = { /* SEQUENCE */
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("callSignalAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(LocationConfirm, callSignalAddress), _TransportAddress},
{FNAME("rasAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(LocationConfirm, rasAddress), _TransportAddress},
{FNAME("nonStandardData") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("destinationInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destExtraCallInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("destinationType") SEQ, 6, 8, 10, STOP | EXT | OPT, 0, NULL},
{FNAME("remoteExtensionAddress") SEQOF, SEMI, 0, 0, STOP | OPT, 0,
NULL},
{FNAME("alternateEndpoints") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("alternateTransportAddresses") SEQ, 1, 1, 1, STOP | EXT | OPT,
0, NULL},
{FNAME("supportedProtocols") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("multipleCalls") BOOL, FIXD, 0, 0, STOP | OPT, 0, NULL},
{FNAME("featureSet") SEQ, 3, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("circuitInfo") SEQ, 3, 3, 3, STOP | EXT | OPT, 0, NULL},
{FNAME("serviceControl") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _InfoRequestResponse_callSignalAddress[] = { /* SEQUENCE OF */
{FNAME("item") CHOICE, 3, 7, 7, DECODE | EXT,
sizeof(TransportAddress), _TransportAddress}
,
};
static const struct field_t _InfoRequestResponse[] = { /* SEQUENCE */
{FNAME("nonStandardData") SEQ, 0, 2, 2, SKIP | OPT, 0,
_NonStandardParameter},
{FNAME("requestSeqNum") INT, WORD, 1, 0, SKIP, 0, NULL},
{FNAME("endpointType") SEQ, 6, 8, 10, SKIP | EXT, 0, _EndpointType},
{FNAME("endpointIdentifier") BMPSTR, 7, 1, 0, SKIP, 0, NULL},
{FNAME("rasAddress") CHOICE, 3, 7, 7, DECODE | EXT,
offsetof(InfoRequestResponse, rasAddress), _TransportAddress},
{FNAME("callSignalAddress") SEQOF, SEMI, 0, 10, DECODE,
offsetof(InfoRequestResponse, callSignalAddress),
_InfoRequestResponse_callSignalAddress},
{FNAME("endpointAlias") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("perCallInfo") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("tokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("cryptoTokens") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
{FNAME("integrityCheckValue") SEQ, 0, 2, 2, STOP | OPT, 0, NULL},
{FNAME("needResponse") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("capacity") SEQ, 2, 2, 2, STOP | EXT | OPT, 0, NULL},
{FNAME("irrStatus") CHOICE, 2, 4, 4, STOP | EXT | OPT, 0, NULL},
{FNAME("unsolicited") BOOL, FIXD, 0, 0, STOP, 0, NULL},
{FNAME("genericData") SEQOF, SEMI, 0, 0, STOP | OPT, 0, NULL},
};
static const struct field_t _RasMessage[] = { /* CHOICE */
{FNAME("gatekeeperRequest") SEQ, 4, 8, 18, DECODE | EXT,
offsetof(RasMessage, gatekeeperRequest), _GatekeeperRequest},
{FNAME("gatekeeperConfirm") SEQ, 2, 5, 14, DECODE | EXT,
offsetof(RasMessage, gatekeeperConfirm), _GatekeeperConfirm},
{FNAME("gatekeeperReject") SEQ, 2, 5, 11, STOP | EXT, 0, NULL},
{FNAME("registrationRequest") SEQ, 3, 10, 31, DECODE | EXT,
offsetof(RasMessage, registrationRequest), _RegistrationRequest},
{FNAME("registrationConfirm") SEQ, 3, 7, 24, DECODE | EXT,
offsetof(RasMessage, registrationConfirm), _RegistrationConfirm},
{FNAME("registrationReject") SEQ, 2, 5, 11, STOP | EXT, 0, NULL},
{FNAME("unregistrationRequest") SEQ, 3, 5, 15, DECODE | EXT,
offsetof(RasMessage, unregistrationRequest), _UnregistrationRequest},
{FNAME("unregistrationConfirm") SEQ, 1, 2, 6, STOP | EXT, 0, NULL},
{FNAME("unregistrationReject") SEQ, 1, 3, 8, STOP | EXT, 0, NULL},
{FNAME("admissionRequest") SEQ, 7, 16, 34, DECODE | EXT,
offsetof(RasMessage, admissionRequest), _AdmissionRequest},
{FNAME("admissionConfirm") SEQ, 2, 6, 27, DECODE | EXT,
offsetof(RasMessage, admissionConfirm), _AdmissionConfirm},
{FNAME("admissionReject") SEQ, 1, 3, 11, STOP | EXT, 0, NULL},
{FNAME("bandwidthRequest") SEQ, 2, 7, 18, STOP | EXT, 0, NULL},
{FNAME("bandwidthConfirm") SEQ, 1, 3, 8, STOP | EXT, 0, NULL},
{FNAME("bandwidthReject") SEQ, 1, 4, 9, STOP | EXT, 0, NULL},
{FNAME("disengageRequest") SEQ, 1, 6, 19, STOP | EXT, 0, NULL},
{FNAME("disengageConfirm") SEQ, 1, 2, 9, STOP | EXT, 0, NULL},
{FNAME("disengageReject") SEQ, 1, 3, 8, STOP | EXT, 0, NULL},
{FNAME("locationRequest") SEQ, 2, 5, 17, DECODE | EXT,
offsetof(RasMessage, locationRequest), _LocationRequest},
{FNAME("locationConfirm") SEQ, 1, 4, 19, DECODE | EXT,
offsetof(RasMessage, locationConfirm), _LocationConfirm},
{FNAME("locationReject") SEQ, 1, 3, 10, STOP | EXT, 0, NULL},
{FNAME("infoRequest") SEQ, 2, 4, 15, STOP | EXT, 0, NULL},
{FNAME("infoRequestResponse") SEQ, 3, 8, 16, DECODE | EXT,
offsetof(RasMessage, infoRequestResponse), _InfoRequestResponse},
{FNAME("nonStandardMessage") SEQ, 0, 2, 7, STOP | EXT, 0, NULL},
{FNAME("unknownMessageResponse") SEQ, 0, 1, 5, STOP | EXT, 0, NULL},
{FNAME("requestInProgress") SEQ, 4, 6, 6, STOP | EXT, 0, NULL},
{FNAME("resourcesAvailableIndicate") SEQ, 4, 9, 11, STOP | EXT, 0,
NULL},
{FNAME("resourcesAvailableConfirm") SEQ, 4, 6, 7, STOP | EXT, 0,
NULL},
{FNAME("infoRequestAck") SEQ, 4, 5, 5, STOP | EXT, 0, NULL},
{FNAME("infoRequestNak") SEQ, 5, 7, 7, STOP | EXT, 0, NULL},
{FNAME("serviceControlIndication") SEQ, 8, 10, 10, STOP | EXT, 0,
NULL},
{FNAME("serviceControlResponse") SEQ, 7, 8, 8, STOP | EXT, 0, NULL},
};
| gpl-2.0 |
Compulsion/linux-stable | drivers/infiniband/hw/nes/nes_verbs.c | 212 | 127305 | /*
* Copyright (c) 2006 - 2011 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/random.h>
#include <linux/highmem.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <rdma/ib_verbs.h>
#include <rdma/iw_cm.h>
#include <rdma/ib_user_verbs.h>
#include "nes.h"
#include <rdma/ib_umem.h>
atomic_t mod_qp_timouts;
atomic_t qps_created;
atomic_t sw_qps_destroyed;
static void nes_unregister_ofa_device(struct nes_ib_device *nesibdev);
/**
* nes_alloc_mw
*/
static struct ib_mw *nes_alloc_mw(struct ib_pd *ibpd, enum ib_mw_type type)
{
struct nes_pd *nespd = to_nespd(ibpd);
struct nes_vnic *nesvnic = to_nesvnic(ibpd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_cqp_request *cqp_request;
struct nes_mr *nesmr;
struct ib_mw *ibmw;
struct nes_hw_cqp_wqe *cqp_wqe;
int ret;
u32 stag;
u32 stag_index = 0;
u32 next_stag_index = 0;
u32 driver_key = 0;
u8 stag_key = 0;
if (type != IB_MW_TYPE_1)
return ERR_PTR(-EINVAL);
get_random_bytes(&next_stag_index, sizeof(next_stag_index));
stag_key = (u8)next_stag_index;
driver_key = 0;
next_stag_index >>= 8;
next_stag_index %= nesadapter->max_mr;
ret = nes_alloc_resource(nesadapter, nesadapter->allocated_mrs,
nesadapter->max_mr, &stag_index, &next_stag_index, NES_RESOURCE_MW);
if (ret) {
return ERR_PTR(ret);
}
nesmr = kzalloc(sizeof(*nesmr), GFP_KERNEL);
if (!nesmr) {
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
return ERR_PTR(-ENOMEM);
}
stag = stag_index << 8;
stag |= driver_key;
stag += (u32)stag_key;
nes_debug(NES_DBG_MR, "Registering STag 0x%08X, index = 0x%08X\n",
stag, stag_index);
/* Register the region with the adapter */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
kfree(nesmr);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
return ERR_PTR(-ENOMEM);
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] =
cpu_to_le32( NES_CQP_ALLOCATE_STAG | NES_CQP_STAG_RIGHTS_REMOTE_READ |
NES_CQP_STAG_RIGHTS_REMOTE_WRITE | NES_CQP_STAG_VA_TO |
NES_CQP_STAG_REM_ACC_EN);
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_LEN_HIGH_PD_IDX, (nespd->pd_id & 0x00007fff));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_STAG_IDX, stag);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
ret = wait_event_timeout(cqp_request->waitq, (cqp_request->request_done != 0),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MR, "Register STag 0x%08X completed, wait_event_timeout ret = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X.\n",
stag, ret, cqp_request->major_code, cqp_request->minor_code);
if ((!ret) || (cqp_request->major_code)) {
nes_put_cqp_request(nesdev, cqp_request);
kfree(nesmr);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
if (!ret) {
return ERR_PTR(-ETIME);
} else {
return ERR_PTR(-ENOMEM);
}
}
nes_put_cqp_request(nesdev, cqp_request);
nesmr->ibmw.rkey = stag;
nesmr->mode = IWNES_MEMREG_TYPE_MW;
ibmw = &nesmr->ibmw;
nesmr->pbl_4k = 0;
nesmr->pbls_used = 0;
return ibmw;
}
/**
* nes_dealloc_mw
*/
static int nes_dealloc_mw(struct ib_mw *ibmw)
{
struct nes_mr *nesmr = to_nesmw(ibmw);
struct nes_vnic *nesvnic = to_nesvnic(ibmw->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
int err = 0;
int ret;
/* Deallocate the window with the adapter */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_MR, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, NES_CQP_DEALLOCATE_STAG);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_STAG_IDX, ibmw->rkey);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
nes_debug(NES_DBG_MR, "Waiting for deallocate STag 0x%08X to complete.\n",
ibmw->rkey);
ret = wait_event_timeout(cqp_request->waitq, (0 != cqp_request->request_done),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MR, "Deallocate STag completed, wait_event_timeout ret = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X.\n",
ret, cqp_request->major_code, cqp_request->minor_code);
if (!ret)
err = -ETIME;
else if (cqp_request->major_code)
err = -EIO;
nes_put_cqp_request(nesdev, cqp_request);
nes_free_resource(nesadapter, nesadapter->allocated_mrs,
(ibmw->rkey & 0x0fffff00) >> 8);
kfree(nesmr);
return err;
}
/**
* nes_bind_mw
*/
static int nes_bind_mw(struct ib_qp *ibqp, struct ib_mw *ibmw,
struct ib_mw_bind *ibmw_bind)
{
u64 u64temp;
struct nes_vnic *nesvnic = to_nesvnic(ibqp->device);
struct nes_device *nesdev = nesvnic->nesdev;
/* struct nes_mr *nesmr = to_nesmw(ibmw); */
struct nes_qp *nesqp = to_nesqp(ibqp);
struct nes_hw_qp_wqe *wqe;
unsigned long flags = 0;
u32 head;
u32 wqe_misc = 0;
u32 qsize;
if (nesqp->ibqp_state > IB_QPS_RTS)
return -EINVAL;
spin_lock_irqsave(&nesqp->lock, flags);
head = nesqp->hwqp.sq_head;
qsize = nesqp->hwqp.sq_tail;
/* Check for SQ overflow */
if (((head + (2 * qsize) - nesqp->hwqp.sq_tail) % qsize) == (qsize - 1)) {
spin_unlock_irqrestore(&nesqp->lock, flags);
return -ENOMEM;
}
wqe = &nesqp->hwqp.sq_vbase[head];
/* nes_debug(NES_DBG_MR, "processing sq wqe at %p, head = %u.\n", wqe, head); */
nes_fill_init_qp_wqe(wqe, nesqp, head);
u64temp = ibmw_bind->wr_id;
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_COMP_SCRATCH_LOW_IDX, u64temp);
wqe_misc = NES_IWARP_SQ_OP_BIND;
wqe_misc |= NES_IWARP_SQ_WQE_LOCAL_FENCE;
if (ibmw_bind->send_flags & IB_SEND_SIGNALED)
wqe_misc |= NES_IWARP_SQ_WQE_SIGNALED_COMPL;
if (ibmw_bind->bind_info.mw_access_flags & IB_ACCESS_REMOTE_WRITE)
wqe_misc |= NES_CQP_STAG_RIGHTS_REMOTE_WRITE;
if (ibmw_bind->bind_info.mw_access_flags & IB_ACCESS_REMOTE_READ)
wqe_misc |= NES_CQP_STAG_RIGHTS_REMOTE_READ;
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_MISC_IDX, wqe_misc);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_BIND_WQE_MR_IDX,
ibmw_bind->bind_info.mr->lkey);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_BIND_WQE_MW_IDX, ibmw->rkey);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_BIND_WQE_LENGTH_LOW_IDX,
ibmw_bind->bind_info.length);
wqe->wqe_words[NES_IWARP_SQ_BIND_WQE_LENGTH_HIGH_IDX] = 0;
u64temp = (u64)ibmw_bind->bind_info.addr;
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_BIND_WQE_VA_FBO_LOW_IDX, u64temp);
head++;
if (head >= qsize)
head = 0;
nesqp->hwqp.sq_head = head;
barrier();
nes_write32(nesdev->regs+NES_WQE_ALLOC,
(1 << 24) | 0x00800000 | nesqp->hwqp.qp_id);
spin_unlock_irqrestore(&nesqp->lock, flags);
return 0;
}
/*
* nes_alloc_fast_mr
*/
static int alloc_fast_reg_mr(struct nes_device *nesdev, struct nes_pd *nespd,
u32 stag, u32 page_count)
{
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
unsigned long flags;
int ret;
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 opcode = 0;
u16 major_code;
u64 region_length = page_count * PAGE_SIZE;
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_MR, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
nes_debug(NES_DBG_MR, "alloc_fast_reg_mr: page_count = %d, "
"region_length = %llu\n",
page_count, region_length);
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (nesadapter->free_4kpbl > 0) {
nesadapter->free_4kpbl--;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
} else {
/* No 4kpbl's available: */
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_debug(NES_DBG_MR, "Out of Pbls\n");
nes_free_cqp_request(nesdev, cqp_request);
return -ENOMEM;
}
opcode = NES_CQP_ALLOCATE_STAG | NES_CQP_STAG_MR |
NES_CQP_STAG_PBL_BLK_SIZE | NES_CQP_STAG_VA_TO |
NES_CQP_STAG_REM_ACC_EN;
/*
* The current OFED API does not support the zero based TO option.
* If added then need to changed the NES_CQP_STAG_VA* option. Also,
* the API does not support that ability to have the MR set for local
* access only when created and not allow the SQ op to override. Given
* this the remote enable must be set here.
*/
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, opcode);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PBL_BLK_COUNT_IDX, 1);
cqp_wqe->wqe_words[NES_CQP_STAG_WQE_LEN_HIGH_PD_IDX] =
cpu_to_le32((u32)(region_length >> 8) & 0xff000000);
cqp_wqe->wqe_words[NES_CQP_STAG_WQE_LEN_HIGH_PD_IDX] |=
cpu_to_le32(nespd->pd_id & 0x00007fff);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_STAG_IDX, stag);
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_VA_LOW_IDX, 0);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_LEN_LOW_IDX, 0);
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PA_LOW_IDX, 0);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PBL_LEN_IDX, (page_count * 8));
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] |= cpu_to_le32(NES_CQP_STAG_PBL_BLK_SIZE);
barrier();
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
ret = wait_event_timeout(cqp_request->waitq,
(0 != cqp_request->request_done),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MR, "Allocate STag 0x%08X completed, "
"wait_event_timeout ret = %u, CQP Major:Minor codes = "
"0x%04X:0x%04X.\n", stag, ret, cqp_request->major_code,
cqp_request->minor_code);
major_code = cqp_request->major_code;
nes_put_cqp_request(nesdev, cqp_request);
if (!ret || major_code) {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
nesadapter->free_4kpbl++;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
}
if (!ret)
return -ETIME;
else if (major_code)
return -EIO;
return 0;
}
/*
* nes_alloc_fast_reg_mr
*/
static struct ib_mr *nes_alloc_fast_reg_mr(struct ib_pd *ibpd, int max_page_list_len)
{
struct nes_pd *nespd = to_nespd(ibpd);
struct nes_vnic *nesvnic = to_nesvnic(ibpd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 next_stag_index;
u8 stag_key = 0;
u32 driver_key = 0;
int err = 0;
u32 stag_index = 0;
struct nes_mr *nesmr;
u32 stag;
int ret;
struct ib_mr *ibmr;
/*
* Note: Set to always use a fixed length single page entry PBL. This is to allow
* for the fast_reg_mr operation to always know the size of the PBL.
*/
if (max_page_list_len > (NES_4K_PBL_CHUNK_SIZE / sizeof(u64)))
return ERR_PTR(-E2BIG);
get_random_bytes(&next_stag_index, sizeof(next_stag_index));
stag_key = (u8)next_stag_index;
next_stag_index >>= 8;
next_stag_index %= nesadapter->max_mr;
err = nes_alloc_resource(nesadapter, nesadapter->allocated_mrs,
nesadapter->max_mr, &stag_index,
&next_stag_index, NES_RESOURCE_FAST_MR);
if (err)
return ERR_PTR(err);
nesmr = kzalloc(sizeof(*nesmr), GFP_KERNEL);
if (!nesmr) {
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
return ERR_PTR(-ENOMEM);
}
stag = stag_index << 8;
stag |= driver_key;
stag += (u32)stag_key;
nes_debug(NES_DBG_MR, "Allocating STag 0x%08X index = 0x%08X\n",
stag, stag_index);
ret = alloc_fast_reg_mr(nesdev, nespd, stag, max_page_list_len);
if (ret == 0) {
nesmr->ibmr.rkey = stag;
nesmr->ibmr.lkey = stag;
nesmr->mode = IWNES_MEMREG_TYPE_FMEM;
ibmr = &nesmr->ibmr;
} else {
kfree(nesmr);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
ibmr = ERR_PTR(-ENOMEM);
}
return ibmr;
}
/*
* nes_alloc_fast_reg_page_list
*/
static struct ib_fast_reg_page_list *nes_alloc_fast_reg_page_list(
struct ib_device *ibdev,
int page_list_len)
{
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct nes_device *nesdev = nesvnic->nesdev;
struct ib_fast_reg_page_list *pifrpl;
struct nes_ib_fast_reg_page_list *pnesfrpl;
if (page_list_len > (NES_4K_PBL_CHUNK_SIZE / sizeof(u64)))
return ERR_PTR(-E2BIG);
/*
* Allocate the ib_fast_reg_page_list structure, the
* nes_fast_bpl structure, and the PLB table.
*/
pnesfrpl = kmalloc(sizeof(struct nes_ib_fast_reg_page_list) +
page_list_len * sizeof(u64), GFP_KERNEL);
if (!pnesfrpl)
return ERR_PTR(-ENOMEM);
pifrpl = &pnesfrpl->ibfrpl;
pifrpl->page_list = &pnesfrpl->pbl;
pifrpl->max_page_list_len = page_list_len;
/*
* Allocate the WQE PBL
*/
pnesfrpl->nes_wqe_pbl.kva = pci_alloc_consistent(nesdev->pcidev,
page_list_len * sizeof(u64),
&pnesfrpl->nes_wqe_pbl.paddr);
if (!pnesfrpl->nes_wqe_pbl.kva) {
kfree(pnesfrpl);
return ERR_PTR(-ENOMEM);
}
nes_debug(NES_DBG_MR, "nes_alloc_fast_reg_pbl: nes_frpl = %p, "
"ibfrpl = %p, ibfrpl.page_list = %p, pbl.kva = %p, "
"pbl.paddr = %llx\n", pnesfrpl, &pnesfrpl->ibfrpl,
pnesfrpl->ibfrpl.page_list, pnesfrpl->nes_wqe_pbl.kva,
(unsigned long long) pnesfrpl->nes_wqe_pbl.paddr);
return pifrpl;
}
/*
* nes_free_fast_reg_page_list
*/
static void nes_free_fast_reg_page_list(struct ib_fast_reg_page_list *pifrpl)
{
struct nes_vnic *nesvnic = to_nesvnic(pifrpl->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_ib_fast_reg_page_list *pnesfrpl;
pnesfrpl = container_of(pifrpl, struct nes_ib_fast_reg_page_list, ibfrpl);
/*
* Free the WQE PBL.
*/
pci_free_consistent(nesdev->pcidev,
pifrpl->max_page_list_len * sizeof(u64),
pnesfrpl->nes_wqe_pbl.kva,
pnesfrpl->nes_wqe_pbl.paddr);
/*
* Free the PBL structure
*/
kfree(pnesfrpl);
}
/**
* nes_query_device
*/
static int nes_query_device(struct ib_device *ibdev, struct ib_device_attr *props,
struct ib_udata *uhw)
{
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_ib_device *nesibdev = nesvnic->nesibdev;
if (uhw->inlen || uhw->outlen)
return -EINVAL;
memset(props, 0, sizeof(*props));
memcpy(&props->sys_image_guid, nesvnic->netdev->dev_addr, 6);
props->fw_ver = nesdev->nesadapter->firmware_version;
props->device_cap_flags = nesdev->nesadapter->device_cap_flags;
props->vendor_id = nesdev->nesadapter->vendor_id;
props->vendor_part_id = nesdev->nesadapter->vendor_part_id;
props->hw_ver = nesdev->nesadapter->hw_rev;
props->max_mr_size = 0x80000000;
props->max_qp = nesibdev->max_qp;
props->max_qp_wr = nesdev->nesadapter->max_qp_wr - 2;
props->max_sge = nesdev->nesadapter->max_sge;
props->max_cq = nesibdev->max_cq;
props->max_cqe = nesdev->nesadapter->max_cqe;
props->max_mr = nesibdev->max_mr;
props->max_mw = nesibdev->max_mr;
props->max_pd = nesibdev->max_pd;
props->max_sge_rd = 1;
switch (nesdev->nesadapter->max_irrq_wr) {
case 0:
props->max_qp_rd_atom = 2;
break;
case 1:
props->max_qp_rd_atom = 8;
break;
case 2:
props->max_qp_rd_atom = 32;
break;
case 3:
props->max_qp_rd_atom = 64;
break;
default:
props->max_qp_rd_atom = 0;
}
props->max_qp_init_rd_atom = props->max_qp_rd_atom;
props->atomic_cap = IB_ATOMIC_NONE;
props->max_map_per_fmr = 1;
return 0;
}
/**
* nes_query_port
*/
static int nes_query_port(struct ib_device *ibdev, u8 port, struct ib_port_attr *props)
{
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct net_device *netdev = nesvnic->netdev;
memset(props, 0, sizeof(*props));
props->max_mtu = IB_MTU_4096;
if (netdev->mtu >= 4096)
props->active_mtu = IB_MTU_4096;
else if (netdev->mtu >= 2048)
props->active_mtu = IB_MTU_2048;
else if (netdev->mtu >= 1024)
props->active_mtu = IB_MTU_1024;
else if (netdev->mtu >= 512)
props->active_mtu = IB_MTU_512;
else
props->active_mtu = IB_MTU_256;
props->lid = 1;
props->lmc = 0;
props->sm_lid = 0;
props->sm_sl = 0;
if (netif_queue_stopped(netdev))
props->state = IB_PORT_DOWN;
else if (nesvnic->linkup)
props->state = IB_PORT_ACTIVE;
else
props->state = IB_PORT_DOWN;
props->phys_state = 0;
props->port_cap_flags = IB_PORT_CM_SUP | IB_PORT_REINIT_SUP |
IB_PORT_VENDOR_CLASS_SUP | IB_PORT_BOOT_MGMT_SUP;
props->gid_tbl_len = 1;
props->pkey_tbl_len = 1;
props->qkey_viol_cntr = 0;
props->active_width = IB_WIDTH_4X;
props->active_speed = IB_SPEED_SDR;
props->max_msg_sz = 0x80000000;
return 0;
}
/**
* nes_query_pkey
*/
static int nes_query_pkey(struct ib_device *ibdev, u8 port, u16 index, u16 *pkey)
{
*pkey = 0;
return 0;
}
/**
* nes_query_gid
*/
static int nes_query_gid(struct ib_device *ibdev, u8 port,
int index, union ib_gid *gid)
{
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
memset(&(gid->raw[0]), 0, sizeof(gid->raw));
memcpy(&(gid->raw[0]), nesvnic->netdev->dev_addr, 6);
return 0;
}
/**
* nes_alloc_ucontext - Allocate the user context data structure. This keeps track
* of all objects associated with a particular user-mode client.
*/
static struct ib_ucontext *nes_alloc_ucontext(struct ib_device *ibdev,
struct ib_udata *udata)
{
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_alloc_ucontext_req req;
struct nes_alloc_ucontext_resp uresp;
struct nes_ucontext *nes_ucontext;
struct nes_ib_device *nesibdev = nesvnic->nesibdev;
if (ib_copy_from_udata(&req, udata, sizeof(struct nes_alloc_ucontext_req))) {
printk(KERN_ERR PFX "Invalid structure size on allocate user context.\n");
return ERR_PTR(-EINVAL);
}
if (req.userspace_ver != NES_ABI_USERSPACE_VER) {
printk(KERN_ERR PFX "Invalid userspace driver version detected. Detected version %d, should be %d\n",
req.userspace_ver, NES_ABI_USERSPACE_VER);
return ERR_PTR(-EINVAL);
}
memset(&uresp, 0, sizeof uresp);
uresp.max_qps = nesibdev->max_qp;
uresp.max_pds = nesibdev->max_pd;
uresp.wq_size = nesdev->nesadapter->max_qp_wr * 2;
uresp.virtwq = nesadapter->virtwq;
uresp.kernel_ver = NES_ABI_KERNEL_VER;
nes_ucontext = kzalloc(sizeof *nes_ucontext, GFP_KERNEL);
if (!nes_ucontext)
return ERR_PTR(-ENOMEM);
nes_ucontext->nesdev = nesdev;
nes_ucontext->mmap_wq_offset = uresp.max_pds;
nes_ucontext->mmap_cq_offset = nes_ucontext->mmap_wq_offset +
((sizeof(struct nes_hw_qp_wqe) * uresp.max_qps * 2) + PAGE_SIZE-1) /
PAGE_SIZE;
if (ib_copy_to_udata(udata, &uresp, sizeof uresp)) {
kfree(nes_ucontext);
return ERR_PTR(-EFAULT);
}
INIT_LIST_HEAD(&nes_ucontext->cq_reg_mem_list);
INIT_LIST_HEAD(&nes_ucontext->qp_reg_mem_list);
atomic_set(&nes_ucontext->usecnt, 1);
return &nes_ucontext->ibucontext;
}
/**
* nes_dealloc_ucontext
*/
static int nes_dealloc_ucontext(struct ib_ucontext *context)
{
/* struct nes_vnic *nesvnic = to_nesvnic(context->device); */
/* struct nes_device *nesdev = nesvnic->nesdev; */
struct nes_ucontext *nes_ucontext = to_nesucontext(context);
if (!atomic_dec_and_test(&nes_ucontext->usecnt))
return 0;
kfree(nes_ucontext);
return 0;
}
/**
* nes_mmap
*/
static int nes_mmap(struct ib_ucontext *context, struct vm_area_struct *vma)
{
unsigned long index;
struct nes_vnic *nesvnic = to_nesvnic(context->device);
struct nes_device *nesdev = nesvnic->nesdev;
/* struct nes_adapter *nesadapter = nesdev->nesadapter; */
struct nes_ucontext *nes_ucontext;
struct nes_qp *nesqp;
nes_ucontext = to_nesucontext(context);
if (vma->vm_pgoff >= nes_ucontext->mmap_wq_offset) {
index = (vma->vm_pgoff - nes_ucontext->mmap_wq_offset) * PAGE_SIZE;
index /= ((sizeof(struct nes_hw_qp_wqe) * nesdev->nesadapter->max_qp_wr * 2) +
PAGE_SIZE-1) & (~(PAGE_SIZE-1));
if (!test_bit(index, nes_ucontext->allocated_wqs)) {
nes_debug(NES_DBG_MMAP, "wq %lu not allocated\n", index);
return -EFAULT;
}
nesqp = nes_ucontext->mmap_nesqp[index];
if (nesqp == NULL) {
nes_debug(NES_DBG_MMAP, "wq %lu has a NULL QP base.\n", index);
return -EFAULT;
}
if (remap_pfn_range(vma, vma->vm_start,
virt_to_phys(nesqp->hwqp.sq_vbase) >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot)) {
nes_debug(NES_DBG_MMAP, "remap_pfn_range failed.\n");
return -EAGAIN;
}
vma->vm_private_data = nesqp;
return 0;
} else {
index = vma->vm_pgoff;
if (!test_bit(index, nes_ucontext->allocated_doorbells))
return -EFAULT;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
if (io_remap_pfn_range(vma, vma->vm_start,
(nesdev->doorbell_start +
((nes_ucontext->mmap_db_index[index] - nesdev->base_doorbell_index) * 4096))
>> PAGE_SHIFT, PAGE_SIZE, vma->vm_page_prot))
return -EAGAIN;
vma->vm_private_data = nes_ucontext;
return 0;
}
return -ENOSYS;
}
/**
* nes_alloc_pd
*/
static struct ib_pd *nes_alloc_pd(struct ib_device *ibdev,
struct ib_ucontext *context, struct ib_udata *udata)
{
struct nes_pd *nespd;
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_ucontext *nesucontext;
struct nes_alloc_pd_resp uresp;
u32 pd_num = 0;
int err;
nes_debug(NES_DBG_PD, "nesvnic=%p, netdev=%p %s, ibdev=%p, context=%p, netdev refcnt=%u\n",
nesvnic, nesdev->netdev[0], nesdev->netdev[0]->name, ibdev, context,
netdev_refcnt_read(nesvnic->netdev));
err = nes_alloc_resource(nesadapter, nesadapter->allocated_pds,
nesadapter->max_pd, &pd_num, &nesadapter->next_pd, NES_RESOURCE_PD);
if (err) {
return ERR_PTR(err);
}
nespd = kzalloc(sizeof (struct nes_pd), GFP_KERNEL);
if (!nespd) {
nes_free_resource(nesadapter, nesadapter->allocated_pds, pd_num);
return ERR_PTR(-ENOMEM);
}
nes_debug(NES_DBG_PD, "Allocating PD (%p) for ib device %s\n",
nespd, nesvnic->nesibdev->ibdev.name);
nespd->pd_id = (pd_num << (PAGE_SHIFT-12)) + nesadapter->base_pd;
if (context) {
nesucontext = to_nesucontext(context);
nespd->mmap_db_index = find_next_zero_bit(nesucontext->allocated_doorbells,
NES_MAX_USER_DB_REGIONS, nesucontext->first_free_db);
nes_debug(NES_DBG_PD, "find_first_zero_biton doorbells returned %u, mapping pd_id %u.\n",
nespd->mmap_db_index, nespd->pd_id);
if (nespd->mmap_db_index >= NES_MAX_USER_DB_REGIONS) {
nes_debug(NES_DBG_PD, "mmap_db_index > MAX\n");
nes_free_resource(nesadapter, nesadapter->allocated_pds, pd_num);
kfree(nespd);
return ERR_PTR(-ENOMEM);
}
uresp.pd_id = nespd->pd_id;
uresp.mmap_db_index = nespd->mmap_db_index;
if (ib_copy_to_udata(udata, &uresp, sizeof (struct nes_alloc_pd_resp))) {
nes_free_resource(nesadapter, nesadapter->allocated_pds, pd_num);
kfree(nespd);
return ERR_PTR(-EFAULT);
}
set_bit(nespd->mmap_db_index, nesucontext->allocated_doorbells);
nesucontext->mmap_db_index[nespd->mmap_db_index] = nespd->pd_id;
nesucontext->first_free_db = nespd->mmap_db_index + 1;
}
nes_debug(NES_DBG_PD, "PD%u structure located @%p.\n", nespd->pd_id, nespd);
return &nespd->ibpd;
}
/**
* nes_dealloc_pd
*/
static int nes_dealloc_pd(struct ib_pd *ibpd)
{
struct nes_ucontext *nesucontext;
struct nes_pd *nespd = to_nespd(ibpd);
struct nes_vnic *nesvnic = to_nesvnic(ibpd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
if ((ibpd->uobject) && (ibpd->uobject->context)) {
nesucontext = to_nesucontext(ibpd->uobject->context);
nes_debug(NES_DBG_PD, "Clearing bit %u from allocated doorbells\n",
nespd->mmap_db_index);
clear_bit(nespd->mmap_db_index, nesucontext->allocated_doorbells);
nesucontext->mmap_db_index[nespd->mmap_db_index] = 0;
if (nesucontext->first_free_db > nespd->mmap_db_index) {
nesucontext->first_free_db = nespd->mmap_db_index;
}
}
nes_debug(NES_DBG_PD, "Deallocating PD%u structure located @%p.\n",
nespd->pd_id, nespd);
nes_free_resource(nesadapter, nesadapter->allocated_pds,
(nespd->pd_id-nesadapter->base_pd)>>(PAGE_SHIFT-12));
kfree(nespd);
return 0;
}
/**
* nes_create_ah
*/
static struct ib_ah *nes_create_ah(struct ib_pd *pd, struct ib_ah_attr *ah_attr)
{
return ERR_PTR(-ENOSYS);
}
/**
* nes_destroy_ah
*/
static int nes_destroy_ah(struct ib_ah *ah)
{
return -ENOSYS;
}
/**
* nes_get_encoded_size
*/
static inline u8 nes_get_encoded_size(int *size)
{
u8 encoded_size = 0;
if (*size <= 32) {
*size = 32;
encoded_size = 1;
} else if (*size <= 128) {
*size = 128;
encoded_size = 2;
} else if (*size <= 512) {
*size = 512;
encoded_size = 3;
}
return (encoded_size);
}
/**
* nes_setup_virt_qp
*/
static int nes_setup_virt_qp(struct nes_qp *nesqp, struct nes_pbl *nespbl,
struct nes_vnic *nesvnic, int sq_size, int rq_size)
{
unsigned long flags;
void *mem;
__le64 *pbl = NULL;
__le64 *tpbl;
__le64 *pblbuffer;
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 pbl_entries;
u8 rq_pbl_entries;
u8 sq_pbl_entries;
pbl_entries = nespbl->pbl_size >> 3;
nes_debug(NES_DBG_QP, "Userspace PBL, pbl_size=%u, pbl_entries = %d pbl_vbase=%p, pbl_pbase=%lx\n",
nespbl->pbl_size, pbl_entries,
(void *)nespbl->pbl_vbase,
(unsigned long) nespbl->pbl_pbase);
pbl = (__le64 *) nespbl->pbl_vbase; /* points to first pbl entry */
/* now lets set the sq_vbase as well as rq_vbase addrs we will assign */
/* the first pbl to be fro the rq_vbase... */
rq_pbl_entries = (rq_size * sizeof(struct nes_hw_qp_wqe)) >> 12;
sq_pbl_entries = (sq_size * sizeof(struct nes_hw_qp_wqe)) >> 12;
nesqp->hwqp.sq_pbase = (le32_to_cpu(((__le32 *)pbl)[0])) | ((u64)((le32_to_cpu(((__le32 *)pbl)[1]))) << 32);
if (!nespbl->page) {
nes_debug(NES_DBG_QP, "QP nespbl->page is NULL \n");
kfree(nespbl);
return -ENOMEM;
}
nesqp->hwqp.sq_vbase = kmap(nespbl->page);
nesqp->page = nespbl->page;
if (!nesqp->hwqp.sq_vbase) {
nes_debug(NES_DBG_QP, "QP sq_vbase kmap failed\n");
kfree(nespbl);
return -ENOMEM;
}
/* Now to get to sq.. we need to calculate how many */
/* PBL entries were used by the rq.. */
pbl += sq_pbl_entries;
nesqp->hwqp.rq_pbase = (le32_to_cpu(((__le32 *)pbl)[0])) | ((u64)((le32_to_cpu(((__le32 *)pbl)[1]))) << 32);
/* nesqp->hwqp.rq_vbase = bus_to_virt(*pbl); */
/*nesqp->hwqp.rq_vbase = phys_to_virt(*pbl); */
nes_debug(NES_DBG_QP, "QP sq_vbase= %p sq_pbase=%lx rq_vbase=%p rq_pbase=%lx\n",
nesqp->hwqp.sq_vbase, (unsigned long) nesqp->hwqp.sq_pbase,
nesqp->hwqp.rq_vbase, (unsigned long) nesqp->hwqp.rq_pbase);
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (!nesadapter->free_256pbl) {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size, nespbl->pbl_vbase,
nespbl->pbl_pbase);
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
kunmap(nesqp->page);
kfree(nespbl);
return -ENOMEM;
}
nesadapter->free_256pbl--;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nesqp->pbl_vbase = pci_alloc_consistent(nesdev->pcidev, 256, &nesqp->pbl_pbase);
pblbuffer = nesqp->pbl_vbase;
if (!nesqp->pbl_vbase) {
/* memory allocated during nes_reg_user_mr() */
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size, nespbl->pbl_vbase,
nespbl->pbl_pbase);
kfree(nespbl);
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
nesadapter->free_256pbl++;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
kunmap(nesqp->page);
return -ENOMEM;
}
memset(nesqp->pbl_vbase, 0, 256);
/* fill in the page address in the pbl buffer.. */
tpbl = pblbuffer + 16;
pbl = (__le64 *)nespbl->pbl_vbase;
while (sq_pbl_entries--)
*tpbl++ = *pbl++;
tpbl = pblbuffer;
while (rq_pbl_entries--)
*tpbl++ = *pbl++;
/* done with memory allocated during nes_reg_user_mr() */
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size, nespbl->pbl_vbase,
nespbl->pbl_pbase);
kfree(nespbl);
nesqp->qp_mem_size =
max((u32)sizeof(struct nes_qp_context), ((u32)256)) + 256; /* this is Q2 */
/* Round up to a multiple of a page */
nesqp->qp_mem_size += PAGE_SIZE - 1;
nesqp->qp_mem_size &= ~(PAGE_SIZE - 1);
mem = pci_alloc_consistent(nesdev->pcidev, nesqp->qp_mem_size,
&nesqp->hwqp.q2_pbase);
if (!mem) {
pci_free_consistent(nesdev->pcidev, 256, nesqp->pbl_vbase, nesqp->pbl_pbase);
nesqp->pbl_vbase = NULL;
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
nesadapter->free_256pbl++;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
kunmap(nesqp->page);
return -ENOMEM;
}
nesqp->sq_kmapped = 1;
nesqp->hwqp.q2_vbase = mem;
mem += 256;
memset(nesqp->hwqp.q2_vbase, 0, 256);
nesqp->nesqp_context = mem;
memset(nesqp->nesqp_context, 0, sizeof(*nesqp->nesqp_context));
nesqp->nesqp_context_pbase = nesqp->hwqp.q2_pbase + 256;
return 0;
}
/**
* nes_setup_mmap_qp
*/
static int nes_setup_mmap_qp(struct nes_qp *nesqp, struct nes_vnic *nesvnic,
int sq_size, int rq_size)
{
void *mem;
struct nes_device *nesdev = nesvnic->nesdev;
nesqp->qp_mem_size = (sizeof(struct nes_hw_qp_wqe) * sq_size) +
(sizeof(struct nes_hw_qp_wqe) * rq_size) +
max((u32)sizeof(struct nes_qp_context), ((u32)256)) +
256; /* this is Q2 */
/* Round up to a multiple of a page */
nesqp->qp_mem_size += PAGE_SIZE - 1;
nesqp->qp_mem_size &= ~(PAGE_SIZE - 1);
mem = pci_alloc_consistent(nesdev->pcidev, nesqp->qp_mem_size,
&nesqp->hwqp.sq_pbase);
if (!mem)
return -ENOMEM;
nes_debug(NES_DBG_QP, "PCI consistent memory for "
"host descriptor rings located @ %p (pa = 0x%08lX.) size = %u.\n",
mem, (unsigned long)nesqp->hwqp.sq_pbase, nesqp->qp_mem_size);
memset(mem, 0, nesqp->qp_mem_size);
nesqp->hwqp.sq_vbase = mem;
mem += sizeof(struct nes_hw_qp_wqe) * sq_size;
nesqp->hwqp.rq_vbase = mem;
nesqp->hwqp.rq_pbase = nesqp->hwqp.sq_pbase +
sizeof(struct nes_hw_qp_wqe) * sq_size;
mem += sizeof(struct nes_hw_qp_wqe) * rq_size;
nesqp->hwqp.q2_vbase = mem;
nesqp->hwqp.q2_pbase = nesqp->hwqp.rq_pbase +
sizeof(struct nes_hw_qp_wqe) * rq_size;
mem += 256;
memset(nesqp->hwqp.q2_vbase, 0, 256);
nesqp->nesqp_context = mem;
nesqp->nesqp_context_pbase = nesqp->hwqp.q2_pbase + 256;
memset(nesqp->nesqp_context, 0, sizeof(*nesqp->nesqp_context));
return 0;
}
/**
* nes_free_qp_mem() is to free up the qp's pci_alloc_consistent() memory.
*/
static inline void nes_free_qp_mem(struct nes_device *nesdev,
struct nes_qp *nesqp, int virt_wqs)
{
unsigned long flags;
struct nes_adapter *nesadapter = nesdev->nesadapter;
if (!virt_wqs) {
pci_free_consistent(nesdev->pcidev, nesqp->qp_mem_size,
nesqp->hwqp.sq_vbase, nesqp->hwqp.sq_pbase);
}else {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
nesadapter->free_256pbl++;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
pci_free_consistent(nesdev->pcidev, nesqp->qp_mem_size, nesqp->hwqp.q2_vbase, nesqp->hwqp.q2_pbase);
pci_free_consistent(nesdev->pcidev, 256, nesqp->pbl_vbase, nesqp->pbl_pbase );
nesqp->pbl_vbase = NULL;
if (nesqp->sq_kmapped) {
nesqp->sq_kmapped = 0;
kunmap(nesqp->page);
}
}
}
/**
* nes_create_qp
*/
static struct ib_qp *nes_create_qp(struct ib_pd *ibpd,
struct ib_qp_init_attr *init_attr, struct ib_udata *udata)
{
u64 u64temp= 0;
u64 u64nesqp = 0;
struct nes_pd *nespd = to_nespd(ibpd);
struct nes_vnic *nesvnic = to_nesvnic(ibpd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_qp *nesqp;
struct nes_cq *nescq;
struct nes_ucontext *nes_ucontext;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
struct nes_create_qp_req req;
struct nes_create_qp_resp uresp;
struct nes_pbl *nespbl = NULL;
u32 qp_num = 0;
u32 opcode = 0;
/* u32 counter = 0; */
void *mem;
unsigned long flags;
int ret;
int err;
int virt_wqs = 0;
int sq_size;
int rq_size;
u8 sq_encoded_size;
u8 rq_encoded_size;
/* int counter; */
if (init_attr->create_flags)
return ERR_PTR(-EINVAL);
atomic_inc(&qps_created);
switch (init_attr->qp_type) {
case IB_QPT_RC:
if (nes_drv_opt & NES_DRV_OPT_NO_INLINE_DATA) {
init_attr->cap.max_inline_data = 0;
} else {
init_attr->cap.max_inline_data = 64;
}
sq_size = init_attr->cap.max_send_wr;
rq_size = init_attr->cap.max_recv_wr;
/* check if the encoded sizes are OK or not... */
sq_encoded_size = nes_get_encoded_size(&sq_size);
rq_encoded_size = nes_get_encoded_size(&rq_size);
if ((!sq_encoded_size) || (!rq_encoded_size)) {
nes_debug(NES_DBG_QP, "ERROR bad rq (%u) or sq (%u) size\n",
rq_size, sq_size);
return ERR_PTR(-EINVAL);
}
init_attr->cap.max_send_wr = sq_size -2;
init_attr->cap.max_recv_wr = rq_size -1;
nes_debug(NES_DBG_QP, "RQ size=%u, SQ Size=%u\n", rq_size, sq_size);
ret = nes_alloc_resource(nesadapter, nesadapter->allocated_qps,
nesadapter->max_qp, &qp_num, &nesadapter->next_qp, NES_RESOURCE_QP);
if (ret) {
return ERR_PTR(ret);
}
/* Need 512 (actually now 1024) byte alignment on this structure */
mem = kzalloc(sizeof(*nesqp)+NES_SW_CONTEXT_ALIGN-1, GFP_KERNEL);
if (!mem) {
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
nes_debug(NES_DBG_QP, "Unable to allocate QP\n");
return ERR_PTR(-ENOMEM);
}
u64nesqp = (unsigned long)mem;
u64nesqp += ((u64)NES_SW_CONTEXT_ALIGN) - 1;
u64temp = ((u64)NES_SW_CONTEXT_ALIGN) - 1;
u64nesqp &= ~u64temp;
nesqp = (struct nes_qp *)(unsigned long)u64nesqp;
/* nes_debug(NES_DBG_QP, "nesqp=%p, allocated buffer=%p. Rounded to closest %u\n",
nesqp, mem, NES_SW_CONTEXT_ALIGN); */
nesqp->allocated_buffer = mem;
if (udata) {
if (ib_copy_from_udata(&req, udata, sizeof(struct nes_create_qp_req))) {
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
kfree(nesqp->allocated_buffer);
nes_debug(NES_DBG_QP, "ib_copy_from_udata() Failed \n");
return ERR_PTR(-EFAULT);
}
if (req.user_wqe_buffers) {
virt_wqs = 1;
}
if (req.user_qp_buffer)
nesqp->nesuqp_addr = req.user_qp_buffer;
if ((ibpd->uobject) && (ibpd->uobject->context)) {
nesqp->user_mode = 1;
nes_ucontext = to_nesucontext(ibpd->uobject->context);
if (virt_wqs) {
err = 1;
list_for_each_entry(nespbl, &nes_ucontext->qp_reg_mem_list, list) {
if (nespbl->user_base == (unsigned long )req.user_wqe_buffers) {
list_del(&nespbl->list);
err = 0;
nes_debug(NES_DBG_QP, "Found PBL for virtual QP. nespbl=%p. user_base=0x%lx\n",
nespbl, nespbl->user_base);
break;
}
}
if (err) {
nes_debug(NES_DBG_QP, "Didn't Find PBL for virtual QP. address = %llx.\n",
(long long unsigned int)req.user_wqe_buffers);
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
kfree(nesqp->allocated_buffer);
return ERR_PTR(-EFAULT);
}
}
nes_ucontext = to_nesucontext(ibpd->uobject->context);
nesqp->mmap_sq_db_index =
find_next_zero_bit(nes_ucontext->allocated_wqs,
NES_MAX_USER_WQ_REGIONS, nes_ucontext->first_free_wq);
/* nes_debug(NES_DBG_QP, "find_first_zero_biton wqs returned %u\n",
nespd->mmap_db_index); */
if (nesqp->mmap_sq_db_index >= NES_MAX_USER_WQ_REGIONS) {
nes_debug(NES_DBG_QP,
"db index > max user regions, failing create QP\n");
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
if (virt_wqs) {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size, nespbl->pbl_vbase,
nespbl->pbl_pbase);
kfree(nespbl);
}
kfree(nesqp->allocated_buffer);
return ERR_PTR(-ENOMEM);
}
set_bit(nesqp->mmap_sq_db_index, nes_ucontext->allocated_wqs);
nes_ucontext->mmap_nesqp[nesqp->mmap_sq_db_index] = nesqp;
nes_ucontext->first_free_wq = nesqp->mmap_sq_db_index + 1;
} else {
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
kfree(nesqp->allocated_buffer);
return ERR_PTR(-EFAULT);
}
}
err = (!virt_wqs) ? nes_setup_mmap_qp(nesqp, nesvnic, sq_size, rq_size) :
nes_setup_virt_qp(nesqp, nespbl, nesvnic, sq_size, rq_size);
if (err) {
nes_debug(NES_DBG_QP,
"error geting qp mem code = %d\n", err);
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
kfree(nesqp->allocated_buffer);
return ERR_PTR(-ENOMEM);
}
nesqp->hwqp.sq_size = sq_size;
nesqp->hwqp.sq_encoded_size = sq_encoded_size;
nesqp->hwqp.sq_head = 1;
nesqp->hwqp.rq_size = rq_size;
nesqp->hwqp.rq_encoded_size = rq_encoded_size;
/* nes_debug(NES_DBG_QP, "nesqp->nesqp_context_pbase = %p\n",
(void *)nesqp->nesqp_context_pbase);
*/
nesqp->hwqp.qp_id = qp_num;
nesqp->ibqp.qp_num = nesqp->hwqp.qp_id;
nesqp->nespd = nespd;
nescq = to_nescq(init_attr->send_cq);
nesqp->nesscq = nescq;
nescq = to_nescq(init_attr->recv_cq);
nesqp->nesrcq = nescq;
nesqp->nesqp_context->misc |= cpu_to_le32((u32)PCI_FUNC(nesdev->pcidev->devfn) <<
NES_QPCONTEXT_MISC_PCI_FCN_SHIFT);
nesqp->nesqp_context->misc |= cpu_to_le32((u32)nesqp->hwqp.rq_encoded_size <<
NES_QPCONTEXT_MISC_RQ_SIZE_SHIFT);
nesqp->nesqp_context->misc |= cpu_to_le32((u32)nesqp->hwqp.sq_encoded_size <<
NES_QPCONTEXT_MISC_SQ_SIZE_SHIFT);
if (!udata) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_PRIV_EN);
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_FAST_REGISTER_EN);
}
nesqp->nesqp_context->cqs = cpu_to_le32(nesqp->nesscq->hw_cq.cq_number +
((u32)nesqp->nesrcq->hw_cq.cq_number << 16));
u64temp = (u64)nesqp->hwqp.sq_pbase;
nesqp->nesqp_context->sq_addr_low = cpu_to_le32((u32)u64temp);
nesqp->nesqp_context->sq_addr_high = cpu_to_le32((u32)(u64temp >> 32));
if (!virt_wqs) {
u64temp = (u64)nesqp->hwqp.sq_pbase;
nesqp->nesqp_context->sq_addr_low = cpu_to_le32((u32)u64temp);
nesqp->nesqp_context->sq_addr_high = cpu_to_le32((u32)(u64temp >> 32));
u64temp = (u64)nesqp->hwqp.rq_pbase;
nesqp->nesqp_context->rq_addr_low = cpu_to_le32((u32)u64temp);
nesqp->nesqp_context->rq_addr_high = cpu_to_le32((u32)(u64temp >> 32));
} else {
u64temp = (u64)nesqp->pbl_pbase;
nesqp->nesqp_context->rq_addr_low = cpu_to_le32((u32)u64temp);
nesqp->nesqp_context->rq_addr_high = cpu_to_le32((u32)(u64temp >> 32));
}
/* nes_debug(NES_DBG_QP, "next_qp_nic_index=%u, using nic_index=%d\n",
nesvnic->next_qp_nic_index,
nesvnic->qp_nic_index[nesvnic->next_qp_nic_index]); */
spin_lock_irqsave(&nesdev->cqp.lock, flags);
nesqp->nesqp_context->misc2 |= cpu_to_le32(
(u32)nesvnic->qp_nic_index[nesvnic->next_qp_nic_index] <<
NES_QPCONTEXT_MISC2_NIC_INDEX_SHIFT);
nesvnic->next_qp_nic_index++;
if ((nesvnic->next_qp_nic_index > 3) ||
(nesvnic->qp_nic_index[nesvnic->next_qp_nic_index] == 0xf)) {
nesvnic->next_qp_nic_index = 0;
}
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
nesqp->nesqp_context->pd_index_wscale |= cpu_to_le32((u32)nesqp->nespd->pd_id << 16);
u64temp = (u64)nesqp->hwqp.q2_pbase;
nesqp->nesqp_context->q2_addr_low = cpu_to_le32((u32)u64temp);
nesqp->nesqp_context->q2_addr_high = cpu_to_le32((u32)(u64temp >> 32));
nesqp->nesqp_context->aeq_token_low = cpu_to_le32((u32)((unsigned long)(nesqp)));
nesqp->nesqp_context->aeq_token_high = cpu_to_le32((u32)(upper_32_bits((unsigned long)(nesqp))));
nesqp->nesqp_context->ird_ord_sizes = cpu_to_le32(NES_QPCONTEXT_ORDIRD_ALSMM |
NES_QPCONTEXT_ORDIRD_AAH |
((((u32)nesadapter->max_irrq_wr) <<
NES_QPCONTEXT_ORDIRD_IRDSIZE_SHIFT) & NES_QPCONTEXT_ORDIRD_IRDSIZE_MASK));
if (disable_mpa_crc) {
nes_debug(NES_DBG_QP, "Disabling MPA crc checking due to module option.\n");
nesqp->nesqp_context->ird_ord_sizes |= cpu_to_le32(NES_QPCONTEXT_ORDIRD_RNMC);
}
/* Create the QP */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_QP, "Failed to get a cqp_request\n");
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
nes_free_qp_mem(nesdev, nesqp,virt_wqs);
kfree(nesqp->allocated_buffer);
return ERR_PTR(-ENOMEM);
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
if (!virt_wqs) {
opcode = NES_CQP_CREATE_QP | NES_CQP_QP_TYPE_IWARP |
NES_CQP_QP_IWARP_STATE_IDLE;
} else {
opcode = NES_CQP_CREATE_QP | NES_CQP_QP_TYPE_IWARP | NES_CQP_QP_VIRT_WQS |
NES_CQP_QP_IWARP_STATE_IDLE;
}
opcode |= NES_CQP_QP_CQS_VALID;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, opcode);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX, nesqp->hwqp.qp_id);
u64temp = (u64)nesqp->nesqp_context_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, u64temp);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
nes_debug(NES_DBG_QP, "Waiting for create iWARP QP%u to complete.\n",
nesqp->hwqp.qp_id);
ret = wait_event_timeout(cqp_request->waitq,
(cqp_request->request_done != 0), NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_QP, "Create iwarp QP%u completed, wait_event_timeout ret=%u,"
" nesdev->cqp_head = %u, nesdev->cqp.sq_tail = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X.\n",
nesqp->hwqp.qp_id, ret, nesdev->cqp.sq_head, nesdev->cqp.sq_tail,
cqp_request->major_code, cqp_request->minor_code);
if ((!ret) || (cqp_request->major_code)) {
nes_put_cqp_request(nesdev, cqp_request);
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
nes_free_qp_mem(nesdev, nesqp,virt_wqs);
kfree(nesqp->allocated_buffer);
if (!ret) {
return ERR_PTR(-ETIME);
} else {
return ERR_PTR(-EIO);
}
}
nes_put_cqp_request(nesdev, cqp_request);
if (ibpd->uobject) {
uresp.mmap_sq_db_index = nesqp->mmap_sq_db_index;
uresp.mmap_rq_db_index = 0;
uresp.actual_sq_size = sq_size;
uresp.actual_rq_size = rq_size;
uresp.qp_id = nesqp->hwqp.qp_id;
uresp.nes_drv_opt = nes_drv_opt;
if (ib_copy_to_udata(udata, &uresp, sizeof uresp)) {
nes_free_resource(nesadapter, nesadapter->allocated_qps, qp_num);
nes_free_qp_mem(nesdev, nesqp,virt_wqs);
kfree(nesqp->allocated_buffer);
return ERR_PTR(-EFAULT);
}
}
nes_debug(NES_DBG_QP, "QP%u structure located @%p.Size = %u.\n",
nesqp->hwqp.qp_id, nesqp, (u32)sizeof(*nesqp));
spin_lock_init(&nesqp->lock);
nes_add_ref(&nesqp->ibqp);
break;
default:
nes_debug(NES_DBG_QP, "Invalid QP type: %d\n", init_attr->qp_type);
return ERR_PTR(-EINVAL);
}
nesqp->sig_all = (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR);
init_timer(&nesqp->terminate_timer);
nesqp->terminate_timer.function = nes_terminate_timeout;
nesqp->terminate_timer.data = (unsigned long)nesqp;
/* update the QP table */
nesdev->nesadapter->qp_table[nesqp->hwqp.qp_id-NES_FIRST_QPN] = nesqp;
nes_debug(NES_DBG_QP, "netdev refcnt=%u\n",
netdev_refcnt_read(nesvnic->netdev));
return &nesqp->ibqp;
}
/**
* nes_clean_cq
*/
static void nes_clean_cq(struct nes_qp *nesqp, struct nes_cq *nescq)
{
u32 cq_head;
u32 lo;
u32 hi;
u64 u64temp;
unsigned long flags = 0;
spin_lock_irqsave(&nescq->lock, flags);
cq_head = nescq->hw_cq.cq_head;
while (le32_to_cpu(nescq->hw_cq.cq_vbase[cq_head].cqe_words[NES_CQE_OPCODE_IDX]) & NES_CQE_VALID) {
rmb();
lo = le32_to_cpu(nescq->hw_cq.cq_vbase[cq_head].cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX]);
hi = le32_to_cpu(nescq->hw_cq.cq_vbase[cq_head].cqe_words[NES_CQE_COMP_COMP_CTX_HIGH_IDX]);
u64temp = (((u64)hi) << 32) | ((u64)lo);
u64temp &= ~(NES_SW_CONTEXT_ALIGN-1);
if (u64temp == (u64)(unsigned long)nesqp) {
/* Zero the context value so cqe will be ignored */
nescq->hw_cq.cq_vbase[cq_head].cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX] = 0;
nescq->hw_cq.cq_vbase[cq_head].cqe_words[NES_CQE_COMP_COMP_CTX_HIGH_IDX] = 0;
}
if (++cq_head >= nescq->hw_cq.cq_size)
cq_head = 0;
}
spin_unlock_irqrestore(&nescq->lock, flags);
}
/**
* nes_destroy_qp
*/
static int nes_destroy_qp(struct ib_qp *ibqp)
{
struct nes_qp *nesqp = to_nesqp(ibqp);
struct nes_ucontext *nes_ucontext;
struct ib_qp_attr attr;
struct iw_cm_id *cm_id;
struct iw_cm_event cm_event;
int ret = 0;
atomic_inc(&sw_qps_destroyed);
nesqp->destroyed = 1;
/* Blow away the connection if it exists. */
if (nesqp->ibqp_state >= IB_QPS_INIT && nesqp->ibqp_state <= IB_QPS_RTS) {
/* if (nesqp->ibqp_state == IB_QPS_RTS) { */
attr.qp_state = IB_QPS_ERR;
nes_modify_qp(&nesqp->ibqp, &attr, IB_QP_STATE, NULL);
}
if (((nesqp->ibqp_state == IB_QPS_INIT) ||
(nesqp->ibqp_state == IB_QPS_RTR)) && (nesqp->cm_id)) {
cm_id = nesqp->cm_id;
cm_event.event = IW_CM_EVENT_CONNECT_REPLY;
cm_event.status = -ETIMEDOUT;
cm_event.local_addr = cm_id->local_addr;
cm_event.remote_addr = cm_id->remote_addr;
cm_event.private_data = NULL;
cm_event.private_data_len = 0;
nes_debug(NES_DBG_QP, "Generating a CM Timeout Event for "
"QP%u. cm_id = %p, refcount = %u. \n",
nesqp->hwqp.qp_id, cm_id, atomic_read(&nesqp->refcount));
cm_id->rem_ref(cm_id);
ret = cm_id->event_handler(cm_id, &cm_event);
if (ret)
nes_debug(NES_DBG_QP, "OFA CM event_handler returned, ret=%d\n", ret);
}
if (nesqp->user_mode) {
if ((ibqp->uobject)&&(ibqp->uobject->context)) {
nes_ucontext = to_nesucontext(ibqp->uobject->context);
clear_bit(nesqp->mmap_sq_db_index, nes_ucontext->allocated_wqs);
nes_ucontext->mmap_nesqp[nesqp->mmap_sq_db_index] = NULL;
if (nes_ucontext->first_free_wq > nesqp->mmap_sq_db_index) {
nes_ucontext->first_free_wq = nesqp->mmap_sq_db_index;
}
}
if (nesqp->pbl_pbase && nesqp->sq_kmapped) {
nesqp->sq_kmapped = 0;
kunmap(nesqp->page);
}
} else {
/* Clean any pending completions from the cq(s) */
if (nesqp->nesscq)
nes_clean_cq(nesqp, nesqp->nesscq);
if ((nesqp->nesrcq) && (nesqp->nesrcq != nesqp->nesscq))
nes_clean_cq(nesqp, nesqp->nesrcq);
}
nes_rem_ref(&nesqp->ibqp);
return 0;
}
/**
* nes_create_cq
*/
static struct ib_cq *nes_create_cq(struct ib_device *ibdev,
const struct ib_cq_init_attr *attr,
struct ib_ucontext *context,
struct ib_udata *udata)
{
int entries = attr->cqe;
u64 u64temp;
struct nes_vnic *nesvnic = to_nesvnic(ibdev);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_cq *nescq;
struct nes_ucontext *nes_ucontext = NULL;
struct nes_cqp_request *cqp_request;
void *mem = NULL;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_pbl *nespbl = NULL;
struct nes_create_cq_req req;
struct nes_create_cq_resp resp;
u32 cq_num = 0;
u32 opcode = 0;
u32 pbl_entries = 1;
int err;
unsigned long flags;
int ret;
if (attr->flags)
return ERR_PTR(-EINVAL);
if (entries > nesadapter->max_cqe)
return ERR_PTR(-EINVAL);
err = nes_alloc_resource(nesadapter, nesadapter->allocated_cqs,
nesadapter->max_cq, &cq_num, &nesadapter->next_cq, NES_RESOURCE_CQ);
if (err) {
return ERR_PTR(err);
}
nescq = kzalloc(sizeof(struct nes_cq), GFP_KERNEL);
if (!nescq) {
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
nes_debug(NES_DBG_CQ, "Unable to allocate nes_cq struct\n");
return ERR_PTR(-ENOMEM);
}
nescq->hw_cq.cq_size = max(entries + 1, 5);
nescq->hw_cq.cq_number = cq_num;
nescq->ibcq.cqe = nescq->hw_cq.cq_size - 1;
if (context) {
nes_ucontext = to_nesucontext(context);
if (ib_copy_from_udata(&req, udata, sizeof (struct nes_create_cq_req))) {
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-EFAULT);
}
nesvnic->mcrq_ucontext = nes_ucontext;
nes_ucontext->mcrqf = req.mcrqf;
if (nes_ucontext->mcrqf) {
if (nes_ucontext->mcrqf & 0x80000000)
nescq->hw_cq.cq_number = nesvnic->nic.qp_id + 28 + 2 * ((nes_ucontext->mcrqf & 0xf) - 1);
else if (nes_ucontext->mcrqf & 0x40000000)
nescq->hw_cq.cq_number = nes_ucontext->mcrqf & 0xffff;
else
nescq->hw_cq.cq_number = nesvnic->mcrq_qp_id + nes_ucontext->mcrqf-1;
nescq->mcrqf = nes_ucontext->mcrqf;
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
}
nes_debug(NES_DBG_CQ, "CQ Virtual Address = %08lX, size = %u.\n",
(unsigned long)req.user_cq_buffer, entries);
err = 1;
list_for_each_entry(nespbl, &nes_ucontext->cq_reg_mem_list, list) {
if (nespbl->user_base == (unsigned long )req.user_cq_buffer) {
list_del(&nespbl->list);
err = 0;
nes_debug(NES_DBG_CQ, "Found PBL for virtual CQ. nespbl=%p.\n",
nespbl);
break;
}
}
if (err) {
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-EFAULT);
}
pbl_entries = nespbl->pbl_size >> 3;
nescq->cq_mem_size = 0;
} else {
nescq->cq_mem_size = nescq->hw_cq.cq_size * sizeof(struct nes_hw_cqe);
nes_debug(NES_DBG_CQ, "Attempting to allocate pci memory (%u entries, %u bytes) for CQ%u.\n",
entries, nescq->cq_mem_size, nescq->hw_cq.cq_number);
/* allocate the physical buffer space */
mem = pci_zalloc_consistent(nesdev->pcidev, nescq->cq_mem_size,
&nescq->hw_cq.cq_pbase);
if (!mem) {
printk(KERN_ERR PFX "Unable to allocate pci memory for cq\n");
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-ENOMEM);
}
nescq->hw_cq.cq_vbase = mem;
nescq->hw_cq.cq_head = 0;
nes_debug(NES_DBG_CQ, "CQ%u virtual address @ %p, phys = 0x%08X\n",
nescq->hw_cq.cq_number, nescq->hw_cq.cq_vbase,
(u32)nescq->hw_cq.cq_pbase);
}
nescq->hw_cq.ce_handler = nes_iwarp_ce_handler;
spin_lock_init(&nescq->lock);
/* send CreateCQ request to CQP */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_CQ, "Failed to get a cqp_request.\n");
if (!context)
pci_free_consistent(nesdev->pcidev, nescq->cq_mem_size, mem,
nescq->hw_cq.cq_pbase);
else {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size,
nespbl->pbl_vbase, nespbl->pbl_pbase);
kfree(nespbl);
}
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-ENOMEM);
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
opcode = NES_CQP_CREATE_CQ | NES_CQP_CQ_CEQ_VALID |
NES_CQP_CQ_CHK_OVERFLOW |
NES_CQP_CQ_CEQE_MASK | ((u32)nescq->hw_cq.cq_size << 16);
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (pbl_entries != 1) {
if (pbl_entries > 32) {
/* use 4k pbl */
nes_debug(NES_DBG_CQ, "pbl_entries=%u, use a 4k PBL\n", pbl_entries);
if (nesadapter->free_4kpbl == 0) {
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_free_cqp_request(nesdev, cqp_request);
if (!context)
pci_free_consistent(nesdev->pcidev, nescq->cq_mem_size, mem,
nescq->hw_cq.cq_pbase);
else {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size,
nespbl->pbl_vbase, nespbl->pbl_pbase);
kfree(nespbl);
}
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-ENOMEM);
} else {
opcode |= (NES_CQP_CQ_VIRT | NES_CQP_CQ_4KB_CHUNK);
nescq->virtual_cq = 2;
nesadapter->free_4kpbl--;
}
} else {
/* use 256 byte pbl */
nes_debug(NES_DBG_CQ, "pbl_entries=%u, use a 256 byte PBL\n", pbl_entries);
if (nesadapter->free_256pbl == 0) {
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_free_cqp_request(nesdev, cqp_request);
if (!context)
pci_free_consistent(nesdev->pcidev, nescq->cq_mem_size, mem,
nescq->hw_cq.cq_pbase);
else {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size,
nespbl->pbl_vbase, nespbl->pbl_pbase);
kfree(nespbl);
}
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-ENOMEM);
} else {
opcode |= NES_CQP_CQ_VIRT;
nescq->virtual_cq = 1;
nesadapter->free_256pbl--;
}
}
}
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, opcode);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
(nescq->hw_cq.cq_number | ((u32)nesdev->ceq_index << 16)));
if (context) {
if (pbl_entries != 1)
u64temp = (u64)nespbl->pbl_pbase;
else
u64temp = le64_to_cpu(nespbl->pbl_vbase[0]);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_DOORBELL_INDEX_HIGH_IDX,
nes_ucontext->mmap_db_index[0]);
} else {
u64temp = (u64)nescq->hw_cq.cq_pbase;
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_DOORBELL_INDEX_HIGH_IDX] = 0;
}
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] = 0;
u64temp = (u64)(unsigned long)&nescq->hw_cq;
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_LOW_IDX] =
cpu_to_le32((u32)(u64temp >> 1));
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] =
cpu_to_le32(((u32)((u64temp) >> 33)) & 0x7FFFFFFF);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
nes_debug(NES_DBG_CQ, "Waiting for create iWARP CQ%u to complete.\n",
nescq->hw_cq.cq_number);
ret = wait_event_timeout(cqp_request->waitq, (0 != cqp_request->request_done),
NES_EVENT_TIMEOUT * 2);
nes_debug(NES_DBG_CQ, "Create iWARP CQ%u completed, wait_event_timeout ret = %d.\n",
nescq->hw_cq.cq_number, ret);
if ((!ret) || (cqp_request->major_code)) {
nes_put_cqp_request(nesdev, cqp_request);
if (!context)
pci_free_consistent(nesdev->pcidev, nescq->cq_mem_size, mem,
nescq->hw_cq.cq_pbase);
else {
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size,
nespbl->pbl_vbase, nespbl->pbl_pbase);
kfree(nespbl);
}
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-EIO);
}
nes_put_cqp_request(nesdev, cqp_request);
if (context) {
/* free the nespbl */
pci_free_consistent(nesdev->pcidev, nespbl->pbl_size, nespbl->pbl_vbase,
nespbl->pbl_pbase);
kfree(nespbl);
resp.cq_id = nescq->hw_cq.cq_number;
resp.cq_size = nescq->hw_cq.cq_size;
resp.mmap_db_index = 0;
if (ib_copy_to_udata(udata, &resp, sizeof resp - sizeof resp.reserved)) {
nes_free_resource(nesadapter, nesadapter->allocated_cqs, cq_num);
kfree(nescq);
return ERR_PTR(-EFAULT);
}
}
return &nescq->ibcq;
}
/**
* nes_destroy_cq
*/
static int nes_destroy_cq(struct ib_cq *ib_cq)
{
struct nes_cq *nescq;
struct nes_device *nesdev;
struct nes_vnic *nesvnic;
struct nes_adapter *nesadapter;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
unsigned long flags;
u32 opcode = 0;
int ret;
if (ib_cq == NULL)
return 0;
nescq = to_nescq(ib_cq);
nesvnic = to_nesvnic(ib_cq->device);
nesdev = nesvnic->nesdev;
nesadapter = nesdev->nesadapter;
nes_debug(NES_DBG_CQ, "Destroy CQ%u\n", nescq->hw_cq.cq_number);
/* Send DestroyCQ request to CQP */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_CQ, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
opcode = NES_CQP_DESTROY_CQ | (nescq->hw_cq.cq_size << 16);
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (nescq->virtual_cq == 1) {
nesadapter->free_256pbl++;
if (nesadapter->free_256pbl > nesadapter->max_256pbl) {
printk(KERN_ERR PFX "%s: free 256B PBLs(%u) has exceeded the max(%u)\n",
__func__, nesadapter->free_256pbl, nesadapter->max_256pbl);
}
} else if (nescq->virtual_cq == 2) {
nesadapter->free_4kpbl++;
if (nesadapter->free_4kpbl > nesadapter->max_4kpbl) {
printk(KERN_ERR PFX "%s: free 4K PBLs(%u) has exceeded the max(%u)\n",
__func__, nesadapter->free_4kpbl, nesadapter->max_4kpbl);
}
opcode |= NES_CQP_CQ_4KB_CHUNK;
}
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, opcode);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
(nescq->hw_cq.cq_number | ((u32)PCI_FUNC(nesdev->pcidev->devfn) << 16)));
if (!nescq->mcrqf)
nes_free_resource(nesadapter, nesadapter->allocated_cqs, nescq->hw_cq.cq_number);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
nes_debug(NES_DBG_CQ, "Waiting for destroy iWARP CQ%u to complete.\n",
nescq->hw_cq.cq_number);
ret = wait_event_timeout(cqp_request->waitq, (0 != cqp_request->request_done),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_CQ, "Destroy iWARP CQ%u completed, wait_event_timeout ret = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X.\n",
nescq->hw_cq.cq_number, ret, cqp_request->major_code,
cqp_request->minor_code);
if (!ret) {
nes_debug(NES_DBG_CQ, "iWARP CQ%u destroy timeout expired\n",
nescq->hw_cq.cq_number);
ret = -ETIME;
} else if (cqp_request->major_code) {
nes_debug(NES_DBG_CQ, "iWARP CQ%u destroy failed\n",
nescq->hw_cq.cq_number);
ret = -EIO;
} else {
ret = 0;
}
nes_put_cqp_request(nesdev, cqp_request);
if (nescq->cq_mem_size)
pci_free_consistent(nesdev->pcidev, nescq->cq_mem_size,
nescq->hw_cq.cq_vbase, nescq->hw_cq.cq_pbase);
kfree(nescq);
return ret;
}
/**
* root_256
*/
static u32 root_256(struct nes_device *nesdev,
struct nes_root_vpbl *root_vpbl,
struct nes_root_vpbl *new_root,
u16 pbl_count_4k)
{
u64 leaf_pbl;
int i, j, k;
if (pbl_count_4k == 1) {
new_root->pbl_vbase = pci_alloc_consistent(nesdev->pcidev,
512, &new_root->pbl_pbase);
if (new_root->pbl_vbase == NULL)
return 0;
leaf_pbl = (u64)root_vpbl->pbl_pbase;
for (i = 0; i < 16; i++) {
new_root->pbl_vbase[i].pa_low =
cpu_to_le32((u32)leaf_pbl);
new_root->pbl_vbase[i].pa_high =
cpu_to_le32((u32)((((u64)leaf_pbl) >> 32)));
leaf_pbl += 256;
}
} else {
for (i = 3; i >= 0; i--) {
j = i * 16;
root_vpbl->pbl_vbase[j] = root_vpbl->pbl_vbase[i];
leaf_pbl = le32_to_cpu(root_vpbl->pbl_vbase[j].pa_low) +
(((u64)le32_to_cpu(root_vpbl->pbl_vbase[j].pa_high))
<< 32);
for (k = 1; k < 16; k++) {
leaf_pbl += 256;
root_vpbl->pbl_vbase[j + k].pa_low =
cpu_to_le32((u32)leaf_pbl);
root_vpbl->pbl_vbase[j + k].pa_high =
cpu_to_le32((u32)((((u64)leaf_pbl) >> 32)));
}
}
}
return 1;
}
/**
* nes_reg_mr
*/
static int nes_reg_mr(struct nes_device *nesdev, struct nes_pd *nespd,
u32 stag, u64 region_length, struct nes_root_vpbl *root_vpbl,
dma_addr_t single_buffer, u16 pbl_count_4k,
u16 residual_page_count_4k, int acc, u64 *iova_start,
u16 *actual_pbl_cnt, u8 *used_4k_pbls)
{
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
unsigned long flags;
int ret;
struct nes_adapter *nesadapter = nesdev->nesadapter;
uint pg_cnt = 0;
u16 pbl_count_256 = 0;
u16 pbl_count = 0;
u8 use_256_pbls = 0;
u8 use_4k_pbls = 0;
u16 use_two_level = (pbl_count_4k > 1) ? 1 : 0;
struct nes_root_vpbl new_root = { 0, NULL, NULL };
u32 opcode = 0;
u16 major_code;
/* Register the region with the adapter */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_MR, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
if (pbl_count_4k) {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
pg_cnt = ((pbl_count_4k - 1) * 512) + residual_page_count_4k;
pbl_count_256 = (pg_cnt + 31) / 32;
if (pg_cnt <= 32) {
if (pbl_count_256 <= nesadapter->free_256pbl)
use_256_pbls = 1;
else if (pbl_count_4k <= nesadapter->free_4kpbl)
use_4k_pbls = 1;
} else if (pg_cnt <= 2048) {
if (((pbl_count_4k + use_two_level) <= nesadapter->free_4kpbl) &&
(nesadapter->free_4kpbl > (nesadapter->max_4kpbl >> 1))) {
use_4k_pbls = 1;
} else if ((pbl_count_256 + 1) <= nesadapter->free_256pbl) {
use_256_pbls = 1;
use_two_level = 1;
} else if ((pbl_count_4k + use_two_level) <= nesadapter->free_4kpbl) {
use_4k_pbls = 1;
}
} else {
if ((pbl_count_4k + 1) <= nesadapter->free_4kpbl)
use_4k_pbls = 1;
}
if (use_256_pbls) {
pbl_count = pbl_count_256;
nesadapter->free_256pbl -= pbl_count + use_two_level;
} else if (use_4k_pbls) {
pbl_count = pbl_count_4k;
nesadapter->free_4kpbl -= pbl_count + use_two_level;
} else {
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
nes_debug(NES_DBG_MR, "Out of Pbls\n");
nes_free_cqp_request(nesdev, cqp_request);
return -ENOMEM;
}
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
}
if (use_256_pbls && use_two_level) {
if (root_256(nesdev, root_vpbl, &new_root, pbl_count_4k) == 1) {
if (new_root.pbl_pbase != 0)
root_vpbl = &new_root;
} else {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
nesadapter->free_256pbl += pbl_count_256 + use_two_level;
use_256_pbls = 0;
if (pbl_count_4k == 1)
use_two_level = 0;
pbl_count = pbl_count_4k;
if ((pbl_count_4k + use_two_level) <= nesadapter->free_4kpbl) {
nesadapter->free_4kpbl -= pbl_count + use_two_level;
use_4k_pbls = 1;
}
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
if (use_4k_pbls == 0)
return -ENOMEM;
}
}
opcode = NES_CQP_REGISTER_STAG | NES_CQP_STAG_RIGHTS_LOCAL_READ |
NES_CQP_STAG_VA_TO | NES_CQP_STAG_MR;
if (acc & IB_ACCESS_LOCAL_WRITE)
opcode |= NES_CQP_STAG_RIGHTS_LOCAL_WRITE;
if (acc & IB_ACCESS_REMOTE_WRITE)
opcode |= NES_CQP_STAG_RIGHTS_REMOTE_WRITE | NES_CQP_STAG_REM_ACC_EN;
if (acc & IB_ACCESS_REMOTE_READ)
opcode |= NES_CQP_STAG_RIGHTS_REMOTE_READ | NES_CQP_STAG_REM_ACC_EN;
if (acc & IB_ACCESS_MW_BIND)
opcode |= NES_CQP_STAG_RIGHTS_WINDOW_BIND | NES_CQP_STAG_REM_ACC_EN;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, opcode);
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_VA_LOW_IDX, *iova_start);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_LEN_LOW_IDX, region_length);
cqp_wqe->wqe_words[NES_CQP_STAG_WQE_LEN_HIGH_PD_IDX] =
cpu_to_le32((u32)(region_length >> 8) & 0xff000000);
cqp_wqe->wqe_words[NES_CQP_STAG_WQE_LEN_HIGH_PD_IDX] |=
cpu_to_le32(nespd->pd_id & 0x00007fff);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_STAG_IDX, stag);
if (pbl_count == 0) {
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PA_LOW_IDX, single_buffer);
} else {
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PA_LOW_IDX, root_vpbl->pbl_pbase);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PBL_BLK_COUNT_IDX, pbl_count);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_PBL_LEN_IDX, (pg_cnt * 8));
if (use_4k_pbls)
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] |= cpu_to_le32(NES_CQP_STAG_PBL_BLK_SIZE);
}
barrier();
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
ret = wait_event_timeout(cqp_request->waitq, (0 != cqp_request->request_done),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MR, "Register STag 0x%08X completed, wait_event_timeout ret = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X.\n",
stag, ret, cqp_request->major_code, cqp_request->minor_code);
major_code = cqp_request->major_code;
nes_put_cqp_request(nesdev, cqp_request);
if ((!ret || major_code) && pbl_count != 0) {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (use_256_pbls)
nesadapter->free_256pbl += pbl_count + use_two_level;
else if (use_4k_pbls)
nesadapter->free_4kpbl += pbl_count + use_two_level;
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
}
if (new_root.pbl_pbase)
pci_free_consistent(nesdev->pcidev, 512, new_root.pbl_vbase,
new_root.pbl_pbase);
if (!ret)
return -ETIME;
else if (major_code)
return -EIO;
*actual_pbl_cnt = pbl_count + use_two_level;
*used_4k_pbls = use_4k_pbls;
return 0;
}
/**
* nes_reg_phys_mr
*/
static struct ib_mr *nes_reg_phys_mr(struct ib_pd *ib_pd,
struct ib_phys_buf *buffer_list, int num_phys_buf, int acc,
u64 * iova_start)
{
u64 region_length;
struct nes_pd *nespd = to_nespd(ib_pd);
struct nes_vnic *nesvnic = to_nesvnic(ib_pd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_mr *nesmr;
struct ib_mr *ibmr;
struct nes_vpbl vpbl;
struct nes_root_vpbl root_vpbl;
u32 stag;
u32 i;
unsigned long mask;
u32 stag_index = 0;
u32 next_stag_index = 0;
u32 driver_key = 0;
u32 root_pbl_index = 0;
u32 cur_pbl_index = 0;
int err = 0;
int ret = 0;
u16 pbl_count = 0;
u8 single_page = 1;
u8 stag_key = 0;
region_length = 0;
vpbl.pbl_vbase = NULL;
root_vpbl.pbl_vbase = NULL;
root_vpbl.pbl_pbase = 0;
get_random_bytes(&next_stag_index, sizeof(next_stag_index));
stag_key = (u8)next_stag_index;
driver_key = 0;
next_stag_index >>= 8;
next_stag_index %= nesadapter->max_mr;
if (num_phys_buf > (1024*512)) {
return ERR_PTR(-E2BIG);
}
if ((buffer_list[0].addr ^ *iova_start) & ~PAGE_MASK)
return ERR_PTR(-EINVAL);
err = nes_alloc_resource(nesadapter, nesadapter->allocated_mrs, nesadapter->max_mr,
&stag_index, &next_stag_index, NES_RESOURCE_PHYS_MR);
if (err) {
return ERR_PTR(err);
}
nesmr = kzalloc(sizeof(*nesmr), GFP_KERNEL);
if (!nesmr) {
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
return ERR_PTR(-ENOMEM);
}
for (i = 0; i < num_phys_buf; i++) {
if ((i & 0x01FF) == 0) {
if (root_pbl_index == 1) {
/* Allocate the root PBL */
root_vpbl.pbl_vbase = pci_alloc_consistent(nesdev->pcidev, 8192,
&root_vpbl.pbl_pbase);
nes_debug(NES_DBG_MR, "Allocating root PBL, va = %p, pa = 0x%08X\n",
root_vpbl.pbl_vbase, (unsigned int)root_vpbl.pbl_pbase);
if (!root_vpbl.pbl_vbase) {
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase,
vpbl.pbl_pbase);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
kfree(nesmr);
return ERR_PTR(-ENOMEM);
}
root_vpbl.leaf_vpbl = kzalloc(sizeof(*root_vpbl.leaf_vpbl)*1024, GFP_KERNEL);
if (!root_vpbl.leaf_vpbl) {
pci_free_consistent(nesdev->pcidev, 8192, root_vpbl.pbl_vbase,
root_vpbl.pbl_pbase);
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase,
vpbl.pbl_pbase);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
kfree(nesmr);
return ERR_PTR(-ENOMEM);
}
root_vpbl.pbl_vbase[0].pa_low = cpu_to_le32((u32)vpbl.pbl_pbase);
root_vpbl.pbl_vbase[0].pa_high =
cpu_to_le32((u32)((((u64)vpbl.pbl_pbase) >> 32)));
root_vpbl.leaf_vpbl[0] = vpbl;
}
/* Allocate a 4K buffer for the PBL */
vpbl.pbl_vbase = pci_alloc_consistent(nesdev->pcidev, 4096,
&vpbl.pbl_pbase);
nes_debug(NES_DBG_MR, "Allocating leaf PBL, va = %p, pa = 0x%016lX\n",
vpbl.pbl_vbase, (unsigned long)vpbl.pbl_pbase);
if (!vpbl.pbl_vbase) {
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
ibmr = ERR_PTR(-ENOMEM);
kfree(nesmr);
goto reg_phys_err;
}
/* Fill in the root table */
if (1 <= root_pbl_index) {
root_vpbl.pbl_vbase[root_pbl_index].pa_low =
cpu_to_le32((u32)vpbl.pbl_pbase);
root_vpbl.pbl_vbase[root_pbl_index].pa_high =
cpu_to_le32((u32)((((u64)vpbl.pbl_pbase) >> 32)));
root_vpbl.leaf_vpbl[root_pbl_index] = vpbl;
}
root_pbl_index++;
cur_pbl_index = 0;
}
mask = !buffer_list[i].size;
if (i != 0)
mask |= buffer_list[i].addr;
if (i != num_phys_buf - 1)
mask |= buffer_list[i].addr + buffer_list[i].size;
if (mask & ~PAGE_MASK) {
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
nes_debug(NES_DBG_MR, "Invalid buffer addr or size\n");
ibmr = ERR_PTR(-EINVAL);
kfree(nesmr);
goto reg_phys_err;
}
region_length += buffer_list[i].size;
if ((i != 0) && (single_page)) {
if ((buffer_list[i-1].addr+PAGE_SIZE) != buffer_list[i].addr)
single_page = 0;
}
vpbl.pbl_vbase[cur_pbl_index].pa_low = cpu_to_le32((u32)buffer_list[i].addr & PAGE_MASK);
vpbl.pbl_vbase[cur_pbl_index++].pa_high =
cpu_to_le32((u32)((((u64)buffer_list[i].addr) >> 32)));
}
stag = stag_index << 8;
stag |= driver_key;
stag += (u32)stag_key;
nes_debug(NES_DBG_MR, "Registering STag 0x%08X, VA = 0x%016lX,"
" length = 0x%016lX, index = 0x%08X\n",
stag, (unsigned long)*iova_start, (unsigned long)region_length, stag_index);
/* Make the leaf PBL the root if only one PBL */
if (root_pbl_index == 1) {
root_vpbl.pbl_pbase = vpbl.pbl_pbase;
}
if (single_page) {
pbl_count = 0;
} else {
pbl_count = root_pbl_index;
}
ret = nes_reg_mr(nesdev, nespd, stag, region_length, &root_vpbl,
buffer_list[0].addr, pbl_count, (u16)cur_pbl_index, acc, iova_start,
&nesmr->pbls_used, &nesmr->pbl_4k);
if (ret == 0) {
nesmr->ibmr.rkey = stag;
nesmr->ibmr.lkey = stag;
nesmr->mode = IWNES_MEMREG_TYPE_MEM;
ibmr = &nesmr->ibmr;
} else {
kfree(nesmr);
ibmr = ERR_PTR(-ENOMEM);
}
reg_phys_err:
/* free the resources */
if (root_pbl_index == 1) {
/* single PBL case */
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase, vpbl.pbl_pbase);
} else {
for (i=0; i<root_pbl_index; i++) {
pci_free_consistent(nesdev->pcidev, 4096, root_vpbl.leaf_vpbl[i].pbl_vbase,
root_vpbl.leaf_vpbl[i].pbl_pbase);
}
kfree(root_vpbl.leaf_vpbl);
pci_free_consistent(nesdev->pcidev, 8192, root_vpbl.pbl_vbase,
root_vpbl.pbl_pbase);
}
return ibmr;
}
/**
* nes_get_dma_mr
*/
static struct ib_mr *nes_get_dma_mr(struct ib_pd *pd, int acc)
{
struct ib_phys_buf bl;
u64 kva = 0;
nes_debug(NES_DBG_MR, "\n");
bl.size = (u64)0xffffffffffULL;
bl.addr = 0;
return nes_reg_phys_mr(pd, &bl, 1, acc, &kva);
}
/**
* nes_reg_user_mr
*/
static struct ib_mr *nes_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
u64 virt, int acc, struct ib_udata *udata)
{
u64 iova_start;
__le64 *pbl;
u64 region_length;
dma_addr_t last_dma_addr = 0;
dma_addr_t first_dma_addr = 0;
struct nes_pd *nespd = to_nespd(pd);
struct nes_vnic *nesvnic = to_nesvnic(pd->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct ib_mr *ibmr = ERR_PTR(-EINVAL);
struct scatterlist *sg;
struct nes_ucontext *nes_ucontext;
struct nes_pbl *nespbl;
struct nes_mr *nesmr;
struct ib_umem *region;
struct nes_mem_reg_req req;
struct nes_vpbl vpbl;
struct nes_root_vpbl root_vpbl;
int entry, page_index;
int page_count = 0;
int err, pbl_depth = 0;
int chunk_pages;
int ret;
u32 stag;
u32 stag_index = 0;
u32 next_stag_index;
u32 driver_key;
u32 root_pbl_index = 0;
u32 cur_pbl_index = 0;
u32 skip_pages;
u16 pbl_count;
u8 single_page = 1;
u8 stag_key;
int first_page = 1;
region = ib_umem_get(pd->uobject->context, start, length, acc, 0);
if (IS_ERR(region)) {
return (struct ib_mr *)region;
}
nes_debug(NES_DBG_MR, "User base = 0x%lX, Virt base = 0x%lX, length = %u,"
" offset = %u, page size = %u.\n",
(unsigned long int)start, (unsigned long int)virt, (u32)length,
ib_umem_offset(region), region->page_size);
skip_pages = ((u32)ib_umem_offset(region)) >> 12;
if (ib_copy_from_udata(&req, udata, sizeof(req))) {
ib_umem_release(region);
return ERR_PTR(-EFAULT);
}
nes_debug(NES_DBG_MR, "Memory Registration type = %08X.\n", req.reg_type);
switch (req.reg_type) {
case IWNES_MEMREG_TYPE_MEM:
pbl_depth = 0;
region_length = 0;
vpbl.pbl_vbase = NULL;
root_vpbl.pbl_vbase = NULL;
root_vpbl.pbl_pbase = 0;
get_random_bytes(&next_stag_index, sizeof(next_stag_index));
stag_key = (u8)next_stag_index;
driver_key = next_stag_index & 0x70000000;
next_stag_index >>= 8;
next_stag_index %= nesadapter->max_mr;
err = nes_alloc_resource(nesadapter, nesadapter->allocated_mrs,
nesadapter->max_mr, &stag_index, &next_stag_index, NES_RESOURCE_USER_MR);
if (err) {
ib_umem_release(region);
return ERR_PTR(err);
}
nesmr = kzalloc(sizeof(*nesmr), GFP_KERNEL);
if (!nesmr) {
ib_umem_release(region);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
return ERR_PTR(-ENOMEM);
}
nesmr->region = region;
for_each_sg(region->sg_head.sgl, sg, region->nmap, entry) {
if (sg_dma_address(sg) & ~PAGE_MASK) {
ib_umem_release(region);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
nes_debug(NES_DBG_MR, "Unaligned Memory Buffer: 0x%x\n",
(unsigned int) sg_dma_address(sg));
ibmr = ERR_PTR(-EINVAL);
kfree(nesmr);
goto reg_user_mr_err;
}
if (!sg_dma_len(sg)) {
ib_umem_release(region);
nes_free_resource(nesadapter, nesadapter->allocated_mrs,
stag_index);
nes_debug(NES_DBG_MR, "Invalid Buffer Size\n");
ibmr = ERR_PTR(-EINVAL);
kfree(nesmr);
goto reg_user_mr_err;
}
region_length += sg_dma_len(sg);
chunk_pages = sg_dma_len(sg) >> 12;
region_length -= skip_pages << 12;
for (page_index = skip_pages; page_index < chunk_pages; page_index++) {
skip_pages = 0;
if ((page_count != 0) && (page_count << 12) - (ib_umem_offset(region) & (4096 - 1)) >= region->length)
goto enough_pages;
if ((page_count&0x01FF) == 0) {
if (page_count >= 1024 * 512) {
ib_umem_release(region);
nes_free_resource(nesadapter,
nesadapter->allocated_mrs, stag_index);
kfree(nesmr);
ibmr = ERR_PTR(-E2BIG);
goto reg_user_mr_err;
}
if (root_pbl_index == 1) {
root_vpbl.pbl_vbase = pci_alloc_consistent(nesdev->pcidev,
8192, &root_vpbl.pbl_pbase);
nes_debug(NES_DBG_MR, "Allocating root PBL, va = %p, pa = 0x%08X\n",
root_vpbl.pbl_vbase, (unsigned int)root_vpbl.pbl_pbase);
if (!root_vpbl.pbl_vbase) {
ib_umem_release(region);
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase,
vpbl.pbl_pbase);
nes_free_resource(nesadapter, nesadapter->allocated_mrs,
stag_index);
kfree(nesmr);
ibmr = ERR_PTR(-ENOMEM);
goto reg_user_mr_err;
}
root_vpbl.leaf_vpbl = kzalloc(sizeof(*root_vpbl.leaf_vpbl)*1024,
GFP_KERNEL);
if (!root_vpbl.leaf_vpbl) {
ib_umem_release(region);
pci_free_consistent(nesdev->pcidev, 8192, root_vpbl.pbl_vbase,
root_vpbl.pbl_pbase);
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase,
vpbl.pbl_pbase);
nes_free_resource(nesadapter, nesadapter->allocated_mrs,
stag_index);
kfree(nesmr);
ibmr = ERR_PTR(-ENOMEM);
goto reg_user_mr_err;
}
root_vpbl.pbl_vbase[0].pa_low =
cpu_to_le32((u32)vpbl.pbl_pbase);
root_vpbl.pbl_vbase[0].pa_high =
cpu_to_le32((u32)((((u64)vpbl.pbl_pbase) >> 32)));
root_vpbl.leaf_vpbl[0] = vpbl;
}
vpbl.pbl_vbase = pci_alloc_consistent(nesdev->pcidev, 4096,
&vpbl.pbl_pbase);
nes_debug(NES_DBG_MR, "Allocating leaf PBL, va = %p, pa = 0x%08X\n",
vpbl.pbl_vbase, (unsigned int)vpbl.pbl_pbase);
if (!vpbl.pbl_vbase) {
ib_umem_release(region);
nes_free_resource(nesadapter, nesadapter->allocated_mrs, stag_index);
ibmr = ERR_PTR(-ENOMEM);
kfree(nesmr);
goto reg_user_mr_err;
}
if (1 <= root_pbl_index) {
root_vpbl.pbl_vbase[root_pbl_index].pa_low =
cpu_to_le32((u32)vpbl.pbl_pbase);
root_vpbl.pbl_vbase[root_pbl_index].pa_high =
cpu_to_le32((u32)((((u64)vpbl.pbl_pbase)>>32)));
root_vpbl.leaf_vpbl[root_pbl_index] = vpbl;
}
root_pbl_index++;
cur_pbl_index = 0;
}
if (single_page) {
if (page_count != 0) {
if ((last_dma_addr+4096) !=
(sg_dma_address(sg)+
(page_index*4096)))
single_page = 0;
last_dma_addr = sg_dma_address(sg)+
(page_index*4096);
} else {
first_dma_addr = sg_dma_address(sg)+
(page_index*4096);
last_dma_addr = first_dma_addr;
}
}
vpbl.pbl_vbase[cur_pbl_index].pa_low =
cpu_to_le32((u32)(sg_dma_address(sg)+
(page_index*4096)));
vpbl.pbl_vbase[cur_pbl_index].pa_high =
cpu_to_le32((u32)((((u64)(sg_dma_address(sg)+
(page_index*4096))) >> 32)));
cur_pbl_index++;
page_count++;
}
}
enough_pages:
nes_debug(NES_DBG_MR, "calculating stag, stag_index=0x%08x, driver_key=0x%08x,"
" stag_key=0x%08x\n",
stag_index, driver_key, stag_key);
stag = stag_index << 8;
stag |= driver_key;
stag += (u32)stag_key;
iova_start = virt;
/* Make the leaf PBL the root if only one PBL */
if (root_pbl_index == 1) {
root_vpbl.pbl_pbase = vpbl.pbl_pbase;
}
if (single_page) {
pbl_count = 0;
} else {
pbl_count = root_pbl_index;
first_dma_addr = 0;
}
nes_debug(NES_DBG_MR, "Registering STag 0x%08X, VA = 0x%08X, length = 0x%08X,"
" index = 0x%08X, region->length=0x%08llx, pbl_count = %u\n",
stag, (unsigned int)iova_start,
(unsigned int)region_length, stag_index,
(unsigned long long)region->length, pbl_count);
ret = nes_reg_mr(nesdev, nespd, stag, region->length, &root_vpbl,
first_dma_addr, pbl_count, (u16)cur_pbl_index, acc,
&iova_start, &nesmr->pbls_used, &nesmr->pbl_4k);
nes_debug(NES_DBG_MR, "ret=%d\n", ret);
if (ret == 0) {
nesmr->ibmr.rkey = stag;
nesmr->ibmr.lkey = stag;
nesmr->mode = IWNES_MEMREG_TYPE_MEM;
ibmr = &nesmr->ibmr;
} else {
ib_umem_release(region);
kfree(nesmr);
ibmr = ERR_PTR(-ENOMEM);
}
reg_user_mr_err:
/* free the resources */
if (root_pbl_index == 1) {
pci_free_consistent(nesdev->pcidev, 4096, vpbl.pbl_vbase,
vpbl.pbl_pbase);
} else {
for (page_index=0; page_index<root_pbl_index; page_index++) {
pci_free_consistent(nesdev->pcidev, 4096,
root_vpbl.leaf_vpbl[page_index].pbl_vbase,
root_vpbl.leaf_vpbl[page_index].pbl_pbase);
}
kfree(root_vpbl.leaf_vpbl);
pci_free_consistent(nesdev->pcidev, 8192, root_vpbl.pbl_vbase,
root_vpbl.pbl_pbase);
}
nes_debug(NES_DBG_MR, "Leaving, ibmr=%p", ibmr);
return ibmr;
case IWNES_MEMREG_TYPE_QP:
case IWNES_MEMREG_TYPE_CQ:
if (!region->length) {
nes_debug(NES_DBG_MR, "Unable to register zero length region for CQ\n");
ib_umem_release(region);
return ERR_PTR(-EINVAL);
}
nespbl = kzalloc(sizeof(*nespbl), GFP_KERNEL);
if (!nespbl) {
nes_debug(NES_DBG_MR, "Unable to allocate PBL\n");
ib_umem_release(region);
return ERR_PTR(-ENOMEM);
}
nesmr = kzalloc(sizeof(*nesmr), GFP_KERNEL);
if (!nesmr) {
ib_umem_release(region);
kfree(nespbl);
nes_debug(NES_DBG_MR, "Unable to allocate nesmr\n");
return ERR_PTR(-ENOMEM);
}
nesmr->region = region;
nes_ucontext = to_nesucontext(pd->uobject->context);
pbl_depth = region->length >> 12;
pbl_depth += (region->length & (4096-1)) ? 1 : 0;
nespbl->pbl_size = pbl_depth*sizeof(u64);
if (req.reg_type == IWNES_MEMREG_TYPE_QP) {
nes_debug(NES_DBG_MR, "Attempting to allocate QP PBL memory");
} else {
nes_debug(NES_DBG_MR, "Attempting to allocate CP PBL memory");
}
nes_debug(NES_DBG_MR, " %u bytes, %u entries.\n",
nespbl->pbl_size, pbl_depth);
pbl = pci_alloc_consistent(nesdev->pcidev, nespbl->pbl_size,
&nespbl->pbl_pbase);
if (!pbl) {
ib_umem_release(region);
kfree(nesmr);
kfree(nespbl);
nes_debug(NES_DBG_MR, "Unable to allocate PBL memory\n");
return ERR_PTR(-ENOMEM);
}
nespbl->pbl_vbase = (u64 *)pbl;
nespbl->user_base = start;
nes_debug(NES_DBG_MR, "Allocated PBL memory, %u bytes, pbl_pbase=%lx,"
" pbl_vbase=%p user_base=0x%lx\n",
nespbl->pbl_size, (unsigned long) nespbl->pbl_pbase,
(void *) nespbl->pbl_vbase, nespbl->user_base);
for_each_sg(region->sg_head.sgl, sg, region->nmap, entry) {
chunk_pages = sg_dma_len(sg) >> 12;
chunk_pages += (sg_dma_len(sg) & (4096-1)) ? 1 : 0;
if (first_page) {
nespbl->page = sg_page(sg);
first_page = 0;
}
for (page_index = 0; page_index < chunk_pages; page_index++) {
((__le32 *)pbl)[0] = cpu_to_le32((u32)
(sg_dma_address(sg)+
(page_index*4096)));
((__le32 *)pbl)[1] = cpu_to_le32(((u64)
(sg_dma_address(sg)+
(page_index*4096)))>>32);
nes_debug(NES_DBG_MR, "pbl=%p, *pbl=0x%016llx, 0x%08x%08x\n", pbl,
(unsigned long long)*pbl,
le32_to_cpu(((__le32 *)pbl)[1]), le32_to_cpu(((__le32 *)pbl)[0]));
pbl++;
}
}
if (req.reg_type == IWNES_MEMREG_TYPE_QP) {
list_add_tail(&nespbl->list, &nes_ucontext->qp_reg_mem_list);
} else {
list_add_tail(&nespbl->list, &nes_ucontext->cq_reg_mem_list);
}
nesmr->ibmr.rkey = -1;
nesmr->ibmr.lkey = -1;
nesmr->mode = req.reg_type;
return &nesmr->ibmr;
}
ib_umem_release(region);
return ERR_PTR(-ENOSYS);
}
/**
* nes_dereg_mr
*/
static int nes_dereg_mr(struct ib_mr *ib_mr)
{
struct nes_mr *nesmr = to_nesmr(ib_mr);
struct nes_vnic *nesvnic = to_nesvnic(ib_mr->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
unsigned long flags;
int ret;
u16 major_code;
u16 minor_code;
if (nesmr->region) {
ib_umem_release(nesmr->region);
}
if (nesmr->mode != IWNES_MEMREG_TYPE_MEM) {
kfree(nesmr);
return 0;
}
/* Deallocate the region with the adapter */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_MR, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
NES_CQP_DEALLOCATE_STAG | NES_CQP_STAG_VA_TO |
NES_CQP_STAG_DEALLOC_PBLS | NES_CQP_STAG_MR);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_STAG_WQE_STAG_IDX, ib_mr->rkey);
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
nes_debug(NES_DBG_MR, "Waiting for deallocate STag 0x%08X completed\n", ib_mr->rkey);
ret = wait_event_timeout(cqp_request->waitq, (cqp_request->request_done != 0),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MR, "Deallocate STag 0x%08X completed, wait_event_timeout ret = %u,"
" CQP Major:Minor codes = 0x%04X:0x%04X\n",
ib_mr->rkey, ret, cqp_request->major_code, cqp_request->minor_code);
major_code = cqp_request->major_code;
minor_code = cqp_request->minor_code;
nes_put_cqp_request(nesdev, cqp_request);
if (!ret) {
nes_debug(NES_DBG_MR, "Timeout waiting to destroy STag,"
" ib_mr=%p, rkey = 0x%08X\n",
ib_mr, ib_mr->rkey);
return -ETIME;
} else if (major_code) {
nes_debug(NES_DBG_MR, "Error (0x%04X:0x%04X) while attempting"
" to destroy STag, ib_mr=%p, rkey = 0x%08X\n",
major_code, minor_code, ib_mr, ib_mr->rkey);
return -EIO;
}
if (nesmr->pbls_used != 0) {
spin_lock_irqsave(&nesadapter->pbl_lock, flags);
if (nesmr->pbl_4k) {
nesadapter->free_4kpbl += nesmr->pbls_used;
if (nesadapter->free_4kpbl > nesadapter->max_4kpbl)
printk(KERN_ERR PFX "free 4KB PBLs(%u) has "
"exceeded the max(%u)\n",
nesadapter->free_4kpbl,
nesadapter->max_4kpbl);
} else {
nesadapter->free_256pbl += nesmr->pbls_used;
if (nesadapter->free_256pbl > nesadapter->max_256pbl)
printk(KERN_ERR PFX "free 256B PBLs(%u) has "
"exceeded the max(%u)\n",
nesadapter->free_256pbl,
nesadapter->max_256pbl);
}
spin_unlock_irqrestore(&nesadapter->pbl_lock, flags);
}
nes_free_resource(nesadapter, nesadapter->allocated_mrs,
(ib_mr->rkey & 0x0fffff00) >> 8);
kfree(nesmr);
return 0;
}
/**
* show_rev
*/
static ssize_t show_rev(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct nes_ib_device *nesibdev =
container_of(dev, struct nes_ib_device, ibdev.dev);
struct nes_vnic *nesvnic = nesibdev->nesvnic;
nes_debug(NES_DBG_INIT, "\n");
return sprintf(buf, "%x\n", nesvnic->nesdev->nesadapter->hw_rev);
}
/**
* show_fw_ver
*/
static ssize_t show_fw_ver(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct nes_ib_device *nesibdev =
container_of(dev, struct nes_ib_device, ibdev.dev);
struct nes_vnic *nesvnic = nesibdev->nesvnic;
nes_debug(NES_DBG_INIT, "\n");
return sprintf(buf, "%u.%u\n",
(nesvnic->nesdev->nesadapter->firmware_version >> 16),
(nesvnic->nesdev->nesadapter->firmware_version & 0x000000ff));
}
/**
* show_hca
*/
static ssize_t show_hca(struct device *dev, struct device_attribute *attr,
char *buf)
{
nes_debug(NES_DBG_INIT, "\n");
return sprintf(buf, "NES020\n");
}
/**
* show_board
*/
static ssize_t show_board(struct device *dev, struct device_attribute *attr,
char *buf)
{
nes_debug(NES_DBG_INIT, "\n");
return sprintf(buf, "%.*s\n", 32, "NES020 Board ID");
}
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(fw_ver, S_IRUGO, show_fw_ver, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_board, NULL);
static struct device_attribute *nes_dev_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_fw_ver,
&dev_attr_hca_type,
&dev_attr_board_id
};
/**
* nes_query_qp
*/
static int nes_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_qp_init_attr *init_attr)
{
struct nes_qp *nesqp = to_nesqp(ibqp);
nes_debug(NES_DBG_QP, "\n");
attr->qp_access_flags = 0;
attr->cap.max_send_wr = nesqp->hwqp.sq_size;
attr->cap.max_recv_wr = nesqp->hwqp.rq_size;
attr->cap.max_recv_sge = 1;
if (nes_drv_opt & NES_DRV_OPT_NO_INLINE_DATA)
attr->cap.max_inline_data = 0;
else
attr->cap.max_inline_data = 64;
init_attr->event_handler = nesqp->ibqp.event_handler;
init_attr->qp_context = nesqp->ibqp.qp_context;
init_attr->send_cq = nesqp->ibqp.send_cq;
init_attr->recv_cq = nesqp->ibqp.recv_cq;
init_attr->srq = nesqp->ibqp.srq;
init_attr->cap = attr->cap;
return 0;
}
/**
* nes_hw_modify_qp
*/
int nes_hw_modify_qp(struct nes_device *nesdev, struct nes_qp *nesqp,
u32 next_iwarp_state, u32 termlen, u32 wait_completion)
{
struct nes_hw_cqp_wqe *cqp_wqe;
/* struct iw_cm_id *cm_id = nesqp->cm_id; */
/* struct iw_cm_event cm_event; */
struct nes_cqp_request *cqp_request;
int ret;
u16 major_code;
nes_debug(NES_DBG_MOD_QP, "QP%u, refcount=%d\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount));
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_MOD_QP, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
if (wait_completion) {
cqp_request->waiting = 1;
} else {
cqp_request->waiting = 0;
}
cqp_wqe = &cqp_request->cqp_wqe;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
NES_CQP_MODIFY_QP | NES_CQP_QP_TYPE_IWARP | next_iwarp_state);
nes_debug(NES_DBG_MOD_QP, "using next_iwarp_state=%08x, wqe_words=%08x\n",
next_iwarp_state, le32_to_cpu(cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX]));
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX, nesqp->hwqp.qp_id);
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, (u64)nesqp->nesqp_context_pbase);
/* If sending a terminate message, fill in the length (in words) */
if (((next_iwarp_state & NES_CQP_QP_IWARP_STATE_MASK) == NES_CQP_QP_IWARP_STATE_TERMINATE) &&
!(next_iwarp_state & NES_CQP_QP_TERM_DONT_SEND_TERM_MSG)) {
termlen = ((termlen + 3) >> 2) << NES_CQP_OP_TERMLEN_SHIFT;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_NEW_MSS_IDX, termlen);
}
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
/* Wait for CQP */
if (wait_completion) {
/* nes_debug(NES_DBG_MOD_QP, "Waiting for modify iWARP QP%u to complete.\n",
nesqp->hwqp.qp_id); */
ret = wait_event_timeout(cqp_request->waitq, (cqp_request->request_done != 0),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_MOD_QP, "Modify iwarp QP%u completed, wait_event_timeout ret=%u, "
"CQP Major:Minor codes = 0x%04X:0x%04X.\n",
nesqp->hwqp.qp_id, ret, cqp_request->major_code, cqp_request->minor_code);
major_code = cqp_request->major_code;
if (major_code) {
nes_debug(NES_DBG_MOD_QP, "Modify iwarp QP%u failed"
"CQP Major:Minor codes = 0x%04X:0x%04X, intended next state = 0x%08X.\n",
nesqp->hwqp.qp_id, cqp_request->major_code,
cqp_request->minor_code, next_iwarp_state);
}
nes_put_cqp_request(nesdev, cqp_request);
if (!ret)
return -ETIME;
else if (major_code)
return -EIO;
else
return 0;
} else {
return 0;
}
}
/**
* nes_modify_qp
*/
int nes_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_udata *udata)
{
struct nes_qp *nesqp = to_nesqp(ibqp);
struct nes_vnic *nesvnic = to_nesvnic(ibqp->device);
struct nes_device *nesdev = nesvnic->nesdev;
/* u32 cqp_head; */
/* u32 counter; */
u32 next_iwarp_state = 0;
int err;
unsigned long qplockflags;
int ret;
u16 original_last_aeq;
u8 issue_modify_qp = 0;
u8 dont_wait = 0;
nes_debug(NES_DBG_MOD_QP, "QP%u: QP State=%u, cur QP State=%u,"
" iwarp_state=0x%X, refcount=%d\n",
nesqp->hwqp.qp_id, attr->qp_state, nesqp->ibqp_state,
nesqp->iwarp_state, atomic_read(&nesqp->refcount));
spin_lock_irqsave(&nesqp->lock, qplockflags);
nes_debug(NES_DBG_MOD_QP, "QP%u: hw_iwarp_state=0x%X, hw_tcp_state=0x%X,"
" QP Access Flags=0x%X, attr_mask = 0x%0x\n",
nesqp->hwqp.qp_id, nesqp->hw_iwarp_state,
nesqp->hw_tcp_state, attr->qp_access_flags, attr_mask);
if (attr_mask & IB_QP_STATE) {
switch (attr->qp_state) {
case IB_QPS_INIT:
nes_debug(NES_DBG_MOD_QP, "QP%u: new state = init\n",
nesqp->hwqp.qp_id);
if (nesqp->iwarp_state > (u32)NES_CQP_QP_IWARP_STATE_IDLE) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
next_iwarp_state = NES_CQP_QP_IWARP_STATE_IDLE;
issue_modify_qp = 1;
break;
case IB_QPS_RTR:
nes_debug(NES_DBG_MOD_QP, "QP%u: new state = rtr\n",
nesqp->hwqp.qp_id);
if (nesqp->iwarp_state>(u32)NES_CQP_QP_IWARP_STATE_IDLE) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
next_iwarp_state = NES_CQP_QP_IWARP_STATE_IDLE;
issue_modify_qp = 1;
break;
case IB_QPS_RTS:
nes_debug(NES_DBG_MOD_QP, "QP%u: new state = rts\n",
nesqp->hwqp.qp_id);
if (nesqp->iwarp_state>(u32)NES_CQP_QP_IWARP_STATE_RTS) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
if (nesqp->cm_id == NULL) {
nes_debug(NES_DBG_MOD_QP, "QP%u: Failing attempt to move QP to RTS without a CM_ID. \n",
nesqp->hwqp.qp_id );
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
next_iwarp_state = NES_CQP_QP_IWARP_STATE_RTS;
if (nesqp->iwarp_state != NES_CQP_QP_IWARP_STATE_RTS)
next_iwarp_state |= NES_CQP_QP_CONTEXT_VALID |
NES_CQP_QP_ARP_VALID | NES_CQP_QP_ORD_VALID;
issue_modify_qp = 1;
nesqp->hw_tcp_state = NES_AEQE_TCP_STATE_ESTABLISHED;
nesqp->hw_iwarp_state = NES_AEQE_IWARP_STATE_RTS;
nesqp->hte_added = 1;
break;
case IB_QPS_SQD:
issue_modify_qp = 1;
nes_debug(NES_DBG_MOD_QP, "QP%u: new state=closing. SQ head=%u, SQ tail=%u\n",
nesqp->hwqp.qp_id, nesqp->hwqp.sq_head, nesqp->hwqp.sq_tail);
if (nesqp->iwarp_state == (u32)NES_CQP_QP_IWARP_STATE_CLOSING) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return 0;
} else {
if (nesqp->iwarp_state > (u32)NES_CQP_QP_IWARP_STATE_CLOSING) {
nes_debug(NES_DBG_MOD_QP, "QP%u: State change to closing"
" ignored due to current iWARP state\n",
nesqp->hwqp.qp_id);
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
if (nesqp->hw_iwarp_state != NES_AEQE_IWARP_STATE_RTS) {
nes_debug(NES_DBG_MOD_QP, "QP%u: State change to closing"
" already done based on hw state.\n",
nesqp->hwqp.qp_id);
issue_modify_qp = 0;
}
switch (nesqp->hw_iwarp_state) {
case NES_AEQE_IWARP_STATE_CLOSING:
next_iwarp_state = NES_CQP_QP_IWARP_STATE_CLOSING;
break;
case NES_AEQE_IWARP_STATE_TERMINATE:
next_iwarp_state = NES_CQP_QP_IWARP_STATE_TERMINATE;
break;
case NES_AEQE_IWARP_STATE_ERROR:
next_iwarp_state = NES_CQP_QP_IWARP_STATE_ERROR;
break;
default:
next_iwarp_state = NES_CQP_QP_IWARP_STATE_CLOSING;
nesqp->hw_iwarp_state = NES_AEQE_IWARP_STATE_CLOSING;
break;
}
}
break;
case IB_QPS_SQE:
nes_debug(NES_DBG_MOD_QP, "QP%u: new state = terminate\n",
nesqp->hwqp.qp_id);
if (nesqp->iwarp_state>=(u32)NES_CQP_QP_IWARP_STATE_TERMINATE) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
/* next_iwarp_state = (NES_CQP_QP_IWARP_STATE_TERMINATE | 0x02000000); */
next_iwarp_state = NES_CQP_QP_IWARP_STATE_TERMINATE;
nesqp->hw_iwarp_state = NES_AEQE_IWARP_STATE_TERMINATE;
issue_modify_qp = 1;
break;
case IB_QPS_ERR:
case IB_QPS_RESET:
if (nesqp->iwarp_state == (u32)NES_CQP_QP_IWARP_STATE_ERROR) {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
}
nes_debug(NES_DBG_MOD_QP, "QP%u: new state = error\n",
nesqp->hwqp.qp_id);
if (nesqp->term_flags)
del_timer(&nesqp->terminate_timer);
next_iwarp_state = NES_CQP_QP_IWARP_STATE_ERROR;
/* next_iwarp_state = (NES_CQP_QP_IWARP_STATE_TERMINATE | 0x02000000); */
if (nesqp->hte_added) {
nes_debug(NES_DBG_MOD_QP, "set CQP_QP_DEL_HTE\n");
next_iwarp_state |= NES_CQP_QP_DEL_HTE;
nesqp->hte_added = 0;
}
if ((nesqp->hw_tcp_state > NES_AEQE_TCP_STATE_CLOSED) &&
(nesdev->iw_status) &&
(nesqp->hw_tcp_state != NES_AEQE_TCP_STATE_TIME_WAIT)) {
next_iwarp_state |= NES_CQP_QP_RESET;
} else {
nes_debug(NES_DBG_MOD_QP, "QP%u NOT setting NES_CQP_QP_RESET since TCP state = %u\n",
nesqp->hwqp.qp_id, nesqp->hw_tcp_state);
dont_wait = 1;
}
issue_modify_qp = 1;
nesqp->hw_iwarp_state = NES_AEQE_IWARP_STATE_ERROR;
break;
default:
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
return -EINVAL;
break;
}
nesqp->ibqp_state = attr->qp_state;
nesqp->iwarp_state = next_iwarp_state & NES_CQP_QP_IWARP_STATE_MASK;
nes_debug(NES_DBG_MOD_QP, "Change nesqp->iwarp_state=%08x\n",
nesqp->iwarp_state);
}
if (attr_mask & IB_QP_ACCESS_FLAGS) {
if (attr->qp_access_flags & IB_ACCESS_LOCAL_WRITE) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_RDMA_WRITE_EN |
NES_QPCONTEXT_MISC_RDMA_READ_EN);
issue_modify_qp = 1;
}
if (attr->qp_access_flags & IB_ACCESS_REMOTE_WRITE) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_RDMA_WRITE_EN);
issue_modify_qp = 1;
}
if (attr->qp_access_flags & IB_ACCESS_REMOTE_READ) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_RDMA_READ_EN);
issue_modify_qp = 1;
}
if (attr->qp_access_flags & IB_ACCESS_MW_BIND) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_WBIND_EN);
issue_modify_qp = 1;
}
if (nesqp->user_mode) {
nesqp->nesqp_context->misc |= cpu_to_le32(NES_QPCONTEXT_MISC_RDMA_WRITE_EN |
NES_QPCONTEXT_MISC_RDMA_READ_EN);
issue_modify_qp = 1;
}
}
original_last_aeq = nesqp->last_aeq;
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
nes_debug(NES_DBG_MOD_QP, "issue_modify_qp=%u\n", issue_modify_qp);
ret = 0;
if (issue_modify_qp) {
nes_debug(NES_DBG_MOD_QP, "call nes_hw_modify_qp\n");
ret = nes_hw_modify_qp(nesdev, nesqp, next_iwarp_state, 0, 1);
if (ret)
nes_debug(NES_DBG_MOD_QP, "nes_hw_modify_qp (next_iwarp_state = 0x%08X)"
" failed for QP%u.\n",
next_iwarp_state, nesqp->hwqp.qp_id);
}
if ((issue_modify_qp) && (nesqp->ibqp_state > IB_QPS_RTS)) {
nes_debug(NES_DBG_MOD_QP, "QP%u Issued ModifyQP refcount (%d),"
" original_last_aeq = 0x%04X. last_aeq = 0x%04X.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
if (!ret || original_last_aeq != NES_AEQE_AEID_RDMAP_ROE_BAD_LLP_CLOSE) {
if (dont_wait) {
if (nesqp->cm_id && nesqp->hw_tcp_state != 0) {
nes_debug(NES_DBG_MOD_QP, "QP%u Queuing fake disconnect for QP refcount (%d),"
" original_last_aeq = 0x%04X. last_aeq = 0x%04X.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
/* this one is for the cm_disconnect thread */
spin_lock_irqsave(&nesqp->lock, qplockflags);
nesqp->hw_tcp_state = NES_AEQE_TCP_STATE_CLOSED;
nesqp->last_aeq = NES_AEQE_AEID_RESET_SENT;
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
nes_cm_disconn(nesqp);
} else {
nes_debug(NES_DBG_MOD_QP, "QP%u No fake disconnect, QP refcount=%d\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount));
}
} else {
spin_lock_irqsave(&nesqp->lock, qplockflags);
if (nesqp->cm_id) {
/* These two are for the timer thread */
if (atomic_inc_return(&nesqp->close_timer_started) == 1) {
nesqp->cm_id->add_ref(nesqp->cm_id);
nes_debug(NES_DBG_MOD_QP, "QP%u Not decrementing QP refcount (%d),"
" need ae to finish up, original_last_aeq = 0x%04X."
" last_aeq = 0x%04X, scheduling timer.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
schedule_nes_timer(nesqp->cm_node, (struct sk_buff *) nesqp, NES_TIMER_TYPE_CLOSE, 1, 0);
}
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
} else {
spin_unlock_irqrestore(&nesqp->lock, qplockflags);
nes_debug(NES_DBG_MOD_QP, "QP%u Not decrementing QP refcount (%d),"
" need ae to finish up, original_last_aeq = 0x%04X."
" last_aeq = 0x%04X.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
}
}
} else {
nes_debug(NES_DBG_MOD_QP, "QP%u Decrementing QP refcount (%d), No ae to finish up,"
" original_last_aeq = 0x%04X. last_aeq = 0x%04X.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
}
} else {
nes_debug(NES_DBG_MOD_QP, "QP%u Decrementing QP refcount (%d), No ae to finish up,"
" original_last_aeq = 0x%04X. last_aeq = 0x%04X.\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
original_last_aeq, nesqp->last_aeq);
}
err = 0;
nes_debug(NES_DBG_MOD_QP, "QP%u Leaving, refcount=%d\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount));
return err;
}
/**
* nes_muticast_attach
*/
static int nes_multicast_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
nes_debug(NES_DBG_INIT, "\n");
return -ENOSYS;
}
/**
* nes_multicast_detach
*/
static int nes_multicast_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
nes_debug(NES_DBG_INIT, "\n");
return -ENOSYS;
}
/**
* nes_process_mad
*/
static int nes_process_mad(struct ib_device *ibdev, int mad_flags,
u8 port_num, const struct ib_wc *in_wc, const struct ib_grh *in_grh,
const struct ib_mad_hdr *in, size_t in_mad_size,
struct ib_mad_hdr *out, size_t *out_mad_size,
u16 *out_mad_pkey_index)
{
nes_debug(NES_DBG_INIT, "\n");
return -ENOSYS;
}
static inline void
fill_wqe_sg_send(struct nes_hw_qp_wqe *wqe, struct ib_send_wr *ib_wr, u32 uselkey)
{
int sge_index;
int total_payload_length = 0;
for (sge_index = 0; sge_index < ib_wr->num_sge; sge_index++) {
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_FRAG0_LOW_IDX+(sge_index*4),
ib_wr->sg_list[sge_index].addr);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_LENGTH0_IDX + (sge_index*4),
ib_wr->sg_list[sge_index].length);
if (uselkey)
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_STAG0_IDX + (sge_index*4),
(ib_wr->sg_list[sge_index].lkey));
else
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_STAG0_IDX + (sge_index*4), 0);
total_payload_length += ib_wr->sg_list[sge_index].length;
}
nes_debug(NES_DBG_IW_TX, "UC UC UC, sending total_payload_length=%u \n",
total_payload_length);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_TOTAL_PAYLOAD_IDX,
total_payload_length);
}
/**
* nes_post_send
*/
static int nes_post_send(struct ib_qp *ibqp, struct ib_send_wr *ib_wr,
struct ib_send_wr **bad_wr)
{
u64 u64temp;
unsigned long flags = 0;
struct nes_vnic *nesvnic = to_nesvnic(ibqp->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_qp *nesqp = to_nesqp(ibqp);
struct nes_hw_qp_wqe *wqe;
int err = 0;
u32 qsize = nesqp->hwqp.sq_size;
u32 head;
u32 wqe_misc = 0;
u32 wqe_count = 0;
u32 counter;
if (nesqp->ibqp_state > IB_QPS_RTS) {
err = -EINVAL;
goto out;
}
spin_lock_irqsave(&nesqp->lock, flags);
head = nesqp->hwqp.sq_head;
while (ib_wr) {
/* Check for QP error */
if (nesqp->term_flags) {
err = -EINVAL;
break;
}
/* Check for SQ overflow */
if (((head + (2 * qsize) - nesqp->hwqp.sq_tail) % qsize) == (qsize - 1)) {
err = -ENOMEM;
break;
}
wqe = &nesqp->hwqp.sq_vbase[head];
/* nes_debug(NES_DBG_IW_TX, "processing sq wqe for QP%u at %p, head = %u.\n",
nesqp->hwqp.qp_id, wqe, head); */
nes_fill_init_qp_wqe(wqe, nesqp, head);
u64temp = (u64)(ib_wr->wr_id);
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_COMP_SCRATCH_LOW_IDX,
u64temp);
switch (ib_wr->opcode) {
case IB_WR_SEND:
case IB_WR_SEND_WITH_INV:
if (IB_WR_SEND == ib_wr->opcode) {
if (ib_wr->send_flags & IB_SEND_SOLICITED)
wqe_misc = NES_IWARP_SQ_OP_SENDSE;
else
wqe_misc = NES_IWARP_SQ_OP_SEND;
} else {
if (ib_wr->send_flags & IB_SEND_SOLICITED)
wqe_misc = NES_IWARP_SQ_OP_SENDSEINV;
else
wqe_misc = NES_IWARP_SQ_OP_SENDINV;
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_INV_STAG_LOW_IDX,
ib_wr->ex.invalidate_rkey);
}
if (ib_wr->num_sge > nesdev->nesadapter->max_sge) {
err = -EINVAL;
break;
}
if (ib_wr->send_flags & IB_SEND_FENCE)
wqe_misc |= NES_IWARP_SQ_WQE_LOCAL_FENCE;
if ((ib_wr->send_flags & IB_SEND_INLINE) &&
((nes_drv_opt & NES_DRV_OPT_NO_INLINE_DATA) == 0) &&
(ib_wr->sg_list[0].length <= 64)) {
memcpy(&wqe->wqe_words[NES_IWARP_SQ_WQE_IMM_DATA_START_IDX],
(void *)(unsigned long)ib_wr->sg_list[0].addr, ib_wr->sg_list[0].length);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_TOTAL_PAYLOAD_IDX,
ib_wr->sg_list[0].length);
wqe_misc |= NES_IWARP_SQ_WQE_IMM_DATA;
} else {
fill_wqe_sg_send(wqe, ib_wr, 1);
}
break;
case IB_WR_RDMA_WRITE:
wqe_misc = NES_IWARP_SQ_OP_RDMAW;
if (ib_wr->num_sge > nesdev->nesadapter->max_sge) {
nes_debug(NES_DBG_IW_TX, "Exceeded max sge, ib_wr=%u, max=%u\n",
ib_wr->num_sge, nesdev->nesadapter->max_sge);
err = -EINVAL;
break;
}
if (ib_wr->send_flags & IB_SEND_FENCE)
wqe_misc |= NES_IWARP_SQ_WQE_LOCAL_FENCE;
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_RDMA_STAG_IDX,
ib_wr->wr.rdma.rkey);
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_RDMA_TO_LOW_IDX,
ib_wr->wr.rdma.remote_addr);
if ((ib_wr->send_flags & IB_SEND_INLINE) &&
((nes_drv_opt & NES_DRV_OPT_NO_INLINE_DATA) == 0) &&
(ib_wr->sg_list[0].length <= 64)) {
memcpy(&wqe->wqe_words[NES_IWARP_SQ_WQE_IMM_DATA_START_IDX],
(void *)(unsigned long)ib_wr->sg_list[0].addr, ib_wr->sg_list[0].length);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_TOTAL_PAYLOAD_IDX,
ib_wr->sg_list[0].length);
wqe_misc |= NES_IWARP_SQ_WQE_IMM_DATA;
} else {
fill_wqe_sg_send(wqe, ib_wr, 1);
}
wqe->wqe_words[NES_IWARP_SQ_WQE_RDMA_LENGTH_IDX] =
wqe->wqe_words[NES_IWARP_SQ_WQE_TOTAL_PAYLOAD_IDX];
break;
case IB_WR_RDMA_READ:
case IB_WR_RDMA_READ_WITH_INV:
/* iWARP only supports 1 sge for RDMA reads */
if (ib_wr->num_sge > 1) {
nes_debug(NES_DBG_IW_TX, "Exceeded max sge, ib_wr=%u, max=1\n",
ib_wr->num_sge);
err = -EINVAL;
break;
}
if (ib_wr->opcode == IB_WR_RDMA_READ) {
wqe_misc = NES_IWARP_SQ_OP_RDMAR;
} else {
wqe_misc = NES_IWARP_SQ_OP_RDMAR_LOCINV;
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_INV_STAG_LOW_IDX,
ib_wr->ex.invalidate_rkey);
}
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_RDMA_TO_LOW_IDX,
ib_wr->wr.rdma.remote_addr);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_RDMA_STAG_IDX,
ib_wr->wr.rdma.rkey);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_RDMA_LENGTH_IDX,
ib_wr->sg_list->length);
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_FRAG0_LOW_IDX,
ib_wr->sg_list->addr);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_STAG0_IDX,
ib_wr->sg_list->lkey);
break;
case IB_WR_LOCAL_INV:
wqe_misc = NES_IWARP_SQ_OP_LOCINV;
set_wqe_32bit_value(wqe->wqe_words,
NES_IWARP_SQ_LOCINV_WQE_INV_STAG_IDX,
ib_wr->ex.invalidate_rkey);
break;
case IB_WR_FAST_REG_MR:
{
int i;
int flags = ib_wr->wr.fast_reg.access_flags;
struct nes_ib_fast_reg_page_list *pnesfrpl =
container_of(ib_wr->wr.fast_reg.page_list,
struct nes_ib_fast_reg_page_list,
ibfrpl);
u64 *src_page_list = pnesfrpl->ibfrpl.page_list;
u64 *dst_page_list = pnesfrpl->nes_wqe_pbl.kva;
if (ib_wr->wr.fast_reg.page_list_len >
(NES_4K_PBL_CHUNK_SIZE / sizeof(u64))) {
nes_debug(NES_DBG_IW_TX, "SQ_FMR: bad page_list_len\n");
err = -EINVAL;
break;
}
wqe_misc = NES_IWARP_SQ_OP_FAST_REG;
set_wqe_64bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_VA_FBO_LOW_IDX,
ib_wr->wr.fast_reg.iova_start);
set_wqe_32bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_LENGTH_LOW_IDX,
ib_wr->wr.fast_reg.length);
set_wqe_32bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_LENGTH_HIGH_IDX, 0);
set_wqe_32bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_MR_STAG_IDX,
ib_wr->wr.fast_reg.rkey);
/* Set page size: */
if (ib_wr->wr.fast_reg.page_shift == 12) {
wqe_misc |= NES_IWARP_SQ_FMR_WQE_PAGE_SIZE_4K;
} else if (ib_wr->wr.fast_reg.page_shift == 21) {
wqe_misc |= NES_IWARP_SQ_FMR_WQE_PAGE_SIZE_2M;
} else {
nes_debug(NES_DBG_IW_TX, "Invalid page shift,"
" ib_wr=%u, max=1\n", ib_wr->num_sge);
err = -EINVAL;
break;
}
/* Set access_flags */
wqe_misc |= NES_IWARP_SQ_FMR_WQE_RIGHTS_ENABLE_LOCAL_READ;
if (flags & IB_ACCESS_LOCAL_WRITE)
wqe_misc |= NES_IWARP_SQ_FMR_WQE_RIGHTS_ENABLE_LOCAL_WRITE;
if (flags & IB_ACCESS_REMOTE_WRITE)
wqe_misc |= NES_IWARP_SQ_FMR_WQE_RIGHTS_ENABLE_REMOTE_WRITE;
if (flags & IB_ACCESS_REMOTE_READ)
wqe_misc |= NES_IWARP_SQ_FMR_WQE_RIGHTS_ENABLE_REMOTE_READ;
if (flags & IB_ACCESS_MW_BIND)
wqe_misc |= NES_IWARP_SQ_FMR_WQE_RIGHTS_ENABLE_WINDOW_BIND;
/* Fill in PBL info: */
if (ib_wr->wr.fast_reg.page_list_len >
pnesfrpl->ibfrpl.max_page_list_len) {
nes_debug(NES_DBG_IW_TX, "Invalid page list length,"
" ib_wr=%p, value=%u, max=%u\n",
ib_wr, ib_wr->wr.fast_reg.page_list_len,
pnesfrpl->ibfrpl.max_page_list_len);
err = -EINVAL;
break;
}
set_wqe_64bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_PBL_ADDR_LOW_IDX,
pnesfrpl->nes_wqe_pbl.paddr);
set_wqe_32bit_value(wqe->wqe_words,
NES_IWARP_SQ_FMR_WQE_PBL_LENGTH_IDX,
ib_wr->wr.fast_reg.page_list_len * 8);
for (i = 0; i < ib_wr->wr.fast_reg.page_list_len; i++)
dst_page_list[i] = cpu_to_le64(src_page_list[i]);
nes_debug(NES_DBG_IW_TX, "SQ_FMR: iova_start: %llx, "
"length: %d, rkey: %0x, pgl_paddr: %llx, "
"page_list_len: %u, wqe_misc: %x\n",
(unsigned long long) ib_wr->wr.fast_reg.iova_start,
ib_wr->wr.fast_reg.length,
ib_wr->wr.fast_reg.rkey,
(unsigned long long) pnesfrpl->nes_wqe_pbl.paddr,
ib_wr->wr.fast_reg.page_list_len,
wqe_misc);
break;
}
default:
/* error */
err = -EINVAL;
break;
}
if (err)
break;
if ((ib_wr->send_flags & IB_SEND_SIGNALED) || nesqp->sig_all)
wqe_misc |= NES_IWARP_SQ_WQE_SIGNALED_COMPL;
wqe->wqe_words[NES_IWARP_SQ_WQE_MISC_IDX] = cpu_to_le32(wqe_misc);
ib_wr = ib_wr->next;
head++;
wqe_count++;
if (head >= qsize)
head = 0;
}
nesqp->hwqp.sq_head = head;
barrier();
while (wqe_count) {
counter = min(wqe_count, ((u32)255));
wqe_count -= counter;
nes_write32(nesdev->regs + NES_WQE_ALLOC,
(counter << 24) | 0x00800000 | nesqp->hwqp.qp_id);
}
spin_unlock_irqrestore(&nesqp->lock, flags);
out:
if (err)
*bad_wr = ib_wr;
return err;
}
/**
* nes_post_recv
*/
static int nes_post_recv(struct ib_qp *ibqp, struct ib_recv_wr *ib_wr,
struct ib_recv_wr **bad_wr)
{
u64 u64temp;
unsigned long flags = 0;
struct nes_vnic *nesvnic = to_nesvnic(ibqp->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_qp *nesqp = to_nesqp(ibqp);
struct nes_hw_qp_wqe *wqe;
int err = 0;
int sge_index;
u32 qsize = nesqp->hwqp.rq_size;
u32 head;
u32 wqe_count = 0;
u32 counter;
u32 total_payload_length;
if (nesqp->ibqp_state > IB_QPS_RTS) {
err = -EINVAL;
goto out;
}
spin_lock_irqsave(&nesqp->lock, flags);
head = nesqp->hwqp.rq_head;
while (ib_wr) {
/* Check for QP error */
if (nesqp->term_flags) {
err = -EINVAL;
break;
}
if (ib_wr->num_sge > nesdev->nesadapter->max_sge) {
err = -EINVAL;
break;
}
/* Check for RQ overflow */
if (((head + (2 * qsize) - nesqp->hwqp.rq_tail) % qsize) == (qsize - 1)) {
err = -ENOMEM;
break;
}
nes_debug(NES_DBG_IW_RX, "ibwr sge count = %u.\n", ib_wr->num_sge);
wqe = &nesqp->hwqp.rq_vbase[head];
/* nes_debug(NES_DBG_IW_RX, "QP%u:processing rq wqe at %p, head = %u.\n",
nesqp->hwqp.qp_id, wqe, head); */
nes_fill_init_qp_wqe(wqe, nesqp, head);
u64temp = (u64)(ib_wr->wr_id);
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_SQ_WQE_COMP_SCRATCH_LOW_IDX,
u64temp);
total_payload_length = 0;
for (sge_index=0; sge_index < ib_wr->num_sge; sge_index++) {
set_wqe_64bit_value(wqe->wqe_words, NES_IWARP_RQ_WQE_FRAG0_LOW_IDX+(sge_index*4),
ib_wr->sg_list[sge_index].addr);
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_RQ_WQE_LENGTH0_IDX+(sge_index*4),
ib_wr->sg_list[sge_index].length);
set_wqe_32bit_value(wqe->wqe_words,NES_IWARP_RQ_WQE_STAG0_IDX+(sge_index*4),
ib_wr->sg_list[sge_index].lkey);
total_payload_length += ib_wr->sg_list[sge_index].length;
}
set_wqe_32bit_value(wqe->wqe_words, NES_IWARP_RQ_WQE_TOTAL_PAYLOAD_IDX,
total_payload_length);
ib_wr = ib_wr->next;
head++;
wqe_count++;
if (head >= qsize)
head = 0;
}
nesqp->hwqp.rq_head = head;
barrier();
while (wqe_count) {
counter = min(wqe_count, ((u32)255));
wqe_count -= counter;
nes_write32(nesdev->regs+NES_WQE_ALLOC, (counter<<24) | nesqp->hwqp.qp_id);
}
spin_unlock_irqrestore(&nesqp->lock, flags);
out:
if (err)
*bad_wr = ib_wr;
return err;
}
/**
* nes_poll_cq
*/
static int nes_poll_cq(struct ib_cq *ibcq, int num_entries, struct ib_wc *entry)
{
u64 u64temp;
u64 wrid;
unsigned long flags = 0;
struct nes_vnic *nesvnic = to_nesvnic(ibcq->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_cq *nescq = to_nescq(ibcq);
struct nes_qp *nesqp;
struct nes_hw_cqe cqe;
u32 head;
u32 wq_tail = 0;
u32 cq_size;
u32 cqe_count = 0;
u32 wqe_index;
u32 u32temp;
u32 move_cq_head = 1;
u32 err_code;
nes_debug(NES_DBG_CQ, "\n");
spin_lock_irqsave(&nescq->lock, flags);
head = nescq->hw_cq.cq_head;
cq_size = nescq->hw_cq.cq_size;
while (cqe_count < num_entries) {
if ((le32_to_cpu(nescq->hw_cq.cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX]) &
NES_CQE_VALID) == 0)
break;
/*
* Make sure we read CQ entry contents *after*
* we've checked the valid bit.
*/
rmb();
cqe = nescq->hw_cq.cq_vbase[head];
u32temp = le32_to_cpu(cqe.cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX]);
wqe_index = u32temp & (nesdev->nesadapter->max_qp_wr - 1);
u32temp &= ~(NES_SW_CONTEXT_ALIGN-1);
/* parse CQE, get completion context from WQE (either rq or sq) */
u64temp = (((u64)(le32_to_cpu(cqe.cqe_words[NES_CQE_COMP_COMP_CTX_HIGH_IDX])))<<32) |
((u64)u32temp);
if (u64temp) {
nesqp = (struct nes_qp *)(unsigned long)u64temp;
memset(entry, 0, sizeof *entry);
if (cqe.cqe_words[NES_CQE_ERROR_CODE_IDX] == 0) {
entry->status = IB_WC_SUCCESS;
} else {
err_code = le32_to_cpu(cqe.cqe_words[NES_CQE_ERROR_CODE_IDX]);
if (NES_IWARP_CQE_MAJOR_DRV == (err_code >> 16)) {
entry->status = err_code & 0x0000ffff;
/* The rest of the cqe's will be marked as flushed */
nescq->hw_cq.cq_vbase[head].cqe_words[NES_CQE_ERROR_CODE_IDX] =
cpu_to_le32((NES_IWARP_CQE_MAJOR_FLUSH << 16) |
NES_IWARP_CQE_MINOR_FLUSH);
} else
entry->status = IB_WC_WR_FLUSH_ERR;
}
entry->qp = &nesqp->ibqp;
entry->src_qp = nesqp->hwqp.qp_id;
if (le32_to_cpu(cqe.cqe_words[NES_CQE_OPCODE_IDX]) & NES_CQE_SQ) {
if (nesqp->skip_lsmm) {
nesqp->skip_lsmm = 0;
nesqp->hwqp.sq_tail++;
}
/* Working on a SQ Completion*/
wrid = (((u64)(cpu_to_le32((u32)nesqp->hwqp.sq_vbase[wqe_index].
wqe_words[NES_IWARP_SQ_WQE_COMP_SCRATCH_HIGH_IDX]))) << 32) |
((u64)(cpu_to_le32((u32)nesqp->hwqp.sq_vbase[wqe_index].
wqe_words[NES_IWARP_SQ_WQE_COMP_SCRATCH_LOW_IDX])));
entry->byte_len = le32_to_cpu(nesqp->hwqp.sq_vbase[wqe_index].
wqe_words[NES_IWARP_SQ_WQE_TOTAL_PAYLOAD_IDX]);
switch (le32_to_cpu(nesqp->hwqp.sq_vbase[wqe_index].
wqe_words[NES_IWARP_SQ_WQE_MISC_IDX]) & 0x3f) {
case NES_IWARP_SQ_OP_RDMAW:
nes_debug(NES_DBG_CQ, "Operation = RDMA WRITE.\n");
entry->opcode = IB_WC_RDMA_WRITE;
break;
case NES_IWARP_SQ_OP_RDMAR:
nes_debug(NES_DBG_CQ, "Operation = RDMA READ.\n");
entry->opcode = IB_WC_RDMA_READ;
entry->byte_len = le32_to_cpu(nesqp->hwqp.sq_vbase[wqe_index].
wqe_words[NES_IWARP_SQ_WQE_RDMA_LENGTH_IDX]);
break;
case NES_IWARP_SQ_OP_SENDINV:
case NES_IWARP_SQ_OP_SENDSEINV:
case NES_IWARP_SQ_OP_SEND:
case NES_IWARP_SQ_OP_SENDSE:
nes_debug(NES_DBG_CQ, "Operation = Send.\n");
entry->opcode = IB_WC_SEND;
break;
case NES_IWARP_SQ_OP_LOCINV:
entry->opcode = IB_WC_LOCAL_INV;
break;
case NES_IWARP_SQ_OP_FAST_REG:
entry->opcode = IB_WC_FAST_REG_MR;
break;
}
nesqp->hwqp.sq_tail = (wqe_index+1)&(nesqp->hwqp.sq_size - 1);
if ((entry->status != IB_WC_SUCCESS) && (nesqp->hwqp.sq_tail != nesqp->hwqp.sq_head)) {
move_cq_head = 0;
wq_tail = nesqp->hwqp.sq_tail;
}
} else {
/* Working on a RQ Completion*/
entry->byte_len = le32_to_cpu(cqe.cqe_words[NES_CQE_PAYLOAD_LENGTH_IDX]);
wrid = ((u64)(le32_to_cpu(nesqp->hwqp.rq_vbase[wqe_index].wqe_words[NES_IWARP_RQ_WQE_COMP_SCRATCH_LOW_IDX]))) |
((u64)(le32_to_cpu(nesqp->hwqp.rq_vbase[wqe_index].wqe_words[NES_IWARP_RQ_WQE_COMP_SCRATCH_HIGH_IDX]))<<32);
entry->opcode = IB_WC_RECV;
nesqp->hwqp.rq_tail = (wqe_index+1)&(nesqp->hwqp.rq_size - 1);
if ((entry->status != IB_WC_SUCCESS) && (nesqp->hwqp.rq_tail != nesqp->hwqp.rq_head)) {
move_cq_head = 0;
wq_tail = nesqp->hwqp.rq_tail;
}
}
entry->wr_id = wrid;
entry++;
cqe_count++;
}
if (move_cq_head) {
nescq->hw_cq.cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX] = 0;
if (++head >= cq_size)
head = 0;
nescq->polled_completions++;
if ((nescq->polled_completions > (cq_size / 2)) ||
(nescq->polled_completions == 255)) {
nes_debug(NES_DBG_CQ, "CQ%u Issuing CQE Allocate since more than half of cqes"
" are pending %u of %u.\n",
nescq->hw_cq.cq_number, nescq->polled_completions, cq_size);
nes_write32(nesdev->regs+NES_CQE_ALLOC,
nescq->hw_cq.cq_number | (nescq->polled_completions << 16));
nescq->polled_completions = 0;
}
} else {
/* Update the wqe index and set status to flush */
wqe_index = le32_to_cpu(cqe.cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX]);
wqe_index = (wqe_index & (~(nesdev->nesadapter->max_qp_wr - 1))) | wq_tail;
nescq->hw_cq.cq_vbase[head].cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX] =
cpu_to_le32(wqe_index);
move_cq_head = 1; /* ready for next pass */
}
}
if (nescq->polled_completions) {
nes_write32(nesdev->regs+NES_CQE_ALLOC,
nescq->hw_cq.cq_number | (nescq->polled_completions << 16));
nescq->polled_completions = 0;
}
nescq->hw_cq.cq_head = head;
nes_debug(NES_DBG_CQ, "Reporting %u completions for CQ%u.\n",
cqe_count, nescq->hw_cq.cq_number);
spin_unlock_irqrestore(&nescq->lock, flags);
return cqe_count;
}
/**
* nes_req_notify_cq
*/
static int nes_req_notify_cq(struct ib_cq *ibcq, enum ib_cq_notify_flags notify_flags)
{
struct nes_vnic *nesvnic = to_nesvnic(ibcq->device);
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_cq *nescq = to_nescq(ibcq);
u32 cq_arm;
nes_debug(NES_DBG_CQ, "Requesting notification for CQ%u.\n",
nescq->hw_cq.cq_number);
cq_arm = nescq->hw_cq.cq_number;
if ((notify_flags & IB_CQ_SOLICITED_MASK) == IB_CQ_NEXT_COMP)
cq_arm |= NES_CQE_ALLOC_NOTIFY_NEXT;
else if ((notify_flags & IB_CQ_SOLICITED_MASK) == IB_CQ_SOLICITED)
cq_arm |= NES_CQE_ALLOC_NOTIFY_SE;
else
return -EINVAL;
nes_write32(nesdev->regs+NES_CQE_ALLOC, cq_arm);
nes_read32(nesdev->regs+NES_CQE_ALLOC);
return 0;
}
static int nes_port_immutable(struct ib_device *ibdev, u8 port_num,
struct ib_port_immutable *immutable)
{
struct ib_port_attr attr;
int err;
err = nes_query_port(ibdev, port_num, &attr);
if (err)
return err;
immutable->pkey_tbl_len = attr.pkey_tbl_len;
immutable->gid_tbl_len = attr.gid_tbl_len;
immutable->core_cap_flags = RDMA_CORE_PORT_IWARP;
return 0;
}
/**
* nes_init_ofa_device
*/
struct nes_ib_device *nes_init_ofa_device(struct net_device *netdev)
{
struct nes_ib_device *nesibdev;
struct nes_vnic *nesvnic = netdev_priv(netdev);
struct nes_device *nesdev = nesvnic->nesdev;
nesibdev = (struct nes_ib_device *)ib_alloc_device(sizeof(struct nes_ib_device));
if (nesibdev == NULL) {
return NULL;
}
strlcpy(nesibdev->ibdev.name, "nes%d", IB_DEVICE_NAME_MAX);
nesibdev->ibdev.owner = THIS_MODULE;
nesibdev->ibdev.node_type = RDMA_NODE_RNIC;
memset(&nesibdev->ibdev.node_guid, 0, sizeof(nesibdev->ibdev.node_guid));
memcpy(&nesibdev->ibdev.node_guid, netdev->dev_addr, 6);
nesibdev->ibdev.uverbs_cmd_mask =
(1ull << IB_USER_VERBS_CMD_GET_CONTEXT) |
(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE) |
(1ull << IB_USER_VERBS_CMD_QUERY_PORT) |
(1ull << IB_USER_VERBS_CMD_ALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_REG_MR) |
(1ull << IB_USER_VERBS_CMD_DEREG_MR) |
(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
(1ull << IB_USER_VERBS_CMD_CREATE_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_CQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_AH) |
(1ull << IB_USER_VERBS_CMD_DESTROY_AH) |
(1ull << IB_USER_VERBS_CMD_REQ_NOTIFY_CQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_QP) |
(1ull << IB_USER_VERBS_CMD_MODIFY_QP) |
(1ull << IB_USER_VERBS_CMD_POLL_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_QP) |
(1ull << IB_USER_VERBS_CMD_ALLOC_MW) |
(1ull << IB_USER_VERBS_CMD_BIND_MW) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_MW) |
(1ull << IB_USER_VERBS_CMD_POST_RECV) |
(1ull << IB_USER_VERBS_CMD_POST_SEND);
nesibdev->ibdev.phys_port_cnt = 1;
nesibdev->ibdev.num_comp_vectors = 1;
nesibdev->ibdev.dma_device = &nesdev->pcidev->dev;
nesibdev->ibdev.dev.parent = &nesdev->pcidev->dev;
nesibdev->ibdev.query_device = nes_query_device;
nesibdev->ibdev.query_port = nes_query_port;
nesibdev->ibdev.query_pkey = nes_query_pkey;
nesibdev->ibdev.query_gid = nes_query_gid;
nesibdev->ibdev.alloc_ucontext = nes_alloc_ucontext;
nesibdev->ibdev.dealloc_ucontext = nes_dealloc_ucontext;
nesibdev->ibdev.mmap = nes_mmap;
nesibdev->ibdev.alloc_pd = nes_alloc_pd;
nesibdev->ibdev.dealloc_pd = nes_dealloc_pd;
nesibdev->ibdev.create_ah = nes_create_ah;
nesibdev->ibdev.destroy_ah = nes_destroy_ah;
nesibdev->ibdev.create_qp = nes_create_qp;
nesibdev->ibdev.modify_qp = nes_modify_qp;
nesibdev->ibdev.query_qp = nes_query_qp;
nesibdev->ibdev.destroy_qp = nes_destroy_qp;
nesibdev->ibdev.create_cq = nes_create_cq;
nesibdev->ibdev.destroy_cq = nes_destroy_cq;
nesibdev->ibdev.poll_cq = nes_poll_cq;
nesibdev->ibdev.get_dma_mr = nes_get_dma_mr;
nesibdev->ibdev.reg_phys_mr = nes_reg_phys_mr;
nesibdev->ibdev.reg_user_mr = nes_reg_user_mr;
nesibdev->ibdev.dereg_mr = nes_dereg_mr;
nesibdev->ibdev.alloc_mw = nes_alloc_mw;
nesibdev->ibdev.dealloc_mw = nes_dealloc_mw;
nesibdev->ibdev.bind_mw = nes_bind_mw;
nesibdev->ibdev.alloc_fast_reg_mr = nes_alloc_fast_reg_mr;
nesibdev->ibdev.alloc_fast_reg_page_list = nes_alloc_fast_reg_page_list;
nesibdev->ibdev.free_fast_reg_page_list = nes_free_fast_reg_page_list;
nesibdev->ibdev.attach_mcast = nes_multicast_attach;
nesibdev->ibdev.detach_mcast = nes_multicast_detach;
nesibdev->ibdev.process_mad = nes_process_mad;
nesibdev->ibdev.req_notify_cq = nes_req_notify_cq;
nesibdev->ibdev.post_send = nes_post_send;
nesibdev->ibdev.post_recv = nes_post_recv;
nesibdev->ibdev.iwcm = kzalloc(sizeof(*nesibdev->ibdev.iwcm), GFP_KERNEL);
if (nesibdev->ibdev.iwcm == NULL) {
ib_dealloc_device(&nesibdev->ibdev);
return NULL;
}
nesibdev->ibdev.iwcm->add_ref = nes_add_ref;
nesibdev->ibdev.iwcm->rem_ref = nes_rem_ref;
nesibdev->ibdev.iwcm->get_qp = nes_get_qp;
nesibdev->ibdev.iwcm->connect = nes_connect;
nesibdev->ibdev.iwcm->accept = nes_accept;
nesibdev->ibdev.iwcm->reject = nes_reject;
nesibdev->ibdev.iwcm->create_listen = nes_create_listen;
nesibdev->ibdev.iwcm->destroy_listen = nes_destroy_listen;
nesibdev->ibdev.get_port_immutable = nes_port_immutable;
return nesibdev;
}
/**
* nes_handle_delayed_event
*/
static void nes_handle_delayed_event(unsigned long data)
{
struct nes_vnic *nesvnic = (void *) data;
if (nesvnic->delayed_event != nesvnic->last_dispatched_event) {
struct ib_event event;
event.device = &nesvnic->nesibdev->ibdev;
if (!event.device)
goto stop_timer;
event.event = nesvnic->delayed_event;
event.element.port_num = nesvnic->logical_port + 1;
ib_dispatch_event(&event);
}
stop_timer:
nesvnic->event_timer.function = NULL;
}
void nes_port_ibevent(struct nes_vnic *nesvnic)
{
struct nes_ib_device *nesibdev = nesvnic->nesibdev;
struct nes_device *nesdev = nesvnic->nesdev;
struct ib_event event;
event.device = &nesibdev->ibdev;
event.element.port_num = nesvnic->logical_port + 1;
event.event = nesdev->iw_status ? IB_EVENT_PORT_ACTIVE : IB_EVENT_PORT_ERR;
if (!nesvnic->event_timer.function) {
ib_dispatch_event(&event);
nesvnic->last_dispatched_event = event.event;
nesvnic->event_timer.function = nes_handle_delayed_event;
nesvnic->event_timer.data = (unsigned long) nesvnic;
nesvnic->event_timer.expires = jiffies + NES_EVENT_DELAY;
add_timer(&nesvnic->event_timer);
} else {
mod_timer(&nesvnic->event_timer, jiffies + NES_EVENT_DELAY);
}
nesvnic->delayed_event = event.event;
}
/**
* nes_destroy_ofa_device
*/
void nes_destroy_ofa_device(struct nes_ib_device *nesibdev)
{
if (nesibdev == NULL)
return;
nes_unregister_ofa_device(nesibdev);
kfree(nesibdev->ibdev.iwcm);
ib_dealloc_device(&nesibdev->ibdev);
}
/**
* nes_register_ofa_device
*/
int nes_register_ofa_device(struct nes_ib_device *nesibdev)
{
struct nes_vnic *nesvnic = nesibdev->nesvnic;
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_adapter *nesadapter = nesdev->nesadapter;
int i, ret;
ret = ib_register_device(&nesvnic->nesibdev->ibdev, NULL);
if (ret) {
return ret;
}
/* Get the resources allocated to this device */
nesibdev->max_cq = (nesadapter->max_cq-NES_FIRST_QPN) / nesadapter->port_count;
nesibdev->max_mr = nesadapter->max_mr / nesadapter->port_count;
nesibdev->max_qp = (nesadapter->max_qp-NES_FIRST_QPN) / nesadapter->port_count;
nesibdev->max_pd = nesadapter->max_pd / nesadapter->port_count;
for (i = 0; i < ARRAY_SIZE(nes_dev_attributes); ++i) {
ret = device_create_file(&nesibdev->ibdev.dev, nes_dev_attributes[i]);
if (ret) {
while (i > 0) {
i--;
device_remove_file(&nesibdev->ibdev.dev,
nes_dev_attributes[i]);
}
ib_unregister_device(&nesibdev->ibdev);
return ret;
}
}
nesvnic->of_device_registered = 1;
return 0;
}
/**
* nes_unregister_ofa_device
*/
static void nes_unregister_ofa_device(struct nes_ib_device *nesibdev)
{
struct nes_vnic *nesvnic = nesibdev->nesvnic;
int i;
for (i = 0; i < ARRAY_SIZE(nes_dev_attributes); ++i) {
device_remove_file(&nesibdev->ibdev.dev, nes_dev_attributes[i]);
}
if (nesvnic->of_device_registered) {
ib_unregister_device(&nesibdev->ibdev);
}
nesvnic->of_device_registered = 0;
}
| gpl-2.0 |
surengrig/Milstone-XT720-kernel-upgrade | net/irda/irnet/irnet_ppp.c | 212 | 32797 | /*
* IrNET protocol module : Synchronous PPP over an IrDA socket.
*
* Jean II - HPL `00 - <jt@hpl.hp.com>
*
* This file implement the PPP interface and /dev/irnet character device.
* The PPP interface hook to the ppp_generic module, handle all our
* relationship to the PPP code in the kernel (and by extension to pppd),
* and exchange PPP frames with this module (send/receive).
* The /dev/irnet device is used primarily for 2 functions :
* 1) as a stub for pppd (the ppp daemon), so that we can appropriately
* generate PPP sessions (we pretend we are a tty).
* 2) as a control channel (write commands, read events)
*/
#include "irnet_ppp.h" /* Private header */
/* Please put other headers in irnet.h - Thanks */
/* Generic PPP callbacks (to call us) */
static struct ppp_channel_ops irnet_ppp_ops = {
.start_xmit = ppp_irnet_send,
.ioctl = ppp_irnet_ioctl
};
/************************* CONTROL CHANNEL *************************/
/*
* When a pppd instance is not active on /dev/irnet, it acts as a control
* channel.
* Writing allow to set up the IrDA destination of the IrNET channel,
* and any application may be read events happening in IrNET...
*/
/*------------------------------------------------------------------*/
/*
* Write is used to send a command to configure a IrNET channel
* before it is open by pppd. The syntax is : "command argument"
* Currently there is only two defined commands :
* o name : set the requested IrDA nickname of the IrNET peer.
* o addr : set the requested IrDA address of the IrNET peer.
* Note : the code is crude, but effective...
*/
static inline ssize_t
irnet_ctrl_write(irnet_socket * ap,
const char __user *buf,
size_t count)
{
char command[IRNET_MAX_COMMAND];
char * start; /* Current command being processed */
char * next; /* Next command to process */
int length; /* Length of current command */
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
/* Check for overflow... */
DABORT(count >= IRNET_MAX_COMMAND, -ENOMEM,
CTRL_ERROR, "Too much data !!!\n");
/* Get the data in the driver */
if(copy_from_user(command, buf, count))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
/* Safe terminate the string */
command[count] = '\0';
DEBUG(CTRL_INFO, "Command line received is ``%s'' (%Zd).\n",
command, count);
/* Check every commands in the command line */
next = command;
while(next != NULL)
{
/* Look at the next command */
start = next;
/* Scrap whitespaces before the command */
while(isspace(*start))
start++;
/* ',' is our command separator */
next = strchr(start, ',');
if(next)
{
*next = '\0'; /* Terminate command */
length = next - start; /* Length */
next++; /* Skip the '\0' */
}
else
length = strlen(start);
DEBUG(CTRL_INFO, "Found command ``%s'' (%d).\n", start, length);
/* Check if we recognised one of the known command
* We can't use "switch" with strings, so hack with "continue" */
/* First command : name -> Requested IrDA nickname */
if(!strncmp(start, "name", 4))
{
/* Copy the name only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
/* Strip out trailing whitespaces */
while(isspace(start[length - 1]))
length--;
/* Copy the name for later reuse */
memcpy(ap->rname, start + 5, length - 5);
ap->rname[length - 5] = '\0';
}
else
ap->rname[0] = '\0';
DEBUG(CTRL_INFO, "Got rname = ``%s''\n", ap->rname);
/* Restart the loop */
continue;
}
/* Second command : addr, daddr -> Requested IrDA destination address
* Also process : saddr -> Requested IrDA source address */
if((!strncmp(start, "addr", 4)) ||
(!strncmp(start, "daddr", 5)) ||
(!strncmp(start, "saddr", 5)))
{
__u32 addr = DEV_ADDR_ANY;
/* Copy the address only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
char * begp = start + 5;
char * endp;
/* Scrap whitespaces before the command */
while(isspace(*begp))
begp++;
/* Convert argument to a number (last arg is the base) */
addr = simple_strtoul(begp, &endp, 16);
/* Has it worked ? (endp should be start + length) */
DABORT(endp <= (start + 5), -EINVAL,
CTRL_ERROR, "Invalid address.\n");
}
/* Which type of address ? */
if(start[0] == 's')
{
/* Save it */
ap->rsaddr = addr;
DEBUG(CTRL_INFO, "Got rsaddr = %08x\n", ap->rsaddr);
}
else
{
/* Save it */
ap->rdaddr = addr;
DEBUG(CTRL_INFO, "Got rdaddr = %08x\n", ap->rdaddr);
}
/* Restart the loop */
continue;
}
/* Other possible command : connect N (number of retries) */
/* No command matched -> Failed... */
DABORT(1, -EINVAL, CTRL_ERROR, "Not a recognised IrNET command.\n");
}
/* Success : we have parsed all commands successfully */
return(count);
}
#ifdef INITIAL_DISCOVERY
/*------------------------------------------------------------------*/
/*
* Function irnet_get_discovery_log (self)
*
* Query the content on the discovery log if not done
*
* This function query the current content of the discovery log
* at the startup of the event channel and save it in the internal struct.
*/
static void
irnet_get_discovery_log(irnet_socket * ap)
{
__u16 mask = irlmp_service_to_hint(S_LAN);
/* Ask IrLMP for the current discovery log */
ap->discoveries = irlmp_get_discoveries(&ap->disco_number, mask,
DISCOVERY_DEFAULT_SLOTS);
/* Check if the we got some results */
if(ap->discoveries == NULL)
ap->disco_number = -1;
DEBUG(CTRL_INFO, "Got the log (0x%p), size is %d\n",
ap->discoveries, ap->disco_number);
}
/*------------------------------------------------------------------*/
/*
* Function irnet_read_discovery_log (self, event)
*
* Read the content on the discovery log
*
* This function dump the current content of the discovery log
* at the startup of the event channel.
* Return 1 if wrote an event on the control channel...
*
* State of the ap->disco_XXX variables :
* Socket creation : discoveries = NULL ; disco_index = 0 ; disco_number = 0
* While reading : discoveries = ptr ; disco_index = X ; disco_number = Y
* After reading : discoveries = NULL ; disco_index = Y ; disco_number = -1
*/
static inline int
irnet_read_discovery_log(irnet_socket * ap,
char * event)
{
int done_event = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, event=0x%p)\n",
ap, event);
/* Test if we have some work to do or we have already finished */
if(ap->disco_number == -1)
{
DEBUG(CTRL_INFO, "Already done\n");
return 0;
}
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Check if we have more item to dump */
if(ap->disco_index < ap->disco_number)
{
/* Write an event */
sprintf(event, "Found %08x (%s) behind %08x {hints %02X-%02X}\n",
ap->discoveries[ap->disco_index].daddr,
ap->discoveries[ap->disco_index].info,
ap->discoveries[ap->disco_index].saddr,
ap->discoveries[ap->disco_index].hints[0],
ap->discoveries[ap->disco_index].hints[1]);
DEBUG(CTRL_INFO, "Writing discovery %d : %s\n",
ap->disco_index, ap->discoveries[ap->disco_index].info);
/* We have an event */
done_event = 1;
/* Next discovery */
ap->disco_index++;
}
/* Check if we have done the last item */
if(ap->disco_index >= ap->disco_number)
{
/* No more items : remove the log and signal termination */
DEBUG(CTRL_INFO, "Cleaning up log (0x%p)\n",
ap->discoveries);
if(ap->discoveries != NULL)
{
/* Cleanup our copy of the discovery log */
kfree(ap->discoveries);
ap->discoveries = NULL;
}
ap->disco_number = -1;
}
return done_event;
}
#endif /* INITIAL_DISCOVERY */
/*------------------------------------------------------------------*/
/*
* Read is used to get IrNET events
*/
static inline ssize_t
irnet_ctrl_read(irnet_socket * ap,
struct file * file,
char __user * buf,
size_t count)
{
DECLARE_WAITQUEUE(wait, current);
char event[64]; /* Max event is 61 char */
ssize_t ret = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
/* Check if we can write an event out in one go */
DABORT(count < sizeof(event), -EOVERFLOW, CTRL_ERROR, "Buffer to small.\n");
#ifdef INITIAL_DISCOVERY
/* Check if we have read the log */
if(irnet_read_discovery_log(ap, event))
{
/* We have an event !!! Copy it to the user */
if(copy_to_user(buf, event, strlen(event)))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return(strlen(event));
}
#endif /* INITIAL_DISCOVERY */
/* Put ourselves on the wait queue to be woken up */
add_wait_queue(&irnet_events.rwait, &wait);
current->state = TASK_INTERRUPTIBLE;
for(;;)
{
/* If there is unread events */
ret = 0;
if(ap->event_index != irnet_events.index)
break;
ret = -EAGAIN;
if(file->f_flags & O_NONBLOCK)
break;
ret = -ERESTARTSYS;
if(signal_pending(current))
break;
/* Yield and wait to be woken up */
schedule();
}
current->state = TASK_RUNNING;
remove_wait_queue(&irnet_events.rwait, &wait);
/* Did we got it ? */
if(ret != 0)
{
/* No, return the error code */
DEXIT(CTRL_TRACE, " - ret %Zd\n", ret);
return ret;
}
/* Which event is it ? */
switch(irnet_events.log[ap->event_index].event)
{
case IRNET_DISCOVER:
sprintf(event, "Discovered %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_EXPIRE:
sprintf(event, "Expired %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_CONNECT_TO:
sprintf(event, "Connected to %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_CONNECT_FROM:
sprintf(event, "Connection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_REQUEST_FROM:
sprintf(event, "Request from %08x (%s) behind %08x\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr);
break;
case IRNET_NOANSWER_FROM:
sprintf(event, "No-answer from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_BLOCKED_LINK:
sprintf(event, "Blocked link with %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_FROM:
sprintf(event, "Disconnection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_TO:
sprintf(event, "Disconnected to %08x (%s)\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name);
break;
default:
sprintf(event, "Bug\n");
}
/* Increment our event index */
ap->event_index = (ap->event_index + 1) % IRNET_MAX_EVENTS;
DEBUG(CTRL_INFO, "Event is :%s", event);
/* Copy it to the user */
if(copy_to_user(buf, event, strlen(event)))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return(strlen(event));
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet.
* Just check if there are new events...
*/
static inline unsigned int
irnet_ctrl_poll(irnet_socket * ap,
struct file * file,
poll_table * wait)
{
unsigned int mask;
DENTER(CTRL_TRACE, "(ap=0x%p)\n", ap);
poll_wait(file, &irnet_events.rwait, wait);
mask = POLLOUT | POLLWRNORM;
/* If there is unread events */
if(ap->event_index != irnet_events.index)
mask |= POLLIN | POLLRDNORM;
#ifdef INITIAL_DISCOVERY
if(ap->disco_number != -1)
{
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Recheck */
if(ap->disco_number != -1)
mask |= POLLIN | POLLRDNORM;
}
#endif /* INITIAL_DISCOVERY */
DEXIT(CTRL_TRACE, " - mask=0x%X\n", mask);
return mask;
}
/*********************** FILESYSTEM CALLBACKS ***********************/
/*
* Implement the usual open, read, write functions that will be called
* by the file system when some action is performed on /dev/irnet.
* Most of those actions will in fact be performed by "pppd" or
* the control channel, we just act as a redirector...
*/
/*------------------------------------------------------------------*/
/*
* Open : when somebody open /dev/irnet
* We basically create a new instance of irnet and initialise it.
*/
static int
dev_irnet_open(struct inode * inode,
struct file * file)
{
struct irnet_socket * ap;
int err;
DENTER(FS_TRACE, "(file=0x%p)\n", file);
#ifdef SECURE_DEVIRNET
/* This could (should?) be enforced by the permissions on /dev/irnet. */
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
/* Allocate a private structure for this IrNET instance */
ap = kzalloc(sizeof(*ap), GFP_KERNEL);
DABORT(ap == NULL, -ENOMEM, FS_ERROR, "Can't allocate struct irnet...\n");
lock_kernel();
/* initialize the irnet structure */
ap->file = file;
/* PPP channel setup */
ap->ppp_open = 0;
ap->chan.private = ap;
ap->chan.ops = &irnet_ppp_ops;
ap->chan.mtu = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->chan.hdrlen = 2 + TTP_MAX_HEADER; /* for A/C + Max IrDA hdr */
/* PPP parameters */
ap->mru = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->xaccm[0] = ~0U;
ap->xaccm[3] = 0x60000000U;
ap->raccm = ~0U;
/* Setup the IrDA part... */
err = irda_irnet_create(ap);
if(err)
{
DERROR(FS_ERROR, "Can't setup IrDA link...\n");
kfree(ap);
unlock_kernel();
return err;
}
/* For the control channel */
ap->event_index = irnet_events.index; /* Cancel all past events */
/* Put our stuff where we will be able to find it later */
file->private_data = ap;
DEXIT(FS_TRACE, " - ap=0x%p\n", ap);
unlock_kernel();
return 0;
}
/*------------------------------------------------------------------*/
/*
* Close : when somebody close /dev/irnet
* Destroy the instance of /dev/irnet
*/
static int
dev_irnet_close(struct inode * inode,
struct file * file)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
DABORT(ap == NULL, 0, FS_ERROR, "ap is NULL !!!\n");
/* Detach ourselves */
file->private_data = NULL;
/* Close IrDA stuff */
irda_irnet_destroy(ap);
/* Disconnect from the generic PPP layer if not already done */
if(ap->ppp_open)
{
DERROR(FS_ERROR, "Channel still registered - deregistering !\n");
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
kfree(ap);
DEXIT(FS_TRACE, "\n");
return 0;
}
/*------------------------------------------------------------------*/
/*
* Write does nothing.
* (we receive packet from ppp_generic through ppp_irnet_send())
*/
static ssize_t
dev_irnet_write(struct file * file,
const char __user *buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_write(ap, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Read doesn't do much either.
* (pppd poll us, but ultimately reads through /dev/ppp)
*/
static ssize_t
dev_irnet_read(struct file * file,
char __user * buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_read(ap, file, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet
*/
static unsigned int
dev_irnet_poll(struct file * file,
poll_table * wait)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
unsigned int mask;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
mask = POLLOUT | POLLWRNORM;
DABORT(ap == NULL, mask, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(!ap->ppp_open)
mask |= irnet_ctrl_poll(ap, file, wait);
DEXIT(FS_TRACE, " - mask=0x%X\n", mask);
return(mask);
}
/*------------------------------------------------------------------*/
/*
* IOCtl : Called when someone does some ioctls on /dev/irnet
* This is the way pppd configure us and control us while the PPP
* instance is active.
*/
static long
dev_irnet_ioctl(
struct file * file,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
int err;
int val;
void __user *argp = (void __user *)arg;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p, cmd=0x%X)\n",
file, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
#ifdef SECURE_DEVIRNET
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
err = -EFAULT;
switch(cmd)
{
/* Set discipline (should be N_SYNC_PPP or N_TTY) */
case TIOCSETD:
if(get_user(val, (int __user *)argp))
break;
if((val == N_SYNC_PPP) || (val == N_PPP))
{
DEBUG(FS_INFO, "Entering PPP discipline.\n");
/* PPP channel setup (ap->chan in configued in dev_irnet_open())*/
lock_kernel();
err = ppp_register_channel(&ap->chan);
if(err == 0)
{
/* Our ppp side is active */
ap->ppp_open = 1;
DEBUG(FS_INFO, "Trying to establish a connection.\n");
/* Setup the IrDA link now - may fail... */
irda_irnet_connect(ap);
}
else
DERROR(FS_ERROR, "Can't setup PPP channel...\n");
unlock_kernel();
}
else
{
/* In theory, should be N_TTY */
DEBUG(FS_INFO, "Exiting PPP discipline.\n");
/* Disconnect from the generic PPP layer */
lock_kernel();
if(ap->ppp_open)
{
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
else
DERROR(FS_ERROR, "Channel not registered !\n");
err = 0;
unlock_kernel();
}
break;
/* Query PPP channel and unit number */
case PPPIOCGCHAN:
if(ap->ppp_open && !put_user(ppp_channel_index(&ap->chan),
(int __user *)argp))
err = 0;
break;
case PPPIOCGUNIT:
lock_kernel();
if(ap->ppp_open && !put_user(ppp_unit_number(&ap->chan),
(int __user *)argp))
err = 0;
break;
/* All these ioctls can be passed both directly and from ppp_generic,
* so we just deal with them in one place...
*/
case PPPIOCGFLAGS:
case PPPIOCSFLAGS:
case PPPIOCGASYNCMAP:
case PPPIOCSASYNCMAP:
case PPPIOCGRASYNCMAP:
case PPPIOCSRASYNCMAP:
case PPPIOCGXASYNCMAP:
case PPPIOCSXASYNCMAP:
case PPPIOCGMRU:
case PPPIOCSMRU:
DEBUG(FS_INFO, "Standard PPP ioctl.\n");
if(!capable(CAP_NET_ADMIN))
err = -EPERM;
else {
lock_kernel();
err = ppp_irnet_ioctl(&ap->chan, cmd, arg);
unlock_kernel();
}
break;
/* TTY IOCTLs : Pretend that we are a tty, to keep pppd happy */
/* Get termios */
case TCGETS:
DEBUG(FS_INFO, "Get termios.\n");
lock_kernel();
#ifndef TCGETS2
if(!kernel_termios_to_user_termios((struct termios __user *)argp, &ap->termios))
err = 0;
#else
if(kernel_termios_to_user_termios_1((struct termios __user *)argp, &ap->termios))
err = 0;
#endif
unlock_kernel();
break;
/* Set termios */
case TCSETSF:
DEBUG(FS_INFO, "Set termios.\n");
lock_kernel();
#ifndef TCGETS2
if(!user_termios_to_kernel_termios(&ap->termios, (struct termios __user *)argp))
err = 0;
#else
if(!user_termios_to_kernel_termios_1(&ap->termios, (struct termios __user *)argp))
err = 0;
#endif
unlock_kernel();
break;
/* Set DTR/RTS */
case TIOCMBIS:
case TIOCMBIC:
/* Set exclusive/non-exclusive mode */
case TIOCEXCL:
case TIOCNXCL:
DEBUG(FS_INFO, "TTY compatibility.\n");
err = 0;
break;
case TCGETA:
DEBUG(FS_INFO, "TCGETA\n");
break;
case TCFLSH:
DEBUG(FS_INFO, "TCFLSH\n");
/* Note : this will flush buffers in PPP, so it *must* be done
* We should also worry that we don't accept junk here and that
* we get rid of our own buffers */
#ifdef FLUSH_TO_PPP
lock_kernel();
ppp_output_wakeup(&ap->chan);
unlock_kernel();
#endif /* FLUSH_TO_PPP */
err = 0;
break;
case FIONREAD:
DEBUG(FS_INFO, "FIONREAD\n");
val = 0;
if(put_user(val, (int __user *)argp))
break;
err = 0;
break;
default:
DERROR(FS_ERROR, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOTTY;
}
DEXIT(FS_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** PPP CALLBACKS **************************/
/*
* This are the functions that the generic PPP driver in the kernel
* will call to communicate to us.
*/
/*------------------------------------------------------------------*/
/*
* Prepare the ppp frame for transmission over the IrDA socket.
* We make sure that the header space is enough, and we change ppp header
* according to flags passed by pppd.
* This is not a callback, but just a helper function used in ppp_irnet_send()
*/
static inline struct sk_buff *
irnet_prepare_skb(irnet_socket * ap,
struct sk_buff * skb)
{
unsigned char * data;
int proto; /* PPP protocol */
int islcp; /* Protocol == LCP */
int needaddr; /* Need PPP address */
DENTER(PPP_TRACE, "(ap=0x%p, skb=0x%p)\n",
ap, skb);
/* Extract PPP protocol from the frame */
data = skb->data;
proto = (data[0] << 8) + data[1];
/* LCP packets with codes between 1 (configure-request)
* and 7 (code-reject) must be sent as though no options
* have been negotiated. */
islcp = (proto == PPP_LCP) && (1 <= data[2]) && (data[2] <= 7);
/* compress protocol field if option enabled */
if((data[0] == 0) && (ap->flags & SC_COMP_PROT) && (!islcp))
skb_pull(skb,1);
/* Check if we need address/control fields */
needaddr = 2*((ap->flags & SC_COMP_AC) == 0 || islcp);
/* Is the skb headroom large enough to contain all IrDA-headers? */
if((skb_headroom(skb) < (ap->max_header_size + needaddr)) ||
(skb_shared(skb)))
{
struct sk_buff * new_skb;
DEBUG(PPP_INFO, "Reallocating skb\n");
/* Create a new skb */
new_skb = skb_realloc_headroom(skb, ap->max_header_size + needaddr);
/* We have to free the original skb anyway */
dev_kfree_skb(skb);
/* Did the realloc succeed ? */
DABORT(new_skb == NULL, NULL, PPP_ERROR, "Could not realloc skb\n");
/* Use the new skb instead */
skb = new_skb;
}
/* prepend address/control fields if necessary */
if(needaddr)
{
skb_push(skb, 2);
skb->data[0] = PPP_ALLSTATIONS;
skb->data[1] = PPP_UI;
}
DEXIT(PPP_TRACE, "\n");
return skb;
}
/*------------------------------------------------------------------*/
/*
* Send a packet to the peer over the IrTTP connection.
* Returns 1 iff the packet was accepted.
* Returns 0 iff packet was not consumed.
* If the packet was not accepted, we will call ppp_output_wakeup
* at some later time to reactivate flow control in ppp_generic.
*/
static int
ppp_irnet_send(struct ppp_channel * chan,
struct sk_buff * skb)
{
irnet_socket * self = (struct irnet_socket *) chan->private;
int ret;
DENTER(PPP_TRACE, "(channel=0x%p, ap/self=0x%p)\n",
chan, self);
/* Check if things are somewhat valid... */
DASSERT(self != NULL, 0, PPP_ERROR, "Self is NULL !!!\n");
/* Check if we are connected */
if(!(test_bit(0, &self->ttp_open)))
{
#ifdef CONNECT_IN_SEND
/* Let's try to connect one more time... */
/* Note : we won't be connected after this call, but we should be
* ready for next packet... */
/* If we are already connecting, this will fail */
irda_irnet_connect(self);
#endif /* CONNECT_IN_SEND */
DEBUG(PPP_INFO, "IrTTP not ready ! (%ld-%ld)\n",
self->ttp_open, self->ttp_connect);
/* Note : we can either drop the packet or block the packet.
*
* Blocking the packet allow us a better connection time,
* because by calling ppp_output_wakeup() we can have
* ppp_generic resending the LCP request immediately to us,
* rather than waiting for one of pppd periodic transmission of
* LCP request.
*
* On the other hand, if we block all packet, all those periodic
* transmissions of pppd accumulate in ppp_generic, creating a
* backlog of LCP request. When we eventually connect later on,
* we have to transmit all this backlog before we can connect
* proper (if we don't timeout before).
*
* The current strategy is as follow :
* While we are attempting to connect, we block packets to get
* a better connection time.
* If we fail to connect, we drain the queue and start dropping packets
*/
#ifdef BLOCK_WHEN_CONNECT
/* If we are attempting to connect */
if(test_bit(0, &self->ttp_connect))
{
/* Blocking packet, ppp_generic will retry later */
return 0;
}
#endif /* BLOCK_WHEN_CONNECT */
/* Dropping packet, pppd will retry later */
dev_kfree_skb(skb);
return 1;
}
/* Check if the queue can accept any packet, otherwise block */
if(self->tx_flow != FLOW_START)
DRETURN(0, PPP_INFO, "IrTTP queue full (%d skbs)...\n",
skb_queue_len(&self->tsap->tx_queue));
/* Prepare ppp frame for transmission */
skb = irnet_prepare_skb(self, skb);
DABORT(skb == NULL, 1, PPP_ERROR, "Prepare skb for Tx failed.\n");
/* Send the packet to IrTTP */
ret = irttp_data_request(self->tsap, skb);
if(ret < 0)
{
/*
* > IrTTPs tx queue is full, so we just have to
* > drop the frame! You might think that we should
* > just return -1 and don't deallocate the frame,
* > but that is dangerous since it's possible that
* > we have replaced the original skb with a new
* > one with larger headroom, and that would really
* > confuse do_dev_queue_xmit() in dev.c! I have
* > tried :-) DB
* Correction : we verify the flow control above (self->tx_flow),
* so we come here only if IrTTP doesn't like the packet (empty,
* too large, IrTTP not connected). In those rare cases, it's ok
* to drop it, we don't want to see it here again...
* Jean II
*/
DERROR(PPP_ERROR, "IrTTP doesn't like this packet !!! (0x%X)\n", ret);
/* irttp_data_request already free the packet */
}
DEXIT(PPP_TRACE, "\n");
return 1; /* Packet has been consumed */
}
/*------------------------------------------------------------------*/
/*
* Take care of the ioctls that ppp_generic doesn't want to deal with...
* Note : we are also called from dev_irnet_ioctl().
*/
static int
ppp_irnet_ioctl(struct ppp_channel * chan,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = (struct irnet_socket *) chan->private;
int err;
int val;
u32 accm[8];
void __user *argp = (void __user *)arg;
DENTER(PPP_TRACE, "(channel=0x%p, ap=0x%p, cmd=0x%X)\n",
chan, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
err = -EFAULT;
switch(cmd)
{
/* PPP flags */
case PPPIOCGFLAGS:
val = ap->flags | ap->rbits;
if(put_user(val, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSFLAGS:
if(get_user(val, (int __user *) argp))
break;
ap->flags = val & ~SC_RCV_BITS;
ap->rbits = val & SC_RCV_BITS;
err = 0;
break;
/* Async map stuff - all dummy to please pppd */
case PPPIOCGASYNCMAP:
if(put_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSASYNCMAP:
if(get_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGRASYNCMAP:
if(put_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSRASYNCMAP:
if(get_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGXASYNCMAP:
if(copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
break;
err = 0;
break;
case PPPIOCSXASYNCMAP:
if(copy_from_user(accm, argp, sizeof(accm)))
break;
accm[2] &= ~0x40000000U; /* can't escape 0x5e */
accm[3] |= 0x60000000U; /* must escape 0x7d, 0x7e */
memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
err = 0;
break;
/* Max PPP frame size */
case PPPIOCGMRU:
if(put_user(ap->mru, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSMRU:
if(get_user(val, (int __user *) argp))
break;
if(val < PPP_MRU)
val = PPP_MRU;
ap->mru = val;
err = 0;
break;
default:
DEBUG(PPP_INFO, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOIOCTLCMD;
}
DEXIT(PPP_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** INITIALISATION **************************/
/*
* Module initialisation and all that jazz...
*/
/*------------------------------------------------------------------*/
/*
* Hook our device callbacks in the filesystem, to connect our code
* to /dev/irnet
*/
static inline int __init
ppp_irnet_init(void)
{
int err = 0;
DENTER(MODULE_TRACE, "()\n");
/* Allocate ourselves as a minor in the misc range */
err = misc_register(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
return err;
}
/*------------------------------------------------------------------*/
/*
* Cleanup at exit...
*/
static inline void __exit
ppp_irnet_cleanup(void)
{
DENTER(MODULE_TRACE, "()\n");
/* De-allocate /dev/irnet minor in misc range */
misc_deregister(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
}
/*------------------------------------------------------------------*/
/*
* Module main entry point
*/
static int __init
irnet_init(void)
{
int err;
/* Initialise both parts... */
err = irda_irnet_init();
if(!err)
err = ppp_irnet_init();
return err;
}
/*------------------------------------------------------------------*/
/*
* Module exit
*/
static void __exit
irnet_cleanup(void)
{
irda_irnet_cleanup();
ppp_irnet_cleanup();
}
/*------------------------------------------------------------------*/
/*
* Module magic
*/
module_init(irnet_init);
module_exit(irnet_cleanup);
MODULE_AUTHOR("Jean Tourrilhes <jt@hpl.hp.com>");
MODULE_DESCRIPTION("IrNET : Synchronous PPP over IrDA");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV(10, 187);
| gpl-2.0 |
GabrielL/linux | drivers/crypto/atmel-aes.c | 212 | 52327 | /*
* Cryptographic API.
*
* Support for ATMEL AES HW acceleration.
*
* Copyright (c) 2012 Eukréa Electromatique - ATMEL
* Author: Nicolas Royer <nicolas@eukrea.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.
*
* Some ideas are from omap-aes.c driver.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/hw_random.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>
#include <linux/of_device.h>
#include <linux/delay.h>
#include <linux/crypto.h>
#include <crypto/scatterwalk.h>
#include <crypto/algapi.h>
#include <crypto/aes.h>
#include <crypto/internal/aead.h>
#include <linux/platform_data/crypto-atmel.h>
#include <dt-bindings/dma/at91.h>
#include "atmel-aes-regs.h"
#define ATMEL_AES_PRIORITY 300
#define ATMEL_AES_BUFFER_ORDER 2
#define ATMEL_AES_BUFFER_SIZE (PAGE_SIZE << ATMEL_AES_BUFFER_ORDER)
#define CFB8_BLOCK_SIZE 1
#define CFB16_BLOCK_SIZE 2
#define CFB32_BLOCK_SIZE 4
#define CFB64_BLOCK_SIZE 8
#define SIZE_IN_WORDS(x) ((x) >> 2)
/* AES flags */
/* Reserve bits [18:16] [14:12] [1:0] for mode (same as for AES_MR) */
#define AES_FLAGS_ENCRYPT AES_MR_CYPHER_ENC
#define AES_FLAGS_GTAGEN AES_MR_GTAGEN
#define AES_FLAGS_OPMODE_MASK (AES_MR_OPMOD_MASK | AES_MR_CFBS_MASK)
#define AES_FLAGS_ECB AES_MR_OPMOD_ECB
#define AES_FLAGS_CBC AES_MR_OPMOD_CBC
#define AES_FLAGS_OFB AES_MR_OPMOD_OFB
#define AES_FLAGS_CFB128 (AES_MR_OPMOD_CFB | AES_MR_CFBS_128b)
#define AES_FLAGS_CFB64 (AES_MR_OPMOD_CFB | AES_MR_CFBS_64b)
#define AES_FLAGS_CFB32 (AES_MR_OPMOD_CFB | AES_MR_CFBS_32b)
#define AES_FLAGS_CFB16 (AES_MR_OPMOD_CFB | AES_MR_CFBS_16b)
#define AES_FLAGS_CFB8 (AES_MR_OPMOD_CFB | AES_MR_CFBS_8b)
#define AES_FLAGS_CTR AES_MR_OPMOD_CTR
#define AES_FLAGS_GCM AES_MR_OPMOD_GCM
#define AES_FLAGS_MODE_MASK (AES_FLAGS_OPMODE_MASK | \
AES_FLAGS_ENCRYPT | \
AES_FLAGS_GTAGEN)
#define AES_FLAGS_INIT BIT(2)
#define AES_FLAGS_BUSY BIT(3)
#define AES_FLAGS_DUMP_REG BIT(4)
#define AES_FLAGS_PERSISTENT (AES_FLAGS_INIT | AES_FLAGS_BUSY)
#define ATMEL_AES_QUEUE_LENGTH 50
#define ATMEL_AES_DMA_THRESHOLD 256
struct atmel_aes_caps {
bool has_dualbuff;
bool has_cfb64;
bool has_ctr32;
bool has_gcm;
u32 max_burst_size;
};
struct atmel_aes_dev;
typedef int (*atmel_aes_fn_t)(struct atmel_aes_dev *);
struct atmel_aes_base_ctx {
struct atmel_aes_dev *dd;
atmel_aes_fn_t start;
int keylen;
u32 key[AES_KEYSIZE_256 / sizeof(u32)];
u16 block_size;
};
struct atmel_aes_ctx {
struct atmel_aes_base_ctx base;
};
struct atmel_aes_ctr_ctx {
struct atmel_aes_base_ctx base;
u32 iv[AES_BLOCK_SIZE / sizeof(u32)];
size_t offset;
struct scatterlist src[2];
struct scatterlist dst[2];
};
struct atmel_aes_gcm_ctx {
struct atmel_aes_base_ctx base;
struct scatterlist src[2];
struct scatterlist dst[2];
u32 j0[AES_BLOCK_SIZE / sizeof(u32)];
u32 tag[AES_BLOCK_SIZE / sizeof(u32)];
u32 ghash[AES_BLOCK_SIZE / sizeof(u32)];
size_t textlen;
const u32 *ghash_in;
u32 *ghash_out;
atmel_aes_fn_t ghash_resume;
};
struct atmel_aes_reqctx {
unsigned long mode;
};
struct atmel_aes_dma {
struct dma_chan *chan;
struct scatterlist *sg;
int nents;
unsigned int remainder;
unsigned int sg_len;
};
struct atmel_aes_dev {
struct list_head list;
unsigned long phys_base;
void __iomem *io_base;
struct crypto_async_request *areq;
struct atmel_aes_base_ctx *ctx;
bool is_async;
atmel_aes_fn_t resume;
atmel_aes_fn_t cpu_transfer_complete;
struct device *dev;
struct clk *iclk;
int irq;
unsigned long flags;
spinlock_t lock;
struct crypto_queue queue;
struct tasklet_struct done_task;
struct tasklet_struct queue_task;
size_t total;
size_t datalen;
u32 *data;
struct atmel_aes_dma src;
struct atmel_aes_dma dst;
size_t buflen;
void *buf;
struct scatterlist aligned_sg;
struct scatterlist *real_dst;
struct atmel_aes_caps caps;
u32 hw_version;
};
struct atmel_aes_drv {
struct list_head dev_list;
spinlock_t lock;
};
static struct atmel_aes_drv atmel_aes = {
.dev_list = LIST_HEAD_INIT(atmel_aes.dev_list),
.lock = __SPIN_LOCK_UNLOCKED(atmel_aes.lock),
};
#ifdef VERBOSE_DEBUG
static const char *atmel_aes_reg_name(u32 offset, char *tmp, size_t sz)
{
switch (offset) {
case AES_CR:
return "CR";
case AES_MR:
return "MR";
case AES_ISR:
return "ISR";
case AES_IMR:
return "IMR";
case AES_IER:
return "IER";
case AES_IDR:
return "IDR";
case AES_KEYWR(0):
case AES_KEYWR(1):
case AES_KEYWR(2):
case AES_KEYWR(3):
case AES_KEYWR(4):
case AES_KEYWR(5):
case AES_KEYWR(6):
case AES_KEYWR(7):
snprintf(tmp, sz, "KEYWR[%u]", (offset - AES_KEYWR(0)) >> 2);
break;
case AES_IDATAR(0):
case AES_IDATAR(1):
case AES_IDATAR(2):
case AES_IDATAR(3):
snprintf(tmp, sz, "IDATAR[%u]", (offset - AES_IDATAR(0)) >> 2);
break;
case AES_ODATAR(0):
case AES_ODATAR(1):
case AES_ODATAR(2):
case AES_ODATAR(3):
snprintf(tmp, sz, "ODATAR[%u]", (offset - AES_ODATAR(0)) >> 2);
break;
case AES_IVR(0):
case AES_IVR(1):
case AES_IVR(2):
case AES_IVR(3):
snprintf(tmp, sz, "IVR[%u]", (offset - AES_IVR(0)) >> 2);
break;
case AES_AADLENR:
return "AADLENR";
case AES_CLENR:
return "CLENR";
case AES_GHASHR(0):
case AES_GHASHR(1):
case AES_GHASHR(2):
case AES_GHASHR(3):
snprintf(tmp, sz, "GHASHR[%u]", (offset - AES_GHASHR(0)) >> 2);
break;
case AES_TAGR(0):
case AES_TAGR(1):
case AES_TAGR(2):
case AES_TAGR(3):
snprintf(tmp, sz, "TAGR[%u]", (offset - AES_TAGR(0)) >> 2);
break;
case AES_CTRR:
return "CTRR";
case AES_GCMHR(0):
case AES_GCMHR(1):
case AES_GCMHR(2):
case AES_GCMHR(3):
snprintf(tmp, sz, "GCMHR[%u]", (offset - AES_GCMHR(0)) >> 2);
break;
default:
snprintf(tmp, sz, "0x%02x", offset);
break;
}
return tmp;
}
#endif /* VERBOSE_DEBUG */
/* Shared functions */
static inline u32 atmel_aes_read(struct atmel_aes_dev *dd, u32 offset)
{
u32 value = readl_relaxed(dd->io_base + offset);
#ifdef VERBOSE_DEBUG
if (dd->flags & AES_FLAGS_DUMP_REG) {
char tmp[16];
dev_vdbg(dd->dev, "read 0x%08x from %s\n", value,
atmel_aes_reg_name(offset, tmp, sizeof(tmp)));
}
#endif /* VERBOSE_DEBUG */
return value;
}
static inline void atmel_aes_write(struct atmel_aes_dev *dd,
u32 offset, u32 value)
{
#ifdef VERBOSE_DEBUG
if (dd->flags & AES_FLAGS_DUMP_REG) {
char tmp[16];
dev_vdbg(dd->dev, "write 0x%08x into %s\n", value,
atmel_aes_reg_name(offset, tmp));
}
#endif /* VERBOSE_DEBUG */
writel_relaxed(value, dd->io_base + offset);
}
static void atmel_aes_read_n(struct atmel_aes_dev *dd, u32 offset,
u32 *value, int count)
{
for (; count--; value++, offset += 4)
*value = atmel_aes_read(dd, offset);
}
static void atmel_aes_write_n(struct atmel_aes_dev *dd, u32 offset,
const u32 *value, int count)
{
for (; count--; value++, offset += 4)
atmel_aes_write(dd, offset, *value);
}
static inline void atmel_aes_read_block(struct atmel_aes_dev *dd, u32 offset,
u32 *value)
{
atmel_aes_read_n(dd, offset, value, SIZE_IN_WORDS(AES_BLOCK_SIZE));
}
static inline void atmel_aes_write_block(struct atmel_aes_dev *dd, u32 offset,
const u32 *value)
{
atmel_aes_write_n(dd, offset, value, SIZE_IN_WORDS(AES_BLOCK_SIZE));
}
static inline int atmel_aes_wait_for_data_ready(struct atmel_aes_dev *dd,
atmel_aes_fn_t resume)
{
u32 isr = atmel_aes_read(dd, AES_ISR);
if (unlikely(isr & AES_INT_DATARDY))
return resume(dd);
dd->resume = resume;
atmel_aes_write(dd, AES_IER, AES_INT_DATARDY);
return -EINPROGRESS;
}
static inline size_t atmel_aes_padlen(size_t len, size_t block_size)
{
len &= block_size - 1;
return len ? block_size - len : 0;
}
static struct atmel_aes_dev *atmel_aes_find_dev(struct atmel_aes_base_ctx *ctx)
{
struct atmel_aes_dev *aes_dd = NULL;
struct atmel_aes_dev *tmp;
spin_lock_bh(&atmel_aes.lock);
if (!ctx->dd) {
list_for_each_entry(tmp, &atmel_aes.dev_list, list) {
aes_dd = tmp;
break;
}
ctx->dd = aes_dd;
} else {
aes_dd = ctx->dd;
}
spin_unlock_bh(&atmel_aes.lock);
return aes_dd;
}
static int atmel_aes_hw_init(struct atmel_aes_dev *dd)
{
int err;
err = clk_enable(dd->iclk);
if (err)
return err;
if (!(dd->flags & AES_FLAGS_INIT)) {
atmel_aes_write(dd, AES_CR, AES_CR_SWRST);
atmel_aes_write(dd, AES_MR, 0xE << AES_MR_CKEY_OFFSET);
dd->flags |= AES_FLAGS_INIT;
}
return 0;
}
static inline unsigned int atmel_aes_get_version(struct atmel_aes_dev *dd)
{
return atmel_aes_read(dd, AES_HW_VERSION) & 0x00000fff;
}
static int atmel_aes_hw_version_init(struct atmel_aes_dev *dd)
{
int err;
err = atmel_aes_hw_init(dd);
if (err)
return err;
dd->hw_version = atmel_aes_get_version(dd);
dev_info(dd->dev, "version: 0x%x\n", dd->hw_version);
clk_disable(dd->iclk);
return 0;
}
static inline void atmel_aes_set_mode(struct atmel_aes_dev *dd,
const struct atmel_aes_reqctx *rctx)
{
/* Clear all but persistent flags and set request flags. */
dd->flags = (dd->flags & AES_FLAGS_PERSISTENT) | rctx->mode;
}
static inline bool atmel_aes_is_encrypt(const struct atmel_aes_dev *dd)
{
return (dd->flags & AES_FLAGS_ENCRYPT);
}
static inline int atmel_aes_complete(struct atmel_aes_dev *dd, int err)
{
clk_disable(dd->iclk);
dd->flags &= ~AES_FLAGS_BUSY;
if (dd->is_async)
dd->areq->complete(dd->areq, err);
tasklet_schedule(&dd->queue_task);
return err;
}
static void atmel_aes_write_ctrl(struct atmel_aes_dev *dd, bool use_dma,
const u32 *iv)
{
u32 valmr = 0;
/* MR register must be set before IV registers */
if (dd->ctx->keylen == AES_KEYSIZE_128)
valmr |= AES_MR_KEYSIZE_128;
else if (dd->ctx->keylen == AES_KEYSIZE_192)
valmr |= AES_MR_KEYSIZE_192;
else
valmr |= AES_MR_KEYSIZE_256;
valmr |= dd->flags & AES_FLAGS_MODE_MASK;
if (use_dma) {
valmr |= AES_MR_SMOD_IDATAR0;
if (dd->caps.has_dualbuff)
valmr |= AES_MR_DUALBUFF;
} else {
valmr |= AES_MR_SMOD_AUTO;
}
atmel_aes_write(dd, AES_MR, valmr);
atmel_aes_write_n(dd, AES_KEYWR(0), dd->ctx->key,
SIZE_IN_WORDS(dd->ctx->keylen));
if (iv && (valmr & AES_MR_OPMOD_MASK) != AES_MR_OPMOD_ECB)
atmel_aes_write_block(dd, AES_IVR(0), iv);
}
/* CPU transfer */
static int atmel_aes_cpu_transfer(struct atmel_aes_dev *dd)
{
int err = 0;
u32 isr;
for (;;) {
atmel_aes_read_block(dd, AES_ODATAR(0), dd->data);
dd->data += 4;
dd->datalen -= AES_BLOCK_SIZE;
if (dd->datalen < AES_BLOCK_SIZE)
break;
atmel_aes_write_block(dd, AES_IDATAR(0), dd->data);
isr = atmel_aes_read(dd, AES_ISR);
if (!(isr & AES_INT_DATARDY)) {
dd->resume = atmel_aes_cpu_transfer;
atmel_aes_write(dd, AES_IER, AES_INT_DATARDY);
return -EINPROGRESS;
}
}
if (!sg_copy_from_buffer(dd->real_dst, sg_nents(dd->real_dst),
dd->buf, dd->total))
err = -EINVAL;
if (err)
return atmel_aes_complete(dd, err);
return dd->cpu_transfer_complete(dd);
}
static int atmel_aes_cpu_start(struct atmel_aes_dev *dd,
struct scatterlist *src,
struct scatterlist *dst,
size_t len,
atmel_aes_fn_t resume)
{
size_t padlen = atmel_aes_padlen(len, AES_BLOCK_SIZE);
if (unlikely(len == 0))
return -EINVAL;
sg_copy_to_buffer(src, sg_nents(src), dd->buf, len);
dd->total = len;
dd->real_dst = dst;
dd->cpu_transfer_complete = resume;
dd->datalen = len + padlen;
dd->data = (u32 *)dd->buf;
atmel_aes_write_block(dd, AES_IDATAR(0), dd->data);
return atmel_aes_wait_for_data_ready(dd, atmel_aes_cpu_transfer);
}
/* DMA transfer */
static void atmel_aes_dma_callback(void *data);
static bool atmel_aes_check_aligned(struct atmel_aes_dev *dd,
struct scatterlist *sg,
size_t len,
struct atmel_aes_dma *dma)
{
int nents;
if (!IS_ALIGNED(len, dd->ctx->block_size))
return false;
for (nents = 0; sg; sg = sg_next(sg), ++nents) {
if (!IS_ALIGNED(sg->offset, sizeof(u32)))
return false;
if (len <= sg->length) {
if (!IS_ALIGNED(len, dd->ctx->block_size))
return false;
dma->nents = nents+1;
dma->remainder = sg->length - len;
sg->length = len;
return true;
}
if (!IS_ALIGNED(sg->length, dd->ctx->block_size))
return false;
len -= sg->length;
}
return false;
}
static inline void atmel_aes_restore_sg(const struct atmel_aes_dma *dma)
{
struct scatterlist *sg = dma->sg;
int nents = dma->nents;
if (!dma->remainder)
return;
while (--nents > 0 && sg)
sg = sg_next(sg);
if (!sg)
return;
sg->length += dma->remainder;
}
static int atmel_aes_map(struct atmel_aes_dev *dd,
struct scatterlist *src,
struct scatterlist *dst,
size_t len)
{
bool src_aligned, dst_aligned;
size_t padlen;
dd->total = len;
dd->src.sg = src;
dd->dst.sg = dst;
dd->real_dst = dst;
src_aligned = atmel_aes_check_aligned(dd, src, len, &dd->src);
if (src == dst)
dst_aligned = src_aligned;
else
dst_aligned = atmel_aes_check_aligned(dd, dst, len, &dd->dst);
if (!src_aligned || !dst_aligned) {
padlen = atmel_aes_padlen(len, dd->ctx->block_size);
if (dd->buflen < len + padlen)
return -ENOMEM;
if (!src_aligned) {
sg_copy_to_buffer(src, sg_nents(src), dd->buf, len);
dd->src.sg = &dd->aligned_sg;
dd->src.nents = 1;
dd->src.remainder = 0;
}
if (!dst_aligned) {
dd->dst.sg = &dd->aligned_sg;
dd->dst.nents = 1;
dd->dst.remainder = 0;
}
sg_init_table(&dd->aligned_sg, 1);
sg_set_buf(&dd->aligned_sg, dd->buf, len + padlen);
}
if (dd->src.sg == dd->dst.sg) {
dd->src.sg_len = dma_map_sg(dd->dev, dd->src.sg, dd->src.nents,
DMA_BIDIRECTIONAL);
dd->dst.sg_len = dd->src.sg_len;
if (!dd->src.sg_len)
return -EFAULT;
} else {
dd->src.sg_len = dma_map_sg(dd->dev, dd->src.sg, dd->src.nents,
DMA_TO_DEVICE);
if (!dd->src.sg_len)
return -EFAULT;
dd->dst.sg_len = dma_map_sg(dd->dev, dd->dst.sg, dd->dst.nents,
DMA_FROM_DEVICE);
if (!dd->dst.sg_len) {
dma_unmap_sg(dd->dev, dd->src.sg, dd->src.nents,
DMA_TO_DEVICE);
return -EFAULT;
}
}
return 0;
}
static void atmel_aes_unmap(struct atmel_aes_dev *dd)
{
if (dd->src.sg == dd->dst.sg) {
dma_unmap_sg(dd->dev, dd->src.sg, dd->src.nents,
DMA_BIDIRECTIONAL);
if (dd->src.sg != &dd->aligned_sg)
atmel_aes_restore_sg(&dd->src);
} else {
dma_unmap_sg(dd->dev, dd->dst.sg, dd->dst.nents,
DMA_FROM_DEVICE);
if (dd->dst.sg != &dd->aligned_sg)
atmel_aes_restore_sg(&dd->dst);
dma_unmap_sg(dd->dev, dd->src.sg, dd->src.nents,
DMA_TO_DEVICE);
if (dd->src.sg != &dd->aligned_sg)
atmel_aes_restore_sg(&dd->src);
}
if (dd->dst.sg == &dd->aligned_sg)
sg_copy_from_buffer(dd->real_dst, sg_nents(dd->real_dst),
dd->buf, dd->total);
}
static int atmel_aes_dma_transfer_start(struct atmel_aes_dev *dd,
enum dma_slave_buswidth addr_width,
enum dma_transfer_direction dir,
u32 maxburst)
{
struct dma_async_tx_descriptor *desc;
struct dma_slave_config config;
dma_async_tx_callback callback;
struct atmel_aes_dma *dma;
int err;
memset(&config, 0, sizeof(config));
config.direction = dir;
config.src_addr_width = addr_width;
config.dst_addr_width = addr_width;
config.src_maxburst = maxburst;
config.dst_maxburst = maxburst;
switch (dir) {
case DMA_MEM_TO_DEV:
dma = &dd->src;
callback = NULL;
config.dst_addr = dd->phys_base + AES_IDATAR(0);
break;
case DMA_DEV_TO_MEM:
dma = &dd->dst;
callback = atmel_aes_dma_callback;
config.src_addr = dd->phys_base + AES_ODATAR(0);
break;
default:
return -EINVAL;
}
err = dmaengine_slave_config(dma->chan, &config);
if (err)
return err;
desc = dmaengine_prep_slave_sg(dma->chan, dma->sg, dma->sg_len, dir,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc)
return -ENOMEM;
desc->callback = callback;
desc->callback_param = dd;
dmaengine_submit(desc);
dma_async_issue_pending(dma->chan);
return 0;
}
static void atmel_aes_dma_transfer_stop(struct atmel_aes_dev *dd,
enum dma_transfer_direction dir)
{
struct atmel_aes_dma *dma;
switch (dir) {
case DMA_MEM_TO_DEV:
dma = &dd->src;
break;
case DMA_DEV_TO_MEM:
dma = &dd->dst;
break;
default:
return;
}
dmaengine_terminate_all(dma->chan);
}
static int atmel_aes_dma_start(struct atmel_aes_dev *dd,
struct scatterlist *src,
struct scatterlist *dst,
size_t len,
atmel_aes_fn_t resume)
{
enum dma_slave_buswidth addr_width;
u32 maxburst;
int err;
switch (dd->ctx->block_size) {
case CFB8_BLOCK_SIZE:
addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
maxburst = 1;
break;
case CFB16_BLOCK_SIZE:
addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
maxburst = 1;
break;
case CFB32_BLOCK_SIZE:
case CFB64_BLOCK_SIZE:
addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
maxburst = 1;
break;
case AES_BLOCK_SIZE:
addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
maxburst = dd->caps.max_burst_size;
break;
default:
err = -EINVAL;
goto exit;
}
err = atmel_aes_map(dd, src, dst, len);
if (err)
goto exit;
dd->resume = resume;
/* Set output DMA transfer first */
err = atmel_aes_dma_transfer_start(dd, addr_width, DMA_DEV_TO_MEM,
maxburst);
if (err)
goto unmap;
/* Then set input DMA transfer */
err = atmel_aes_dma_transfer_start(dd, addr_width, DMA_MEM_TO_DEV,
maxburst);
if (err)
goto output_transfer_stop;
return -EINPROGRESS;
output_transfer_stop:
atmel_aes_dma_transfer_stop(dd, DMA_DEV_TO_MEM);
unmap:
atmel_aes_unmap(dd);
exit:
return atmel_aes_complete(dd, err);
}
static void atmel_aes_dma_stop(struct atmel_aes_dev *dd)
{
atmel_aes_dma_transfer_stop(dd, DMA_MEM_TO_DEV);
atmel_aes_dma_transfer_stop(dd, DMA_DEV_TO_MEM);
atmel_aes_unmap(dd);
}
static void atmel_aes_dma_callback(void *data)
{
struct atmel_aes_dev *dd = data;
atmel_aes_dma_stop(dd);
dd->is_async = true;
(void)dd->resume(dd);
}
static int atmel_aes_handle_queue(struct atmel_aes_dev *dd,
struct crypto_async_request *new_areq)
{
struct crypto_async_request *areq, *backlog;
struct atmel_aes_base_ctx *ctx;
unsigned long flags;
int err, ret = 0;
spin_lock_irqsave(&dd->lock, flags);
if (new_areq)
ret = crypto_enqueue_request(&dd->queue, new_areq);
if (dd->flags & AES_FLAGS_BUSY) {
spin_unlock_irqrestore(&dd->lock, flags);
return ret;
}
backlog = crypto_get_backlog(&dd->queue);
areq = crypto_dequeue_request(&dd->queue);
if (areq)
dd->flags |= AES_FLAGS_BUSY;
spin_unlock_irqrestore(&dd->lock, flags);
if (!areq)
return ret;
if (backlog)
backlog->complete(backlog, -EINPROGRESS);
ctx = crypto_tfm_ctx(areq->tfm);
dd->areq = areq;
dd->ctx = ctx;
dd->is_async = (areq != new_areq);
err = ctx->start(dd);
return (dd->is_async) ? ret : err;
}
/* AES async block ciphers */
static int atmel_aes_transfer_complete(struct atmel_aes_dev *dd)
{
return atmel_aes_complete(dd, 0);
}
static int atmel_aes_start(struct atmel_aes_dev *dd)
{
struct ablkcipher_request *req = ablkcipher_request_cast(dd->areq);
struct atmel_aes_reqctx *rctx = ablkcipher_request_ctx(req);
bool use_dma = (req->nbytes >= ATMEL_AES_DMA_THRESHOLD ||
dd->ctx->block_size != AES_BLOCK_SIZE);
int err;
atmel_aes_set_mode(dd, rctx);
err = atmel_aes_hw_init(dd);
if (err)
return atmel_aes_complete(dd, err);
atmel_aes_write_ctrl(dd, use_dma, req->info);
if (use_dma)
return atmel_aes_dma_start(dd, req->src, req->dst, req->nbytes,
atmel_aes_transfer_complete);
return atmel_aes_cpu_start(dd, req->src, req->dst, req->nbytes,
atmel_aes_transfer_complete);
}
static inline struct atmel_aes_ctr_ctx *
atmel_aes_ctr_ctx_cast(struct atmel_aes_base_ctx *ctx)
{
return container_of(ctx, struct atmel_aes_ctr_ctx, base);
}
static int atmel_aes_ctr_transfer(struct atmel_aes_dev *dd)
{
struct atmel_aes_ctr_ctx *ctx = atmel_aes_ctr_ctx_cast(dd->ctx);
struct ablkcipher_request *req = ablkcipher_request_cast(dd->areq);
struct scatterlist *src, *dst;
u32 ctr, blocks;
size_t datalen;
bool use_dma, fragmented = false;
/* Check for transfer completion. */
ctx->offset += dd->total;
if (ctx->offset >= req->nbytes)
return atmel_aes_transfer_complete(dd);
/* Compute data length. */
datalen = req->nbytes - ctx->offset;
blocks = DIV_ROUND_UP(datalen, AES_BLOCK_SIZE);
ctr = be32_to_cpu(ctx->iv[3]);
if (dd->caps.has_ctr32) {
/* Check 32bit counter overflow. */
u32 start = ctr;
u32 end = start + blocks - 1;
if (end < start) {
ctr |= 0xffffffff;
datalen = AES_BLOCK_SIZE * -start;
fragmented = true;
}
} else {
/* Check 16bit counter overflow. */
u16 start = ctr & 0xffff;
u16 end = start + (u16)blocks - 1;
if (blocks >> 16 || end < start) {
ctr |= 0xffff;
datalen = AES_BLOCK_SIZE * (0x10000-start);
fragmented = true;
}
}
use_dma = (datalen >= ATMEL_AES_DMA_THRESHOLD);
/* Jump to offset. */
src = scatterwalk_ffwd(ctx->src, req->src, ctx->offset);
dst = ((req->src == req->dst) ? src :
scatterwalk_ffwd(ctx->dst, req->dst, ctx->offset));
/* Configure hardware. */
atmel_aes_write_ctrl(dd, use_dma, ctx->iv);
if (unlikely(fragmented)) {
/*
* Increment the counter manually to cope with the hardware
* counter overflow.
*/
ctx->iv[3] = cpu_to_be32(ctr);
crypto_inc((u8 *)ctx->iv, AES_BLOCK_SIZE);
}
if (use_dma)
return atmel_aes_dma_start(dd, src, dst, datalen,
atmel_aes_ctr_transfer);
return atmel_aes_cpu_start(dd, src, dst, datalen,
atmel_aes_ctr_transfer);
}
static int atmel_aes_ctr_start(struct atmel_aes_dev *dd)
{
struct atmel_aes_ctr_ctx *ctx = atmel_aes_ctr_ctx_cast(dd->ctx);
struct ablkcipher_request *req = ablkcipher_request_cast(dd->areq);
struct atmel_aes_reqctx *rctx = ablkcipher_request_ctx(req);
int err;
atmel_aes_set_mode(dd, rctx);
err = atmel_aes_hw_init(dd);
if (err)
return atmel_aes_complete(dd, err);
memcpy(ctx->iv, req->info, AES_BLOCK_SIZE);
ctx->offset = 0;
dd->total = 0;
return atmel_aes_ctr_transfer(dd);
}
static int atmel_aes_crypt(struct ablkcipher_request *req, unsigned long mode)
{
struct atmel_aes_base_ctx *ctx;
struct atmel_aes_reqctx *rctx;
struct atmel_aes_dev *dd;
ctx = crypto_ablkcipher_ctx(crypto_ablkcipher_reqtfm(req));
switch (mode & AES_FLAGS_OPMODE_MASK) {
case AES_FLAGS_CFB8:
ctx->block_size = CFB8_BLOCK_SIZE;
break;
case AES_FLAGS_CFB16:
ctx->block_size = CFB16_BLOCK_SIZE;
break;
case AES_FLAGS_CFB32:
ctx->block_size = CFB32_BLOCK_SIZE;
break;
case AES_FLAGS_CFB64:
ctx->block_size = CFB64_BLOCK_SIZE;
break;
default:
ctx->block_size = AES_BLOCK_SIZE;
break;
}
dd = atmel_aes_find_dev(ctx);
if (!dd)
return -ENODEV;
rctx = ablkcipher_request_ctx(req);
rctx->mode = mode;
return atmel_aes_handle_queue(dd, &req->base);
}
static int atmel_aes_setkey(struct crypto_ablkcipher *tfm, const u8 *key,
unsigned int keylen)
{
struct atmel_aes_base_ctx *ctx = crypto_ablkcipher_ctx(tfm);
if (keylen != AES_KEYSIZE_128 &&
keylen != AES_KEYSIZE_192 &&
keylen != AES_KEYSIZE_256) {
crypto_ablkcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
memcpy(ctx->key, key, keylen);
ctx->keylen = keylen;
return 0;
}
static int atmel_aes_ecb_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_ECB | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_ecb_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_ECB);
}
static int atmel_aes_cbc_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CBC | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cbc_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CBC);
}
static int atmel_aes_ofb_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_OFB | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_ofb_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_OFB);
}
static int atmel_aes_cfb_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB128 | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cfb_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB128);
}
static int atmel_aes_cfb64_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB64 | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cfb64_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB64);
}
static int atmel_aes_cfb32_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB32 | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cfb32_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB32);
}
static int atmel_aes_cfb16_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB16 | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cfb16_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB16);
}
static int atmel_aes_cfb8_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB8 | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_cfb8_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CFB8);
}
static int atmel_aes_ctr_encrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CTR | AES_FLAGS_ENCRYPT);
}
static int atmel_aes_ctr_decrypt(struct ablkcipher_request *req)
{
return atmel_aes_crypt(req, AES_FLAGS_CTR);
}
static int atmel_aes_cra_init(struct crypto_tfm *tfm)
{
struct atmel_aes_ctx *ctx = crypto_tfm_ctx(tfm);
tfm->crt_ablkcipher.reqsize = sizeof(struct atmel_aes_reqctx);
ctx->base.start = atmel_aes_start;
return 0;
}
static int atmel_aes_ctr_cra_init(struct crypto_tfm *tfm)
{
struct atmel_aes_ctx *ctx = crypto_tfm_ctx(tfm);
tfm->crt_ablkcipher.reqsize = sizeof(struct atmel_aes_reqctx);
ctx->base.start = atmel_aes_ctr_start;
return 0;
}
static void atmel_aes_cra_exit(struct crypto_tfm *tfm)
{
}
static struct crypto_alg aes_algs[] = {
{
.cra_name = "ecb(aes)",
.cra_driver_name = "atmel-ecb-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0xf,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_ecb_encrypt,
.decrypt = atmel_aes_ecb_decrypt,
}
},
{
.cra_name = "cbc(aes)",
.cra_driver_name = "atmel-cbc-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0xf,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cbc_encrypt,
.decrypt = atmel_aes_cbc_decrypt,
}
},
{
.cra_name = "ofb(aes)",
.cra_driver_name = "atmel-ofb-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0xf,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_ofb_encrypt,
.decrypt = atmel_aes_ofb_decrypt,
}
},
{
.cra_name = "cfb(aes)",
.cra_driver_name = "atmel-cfb-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0xf,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cfb_encrypt,
.decrypt = atmel_aes_cfb_decrypt,
}
},
{
.cra_name = "cfb32(aes)",
.cra_driver_name = "atmel-cfb32-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CFB32_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0x3,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cfb32_encrypt,
.decrypt = atmel_aes_cfb32_decrypt,
}
},
{
.cra_name = "cfb16(aes)",
.cra_driver_name = "atmel-cfb16-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CFB16_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0x1,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cfb16_encrypt,
.decrypt = atmel_aes_cfb16_decrypt,
}
},
{
.cra_name = "cfb8(aes)",
.cra_driver_name = "atmel-cfb8-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CFB8_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0x0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cfb8_encrypt,
.decrypt = atmel_aes_cfb8_decrypt,
}
},
{
.cra_name = "ctr(aes)",
.cra_driver_name = "atmel-ctr-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct atmel_aes_ctr_ctx),
.cra_alignmask = 0xf,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_ctr_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_ctr_encrypt,
.decrypt = atmel_aes_ctr_decrypt,
}
},
};
static struct crypto_alg aes_cfb64_alg = {
.cra_name = "cfb64(aes)",
.cra_driver_name = "atmel-cfb64-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CFB64_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct atmel_aes_ctx),
.cra_alignmask = 0x7,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = atmel_aes_cra_init,
.cra_exit = atmel_aes_cra_exit,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = atmel_aes_setkey,
.encrypt = atmel_aes_cfb64_encrypt,
.decrypt = atmel_aes_cfb64_decrypt,
}
};
/* gcm aead functions */
static int atmel_aes_gcm_ghash(struct atmel_aes_dev *dd,
const u32 *data, size_t datalen,
const u32 *ghash_in, u32 *ghash_out,
atmel_aes_fn_t resume);
static int atmel_aes_gcm_ghash_init(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_ghash_finalize(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_start(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_process(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_length(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_data(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_tag_init(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_tag(struct atmel_aes_dev *dd);
static int atmel_aes_gcm_finalize(struct atmel_aes_dev *dd);
static inline struct atmel_aes_gcm_ctx *
atmel_aes_gcm_ctx_cast(struct atmel_aes_base_ctx *ctx)
{
return container_of(ctx, struct atmel_aes_gcm_ctx, base);
}
static int atmel_aes_gcm_ghash(struct atmel_aes_dev *dd,
const u32 *data, size_t datalen,
const u32 *ghash_in, u32 *ghash_out,
atmel_aes_fn_t resume)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
dd->data = (u32 *)data;
dd->datalen = datalen;
ctx->ghash_in = ghash_in;
ctx->ghash_out = ghash_out;
ctx->ghash_resume = resume;
atmel_aes_write_ctrl(dd, false, NULL);
return atmel_aes_wait_for_data_ready(dd, atmel_aes_gcm_ghash_init);
}
static int atmel_aes_gcm_ghash_init(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
/* Set the data length. */
atmel_aes_write(dd, AES_AADLENR, dd->total);
atmel_aes_write(dd, AES_CLENR, 0);
/* If needed, overwrite the GCM Intermediate Hash Word Registers */
if (ctx->ghash_in)
atmel_aes_write_block(dd, AES_GHASHR(0), ctx->ghash_in);
return atmel_aes_gcm_ghash_finalize(dd);
}
static int atmel_aes_gcm_ghash_finalize(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
u32 isr;
/* Write data into the Input Data Registers. */
while (dd->datalen > 0) {
atmel_aes_write_block(dd, AES_IDATAR(0), dd->data);
dd->data += 4;
dd->datalen -= AES_BLOCK_SIZE;
isr = atmel_aes_read(dd, AES_ISR);
if (!(isr & AES_INT_DATARDY)) {
dd->resume = atmel_aes_gcm_ghash_finalize;
atmel_aes_write(dd, AES_IER, AES_INT_DATARDY);
return -EINPROGRESS;
}
}
/* Read the computed hash from GHASHRx. */
atmel_aes_read_block(dd, AES_GHASHR(0), ctx->ghash_out);
return ctx->ghash_resume(dd);
}
static int atmel_aes_gcm_start(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
struct atmel_aes_reqctx *rctx = aead_request_ctx(req);
size_t ivsize = crypto_aead_ivsize(tfm);
size_t datalen, padlen;
const void *iv = req->iv;
u8 *data = dd->buf;
int err;
atmel_aes_set_mode(dd, rctx);
err = atmel_aes_hw_init(dd);
if (err)
return atmel_aes_complete(dd, err);
if (likely(ivsize == 12)) {
memcpy(ctx->j0, iv, ivsize);
ctx->j0[3] = cpu_to_be32(1);
return atmel_aes_gcm_process(dd);
}
padlen = atmel_aes_padlen(ivsize, AES_BLOCK_SIZE);
datalen = ivsize + padlen + AES_BLOCK_SIZE;
if (datalen > dd->buflen)
return atmel_aes_complete(dd, -EINVAL);
memcpy(data, iv, ivsize);
memset(data + ivsize, 0, padlen + sizeof(u64));
((u64 *)(data + datalen))[-1] = cpu_to_be64(ivsize * 8);
return atmel_aes_gcm_ghash(dd, (const u32 *)data, datalen,
NULL, ctx->j0, atmel_aes_gcm_process);
}
static int atmel_aes_gcm_process(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
bool enc = atmel_aes_is_encrypt(dd);
u32 authsize;
/* Compute text length. */
authsize = crypto_aead_authsize(tfm);
ctx->textlen = req->cryptlen - (enc ? 0 : authsize);
/*
* According to tcrypt test suite, the GCM Automatic Tag Generation
* fails when both the message and its associated data are empty.
*/
if (likely(req->assoclen != 0 || ctx->textlen != 0))
dd->flags |= AES_FLAGS_GTAGEN;
atmel_aes_write_ctrl(dd, false, NULL);
return atmel_aes_wait_for_data_ready(dd, atmel_aes_gcm_length);
}
static int atmel_aes_gcm_length(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
u32 j0_lsw, *j0 = ctx->j0;
size_t padlen;
/* Write incr32(J0) into IV. */
j0_lsw = j0[3];
j0[3] = cpu_to_be32(be32_to_cpu(j0[3]) + 1);
atmel_aes_write_block(dd, AES_IVR(0), j0);
j0[3] = j0_lsw;
/* Set aad and text lengths. */
atmel_aes_write(dd, AES_AADLENR, req->assoclen);
atmel_aes_write(dd, AES_CLENR, ctx->textlen);
/* Check whether AAD are present. */
if (unlikely(req->assoclen == 0)) {
dd->datalen = 0;
return atmel_aes_gcm_data(dd);
}
/* Copy assoc data and add padding. */
padlen = atmel_aes_padlen(req->assoclen, AES_BLOCK_SIZE);
if (unlikely(req->assoclen + padlen > dd->buflen))
return atmel_aes_complete(dd, -EINVAL);
sg_copy_to_buffer(req->src, sg_nents(req->src), dd->buf, req->assoclen);
/* Write assoc data into the Input Data register. */
dd->data = (u32 *)dd->buf;
dd->datalen = req->assoclen + padlen;
return atmel_aes_gcm_data(dd);
}
static int atmel_aes_gcm_data(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
bool use_dma = (ctx->textlen >= ATMEL_AES_DMA_THRESHOLD);
struct scatterlist *src, *dst;
u32 isr, mr;
/* Write AAD first. */
while (dd->datalen > 0) {
atmel_aes_write_block(dd, AES_IDATAR(0), dd->data);
dd->data += 4;
dd->datalen -= AES_BLOCK_SIZE;
isr = atmel_aes_read(dd, AES_ISR);
if (!(isr & AES_INT_DATARDY)) {
dd->resume = atmel_aes_gcm_data;
atmel_aes_write(dd, AES_IER, AES_INT_DATARDY);
return -EINPROGRESS;
}
}
/* GMAC only. */
if (unlikely(ctx->textlen == 0))
return atmel_aes_gcm_tag_init(dd);
/* Prepare src and dst scatter lists to transfer cipher/plain texts */
src = scatterwalk_ffwd(ctx->src, req->src, req->assoclen);
dst = ((req->src == req->dst) ? src :
scatterwalk_ffwd(ctx->dst, req->dst, req->assoclen));
if (use_dma) {
/* Update the Mode Register for DMA transfers. */
mr = atmel_aes_read(dd, AES_MR);
mr &= ~(AES_MR_SMOD_MASK | AES_MR_DUALBUFF);
mr |= AES_MR_SMOD_IDATAR0;
if (dd->caps.has_dualbuff)
mr |= AES_MR_DUALBUFF;
atmel_aes_write(dd, AES_MR, mr);
return atmel_aes_dma_start(dd, src, dst, ctx->textlen,
atmel_aes_gcm_tag_init);
}
return atmel_aes_cpu_start(dd, src, dst, ctx->textlen,
atmel_aes_gcm_tag_init);
}
static int atmel_aes_gcm_tag_init(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
u64 *data = dd->buf;
if (likely(dd->flags & AES_FLAGS_GTAGEN)) {
if (!(atmel_aes_read(dd, AES_ISR) & AES_INT_TAGRDY)) {
dd->resume = atmel_aes_gcm_tag_init;
atmel_aes_write(dd, AES_IER, AES_INT_TAGRDY);
return -EINPROGRESS;
}
return atmel_aes_gcm_finalize(dd);
}
/* Read the GCM Intermediate Hash Word Registers. */
atmel_aes_read_block(dd, AES_GHASHR(0), ctx->ghash);
data[0] = cpu_to_be64(req->assoclen * 8);
data[1] = cpu_to_be64(ctx->textlen * 8);
return atmel_aes_gcm_ghash(dd, (const u32 *)data, AES_BLOCK_SIZE,
ctx->ghash, ctx->ghash, atmel_aes_gcm_tag);
}
static int atmel_aes_gcm_tag(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
unsigned long flags;
/*
* Change mode to CTR to complete the tag generation.
* Use J0 as Initialization Vector.
*/
flags = dd->flags;
dd->flags &= ~(AES_FLAGS_OPMODE_MASK | AES_FLAGS_GTAGEN);
dd->flags |= AES_FLAGS_CTR;
atmel_aes_write_ctrl(dd, false, ctx->j0);
dd->flags = flags;
atmel_aes_write_block(dd, AES_IDATAR(0), ctx->ghash);
return atmel_aes_wait_for_data_ready(dd, atmel_aes_gcm_finalize);
}
static int atmel_aes_gcm_finalize(struct atmel_aes_dev *dd)
{
struct atmel_aes_gcm_ctx *ctx = atmel_aes_gcm_ctx_cast(dd->ctx);
struct aead_request *req = aead_request_cast(dd->areq);
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
bool enc = atmel_aes_is_encrypt(dd);
u32 offset, authsize, itag[4], *otag = ctx->tag;
int err;
/* Read the computed tag. */
if (likely(dd->flags & AES_FLAGS_GTAGEN))
atmel_aes_read_block(dd, AES_TAGR(0), ctx->tag);
else
atmel_aes_read_block(dd, AES_ODATAR(0), ctx->tag);
offset = req->assoclen + ctx->textlen;
authsize = crypto_aead_authsize(tfm);
if (enc) {
scatterwalk_map_and_copy(otag, req->dst, offset, authsize, 1);
err = 0;
} else {
scatterwalk_map_and_copy(itag, req->src, offset, authsize, 0);
err = crypto_memneq(itag, otag, authsize) ? -EBADMSG : 0;
}
return atmel_aes_complete(dd, err);
}
static int atmel_aes_gcm_crypt(struct aead_request *req,
unsigned long mode)
{
struct atmel_aes_base_ctx *ctx;
struct atmel_aes_reqctx *rctx;
struct atmel_aes_dev *dd;
ctx = crypto_aead_ctx(crypto_aead_reqtfm(req));
ctx->block_size = AES_BLOCK_SIZE;
dd = atmel_aes_find_dev(ctx);
if (!dd)
return -ENODEV;
rctx = aead_request_ctx(req);
rctx->mode = AES_FLAGS_GCM | mode;
return atmel_aes_handle_queue(dd, &req->base);
}
static int atmel_aes_gcm_setkey(struct crypto_aead *tfm, const u8 *key,
unsigned int keylen)
{
struct atmel_aes_base_ctx *ctx = crypto_aead_ctx(tfm);
if (keylen != AES_KEYSIZE_256 &&
keylen != AES_KEYSIZE_192 &&
keylen != AES_KEYSIZE_128) {
crypto_aead_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
memcpy(ctx->key, key, keylen);
ctx->keylen = keylen;
return 0;
}
static int atmel_aes_gcm_setauthsize(struct crypto_aead *tfm,
unsigned int authsize)
{
/* Same as crypto_gcm_authsize() from crypto/gcm.c */
switch (authsize) {
case 4:
case 8:
case 12:
case 13:
case 14:
case 15:
case 16:
break;
default:
return -EINVAL;
}
return 0;
}
static int atmel_aes_gcm_encrypt(struct aead_request *req)
{
return atmel_aes_gcm_crypt(req, AES_FLAGS_ENCRYPT);
}
static int atmel_aes_gcm_decrypt(struct aead_request *req)
{
return atmel_aes_gcm_crypt(req, 0);
}
static int atmel_aes_gcm_init(struct crypto_aead *tfm)
{
struct atmel_aes_gcm_ctx *ctx = crypto_aead_ctx(tfm);
crypto_aead_set_reqsize(tfm, sizeof(struct atmel_aes_reqctx));
ctx->base.start = atmel_aes_gcm_start;
return 0;
}
static void atmel_aes_gcm_exit(struct crypto_aead *tfm)
{
}
static struct aead_alg aes_gcm_alg = {
.setkey = atmel_aes_gcm_setkey,
.setauthsize = atmel_aes_gcm_setauthsize,
.encrypt = atmel_aes_gcm_encrypt,
.decrypt = atmel_aes_gcm_decrypt,
.init = atmel_aes_gcm_init,
.exit = atmel_aes_gcm_exit,
.ivsize = 12,
.maxauthsize = AES_BLOCK_SIZE,
.base = {
.cra_name = "gcm(aes)",
.cra_driver_name = "atmel-gcm-aes",
.cra_priority = ATMEL_AES_PRIORITY,
.cra_flags = CRYPTO_ALG_ASYNC,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct atmel_aes_gcm_ctx),
.cra_alignmask = 0xf,
.cra_module = THIS_MODULE,
},
};
/* Probe functions */
static int atmel_aes_buff_init(struct atmel_aes_dev *dd)
{
dd->buf = (void *)__get_free_pages(GFP_KERNEL, ATMEL_AES_BUFFER_ORDER);
dd->buflen = ATMEL_AES_BUFFER_SIZE;
dd->buflen &= ~(AES_BLOCK_SIZE - 1);
if (!dd->buf) {
dev_err(dd->dev, "unable to alloc pages.\n");
return -ENOMEM;
}
return 0;
}
static void atmel_aes_buff_cleanup(struct atmel_aes_dev *dd)
{
free_page((unsigned long)dd->buf);
}
static bool atmel_aes_filter(struct dma_chan *chan, void *slave)
{
struct at_dma_slave *sl = slave;
if (sl && sl->dma_dev == chan->device->dev) {
chan->private = sl;
return true;
} else {
return false;
}
}
static int atmel_aes_dma_init(struct atmel_aes_dev *dd,
struct crypto_platform_data *pdata)
{
struct at_dma_slave *slave;
int err = -ENOMEM;
dma_cap_mask_t mask;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
/* Try to grab 2 DMA channels */
slave = &pdata->dma_slave->rxdata;
dd->src.chan = dma_request_slave_channel_compat(mask, atmel_aes_filter,
slave, dd->dev, "tx");
if (!dd->src.chan)
goto err_dma_in;
slave = &pdata->dma_slave->txdata;
dd->dst.chan = dma_request_slave_channel_compat(mask, atmel_aes_filter,
slave, dd->dev, "rx");
if (!dd->dst.chan)
goto err_dma_out;
return 0;
err_dma_out:
dma_release_channel(dd->src.chan);
err_dma_in:
dev_warn(dd->dev, "no DMA channel available\n");
return err;
}
static void atmel_aes_dma_cleanup(struct atmel_aes_dev *dd)
{
dma_release_channel(dd->dst.chan);
dma_release_channel(dd->src.chan);
}
static void atmel_aes_queue_task(unsigned long data)
{
struct atmel_aes_dev *dd = (struct atmel_aes_dev *)data;
atmel_aes_handle_queue(dd, NULL);
}
static void atmel_aes_done_task(unsigned long data)
{
struct atmel_aes_dev *dd = (struct atmel_aes_dev *)data;
dd->is_async = true;
(void)dd->resume(dd);
}
static irqreturn_t atmel_aes_irq(int irq, void *dev_id)
{
struct atmel_aes_dev *aes_dd = dev_id;
u32 reg;
reg = atmel_aes_read(aes_dd, AES_ISR);
if (reg & atmel_aes_read(aes_dd, AES_IMR)) {
atmel_aes_write(aes_dd, AES_IDR, reg);
if (AES_FLAGS_BUSY & aes_dd->flags)
tasklet_schedule(&aes_dd->done_task);
else
dev_warn(aes_dd->dev, "AES interrupt when no active requests.\n");
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static void atmel_aes_unregister_algs(struct atmel_aes_dev *dd)
{
int i;
if (dd->caps.has_gcm)
crypto_unregister_aead(&aes_gcm_alg);
if (dd->caps.has_cfb64)
crypto_unregister_alg(&aes_cfb64_alg);
for (i = 0; i < ARRAY_SIZE(aes_algs); i++)
crypto_unregister_alg(&aes_algs[i]);
}
static int atmel_aes_register_algs(struct atmel_aes_dev *dd)
{
int err, i, j;
for (i = 0; i < ARRAY_SIZE(aes_algs); i++) {
err = crypto_register_alg(&aes_algs[i]);
if (err)
goto err_aes_algs;
}
if (dd->caps.has_cfb64) {
err = crypto_register_alg(&aes_cfb64_alg);
if (err)
goto err_aes_cfb64_alg;
}
if (dd->caps.has_gcm) {
err = crypto_register_aead(&aes_gcm_alg);
if (err)
goto err_aes_gcm_alg;
}
return 0;
err_aes_gcm_alg:
crypto_unregister_alg(&aes_cfb64_alg);
err_aes_cfb64_alg:
i = ARRAY_SIZE(aes_algs);
err_aes_algs:
for (j = 0; j < i; j++)
crypto_unregister_alg(&aes_algs[j]);
return err;
}
static void atmel_aes_get_cap(struct atmel_aes_dev *dd)
{
dd->caps.has_dualbuff = 0;
dd->caps.has_cfb64 = 0;
dd->caps.has_ctr32 = 0;
dd->caps.has_gcm = 0;
dd->caps.max_burst_size = 1;
/* keep only major version number */
switch (dd->hw_version & 0xff0) {
case 0x500:
dd->caps.has_dualbuff = 1;
dd->caps.has_cfb64 = 1;
dd->caps.has_ctr32 = 1;
dd->caps.has_gcm = 1;
dd->caps.max_burst_size = 4;
break;
case 0x200:
dd->caps.has_dualbuff = 1;
dd->caps.has_cfb64 = 1;
dd->caps.has_ctr32 = 1;
dd->caps.has_gcm = 1;
dd->caps.max_burst_size = 4;
break;
case 0x130:
dd->caps.has_dualbuff = 1;
dd->caps.has_cfb64 = 1;
dd->caps.max_burst_size = 4;
break;
case 0x120:
break;
default:
dev_warn(dd->dev,
"Unmanaged aes version, set minimum capabilities\n");
break;
}
}
#if defined(CONFIG_OF)
static const struct of_device_id atmel_aes_dt_ids[] = {
{ .compatible = "atmel,at91sam9g46-aes" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, atmel_aes_dt_ids);
static struct crypto_platform_data *atmel_aes_of_init(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct crypto_platform_data *pdata;
if (!np) {
dev_err(&pdev->dev, "device node not found\n");
return ERR_PTR(-EINVAL);
}
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
dev_err(&pdev->dev, "could not allocate memory for pdata\n");
return ERR_PTR(-ENOMEM);
}
pdata->dma_slave = devm_kzalloc(&pdev->dev,
sizeof(*(pdata->dma_slave)),
GFP_KERNEL);
if (!pdata->dma_slave) {
dev_err(&pdev->dev, "could not allocate memory for dma_slave\n");
devm_kfree(&pdev->dev, pdata);
return ERR_PTR(-ENOMEM);
}
return pdata;
}
#else
static inline struct crypto_platform_data *atmel_aes_of_init(struct platform_device *pdev)
{
return ERR_PTR(-EINVAL);
}
#endif
static int atmel_aes_probe(struct platform_device *pdev)
{
struct atmel_aes_dev *aes_dd;
struct crypto_platform_data *pdata;
struct device *dev = &pdev->dev;
struct resource *aes_res;
int err;
pdata = pdev->dev.platform_data;
if (!pdata) {
pdata = atmel_aes_of_init(pdev);
if (IS_ERR(pdata)) {
err = PTR_ERR(pdata);
goto aes_dd_err;
}
}
if (!pdata->dma_slave) {
err = -ENXIO;
goto aes_dd_err;
}
aes_dd = devm_kzalloc(&pdev->dev, sizeof(*aes_dd), GFP_KERNEL);
if (aes_dd == NULL) {
dev_err(dev, "unable to alloc data struct.\n");
err = -ENOMEM;
goto aes_dd_err;
}
aes_dd->dev = dev;
platform_set_drvdata(pdev, aes_dd);
INIT_LIST_HEAD(&aes_dd->list);
spin_lock_init(&aes_dd->lock);
tasklet_init(&aes_dd->done_task, atmel_aes_done_task,
(unsigned long)aes_dd);
tasklet_init(&aes_dd->queue_task, atmel_aes_queue_task,
(unsigned long)aes_dd);
crypto_init_queue(&aes_dd->queue, ATMEL_AES_QUEUE_LENGTH);
aes_dd->irq = -1;
/* Get the base address */
aes_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!aes_res) {
dev_err(dev, "no MEM resource info\n");
err = -ENODEV;
goto res_err;
}
aes_dd->phys_base = aes_res->start;
/* Get the IRQ */
aes_dd->irq = platform_get_irq(pdev, 0);
if (aes_dd->irq < 0) {
dev_err(dev, "no IRQ resource info\n");
err = aes_dd->irq;
goto res_err;
}
err = devm_request_irq(&pdev->dev, aes_dd->irq, atmel_aes_irq,
IRQF_SHARED, "atmel-aes", aes_dd);
if (err) {
dev_err(dev, "unable to request aes irq.\n");
goto res_err;
}
/* Initializing the clock */
aes_dd->iclk = devm_clk_get(&pdev->dev, "aes_clk");
if (IS_ERR(aes_dd->iclk)) {
dev_err(dev, "clock initialization failed.\n");
err = PTR_ERR(aes_dd->iclk);
goto res_err;
}
aes_dd->io_base = devm_ioremap_resource(&pdev->dev, aes_res);
if (IS_ERR(aes_dd->io_base)) {
dev_err(dev, "can't ioremap\n");
err = PTR_ERR(aes_dd->io_base);
goto res_err;
}
err = clk_prepare(aes_dd->iclk);
if (err)
goto res_err;
err = atmel_aes_hw_version_init(aes_dd);
if (err)
goto iclk_unprepare;
atmel_aes_get_cap(aes_dd);
err = atmel_aes_buff_init(aes_dd);
if (err)
goto err_aes_buff;
err = atmel_aes_dma_init(aes_dd, pdata);
if (err)
goto err_aes_dma;
spin_lock(&atmel_aes.lock);
list_add_tail(&aes_dd->list, &atmel_aes.dev_list);
spin_unlock(&atmel_aes.lock);
err = atmel_aes_register_algs(aes_dd);
if (err)
goto err_algs;
dev_info(dev, "Atmel AES - Using %s, %s for DMA transfers\n",
dma_chan_name(aes_dd->src.chan),
dma_chan_name(aes_dd->dst.chan));
return 0;
err_algs:
spin_lock(&atmel_aes.lock);
list_del(&aes_dd->list);
spin_unlock(&atmel_aes.lock);
atmel_aes_dma_cleanup(aes_dd);
err_aes_dma:
atmel_aes_buff_cleanup(aes_dd);
err_aes_buff:
iclk_unprepare:
clk_unprepare(aes_dd->iclk);
res_err:
tasklet_kill(&aes_dd->done_task);
tasklet_kill(&aes_dd->queue_task);
aes_dd_err:
dev_err(dev, "initialization failed.\n");
return err;
}
static int atmel_aes_remove(struct platform_device *pdev)
{
static struct atmel_aes_dev *aes_dd;
aes_dd = platform_get_drvdata(pdev);
if (!aes_dd)
return -ENODEV;
spin_lock(&atmel_aes.lock);
list_del(&aes_dd->list);
spin_unlock(&atmel_aes.lock);
atmel_aes_unregister_algs(aes_dd);
tasklet_kill(&aes_dd->done_task);
tasklet_kill(&aes_dd->queue_task);
atmel_aes_dma_cleanup(aes_dd);
atmel_aes_buff_cleanup(aes_dd);
clk_unprepare(aes_dd->iclk);
return 0;
}
static struct platform_driver atmel_aes_driver = {
.probe = atmel_aes_probe,
.remove = atmel_aes_remove,
.driver = {
.name = "atmel_aes",
.of_match_table = of_match_ptr(atmel_aes_dt_ids),
},
};
module_platform_driver(atmel_aes_driver);
MODULE_DESCRIPTION("Atmel AES hw acceleration support.");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Nicolas Royer - Eukréa Electromatique");
| gpl-2.0 |
dtuchsch/linux-preempt_rt | fs/ocfs2/stack_o2cb.c | 980 | 11816 | /* -*- 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 "cluster/tcp.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);
}
/*
* Check if this node is heartbeating and is connected to all other
* heartbeating nodes.
*/
static int o2cb_cluster_check(void)
{
u8 node_num;
int i;
unsigned long hbmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long netmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
node_num = o2nm_this_node();
if (node_num == O2NM_MAX_NODES) {
printk(KERN_ERR "o2cb: This node has not been configured.\n");
return -EINVAL;
}
/*
* o2dlm expects o2net sockets to be created. If not, then
* dlm_join_domain() fails with a stack of errors which are both cryptic
* and incomplete. The idea here is to detect upfront whether we have
* managed to connect to all nodes or not. If not, then list the nodes
* to allow the user to check the configuration (incorrect IP, firewall,
* etc.) Yes, this is racy. But its not the end of the world.
*/
#define O2CB_MAP_STABILIZE_COUNT 60
for (i = 0; i < O2CB_MAP_STABILIZE_COUNT; ++i) {
o2hb_fill_node_map(hbmap, sizeof(hbmap));
if (!test_bit(node_num, hbmap)) {
printk(KERN_ERR "o2cb: %s heartbeat has not been "
"started.\n", (o2hb_global_heartbeat_active() ?
"Global" : "Local"));
return -EINVAL;
}
o2net_fill_node_map(netmap, sizeof(netmap));
/* Force set the current node to allow easy compare */
set_bit(node_num, netmap);
if (!memcmp(hbmap, netmap, sizeof(hbmap)))
return 0;
if (i < O2CB_MAP_STABILIZE_COUNT)
msleep(1000);
}
printk(KERN_ERR "o2cb: This node could not connect to nodes:");
i = -1;
while ((i = find_next_bit(hbmap, O2NM_MAX_NODES,
i + 1)) < O2NM_MAX_NODES) {
if (!test_bit(i, netmap))
printk(" %u", i);
}
printk(".\n");
return -ENOTCONN;
}
/*
* 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;
printk(KERN_NOTICE "o2cb: o2dlm has evicted node %d from domain %.*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);
/* Ensure cluster stack is up and all nodes are connected */
rc = o2cb_cluster_check();
if (rc) {
printk(KERN_ERR "o2cb: Cluster check failed. Fix errors "
"before retrying.\n");
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)
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(struct ocfs2_cluster_connection *conn,
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 |
icalik/linux | drivers/usb/gadget/function/f_ecm.c | 1236 | 27522 | /*
* f_ecm.c -- USB CDC Ethernet (ECM) link function driver
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/etherdevice.h>
#include "u_ether.h"
#include "u_ether_configfs.h"
#include "u_ecm.h"
/*
* This function is a "CDC Ethernet Networking Control Model" (CDC ECM)
* Ethernet link. The data transfer model is simple (packets sent and
* received over bulk endpoints using normal short packet termination),
* and the control model exposes various data and optional notifications.
*
* ECM is well standardized and (except for Microsoft) supported by most
* operating systems with USB host support. It's the preferred interop
* solution for Ethernet over USB, at least for firmware based solutions.
* (Hardware solutions tend to be more minimalist.) A newer and simpler
* "Ethernet Emulation Model" (CDC EEM) hasn't yet caught on.
*
* Note that ECM requires the use of "alternate settings" for its data
* interface. This means that the set_alt() method has real work to do,
* and also means that a get_alt() method is required.
*/
enum ecm_notify_state {
ECM_NOTIFY_NONE, /* don't notify */
ECM_NOTIFY_CONNECT, /* issue CONNECT next */
ECM_NOTIFY_SPEED, /* issue SPEED_CHANGE next */
};
struct f_ecm {
struct gether port;
u8 ctrl_id, data_id;
char ethaddr[14];
struct usb_ep *notify;
struct usb_request *notify_req;
u8 notify_state;
bool is_open;
/* FIXME is_open needs some irq-ish locking
* ... possibly the same as port.ioport
*/
};
static inline struct f_ecm *func_to_ecm(struct usb_function *f)
{
return container_of(f, struct f_ecm, port.func);
}
/* peak (theoretical) bulk transfer rate in bits-per-second */
static inline unsigned ecm_bitrate(struct usb_gadget *g)
{
if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
return 13 * 1024 * 8 * 1000 * 8;
else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return 13 * 512 * 8 * 1000 * 8;
else
return 19 * 64 * 1 * 1000 * 8;
}
/*-------------------------------------------------------------------------*/
/*
* Include the status endpoint if we can, even though it's optional.
*
* Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
* packet, to simplify cancellation; and a big transfer interval, to
* waste less bandwidth.
*
* Some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
* if they ignore the connect/disconnect notifications that real aether
* can provide. More advanced cdc configurations might want to support
* encapsulated commands (vendor-specific, using control-OUT).
*/
#define ECM_STATUS_INTERVAL_MS 32
#define ECM_STATUS_BYTECOUNT 16 /* 8 byte header + data */
/* interface descriptor: */
static struct usb_interface_assoc_descriptor
ecm_iad_descriptor = {
.bLength = sizeof ecm_iad_descriptor,
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
/* .bFirstInterface = DYNAMIC, */
.bInterfaceCount = 2, /* control + data */
.bFunctionClass = USB_CLASS_COMM,
.bFunctionSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bFunctionProtocol = USB_CDC_PROTO_NONE,
/* .iFunction = DYNAMIC */
};
static struct usb_interface_descriptor ecm_control_intf = {
.bLength = sizeof ecm_control_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
/* status endpoint is optional; this could be patched later */
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bInterfaceProtocol = USB_CDC_PROTO_NONE,
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc ecm_header_desc = {
.bLength = sizeof ecm_header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_union_desc ecm_union_desc = {
.bLength = sizeof(ecm_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
static struct usb_cdc_ether_desc ecm_desc = {
.bLength = sizeof ecm_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
/* this descriptor actually adds value, surprise! */
/* .iMACAddress = DYNAMIC */
.bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
.wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
.wNumberMCFilters = cpu_to_le16(0),
.bNumberPowerFilters = 0,
};
/* the default data interface has no endpoints ... */
static struct usb_interface_descriptor ecm_data_nop_intf = {
.bLength = sizeof ecm_data_nop_intf,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* ... but the "real" data interface has two bulk endpoints */
static struct usb_interface_descriptor ecm_data_intf = {
.bLength = sizeof ecm_data_intf,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor fs_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = ECM_STATUS_INTERVAL_MS,
};
static struct usb_endpoint_descriptor fs_ecm_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 fs_ecm_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 *ecm_fs_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_iad_descriptor,
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &fs_ecm_notify_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &fs_ecm_in_desc,
(struct usb_descriptor_header *) &fs_ecm_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor hs_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
};
static struct usb_endpoint_descriptor hs_ecm_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor hs_ecm_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *ecm_hs_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_iad_descriptor,
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &hs_ecm_notify_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &hs_ecm_in_desc,
(struct usb_descriptor_header *) &hs_ecm_out_desc,
NULL,
};
/* super speed support: */
static struct usb_endpoint_descriptor ss_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
};
static struct usb_ss_ep_comp_descriptor ss_ecm_intr_comp_desc = {
.bLength = sizeof ss_ecm_intr_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 3 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
.wBytesPerInterval = cpu_to_le16(ECM_STATUS_BYTECOUNT),
};
static struct usb_endpoint_descriptor ss_ecm_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_endpoint_descriptor ss_ecm_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_ss_ep_comp_descriptor ss_ecm_bulk_comp_desc = {
.bLength = sizeof ss_ecm_bulk_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 2 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
};
static struct usb_descriptor_header *ecm_ss_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_iad_descriptor,
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &ss_ecm_notify_desc,
(struct usb_descriptor_header *) &ss_ecm_intr_comp_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &ss_ecm_in_desc,
(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
(struct usb_descriptor_header *) &ss_ecm_out_desc,
(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
NULL,
};
/* string descriptors: */
static struct usb_string ecm_string_defs[] = {
[0].s = "CDC Ethernet Control Model (ECM)",
[1].s = "",
[2].s = "CDC Ethernet Data",
[3].s = "CDC ECM",
{ } /* end of list */
};
static struct usb_gadget_strings ecm_string_table = {
.language = 0x0409, /* en-us */
.strings = ecm_string_defs,
};
static struct usb_gadget_strings *ecm_strings[] = {
&ecm_string_table,
NULL,
};
/*-------------------------------------------------------------------------*/
static void ecm_do_notify(struct f_ecm *ecm)
{
struct usb_request *req = ecm->notify_req;
struct usb_cdc_notification *event;
struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
__le32 *data;
int status;
/* notification already in flight? */
if (!req)
return;
event = req->buf;
switch (ecm->notify_state) {
case ECM_NOTIFY_NONE:
return;
case ECM_NOTIFY_CONNECT:
event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
if (ecm->is_open)
event->wValue = cpu_to_le16(1);
else
event->wValue = cpu_to_le16(0);
event->wLength = 0;
req->length = sizeof *event;
DBG(cdev, "notify connect %s\n",
ecm->is_open ? "true" : "false");
ecm->notify_state = ECM_NOTIFY_SPEED;
break;
case ECM_NOTIFY_SPEED:
event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
event->wValue = cpu_to_le16(0);
event->wLength = cpu_to_le16(8);
req->length = ECM_STATUS_BYTECOUNT;
/* SPEED_CHANGE data is up/down speeds in bits/sec */
data = req->buf + sizeof *event;
data[0] = cpu_to_le32(ecm_bitrate(cdev->gadget));
data[1] = data[0];
DBG(cdev, "notify speed %d\n", ecm_bitrate(cdev->gadget));
ecm->notify_state = ECM_NOTIFY_NONE;
break;
}
event->bmRequestType = 0xA1;
event->wIndex = cpu_to_le16(ecm->ctrl_id);
ecm->notify_req = NULL;
status = usb_ep_queue(ecm->notify, req, GFP_ATOMIC);
if (status < 0) {
ecm->notify_req = req;
DBG(cdev, "notify --> %d\n", status);
}
}
static void ecm_notify(struct f_ecm *ecm)
{
/* NOTE on most versions of Linux, host side cdc-ethernet
* won't listen for notifications until its netdevice opens.
* The first notification then sits in the FIFO for a long
* time, and the second one is queued.
*/
ecm->notify_state = ECM_NOTIFY_CONNECT;
ecm_do_notify(ecm);
}
static void ecm_notify_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_ecm *ecm = req->context;
struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
struct usb_cdc_notification *event = req->buf;
switch (req->status) {
case 0:
/* no fault */
break;
case -ECONNRESET:
case -ESHUTDOWN:
ecm->notify_state = ECM_NOTIFY_NONE;
break;
default:
DBG(cdev, "event %02x --> %d\n",
event->bNotificationType, req->status);
break;
}
ecm->notify_req = req;
ecm_do_notify(ecm);
}
static int ecm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*/
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_SET_ETHERNET_PACKET_FILTER:
/* see 6.2.30: no data, wIndex = interface,
* wValue = packet filter bitmap
*/
if (w_length != 0 || w_index != ecm->ctrl_id)
goto invalid;
DBG(cdev, "packet filter %02x\n", w_value);
/* REVISIT locking of cdc_filter. This assumes the UDC
* driver won't have a concurrent packet TX irq running on
* another CPU; or that if it does, this write is atomic...
*/
ecm->port.cdc_filter = w_value;
value = 0;
break;
/* and optionally:
* case USB_CDC_SEND_ENCAPSULATED_COMMAND:
* case USB_CDC_GET_ENCAPSULATED_RESPONSE:
* case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
* case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
* case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
* case USB_CDC_GET_ETHERNET_STATISTIC:
*/
default:
invalid:
DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "ecm req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 0;
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "ecm req %02x.%02x response err %d\n",
ctrl->bRequestType, ctrl->bRequest,
value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* Control interface has only altsetting 0 */
if (intf == ecm->ctrl_id) {
if (alt != 0)
goto fail;
if (ecm->notify->driver_data) {
VDBG(cdev, "reset ecm control %d\n", intf);
usb_ep_disable(ecm->notify);
}
if (!(ecm->notify->desc)) {
VDBG(cdev, "init ecm ctrl %d\n", intf);
if (config_ep_by_speed(cdev->gadget, f, ecm->notify))
goto fail;
}
usb_ep_enable(ecm->notify);
ecm->notify->driver_data = ecm;
/* Data interface has two altsettings, 0 and 1 */
} else if (intf == ecm->data_id) {
if (alt > 1)
goto fail;
if (ecm->port.in_ep->driver_data) {
DBG(cdev, "reset ecm\n");
gether_disconnect(&ecm->port);
}
if (!ecm->port.in_ep->desc ||
!ecm->port.out_ep->desc) {
DBG(cdev, "init ecm\n");
if (config_ep_by_speed(cdev->gadget, f,
ecm->port.in_ep) ||
config_ep_by_speed(cdev->gadget, f,
ecm->port.out_ep)) {
ecm->port.in_ep->desc = NULL;
ecm->port.out_ep->desc = NULL;
goto fail;
}
}
/* CDC Ethernet only sends data in non-default altsettings.
* Changing altsettings resets filters, statistics, etc.
*/
if (alt == 1) {
struct net_device *net;
/* Enable zlps by default for ECM conformance;
* override for musb_hdrc (avoids txdma ovhead).
*/
ecm->port.is_zlp_ok = !(gadget_is_musbhdrc(cdev->gadget)
);
ecm->port.cdc_filter = DEFAULT_FILTER;
DBG(cdev, "activate ecm\n");
net = gether_connect(&ecm->port);
if (IS_ERR(net))
return PTR_ERR(net);
}
/* NOTE this can be a minor disagreement with the ECM spec,
* which says speed notifications will "always" follow
* connection notifications. But we allow one connect to
* follow another (if the first is in flight), and instead
* just guarantee that a speed notification is always sent.
*/
ecm_notify(ecm);
} else
goto fail;
return 0;
fail:
return -EINVAL;
}
/* Because the data interface supports multiple altsettings,
* this ECM function *MUST* implement a get_alt() method.
*/
static int ecm_get_alt(struct usb_function *f, unsigned intf)
{
struct f_ecm *ecm = func_to_ecm(f);
if (intf == ecm->ctrl_id)
return 0;
return ecm->port.in_ep->driver_data ? 1 : 0;
}
static void ecm_disable(struct usb_function *f)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
DBG(cdev, "ecm deactivated\n");
if (ecm->port.in_ep->driver_data)
gether_disconnect(&ecm->port);
if (ecm->notify->driver_data) {
usb_ep_disable(ecm->notify);
ecm->notify->driver_data = NULL;
ecm->notify->desc = NULL;
}
}
/*-------------------------------------------------------------------------*/
/*
* Callbacks let us notify the host about connect/disconnect when the
* net device is opened or closed.
*
* For testing, note that link states on this side include both opened
* and closed variants of:
*
* - disconnected/unconfigured
* - configured but inactive (data alt 0)
* - configured and active (data alt 1)
*
* Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
* SET_INTERFACE (altsetting). Remember also that "configured" doesn't
* imply the host is actually polling the notification endpoint, and
* likewise that "active" doesn't imply it's actually using the data
* endpoints for traffic.
*/
static void ecm_open(struct gether *geth)
{
struct f_ecm *ecm = func_to_ecm(&geth->func);
DBG(ecm->port.func.config->cdev, "%s\n", __func__);
ecm->is_open = true;
ecm_notify(ecm);
}
static void ecm_close(struct gether *geth)
{
struct f_ecm *ecm = func_to_ecm(&geth->func);
DBG(ecm->port.func.config->cdev, "%s\n", __func__);
ecm->is_open = false;
ecm_notify(ecm);
}
/*-------------------------------------------------------------------------*/
/* ethernet function driver setup/binding */
static int
ecm_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_ecm *ecm = func_to_ecm(f);
struct usb_string *us;
int status;
struct usb_ep *ep;
struct f_ecm_opts *ecm_opts;
if (!can_support_ecm(cdev->gadget))
return -EINVAL;
ecm_opts = container_of(f->fi, struct f_ecm_opts, func_inst);
/*
* in drivers/usb/gadget/configfs.c:configfs_composite_bind()
* configurations are bound in sequence with list_for_each_entry,
* in each configuration its functions are bound in sequence
* with list_for_each_entry, so we assume no race condition
* with regard to ecm_opts->bound access
*/
if (!ecm_opts->bound) {
mutex_lock(&ecm_opts->lock);
gether_set_gadget(ecm_opts->net, cdev->gadget);
status = gether_register_netdev(ecm_opts->net);
mutex_unlock(&ecm_opts->lock);
if (status)
return status;
ecm_opts->bound = true;
}
us = usb_gstrings_attach(cdev, ecm_strings,
ARRAY_SIZE(ecm_string_defs));
if (IS_ERR(us))
return PTR_ERR(us);
ecm_control_intf.iInterface = us[0].id;
ecm_data_intf.iInterface = us[2].id;
ecm_desc.iMACAddress = us[1].id;
ecm_iad_descriptor.iFunction = us[3].id;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
ecm->ctrl_id = status;
ecm_iad_descriptor.bFirstInterface = status;
ecm_control_intf.bInterfaceNumber = status;
ecm_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
ecm->data_id = status;
ecm_data_nop_intf.bInterfaceNumber = status;
ecm_data_intf.bInterfaceNumber = status;
ecm_union_desc.bSlaveInterface0 = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_in_desc);
if (!ep)
goto fail;
ecm->port.in_ep = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_out_desc);
if (!ep)
goto fail;
ecm->port.out_ep = ep;
ep->driver_data = cdev; /* claim */
/* NOTE: a status/notification endpoint is *OPTIONAL* but we
* don't treat it that way. It's simpler, and some newer CDC
* profiles (wireless handsets) no longer treat it as optional.
*/
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_notify_desc);
if (!ep)
goto fail;
ecm->notify = ep;
ep->driver_data = cdev; /* claim */
status = -ENOMEM;
/* allocate notification request and buffer */
ecm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!ecm->notify_req)
goto fail;
ecm->notify_req->buf = kmalloc(ECM_STATUS_BYTECOUNT, GFP_KERNEL);
if (!ecm->notify_req->buf)
goto fail;
ecm->notify_req->context = ecm;
ecm->notify_req->complete = ecm_notify_complete;
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
hs_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
hs_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
hs_ecm_notify_desc.bEndpointAddress =
fs_ecm_notify_desc.bEndpointAddress;
ss_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
ss_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
ss_ecm_notify_desc.bEndpointAddress =
fs_ecm_notify_desc.bEndpointAddress;
status = usb_assign_descriptors(f, ecm_fs_function, ecm_hs_function,
ecm_ss_function);
if (status)
goto fail;
/* NOTE: all that is done without knowing or caring about
* the network link ... which is unavailable to this code
* until we're activated via set_alt().
*/
ecm->port.open = ecm_open;
ecm->port.close = ecm_close;
DBG(cdev, "CDC Ethernet: %s speed IN/%s OUT/%s NOTIFY/%s\n",
gadget_is_superspeed(c->cdev->gadget) ? "super" :
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
ecm->port.in_ep->name, ecm->port.out_ep->name,
ecm->notify->name);
return 0;
fail:
if (ecm->notify_req) {
kfree(ecm->notify_req->buf);
usb_ep_free_request(ecm->notify, ecm->notify_req);
}
/* we might as well release our claims on endpoints */
if (ecm->notify)
ecm->notify->driver_data = NULL;
if (ecm->port.out_ep)
ecm->port.out_ep->driver_data = NULL;
if (ecm->port.in_ep)
ecm->port.in_ep->driver_data = NULL;
ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
return status;
}
static inline struct f_ecm_opts *to_f_ecm_opts(struct config_item *item)
{
return container_of(to_config_group(item), struct f_ecm_opts,
func_inst.group);
}
/* f_ecm_item_ops */
USB_ETHERNET_CONFIGFS_ITEM(ecm);
/* f_ecm_opts_dev_addr */
USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ecm);
/* f_ecm_opts_host_addr */
USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ecm);
/* f_ecm_opts_qmult */
USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ecm);
/* f_ecm_opts_ifname */
USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ecm);
static struct configfs_attribute *ecm_attrs[] = {
&f_ecm_opts_dev_addr.attr,
&f_ecm_opts_host_addr.attr,
&f_ecm_opts_qmult.attr,
&f_ecm_opts_ifname.attr,
NULL,
};
static struct config_item_type ecm_func_type = {
.ct_item_ops = &ecm_item_ops,
.ct_attrs = ecm_attrs,
.ct_owner = THIS_MODULE,
};
static void ecm_free_inst(struct usb_function_instance *f)
{
struct f_ecm_opts *opts;
opts = container_of(f, struct f_ecm_opts, func_inst);
if (opts->bound)
gether_cleanup(netdev_priv(opts->net));
else
free_netdev(opts->net);
kfree(opts);
}
static struct usb_function_instance *ecm_alloc_inst(void)
{
struct f_ecm_opts *opts;
opts = kzalloc(sizeof(*opts), GFP_KERNEL);
if (!opts)
return ERR_PTR(-ENOMEM);
mutex_init(&opts->lock);
opts->func_inst.free_func_inst = ecm_free_inst;
opts->net = gether_setup_default();
if (IS_ERR(opts->net)) {
struct net_device *net = opts->net;
kfree(opts);
return ERR_CAST(net);
}
config_group_init_type_name(&opts->func_inst.group, "", &ecm_func_type);
return &opts->func_inst;
}
static void ecm_free(struct usb_function *f)
{
struct f_ecm *ecm;
struct f_ecm_opts *opts;
ecm = func_to_ecm(f);
opts = container_of(f->fi, struct f_ecm_opts, func_inst);
kfree(ecm);
mutex_lock(&opts->lock);
opts->refcnt--;
mutex_unlock(&opts->lock);
}
static void ecm_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_ecm *ecm = func_to_ecm(f);
DBG(c->cdev, "ecm unbind\n");
usb_free_all_descriptors(f);
kfree(ecm->notify_req->buf);
usb_ep_free_request(ecm->notify, ecm->notify_req);
}
static struct usb_function *ecm_alloc(struct usb_function_instance *fi)
{
struct f_ecm *ecm;
struct f_ecm_opts *opts;
int status;
/* allocate and initialize one new instance */
ecm = kzalloc(sizeof(*ecm), GFP_KERNEL);
if (!ecm)
return ERR_PTR(-ENOMEM);
opts = container_of(fi, struct f_ecm_opts, func_inst);
mutex_lock(&opts->lock);
opts->refcnt++;
/* export host's Ethernet address in CDC format */
status = gether_get_host_addr_cdc(opts->net, ecm->ethaddr,
sizeof(ecm->ethaddr));
if (status < 12) {
kfree(ecm);
mutex_unlock(&opts->lock);
return ERR_PTR(-EINVAL);
}
ecm_string_defs[1].s = ecm->ethaddr;
ecm->port.ioport = netdev_priv(opts->net);
mutex_unlock(&opts->lock);
ecm->port.cdc_filter = DEFAULT_FILTER;
ecm->port.func.name = "cdc_ethernet";
/* descriptors are per-instance copies */
ecm->port.func.bind = ecm_bind;
ecm->port.func.unbind = ecm_unbind;
ecm->port.func.set_alt = ecm_set_alt;
ecm->port.func.get_alt = ecm_get_alt;
ecm->port.func.setup = ecm_setup;
ecm->port.func.disable = ecm_disable;
ecm->port.func.free_func = ecm_free;
return &ecm->port.func;
}
DECLARE_USB_FUNCTION_INIT(ecm, ecm_alloc_inst, ecm_alloc);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Brownell");
| gpl-2.0 |
arokux/linux | drivers/mtd/ubi/attach.c | 1236 | 47992 | /*
* Copyright (c) International Business Machines Corp., 2006
*
* 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
*
* Author: Artem Bityutskiy (Битюцкий Артём)
*/
/*
* UBI attaching sub-system.
*
* This sub-system is responsible for attaching MTD devices and it also
* implements flash media scanning.
*
* The attaching information is represented by a &struct ubi_attach_info'
* object. Information about volumes is represented by &struct ubi_ainf_volume
* objects which are kept in volume RB-tree with root at the @volumes field.
* The RB-tree is indexed by the volume ID.
*
* Logical eraseblocks are represented by &struct ubi_ainf_peb objects. These
* objects are kept in per-volume RB-trees with the root at the corresponding
* &struct ubi_ainf_volume object. To put it differently, we keep an RB-tree of
* per-volume objects and each of these objects is the root of RB-tree of
* per-LEB objects.
*
* Corrupted physical eraseblocks are put to the @corr list, free physical
* eraseblocks are put to the @free list and the physical eraseblock to be
* erased are put to the @erase list.
*
* About corruptions
* ~~~~~~~~~~~~~~~~~
*
* UBI protects EC and VID headers with CRC-32 checksums, so it can detect
* whether the headers are corrupted or not. Sometimes UBI also protects the
* data with CRC-32, e.g., when it executes the atomic LEB change operation, or
* when it moves the contents of a PEB for wear-leveling purposes.
*
* UBI tries to distinguish between 2 types of corruptions.
*
* 1. Corruptions caused by power cuts. These are expected corruptions and UBI
* tries to handle them gracefully, without printing too many warnings and
* error messages. The idea is that we do not lose important data in these
* cases - we may lose only the data which were being written to the media just
* before the power cut happened, and the upper layers (e.g., UBIFS) are
* supposed to handle such data losses (e.g., by using the FS journal).
*
* When UBI detects a corruption (CRC-32 mismatch) in a PEB, and it looks like
* the reason is a power cut, UBI puts this PEB to the @erase list, and all
* PEBs in the @erase list are scheduled for erasure later.
*
* 2. Unexpected corruptions which are not caused by power cuts. During
* attaching, such PEBs are put to the @corr list and UBI preserves them.
* Obviously, this lessens the amount of available PEBs, and if at some point
* UBI runs out of free PEBs, it switches to R/O mode. UBI also loudly informs
* about such PEBs every time the MTD device is attached.
*
* However, it is difficult to reliably distinguish between these types of
* corruptions and UBI's strategy is as follows (in case of attaching by
* scanning). UBI assumes corruption type 2 if the VID header is corrupted and
* the data area does not contain all 0xFFs, and there were no bit-flips or
* integrity errors (e.g., ECC errors in case of NAND) while reading the data
* area. Otherwise UBI assumes corruption type 1. So the decision criteria
* are as follows.
* o If the data area contains only 0xFFs, there are no data, and it is safe
* to just erase this PEB - this is corruption type 1.
* o If the data area has bit-flips or data integrity errors (ECC errors on
* NAND), it is probably a PEB which was being erased when power cut
* happened, so this is corruption type 1. However, this is just a guess,
* which might be wrong.
* o Otherwise this is corruption type 2.
*/
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/crc32.h>
#include <linux/math64.h>
#include <linux/random.h>
#include "ubi.h"
static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai);
/* Temporary variables used during scanning */
static struct ubi_ec_hdr *ech;
static struct ubi_vid_hdr *vidh;
/**
* add_to_list - add physical eraseblock to a list.
* @ai: attaching information
* @pnum: physical eraseblock number to add
* @vol_id: the last used volume id for the PEB
* @lnum: the last used LEB number for the PEB
* @ec: erase counter of the physical eraseblock
* @to_head: if not zero, add to the head of the list
* @list: the list to add to
*
* This function allocates a 'struct ubi_ainf_peb' object for physical
* eraseblock @pnum and adds it to the "free", "erase", or "alien" lists.
* It stores the @lnum and @vol_id alongside, which can both be
* %UBI_UNKNOWN if they are not available, not readable, or not assigned.
* If @to_head is not zero, PEB will be added to the head of the list, which
* basically means it will be processed first later. E.g., we add corrupted
* PEBs (corrupted due to power cuts) to the head of the erase list to make
* sure we erase them first and get rid of corruptions ASAP. This function
* returns zero in case of success and a negative error code in case of
* failure.
*/
static int add_to_list(struct ubi_attach_info *ai, int pnum, int vol_id,
int lnum, int ec, int to_head, struct list_head *list)
{
struct ubi_ainf_peb *aeb;
if (list == &ai->free) {
dbg_bld("add to free: PEB %d, EC %d", pnum, ec);
} else if (list == &ai->erase) {
dbg_bld("add to erase: PEB %d, EC %d", pnum, ec);
} else if (list == &ai->alien) {
dbg_bld("add to alien: PEB %d, EC %d", pnum, ec);
ai->alien_peb_count += 1;
} else
BUG();
aeb = kmem_cache_alloc(ai->aeb_slab_cache, GFP_KERNEL);
if (!aeb)
return -ENOMEM;
aeb->pnum = pnum;
aeb->vol_id = vol_id;
aeb->lnum = lnum;
aeb->ec = ec;
if (to_head)
list_add(&aeb->u.list, list);
else
list_add_tail(&aeb->u.list, list);
return 0;
}
/**
* add_corrupted - add a corrupted physical eraseblock.
* @ai: attaching information
* @pnum: physical eraseblock number to add
* @ec: erase counter of the physical eraseblock
*
* This function allocates a 'struct ubi_ainf_peb' object for a corrupted
* physical eraseblock @pnum and adds it to the 'corr' list. The corruption
* was presumably not caused by a power cut. Returns zero in case of success
* and a negative error code in case of failure.
*/
static int add_corrupted(struct ubi_attach_info *ai, int pnum, int ec)
{
struct ubi_ainf_peb *aeb;
dbg_bld("add to corrupted: PEB %d, EC %d", pnum, ec);
aeb = kmem_cache_alloc(ai->aeb_slab_cache, GFP_KERNEL);
if (!aeb)
return -ENOMEM;
ai->corr_peb_count += 1;
aeb->pnum = pnum;
aeb->ec = ec;
list_add(&aeb->u.list, &ai->corr);
return 0;
}
/**
* validate_vid_hdr - check volume identifier header.
* @vid_hdr: the volume identifier header to check
* @av: information about the volume this logical eraseblock belongs to
* @pnum: physical eraseblock number the VID header came from
*
* This function checks that data stored in @vid_hdr is consistent. Returns
* non-zero if an inconsistency was found and zero if not.
*
* Note, UBI does sanity check of everything it reads from the flash media.
* Most of the checks are done in the I/O sub-system. Here we check that the
* information in the VID header is consistent to the information in other VID
* headers of the same volume.
*/
static int validate_vid_hdr(const struct ubi_vid_hdr *vid_hdr,
const struct ubi_ainf_volume *av, int pnum)
{
int vol_type = vid_hdr->vol_type;
int vol_id = be32_to_cpu(vid_hdr->vol_id);
int used_ebs = be32_to_cpu(vid_hdr->used_ebs);
int data_pad = be32_to_cpu(vid_hdr->data_pad);
if (av->leb_count != 0) {
int av_vol_type;
/*
* This is not the first logical eraseblock belonging to this
* volume. Ensure that the data in its VID header is consistent
* to the data in previous logical eraseblock headers.
*/
if (vol_id != av->vol_id) {
ubi_err("inconsistent vol_id");
goto bad;
}
if (av->vol_type == UBI_STATIC_VOLUME)
av_vol_type = UBI_VID_STATIC;
else
av_vol_type = UBI_VID_DYNAMIC;
if (vol_type != av_vol_type) {
ubi_err("inconsistent vol_type");
goto bad;
}
if (used_ebs != av->used_ebs) {
ubi_err("inconsistent used_ebs");
goto bad;
}
if (data_pad != av->data_pad) {
ubi_err("inconsistent data_pad");
goto bad;
}
}
return 0;
bad:
ubi_err("inconsistent VID header at PEB %d", pnum);
ubi_dump_vid_hdr(vid_hdr);
ubi_dump_av(av);
return -EINVAL;
}
/**
* add_volume - add volume to the attaching information.
* @ai: attaching information
* @vol_id: ID of the volume to add
* @pnum: physical eraseblock number
* @vid_hdr: volume identifier header
*
* If the volume corresponding to the @vid_hdr logical eraseblock is already
* present in the attaching information, this function does nothing. Otherwise
* it adds corresponding volume to the attaching information. Returns a pointer
* to the allocated "av" object in case of success and a negative error code in
* case of failure.
*/
static struct ubi_ainf_volume *add_volume(struct ubi_attach_info *ai,
int vol_id, int pnum,
const struct ubi_vid_hdr *vid_hdr)
{
struct ubi_ainf_volume *av;
struct rb_node **p = &ai->volumes.rb_node, *parent = NULL;
ubi_assert(vol_id == be32_to_cpu(vid_hdr->vol_id));
/* Walk the volume RB-tree to look if this volume is already present */
while (*p) {
parent = *p;
av = rb_entry(parent, struct ubi_ainf_volume, rb);
if (vol_id == av->vol_id)
return av;
if (vol_id > av->vol_id)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
/* The volume is absent - add it */
av = kmalloc(sizeof(struct ubi_ainf_volume), GFP_KERNEL);
if (!av)
return ERR_PTR(-ENOMEM);
av->highest_lnum = av->leb_count = 0;
av->vol_id = vol_id;
av->root = RB_ROOT;
av->used_ebs = be32_to_cpu(vid_hdr->used_ebs);
av->data_pad = be32_to_cpu(vid_hdr->data_pad);
av->compat = vid_hdr->compat;
av->vol_type = vid_hdr->vol_type == UBI_VID_DYNAMIC ? UBI_DYNAMIC_VOLUME
: UBI_STATIC_VOLUME;
if (vol_id > ai->highest_vol_id)
ai->highest_vol_id = vol_id;
rb_link_node(&av->rb, parent, p);
rb_insert_color(&av->rb, &ai->volumes);
ai->vols_found += 1;
dbg_bld("added volume %d", vol_id);
return av;
}
/**
* ubi_compare_lebs - find out which logical eraseblock is newer.
* @ubi: UBI device description object
* @aeb: first logical eraseblock to compare
* @pnum: physical eraseblock number of the second logical eraseblock to
* compare
* @vid_hdr: volume identifier header of the second logical eraseblock
*
* This function compares 2 copies of a LEB and informs which one is newer. In
* case of success this function returns a positive value, in case of failure, a
* negative error code is returned. The success return codes use the following
* bits:
* o bit 0 is cleared: the first PEB (described by @aeb) is newer than the
* second PEB (described by @pnum and @vid_hdr);
* o bit 0 is set: the second PEB is newer;
* o bit 1 is cleared: no bit-flips were detected in the newer LEB;
* o bit 1 is set: bit-flips were detected in the newer LEB;
* o bit 2 is cleared: the older LEB is not corrupted;
* o bit 2 is set: the older LEB is corrupted.
*/
int ubi_compare_lebs(struct ubi_device *ubi, const struct ubi_ainf_peb *aeb,
int pnum, const struct ubi_vid_hdr *vid_hdr)
{
int len, err, second_is_newer, bitflips = 0, corrupted = 0;
uint32_t data_crc, crc;
struct ubi_vid_hdr *vh = NULL;
unsigned long long sqnum2 = be64_to_cpu(vid_hdr->sqnum);
if (sqnum2 == aeb->sqnum) {
/*
* This must be a really ancient UBI image which has been
* created before sequence numbers support has been added. At
* that times we used 32-bit LEB versions stored in logical
* eraseblocks. That was before UBI got into mainline. We do not
* support these images anymore. Well, those images still work,
* but only if no unclean reboots happened.
*/
ubi_err("unsupported on-flash UBI format");
return -EINVAL;
}
/* Obviously the LEB with lower sequence counter is older */
second_is_newer = (sqnum2 > aeb->sqnum);
/*
* Now we know which copy is newer. If the copy flag of the PEB with
* newer version is not set, then we just return, otherwise we have to
* check data CRC. For the second PEB we already have the VID header,
* for the first one - we'll need to re-read it from flash.
*
* Note: this may be optimized so that we wouldn't read twice.
*/
if (second_is_newer) {
if (!vid_hdr->copy_flag) {
/* It is not a copy, so it is newer */
dbg_bld("second PEB %d is newer, copy_flag is unset",
pnum);
return 1;
}
} else {
if (!aeb->copy_flag) {
/* It is not a copy, so it is newer */
dbg_bld("first PEB %d is newer, copy_flag is unset",
pnum);
return bitflips << 1;
}
vh = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
if (!vh)
return -ENOMEM;
pnum = aeb->pnum;
err = ubi_io_read_vid_hdr(ubi, pnum, vh, 0);
if (err) {
if (err == UBI_IO_BITFLIPS)
bitflips = 1;
else {
ubi_err("VID of PEB %d header is bad, but it was OK earlier, err %d",
pnum, err);
if (err > 0)
err = -EIO;
goto out_free_vidh;
}
}
vid_hdr = vh;
}
/* Read the data of the copy and check the CRC */
len = be32_to_cpu(vid_hdr->data_size);
mutex_lock(&ubi->buf_mutex);
err = ubi_io_read_data(ubi, ubi->peb_buf, pnum, 0, len);
if (err && err != UBI_IO_BITFLIPS && !mtd_is_eccerr(err))
goto out_unlock;
data_crc = be32_to_cpu(vid_hdr->data_crc);
crc = crc32(UBI_CRC32_INIT, ubi->peb_buf, len);
if (crc != data_crc) {
dbg_bld("PEB %d CRC error: calculated %#08x, must be %#08x",
pnum, crc, data_crc);
corrupted = 1;
bitflips = 0;
second_is_newer = !second_is_newer;
} else {
dbg_bld("PEB %d CRC is OK", pnum);
bitflips = !!err;
}
mutex_unlock(&ubi->buf_mutex);
ubi_free_vid_hdr(ubi, vh);
if (second_is_newer)
dbg_bld("second PEB %d is newer, copy_flag is set", pnum);
else
dbg_bld("first PEB %d is newer, copy_flag is set", pnum);
return second_is_newer | (bitflips << 1) | (corrupted << 2);
out_unlock:
mutex_unlock(&ubi->buf_mutex);
out_free_vidh:
ubi_free_vid_hdr(ubi, vh);
return err;
}
/**
* ubi_add_to_av - add used physical eraseblock to the attaching information.
* @ubi: UBI device description object
* @ai: attaching information
* @pnum: the physical eraseblock number
* @ec: erase counter
* @vid_hdr: the volume identifier header
* @bitflips: if bit-flips were detected when this physical eraseblock was read
*
* This function adds information about a used physical eraseblock to the
* 'used' tree of the corresponding volume. The function is rather complex
* because it has to handle cases when this is not the first physical
* eraseblock belonging to the same logical eraseblock, and the newer one has
* to be picked, while the older one has to be dropped. This function returns
* zero in case of success and a negative error code in case of failure.
*/
int ubi_add_to_av(struct ubi_device *ubi, struct ubi_attach_info *ai, int pnum,
int ec, const struct ubi_vid_hdr *vid_hdr, int bitflips)
{
int err, vol_id, lnum;
unsigned long long sqnum;
struct ubi_ainf_volume *av;
struct ubi_ainf_peb *aeb;
struct rb_node **p, *parent = NULL;
vol_id = be32_to_cpu(vid_hdr->vol_id);
lnum = be32_to_cpu(vid_hdr->lnum);
sqnum = be64_to_cpu(vid_hdr->sqnum);
dbg_bld("PEB %d, LEB %d:%d, EC %d, sqnum %llu, bitflips %d",
pnum, vol_id, lnum, ec, sqnum, bitflips);
av = add_volume(ai, vol_id, pnum, vid_hdr);
if (IS_ERR(av))
return PTR_ERR(av);
if (ai->max_sqnum < sqnum)
ai->max_sqnum = sqnum;
/*
* Walk the RB-tree of logical eraseblocks of volume @vol_id to look
* if this is the first instance of this logical eraseblock or not.
*/
p = &av->root.rb_node;
while (*p) {
int cmp_res;
parent = *p;
aeb = rb_entry(parent, struct ubi_ainf_peb, u.rb);
if (lnum != aeb->lnum) {
if (lnum < aeb->lnum)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
continue;
}
/*
* There is already a physical eraseblock describing the same
* logical eraseblock present.
*/
dbg_bld("this LEB already exists: PEB %d, sqnum %llu, EC %d",
aeb->pnum, aeb->sqnum, aeb->ec);
/*
* Make sure that the logical eraseblocks have different
* sequence numbers. Otherwise the image is bad.
*
* However, if the sequence number is zero, we assume it must
* be an ancient UBI image from the era when UBI did not have
* sequence numbers. We still can attach these images, unless
* there is a need to distinguish between old and new
* eraseblocks, in which case we'll refuse the image in
* 'ubi_compare_lebs()'. In other words, we attach old clean
* images, but refuse attaching old images with duplicated
* logical eraseblocks because there was an unclean reboot.
*/
if (aeb->sqnum == sqnum && sqnum != 0) {
ubi_err("two LEBs with same sequence number %llu",
sqnum);
ubi_dump_aeb(aeb, 0);
ubi_dump_vid_hdr(vid_hdr);
return -EINVAL;
}
/*
* Now we have to drop the older one and preserve the newer
* one.
*/
cmp_res = ubi_compare_lebs(ubi, aeb, pnum, vid_hdr);
if (cmp_res < 0)
return cmp_res;
if (cmp_res & 1) {
/*
* This logical eraseblock is newer than the one
* found earlier.
*/
err = validate_vid_hdr(vid_hdr, av, pnum);
if (err)
return err;
err = add_to_list(ai, aeb->pnum, aeb->vol_id,
aeb->lnum, aeb->ec, cmp_res & 4,
&ai->erase);
if (err)
return err;
aeb->ec = ec;
aeb->pnum = pnum;
aeb->vol_id = vol_id;
aeb->lnum = lnum;
aeb->scrub = ((cmp_res & 2) || bitflips);
aeb->copy_flag = vid_hdr->copy_flag;
aeb->sqnum = sqnum;
if (av->highest_lnum == lnum)
av->last_data_size =
be32_to_cpu(vid_hdr->data_size);
return 0;
} else {
/*
* This logical eraseblock is older than the one found
* previously.
*/
return add_to_list(ai, pnum, vol_id, lnum, ec,
cmp_res & 4, &ai->erase);
}
}
/*
* We've met this logical eraseblock for the first time, add it to the
* attaching information.
*/
err = validate_vid_hdr(vid_hdr, av, pnum);
if (err)
return err;
aeb = kmem_cache_alloc(ai->aeb_slab_cache, GFP_KERNEL);
if (!aeb)
return -ENOMEM;
aeb->ec = ec;
aeb->pnum = pnum;
aeb->vol_id = vol_id;
aeb->lnum = lnum;
aeb->scrub = bitflips;
aeb->copy_flag = vid_hdr->copy_flag;
aeb->sqnum = sqnum;
if (av->highest_lnum <= lnum) {
av->highest_lnum = lnum;
av->last_data_size = be32_to_cpu(vid_hdr->data_size);
}
av->leb_count += 1;
rb_link_node(&aeb->u.rb, parent, p);
rb_insert_color(&aeb->u.rb, &av->root);
return 0;
}
/**
* ubi_find_av - find volume in the attaching information.
* @ai: attaching information
* @vol_id: the requested volume ID
*
* This function returns a pointer to the volume description or %NULL if there
* are no data about this volume in the attaching information.
*/
struct ubi_ainf_volume *ubi_find_av(const struct ubi_attach_info *ai,
int vol_id)
{
struct ubi_ainf_volume *av;
struct rb_node *p = ai->volumes.rb_node;
while (p) {
av = rb_entry(p, struct ubi_ainf_volume, rb);
if (vol_id == av->vol_id)
return av;
if (vol_id > av->vol_id)
p = p->rb_left;
else
p = p->rb_right;
}
return NULL;
}
/**
* ubi_remove_av - delete attaching information about a volume.
* @ai: attaching information
* @av: the volume attaching information to delete
*/
void ubi_remove_av(struct ubi_attach_info *ai, struct ubi_ainf_volume *av)
{
struct rb_node *rb;
struct ubi_ainf_peb *aeb;
dbg_bld("remove attaching information about volume %d", av->vol_id);
while ((rb = rb_first(&av->root))) {
aeb = rb_entry(rb, struct ubi_ainf_peb, u.rb);
rb_erase(&aeb->u.rb, &av->root);
list_add_tail(&aeb->u.list, &ai->erase);
}
rb_erase(&av->rb, &ai->volumes);
kfree(av);
ai->vols_found -= 1;
}
/**
* early_erase_peb - erase a physical eraseblock.
* @ubi: UBI device description object
* @ai: attaching information
* @pnum: physical eraseblock number to erase;
* @ec: erase counter value to write (%UBI_UNKNOWN if it is unknown)
*
* This function erases physical eraseblock 'pnum', and writes the erase
* counter header to it. This function should only be used on UBI device
* initialization stages, when the EBA sub-system had not been yet initialized.
* This function returns zero in case of success and a negative error code in
* case of failure.
*/
static int early_erase_peb(struct ubi_device *ubi,
const struct ubi_attach_info *ai, int pnum, int ec)
{
int err;
struct ubi_ec_hdr *ec_hdr;
if ((long long)ec >= UBI_MAX_ERASECOUNTER) {
/*
* Erase counter overflow. Upgrade UBI and use 64-bit
* erase counters internally.
*/
ubi_err("erase counter overflow at PEB %d, EC %d", pnum, ec);
return -EINVAL;
}
ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
if (!ec_hdr)
return -ENOMEM;
ec_hdr->ec = cpu_to_be64(ec);
err = ubi_io_sync_erase(ubi, pnum, 0);
if (err < 0)
goto out_free;
err = ubi_io_write_ec_hdr(ubi, pnum, ec_hdr);
out_free:
kfree(ec_hdr);
return err;
}
/**
* ubi_early_get_peb - get a free physical eraseblock.
* @ubi: UBI device description object
* @ai: attaching information
*
* This function returns a free physical eraseblock. It is supposed to be
* called on the UBI initialization stages when the wear-leveling sub-system is
* not initialized yet. This function picks a physical eraseblocks from one of
* the lists, writes the EC header if it is needed, and removes it from the
* list.
*
* This function returns a pointer to the "aeb" of the found free PEB in case
* of success and an error code in case of failure.
*/
struct ubi_ainf_peb *ubi_early_get_peb(struct ubi_device *ubi,
struct ubi_attach_info *ai)
{
int err = 0;
struct ubi_ainf_peb *aeb, *tmp_aeb;
if (!list_empty(&ai->free)) {
aeb = list_entry(ai->free.next, struct ubi_ainf_peb, u.list);
list_del(&aeb->u.list);
dbg_bld("return free PEB %d, EC %d", aeb->pnum, aeb->ec);
return aeb;
}
/*
* We try to erase the first physical eraseblock from the erase list
* and pick it if we succeed, or try to erase the next one if not. And
* so forth. We don't want to take care about bad eraseblocks here -
* they'll be handled later.
*/
list_for_each_entry_safe(aeb, tmp_aeb, &ai->erase, u.list) {
if (aeb->ec == UBI_UNKNOWN)
aeb->ec = ai->mean_ec;
err = early_erase_peb(ubi, ai, aeb->pnum, aeb->ec+1);
if (err)
continue;
aeb->ec += 1;
list_del(&aeb->u.list);
dbg_bld("return PEB %d, EC %d", aeb->pnum, aeb->ec);
return aeb;
}
ubi_err("no free eraseblocks");
return ERR_PTR(-ENOSPC);
}
/**
* check_corruption - check the data area of PEB.
* @ubi: UBI device description object
* @vid_hdr: the (corrupted) VID header of this PEB
* @pnum: the physical eraseblock number to check
*
* This is a helper function which is used to distinguish between VID header
* corruptions caused by power cuts and other reasons. If the PEB contains only
* 0xFF bytes in the data area, the VID header is most probably corrupted
* because of a power cut (%0 is returned in this case). Otherwise, it was
* probably corrupted for some other reasons (%1 is returned in this case). A
* negative error code is returned if a read error occurred.
*
* If the corruption reason was a power cut, UBI can safely erase this PEB.
* Otherwise, it should preserve it to avoid possibly destroying important
* information.
*/
static int check_corruption(struct ubi_device *ubi, struct ubi_vid_hdr *vid_hdr,
int pnum)
{
int err;
mutex_lock(&ubi->buf_mutex);
memset(ubi->peb_buf, 0x00, ubi->leb_size);
err = ubi_io_read(ubi, ubi->peb_buf, pnum, ubi->leb_start,
ubi->leb_size);
if (err == UBI_IO_BITFLIPS || mtd_is_eccerr(err)) {
/*
* Bit-flips or integrity errors while reading the data area.
* It is difficult to say for sure what type of corruption is
* this, but presumably a power cut happened while this PEB was
* erased, so it became unstable and corrupted, and should be
* erased.
*/
err = 0;
goto out_unlock;
}
if (err)
goto out_unlock;
if (ubi_check_pattern(ubi->peb_buf, 0xFF, ubi->leb_size))
goto out_unlock;
ubi_err("PEB %d contains corrupted VID header, and the data does not contain all 0xFF",
pnum);
ubi_err("this may be a non-UBI PEB or a severe VID header corruption which requires manual inspection");
ubi_dump_vid_hdr(vid_hdr);
pr_err("hexdump of PEB %d offset %d, length %d",
pnum, ubi->leb_start, ubi->leb_size);
ubi_dbg_print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
ubi->peb_buf, ubi->leb_size, 1);
err = 1;
out_unlock:
mutex_unlock(&ubi->buf_mutex);
return err;
}
/**
* scan_peb - scan and process UBI headers of a PEB.
* @ubi: UBI device description object
* @ai: attaching information
* @pnum: the physical eraseblock number
* @vid: The volume ID of the found volume will be stored in this pointer
* @sqnum: The sqnum of the found volume will be stored in this pointer
*
* This function reads UBI headers of PEB @pnum, checks them, and adds
* information about this PEB to the corresponding list or RB-tree in the
* "attaching info" structure. Returns zero if the physical eraseblock was
* successfully handled and a negative error code in case of failure.
*/
static int scan_peb(struct ubi_device *ubi, struct ubi_attach_info *ai,
int pnum, int *vid, unsigned long long *sqnum)
{
long long uninitialized_var(ec);
int err, bitflips = 0, vol_id = -1, ec_err = 0;
dbg_bld("scan PEB %d", pnum);
/* Skip bad physical eraseblocks */
err = ubi_io_is_bad(ubi, pnum);
if (err < 0)
return err;
else if (err) {
ai->bad_peb_count += 1;
return 0;
}
err = ubi_io_read_ec_hdr(ubi, pnum, ech, 0);
if (err < 0)
return err;
switch (err) {
case 0:
break;
case UBI_IO_BITFLIPS:
bitflips = 1;
break;
case UBI_IO_FF:
ai->empty_peb_count += 1;
return add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
UBI_UNKNOWN, 0, &ai->erase);
case UBI_IO_FF_BITFLIPS:
ai->empty_peb_count += 1;
return add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
UBI_UNKNOWN, 1, &ai->erase);
case UBI_IO_BAD_HDR_EBADMSG:
case UBI_IO_BAD_HDR:
/*
* We have to also look at the VID header, possibly it is not
* corrupted. Set %bitflips flag in order to make this PEB be
* moved and EC be re-created.
*/
ec_err = err;
ec = UBI_UNKNOWN;
bitflips = 1;
break;
default:
ubi_err("'ubi_io_read_ec_hdr()' returned unknown code %d", err);
return -EINVAL;
}
if (!ec_err) {
int image_seq;
/* Make sure UBI version is OK */
if (ech->version != UBI_VERSION) {
ubi_err("this UBI version is %d, image version is %d",
UBI_VERSION, (int)ech->version);
return -EINVAL;
}
ec = be64_to_cpu(ech->ec);
if (ec > UBI_MAX_ERASECOUNTER) {
/*
* Erase counter overflow. The EC headers have 64 bits
* reserved, but we anyway make use of only 31 bit
* values, as this seems to be enough for any existing
* flash. Upgrade UBI and use 64-bit erase counters
* internally.
*/
ubi_err("erase counter overflow, max is %d",
UBI_MAX_ERASECOUNTER);
ubi_dump_ec_hdr(ech);
return -EINVAL;
}
/*
* Make sure that all PEBs have the same image sequence number.
* This allows us to detect situations when users flash UBI
* images incorrectly, so that the flash has the new UBI image
* and leftovers from the old one. This feature was added
* relatively recently, and the sequence number was always
* zero, because old UBI implementations always set it to zero.
* For this reasons, we do not panic if some PEBs have zero
* sequence number, while other PEBs have non-zero sequence
* number.
*/
image_seq = be32_to_cpu(ech->image_seq);
if (!ubi->image_seq && image_seq)
ubi->image_seq = image_seq;
if (ubi->image_seq && image_seq &&
ubi->image_seq != image_seq) {
ubi_err("bad image sequence number %d in PEB %d, expected %d",
image_seq, pnum, ubi->image_seq);
ubi_dump_ec_hdr(ech);
return -EINVAL;
}
}
/* OK, we've done with the EC header, let's look at the VID header */
err = ubi_io_read_vid_hdr(ubi, pnum, vidh, 0);
if (err < 0)
return err;
switch (err) {
case 0:
break;
case UBI_IO_BITFLIPS:
bitflips = 1;
break;
case UBI_IO_BAD_HDR_EBADMSG:
if (ec_err == UBI_IO_BAD_HDR_EBADMSG)
/*
* Both EC and VID headers are corrupted and were read
* with data integrity error, probably this is a bad
* PEB, bit it is not marked as bad yet. This may also
* be a result of power cut during erasure.
*/
ai->maybe_bad_peb_count += 1;
case UBI_IO_BAD_HDR:
if (ec_err)
/*
* Both headers are corrupted. There is a possibility
* that this a valid UBI PEB which has corresponding
* LEB, but the headers are corrupted. However, it is
* impossible to distinguish it from a PEB which just
* contains garbage because of a power cut during erase
* operation. So we just schedule this PEB for erasure.
*
* Besides, in case of NOR flash, we deliberately
* corrupt both headers because NOR flash erasure is
* slow and can start from the end.
*/
err = 0;
else
/*
* The EC was OK, but the VID header is corrupted. We
* have to check what is in the data area.
*/
err = check_corruption(ubi, vidh, pnum);
if (err < 0)
return err;
else if (!err)
/* This corruption is caused by a power cut */
err = add_to_list(ai, pnum, UBI_UNKNOWN,
UBI_UNKNOWN, ec, 1, &ai->erase);
else
/* This is an unexpected corruption */
err = add_corrupted(ai, pnum, ec);
if (err)
return err;
goto adjust_mean_ec;
case UBI_IO_FF_BITFLIPS:
err = add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
ec, 1, &ai->erase);
if (err)
return err;
goto adjust_mean_ec;
case UBI_IO_FF:
if (ec_err || bitflips)
err = add_to_list(ai, pnum, UBI_UNKNOWN,
UBI_UNKNOWN, ec, 1, &ai->erase);
else
err = add_to_list(ai, pnum, UBI_UNKNOWN,
UBI_UNKNOWN, ec, 0, &ai->free);
if (err)
return err;
goto adjust_mean_ec;
default:
ubi_err("'ubi_io_read_vid_hdr()' returned unknown code %d",
err);
return -EINVAL;
}
vol_id = be32_to_cpu(vidh->vol_id);
if (vid)
*vid = vol_id;
if (sqnum)
*sqnum = be64_to_cpu(vidh->sqnum);
if (vol_id > UBI_MAX_VOLUMES && vol_id != UBI_LAYOUT_VOLUME_ID) {
int lnum = be32_to_cpu(vidh->lnum);
/* Unsupported internal volume */
switch (vidh->compat) {
case UBI_COMPAT_DELETE:
if (vol_id != UBI_FM_SB_VOLUME_ID
&& vol_id != UBI_FM_DATA_VOLUME_ID) {
ubi_msg("\"delete\" compatible internal volume %d:%d found, will remove it",
vol_id, lnum);
}
err = add_to_list(ai, pnum, vol_id, lnum,
ec, 1, &ai->erase);
if (err)
return err;
return 0;
case UBI_COMPAT_RO:
ubi_msg("read-only compatible internal volume %d:%d found, switch to read-only mode",
vol_id, lnum);
ubi->ro_mode = 1;
break;
case UBI_COMPAT_PRESERVE:
ubi_msg("\"preserve\" compatible internal volume %d:%d found",
vol_id, lnum);
err = add_to_list(ai, pnum, vol_id, lnum,
ec, 0, &ai->alien);
if (err)
return err;
return 0;
case UBI_COMPAT_REJECT:
ubi_err("incompatible internal volume %d:%d found",
vol_id, lnum);
return -EINVAL;
}
}
if (ec_err)
ubi_warn("valid VID header but corrupted EC header at PEB %d",
pnum);
err = ubi_add_to_av(ubi, ai, pnum, ec, vidh, bitflips);
if (err)
return err;
adjust_mean_ec:
if (!ec_err) {
ai->ec_sum += ec;
ai->ec_count += 1;
if (ec > ai->max_ec)
ai->max_ec = ec;
if (ec < ai->min_ec)
ai->min_ec = ec;
}
return 0;
}
/**
* late_analysis - analyze the overall situation with PEB.
* @ubi: UBI device description object
* @ai: attaching information
*
* This is a helper function which takes a look what PEBs we have after we
* gather information about all of them ("ai" is compete). It decides whether
* the flash is empty and should be formatted of whether there are too many
* corrupted PEBs and we should not attach this MTD device. Returns zero if we
* should proceed with attaching the MTD device, and %-EINVAL if we should not.
*/
static int late_analysis(struct ubi_device *ubi, struct ubi_attach_info *ai)
{
struct ubi_ainf_peb *aeb;
int max_corr, peb_count;
peb_count = ubi->peb_count - ai->bad_peb_count - ai->alien_peb_count;
max_corr = peb_count / 20 ?: 8;
/*
* Few corrupted PEBs is not a problem and may be just a result of
* unclean reboots. However, many of them may indicate some problems
* with the flash HW or driver.
*/
if (ai->corr_peb_count) {
ubi_err("%d PEBs are corrupted and preserved",
ai->corr_peb_count);
pr_err("Corrupted PEBs are:");
list_for_each_entry(aeb, &ai->corr, u.list)
pr_cont(" %d", aeb->pnum);
pr_cont("\n");
/*
* If too many PEBs are corrupted, we refuse attaching,
* otherwise, only print a warning.
*/
if (ai->corr_peb_count >= max_corr) {
ubi_err("too many corrupted PEBs, refusing");
return -EINVAL;
}
}
if (ai->empty_peb_count + ai->maybe_bad_peb_count == peb_count) {
/*
* All PEBs are empty, or almost all - a couple PEBs look like
* they may be bad PEBs which were not marked as bad yet.
*
* This piece of code basically tries to distinguish between
* the following situations:
*
* 1. Flash is empty, but there are few bad PEBs, which are not
* marked as bad so far, and which were read with error. We
* want to go ahead and format this flash. While formatting,
* the faulty PEBs will probably be marked as bad.
*
* 2. Flash contains non-UBI data and we do not want to format
* it and destroy possibly important information.
*/
if (ai->maybe_bad_peb_count <= 2) {
ai->is_empty = 1;
ubi_msg("empty MTD device detected");
get_random_bytes(&ubi->image_seq,
sizeof(ubi->image_seq));
} else {
ubi_err("MTD device is not UBI-formatted and possibly contains non-UBI data - refusing it");
return -EINVAL;
}
}
return 0;
}
/**
* destroy_av - free volume attaching information.
* @av: volume attaching information
* @ai: attaching information
*
* This function destroys the volume attaching information.
*/
static void destroy_av(struct ubi_attach_info *ai, struct ubi_ainf_volume *av)
{
struct ubi_ainf_peb *aeb;
struct rb_node *this = av->root.rb_node;
while (this) {
if (this->rb_left)
this = this->rb_left;
else if (this->rb_right)
this = this->rb_right;
else {
aeb = rb_entry(this, struct ubi_ainf_peb, u.rb);
this = rb_parent(this);
if (this) {
if (this->rb_left == &aeb->u.rb)
this->rb_left = NULL;
else
this->rb_right = NULL;
}
kmem_cache_free(ai->aeb_slab_cache, aeb);
}
}
kfree(av);
}
/**
* destroy_ai - destroy attaching information.
* @ai: attaching information
*/
static void destroy_ai(struct ubi_attach_info *ai)
{
struct ubi_ainf_peb *aeb, *aeb_tmp;
struct ubi_ainf_volume *av;
struct rb_node *rb;
list_for_each_entry_safe(aeb, aeb_tmp, &ai->alien, u.list) {
list_del(&aeb->u.list);
kmem_cache_free(ai->aeb_slab_cache, aeb);
}
list_for_each_entry_safe(aeb, aeb_tmp, &ai->erase, u.list) {
list_del(&aeb->u.list);
kmem_cache_free(ai->aeb_slab_cache, aeb);
}
list_for_each_entry_safe(aeb, aeb_tmp, &ai->corr, u.list) {
list_del(&aeb->u.list);
kmem_cache_free(ai->aeb_slab_cache, aeb);
}
list_for_each_entry_safe(aeb, aeb_tmp, &ai->free, u.list) {
list_del(&aeb->u.list);
kmem_cache_free(ai->aeb_slab_cache, aeb);
}
/* Destroy the volume RB-tree */
rb = ai->volumes.rb_node;
while (rb) {
if (rb->rb_left)
rb = rb->rb_left;
else if (rb->rb_right)
rb = rb->rb_right;
else {
av = rb_entry(rb, struct ubi_ainf_volume, rb);
rb = rb_parent(rb);
if (rb) {
if (rb->rb_left == &av->rb)
rb->rb_left = NULL;
else
rb->rb_right = NULL;
}
destroy_av(ai, av);
}
}
if (ai->aeb_slab_cache)
kmem_cache_destroy(ai->aeb_slab_cache);
kfree(ai);
}
/**
* scan_all - scan entire MTD device.
* @ubi: UBI device description object
* @ai: attach info object
* @start: start scanning at this PEB
*
* This function does full scanning of an MTD device and returns complete
* information about it in form of a "struct ubi_attach_info" object. In case
* of failure, an error code is returned.
*/
static int scan_all(struct ubi_device *ubi, struct ubi_attach_info *ai,
int start)
{
int err, pnum;
struct rb_node *rb1, *rb2;
struct ubi_ainf_volume *av;
struct ubi_ainf_peb *aeb;
err = -ENOMEM;
ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
if (!ech)
return err;
vidh = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
if (!vidh)
goto out_ech;
for (pnum = start; pnum < ubi->peb_count; pnum++) {
cond_resched();
dbg_gen("process PEB %d", pnum);
err = scan_peb(ubi, ai, pnum, NULL, NULL);
if (err < 0)
goto out_vidh;
}
ubi_msg("scanning is finished");
/* Calculate mean erase counter */
if (ai->ec_count)
ai->mean_ec = div_u64(ai->ec_sum, ai->ec_count);
err = late_analysis(ubi, ai);
if (err)
goto out_vidh;
/*
* In case of unknown erase counter we use the mean erase counter
* value.
*/
ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb)
if (aeb->ec == UBI_UNKNOWN)
aeb->ec = ai->mean_ec;
}
list_for_each_entry(aeb, &ai->free, u.list) {
if (aeb->ec == UBI_UNKNOWN)
aeb->ec = ai->mean_ec;
}
list_for_each_entry(aeb, &ai->corr, u.list)
if (aeb->ec == UBI_UNKNOWN)
aeb->ec = ai->mean_ec;
list_for_each_entry(aeb, &ai->erase, u.list)
if (aeb->ec == UBI_UNKNOWN)
aeb->ec = ai->mean_ec;
err = self_check_ai(ubi, ai);
if (err)
goto out_vidh;
ubi_free_vid_hdr(ubi, vidh);
kfree(ech);
return 0;
out_vidh:
ubi_free_vid_hdr(ubi, vidh);
out_ech:
kfree(ech);
return err;
}
#ifdef CONFIG_MTD_UBI_FASTMAP
/**
* scan_fastmap - try to find a fastmap and attach from it.
* @ubi: UBI device description object
* @ai: attach info object
*
* Returns 0 on success, negative return values indicate an internal
* error.
* UBI_NO_FASTMAP denotes that no fastmap was found.
* UBI_BAD_FASTMAP denotes that the found fastmap was invalid.
*/
static int scan_fast(struct ubi_device *ubi, struct ubi_attach_info *ai)
{
int err, pnum, fm_anchor = -1;
unsigned long long max_sqnum = 0;
err = -ENOMEM;
ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
if (!ech)
goto out;
vidh = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
if (!vidh)
goto out_ech;
for (pnum = 0; pnum < UBI_FM_MAX_START; pnum++) {
int vol_id = -1;
unsigned long long sqnum = -1;
cond_resched();
dbg_gen("process PEB %d", pnum);
err = scan_peb(ubi, ai, pnum, &vol_id, &sqnum);
if (err < 0)
goto out_vidh;
if (vol_id == UBI_FM_SB_VOLUME_ID && sqnum > max_sqnum) {
max_sqnum = sqnum;
fm_anchor = pnum;
}
}
ubi_free_vid_hdr(ubi, vidh);
kfree(ech);
if (fm_anchor < 0)
return UBI_NO_FASTMAP;
return ubi_scan_fastmap(ubi, ai, fm_anchor);
out_vidh:
ubi_free_vid_hdr(ubi, vidh);
out_ech:
kfree(ech);
out:
return err;
}
#endif
static struct ubi_attach_info *alloc_ai(const char *slab_name)
{
struct ubi_attach_info *ai;
ai = kzalloc(sizeof(struct ubi_attach_info), GFP_KERNEL);
if (!ai)
return ai;
INIT_LIST_HEAD(&ai->corr);
INIT_LIST_HEAD(&ai->free);
INIT_LIST_HEAD(&ai->erase);
INIT_LIST_HEAD(&ai->alien);
ai->volumes = RB_ROOT;
ai->aeb_slab_cache = kmem_cache_create(slab_name,
sizeof(struct ubi_ainf_peb),
0, 0, NULL);
if (!ai->aeb_slab_cache) {
kfree(ai);
ai = NULL;
}
return ai;
}
/**
* ubi_attach - attach an MTD device.
* @ubi: UBI device descriptor
* @force_scan: if set to non-zero attach by scanning
*
* This function returns zero in case of success and a negative error code in
* case of failure.
*/
int ubi_attach(struct ubi_device *ubi, int force_scan)
{
int err;
struct ubi_attach_info *ai;
ai = alloc_ai("ubi_aeb_slab_cache");
if (!ai)
return -ENOMEM;
#ifdef CONFIG_MTD_UBI_FASTMAP
/* On small flash devices we disable fastmap in any case. */
if ((int)mtd_div_by_eb(ubi->mtd->size, ubi->mtd) <= UBI_FM_MAX_START) {
ubi->fm_disabled = 1;
force_scan = 1;
}
if (force_scan)
err = scan_all(ubi, ai, 0);
else {
err = scan_fast(ubi, ai);
if (err > 0) {
if (err != UBI_NO_FASTMAP) {
destroy_ai(ai);
ai = alloc_ai("ubi_aeb_slab_cache2");
if (!ai)
return -ENOMEM;
}
err = scan_all(ubi, ai, UBI_FM_MAX_START);
}
}
#else
err = scan_all(ubi, ai, 0);
#endif
if (err)
goto out_ai;
ubi->bad_peb_count = ai->bad_peb_count;
ubi->good_peb_count = ubi->peb_count - ubi->bad_peb_count;
ubi->corr_peb_count = ai->corr_peb_count;
ubi->max_ec = ai->max_ec;
ubi->mean_ec = ai->mean_ec;
dbg_gen("max. sequence number: %llu", ai->max_sqnum);
err = ubi_read_volume_table(ubi, ai);
if (err)
goto out_ai;
err = ubi_wl_init(ubi, ai);
if (err)
goto out_vtbl;
err = ubi_eba_init(ubi, ai);
if (err)
goto out_wl;
#ifdef CONFIG_MTD_UBI_FASTMAP
if (ubi->fm && ubi_dbg_chk_gen(ubi)) {
struct ubi_attach_info *scan_ai;
scan_ai = alloc_ai("ubi_ckh_aeb_slab_cache");
if (!scan_ai)
goto out_wl;
err = scan_all(ubi, scan_ai, 0);
if (err) {
destroy_ai(scan_ai);
goto out_wl;
}
err = self_check_eba(ubi, ai, scan_ai);
destroy_ai(scan_ai);
if (err)
goto out_wl;
}
#endif
destroy_ai(ai);
return 0;
out_wl:
ubi_wl_close(ubi);
out_vtbl:
ubi_free_internal_volumes(ubi);
vfree(ubi->vtbl);
out_ai:
destroy_ai(ai);
return err;
}
/**
* self_check_ai - check the attaching information.
* @ubi: UBI device description object
* @ai: attaching information
*
* This function returns zero if the attaching information is all right, and a
* negative error code if not or if an error occurred.
*/
static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai)
{
int pnum, err, vols_found = 0;
struct rb_node *rb1, *rb2;
struct ubi_ainf_volume *av;
struct ubi_ainf_peb *aeb, *last_aeb;
uint8_t *buf;
if (!ubi_dbg_chk_gen(ubi))
return 0;
/*
* At first, check that attaching information is OK.
*/
ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
int leb_count = 0;
cond_resched();
vols_found += 1;
if (ai->is_empty) {
ubi_err("bad is_empty flag");
goto bad_av;
}
if (av->vol_id < 0 || av->highest_lnum < 0 ||
av->leb_count < 0 || av->vol_type < 0 || av->used_ebs < 0 ||
av->data_pad < 0 || av->last_data_size < 0) {
ubi_err("negative values");
goto bad_av;
}
if (av->vol_id >= UBI_MAX_VOLUMES &&
av->vol_id < UBI_INTERNAL_VOL_START) {
ubi_err("bad vol_id");
goto bad_av;
}
if (av->vol_id > ai->highest_vol_id) {
ubi_err("highest_vol_id is %d, but vol_id %d is there",
ai->highest_vol_id, av->vol_id);
goto out;
}
if (av->vol_type != UBI_DYNAMIC_VOLUME &&
av->vol_type != UBI_STATIC_VOLUME) {
ubi_err("bad vol_type");
goto bad_av;
}
if (av->data_pad > ubi->leb_size / 2) {
ubi_err("bad data_pad");
goto bad_av;
}
last_aeb = NULL;
ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
cond_resched();
last_aeb = aeb;
leb_count += 1;
if (aeb->pnum < 0 || aeb->ec < 0) {
ubi_err("negative values");
goto bad_aeb;
}
if (aeb->ec < ai->min_ec) {
ubi_err("bad ai->min_ec (%d), %d found",
ai->min_ec, aeb->ec);
goto bad_aeb;
}
if (aeb->ec > ai->max_ec) {
ubi_err("bad ai->max_ec (%d), %d found",
ai->max_ec, aeb->ec);
goto bad_aeb;
}
if (aeb->pnum >= ubi->peb_count) {
ubi_err("too high PEB number %d, total PEBs %d",
aeb->pnum, ubi->peb_count);
goto bad_aeb;
}
if (av->vol_type == UBI_STATIC_VOLUME) {
if (aeb->lnum >= av->used_ebs) {
ubi_err("bad lnum or used_ebs");
goto bad_aeb;
}
} else {
if (av->used_ebs != 0) {
ubi_err("non-zero used_ebs");
goto bad_aeb;
}
}
if (aeb->lnum > av->highest_lnum) {
ubi_err("incorrect highest_lnum or lnum");
goto bad_aeb;
}
}
if (av->leb_count != leb_count) {
ubi_err("bad leb_count, %d objects in the tree",
leb_count);
goto bad_av;
}
if (!last_aeb)
continue;
aeb = last_aeb;
if (aeb->lnum != av->highest_lnum) {
ubi_err("bad highest_lnum");
goto bad_aeb;
}
}
if (vols_found != ai->vols_found) {
ubi_err("bad ai->vols_found %d, should be %d",
ai->vols_found, vols_found);
goto out;
}
/* Check that attaching information is correct */
ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
last_aeb = NULL;
ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
int vol_type;
cond_resched();
last_aeb = aeb;
err = ubi_io_read_vid_hdr(ubi, aeb->pnum, vidh, 1);
if (err && err != UBI_IO_BITFLIPS) {
ubi_err("VID header is not OK (%d)", err);
if (err > 0)
err = -EIO;
return err;
}
vol_type = vidh->vol_type == UBI_VID_DYNAMIC ?
UBI_DYNAMIC_VOLUME : UBI_STATIC_VOLUME;
if (av->vol_type != vol_type) {
ubi_err("bad vol_type");
goto bad_vid_hdr;
}
if (aeb->sqnum != be64_to_cpu(vidh->sqnum)) {
ubi_err("bad sqnum %llu", aeb->sqnum);
goto bad_vid_hdr;
}
if (av->vol_id != be32_to_cpu(vidh->vol_id)) {
ubi_err("bad vol_id %d", av->vol_id);
goto bad_vid_hdr;
}
if (av->compat != vidh->compat) {
ubi_err("bad compat %d", vidh->compat);
goto bad_vid_hdr;
}
if (aeb->lnum != be32_to_cpu(vidh->lnum)) {
ubi_err("bad lnum %d", aeb->lnum);
goto bad_vid_hdr;
}
if (av->used_ebs != be32_to_cpu(vidh->used_ebs)) {
ubi_err("bad used_ebs %d", av->used_ebs);
goto bad_vid_hdr;
}
if (av->data_pad != be32_to_cpu(vidh->data_pad)) {
ubi_err("bad data_pad %d", av->data_pad);
goto bad_vid_hdr;
}
}
if (!last_aeb)
continue;
if (av->highest_lnum != be32_to_cpu(vidh->lnum)) {
ubi_err("bad highest_lnum %d", av->highest_lnum);
goto bad_vid_hdr;
}
if (av->last_data_size != be32_to_cpu(vidh->data_size)) {
ubi_err("bad last_data_size %d", av->last_data_size);
goto bad_vid_hdr;
}
}
/*
* Make sure that all the physical eraseblocks are in one of the lists
* or trees.
*/
buf = kzalloc(ubi->peb_count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
for (pnum = 0; pnum < ubi->peb_count; pnum++) {
err = ubi_io_is_bad(ubi, pnum);
if (err < 0) {
kfree(buf);
return err;
} else if (err)
buf[pnum] = 1;
}
ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb)
ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb)
buf[aeb->pnum] = 1;
list_for_each_entry(aeb, &ai->free, u.list)
buf[aeb->pnum] = 1;
list_for_each_entry(aeb, &ai->corr, u.list)
buf[aeb->pnum] = 1;
list_for_each_entry(aeb, &ai->erase, u.list)
buf[aeb->pnum] = 1;
list_for_each_entry(aeb, &ai->alien, u.list)
buf[aeb->pnum] = 1;
err = 0;
for (pnum = 0; pnum < ubi->peb_count; pnum++)
if (!buf[pnum]) {
ubi_err("PEB %d is not referred", pnum);
err = 1;
}
kfree(buf);
if (err)
goto out;
return 0;
bad_aeb:
ubi_err("bad attaching information about LEB %d", aeb->lnum);
ubi_dump_aeb(aeb, 0);
ubi_dump_av(av);
goto out;
bad_av:
ubi_err("bad attaching information about volume %d", av->vol_id);
ubi_dump_av(av);
goto out;
bad_vid_hdr:
ubi_err("bad attaching information about volume %d", av->vol_id);
ubi_dump_av(av);
ubi_dump_vid_hdr(vidh);
out:
dump_stack();
return -EINVAL;
}
| gpl-2.0 |
rajat1994/linux | drivers/target/iscsi/iscsi_target_transport.c | 1236 | 1202 | #include <linux/spinlock.h>
#include <linux/list.h>
#include <target/iscsi/iscsi_transport.h>
static LIST_HEAD(g_transport_list);
static DEFINE_MUTEX(transport_mutex);
struct iscsit_transport *iscsit_get_transport(int type)
{
struct iscsit_transport *t;
mutex_lock(&transport_mutex);
list_for_each_entry(t, &g_transport_list, t_node) {
if (t->transport_type == type) {
if (t->owner && !try_module_get(t->owner)) {
t = NULL;
}
mutex_unlock(&transport_mutex);
return t;
}
}
mutex_unlock(&transport_mutex);
return NULL;
}
void iscsit_put_transport(struct iscsit_transport *t)
{
module_put(t->owner);
}
int iscsit_register_transport(struct iscsit_transport *t)
{
INIT_LIST_HEAD(&t->t_node);
mutex_lock(&transport_mutex);
list_add_tail(&t->t_node, &g_transport_list);
mutex_unlock(&transport_mutex);
pr_debug("Registered iSCSI transport: %s\n", t->name);
return 0;
}
EXPORT_SYMBOL(iscsit_register_transport);
void iscsit_unregister_transport(struct iscsit_transport *t)
{
mutex_lock(&transport_mutex);
list_del(&t->t_node);
mutex_unlock(&transport_mutex);
pr_debug("Unregistered iSCSI transport: %s\n", t->name);
}
EXPORT_SYMBOL(iscsit_unregister_transport);
| gpl-2.0 |
dagnarf/i957kernel | drivers/media/video/tda7432.c | 1492 | 12921 | /*
* For the STS-Thompson TDA7432 audio processor chip
*
* Handles audio functions: volume, balance, tone, loudness
* This driver will not complain if used with any
* other i2c device with the same address.
*
* Muting and tone control by Jonathan Isom <jisom@ematic.com>
*
* Copyright (c) 2000 Eric Sandeen <eric_sandeen@bigfoot.com>
* Copyright (c) 2006 Mauro Carvalho Chehab <mchehab@infradead.org>
* This code is placed under the terms of the GNU General Public License
* Based on tda9855.c by Steve VanDeBogart (vandebo@uclink.berkeley.edu)
* Which was based on tda8425.c by Greg Alexander (c) 1998
*
* OPTIONS:
* debug - set to 1 if you'd like to see debug messages
* set to 2 if you'd like to be inundated with debug messages
*
* loudness - set between 0 and 15 for varying degrees of loudness effect
*
* maxvol - set maximium volume to +20db (1), default is 0db(0)
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/i2c-addr.h>
#include <media/v4l2-i2c-drv.h>
#ifndef VIDEO_AUDIO_BALANCE
# define VIDEO_AUDIO_BALANCE 32
#endif
MODULE_AUTHOR("Eric Sandeen <eric_sandeen@bigfoot.com>");
MODULE_DESCRIPTION("bttv driver for the tda7432 audio processor chip");
MODULE_LICENSE("GPL");
static int maxvol;
static int loudness; /* disable loudness by default */
static int debug; /* insmod parameter */
module_param(debug, int, S_IRUGO | S_IWUSR);
module_param(loudness, int, S_IRUGO);
MODULE_PARM_DESC(maxvol,"Set maximium volume to +20db (0), default is 0db(1)");
module_param(maxvol, int, S_IRUGO | S_IWUSR);
/* Structure of address and subaddresses for the tda7432 */
struct tda7432 {
struct v4l2_subdev sd;
int addr;
int input;
int volume;
int muted;
int bass, treble;
int lf, lr, rf, rr;
int loud;
};
static inline struct tda7432 *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct tda7432, sd);
}
/* The TDA7432 is made by STS-Thompson
* http://www.st.com
* http://us.st.com/stonline/books/pdf/docs/4056.pdf
*
* TDA7432: I2C-bus controlled basic audio processor
*
* The TDA7432 controls basic audio functions like volume, balance,
* and tone control (including loudness). It also has four channel
* output (for front and rear). Since most vidcap cards probably
* don't have 4 channel output, this driver will set front & rear
* together (no independent control).
*/
/* Subaddresses for TDA7432 */
#define TDA7432_IN 0x00 /* Input select */
#define TDA7432_VL 0x01 /* Volume */
#define TDA7432_TN 0x02 /* Bass, Treble (Tone) */
#define TDA7432_LF 0x03 /* Attenuation LF (Left Front) */
#define TDA7432_LR 0x04 /* Attenuation LR (Left Rear) */
#define TDA7432_RF 0x05 /* Attenuation RF (Right Front) */
#define TDA7432_RR 0x06 /* Attenuation RR (Right Rear) */
#define TDA7432_LD 0x07 /* Loudness */
/* Masks for bits in TDA7432 subaddresses */
/* Many of these not used - just for documentation */
/* Subaddress 0x00 - Input selection and bass control */
/* Bits 0,1,2 control input:
* 0x00 - Stereo input
* 0x02 - Mono input
* 0x03 - Mute (Using Attenuators Plays better with modules)
* Mono probably isn't used - I'm guessing only the stereo
* input is connected on most cards, so we'll set it to stereo.
*
* Bit 3 controls bass cut: 0/1 is non-symmetric/symmetric bass cut
* Bit 4 controls bass range: 0/1 is extended/standard bass range
*
* Highest 3 bits not used
*/
#define TDA7432_STEREO_IN 0
#define TDA7432_MONO_IN 2 /* Probably won't be used */
#define TDA7432_BASS_SYM 1 << 3
#define TDA7432_BASS_NORM 1 << 4
/* Subaddress 0x01 - Volume */
/* Lower 7 bits control volume from -79dB to +32dB in 1dB steps
* Recommended maximum is +20 dB
*
* +32dB: 0x00
* +20dB: 0x0c
* 0dB: 0x20
* -79dB: 0x6f
*
* MSB (bit 7) controls loudness: 1/0 is loudness on/off
*/
#define TDA7432_VOL_0DB 0x20
#define TDA7432_LD_ON 1 << 7
/* Subaddress 0x02 - Tone control */
/* Bits 0,1,2 control absolute treble gain from 0dB to 14dB
* 0x0 is 14dB, 0x7 is 0dB
*
* Bit 3 controls treble attenuation/gain (sign)
* 1 = gain (+)
* 0 = attenuation (-)
*
* Bits 4,5,6 control absolute bass gain from 0dB to 14dB
* (This is only true for normal base range, set in 0x00)
* 0x0 << 4 is 14dB, 0x7 is 0dB
*
* Bit 7 controls bass attenuation/gain (sign)
* 1 << 7 = gain (+)
* 0 << 7 = attenuation (-)
*
* Example:
* 1 1 0 1 0 1 0 1 is +4dB bass, -4dB treble
*/
#define TDA7432_TREBLE_0DB 0xf
#define TDA7432_TREBLE 7
#define TDA7432_TREBLE_GAIN 1 << 3
#define TDA7432_BASS_0DB 0xf
#define TDA7432_BASS 7 << 4
#define TDA7432_BASS_GAIN 1 << 7
/* Subaddress 0x03 - Left Front attenuation */
/* Subaddress 0x04 - Left Rear attenuation */
/* Subaddress 0x05 - Right Front attenuation */
/* Subaddress 0x06 - Right Rear attenuation */
/* Bits 0,1,2,3,4 control attenuation from 0dB to -37.5dB
* in 1.5dB steps.
*
* 0x00 is 0dB
* 0x1f is -37.5dB
*
* Bit 5 mutes that channel when set (1 = mute, 0 = unmute)
* We'll use the mute on the input, though (above)
* Bits 6,7 unused
*/
#define TDA7432_ATTEN_0DB 0x00
#define TDA7432_MUTE 0x1 << 5
/* Subaddress 0x07 - Loudness Control */
/* Bits 0,1,2,3 control loudness from 0dB to -15dB in 1dB steps
* when bit 4 is NOT set
*
* 0x0 is 0dB
* 0xf is -15dB
*
* If bit 4 is set, then there is a flat attenuation according to
* the lower 4 bits, as above.
*
* Bits 5,6,7 unused
*/
/* Begin code */
static int tda7432_write(struct v4l2_subdev *sd, int subaddr, int val)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
unsigned char buffer[2];
v4l2_dbg(2, debug, sd, "In tda7432_write\n");
v4l2_dbg(1, debug, sd, "Writing %d 0x%x\n", subaddr, val);
buffer[0] = subaddr;
buffer[1] = val;
if (2 != i2c_master_send(client, buffer, 2)) {
v4l2_err(sd, "I/O error, trying (write %d 0x%x)\n",
subaddr, val);
return -1;
}
return 0;
}
static int tda7432_set(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tda7432 *t = to_state(sd);
unsigned char buf[16];
v4l2_dbg(1, debug, sd,
"tda7432: 7432_set(0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x)\n",
t->input, t->volume, t->bass, t->treble, t->lf, t->lr,
t->rf, t->rr, t->loud);
buf[0] = TDA7432_IN;
buf[1] = t->input;
buf[2] = t->volume;
buf[3] = t->bass;
buf[4] = t->treble;
buf[5] = t->lf;
buf[6] = t->lr;
buf[7] = t->rf;
buf[8] = t->rr;
buf[9] = t->loud;
if (10 != i2c_master_send(client, buf, 10)) {
v4l2_err(sd, "I/O error, trying tda7432_set\n");
return -1;
}
return 0;
}
static void do_tda7432_init(struct v4l2_subdev *sd)
{
struct tda7432 *t = to_state(sd);
v4l2_dbg(2, debug, sd, "In tda7432_init\n");
t->input = TDA7432_STEREO_IN | /* Main (stereo) input */
TDA7432_BASS_SYM | /* Symmetric bass cut */
TDA7432_BASS_NORM; /* Normal bass range */
t->volume = 0x3b ; /* -27dB Volume */
if (loudness) /* Turn loudness on? */
t->volume |= TDA7432_LD_ON;
t->muted = 1;
t->treble = TDA7432_TREBLE_0DB; /* 0dB Treble */
t->bass = TDA7432_BASS_0DB; /* 0dB Bass */
t->lf = TDA7432_ATTEN_0DB; /* 0dB attenuation */
t->lr = TDA7432_ATTEN_0DB; /* 0dB attenuation */
t->rf = TDA7432_ATTEN_0DB; /* 0dB attenuation */
t->rr = TDA7432_ATTEN_0DB; /* 0dB attenuation */
t->loud = loudness; /* insmod parameter */
tda7432_set(sd);
}
static int tda7432_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct tda7432 *t = to_state(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
ctrl->value=t->muted;
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (!maxvol){ /* max +20db */
ctrl->value = ( 0x6f - (t->volume & 0x7F) ) * 630;
} else { /* max 0db */
ctrl->value = ( 0x6f - (t->volume & 0x7F) ) * 829;
}
return 0;
case V4L2_CID_AUDIO_BALANCE:
{
if ( (t->lf) < (t->rf) )
/* right is attenuated, balance shifted left */
ctrl->value = (32768 - 1057*(t->rf));
else
/* left is attenuated, balance shifted right */
ctrl->value = (32768 + 1057*(t->lf));
return 0;
}
case V4L2_CID_AUDIO_BASS:
{
/* Bass/treble 4 bits each */
int bass=t->bass;
if(bass >= 0x8)
bass = ~(bass - 0x8) & 0xf;
ctrl->value = (bass << 12)+(bass << 8)+(bass << 4)+(bass);
return 0;
}
case V4L2_CID_AUDIO_TREBLE:
{
int treble=t->treble;
if(treble >= 0x8)
treble = ~(treble - 0x8) & 0xf;
ctrl->value = (treble << 12)+(treble << 8)+(treble << 4)+(treble);
return 0;
}
}
return -EINVAL;
}
static int tda7432_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct tda7432 *t = to_state(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
t->muted=ctrl->value;
break;
case V4L2_CID_AUDIO_VOLUME:
if(!maxvol){ /* max +20db */
t->volume = 0x6f - ((ctrl->value)/630);
} else { /* max 0db */
t->volume = 0x6f - ((ctrl->value)/829);
}
if (loudness) /* Turn on the loudness bit */
t->volume |= TDA7432_LD_ON;
tda7432_write(sd, TDA7432_VL, t->volume);
return 0;
case V4L2_CID_AUDIO_BALANCE:
if (ctrl->value < 32768) {
/* shifted to left, attenuate right */
t->rr = (32768 - ctrl->value)/1057;
t->rf = t->rr;
t->lr = TDA7432_ATTEN_0DB;
t->lf = TDA7432_ATTEN_0DB;
} else if(ctrl->value > 32769) {
/* shifted to right, attenuate left */
t->lf = (ctrl->value - 32768)/1057;
t->lr = t->lf;
t->rr = TDA7432_ATTEN_0DB;
t->rf = TDA7432_ATTEN_0DB;
} else {
/* centered */
t->rr = TDA7432_ATTEN_0DB;
t->rf = TDA7432_ATTEN_0DB;
t->lf = TDA7432_ATTEN_0DB;
t->lr = TDA7432_ATTEN_0DB;
}
break;
case V4L2_CID_AUDIO_BASS:
t->bass = ctrl->value >> 12;
if(t->bass>= 0x8)
t->bass = (~t->bass & 0xf) + 0x8 ;
tda7432_write(sd, TDA7432_TN, 0x10 | (t->bass << 4) | t->treble);
return 0;
case V4L2_CID_AUDIO_TREBLE:
t->treble= ctrl->value >> 12;
if(t->treble>= 0x8)
t->treble = (~t->treble & 0xf) + 0x8 ;
tda7432_write(sd, TDA7432_TN, 0x10 | (t->bass << 4) | t->treble);
return 0;
default:
return -EINVAL;
}
/* Used for both mute and balance changes */
if (t->muted)
{
/* Mute & update balance*/
tda7432_write(sd, TDA7432_LF, t->lf | TDA7432_MUTE);
tda7432_write(sd, TDA7432_LR, t->lr | TDA7432_MUTE);
tda7432_write(sd, TDA7432_RF, t->rf | TDA7432_MUTE);
tda7432_write(sd, TDA7432_RR, t->rr | TDA7432_MUTE);
} else {
tda7432_write(sd, TDA7432_LF, t->lf);
tda7432_write(sd, TDA7432_LR, t->lr);
tda7432_write(sd, TDA7432_RF, t->rf);
tda7432_write(sd, TDA7432_RR, t->rr);
}
return 0;
}
static int tda7432_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_AUDIO_VOLUME:
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 58880);
case V4L2_CID_AUDIO_MUTE:
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 0);
case V4L2_CID_AUDIO_BALANCE:
case V4L2_CID_AUDIO_BASS:
case V4L2_CID_AUDIO_TREBLE:
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768);
}
return -EINVAL;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops tda7432_core_ops = {
.queryctrl = tda7432_queryctrl,
.g_ctrl = tda7432_g_ctrl,
.s_ctrl = tda7432_s_ctrl,
};
static const struct v4l2_subdev_ops tda7432_ops = {
.core = &tda7432_core_ops,
};
/* ----------------------------------------------------------------------- */
/* *********************** *
* i2c interface functions *
* *********************** */
static int tda7432_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tda7432 *t;
struct v4l2_subdev *sd;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
t = kzalloc(sizeof(*t), GFP_KERNEL);
if (!t)
return -ENOMEM;
sd = &t->sd;
v4l2_i2c_subdev_init(sd, client, &tda7432_ops);
if (loudness < 0 || loudness > 15) {
v4l2_warn(sd, "loudness parameter must be between 0 and 15\n");
if (loudness < 0)
loudness = 0;
if (loudness > 15)
loudness = 15;
}
do_tda7432_init(sd);
return 0;
}
static int tda7432_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
do_tda7432_init(sd);
v4l2_device_unregister_subdev(sd);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id tda7432_id[] = {
{ "tda7432", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tda7432_id);
static struct v4l2_i2c_driver_data v4l2_i2c_data = {
.name = "tda7432",
.probe = tda7432_probe,
.remove = tda7432_remove,
.id_table = tda7432_id,
};
| gpl-2.0 |
janarthananfit/android_kernel_msm_beni | arch/x86/kernel/probe_roms_32.c | 1748 | 4182 | #include <linux/sched.h>
#include <linux/mm.h>
#include <linux/uaccess.h>
#include <linux/mmzone.h>
#include <linux/ioport.h>
#include <linux/seq_file.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/edd.h>
#include <linux/dmi.h>
#include <linux/pfn.h>
#include <linux/pci.h>
#include <asm/pci-direct.h>
#include <asm/e820.h>
#include <asm/mmzone.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/io.h>
#include <asm/setup_arch.h>
static struct resource system_rom_resource = {
.name = "System ROM",
.start = 0xf0000,
.end = 0xfffff,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
};
static struct resource extension_rom_resource = {
.name = "Extension ROM",
.start = 0xe0000,
.end = 0xeffff,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
};
static struct resource adapter_rom_resources[] = { {
.name = "Adapter ROM",
.start = 0xc8000,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
}, {
.name = "Adapter ROM",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
}, {
.name = "Adapter ROM",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
}, {
.name = "Adapter ROM",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
}, {
.name = "Adapter ROM",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
}, {
.name = "Adapter ROM",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
} };
static struct resource video_rom_resource = {
.name = "Video ROM",
.start = 0xc0000,
.end = 0xc7fff,
.flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM
};
#define ROMSIGNATURE 0xaa55
static int __init romsignature(const unsigned char *rom)
{
const unsigned short * const ptr = (const unsigned short *)rom;
unsigned short sig;
return probe_kernel_address(ptr, sig) == 0 && sig == ROMSIGNATURE;
}
static int __init romchecksum(const unsigned char *rom, unsigned long length)
{
unsigned char sum, c;
for (sum = 0; length && probe_kernel_address(rom++, c) == 0; length--)
sum += c;
return !length && !sum;
}
void __init probe_roms(void)
{
const unsigned char *rom;
unsigned long start, length, upper;
unsigned char c;
int i;
/* video rom */
upper = adapter_rom_resources[0].start;
for (start = video_rom_resource.start; start < upper; start += 2048) {
rom = isa_bus_to_virt(start);
if (!romsignature(rom))
continue;
video_rom_resource.start = start;
if (probe_kernel_address(rom + 2, c) != 0)
continue;
/* 0 < length <= 0x7f * 512, historically */
length = c * 512;
/* if checksum okay, trust length byte */
if (length && romchecksum(rom, length))
video_rom_resource.end = start + length - 1;
request_resource(&iomem_resource, &video_rom_resource);
break;
}
start = (video_rom_resource.end + 1 + 2047) & ~2047UL;
if (start < upper)
start = upper;
/* system rom */
request_resource(&iomem_resource, &system_rom_resource);
upper = system_rom_resource.start;
/* check for extension rom (ignore length byte!) */
rom = isa_bus_to_virt(extension_rom_resource.start);
if (romsignature(rom)) {
length = extension_rom_resource.end - extension_rom_resource.start + 1;
if (romchecksum(rom, length)) {
request_resource(&iomem_resource, &extension_rom_resource);
upper = extension_rom_resource.start;
}
}
/* check for adapter roms on 2k boundaries */
for (i = 0; i < ARRAY_SIZE(adapter_rom_resources) && start < upper; start += 2048) {
rom = isa_bus_to_virt(start);
if (!romsignature(rom))
continue;
if (probe_kernel_address(rom + 2, c) != 0)
continue;
/* 0 < length <= 0x7f * 512, historically */
length = c * 512;
/* but accept any length that fits if checksum okay */
if (!length || start + length > upper || !romchecksum(rom, length))
continue;
adapter_rom_resources[i].start = start;
adapter_rom_resources[i].end = start + length - 1;
request_resource(&iomem_resource, &adapter_rom_resources[i]);
start = adapter_rom_resources[i++].end & ~2047UL;
}
}
| gpl-2.0 |
schqiushui/kernel_lollipop_sense_a52 | drivers/infiniband/hw/qib/qib_sysfs.c | 2260 | 21567 | /*
* Copyright (c) 2012 Intel Corporation. All rights reserved.
* Copyright (c) 2006 - 2012 QLogic Corporation. All rights reserved.
* Copyright (c) 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/ctype.h>
#include "qib.h"
#include "qib_mad.h"
/* start of per-port functions */
/*
* Get/Set heartbeat enable. OR of 1=enabled, 2=auto
*/
static ssize_t show_hrtbt_enb(struct qib_pportdata *ppd, char *buf)
{
struct qib_devdata *dd = ppd->dd;
int ret;
ret = dd->f_get_ib_cfg(ppd, QIB_IB_CFG_HRTBT);
ret = scnprintf(buf, PAGE_SIZE, "%d\n", ret);
return ret;
}
static ssize_t store_hrtbt_enb(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret;
u16 val;
ret = kstrtou16(buf, 0, &val);
if (ret) {
qib_dev_err(dd, "attempt to set invalid Heartbeat enable\n");
return ret;
}
/*
* Set the "intentional" heartbeat enable per either of
* "Enable" and "Auto", as these are normally set together.
* This bit is consulted when leaving loopback mode,
* because entering loopback mode overrides it and automatically
* disables heartbeat.
*/
ret = dd->f_set_ib_cfg(ppd, QIB_IB_CFG_HRTBT, val);
return ret < 0 ? ret : count;
}
static ssize_t store_loopback(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret = count, r;
r = dd->f_set_ib_loopback(ppd, buf);
if (r < 0)
ret = r;
return ret;
}
static ssize_t store_led_override(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret;
u16 val;
ret = kstrtou16(buf, 0, &val);
if (ret) {
qib_dev_err(dd, "attempt to set invalid LED override\n");
return ret;
}
qib_set_led_override(ppd, val);
return count;
}
static ssize_t show_status(struct qib_pportdata *ppd, char *buf)
{
ssize_t ret;
if (!ppd->statusp)
ret = -EINVAL;
else
ret = scnprintf(buf, PAGE_SIZE, "0x%llx\n",
(unsigned long long) *(ppd->statusp));
return ret;
}
/*
* For userland compatibility, these offsets must remain fixed.
* They are strings for QIB_STATUS_*
*/
static const char * const qib_status_str[] = {
"Initted",
"",
"",
"",
"",
"Present",
"IB_link_up",
"IB_configured",
"",
"Fatal_Hardware_Error",
NULL,
};
static ssize_t show_status_str(struct qib_pportdata *ppd, char *buf)
{
int i, any;
u64 s;
ssize_t ret;
if (!ppd->statusp) {
ret = -EINVAL;
goto bail;
}
s = *(ppd->statusp);
*buf = '\0';
for (any = i = 0; s && qib_status_str[i]; i++) {
if (s & 1) {
/* if overflow */
if (any && strlcat(buf, " ", PAGE_SIZE) >= PAGE_SIZE)
break;
if (strlcat(buf, qib_status_str[i], PAGE_SIZE) >=
PAGE_SIZE)
break;
any = 1;
}
s >>= 1;
}
if (any)
strlcat(buf, "\n", PAGE_SIZE);
ret = strlen(buf);
bail:
return ret;
}
/* end of per-port functions */
/*
* Start of per-port file structures and support code
* Because we are fitting into other infrastructure, we have to supply the
* full set of kobject/sysfs_ops structures and routines.
*/
#define QIB_PORT_ATTR(name, mode, show, store) \
static struct qib_port_attr qib_port_attr_##name = \
__ATTR(name, mode, show, store)
struct qib_port_attr {
struct attribute attr;
ssize_t (*show)(struct qib_pportdata *, char *);
ssize_t (*store)(struct qib_pportdata *, const char *, size_t);
};
QIB_PORT_ATTR(loopback, S_IWUSR, NULL, store_loopback);
QIB_PORT_ATTR(led_override, S_IWUSR, NULL, store_led_override);
QIB_PORT_ATTR(hrtbt_enable, S_IWUSR | S_IRUGO, show_hrtbt_enb,
store_hrtbt_enb);
QIB_PORT_ATTR(status, S_IRUGO, show_status, NULL);
QIB_PORT_ATTR(status_str, S_IRUGO, show_status_str, NULL);
static struct attribute *port_default_attributes[] = {
&qib_port_attr_loopback.attr,
&qib_port_attr_led_override.attr,
&qib_port_attr_hrtbt_enable.attr,
&qib_port_attr_status.attr,
&qib_port_attr_status_str.attr,
NULL
};
/*
* Start of per-port congestion control structures and support code
*/
/*
* Congestion control table size followed by table entries
*/
static ssize_t read_cc_table_bin(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t count)
{
int ret;
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_cc_kobj);
if (!qib_cc_table_size || !ppd->ccti_entries_shadow)
return -EINVAL;
ret = ppd->total_cct_entry * sizeof(struct ib_cc_table_entry_shadow)
+ sizeof(__be16);
if (pos > ret)
return -EINVAL;
if (count > ret - pos)
count = ret - pos;
if (!count)
return count;
spin_lock(&ppd->cc_shadow_lock);
memcpy(buf, ppd->ccti_entries_shadow, count);
spin_unlock(&ppd->cc_shadow_lock);
return count;
}
static void qib_port_release(struct kobject *kobj)
{
/* nothing to do since memory is freed by qib_free_devdata() */
}
static struct kobj_type qib_port_cc_ktype = {
.release = qib_port_release,
};
static struct bin_attribute cc_table_bin_attr = {
.attr = {.name = "cc_table_bin", .mode = 0444},
.read = read_cc_table_bin,
.size = PAGE_SIZE,
};
/*
* Congestion settings: port control, control map and an array of 16
* entries for the congestion entries - increase, timer, event log
* trigger threshold and the minimum injection rate delay.
*/
static ssize_t read_cc_setting_bin(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t count)
{
int ret;
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_cc_kobj);
if (!qib_cc_table_size || !ppd->congestion_entries_shadow)
return -EINVAL;
ret = sizeof(struct ib_cc_congestion_setting_attr_shadow);
if (pos > ret)
return -EINVAL;
if (count > ret - pos)
count = ret - pos;
if (!count)
return count;
spin_lock(&ppd->cc_shadow_lock);
memcpy(buf, ppd->congestion_entries_shadow, count);
spin_unlock(&ppd->cc_shadow_lock);
return count;
}
static struct bin_attribute cc_setting_bin_attr = {
.attr = {.name = "cc_settings_bin", .mode = 0444},
.read = read_cc_setting_bin,
.size = PAGE_SIZE,
};
static ssize_t qib_portattr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct qib_port_attr *pattr =
container_of(attr, struct qib_port_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_kobj);
return pattr->show(ppd, buf);
}
static ssize_t qib_portattr_store(struct kobject *kobj,
struct attribute *attr, const char *buf, size_t len)
{
struct qib_port_attr *pattr =
container_of(attr, struct qib_port_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_kobj);
return pattr->store(ppd, buf, len);
}
static const struct sysfs_ops qib_port_ops = {
.show = qib_portattr_show,
.store = qib_portattr_store,
};
static struct kobj_type qib_port_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_port_ops,
.default_attrs = port_default_attributes
};
/* Start sl2vl */
#define QIB_SL2VL_ATTR(N) \
static struct qib_sl2vl_attr qib_sl2vl_attr_##N = { \
.attr = { .name = __stringify(N), .mode = 0444 }, \
.sl = N \
}
struct qib_sl2vl_attr {
struct attribute attr;
int sl;
};
QIB_SL2VL_ATTR(0);
QIB_SL2VL_ATTR(1);
QIB_SL2VL_ATTR(2);
QIB_SL2VL_ATTR(3);
QIB_SL2VL_ATTR(4);
QIB_SL2VL_ATTR(5);
QIB_SL2VL_ATTR(6);
QIB_SL2VL_ATTR(7);
QIB_SL2VL_ATTR(8);
QIB_SL2VL_ATTR(9);
QIB_SL2VL_ATTR(10);
QIB_SL2VL_ATTR(11);
QIB_SL2VL_ATTR(12);
QIB_SL2VL_ATTR(13);
QIB_SL2VL_ATTR(14);
QIB_SL2VL_ATTR(15);
static struct attribute *sl2vl_default_attributes[] = {
&qib_sl2vl_attr_0.attr,
&qib_sl2vl_attr_1.attr,
&qib_sl2vl_attr_2.attr,
&qib_sl2vl_attr_3.attr,
&qib_sl2vl_attr_4.attr,
&qib_sl2vl_attr_5.attr,
&qib_sl2vl_attr_6.attr,
&qib_sl2vl_attr_7.attr,
&qib_sl2vl_attr_8.attr,
&qib_sl2vl_attr_9.attr,
&qib_sl2vl_attr_10.attr,
&qib_sl2vl_attr_11.attr,
&qib_sl2vl_attr_12.attr,
&qib_sl2vl_attr_13.attr,
&qib_sl2vl_attr_14.attr,
&qib_sl2vl_attr_15.attr,
NULL
};
static ssize_t sl2vl_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct qib_sl2vl_attr *sattr =
container_of(attr, struct qib_sl2vl_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, sl2vl_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
return sprintf(buf, "%u\n", qibp->sl_to_vl[sattr->sl]);
}
static const struct sysfs_ops qib_sl2vl_ops = {
.show = sl2vl_attr_show,
};
static struct kobj_type qib_sl2vl_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_sl2vl_ops,
.default_attrs = sl2vl_default_attributes
};
/* End sl2vl */
/* Start diag_counters */
#define QIB_DIAGC_ATTR(N) \
static struct qib_diagc_attr qib_diagc_attr_##N = { \
.attr = { .name = __stringify(N), .mode = 0664 }, \
.counter = offsetof(struct qib_ibport, n_##N) \
}
struct qib_diagc_attr {
struct attribute attr;
size_t counter;
};
QIB_DIAGC_ATTR(rc_resends);
QIB_DIAGC_ATTR(rc_acks);
QIB_DIAGC_ATTR(rc_qacks);
QIB_DIAGC_ATTR(rc_delayed_comp);
QIB_DIAGC_ATTR(seq_naks);
QIB_DIAGC_ATTR(rdma_seq);
QIB_DIAGC_ATTR(rnr_naks);
QIB_DIAGC_ATTR(other_naks);
QIB_DIAGC_ATTR(rc_timeouts);
QIB_DIAGC_ATTR(loop_pkts);
QIB_DIAGC_ATTR(pkt_drops);
QIB_DIAGC_ATTR(dmawait);
QIB_DIAGC_ATTR(unaligned);
QIB_DIAGC_ATTR(rc_dupreq);
QIB_DIAGC_ATTR(rc_seqnak);
static struct attribute *diagc_default_attributes[] = {
&qib_diagc_attr_rc_resends.attr,
&qib_diagc_attr_rc_acks.attr,
&qib_diagc_attr_rc_qacks.attr,
&qib_diagc_attr_rc_delayed_comp.attr,
&qib_diagc_attr_seq_naks.attr,
&qib_diagc_attr_rdma_seq.attr,
&qib_diagc_attr_rnr_naks.attr,
&qib_diagc_attr_other_naks.attr,
&qib_diagc_attr_rc_timeouts.attr,
&qib_diagc_attr_loop_pkts.attr,
&qib_diagc_attr_pkt_drops.attr,
&qib_diagc_attr_dmawait.attr,
&qib_diagc_attr_unaligned.attr,
&qib_diagc_attr_rc_dupreq.attr,
&qib_diagc_attr_rc_seqnak.attr,
NULL
};
static ssize_t diagc_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct qib_diagc_attr *dattr =
container_of(attr, struct qib_diagc_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, diagc_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
return sprintf(buf, "%u\n", *(u32 *)((char *)qibp + dattr->counter));
}
static ssize_t diagc_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t size)
{
struct qib_diagc_attr *dattr =
container_of(attr, struct qib_diagc_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, diagc_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
u32 val;
int ret;
ret = kstrtou32(buf, 0, &val);
if (ret)
return ret;
*(u32 *)((char *) qibp + dattr->counter) = val;
return size;
}
static const struct sysfs_ops qib_diagc_ops = {
.show = diagc_attr_show,
.store = diagc_attr_store,
};
static struct kobj_type qib_diagc_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_diagc_ops,
.default_attrs = diagc_default_attributes
};
/* End diag_counters */
/* end of per-port file structures and support code */
/*
* Start of per-unit (or driver, in some cases, but replicated
* per unit) functions (these get a device *)
*/
static ssize_t show_rev(struct device *device, struct device_attribute *attr,
char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
return sprintf(buf, "%x\n", dd_from_dev(dev)->minrev);
}
static ssize_t show_hca(struct device *device, struct device_attribute *attr,
char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
if (!dd->boardname)
ret = -EINVAL;
else
ret = scnprintf(buf, PAGE_SIZE, "%s\n", dd->boardname);
return ret;
}
static ssize_t show_version(struct device *device,
struct device_attribute *attr, char *buf)
{
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", (char *)ib_qib_version);
}
static ssize_t show_boardversion(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", dd->boardversion);
}
static ssize_t show_localbus_info(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", dd->lbus_info);
}
static ssize_t show_nctxts(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* Return the number of user ports (contexts) available. */
/* The calculation below deals with a special case where
* cfgctxts is set to 1 on a single-port board. */
return scnprintf(buf, PAGE_SIZE, "%u\n",
(dd->first_user_ctxt > dd->cfgctxts) ? 0 :
(dd->cfgctxts - dd->first_user_ctxt));
}
static ssize_t show_nfreectxts(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* Return the number of free user ports (contexts) available. */
return scnprintf(buf, PAGE_SIZE, "%u\n", dd->freectxts);
}
static ssize_t show_serial(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
buf[sizeof dd->serial] = '\0';
memcpy(buf, dd->serial, sizeof dd->serial);
strcat(buf, "\n");
return strlen(buf);
}
static ssize_t store_chip_reset(struct device *device,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
if (count < 5 || memcmp(buf, "reset", 5) || !dd->diag_client) {
ret = -EINVAL;
goto bail;
}
ret = qib_reset_device(dd->unit);
bail:
return ret < 0 ? ret : count;
}
static ssize_t show_logged_errs(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int idx, count;
/* force consistency with actual EEPROM */
if (qib_update_eeprom_log(dd) != 0)
return -ENXIO;
count = 0;
for (idx = 0; idx < QIB_EEP_LOG_CNT; ++idx) {
count += scnprintf(buf + count, PAGE_SIZE - count, "%d%c",
dd->eep_st_errs[idx],
idx == (QIB_EEP_LOG_CNT - 1) ? '\n' : ' ');
}
return count;
}
/*
* Dump tempsense regs. in decimal, to ease shell-scripts.
*/
static ssize_t show_tempsense(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
int idx;
u8 regvals[8];
ret = -ENXIO;
for (idx = 0; idx < 8; ++idx) {
if (idx == 6)
continue;
ret = dd->f_tempsense_rd(dd, idx);
if (ret < 0)
break;
regvals[idx] = ret;
}
if (idx == 8)
ret = scnprintf(buf, PAGE_SIZE, "%d %d %02X %02X %d %d\n",
*(signed char *)(regvals),
*(signed char *)(regvals + 1),
regvals[2], regvals[3],
*(signed char *)(regvals + 5),
*(signed char *)(regvals + 7));
return ret;
}
/*
* end of per-unit (or driver, in some cases, but replicated
* per unit) functions
*/
/* start of per-unit file structures and support code */
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(version, S_IRUGO, show_version, NULL);
static DEVICE_ATTR(nctxts, S_IRUGO, show_nctxts, NULL);
static DEVICE_ATTR(nfreectxts, S_IRUGO, show_nfreectxts, NULL);
static DEVICE_ATTR(serial, S_IRUGO, show_serial, NULL);
static DEVICE_ATTR(boardversion, S_IRUGO, show_boardversion, NULL);
static DEVICE_ATTR(logged_errors, S_IRUGO, show_logged_errs, NULL);
static DEVICE_ATTR(tempsense, S_IRUGO, show_tempsense, NULL);
static DEVICE_ATTR(localbus_info, S_IRUGO, show_localbus_info, NULL);
static DEVICE_ATTR(chip_reset, S_IWUSR, NULL, store_chip_reset);
static struct device_attribute *qib_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_hca_type,
&dev_attr_board_id,
&dev_attr_version,
&dev_attr_nctxts,
&dev_attr_nfreectxts,
&dev_attr_serial,
&dev_attr_boardversion,
&dev_attr_logged_errors,
&dev_attr_tempsense,
&dev_attr_localbus_info,
&dev_attr_chip_reset,
};
int qib_create_port_files(struct ib_device *ibdev, u8 port_num,
struct kobject *kobj)
{
struct qib_pportdata *ppd;
struct qib_devdata *dd = dd_from_ibdev(ibdev);
int ret;
if (!port_num || port_num > dd->num_pports) {
qib_dev_err(dd,
"Skipping infiniband class with invalid port %u\n",
port_num);
ret = -ENODEV;
goto bail;
}
ppd = &dd->pport[port_num - 1];
ret = kobject_init_and_add(&ppd->pport_kobj, &qib_port_ktype, kobj,
"linkcontrol");
if (ret) {
qib_dev_err(dd,
"Skipping linkcontrol sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail;
}
kobject_uevent(&ppd->pport_kobj, KOBJ_ADD);
ret = kobject_init_and_add(&ppd->sl2vl_kobj, &qib_sl2vl_ktype, kobj,
"sl2vl");
if (ret) {
qib_dev_err(dd,
"Skipping sl2vl sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail_link;
}
kobject_uevent(&ppd->sl2vl_kobj, KOBJ_ADD);
ret = kobject_init_and_add(&ppd->diagc_kobj, &qib_diagc_ktype, kobj,
"diag_counters");
if (ret) {
qib_dev_err(dd,
"Skipping diag_counters sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail_sl;
}
kobject_uevent(&ppd->diagc_kobj, KOBJ_ADD);
if (!qib_cc_table_size || !ppd->congestion_entries_shadow)
return 0;
ret = kobject_init_and_add(&ppd->pport_cc_kobj, &qib_port_cc_ktype,
kobj, "CCMgtA");
if (ret) {
qib_dev_err(dd,
"Skipping Congestion Control sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail_diagc;
}
kobject_uevent(&ppd->pport_cc_kobj, KOBJ_ADD);
ret = sysfs_create_bin_file(&ppd->pport_cc_kobj,
&cc_setting_bin_attr);
if (ret) {
qib_dev_err(dd,
"Skipping Congestion Control setting sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail_cc;
}
ret = sysfs_create_bin_file(&ppd->pport_cc_kobj,
&cc_table_bin_attr);
if (ret) {
qib_dev_err(dd,
"Skipping Congestion Control table sysfs info, (err %d) port %u\n",
ret, port_num);
goto bail_cc_entry_bin;
}
qib_devinfo(dd->pcidev,
"IB%u: Congestion Control Agent enabled for port %d\n",
dd->unit, port_num);
return 0;
bail_cc_entry_bin:
sysfs_remove_bin_file(&ppd->pport_cc_kobj, &cc_setting_bin_attr);
bail_cc:
kobject_put(&ppd->pport_cc_kobj);
bail_diagc:
kobject_put(&ppd->diagc_kobj);
bail_sl:
kobject_put(&ppd->sl2vl_kobj);
bail_link:
kobject_put(&ppd->pport_kobj);
bail:
return ret;
}
/*
* Register and create our files in /sys/class/infiniband.
*/
int qib_verbs_register_sysfs(struct qib_devdata *dd)
{
struct ib_device *dev = &dd->verbs_dev.ibdev;
int i, ret;
for (i = 0; i < ARRAY_SIZE(qib_attributes); ++i) {
ret = device_create_file(&dev->dev, qib_attributes[i]);
if (ret)
goto bail;
}
return 0;
bail:
for (i = 0; i < ARRAY_SIZE(qib_attributes); ++i)
device_remove_file(&dev->dev, qib_attributes[i]);
return ret;
}
/*
* Unregister and remove our files in /sys/class/infiniband.
*/
void qib_verbs_unregister_sysfs(struct qib_devdata *dd)
{
struct qib_pportdata *ppd;
int i;
for (i = 0; i < dd->num_pports; i++) {
ppd = &dd->pport[i];
if (qib_cc_table_size &&
ppd->congestion_entries_shadow) {
sysfs_remove_bin_file(&ppd->pport_cc_kobj,
&cc_setting_bin_attr);
sysfs_remove_bin_file(&ppd->pport_cc_kobj,
&cc_table_bin_attr);
kobject_put(&ppd->pport_cc_kobj);
}
kobject_put(&ppd->sl2vl_kobj);
kobject_put(&ppd->pport_kobj);
}
}
| gpl-2.0 |
andr00ib/kernel_v30c | drivers/hid/hid-sjoy.c | 3028 | 4395 | /*
* Force feedback support for SmartJoy PLUS PS2->USB adapter
*
* Copyright (c) 2009 Jussi Kivilinna <jussi.kivilinna@mbnet.fi>
*
* Based of hid-pl.c and hid-gaff.c
* Copyright (c) 2007, 2009 Anssi Hannula <anssi.hannula@gmail.com>
* Copyright (c) 2008 Lukasz Lubojanski <lukasz@lubojanski.info>
*/
/*
* 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 DEBUG */
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include "hid-ids.h"
#ifdef CONFIG_SMARTJOYPLUS_FF
#include "usbhid/usbhid.h"
struct sjoyff_device {
struct hid_report *report;
};
static int hid_sjoyff_play(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct sjoyff_device *sjoyff = data;
u32 left, right;
left = effect->u.rumble.strong_magnitude;
right = effect->u.rumble.weak_magnitude;
dev_dbg(&dev->dev, "called with 0x%08x 0x%08x\n", left, right);
left = left * 0xff / 0xffff;
right = (right != 0); /* on/off only */
sjoyff->report->field[0]->value[1] = right;
sjoyff->report->field[0]->value[2] = left;
dev_dbg(&dev->dev, "running with 0x%02x 0x%02x\n", left, right);
usbhid_submit_report(hid, sjoyff->report, USB_DIR_OUT);
return 0;
}
static int sjoyff_init(struct hid_device *hid)
{
struct sjoyff_device *sjoyff;
struct hid_report *report;
struct hid_input *hidinput = list_entry(hid->inputs.next,
struct hid_input, list);
struct list_head *report_list =
&hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct list_head *report_ptr = report_list;
struct input_dev *dev;
int error;
if (list_empty(report_list)) {
hid_err(hid, "no output reports found\n");
return -ENODEV;
}
report_ptr = report_ptr->next;
if (report_ptr == report_list) {
hid_err(hid, "required output report is missing\n");
return -ENODEV;
}
report = list_entry(report_ptr, struct hid_report, list);
if (report->maxfield < 1) {
hid_err(hid, "no fields in the report\n");
return -ENODEV;
}
if (report->field[0]->report_count < 3) {
hid_err(hid, "not enough values in the field\n");
return -ENODEV;
}
sjoyff = kzalloc(sizeof(struct sjoyff_device), GFP_KERNEL);
if (!sjoyff)
return -ENOMEM;
dev = hidinput->input;
set_bit(FF_RUMBLE, dev->ffbit);
error = input_ff_create_memless(dev, sjoyff, hid_sjoyff_play);
if (error) {
kfree(sjoyff);
return error;
}
sjoyff->report = report;
sjoyff->report->field[0]->value[0] = 0x01;
sjoyff->report->field[0]->value[1] = 0x00;
sjoyff->report->field[0]->value[2] = 0x00;
usbhid_submit_report(hid, sjoyff->report, USB_DIR_OUT);
hid_info(hid, "Force feedback for SmartJoy PLUS PS2/USB adapter\n");
return 0;
}
#else
static inline int sjoyff_init(struct hid_device *hid)
{
return 0;
}
#endif
static int sjoy_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
int ret;
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err;
}
sjoyff_init(hdev);
return 0;
err:
return ret;
}
static const struct hid_device_id sjoy_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_SMARTJOY_PLUS) },
{ }
};
MODULE_DEVICE_TABLE(hid, sjoy_devices);
static struct hid_driver sjoy_driver = {
.name = "smartjoyplus",
.id_table = sjoy_devices,
.probe = sjoy_probe,
};
static int __init sjoy_init(void)
{
return hid_register_driver(&sjoy_driver);
}
static void __exit sjoy_exit(void)
{
hid_unregister_driver(&sjoy_driver);
}
module_init(sjoy_init);
module_exit(sjoy_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jussi Kivilinna");
| gpl-2.0 |
chiehwen/AGNI-pureSTOCK-I9300 | drivers/edac/i5400_edac.c | 3028 | 39969 | /*
* Intel 5400 class Memory Controllers kernel module (Seaburg)
*
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Copyright (c) 2008 by:
* Ben Woodard <woodard@redhat.com>
* Mauro Carvalho Chehab <mchehab@redhat.com>
*
* Red Hat Inc. http://www.redhat.com
*
* Forked and adapted from the i5000_edac driver which was
* written by Douglas Thompson Linux Networx <norsk5@xmission.com>
*
* This module is based on the following document:
*
* Intel 5400 Chipset Memory Controller Hub (MCH) - Datasheet
* http://developer.intel.com/design/chipsets/datashts/313070.htm
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/slab.h>
#include <linux/edac.h>
#include <linux/mmzone.h>
#include "edac_core.h"
/*
* Alter this version for the I5400 module when modifications are made
*/
#define I5400_REVISION " Ver: 1.0.0"
#define EDAC_MOD_STR "i5400_edac"
#define i5400_printk(level, fmt, arg...) \
edac_printk(level, "i5400", fmt, ##arg)
#define i5400_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "i5400", fmt, ##arg)
/* Limits for i5400 */
#define NUM_MTRS_PER_BRANCH 4
#define CHANNELS_PER_BRANCH 2
#define MAX_DIMMS_PER_CHANNEL NUM_MTRS_PER_BRANCH
#define MAX_CHANNELS 4
/* max possible csrows per channel */
#define MAX_CSROWS (MAX_DIMMS_PER_CHANNEL)
/* Device 16,
* Function 0: System Address
* Function 1: Memory Branch Map, Control, Errors Register
* Function 2: FSB Error Registers
*
* All 3 functions of Device 16 (0,1,2) share the SAME DID and
* uses PCI_DEVICE_ID_INTEL_5400_ERR for device 16 (0,1,2),
* PCI_DEVICE_ID_INTEL_5400_FBD0 and PCI_DEVICE_ID_INTEL_5400_FBD1
* for device 21 (0,1).
*/
/* OFFSETS for Function 0 */
#define AMBASE 0x48 /* AMB Mem Mapped Reg Region Base */
#define MAXCH 0x56 /* Max Channel Number */
#define MAXDIMMPERCH 0x57 /* Max DIMM PER Channel Number */
/* OFFSETS for Function 1 */
#define TOLM 0x6C
#define REDMEMB 0x7C
#define REC_ECC_LOCATOR_ODD(x) ((x) & 0x3fe00) /* bits [17:9] indicate ODD, [8:0] indicate EVEN */
#define MIR0 0x80
#define MIR1 0x84
#define AMIR0 0x8c
#define AMIR1 0x90
/* Fatal error registers */
#define FERR_FAT_FBD 0x98 /* also called as FERR_FAT_FB_DIMM at datasheet */
#define FERR_FAT_FBDCHAN (3<<28) /* channel index where the highest-order error occurred */
#define NERR_FAT_FBD 0x9c
#define FERR_NF_FBD 0xa0 /* also called as FERR_NFAT_FB_DIMM at datasheet */
/* Non-fatal error register */
#define NERR_NF_FBD 0xa4
/* Enable error mask */
#define EMASK_FBD 0xa8
#define ERR0_FBD 0xac
#define ERR1_FBD 0xb0
#define ERR2_FBD 0xb4
#define MCERR_FBD 0xb8
/* No OFFSETS for Device 16 Function 2 */
/*
* Device 21,
* Function 0: Memory Map Branch 0
*
* Device 22,
* Function 0: Memory Map Branch 1
*/
/* OFFSETS for Function 0 */
#define AMBPRESENT_0 0x64
#define AMBPRESENT_1 0x66
#define MTR0 0x80
#define MTR1 0x82
#define MTR2 0x84
#define MTR3 0x86
/* OFFSETS for Function 1 */
#define NRECFGLOG 0x74
#define RECFGLOG 0x78
#define NRECMEMA 0xbe
#define NRECMEMB 0xc0
#define NRECFB_DIMMA 0xc4
#define NRECFB_DIMMB 0xc8
#define NRECFB_DIMMC 0xcc
#define NRECFB_DIMMD 0xd0
#define NRECFB_DIMME 0xd4
#define NRECFB_DIMMF 0xd8
#define REDMEMA 0xdC
#define RECMEMA 0xf0
#define RECMEMB 0xf4
#define RECFB_DIMMA 0xf8
#define RECFB_DIMMB 0xec
#define RECFB_DIMMC 0xf0
#define RECFB_DIMMD 0xf4
#define RECFB_DIMME 0xf8
#define RECFB_DIMMF 0xfC
/*
* Error indicator bits and masks
* Error masks are according with Table 5-17 of i5400 datasheet
*/
enum error_mask {
EMASK_M1 = 1<<0, /* Memory Write error on non-redundant retry */
EMASK_M2 = 1<<1, /* Memory or FB-DIMM configuration CRC read error */
EMASK_M3 = 1<<2, /* Reserved */
EMASK_M4 = 1<<3, /* Uncorrectable Data ECC on Replay */
EMASK_M5 = 1<<4, /* Aliased Uncorrectable Non-Mirrored Demand Data ECC */
EMASK_M6 = 1<<5, /* Unsupported on i5400 */
EMASK_M7 = 1<<6, /* Aliased Uncorrectable Resilver- or Spare-Copy Data ECC */
EMASK_M8 = 1<<7, /* Aliased Uncorrectable Patrol Data ECC */
EMASK_M9 = 1<<8, /* Non-Aliased Uncorrectable Non-Mirrored Demand Data ECC */
EMASK_M10 = 1<<9, /* Unsupported on i5400 */
EMASK_M11 = 1<<10, /* Non-Aliased Uncorrectable Resilver- or Spare-Copy Data ECC */
EMASK_M12 = 1<<11, /* Non-Aliased Uncorrectable Patrol Data ECC */
EMASK_M13 = 1<<12, /* Memory Write error on first attempt */
EMASK_M14 = 1<<13, /* FB-DIMM Configuration Write error on first attempt */
EMASK_M15 = 1<<14, /* Memory or FB-DIMM configuration CRC read error */
EMASK_M16 = 1<<15, /* Channel Failed-Over Occurred */
EMASK_M17 = 1<<16, /* Correctable Non-Mirrored Demand Data ECC */
EMASK_M18 = 1<<17, /* Unsupported on i5400 */
EMASK_M19 = 1<<18, /* Correctable Resilver- or Spare-Copy Data ECC */
EMASK_M20 = 1<<19, /* Correctable Patrol Data ECC */
EMASK_M21 = 1<<20, /* FB-DIMM Northbound parity error on FB-DIMM Sync Status */
EMASK_M22 = 1<<21, /* SPD protocol Error */
EMASK_M23 = 1<<22, /* Non-Redundant Fast Reset Timeout */
EMASK_M24 = 1<<23, /* Refresh error */
EMASK_M25 = 1<<24, /* Memory Write error on redundant retry */
EMASK_M26 = 1<<25, /* Redundant Fast Reset Timeout */
EMASK_M27 = 1<<26, /* Correctable Counter Threshold Exceeded */
EMASK_M28 = 1<<27, /* DIMM-Spare Copy Completed */
EMASK_M29 = 1<<28, /* DIMM-Isolation Completed */
};
/*
* Names to translate bit error into something useful
*/
static const char *error_name[] = {
[0] = "Memory Write error on non-redundant retry",
[1] = "Memory or FB-DIMM configuration CRC read error",
/* Reserved */
[3] = "Uncorrectable Data ECC on Replay",
[4] = "Aliased Uncorrectable Non-Mirrored Demand Data ECC",
/* M6 Unsupported on i5400 */
[6] = "Aliased Uncorrectable Resilver- or Spare-Copy Data ECC",
[7] = "Aliased Uncorrectable Patrol Data ECC",
[8] = "Non-Aliased Uncorrectable Non-Mirrored Demand Data ECC",
/* M10 Unsupported on i5400 */
[10] = "Non-Aliased Uncorrectable Resilver- or Spare-Copy Data ECC",
[11] = "Non-Aliased Uncorrectable Patrol Data ECC",
[12] = "Memory Write error on first attempt",
[13] = "FB-DIMM Configuration Write error on first attempt",
[14] = "Memory or FB-DIMM configuration CRC read error",
[15] = "Channel Failed-Over Occurred",
[16] = "Correctable Non-Mirrored Demand Data ECC",
/* M18 Unsupported on i5400 */
[18] = "Correctable Resilver- or Spare-Copy Data ECC",
[19] = "Correctable Patrol Data ECC",
[20] = "FB-DIMM Northbound parity error on FB-DIMM Sync Status",
[21] = "SPD protocol Error",
[22] = "Non-Redundant Fast Reset Timeout",
[23] = "Refresh error",
[24] = "Memory Write error on redundant retry",
[25] = "Redundant Fast Reset Timeout",
[26] = "Correctable Counter Threshold Exceeded",
[27] = "DIMM-Spare Copy Completed",
[28] = "DIMM-Isolation Completed",
};
/* Fatal errors */
#define ERROR_FAT_MASK (EMASK_M1 | \
EMASK_M2 | \
EMASK_M23)
/* Correctable errors */
#define ERROR_NF_CORRECTABLE (EMASK_M27 | \
EMASK_M20 | \
EMASK_M19 | \
EMASK_M18 | \
EMASK_M17 | \
EMASK_M16)
#define ERROR_NF_DIMM_SPARE (EMASK_M29 | \
EMASK_M28)
#define ERROR_NF_SPD_PROTOCOL (EMASK_M22)
#define ERROR_NF_NORTH_CRC (EMASK_M21)
/* Recoverable errors */
#define ERROR_NF_RECOVERABLE (EMASK_M26 | \
EMASK_M25 | \
EMASK_M24 | \
EMASK_M15 | \
EMASK_M14 | \
EMASK_M13 | \
EMASK_M12 | \
EMASK_M11 | \
EMASK_M9 | \
EMASK_M8 | \
EMASK_M7 | \
EMASK_M5)
/* uncorrectable errors */
#define ERROR_NF_UNCORRECTABLE (EMASK_M4)
/* mask to all non-fatal errors */
#define ERROR_NF_MASK (ERROR_NF_CORRECTABLE | \
ERROR_NF_UNCORRECTABLE | \
ERROR_NF_RECOVERABLE | \
ERROR_NF_DIMM_SPARE | \
ERROR_NF_SPD_PROTOCOL | \
ERROR_NF_NORTH_CRC)
/*
* Define error masks for the several registers
*/
/* Enable all fatal and non fatal errors */
#define ENABLE_EMASK_ALL (ERROR_FAT_MASK | ERROR_NF_MASK)
/* mask for fatal error registers */
#define FERR_FAT_MASK ERROR_FAT_MASK
/* masks for non-fatal error register */
static inline int to_nf_mask(unsigned int mask)
{
return (mask & EMASK_M29) | (mask >> 3);
};
static inline int from_nf_ferr(unsigned int mask)
{
return (mask & EMASK_M29) | /* Bit 28 */
(mask & ((1 << 28) - 1) << 3); /* Bits 0 to 27 */
};
#define FERR_NF_MASK to_nf_mask(ERROR_NF_MASK)
#define FERR_NF_CORRECTABLE to_nf_mask(ERROR_NF_CORRECTABLE)
#define FERR_NF_DIMM_SPARE to_nf_mask(ERROR_NF_DIMM_SPARE)
#define FERR_NF_SPD_PROTOCOL to_nf_mask(ERROR_NF_SPD_PROTOCOL)
#define FERR_NF_NORTH_CRC to_nf_mask(ERROR_NF_NORTH_CRC)
#define FERR_NF_RECOVERABLE to_nf_mask(ERROR_NF_RECOVERABLE)
#define FERR_NF_UNCORRECTABLE to_nf_mask(ERROR_NF_UNCORRECTABLE)
/* Defines to extract the vaious fields from the
* MTRx - Memory Technology Registers
*/
#define MTR_DIMMS_PRESENT(mtr) ((mtr) & (1 << 10))
#define MTR_DIMMS_ETHROTTLE(mtr) ((mtr) & (1 << 9))
#define MTR_DRAM_WIDTH(mtr) (((mtr) & (1 << 8)) ? 8 : 4)
#define MTR_DRAM_BANKS(mtr) (((mtr) & (1 << 6)) ? 8 : 4)
#define MTR_DRAM_BANKS_ADDR_BITS(mtr) ((MTR_DRAM_BANKS(mtr) == 8) ? 3 : 2)
#define MTR_DIMM_RANK(mtr) (((mtr) >> 5) & 0x1)
#define MTR_DIMM_RANK_ADDR_BITS(mtr) (MTR_DIMM_RANK(mtr) ? 2 : 1)
#define MTR_DIMM_ROWS(mtr) (((mtr) >> 2) & 0x3)
#define MTR_DIMM_ROWS_ADDR_BITS(mtr) (MTR_DIMM_ROWS(mtr) + 13)
#define MTR_DIMM_COLS(mtr) ((mtr) & 0x3)
#define MTR_DIMM_COLS_ADDR_BITS(mtr) (MTR_DIMM_COLS(mtr) + 10)
/* This applies to FERR_NF_FB-DIMM as well as FERR_FAT_FB-DIMM */
static inline int extract_fbdchan_indx(u32 x)
{
return (x>>28) & 0x3;
}
#ifdef CONFIG_EDAC_DEBUG
/* MTR NUMROW */
static const char *numrow_toString[] = {
"8,192 - 13 rows",
"16,384 - 14 rows",
"32,768 - 15 rows",
"65,536 - 16 rows"
};
/* MTR NUMCOL */
static const char *numcol_toString[] = {
"1,024 - 10 columns",
"2,048 - 11 columns",
"4,096 - 12 columns",
"reserved"
};
#endif
/* Device name and register DID (Device ID) */
struct i5400_dev_info {
const char *ctl_name; /* name for this device */
u16 fsb_mapping_errors; /* DID for the branchmap,control */
};
/* Table of devices attributes supported by this driver */
static const struct i5400_dev_info i5400_devs[] = {
{
.ctl_name = "I5400",
.fsb_mapping_errors = PCI_DEVICE_ID_INTEL_5400_ERR,
},
};
struct i5400_dimm_info {
int megabytes; /* size, 0 means not present */
};
/* driver private data structure */
struct i5400_pvt {
struct pci_dev *system_address; /* 16.0 */
struct pci_dev *branchmap_werrors; /* 16.1 */
struct pci_dev *fsb_error_regs; /* 16.2 */
struct pci_dev *branch_0; /* 21.0 */
struct pci_dev *branch_1; /* 22.0 */
u16 tolm; /* top of low memory */
u64 ambase; /* AMB BAR */
u16 mir0, mir1;
u16 b0_mtr[NUM_MTRS_PER_BRANCH]; /* Memory Technlogy Reg */
u16 b0_ambpresent0; /* Branch 0, Channel 0 */
u16 b0_ambpresent1; /* Brnach 0, Channel 1 */
u16 b1_mtr[NUM_MTRS_PER_BRANCH]; /* Memory Technlogy Reg */
u16 b1_ambpresent0; /* Branch 1, Channel 8 */
u16 b1_ambpresent1; /* Branch 1, Channel 1 */
/* DIMM information matrix, allocating architecture maximums */
struct i5400_dimm_info dimm_info[MAX_CSROWS][MAX_CHANNELS];
/* Actual values for this controller */
int maxch; /* Max channels */
int maxdimmperch; /* Max DIMMs per channel */
};
/* I5400 MCH error information retrieved from Hardware */
struct i5400_error_info {
/* These registers are always read from the MC */
u32 ferr_fat_fbd; /* First Errors Fatal */
u32 nerr_fat_fbd; /* Next Errors Fatal */
u32 ferr_nf_fbd; /* First Errors Non-Fatal */
u32 nerr_nf_fbd; /* Next Errors Non-Fatal */
/* These registers are input ONLY if there was a Recoverable Error */
u32 redmemb; /* Recoverable Mem Data Error log B */
u16 recmema; /* Recoverable Mem Error log A */
u32 recmemb; /* Recoverable Mem Error log B */
/* These registers are input ONLY if there was a Non-Rec Error */
u16 nrecmema; /* Non-Recoverable Mem log A */
u16 nrecmemb; /* Non-Recoverable Mem log B */
};
/* note that nrec_rdwr changed from NRECMEMA to NRECMEMB between the 5000 and
5400 better to use an inline function than a macro in this case */
static inline int nrec_bank(struct i5400_error_info *info)
{
return ((info->nrecmema) >> 12) & 0x7;
}
static inline int nrec_rank(struct i5400_error_info *info)
{
return ((info->nrecmema) >> 8) & 0xf;
}
static inline int nrec_buf_id(struct i5400_error_info *info)
{
return ((info->nrecmema)) & 0xff;
}
static inline int nrec_rdwr(struct i5400_error_info *info)
{
return (info->nrecmemb) >> 31;
}
/* This applies to both NREC and REC string so it can be used with nrec_rdwr
and rec_rdwr */
static inline const char *rdwr_str(int rdwr)
{
return rdwr ? "Write" : "Read";
}
static inline int nrec_cas(struct i5400_error_info *info)
{
return ((info->nrecmemb) >> 16) & 0x1fff;
}
static inline int nrec_ras(struct i5400_error_info *info)
{
return (info->nrecmemb) & 0xffff;
}
static inline int rec_bank(struct i5400_error_info *info)
{
return ((info->recmema) >> 12) & 0x7;
}
static inline int rec_rank(struct i5400_error_info *info)
{
return ((info->recmema) >> 8) & 0xf;
}
static inline int rec_rdwr(struct i5400_error_info *info)
{
return (info->recmemb) >> 31;
}
static inline int rec_cas(struct i5400_error_info *info)
{
return ((info->recmemb) >> 16) & 0x1fff;
}
static inline int rec_ras(struct i5400_error_info *info)
{
return (info->recmemb) & 0xffff;
}
static struct edac_pci_ctl_info *i5400_pci;
/*
* i5400_get_error_info Retrieve the hardware error information from
* the hardware and cache it in the 'info'
* structure
*/
static void i5400_get_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{
struct i5400_pvt *pvt;
u32 value;
pvt = mci->pvt_info;
/* read in the 1st FATAL error register */
pci_read_config_dword(pvt->branchmap_werrors, FERR_FAT_FBD, &value);
/* Mask only the bits that the doc says are valid
*/
value &= (FERR_FAT_FBDCHAN | FERR_FAT_MASK);
/* If there is an error, then read in the
NEXT FATAL error register and the Memory Error Log Register A
*/
if (value & FERR_FAT_MASK) {
info->ferr_fat_fbd = value;
/* harvest the various error data we need */
pci_read_config_dword(pvt->branchmap_werrors,
NERR_FAT_FBD, &info->nerr_fat_fbd);
pci_read_config_word(pvt->branchmap_werrors,
NRECMEMA, &info->nrecmema);
pci_read_config_word(pvt->branchmap_werrors,
NRECMEMB, &info->nrecmemb);
/* Clear the error bits, by writing them back */
pci_write_config_dword(pvt->branchmap_werrors,
FERR_FAT_FBD, value);
} else {
info->ferr_fat_fbd = 0;
info->nerr_fat_fbd = 0;
info->nrecmema = 0;
info->nrecmemb = 0;
}
/* read in the 1st NON-FATAL error register */
pci_read_config_dword(pvt->branchmap_werrors, FERR_NF_FBD, &value);
/* If there is an error, then read in the 1st NON-FATAL error
* register as well */
if (value & FERR_NF_MASK) {
info->ferr_nf_fbd = value;
/* harvest the various error data we need */
pci_read_config_dword(pvt->branchmap_werrors,
NERR_NF_FBD, &info->nerr_nf_fbd);
pci_read_config_word(pvt->branchmap_werrors,
RECMEMA, &info->recmema);
pci_read_config_dword(pvt->branchmap_werrors,
RECMEMB, &info->recmemb);
pci_read_config_dword(pvt->branchmap_werrors,
REDMEMB, &info->redmemb);
/* Clear the error bits, by writing them back */
pci_write_config_dword(pvt->branchmap_werrors,
FERR_NF_FBD, value);
} else {
info->ferr_nf_fbd = 0;
info->nerr_nf_fbd = 0;
info->recmema = 0;
info->recmemb = 0;
info->redmemb = 0;
}
}
/*
* i5400_proccess_non_recoverable_info(struct mem_ctl_info *mci,
* struct i5400_error_info *info,
* int handle_errors);
*
* handle the Intel FATAL and unrecoverable errors, if any
*/
static void i5400_proccess_non_recoverable_info(struct mem_ctl_info *mci,
struct i5400_error_info *info,
unsigned long allErrors)
{
char msg[EDAC_MC_LABEL_LEN + 1 + 90 + 80];
int branch;
int channel;
int bank;
int buf_id;
int rank;
int rdwr;
int ras, cas;
int errnum;
char *type = NULL;
if (!allErrors)
return; /* if no error, return now */
if (allErrors & ERROR_FAT_MASK)
type = "FATAL";
else if (allErrors & FERR_NF_UNCORRECTABLE)
type = "NON-FATAL uncorrected";
else
type = "NON-FATAL recoverable";
/* ONLY ONE of the possible error bits will be set, as per the docs */
branch = extract_fbdchan_indx(info->ferr_fat_fbd);
channel = branch;
/* Use the NON-Recoverable macros to extract data */
bank = nrec_bank(info);
rank = nrec_rank(info);
buf_id = nrec_buf_id(info);
rdwr = nrec_rdwr(info);
ras = nrec_ras(info);
cas = nrec_cas(info);
debugf0("\t\tCSROW= %d Channels= %d,%d (Branch= %d "
"DRAM Bank= %d Buffer ID = %d rdwr= %s ras= %d cas= %d)\n",
rank, channel, channel + 1, branch >> 1, bank,
buf_id, rdwr_str(rdwr), ras, cas);
/* Only 1 bit will be on */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
/* Form out message */
snprintf(msg, sizeof(msg),
"%s (Branch=%d DRAM-Bank=%d Buffer ID = %d RDWR=%s "
"RAS=%d CAS=%d %s Err=0x%lx (%s))",
type, branch >> 1, bank, buf_id, rdwr_str(rdwr), ras, cas,
type, allErrors, error_name[errnum]);
/* Call the helper to output message */
edac_mc_handle_fbd_ue(mci, rank, channel, channel + 1, msg);
}
/*
* i5400_process_fatal_error_info(struct mem_ctl_info *mci,
* struct i5400_error_info *info,
* int handle_errors);
*
* handle the Intel NON-FATAL errors, if any
*/
static void i5400_process_nonfatal_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{
char msg[EDAC_MC_LABEL_LEN + 1 + 90 + 80];
unsigned long allErrors;
int branch;
int channel;
int bank;
int rank;
int rdwr;
int ras, cas;
int errnum;
/* mask off the Error bits that are possible */
allErrors = from_nf_ferr(info->ferr_nf_fbd & FERR_NF_MASK);
if (!allErrors)
return; /* if no error, return now */
/* ONLY ONE of the possible error bits will be set, as per the docs */
if (allErrors & (ERROR_NF_UNCORRECTABLE | ERROR_NF_RECOVERABLE)) {
i5400_proccess_non_recoverable_info(mci, info, allErrors);
return;
}
/* Correctable errors */
if (allErrors & ERROR_NF_CORRECTABLE) {
debugf0("\tCorrected bits= 0x%lx\n", allErrors);
branch = extract_fbdchan_indx(info->ferr_nf_fbd);
channel = 0;
if (REC_ECC_LOCATOR_ODD(info->redmemb))
channel = 1;
/* Convert channel to be based from zero, instead of
* from branch base of 0 */
channel += branch;
bank = rec_bank(info);
rank = rec_rank(info);
rdwr = rec_rdwr(info);
ras = rec_ras(info);
cas = rec_cas(info);
/* Only 1 bit will be on */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
debugf0("\t\tCSROW= %d Channel= %d (Branch %d "
"DRAM Bank= %d rdwr= %s ras= %d cas= %d)\n",
rank, channel, branch >> 1, bank,
rdwr_str(rdwr), ras, cas);
/* Form out message */
snprintf(msg, sizeof(msg),
"Corrected error (Branch=%d DRAM-Bank=%d RDWR=%s "
"RAS=%d CAS=%d, CE Err=0x%lx (%s))",
branch >> 1, bank, rdwr_str(rdwr), ras, cas,
allErrors, error_name[errnum]);
/* Call the helper to output message */
edac_mc_handle_fbd_ce(mci, rank, channel, msg);
return;
}
/* Miscellaneous errors */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
branch = extract_fbdchan_indx(info->ferr_nf_fbd);
i5400_mc_printk(mci, KERN_EMERG,
"Non-Fatal misc error (Branch=%d Err=%#lx (%s))",
branch >> 1, allErrors, error_name[errnum]);
}
/*
* i5400_process_error_info Process the error info that is
* in the 'info' structure, previously retrieved from hardware
*/
static void i5400_process_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{ u32 allErrors;
/* First handle any fatal errors that occurred */
allErrors = (info->ferr_fat_fbd & FERR_FAT_MASK);
i5400_proccess_non_recoverable_info(mci, info, allErrors);
/* now handle any non-fatal errors that occurred */
i5400_process_nonfatal_error_info(mci, info);
}
/*
* i5400_clear_error Retrieve any error from the hardware
* but do NOT process that error.
* Used for 'clearing' out of previous errors
* Called by the Core module.
*/
static void i5400_clear_error(struct mem_ctl_info *mci)
{
struct i5400_error_info info;
i5400_get_error_info(mci, &info);
}
/*
* i5400_check_error Retrieve and process errors reported by the
* hardware. Called by the Core module.
*/
static void i5400_check_error(struct mem_ctl_info *mci)
{
struct i5400_error_info info;
debugf4("MC%d: %s: %s()\n", mci->mc_idx, __FILE__, __func__);
i5400_get_error_info(mci, &info);
i5400_process_error_info(mci, &info);
}
/*
* i5400_put_devices 'put' all the devices that we have
* reserved via 'get'
*/
static void i5400_put_devices(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
pvt = mci->pvt_info;
/* Decrement usage count for devices */
pci_dev_put(pvt->branch_1);
pci_dev_put(pvt->branch_0);
pci_dev_put(pvt->fsb_error_regs);
pci_dev_put(pvt->branchmap_werrors);
}
/*
* i5400_get_devices Find and perform 'get' operation on the MCH's
* device/functions we want to reference for this driver
*
* Need to 'get' device 16 func 1 and func 2
*/
static int i5400_get_devices(struct mem_ctl_info *mci, int dev_idx)
{
struct i5400_pvt *pvt;
struct pci_dev *pdev;
pvt = mci->pvt_info;
pvt->branchmap_werrors = NULL;
pvt->fsb_error_regs = NULL;
pvt->branch_0 = NULL;
pvt->branch_1 = NULL;
/* Attempt to 'get' the MCH register we want */
pdev = NULL;
while (!pvt->branchmap_werrors || !pvt->fsb_error_regs) {
pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR, pdev);
if (!pdev) {
/* End of list, leave */
i5400_printk(KERN_ERR,
"'system address,Process Bus' "
"device not found:"
"vendor 0x%x device 0x%x ERR funcs "
"(broken BIOS?)\n",
PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR);
goto error;
}
/* Store device 16 funcs 1 and 2 */
switch (PCI_FUNC(pdev->devfn)) {
case 1:
pvt->branchmap_werrors = pdev;
break;
case 2:
pvt->fsb_error_regs = pdev;
break;
}
}
debugf1("System Address, processor bus- PCI Bus ID: %s %x:%x\n",
pci_name(pvt->system_address),
pvt->system_address->vendor, pvt->system_address->device);
debugf1("Branchmap, control and errors - PCI Bus ID: %s %x:%x\n",
pci_name(pvt->branchmap_werrors),
pvt->branchmap_werrors->vendor, pvt->branchmap_werrors->device);
debugf1("FSB Error Regs - PCI Bus ID: %s %x:%x\n",
pci_name(pvt->fsb_error_regs),
pvt->fsb_error_regs->vendor, pvt->fsb_error_regs->device);
pvt->branch_0 = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD0, NULL);
if (!pvt->branch_0) {
i5400_printk(KERN_ERR,
"MC: 'BRANCH 0' device not found:"
"vendor 0x%x device 0x%x Func 0 (broken BIOS?)\n",
PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_5400_FBD0);
goto error;
}
/* If this device claims to have more than 2 channels then
* fetch Branch 1's information
*/
if (pvt->maxch < CHANNELS_PER_BRANCH)
return 0;
pvt->branch_1 = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD1, NULL);
if (!pvt->branch_1) {
i5400_printk(KERN_ERR,
"MC: 'BRANCH 1' device not found:"
"vendor 0x%x device 0x%x Func 0 "
"(broken BIOS?)\n",
PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD1);
goto error;
}
return 0;
error:
i5400_put_devices(mci);
return -ENODEV;
}
/*
* determine_amb_present
*
* the information is contained in NUM_MTRS_PER_BRANCH different
* registers determining which of the NUM_MTRS_PER_BRANCH requires
* knowing which channel is in question
*
* 2 branches, each with 2 channels
* b0_ambpresent0 for channel '0'
* b0_ambpresent1 for channel '1'
* b1_ambpresent0 for channel '2'
* b1_ambpresent1 for channel '3'
*/
static int determine_amb_present_reg(struct i5400_pvt *pvt, int channel)
{
int amb_present;
if (channel < CHANNELS_PER_BRANCH) {
if (channel & 0x1)
amb_present = pvt->b0_ambpresent1;
else
amb_present = pvt->b0_ambpresent0;
} else {
if (channel & 0x1)
amb_present = pvt->b1_ambpresent1;
else
amb_present = pvt->b1_ambpresent0;
}
return amb_present;
}
/*
* determine_mtr(pvt, csrow, channel)
*
* return the proper MTR register as determine by the csrow and desired channel
*/
static int determine_mtr(struct i5400_pvt *pvt, int csrow, int channel)
{
int mtr;
int n;
/* There is one MTR for each slot pair of FB-DIMMs,
Each slot pair may be at branch 0 or branch 1.
*/
n = csrow;
if (n >= NUM_MTRS_PER_BRANCH) {
debugf0("ERROR: trying to access an invalid csrow: %d\n",
csrow);
return 0;
}
if (channel < CHANNELS_PER_BRANCH)
mtr = pvt->b0_mtr[n];
else
mtr = pvt->b1_mtr[n];
return mtr;
}
/*
*/
static void decode_mtr(int slot_row, u16 mtr)
{
int ans;
ans = MTR_DIMMS_PRESENT(mtr);
debugf2("\tMTR%d=0x%x: DIMMs are %s\n", slot_row, mtr,
ans ? "Present" : "NOT Present");
if (!ans)
return;
debugf2("\t\tWIDTH: x%d\n", MTR_DRAM_WIDTH(mtr));
debugf2("\t\tELECTRICAL THROTTLING is %s\n",
MTR_DIMMS_ETHROTTLE(mtr) ? "enabled" : "disabled");
debugf2("\t\tNUMBANK: %d bank(s)\n", MTR_DRAM_BANKS(mtr));
debugf2("\t\tNUMRANK: %s\n", MTR_DIMM_RANK(mtr) ? "double" : "single");
debugf2("\t\tNUMROW: %s\n", numrow_toString[MTR_DIMM_ROWS(mtr)]);
debugf2("\t\tNUMCOL: %s\n", numcol_toString[MTR_DIMM_COLS(mtr)]);
}
static void handle_channel(struct i5400_pvt *pvt, int csrow, int channel,
struct i5400_dimm_info *dinfo)
{
int mtr;
int amb_present_reg;
int addrBits;
mtr = determine_mtr(pvt, csrow, channel);
if (MTR_DIMMS_PRESENT(mtr)) {
amb_present_reg = determine_amb_present_reg(pvt, channel);
/* Determine if there is a DIMM present in this DIMM slot */
if (amb_present_reg & (1 << csrow)) {
/* Start with the number of bits for a Bank
* on the DRAM */
addrBits = MTR_DRAM_BANKS_ADDR_BITS(mtr);
/* Add thenumber of ROW bits */
addrBits += MTR_DIMM_ROWS_ADDR_BITS(mtr);
/* add the number of COLUMN bits */
addrBits += MTR_DIMM_COLS_ADDR_BITS(mtr);
/* add the number of RANK bits */
addrBits += MTR_DIMM_RANK(mtr);
addrBits += 6; /* add 64 bits per DIMM */
addrBits -= 20; /* divide by 2^^20 */
addrBits -= 3; /* 8 bits per bytes */
dinfo->megabytes = 1 << addrBits;
}
}
}
/*
* calculate_dimm_size
*
* also will output a DIMM matrix map, if debug is enabled, for viewing
* how the DIMMs are populated
*/
static void calculate_dimm_size(struct i5400_pvt *pvt)
{
struct i5400_dimm_info *dinfo;
int csrow, max_csrows;
char *p, *mem_buffer;
int space, n;
int channel;
/* ================= Generate some debug output ================= */
space = PAGE_SIZE;
mem_buffer = p = kmalloc(space, GFP_KERNEL);
if (p == NULL) {
i5400_printk(KERN_ERR, "MC: %s:%s() kmalloc() failed\n",
__FILE__, __func__);
return;
}
/* Scan all the actual CSROWS
* and calculate the information for each DIMM
* Start with the highest csrow first, to display it first
* and work toward the 0th csrow
*/
max_csrows = pvt->maxdimmperch;
for (csrow = max_csrows - 1; csrow >= 0; csrow--) {
/* on an odd csrow, first output a 'boundary' marker,
* then reset the message buffer */
if (csrow & 0x1) {
n = snprintf(p, space, "---------------------------"
"--------------------------------");
p += n;
space -= n;
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
}
n = snprintf(p, space, "csrow %2d ", csrow);
p += n;
space -= n;
for (channel = 0; channel < pvt->maxch; channel++) {
dinfo = &pvt->dimm_info[csrow][channel];
handle_channel(pvt, csrow, channel, dinfo);
n = snprintf(p, space, "%4d MB | ", dinfo->megabytes);
p += n;
space -= n;
}
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
}
/* Output the last bottom 'boundary' marker */
n = snprintf(p, space, "---------------------------"
"--------------------------------");
p += n;
space -= n;
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
/* now output the 'channel' labels */
n = snprintf(p, space, " ");
p += n;
space -= n;
for (channel = 0; channel < pvt->maxch; channel++) {
n = snprintf(p, space, "channel %d | ", channel);
p += n;
space -= n;
}
/* output the last message and free buffer */
debugf2("%s\n", mem_buffer);
kfree(mem_buffer);
}
/*
* i5400_get_mc_regs read in the necessary registers and
* cache locally
*
* Fills in the private data members
*/
static void i5400_get_mc_regs(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
u32 actual_tolm;
u16 limit;
int slot_row;
int maxch;
int maxdimmperch;
int way0, way1;
pvt = mci->pvt_info;
pci_read_config_dword(pvt->system_address, AMBASE,
(u32 *) &pvt->ambase);
pci_read_config_dword(pvt->system_address, AMBASE + sizeof(u32),
((u32 *) &pvt->ambase) + sizeof(u32));
maxdimmperch = pvt->maxdimmperch;
maxch = pvt->maxch;
debugf2("AMBASE= 0x%lx MAXCH= %d MAX-DIMM-Per-CH= %d\n",
(long unsigned int)pvt->ambase, pvt->maxch, pvt->maxdimmperch);
/* Get the Branch Map regs */
pci_read_config_word(pvt->branchmap_werrors, TOLM, &pvt->tolm);
pvt->tolm >>= 12;
debugf2("\nTOLM (number of 256M regions) =%u (0x%x)\n", pvt->tolm,
pvt->tolm);
actual_tolm = (u32) ((1000l * pvt->tolm) >> (30 - 28));
debugf2("Actual TOLM byte addr=%u.%03u GB (0x%x)\n",
actual_tolm/1000, actual_tolm % 1000, pvt->tolm << 28);
pci_read_config_word(pvt->branchmap_werrors, MIR0, &pvt->mir0);
pci_read_config_word(pvt->branchmap_werrors, MIR1, &pvt->mir1);
/* Get the MIR[0-1] regs */
limit = (pvt->mir0 >> 4) & 0x0fff;
way0 = pvt->mir0 & 0x1;
way1 = pvt->mir0 & 0x2;
debugf2("MIR0: limit= 0x%x WAY1= %u WAY0= %x\n", limit, way1, way0);
limit = (pvt->mir1 >> 4) & 0xfff;
way0 = pvt->mir1 & 0x1;
way1 = pvt->mir1 & 0x2;
debugf2("MIR1: limit= 0x%x WAY1= %u WAY0= %x\n", limit, way1, way0);
/* Get the set of MTR[0-3] regs by each branch */
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++) {
int where = MTR0 + (slot_row * sizeof(u16));
/* Branch 0 set of MTR registers */
pci_read_config_word(pvt->branch_0, where,
&pvt->b0_mtr[slot_row]);
debugf2("MTR%d where=0x%x B0 value=0x%x\n", slot_row, where,
pvt->b0_mtr[slot_row]);
if (pvt->maxch < CHANNELS_PER_BRANCH) {
pvt->b1_mtr[slot_row] = 0;
continue;
}
/* Branch 1 set of MTR registers */
pci_read_config_word(pvt->branch_1, where,
&pvt->b1_mtr[slot_row]);
debugf2("MTR%d where=0x%x B1 value=0x%x\n", slot_row, where,
pvt->b1_mtr[slot_row]);
}
/* Read and dump branch 0's MTRs */
debugf2("\nMemory Technology Registers:\n");
debugf2(" Branch 0:\n");
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++)
decode_mtr(slot_row, pvt->b0_mtr[slot_row]);
pci_read_config_word(pvt->branch_0, AMBPRESENT_0,
&pvt->b0_ambpresent0);
debugf2("\t\tAMB-Branch 0-present0 0x%x:\n", pvt->b0_ambpresent0);
pci_read_config_word(pvt->branch_0, AMBPRESENT_1,
&pvt->b0_ambpresent1);
debugf2("\t\tAMB-Branch 0-present1 0x%x:\n", pvt->b0_ambpresent1);
/* Only if we have 2 branchs (4 channels) */
if (pvt->maxch < CHANNELS_PER_BRANCH) {
pvt->b1_ambpresent0 = 0;
pvt->b1_ambpresent1 = 0;
} else {
/* Read and dump branch 1's MTRs */
debugf2(" Branch 1:\n");
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++)
decode_mtr(slot_row, pvt->b1_mtr[slot_row]);
pci_read_config_word(pvt->branch_1, AMBPRESENT_0,
&pvt->b1_ambpresent0);
debugf2("\t\tAMB-Branch 1-present0 0x%x:\n",
pvt->b1_ambpresent0);
pci_read_config_word(pvt->branch_1, AMBPRESENT_1,
&pvt->b1_ambpresent1);
debugf2("\t\tAMB-Branch 1-present1 0x%x:\n",
pvt->b1_ambpresent1);
}
/* Go and determine the size of each DIMM and place in an
* orderly matrix */
calculate_dimm_size(pvt);
}
/*
* i5400_init_csrows Initialize the 'csrows' table within
* the mci control structure with the
* addressing of memory.
*
* return:
* 0 success
* 1 no actual memory found on this MC
*/
static int i5400_init_csrows(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
struct csrow_info *p_csrow;
int empty, channel_count;
int max_csrows;
int mtr;
int csrow_megs;
int channel;
int csrow;
pvt = mci->pvt_info;
channel_count = pvt->maxch;
max_csrows = pvt->maxdimmperch;
empty = 1; /* Assume NO memory */
for (csrow = 0; csrow < max_csrows; csrow++) {
p_csrow = &mci->csrows[csrow];
p_csrow->csrow_idx = csrow;
/* use branch 0 for the basis */
mtr = determine_mtr(pvt, csrow, 0);
/* if no DIMMS on this row, continue */
if (!MTR_DIMMS_PRESENT(mtr))
continue;
/* FAKE OUT VALUES, FIXME */
p_csrow->first_page = 0 + csrow * 20;
p_csrow->last_page = 9 + csrow * 20;
p_csrow->page_mask = 0xFFF;
p_csrow->grain = 8;
csrow_megs = 0;
for (channel = 0; channel < pvt->maxch; channel++)
csrow_megs += pvt->dimm_info[csrow][channel].megabytes;
p_csrow->nr_pages = csrow_megs << 8;
/* Assume DDR2 for now */
p_csrow->mtype = MEM_FB_DDR2;
/* ask what device type on this row */
if (MTR_DRAM_WIDTH(mtr))
p_csrow->dtype = DEV_X8;
else
p_csrow->dtype = DEV_X4;
p_csrow->edac_mode = EDAC_S8ECD8ED;
empty = 0;
}
return empty;
}
/*
* i5400_enable_error_reporting
* Turn on the memory reporting features of the hardware
*/
static void i5400_enable_error_reporting(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
u32 fbd_error_mask;
pvt = mci->pvt_info;
/* Read the FBD Error Mask Register */
pci_read_config_dword(pvt->branchmap_werrors, EMASK_FBD,
&fbd_error_mask);
/* Enable with a '0' */
fbd_error_mask &= ~(ENABLE_EMASK_ALL);
pci_write_config_dword(pvt->branchmap_werrors, EMASK_FBD,
fbd_error_mask);
}
/*
* i5400_probe1 Probe for ONE instance of device to see if it is
* present.
* return:
* 0 for FOUND a device
* < 0 for error code
*/
static int i5400_probe1(struct pci_dev *pdev, int dev_idx)
{
struct mem_ctl_info *mci;
struct i5400_pvt *pvt;
int num_channels;
int num_dimms_per_channel;
int num_csrows;
if (dev_idx >= ARRAY_SIZE(i5400_devs))
return -EINVAL;
debugf0("MC: %s: %s(), pdev bus %u dev=0x%x fn=0x%x\n",
__FILE__, __func__,
pdev->bus->number,
PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
/* We only are looking for func 0 of the set */
if (PCI_FUNC(pdev->devfn) != 0)
return -ENODEV;
/* As we don't have a motherboard identification routine to determine
* actual number of slots/dimms per channel, we thus utilize the
* resource as specified by the chipset. Thus, we might have
* have more DIMMs per channel than actually on the mobo, but this
* allows the driver to support up to the chipset max, without
* some fancy mobo determination.
*/
num_dimms_per_channel = MAX_DIMMS_PER_CHANNEL;
num_channels = MAX_CHANNELS;
num_csrows = num_dimms_per_channel;
debugf0("MC: %s(): Number of - Channels= %d DIMMS= %d CSROWS= %d\n",
__func__, num_channels, num_dimms_per_channel, num_csrows);
/* allocate a new MC control structure */
mci = edac_mc_alloc(sizeof(*pvt), num_csrows, num_channels, 0);
if (mci == NULL)
return -ENOMEM;
debugf0("MC: %s: %s(): mci = %p\n", __FILE__, __func__, mci);
mci->dev = &pdev->dev; /* record ptr to the generic device */
pvt = mci->pvt_info;
pvt->system_address = pdev; /* Record this device in our private */
pvt->maxch = num_channels;
pvt->maxdimmperch = num_dimms_per_channel;
/* 'get' the pci devices we want to reserve for our use */
if (i5400_get_devices(mci, dev_idx))
goto fail0;
/* Time to get serious */
i5400_get_mc_regs(mci); /* retrieve the hardware registers */
mci->mc_idx = 0;
mci->mtype_cap = MEM_FLAG_FB_DDR2;
mci->edac_ctl_cap = EDAC_FLAG_NONE;
mci->edac_cap = EDAC_FLAG_NONE;
mci->mod_name = "i5400_edac.c";
mci->mod_ver = I5400_REVISION;
mci->ctl_name = i5400_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->ctl_page_to_phys = NULL;
/* Set the function pointer to an actual operation function */
mci->edac_check = i5400_check_error;
/* initialize the MC control structure 'csrows' table
* with the mapping and control information */
if (i5400_init_csrows(mci)) {
debugf0("MC: Setting mci->edac_cap to EDAC_FLAG_NONE\n"
" because i5400_init_csrows() returned nonzero "
"value\n");
mci->edac_cap = EDAC_FLAG_NONE; /* no csrows found */
} else {
debugf1("MC: Enable error reporting now\n");
i5400_enable_error_reporting(mci);
}
/* add this new MC control structure to EDAC's list of MCs */
if (edac_mc_add_mc(mci)) {
debugf0("MC: %s: %s(): failed edac_mc_add_mc()\n",
__FILE__, __func__);
/* FIXME: perhaps some code should go here that disables error
* reporting if we just enabled it
*/
goto fail1;
}
i5400_clear_error(mci);
/* allocating generic PCI control info */
i5400_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i5400_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
return 0;
/* Error exit unwinding stack */
fail1:
i5400_put_devices(mci);
fail0:
edac_mc_free(mci);
return -ENODEV;
}
/*
* i5400_init_one constructor for one instance of device
*
* returns:
* negative on error
* count (>= 0)
*/
static int __devinit i5400_init_one(struct pci_dev *pdev,
const struct pci_device_id *id)
{
int rc;
debugf0("MC: %s: %s()\n", __FILE__, __func__);
/* wake up device */
rc = pci_enable_device(pdev);
if (rc)
return rc;
/* now probe and enable the device */
return i5400_probe1(pdev, id->driver_data);
}
/*
* i5400_remove_one destructor for one instance of device
*
*/
static void __devexit i5400_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s: %s()\n", __FILE__, __func__);
if (i5400_pci)
edac_pci_release_generic_ctl(i5400_pci);
mci = edac_mc_del_mc(&pdev->dev);
if (!mci)
return;
/* retrieve references to resources, and free those resources */
i5400_put_devices(mci);
edac_mc_free(mci);
}
/*
* pci_device_id table for which devices we are looking for
*
* The "E500P" device is the first device supported.
*/
static const struct pci_device_id i5400_pci_tbl[] __devinitdata = {
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_5400_ERR)},
{0,} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i5400_pci_tbl);
/*
* i5400_driver pci_driver structure for this module
*
*/
static struct pci_driver i5400_driver = {
.name = "i5400_edac",
.probe = i5400_init_one,
.remove = __devexit_p(i5400_remove_one),
.id_table = i5400_pci_tbl,
};
/*
* i5400_init Module entry function
* Try to initialize this module for its devices
*/
static int __init i5400_init(void)
{
int pci_rc;
debugf2("MC: %s: %s()\n", __FILE__, __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&i5400_driver);
return (pci_rc < 0) ? pci_rc : 0;
}
/*
* i5400_exit() Module exit function
* Unregister the driver
*/
static void __exit i5400_exit(void)
{
debugf2("MC: %s: %s()\n", __FILE__, __func__);
pci_unregister_driver(&i5400_driver);
}
module_init(i5400_init);
module_exit(i5400_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Woodard <woodard@redhat.com>");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)");
MODULE_DESCRIPTION("MC Driver for Intel I5400 memory controllers - "
I5400_REVISION);
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
MoKee/android_kernel_oppo_find7a | drivers/usb/misc/iowarrior.c | 4820 | 26131 | /*
* Native support for the I/O-Warrior USB devices
*
* Copyright (c) 2003-2005 Code Mercenaries GmbH
* written by Christian Lucht <lucht@codemercs.com>
*
* based on
* usb-skeleton.c by Greg Kroah-Hartman <greg@kroah.com>
* brlvger.c by Stephane Dalton <sdalton@videotron.ca>
* and St�hane Doyon <s.doyon@videotron.ca>
*
* Released under the GPLv2.
*/
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/usb/iowarrior.h>
/* Version Information */
#define DRIVER_VERSION "v0.4.0"
#define DRIVER_AUTHOR "Christian Lucht <lucht@codemercs.com>"
#define DRIVER_DESC "USB IO-Warrior driver (Linux 2.6.x)"
#define USB_VENDOR_ID_CODEMERCS 1984
/* low speed iowarrior */
#define USB_DEVICE_ID_CODEMERCS_IOW40 0x1500
#define USB_DEVICE_ID_CODEMERCS_IOW24 0x1501
#define USB_DEVICE_ID_CODEMERCS_IOWPV1 0x1511
#define USB_DEVICE_ID_CODEMERCS_IOWPV2 0x1512
/* full speed iowarrior */
#define USB_DEVICE_ID_CODEMERCS_IOW56 0x1503
/* Get a minor range for your devices from the usb maintainer */
#ifdef CONFIG_USB_DYNAMIC_MINORS
#define IOWARRIOR_MINOR_BASE 0
#else
#define IOWARRIOR_MINOR_BASE 208 // SKELETON_MINOR_BASE 192 + 16, not official yet
#endif
/* interrupt input queue size */
#define MAX_INTERRUPT_BUFFER 16
/*
maximum number of urbs that are submitted for writes at the same time,
this applies to the IOWarrior56 only!
IOWarrior24 and IOWarrior40 use synchronous usb_control_msg calls.
*/
#define MAX_WRITES_IN_FLIGHT 4
/* Use our own dbg macro */
#undef dbg
#define dbg( format, arg... ) do { if( debug ) printk( KERN_DEBUG __FILE__ ": " format "\n" , ## arg ); } while ( 0 )
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/* Module parameters */
static DEFINE_MUTEX(iowarrior_mutex);
static bool debug = 0;
module_param(debug, bool, 0644);
MODULE_PARM_DESC(debug, "debug=1 enables debugging messages");
static struct usb_driver iowarrior_driver;
static DEFINE_MUTEX(iowarrior_open_disc_lock);
/*--------------*/
/* data */
/*--------------*/
/* Structure to hold all of our device specific stuff */
struct iowarrior {
struct mutex mutex; /* locks this structure */
struct usb_device *udev; /* save off the usb device pointer */
struct usb_interface *interface; /* the interface for this device */
unsigned char minor; /* the starting minor number for this device */
struct usb_endpoint_descriptor *int_out_endpoint; /* endpoint for reading (needed for IOW56 only) */
struct usb_endpoint_descriptor *int_in_endpoint; /* endpoint for reading */
struct urb *int_in_urb; /* the urb for reading data */
unsigned char *int_in_buffer; /* buffer for data to be read */
unsigned char serial_number; /* to detect lost packages */
unsigned char *read_queue; /* size is MAX_INTERRUPT_BUFFER * packet size */
wait_queue_head_t read_wait;
wait_queue_head_t write_wait; /* wait-queue for writing to the device */
atomic_t write_busy; /* number of write-urbs submitted */
atomic_t read_idx;
atomic_t intr_idx;
spinlock_t intr_idx_lock; /* protects intr_idx */
atomic_t overflow_flag; /* signals an index 'rollover' */
int present; /* this is 1 as long as the device is connected */
int opened; /* this is 1 if the device is currently open */
char chip_serial[9]; /* the serial number string of the chip connected */
int report_size; /* number of bytes in a report */
u16 product_id;
};
/*--------------*/
/* globals */
/*--------------*/
/*
* USB spec identifies 5 second timeouts.
*/
#define GET_TIMEOUT 5
#define USB_REQ_GET_REPORT 0x01
//#if 0
static int usb_get_report(struct usb_device *dev,
struct usb_host_interface *inter, unsigned char type,
unsigned char id, void *buf, int size)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_REPORT,
USB_DIR_IN | USB_TYPE_CLASS |
USB_RECIP_INTERFACE, (type << 8) + id,
inter->desc.bInterfaceNumber, buf, size,
GET_TIMEOUT*HZ);
}
//#endif
#define USB_REQ_SET_REPORT 0x09
static int usb_set_report(struct usb_interface *intf, unsigned char type,
unsigned char id, void *buf, int size)
{
return usb_control_msg(interface_to_usbdev(intf),
usb_sndctrlpipe(interface_to_usbdev(intf), 0),
USB_REQ_SET_REPORT,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
(type << 8) + id,
intf->cur_altsetting->desc.bInterfaceNumber, buf,
size, HZ);
}
/*---------------------*/
/* driver registration */
/*---------------------*/
/* table of devices that work with this driver */
static const struct usb_device_id iowarrior_ids[] = {
{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW40)},
{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW24)},
{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOWPV1)},
{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOWPV2)},
{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW56)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, iowarrior_ids);
/*
* USB callback handler for reading data
*/
static void iowarrior_callback(struct urb *urb)
{
struct iowarrior *dev = urb->context;
int intr_idx;
int read_idx;
int aux_idx;
int offset;
int status = urb->status;
int retval;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
return;
default:
goto exit;
}
spin_lock(&dev->intr_idx_lock);
intr_idx = atomic_read(&dev->intr_idx);
/* aux_idx become previous intr_idx */
aux_idx = (intr_idx == 0) ? (MAX_INTERRUPT_BUFFER - 1) : (intr_idx - 1);
read_idx = atomic_read(&dev->read_idx);
/* queue is not empty and it's interface 0 */
if ((intr_idx != read_idx)
&& (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0)) {
/* + 1 for serial number */
offset = aux_idx * (dev->report_size + 1);
if (!memcmp
(dev->read_queue + offset, urb->transfer_buffer,
dev->report_size)) {
/* equal values on interface 0 will be ignored */
spin_unlock(&dev->intr_idx_lock);
goto exit;
}
}
/* aux_idx become next intr_idx */
aux_idx = (intr_idx == (MAX_INTERRUPT_BUFFER - 1)) ? 0 : (intr_idx + 1);
if (read_idx == aux_idx) {
/* queue full, dropping oldest input */
read_idx = (++read_idx == MAX_INTERRUPT_BUFFER) ? 0 : read_idx;
atomic_set(&dev->read_idx, read_idx);
atomic_set(&dev->overflow_flag, 1);
}
/* +1 for serial number */
offset = intr_idx * (dev->report_size + 1);
memcpy(dev->read_queue + offset, urb->transfer_buffer,
dev->report_size);
*(dev->read_queue + offset + (dev->report_size)) = dev->serial_number++;
atomic_set(&dev->intr_idx, aux_idx);
spin_unlock(&dev->intr_idx_lock);
/* tell the blocking read about the new data */
wake_up_interruptible(&dev->read_wait);
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&dev->interface->dev, "%s - usb_submit_urb failed with result %d\n",
__func__, retval);
}
/*
* USB Callback handler for write-ops
*/
static void iowarrior_write_callback(struct urb *urb)
{
struct iowarrior *dev;
int status = urb->status;
dev = urb->context;
/* sync/async unlink faults aren't errors */
if (status &&
!(status == -ENOENT ||
status == -ECONNRESET || status == -ESHUTDOWN)) {
dbg("%s - nonzero write bulk status received: %d",
__func__, status);
}
/* free up our allocated buffer */
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
/* tell a waiting writer the interrupt-out-pipe is available again */
atomic_dec(&dev->write_busy);
wake_up_interruptible(&dev->write_wait);
}
/**
* iowarrior_delete
*/
static inline void iowarrior_delete(struct iowarrior *dev)
{
dbg("%s - minor %d", __func__, dev->minor);
kfree(dev->int_in_buffer);
usb_free_urb(dev->int_in_urb);
kfree(dev->read_queue);
kfree(dev);
}
/*---------------------*/
/* fops implementation */
/*---------------------*/
static int read_index(struct iowarrior *dev)
{
int intr_idx, read_idx;
read_idx = atomic_read(&dev->read_idx);
intr_idx = atomic_read(&dev->intr_idx);
return (read_idx == intr_idx ? -1 : read_idx);
}
/**
* iowarrior_read
*/
static ssize_t iowarrior_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct iowarrior *dev;
int read_idx;
int offset;
dev = file->private_data;
/* verify that the device wasn't unplugged */
if (dev == NULL || !dev->present)
return -ENODEV;
dbg("%s - minor %d, count = %zd", __func__, dev->minor, count);
/* read count must be packet size (+ time stamp) */
if ((count != dev->report_size)
&& (count != (dev->report_size + 1)))
return -EINVAL;
/* repeat until no buffer overrun in callback handler occur */
do {
atomic_set(&dev->overflow_flag, 0);
if ((read_idx = read_index(dev)) == -1) {
/* queue emty */
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
else {
//next line will return when there is either new data, or the device is unplugged
int r = wait_event_interruptible(dev->read_wait,
(!dev->present
|| (read_idx =
read_index
(dev)) !=
-1));
if (r) {
//we were interrupted by a signal
return -ERESTART;
}
if (!dev->present) {
//The device was unplugged
return -ENODEV;
}
if (read_idx == -1) {
// Can this happen ???
return 0;
}
}
}
offset = read_idx * (dev->report_size + 1);
if (copy_to_user(buffer, dev->read_queue + offset, count)) {
return -EFAULT;
}
} while (atomic_read(&dev->overflow_flag));
read_idx = ++read_idx == MAX_INTERRUPT_BUFFER ? 0 : read_idx;
atomic_set(&dev->read_idx, read_idx);
return count;
}
/*
* iowarrior_write
*/
static ssize_t iowarrior_write(struct file *file,
const char __user *user_buffer,
size_t count, loff_t *ppos)
{
struct iowarrior *dev;
int retval = 0;
char *buf = NULL; /* for IOW24 and IOW56 we need a buffer */
struct urb *int_out_urb = NULL;
dev = file->private_data;
mutex_lock(&dev->mutex);
/* verify that the device wasn't unplugged */
if (!dev->present) {
retval = -ENODEV;
goto exit;
}
dbg("%s - minor %d, count = %zd", __func__, dev->minor, count);
/* if count is 0 we're already done */
if (count == 0) {
retval = 0;
goto exit;
}
/* We only accept full reports */
if (count != dev->report_size) {
retval = -EINVAL;
goto exit;
}
switch (dev->product_id) {
case USB_DEVICE_ID_CODEMERCS_IOW24:
case USB_DEVICE_ID_CODEMERCS_IOWPV1:
case USB_DEVICE_ID_CODEMERCS_IOWPV2:
case USB_DEVICE_ID_CODEMERCS_IOW40:
/* IOW24 and IOW40 use a synchronous call */
buf = kmalloc(count, GFP_KERNEL);
if (!buf) {
retval = -ENOMEM;
goto exit;
}
if (copy_from_user(buf, user_buffer, count)) {
retval = -EFAULT;
kfree(buf);
goto exit;
}
retval = usb_set_report(dev->interface, 2, 0, buf, count);
kfree(buf);
goto exit;
break;
case USB_DEVICE_ID_CODEMERCS_IOW56:
/* The IOW56 uses asynchronous IO and more urbs */
if (atomic_read(&dev->write_busy) == MAX_WRITES_IN_FLIGHT) {
/* Wait until we are below the limit for submitted urbs */
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto exit;
} else {
retval = wait_event_interruptible(dev->write_wait,
(!dev->present || (atomic_read (&dev-> write_busy) < MAX_WRITES_IN_FLIGHT)));
if (retval) {
/* we were interrupted by a signal */
retval = -ERESTART;
goto exit;
}
if (!dev->present) {
/* The device was unplugged */
retval = -ENODEV;
goto exit;
}
if (!dev->opened) {
/* We were closed while waiting for an URB */
retval = -ENODEV;
goto exit;
}
}
}
atomic_inc(&dev->write_busy);
int_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!int_out_urb) {
retval = -ENOMEM;
dbg("%s Unable to allocate urb ", __func__);
goto error_no_urb;
}
buf = usb_alloc_coherent(dev->udev, dev->report_size,
GFP_KERNEL, &int_out_urb->transfer_dma);
if (!buf) {
retval = -ENOMEM;
dbg("%s Unable to allocate buffer ", __func__);
goto error_no_buffer;
}
usb_fill_int_urb(int_out_urb, dev->udev,
usb_sndintpipe(dev->udev,
dev->int_out_endpoint->bEndpointAddress),
buf, dev->report_size,
iowarrior_write_callback, dev,
dev->int_out_endpoint->bInterval);
int_out_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
if (copy_from_user(buf, user_buffer, count)) {
retval = -EFAULT;
goto error;
}
retval = usb_submit_urb(int_out_urb, GFP_KERNEL);
if (retval) {
dbg("%s submit error %d for urb nr.%d", __func__,
retval, atomic_read(&dev->write_busy));
goto error;
}
/* submit was ok */
retval = count;
usb_free_urb(int_out_urb);
goto exit;
break;
default:
/* what do we have here ? An unsupported Product-ID ? */
dev_err(&dev->interface->dev, "%s - not supported for product=0x%x\n",
__func__, dev->product_id);
retval = -EFAULT;
goto exit;
break;
}
error:
usb_free_coherent(dev->udev, dev->report_size, buf,
int_out_urb->transfer_dma);
error_no_buffer:
usb_free_urb(int_out_urb);
error_no_urb:
atomic_dec(&dev->write_busy);
wake_up_interruptible(&dev->write_wait);
exit:
mutex_unlock(&dev->mutex);
return retval;
}
/**
* iowarrior_ioctl
*/
static long iowarrior_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct iowarrior *dev = NULL;
__u8 *buffer;
__u8 __user *user_buffer;
int retval;
int io_res; /* checks for bytes read/written and copy_to/from_user results */
dev = file->private_data;
if (dev == NULL) {
return -ENODEV;
}
buffer = kzalloc(dev->report_size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
/* lock this object */
mutex_lock(&iowarrior_mutex);
mutex_lock(&dev->mutex);
/* verify that the device wasn't unplugged */
if (!dev->present) {
retval = -ENODEV;
goto error_out;
}
dbg("%s - minor %d, cmd 0x%.4x, arg %ld", __func__, dev->minor, cmd,
arg);
retval = 0;
io_res = 0;
switch (cmd) {
case IOW_WRITE:
if (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW24 ||
dev->product_id == USB_DEVICE_ID_CODEMERCS_IOWPV1 ||
dev->product_id == USB_DEVICE_ID_CODEMERCS_IOWPV2 ||
dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW40) {
user_buffer = (__u8 __user *)arg;
io_res = copy_from_user(buffer, user_buffer,
dev->report_size);
if (io_res) {
retval = -EFAULT;
} else {
io_res = usb_set_report(dev->interface, 2, 0,
buffer,
dev->report_size);
if (io_res < 0)
retval = io_res;
}
} else {
retval = -EINVAL;
dev_err(&dev->interface->dev,
"ioctl 'IOW_WRITE' is not supported for product=0x%x.\n",
dev->product_id);
}
break;
case IOW_READ:
user_buffer = (__u8 __user *)arg;
io_res = usb_get_report(dev->udev,
dev->interface->cur_altsetting, 1, 0,
buffer, dev->report_size);
if (io_res < 0)
retval = io_res;
else {
io_res = copy_to_user(user_buffer, buffer, dev->report_size);
if (io_res)
retval = -EFAULT;
}
break;
case IOW_GETINFO:
{
/* Report available information for the device */
struct iowarrior_info info;
/* needed for power consumption */
struct usb_config_descriptor *cfg_descriptor = &dev->udev->actconfig->desc;
memset(&info, 0, sizeof(info));
/* directly from the descriptor */
info.vendor = le16_to_cpu(dev->udev->descriptor.idVendor);
info.product = dev->product_id;
info.revision = le16_to_cpu(dev->udev->descriptor.bcdDevice);
/* 0==UNKNOWN, 1==LOW(usb1.1) ,2=FULL(usb1.1), 3=HIGH(usb2.0) */
info.speed = le16_to_cpu(dev->udev->speed);
info.if_num = dev->interface->cur_altsetting->desc.bInterfaceNumber;
info.report_size = dev->report_size;
/* serial number string has been read earlier 8 chars or empty string */
memcpy(info.serial, dev->chip_serial,
sizeof(dev->chip_serial));
if (cfg_descriptor == NULL) {
info.power = -1; /* no information available */
} else {
/* the MaxPower is stored in units of 2mA to make it fit into a byte-value */
info.power = cfg_descriptor->bMaxPower * 2;
}
io_res = copy_to_user((struct iowarrior_info __user *)arg, &info,
sizeof(struct iowarrior_info));
if (io_res)
retval = -EFAULT;
break;
}
default:
/* return that we did not understand this ioctl call */
retval = -ENOTTY;
break;
}
error_out:
/* unlock the device */
mutex_unlock(&dev->mutex);
mutex_unlock(&iowarrior_mutex);
kfree(buffer);
return retval;
}
/**
* iowarrior_open
*/
static int iowarrior_open(struct inode *inode, struct file *file)
{
struct iowarrior *dev = NULL;
struct usb_interface *interface;
int subminor;
int retval = 0;
dbg("%s", __func__);
mutex_lock(&iowarrior_mutex);
subminor = iminor(inode);
interface = usb_find_interface(&iowarrior_driver, subminor);
if (!interface) {
mutex_unlock(&iowarrior_mutex);
err("%s - error, can't find device for minor %d", __func__,
subminor);
return -ENODEV;
}
mutex_lock(&iowarrior_open_disc_lock);
dev = usb_get_intfdata(interface);
if (!dev) {
mutex_unlock(&iowarrior_open_disc_lock);
mutex_unlock(&iowarrior_mutex);
return -ENODEV;
}
mutex_lock(&dev->mutex);
mutex_unlock(&iowarrior_open_disc_lock);
/* Only one process can open each device, no sharing. */
if (dev->opened) {
retval = -EBUSY;
goto out;
}
/* setup interrupt handler for receiving values */
if ((retval = usb_submit_urb(dev->int_in_urb, GFP_KERNEL)) < 0) {
dev_err(&interface->dev, "Error %d while submitting URB\n", retval);
retval = -EFAULT;
goto out;
}
/* increment our usage count for the driver */
++dev->opened;
/* save our object in the file's private structure */
file->private_data = dev;
retval = 0;
out:
mutex_unlock(&dev->mutex);
mutex_unlock(&iowarrior_mutex);
return retval;
}
/**
* iowarrior_release
*/
static int iowarrior_release(struct inode *inode, struct file *file)
{
struct iowarrior *dev;
int retval = 0;
dev = file->private_data;
if (dev == NULL) {
return -ENODEV;
}
dbg("%s - minor %d", __func__, dev->minor);
/* lock our device */
mutex_lock(&dev->mutex);
if (dev->opened <= 0) {
retval = -ENODEV; /* close called more than once */
mutex_unlock(&dev->mutex);
} else {
dev->opened = 0; /* we're closeing now */
retval = 0;
if (dev->present) {
/*
The device is still connected so we only shutdown
pending read-/write-ops.
*/
usb_kill_urb(dev->int_in_urb);
wake_up_interruptible(&dev->read_wait);
wake_up_interruptible(&dev->write_wait);
mutex_unlock(&dev->mutex);
} else {
/* The device was unplugged, cleanup resources */
mutex_unlock(&dev->mutex);
iowarrior_delete(dev);
}
}
return retval;
}
static unsigned iowarrior_poll(struct file *file, poll_table * wait)
{
struct iowarrior *dev = file->private_data;
unsigned int mask = 0;
if (!dev->present)
return POLLERR | POLLHUP;
poll_wait(file, &dev->read_wait, wait);
poll_wait(file, &dev->write_wait, wait);
if (!dev->present)
return POLLERR | POLLHUP;
if (read_index(dev) != -1)
mask |= POLLIN | POLLRDNORM;
if (atomic_read(&dev->write_busy) < MAX_WRITES_IN_FLIGHT)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/*
* File operations needed when we register this driver.
* This assumes that this driver NEEDS file operations,
* of course, which means that the driver is expected
* to have a node in the /dev directory. If the USB
* device were for a network interface then the driver
* would use "struct net_driver" instead, and a serial
* device would use "struct tty_driver".
*/
static const struct file_operations iowarrior_fops = {
.owner = THIS_MODULE,
.write = iowarrior_write,
.read = iowarrior_read,
.unlocked_ioctl = iowarrior_ioctl,
.open = iowarrior_open,
.release = iowarrior_release,
.poll = iowarrior_poll,
.llseek = noop_llseek,
};
static char *iowarrior_devnode(struct device *dev, umode_t *mode)
{
return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev));
}
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with devfs and the driver core
*/
static struct usb_class_driver iowarrior_class = {
.name = "iowarrior%d",
.devnode = iowarrior_devnode,
.fops = &iowarrior_fops,
.minor_base = IOWARRIOR_MINOR_BASE,
};
/*---------------------------------*/
/* probe and disconnect functions */
/*---------------------------------*/
/**
* iowarrior_probe
*
* Called by the usb core when a new device is connected that it thinks
* this driver might be interested in.
*/
static int iowarrior_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct iowarrior *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
int retval = -ENOMEM;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL);
if (dev == NULL) {
dev_err(&interface->dev, "Out of memory\n");
return retval;
}
mutex_init(&dev->mutex);
atomic_set(&dev->intr_idx, 0);
atomic_set(&dev->read_idx, 0);
spin_lock_init(&dev->intr_idx_lock);
atomic_set(&dev->overflow_flag, 0);
init_waitqueue_head(&dev->read_wait);
atomic_set(&dev->write_busy, 0);
init_waitqueue_head(&dev->write_wait);
dev->udev = udev;
dev->interface = interface;
iface_desc = interface->cur_altsetting;
dev->product_id = le16_to_cpu(udev->descriptor.idProduct);
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint))
dev->int_in_endpoint = endpoint;
if (usb_endpoint_is_int_out(endpoint))
/* this one will match for the IOWarrior56 only */
dev->int_out_endpoint = endpoint;
}
/* we have to check the report_size often, so remember it in the endianess suitable for our machine */
dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint);
if ((dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) &&
(dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56))
/* IOWarrior56 has wMaxPacketSize different from report size */
dev->report_size = 7;
/* create the urb and buffer for reading */
dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->int_in_urb) {
dev_err(&interface->dev, "Couldn't allocate interrupt_in_urb\n");
goto error;
}
dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL);
if (!dev->int_in_buffer) {
dev_err(&interface->dev, "Couldn't allocate int_in_buffer\n");
goto error;
}
usb_fill_int_urb(dev->int_in_urb, dev->udev,
usb_rcvintpipe(dev->udev,
dev->int_in_endpoint->bEndpointAddress),
dev->int_in_buffer, dev->report_size,
iowarrior_callback, dev,
dev->int_in_endpoint->bInterval);
/* create an internal buffer for interrupt data from the device */
dev->read_queue =
kmalloc(((dev->report_size + 1) * MAX_INTERRUPT_BUFFER),
GFP_KERNEL);
if (!dev->read_queue) {
dev_err(&interface->dev, "Couldn't allocate read_queue\n");
goto error;
}
/* Get the serial-number of the chip */
memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial));
usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial,
sizeof(dev->chip_serial));
if (strlen(dev->chip_serial) != 8)
memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial));
/* Set the idle timeout to 0, if this is interface 0 */
if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) {
usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x0A,
USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0,
0, NULL, 0, USB_CTRL_SET_TIMEOUT);
}
/* allow device read and ioctl */
dev->present = 1;
/* we can register the device now, as it is ready */
usb_set_intfdata(interface, dev);
retval = usb_register_dev(interface, &iowarrior_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(&interface->dev, "Not able to get a minor for this device.\n");
usb_set_intfdata(interface, NULL);
goto error;
}
dev->minor = interface->minor;
/* let the user know what node this device is now attached to */
dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d "
"now attached to iowarrior%d\n", dev->product_id, dev->chip_serial,
iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE);
return retval;
error:
iowarrior_delete(dev);
return retval;
}
/**
* iowarrior_disconnect
*
* Called by the usb core when the device is removed from the system.
*/
static void iowarrior_disconnect(struct usb_interface *interface)
{
struct iowarrior *dev;
int minor;
dev = usb_get_intfdata(interface);
mutex_lock(&iowarrior_open_disc_lock);
usb_set_intfdata(interface, NULL);
minor = dev->minor;
/* give back our minor */
usb_deregister_dev(interface, &iowarrior_class);
mutex_lock(&dev->mutex);
/* prevent device read, write and ioctl */
dev->present = 0;
mutex_unlock(&dev->mutex);
mutex_unlock(&iowarrior_open_disc_lock);
if (dev->opened) {
/* There is a process that holds a filedescriptor to the device ,
so we only shutdown read-/write-ops going on.
Deleting the device is postponed until close() was called.
*/
usb_kill_urb(dev->int_in_urb);
wake_up_interruptible(&dev->read_wait);
wake_up_interruptible(&dev->write_wait);
} else {
/* no process is using the device, cleanup now */
iowarrior_delete(dev);
}
dev_info(&interface->dev, "I/O-Warror #%d now disconnected\n",
minor - IOWARRIOR_MINOR_BASE);
}
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver iowarrior_driver = {
.name = "iowarrior",
.probe = iowarrior_probe,
.disconnect = iowarrior_disconnect,
.id_table = iowarrior_ids,
};
module_usb_driver(iowarrior_driver);
| gpl-2.0 |
pausa/android_kernel_htc_k2_ul | arch/arm/mach-s3c24xx/mach-amlm5900.c | 4820 | 5868 | /* linux/arch/arm/mach-s3c2410/mach-amlm5900.c
*
* linux/arch/arm/mach-s3c2410/mach-amlm5900.c
*
* Copyright (c) 2006 American Microsystems Limited
* David Anders <danders@amltd.com>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* @History:
* derived from linux/arch/arm/mach-s3c2410/mach-bast.c, written by
* Ben Dooks <ben@simtec.co.uk>
*
***********************************************************************/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/proc_fs.h>
#include <linux/serial_core.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/flash.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/fb.h>
#include <plat/regs-serial.h>
#include <mach/regs-lcd.h>
#include <mach/regs-gpio.h>
#include <plat/iic.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/gpio-cfg.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/map.h>
#include <linux/mtd/physmap.h>
#include "common.h"
static struct resource amlm5900_nor_resource = {
.start = 0x00000000,
.end = 0x01000000 - 1,
.flags = IORESOURCE_MEM,
};
static struct mtd_partition amlm5900_mtd_partitions[] = {
{
.name = "System",
.size = 0x240000,
.offset = 0,
.mask_flags = MTD_WRITEABLE, /* force read-only */
}, {
.name = "Kernel",
.size = 0x100000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "Ramdisk",
.size = 0x300000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "JFFS2",
.size = 0x9A0000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "Settings",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct physmap_flash_data amlm5900_flash_data = {
.width = 2,
.parts = amlm5900_mtd_partitions,
.nr_parts = ARRAY_SIZE(amlm5900_mtd_partitions),
};
static struct platform_device amlm5900_device_nor = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &amlm5900_flash_data,
},
.num_resources = 1,
.resource = &amlm5900_nor_resource,
};
static struct map_desc amlm5900_iodesc[] __initdata = {
};
#define UCON S3C2410_UCON_DEFAULT
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg amlm5900_uartcfgs[] = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
static struct platform_device *amlm5900_devices[] __initdata = {
#ifdef CONFIG_FB_S3C2410
&s3c_device_lcd,
#endif
&s3c_device_adc,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_ohci,
&s3c_device_rtc,
&s3c_device_usbgadget,
&s3c_device_sdi,
&amlm5900_device_nor,
};
static void __init amlm5900_map_io(void)
{
s3c24xx_init_io(amlm5900_iodesc, ARRAY_SIZE(amlm5900_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(amlm5900_uartcfgs, ARRAY_SIZE(amlm5900_uartcfgs));
}
#ifdef CONFIG_FB_S3C2410
static struct s3c2410fb_display __initdata amlm5900_lcd_info = {
.width = 160,
.height = 160,
.type = S3C2410_LCDCON1_STN4,
.pixclock = 680000, /* HCLK = 100MHz */
.xres = 160,
.yres = 160,
.bpp = 4,
.left_margin = 1 << (4 + 3),
.right_margin = 8 << 3,
.hsync_len = 48,
.upper_margin = 0,
.lower_margin = 0,
.lcdcon5 = 0x00000001,
};
static struct s3c2410fb_mach_info __initdata amlm5900_fb_info = {
.displays = &amlm5900_lcd_info,
.num_displays = 1,
.default_display = 0,
.gpccon = 0xaaaaaaaa,
.gpccon_mask = 0xffffffff,
.gpcup = 0x0000ffff,
.gpcup_mask = 0xffffffff,
.gpdcon = 0xaaaaaaaa,
.gpdcon_mask = 0xffffffff,
.gpdup = 0x0000ffff,
.gpdup_mask = 0xffffffff,
};
#endif
static irqreturn_t
amlm5900_wake_interrupt(int irq, void *ignored)
{
return IRQ_HANDLED;
}
static void amlm5900_init_pm(void)
{
int ret = 0;
ret = request_irq(IRQ_EINT9, &amlm5900_wake_interrupt,
IRQF_TRIGGER_RISING | IRQF_SHARED,
"amlm5900_wakeup", &amlm5900_wake_interrupt);
if (ret != 0) {
printk(KERN_ERR "AML-M5900: no wakeup irq, %d?\n", ret);
} else {
enable_irq_wake(IRQ_EINT9);
/* configure the suspend/resume status pin */
s3c_gpio_cfgpin(S3C2410_GPF(2), S3C2410_GPIO_OUTPUT);
s3c_gpio_setpull(S3C2410_GPF(2), S3C_GPIO_PULL_UP);
}
}
static void __init amlm5900_init(void)
{
amlm5900_init_pm();
#ifdef CONFIG_FB_S3C2410
s3c24xx_fb_set_platdata(&amlm5900_fb_info);
#endif
s3c_i2c0_set_platdata(NULL);
platform_add_devices(amlm5900_devices, ARRAY_SIZE(amlm5900_devices));
}
MACHINE_START(AML_M5900, "AML_M5900")
.atag_offset = 0x100,
.map_io = amlm5900_map_io,
.init_irq = s3c24xx_init_irq,
.init_machine = amlm5900_init,
.timer = &s3c24xx_timer,
.restart = s3c2410_restart,
MACHINE_END
| gpl-2.0 |
klabit87/kltevzw_pb1 | sound/soc/au1x/i2sc.c | 5076 | 7393 | /*
* Au1000/Au1500/Au1100 I2S controller driver for ASoC
*
* (c) 2011 Manuel Lauss <manuel.lauss@googlemail.com>
*
* Note: clock supplied to the I2S controller must be 256x samplerate.
*/
#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 "psc.h"
#define I2S_RXTX 0x00
#define I2S_CFG 0x04
#define I2S_ENABLE 0x08
#define CFG_XU (1 << 25) /* tx underflow */
#define CFG_XO (1 << 24)
#define CFG_RU (1 << 23)
#define CFG_RO (1 << 22)
#define CFG_TR (1 << 21)
#define CFG_TE (1 << 20)
#define CFG_TF (1 << 19)
#define CFG_RR (1 << 18)
#define CFG_RF (1 << 17)
#define CFG_ICK (1 << 12) /* clock invert */
#define CFG_PD (1 << 11) /* set to make I2SDIO INPUT */
#define CFG_LB (1 << 10) /* loopback */
#define CFG_IC (1 << 9) /* word select invert */
#define CFG_FM_I2S (0 << 7) /* I2S format */
#define CFG_FM_LJ (1 << 7) /* left-justified */
#define CFG_FM_RJ (2 << 7) /* right-justified */
#define CFG_FM_MASK (3 << 7)
#define CFG_TN (1 << 6) /* tx fifo en */
#define CFG_RN (1 << 5) /* rx fifo en */
#define CFG_SZ_8 (0x08)
#define CFG_SZ_16 (0x10)
#define CFG_SZ_18 (0x12)
#define CFG_SZ_20 (0x14)
#define CFG_SZ_24 (0x18)
#define CFG_SZ_MASK (0x1f)
#define EN_D (1 << 1) /* DISable */
#define EN_CE (1 << 0) /* clock enable */
/* only limited by clock generator and board design */
#define AU1XI2SC_RATES \
SNDRV_PCM_RATE_CONTINUOUS
#define AU1XI2SC_FMTS \
(SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8 | \
SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | \
SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE | \
SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_U18_3LE | \
SNDRV_PCM_FMTBIT_S18_3BE | SNDRV_PCM_FMTBIT_U18_3BE | \
SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_U20_3LE | \
SNDRV_PCM_FMTBIT_S20_3BE | SNDRV_PCM_FMTBIT_U20_3BE | \
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | \
SNDRV_PCM_FMTBIT_U24_LE | SNDRV_PCM_FMTBIT_U24_BE | \
0)
static inline unsigned long RD(struct au1xpsc_audio_data *ctx, int reg)
{
return __raw_readl(ctx->mmio + reg);
}
static inline void WR(struct au1xpsc_audio_data *ctx, int reg, unsigned long v)
{
__raw_writel(v, ctx->mmio + reg);
wmb();
}
static int au1xi2s_set_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt)
{
struct au1xpsc_audio_data *ctx = snd_soc_dai_get_drvdata(cpu_dai);
unsigned long c;
int ret;
ret = -EINVAL;
c = ctx->cfg;
c &= ~CFG_FM_MASK;
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
c |= CFG_FM_I2S;
break;
case SND_SOC_DAIFMT_MSB:
c |= CFG_FM_RJ;
break;
case SND_SOC_DAIFMT_LSB:
c |= CFG_FM_LJ;
break;
default:
goto out;
}
c &= ~(CFG_IC | CFG_ICK); /* IB-IF */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
c |= CFG_IC | CFG_ICK;
break;
case SND_SOC_DAIFMT_NB_IF:
c |= CFG_IC;
break;
case SND_SOC_DAIFMT_IB_NF:
c |= CFG_ICK;
break;
case SND_SOC_DAIFMT_IB_IF:
break;
default:
goto out;
}
/* I2S controller only supports master */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS: /* CODEC slave */
break;
default:
goto out;
}
ret = 0;
ctx->cfg = c;
out:
return ret;
}
static int au1xi2s_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *ctx = snd_soc_dai_get_drvdata(dai);
int stype = SUBSTREAM_TYPE(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
/* power up */
WR(ctx, I2S_ENABLE, EN_D | EN_CE);
WR(ctx, I2S_ENABLE, EN_CE);
ctx->cfg |= (stype == PCM_TX) ? CFG_TN : CFG_RN;
WR(ctx, I2S_CFG, ctx->cfg);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
ctx->cfg &= ~((stype == PCM_TX) ? CFG_TN : CFG_RN);
WR(ctx, I2S_CFG, ctx->cfg);
WR(ctx, I2S_ENABLE, EN_D); /* power off */
break;
default:
return -EINVAL;
}
return 0;
}
static unsigned long msbits_to_reg(int msbits)
{
switch (msbits) {
case 8:
return CFG_SZ_8;
case 16:
return CFG_SZ_16;
case 18:
return CFG_SZ_18;
case 20:
return CFG_SZ_20;
case 24:
return CFG_SZ_24;
}
return 0;
}
static int au1xi2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *ctx = snd_soc_dai_get_drvdata(dai);
unsigned long v;
v = msbits_to_reg(params->msbits);
if (!v)
return -EINVAL;
ctx->cfg &= ~CFG_SZ_MASK;
ctx->cfg |= v;
return 0;
}
static int au1xi2s_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *ctx = snd_soc_dai_get_drvdata(dai);
snd_soc_dai_set_dma_data(dai, substream, &ctx->dmaids[0]);
return 0;
}
static const struct snd_soc_dai_ops au1xi2s_dai_ops = {
.startup = au1xi2s_startup,
.trigger = au1xi2s_trigger,
.hw_params = au1xi2s_hw_params,
.set_fmt = au1xi2s_set_fmt,
};
static struct snd_soc_dai_driver au1xi2s_dai_driver = {
.symmetric_rates = 1,
.playback = {
.rates = AU1XI2SC_RATES,
.formats = AU1XI2SC_FMTS,
.channels_min = 2,
.channels_max = 2,
},
.capture = {
.rates = AU1XI2SC_RATES,
.formats = AU1XI2SC_FMTS,
.channels_min = 2,
.channels_max = 2,
},
.ops = &au1xi2s_dai_ops,
};
static int __devinit au1xi2s_drvprobe(struct platform_device *pdev)
{
struct resource *iores, *dmares;
struct au1xpsc_audio_data *ctx;
ctx = devm_kzalloc(&pdev->dev, sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
iores = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!iores)
return -ENODEV;
if (!devm_request_mem_region(&pdev->dev, iores->start,
resource_size(iores),
pdev->name))
return -EBUSY;
ctx->mmio = devm_ioremap_nocache(&pdev->dev, iores->start,
resource_size(iores));
if (!ctx->mmio)
return -EBUSY;
dmares = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmares)
return -EBUSY;
ctx->dmaids[SNDRV_PCM_STREAM_PLAYBACK] = dmares->start;
dmares = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (!dmares)
return -EBUSY;
ctx->dmaids[SNDRV_PCM_STREAM_CAPTURE] = dmares->start;
platform_set_drvdata(pdev, ctx);
return snd_soc_register_dai(&pdev->dev, &au1xi2s_dai_driver);
}
static int __devexit au1xi2s_drvremove(struct platform_device *pdev)
{
struct au1xpsc_audio_data *ctx = platform_get_drvdata(pdev);
snd_soc_unregister_dai(&pdev->dev);
WR(ctx, I2S_ENABLE, EN_D); /* clock off, disable */
return 0;
}
#ifdef CONFIG_PM
static int au1xi2s_drvsuspend(struct device *dev)
{
struct au1xpsc_audio_data *ctx = dev_get_drvdata(dev);
WR(ctx, I2S_ENABLE, EN_D); /* clock off, disable */
return 0;
}
static int au1xi2s_drvresume(struct device *dev)
{
return 0;
}
static const struct dev_pm_ops au1xi2sc_pmops = {
.suspend = au1xi2s_drvsuspend,
.resume = au1xi2s_drvresume,
};
#define AU1XI2SC_PMOPS (&au1xi2sc_pmops)
#else
#define AU1XI2SC_PMOPS NULL
#endif
static struct platform_driver au1xi2s_driver = {
.driver = {
.name = "alchemy-i2sc",
.owner = THIS_MODULE,
.pm = AU1XI2SC_PMOPS,
},
.probe = au1xi2s_drvprobe,
.remove = __devexit_p(au1xi2s_drvremove),
};
module_platform_driver(au1xi2s_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Au1000/1500/1100 I2S ASoC driver");
MODULE_AUTHOR("Manuel Lauss");
| gpl-2.0 |
zparallax/amplitude_kernel_tw | sound/pci/asihpi/hpioctl.c | 5076 | 12505 | /*******************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation;
This program is distributed in the hope that it will be useful,
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
Common Linux HPI ioctl and module probe/remove functions
*******************************************************************************/
#define SOURCEFILE_NAME "hpioctl.c"
#include "hpi_internal.h"
#include "hpi_version.h"
#include "hpimsginit.h"
#include "hpidebug.h"
#include "hpimsgx.h"
#include "hpioctl.h"
#include "hpicmn.h"
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
#include <asm/uaccess.h>
#include <linux/pci.h>
#include <linux/stringify.h>
#include <linux/module.h>
#ifdef MODULE_FIRMWARE
MODULE_FIRMWARE("asihpi/dsp5000.bin");
MODULE_FIRMWARE("asihpi/dsp6200.bin");
MODULE_FIRMWARE("asihpi/dsp6205.bin");
MODULE_FIRMWARE("asihpi/dsp6400.bin");
MODULE_FIRMWARE("asihpi/dsp6600.bin");
MODULE_FIRMWARE("asihpi/dsp8700.bin");
MODULE_FIRMWARE("asihpi/dsp8900.bin");
#endif
static int prealloc_stream_buf;
module_param(prealloc_stream_buf, int, S_IRUGO);
MODULE_PARM_DESC(prealloc_stream_buf,
"Preallocate size for per-adapter stream buffer");
/* Allow the debug level to be changed after module load.
E.g. echo 2 > /sys/module/asihpi/parameters/hpiDebugLevel
*/
module_param(hpi_debug_level, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(hpi_debug_level, "debug verbosity 0..5");
/* List of adapters found */
static struct hpi_adapter adapters[HPI_MAX_ADAPTERS];
/* Wrapper function to HPI_Message to enable dumping of the
message and response types.
*/
static void hpi_send_recv_f(struct hpi_message *phm, struct hpi_response *phr,
struct file *file)
{
if ((phm->adapter_index >= HPI_MAX_ADAPTERS)
&& (phm->object != HPI_OBJ_SUBSYSTEM))
phr->error = HPI_ERROR_INVALID_OBJ_INDEX;
else
hpi_send_recv_ex(phm, phr, file);
}
/* This is called from hpifunc.c functions, called by ALSA
* (or other kernel process) In this case there is no file descriptor
* available for the message cache code
*/
void hpi_send_recv(struct hpi_message *phm, struct hpi_response *phr)
{
hpi_send_recv_f(phm, phr, HOWNER_KERNEL);
}
EXPORT_SYMBOL(hpi_send_recv);
/* for radio-asihpi */
int asihpi_hpi_release(struct file *file)
{
struct hpi_message hm;
struct hpi_response hr;
/* HPI_DEBUG_LOG(INFO,"hpi_release file %p, pid %d\n", file, current->pid); */
/* close the subsystem just in case the application forgot to. */
hpi_init_message_response(&hm, &hr, HPI_OBJ_SUBSYSTEM,
HPI_SUBSYS_CLOSE);
hpi_send_recv_ex(&hm, &hr, file);
return 0;
}
long asihpi_hpi_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct hpi_ioctl_linux __user *phpi_ioctl_data;
void __user *puhm;
void __user *puhr;
union hpi_message_buffer_v1 *hm;
union hpi_response_buffer_v1 *hr;
u16 res_max_size;
u32 uncopied_bytes;
int err = 0;
if (cmd != HPI_IOCTL_LINUX)
return -EINVAL;
hm = kmalloc(sizeof(*hm), GFP_KERNEL);
hr = kmalloc(sizeof(*hr), GFP_KERNEL);
if (!hm || !hr) {
err = -ENOMEM;
goto out;
}
phpi_ioctl_data = (struct hpi_ioctl_linux __user *)arg;
/* Read the message and response pointers from user space. */
if (get_user(puhm, &phpi_ioctl_data->phm)
|| get_user(puhr, &phpi_ioctl_data->phr)) {
err = -EFAULT;
goto out;
}
/* Now read the message size and data from user space. */
if (get_user(hm->h.size, (u16 __user *)puhm)) {
err = -EFAULT;
goto out;
}
if (hm->h.size > sizeof(*hm))
hm->h.size = sizeof(*hm);
/* printk(KERN_INFO "message size %d\n", hm->h.wSize); */
uncopied_bytes = copy_from_user(hm, puhm, hm->h.size);
if (uncopied_bytes) {
HPI_DEBUG_LOG(ERROR, "uncopied bytes %d\n", uncopied_bytes);
err = -EFAULT;
goto out;
}
if (get_user(res_max_size, (u16 __user *)puhr)) {
err = -EFAULT;
goto out;
}
/* printk(KERN_INFO "user response size %d\n", res_max_size); */
if (res_max_size < sizeof(struct hpi_response_header)) {
HPI_DEBUG_LOG(WARNING, "small res size %d\n", res_max_size);
err = -EFAULT;
goto out;
}
switch (hm->h.function) {
case HPI_SUBSYS_CREATE_ADAPTER:
case HPI_ADAPTER_DELETE:
/* Application must not use these functions! */
hr->h.size = sizeof(hr->h);
hr->h.error = HPI_ERROR_INVALID_OPERATION;
hr->h.function = hm->h.function;
uncopied_bytes = copy_to_user(puhr, hr, hr->h.size);
if (uncopied_bytes)
err = -EFAULT;
else
err = 0;
goto out;
}
hr->h.size = res_max_size;
if (hm->h.object == HPI_OBJ_SUBSYSTEM) {
hpi_send_recv_f(&hm->m0, &hr->r0, file);
} else {
u16 __user *ptr = NULL;
u32 size = 0;
/* -1=no data 0=read from user mem, 1=write to user mem */
int wrflag = -1;
struct hpi_adapter *pa = NULL;
if (hm->h.adapter_index < ARRAY_SIZE(adapters))
pa = &adapters[hm->h.adapter_index];
if (!pa || !pa->adapter || !pa->adapter->type) {
hpi_init_response(&hr->r0, hm->h.object,
hm->h.function, HPI_ERROR_BAD_ADAPTER_NUMBER);
uncopied_bytes =
copy_to_user(puhr, hr, sizeof(hr->h));
if (uncopied_bytes)
err = -EFAULT;
else
err = 0;
goto out;
}
if (mutex_lock_interruptible(&pa->mutex)) {
err = -EINTR;
goto out;
}
/* Dig out any pointers embedded in the message. */
switch (hm->h.function) {
case HPI_OSTREAM_WRITE:
case HPI_ISTREAM_READ:{
/* Yes, sparse, this is correct. */
ptr = (u16 __user *)hm->m0.u.d.u.data.pb_data;
size = hm->m0.u.d.u.data.data_size;
/* Allocate buffer according to application request.
?Is it better to alloc/free for the duration
of the transaction?
*/
if (pa->buffer_size < size) {
HPI_DEBUG_LOG(DEBUG,
"Realloc adapter %d stream "
"buffer from %zd to %d\n",
hm->h.adapter_index,
pa->buffer_size, size);
if (pa->p_buffer) {
pa->buffer_size = 0;
vfree(pa->p_buffer);
}
pa->p_buffer = vmalloc(size);
if (pa->p_buffer)
pa->buffer_size = size;
else {
HPI_DEBUG_LOG(ERROR,
"HPI could not allocate "
"stream buffer size %d\n",
size);
mutex_unlock(&pa->mutex);
err = -EINVAL;
goto out;
}
}
hm->m0.u.d.u.data.pb_data = pa->p_buffer;
if (hm->h.function == HPI_ISTREAM_READ)
/* from card, WRITE to user mem */
wrflag = 1;
else
wrflag = 0;
break;
}
default:
size = 0;
break;
}
if (size && (wrflag == 0)) {
uncopied_bytes =
copy_from_user(pa->p_buffer, ptr, size);
if (uncopied_bytes)
HPI_DEBUG_LOG(WARNING,
"Missed %d of %d "
"bytes from user\n", uncopied_bytes,
size);
}
hpi_send_recv_f(&hm->m0, &hr->r0, file);
if (size && (wrflag == 1)) {
uncopied_bytes =
copy_to_user(ptr, pa->p_buffer, size);
if (uncopied_bytes)
HPI_DEBUG_LOG(WARNING,
"Missed %d of %d " "bytes to user\n",
uncopied_bytes, size);
}
mutex_unlock(&pa->mutex);
}
/* on return response size must be set */
/*printk(KERN_INFO "response size %d\n", hr->h.wSize); */
if (!hr->h.size) {
HPI_DEBUG_LOG(ERROR, "response zero size\n");
err = -EFAULT;
goto out;
}
if (hr->h.size > res_max_size) {
HPI_DEBUG_LOG(ERROR, "response too big %d %d\n", hr->h.size,
res_max_size);
hr->h.error = HPI_ERROR_RESPONSE_BUFFER_TOO_SMALL;
hr->h.specific_error = hr->h.size;
hr->h.size = sizeof(hr->h);
}
uncopied_bytes = copy_to_user(puhr, hr, hr->h.size);
if (uncopied_bytes) {
HPI_DEBUG_LOG(ERROR, "uncopied bytes %d\n", uncopied_bytes);
err = -EFAULT;
goto out;
}
out:
kfree(hm);
kfree(hr);
return err;
}
int __devinit asihpi_adapter_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
int idx, nm;
int adapter_index;
unsigned int memlen;
struct hpi_message hm;
struct hpi_response hr;
struct hpi_adapter adapter;
struct hpi_pci pci;
memset(&adapter, 0, sizeof(adapter));
dev_printk(KERN_DEBUG, &pci_dev->dev,
"probe %04x:%04x,%04x:%04x,%04x\n", pci_dev->vendor,
pci_dev->device, pci_dev->subsystem_vendor,
pci_dev->subsystem_device, pci_dev->devfn);
if (pci_enable_device(pci_dev) < 0) {
dev_printk(KERN_ERR, &pci_dev->dev,
"pci_enable_device failed, disabling device\n");
return -EIO;
}
pci_set_master(pci_dev); /* also sets latency timer if < 16 */
hpi_init_message_response(&hm, &hr, HPI_OBJ_SUBSYSTEM,
HPI_SUBSYS_CREATE_ADAPTER);
hpi_init_response(&hr, HPI_OBJ_SUBSYSTEM, HPI_SUBSYS_CREATE_ADAPTER,
HPI_ERROR_PROCESSING_MESSAGE);
hm.adapter_index = HPI_ADAPTER_INDEX_INVALID;
nm = HPI_MAX_ADAPTER_MEM_SPACES;
for (idx = 0; idx < nm; idx++) {
HPI_DEBUG_LOG(INFO, "resource %d %pR\n", idx,
&pci_dev->resource[idx]);
if (pci_resource_flags(pci_dev, idx) & IORESOURCE_MEM) {
memlen = pci_resource_len(pci_dev, idx);
pci.ap_mem_base[idx] =
ioremap(pci_resource_start(pci_dev, idx),
memlen);
if (!pci.ap_mem_base[idx]) {
HPI_DEBUG_LOG(ERROR,
"ioremap failed, aborting\n");
/* unmap previously mapped pci mem space */
goto err;
}
}
}
pci.pci_dev = pci_dev;
hm.u.s.resource.bus_type = HPI_BUS_PCI;
hm.u.s.resource.r.pci = &pci;
/* call CreateAdapterObject on the relevant hpi module */
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
if (hr.error)
goto err;
adapter_index = hr.u.s.adapter_index;
adapter.adapter = hpi_find_adapter(adapter_index);
if (prealloc_stream_buf) {
adapter.p_buffer = vmalloc(prealloc_stream_buf);
if (!adapter.p_buffer) {
HPI_DEBUG_LOG(ERROR,
"HPI could not allocate "
"kernel buffer size %d\n",
prealloc_stream_buf);
goto err;
}
}
hpi_init_message_response(&hm, &hr, HPI_OBJ_ADAPTER,
HPI_ADAPTER_OPEN);
hm.adapter_index = adapter.adapter->index;
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
if (hr.error)
goto err;
/* WARNING can't init mutex in 'adapter'
* and then copy it to adapters[] ?!?!
*/
adapters[adapter_index] = adapter;
mutex_init(&adapters[adapter_index].mutex);
pci_set_drvdata(pci_dev, &adapters[adapter_index]);
dev_printk(KERN_INFO, &pci_dev->dev,
"probe succeeded for ASI%04X HPI index %d\n",
adapter.adapter->type, adapter_index);
return 0;
err:
for (idx = 0; idx < HPI_MAX_ADAPTER_MEM_SPACES; idx++) {
if (pci.ap_mem_base[idx]) {
iounmap(pci.ap_mem_base[idx]);
pci.ap_mem_base[idx] = NULL;
}
}
if (adapter.p_buffer) {
adapter.buffer_size = 0;
vfree(adapter.p_buffer);
}
HPI_DEBUG_LOG(ERROR, "adapter_probe failed\n");
return -ENODEV;
}
void __devexit asihpi_adapter_remove(struct pci_dev *pci_dev)
{
int idx;
struct hpi_message hm;
struct hpi_response hr;
struct hpi_adapter *pa;
struct hpi_pci pci;
pa = pci_get_drvdata(pci_dev);
pci = pa->adapter->pci;
hpi_init_message_response(&hm, &hr, HPI_OBJ_ADAPTER,
HPI_ADAPTER_DELETE);
hm.adapter_index = pa->adapter->index;
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
/* unmap PCI memory space, mapped during device init. */
for (idx = 0; idx < HPI_MAX_ADAPTER_MEM_SPACES; idx++) {
if (pci.ap_mem_base[idx])
iounmap(pci.ap_mem_base[idx]);
}
if (pa->p_buffer)
vfree(pa->p_buffer);
pci_set_drvdata(pci_dev, NULL);
if (1)
dev_printk(KERN_INFO, &pci_dev->dev,
"remove %04x:%04x,%04x:%04x,%04x," " HPI index %d.\n",
pci_dev->vendor, pci_dev->device,
pci_dev->subsystem_vendor, pci_dev->subsystem_device,
pci_dev->devfn, pa->adapter->index);
memset(pa, 0, sizeof(*pa));
}
void __init asihpi_init(void)
{
struct hpi_message hm;
struct hpi_response hr;
memset(adapters, 0, sizeof(adapters));
printk(KERN_INFO "ASIHPI driver " HPI_VER_STRING "\n");
hpi_init_message_response(&hm, &hr, HPI_OBJ_SUBSYSTEM,
HPI_SUBSYS_DRIVER_LOAD);
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
}
void asihpi_exit(void)
{
struct hpi_message hm;
struct hpi_response hr;
hpi_init_message_response(&hm, &hr, HPI_OBJ_SUBSYSTEM,
HPI_SUBSYS_DRIVER_UNLOAD);
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
}
| gpl-2.0 |
basr/Hammerhead | drivers/gpu/drm/gma500/mdfld_output.c | 10452 | 2343 | /*
* Copyright (c) 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicensen
* 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:
* Thomas Eaton <thomas.g.eaton@intel.com>
* Scott Rowe <scott.m.rowe@intel.com>
*/
#include "mdfld_output.h"
#include "mdfld_dsi_dpi.h"
#include "mdfld_dsi_output.h"
#include "tc35876x-dsi-lvds.h"
int mdfld_get_panel_type(struct drm_device *dev, int pipe)
{
struct drm_psb_private *dev_priv = dev->dev_private;
return dev_priv->mdfld_panel_id;
}
static void mdfld_init_panel(struct drm_device *dev, int mipi_pipe,
int p_type)
{
switch (p_type) {
case TPO_VID:
mdfld_dsi_output_init(dev, mipi_pipe, &mdfld_tpo_vid_funcs);
break;
case TC35876X:
tc35876x_init(dev);
mdfld_dsi_output_init(dev, mipi_pipe, &mdfld_tc35876x_funcs);
break;
case TMD_VID:
mdfld_dsi_output_init(dev, mipi_pipe, &mdfld_tmd_vid_funcs);
break;
case HDMI:
/* if (dev_priv->mdfld_hdmi_present)
mdfld_hdmi_init(dev, &dev_priv->mode_dev); */
break;
}
}
int mdfld_output_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
/* FIXME: hardcoded for now */
dev_priv->mdfld_panel_id = TC35876X;
/* MIPI panel 1 */
mdfld_init_panel(dev, 0, dev_priv->mdfld_panel_id);
/* HDMI panel */
mdfld_init_panel(dev, 1, HDMI);
return 0;
}
| gpl-2.0 |
mythos234/AndromedaCANCRO-KK | drivers/pci/hotplug/ibmphp_hpc.c | 10708 | 33511 | /*
* IBM Hot Plug Controller Driver
*
* Written By: Jyoti Shah, IBM Corporation
*
* Copyright (C) 2001-2003 IBM Corp.
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <gregkh@us.ibm.com>
* <jshah@us.ibm.com>
*
*/
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/semaphore.h>
#include <linux/kthread.h>
#include "ibmphp.h"
static int to_debug = 0;
#define debug_polling(fmt, arg...) do { if (to_debug) debug (fmt, arg); } while (0)
//----------------------------------------------------------------------------
// timeout values
//----------------------------------------------------------------------------
#define CMD_COMPLETE_TOUT_SEC 60 // give HPC 60 sec to finish cmd
#define HPC_CTLR_WORKING_TOUT 60 // give HPC 60 sec to finish cmd
#define HPC_GETACCESS_TIMEOUT 60 // seconds
#define POLL_INTERVAL_SEC 2 // poll HPC every 2 seconds
#define POLL_LATCH_CNT 5 // poll latch 5 times, then poll slots
//----------------------------------------------------------------------------
// Winnipeg Architected Register Offsets
//----------------------------------------------------------------------------
#define WPG_I2CMBUFL_OFFSET 0x08 // I2C Message Buffer Low
#define WPG_I2CMOSUP_OFFSET 0x10 // I2C Master Operation Setup Reg
#define WPG_I2CMCNTL_OFFSET 0x20 // I2C Master Control Register
#define WPG_I2CPARM_OFFSET 0x40 // I2C Parameter Register
#define WPG_I2CSTAT_OFFSET 0x70 // I2C Status Register
//----------------------------------------------------------------------------
// Winnipeg Store Type commands (Add this commands to the register offset)
//----------------------------------------------------------------------------
#define WPG_I2C_AND 0x1000 // I2C AND operation
#define WPG_I2C_OR 0x2000 // I2C OR operation
//----------------------------------------------------------------------------
// Command set for I2C Master Operation Setup Register
//----------------------------------------------------------------------------
#define WPG_READATADDR_MASK 0x00010000 // read,bytes,I2C shifted,index
#define WPG_WRITEATADDR_MASK 0x40010000 // write,bytes,I2C shifted,index
#define WPG_READDIRECT_MASK 0x10010000
#define WPG_WRITEDIRECT_MASK 0x60010000
//----------------------------------------------------------------------------
// bit masks for I2C Master Control Register
//----------------------------------------------------------------------------
#define WPG_I2CMCNTL_STARTOP_MASK 0x00000002 // Start the Operation
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
#define WPG_I2C_IOREMAP_SIZE 0x2044 // size of linear address interval
//----------------------------------------------------------------------------
// command index
//----------------------------------------------------------------------------
#define WPG_1ST_SLOT_INDEX 0x01 // index - 1st slot for ctlr
#define WPG_CTLR_INDEX 0x0F // index - ctlr
#define WPG_1ST_EXTSLOT_INDEX 0x10 // index - 1st ext slot for ctlr
#define WPG_1ST_BUS_INDEX 0x1F // index - 1st bus for ctlr
//----------------------------------------------------------------------------
// macro utilities
//----------------------------------------------------------------------------
// if bits 20,22,25,26,27,29,30 are OFF return 1
#define HPC_I2CSTATUS_CHECK(s) ((u8)((s & 0x00000A76) ? 0 : 1))
//----------------------------------------------------------------------------
// global variables
//----------------------------------------------------------------------------
static struct mutex sem_hpcaccess; // lock access to HPC
static struct semaphore semOperations; // lock all operations and
// access to data structures
static struct semaphore sem_exit; // make sure polling thread goes away
static struct task_struct *ibmphp_poll_thread;
//----------------------------------------------------------------------------
// local function prototypes
//----------------------------------------------------------------------------
static u8 i2c_ctrl_read (struct controller *, void __iomem *, u8);
static u8 i2c_ctrl_write (struct controller *, void __iomem *, u8, u8);
static u8 hpc_writecmdtoindex (u8, u8);
static u8 hpc_readcmdtoindex (u8, u8);
static void get_hpc_access (void);
static void free_hpc_access (void);
static int poll_hpc(void *data);
static int process_changeinstatus (struct slot *, struct slot *);
static int process_changeinlatch (u8, u8, struct controller *);
static int hpc_wait_ctlr_notworking (int, struct controller *, void __iomem *, u8 *);
//----------------------------------------------------------------------------
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_initvars
*
* Action: initialize semaphores and variables
*---------------------------------------------------------------------*/
void __init ibmphp_hpc_initvars (void)
{
debug ("%s - Entry\n", __func__);
mutex_init(&sem_hpcaccess);
sema_init(&semOperations, 1);
sema_init(&sem_exit, 0);
to_debug = 0;
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: i2c_ctrl_read
*
* Action: read from HPC over I2C
*
*---------------------------------------------------------------------*/
static u8 i2c_ctrl_read (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index)
{
u8 status;
int i;
void __iomem *wpg_addr; // base addr + offset
unsigned long wpg_data; // data to/from WPG LOHI format
unsigned long ultemp;
unsigned long data; // actual data HILO format
debug_polling ("%s - Entry WPGBbar[%p] index[%x] \n", __func__, WPGBbar, index);
//--------------------------------------------------------------------
// READ - step 1
// read at address, byte length, I2C address (shifted), index
// or read direct, byte length, index
if (ctlr_ptr->ctlr_type == 0x02) {
data = WPG_READATADDR_MASK;
// fill in I2C address
ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr;
ultemp = ultemp >> 1;
data |= (ultemp << 8);
// fill in index
data |= (unsigned long)index;
} else if (ctlr_ptr->ctlr_type == 0x04) {
data = WPG_READDIRECT_MASK;
// fill in index
ultemp = (unsigned long)index;
ultemp = ultemp << 8;
data |= ultemp;
} else {
err ("this controller type is not supported \n");
return HPC_ERROR;
}
wpg_data = swab32 (data); // swap data before writing
wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 2 : clear the message buffer
data = 0x00000000;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 3 : issue start operation, I2C master control bit 30:ON
// 2020 : [20] OR operation at [20] offset 0x20
data = WPG_I2CMCNTL_STARTOP_MASK;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 4 : wait until start operation bit clears
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (!(data & WPG_I2CMCNTL_STARTOP_MASK))
break;
i--;
}
if (i == 0) {
debug ("%s - Error : WPG timeout\n", __func__);
return HPC_ERROR;
}
//--------------------------------------------------------------------
// READ - step 5 : read I2C status register
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (HPC_I2CSTATUS_CHECK (data))
break;
i--;
}
if (i == 0) {
debug ("ctrl_read - Exit Error:I2C timeout\n");
return HPC_ERROR;
}
//--------------------------------------------------------------------
// READ - step 6 : get DATA
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
status = (u8) data;
debug_polling ("%s - Exit index[%x] status[%x]\n", __func__, index, status);
return (status);
}
/*----------------------------------------------------------------------
* Name: i2c_ctrl_write
*
* Action: write to HPC over I2C
*
* Return 0 or error codes
*---------------------------------------------------------------------*/
static u8 i2c_ctrl_write (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index, u8 cmd)
{
u8 rc;
void __iomem *wpg_addr; // base addr + offset
unsigned long wpg_data; // data to/from WPG LOHI format
unsigned long ultemp;
unsigned long data; // actual data HILO format
int i;
debug_polling ("%s - Entry WPGBbar[%p] index[%x] cmd[%x]\n", __func__, WPGBbar, index, cmd);
rc = 0;
//--------------------------------------------------------------------
// WRITE - step 1
// write at address, byte length, I2C address (shifted), index
// or write direct, byte length, index
data = 0x00000000;
if (ctlr_ptr->ctlr_type == 0x02) {
data = WPG_WRITEATADDR_MASK;
// fill in I2C address
ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr;
ultemp = ultemp >> 1;
data |= (ultemp << 8);
// fill in index
data |= (unsigned long)index;
} else if (ctlr_ptr->ctlr_type == 0x04) {
data = WPG_WRITEDIRECT_MASK;
// fill in index
ultemp = (unsigned long)index;
ultemp = ultemp << 8;
data |= ultemp;
} else {
err ("this controller type is not supported \n");
return HPC_ERROR;
}
wpg_data = swab32 (data); // swap data before writing
wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 2 : clear the message buffer
data = 0x00000000 | (unsigned long)cmd;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 3 : issue start operation,I2C master control bit 30:ON
// 2020 : [20] OR operation at [20] offset 0x20
data = WPG_I2CMCNTL_STARTOP_MASK;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 4 : wait until start operation bit clears
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (!(data & WPG_I2CMCNTL_STARTOP_MASK))
break;
i--;
}
if (i == 0) {
debug ("%s - Exit Error:WPG timeout\n", __func__);
rc = HPC_ERROR;
}
//--------------------------------------------------------------------
// WRITE - step 5 : read I2C status register
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (HPC_I2CSTATUS_CHECK (data))
break;
i--;
}
if (i == 0) {
debug ("ctrl_read - Error : I2C timeout\n");
rc = HPC_ERROR;
}
debug_polling ("%s Exit rc[%x]\n", __func__, rc);
return (rc);
}
//------------------------------------------------------------
// Read from ISA type HPC
//------------------------------------------------------------
static u8 isa_ctrl_read (struct controller *ctlr_ptr, u8 offset)
{
u16 start_address;
u16 end_address;
u8 data;
start_address = ctlr_ptr->u.isa_ctlr.io_start;
end_address = ctlr_ptr->u.isa_ctlr.io_end;
data = inb (start_address + offset);
return data;
}
//--------------------------------------------------------------
// Write to ISA type HPC
//--------------------------------------------------------------
static void isa_ctrl_write (struct controller *ctlr_ptr, u8 offset, u8 data)
{
u16 start_address;
u16 port_address;
start_address = ctlr_ptr->u.isa_ctlr.io_start;
port_address = start_address + (u16) offset;
outb (data, port_address);
}
static u8 pci_ctrl_read (struct controller *ctrl, u8 offset)
{
u8 data = 0x00;
debug ("inside pci_ctrl_read\n");
if (ctrl->ctrl_dev)
pci_read_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, &data);
return data;
}
static u8 pci_ctrl_write (struct controller *ctrl, u8 offset, u8 data)
{
u8 rc = -ENODEV;
debug ("inside pci_ctrl_write\n");
if (ctrl->ctrl_dev) {
pci_write_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, data);
rc = 0;
}
return rc;
}
static u8 ctrl_read (struct controller *ctlr, void __iomem *base, u8 offset)
{
u8 rc;
switch (ctlr->ctlr_type) {
case 0:
rc = isa_ctrl_read (ctlr, offset);
break;
case 1:
rc = pci_ctrl_read (ctlr, offset);
break;
case 2:
case 4:
rc = i2c_ctrl_read (ctlr, base, offset);
break;
default:
return -ENODEV;
}
return rc;
}
static u8 ctrl_write (struct controller *ctlr, void __iomem *base, u8 offset, u8 data)
{
u8 rc = 0;
switch (ctlr->ctlr_type) {
case 0:
isa_ctrl_write(ctlr, offset, data);
break;
case 1:
rc = pci_ctrl_write (ctlr, offset, data);
break;
case 2:
case 4:
rc = i2c_ctrl_write(ctlr, base, offset, data);
break;
default:
return -ENODEV;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: hpc_writecmdtoindex()
*
* Action: convert a write command to proper index within a controller
*
* Return index, HPC_ERROR
*---------------------------------------------------------------------*/
static u8 hpc_writecmdtoindex (u8 cmd, u8 index)
{
u8 rc;
switch (cmd) {
case HPC_CTLR_ENABLEIRQ: // 0x00.N.15
case HPC_CTLR_CLEARIRQ: // 0x06.N.15
case HPC_CTLR_RESET: // 0x07.N.15
case HPC_CTLR_IRQSTEER: // 0x08.N.15
case HPC_CTLR_DISABLEIRQ: // 0x01.N.15
case HPC_ALLSLOT_ON: // 0x11.N.15
case HPC_ALLSLOT_OFF: // 0x12.N.15
rc = 0x0F;
break;
case HPC_SLOT_OFF: // 0x02.Y.0-14
case HPC_SLOT_ON: // 0x03.Y.0-14
case HPC_SLOT_ATTNOFF: // 0x04.N.0-14
case HPC_SLOT_ATTNON: // 0x05.N.0-14
case HPC_SLOT_BLINKLED: // 0x13.N.0-14
rc = index;
break;
case HPC_BUS_33CONVMODE:
case HPC_BUS_66CONVMODE:
case HPC_BUS_66PCIXMODE:
case HPC_BUS_100PCIXMODE:
case HPC_BUS_133PCIXMODE:
rc = index + WPG_1ST_BUS_INDEX - 1;
break;
default:
err ("hpc_writecmdtoindex - Error invalid cmd[%x]\n", cmd);
rc = HPC_ERROR;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: hpc_readcmdtoindex()
*
* Action: convert a read command to proper index within a controller
*
* Return index, HPC_ERROR
*---------------------------------------------------------------------*/
static u8 hpc_readcmdtoindex (u8 cmd, u8 index)
{
u8 rc;
switch (cmd) {
case READ_CTLRSTATUS:
rc = 0x0F;
break;
case READ_SLOTSTATUS:
case READ_ALLSTAT:
rc = index;
break;
case READ_EXTSLOTSTATUS:
rc = index + WPG_1ST_EXTSLOT_INDEX;
break;
case READ_BUSSTATUS:
rc = index + WPG_1ST_BUS_INDEX - 1;
break;
case READ_SLOTLATCHLOWREG:
rc = 0x28;
break;
case READ_REVLEVEL:
rc = 0x25;
break;
case READ_HPCOPTIONS:
rc = 0x27;
break;
default:
rc = HPC_ERROR;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: HPCreadslot()
*
* Action: issue a READ command to HPC
*
* Input: pslot - cannot be NULL for READ_ALLSTAT
* pstatus - can be NULL for READ_ALLSTAT
*
* Return 0 or error codes
*---------------------------------------------------------------------*/
int ibmphp_hpc_readslot (struct slot * pslot, u8 cmd, u8 * pstatus)
{
void __iomem *wpg_bbar = NULL;
struct controller *ctlr_ptr;
struct list_head *pslotlist;
u8 index, status;
int rc = 0;
int busindex;
debug_polling ("%s - Entry pslot[%p] cmd[%x] pstatus[%p]\n", __func__, pslot, cmd, pstatus);
if ((pslot == NULL)
|| ((pstatus == NULL) && (cmd != READ_ALLSTAT) && (cmd != READ_BUSSTATUS))) {
rc = -EINVAL;
err ("%s - Error invalid pointer, rc[%d]\n", __func__, rc);
return rc;
}
if (cmd == READ_BUSSTATUS) {
busindex = ibmphp_get_bus_index (pslot->bus);
if (busindex < 0) {
rc = -EINVAL;
err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc);
return rc;
} else
index = (u8) busindex;
} else
index = pslot->ctlr_index;
index = hpc_readcmdtoindex (cmd, index);
if (index == HPC_ERROR) {
rc = -EINVAL;
err ("%s - Exit Error:invalid index, rc[%d]\n", __func__, rc);
return rc;
}
ctlr_ptr = pslot->ctrl;
get_hpc_access ();
//--------------------------------------------------------------------
// map physical address to logical address
//--------------------------------------------------------------------
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE);
//--------------------------------------------------------------------
// check controller status before reading
//--------------------------------------------------------------------
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status);
if (!rc) {
switch (cmd) {
case READ_ALLSTAT:
// update the slot structure
pslot->ctrl->status = status;
pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index);
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar,
&status);
if (!rc)
pslot->ext_status = ctrl_read (ctlr_ptr, wpg_bbar, index + WPG_1ST_EXTSLOT_INDEX);
break;
case READ_SLOTSTATUS:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_EXTSLOTSTATUS:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_CTLRSTATUS:
// DO NOT update the slot structure
*pstatus = status;
break;
case READ_BUSSTATUS:
pslot->busstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_REVLEVEL:
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_HPCOPTIONS:
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_SLOTLATCHLOWREG:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
// Not used
case READ_ALLSLOT:
list_for_each (pslotlist, &ibmphp_slot_head) {
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
index = pslot->ctlr_index;
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr,
wpg_bbar, &status);
if (!rc) {
pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index);
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT,
ctlr_ptr, wpg_bbar, &status);
if (!rc)
pslot->ext_status =
ctrl_read (ctlr_ptr, wpg_bbar,
index + WPG_1ST_EXTSLOT_INDEX);
} else {
err ("%s - Error ctrl_read failed\n", __func__);
rc = -EINVAL;
break;
}
}
break;
default:
rc = -EINVAL;
break;
}
}
//--------------------------------------------------------------------
// cleanup
//--------------------------------------------------------------------
// remove physical to logical address mapping
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
iounmap (wpg_bbar);
free_hpc_access ();
debug_polling ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_writeslot()
*
* Action: issue a WRITE command to HPC
*---------------------------------------------------------------------*/
int ibmphp_hpc_writeslot (struct slot * pslot, u8 cmd)
{
void __iomem *wpg_bbar = NULL;
struct controller *ctlr_ptr;
u8 index, status;
int busindex;
u8 done;
int rc = 0;
int timeout;
debug_polling ("%s - Entry pslot[%p] cmd[%x]\n", __func__, pslot, cmd);
if (pslot == NULL) {
rc = -EINVAL;
err ("%s - Error Exit rc[%d]\n", __func__, rc);
return rc;
}
if ((cmd == HPC_BUS_33CONVMODE) || (cmd == HPC_BUS_66CONVMODE) ||
(cmd == HPC_BUS_66PCIXMODE) || (cmd == HPC_BUS_100PCIXMODE) ||
(cmd == HPC_BUS_133PCIXMODE)) {
busindex = ibmphp_get_bus_index (pslot->bus);
if (busindex < 0) {
rc = -EINVAL;
err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc);
return rc;
} else
index = (u8) busindex;
} else
index = pslot->ctlr_index;
index = hpc_writecmdtoindex (cmd, index);
if (index == HPC_ERROR) {
rc = -EINVAL;
err ("%s - Error Exit rc[%d]\n", __func__, rc);
return rc;
}
ctlr_ptr = pslot->ctrl;
get_hpc_access ();
//--------------------------------------------------------------------
// map physical address to logical address
//--------------------------------------------------------------------
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) {
wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE);
debug ("%s - ctlr id[%x] physical[%lx] logical[%lx] i2c[%x]\n", __func__,
ctlr_ptr->ctlr_id, (ulong) (ctlr_ptr->u.wpeg_ctlr.wpegbbar), (ulong) wpg_bbar,
ctlr_ptr->u.wpeg_ctlr.i2c_addr);
}
//--------------------------------------------------------------------
// check controller status before writing
//--------------------------------------------------------------------
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status);
if (!rc) {
ctrl_write (ctlr_ptr, wpg_bbar, index, cmd);
//--------------------------------------------------------------------
// check controller is still not working on the command
//--------------------------------------------------------------------
timeout = CMD_COMPLETE_TOUT_SEC;
done = 0;
while (!done) {
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar,
&status);
if (!rc) {
if (NEEDTOCHECK_CMDSTATUS (cmd)) {
if (CTLR_FINISHED (status) == HPC_CTLR_FINISHED_YES)
done = 1;
} else
done = 1;
}
if (!done) {
msleep(1000);
if (timeout < 1) {
done = 1;
err ("%s - Error command complete timeout\n", __func__);
rc = -EFAULT;
} else
timeout--;
}
}
ctlr_ptr->status = status;
}
// cleanup
// remove physical to logical address mapping
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
iounmap (wpg_bbar);
free_hpc_access ();
debug_polling ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: get_hpc_access()
*
* Action: make sure only one process can access HPC at one time
*---------------------------------------------------------------------*/
static void get_hpc_access (void)
{
mutex_lock(&sem_hpcaccess);
}
/*----------------------------------------------------------------------
* Name: free_hpc_access()
*---------------------------------------------------------------------*/
void free_hpc_access (void)
{
mutex_unlock(&sem_hpcaccess);
}
/*----------------------------------------------------------------------
* Name: ibmphp_lock_operations()
*
* Action: make sure only one process can change the data structure
*---------------------------------------------------------------------*/
void ibmphp_lock_operations (void)
{
down (&semOperations);
to_debug = 1;
}
/*----------------------------------------------------------------------
* Name: ibmphp_unlock_operations()
*---------------------------------------------------------------------*/
void ibmphp_unlock_operations (void)
{
debug ("%s - Entry\n", __func__);
up (&semOperations);
to_debug = 0;
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: poll_hpc()
*---------------------------------------------------------------------*/
#define POLL_LATCH_REGISTER 0
#define POLL_SLOTS 1
#define POLL_SLEEP 2
static int poll_hpc(void *data)
{
struct slot myslot;
struct slot *pslot = NULL;
struct list_head *pslotlist;
int rc;
int poll_state = POLL_LATCH_REGISTER;
u8 oldlatchlow = 0x00;
u8 curlatchlow = 0x00;
int poll_count = 0;
u8 ctrl_count = 0x00;
debug ("%s - Entry\n", __func__);
while (!kthread_should_stop()) {
/* try to get the lock to do some kind of hardware access */
down (&semOperations);
switch (poll_state) {
case POLL_LATCH_REGISTER:
oldlatchlow = curlatchlow;
ctrl_count = 0x00;
list_for_each (pslotlist, &ibmphp_slot_head) {
if (ctrl_count >= ibmphp_get_total_controllers())
break;
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
if (pslot->ctrl->ctlr_relative_id == ctrl_count) {
ctrl_count++;
if (READ_SLOT_LATCH (pslot->ctrl)) {
rc = ibmphp_hpc_readslot (pslot,
READ_SLOTLATCHLOWREG,
&curlatchlow);
if (oldlatchlow != curlatchlow)
process_changeinlatch (oldlatchlow,
curlatchlow,
pslot->ctrl);
}
}
}
++poll_count;
poll_state = POLL_SLEEP;
break;
case POLL_SLOTS:
list_for_each (pslotlist, &ibmphp_slot_head) {
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
// make a copy of the old status
memcpy ((void *) &myslot, (void *) pslot,
sizeof (struct slot));
rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL);
if ((myslot.status != pslot->status)
|| (myslot.ext_status != pslot->ext_status))
process_changeinstatus (pslot, &myslot);
}
ctrl_count = 0x00;
list_for_each (pslotlist, &ibmphp_slot_head) {
if (ctrl_count >= ibmphp_get_total_controllers())
break;
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
if (pslot->ctrl->ctlr_relative_id == ctrl_count) {
ctrl_count++;
if (READ_SLOT_LATCH (pslot->ctrl))
rc = ibmphp_hpc_readslot (pslot,
READ_SLOTLATCHLOWREG,
&curlatchlow);
}
}
++poll_count;
poll_state = POLL_SLEEP;
break;
case POLL_SLEEP:
/* don't sleep with a lock on the hardware */
up (&semOperations);
msleep(POLL_INTERVAL_SEC * 1000);
if (kthread_should_stop())
goto out_sleep;
down (&semOperations);
if (poll_count >= POLL_LATCH_CNT) {
poll_count = 0;
poll_state = POLL_SLOTS;
} else
poll_state = POLL_LATCH_REGISTER;
break;
}
/* give up the hardware semaphore */
up (&semOperations);
/* sleep for a short time just for good measure */
out_sleep:
msleep(100);
}
up (&sem_exit);
debug ("%s - Exit\n", __func__);
return 0;
}
/*----------------------------------------------------------------------
* Name: process_changeinstatus
*
* Action: compare old and new slot status, process the change in status
*
* Input: pointer to slot struct, old slot struct
*
* Return 0 or error codes
* Value:
*
* Side
* Effects: None.
*
* Notes:
*---------------------------------------------------------------------*/
static int process_changeinstatus (struct slot *pslot, struct slot *poldslot)
{
u8 status;
int rc = 0;
u8 disable = 0;
u8 update = 0;
debug ("process_changeinstatus - Entry pslot[%p], poldslot[%p]\n", pslot, poldslot);
// bit 0 - HPC_SLOT_POWER
if ((pslot->status & 0x01) != (poldslot->status & 0x01))
update = 1;
// bit 1 - HPC_SLOT_CONNECT
// ignore
// bit 2 - HPC_SLOT_ATTN
if ((pslot->status & 0x04) != (poldslot->status & 0x04))
update = 1;
// bit 3 - HPC_SLOT_PRSNT2
// bit 4 - HPC_SLOT_PRSNT1
if (((pslot->status & 0x08) != (poldslot->status & 0x08))
|| ((pslot->status & 0x10) != (poldslot->status & 0x10)))
update = 1;
// bit 5 - HPC_SLOT_PWRGD
if ((pslot->status & 0x20) != (poldslot->status & 0x20))
// OFF -> ON: ignore, ON -> OFF: disable slot
if ((poldslot->status & 0x20) && (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status)))
disable = 1;
// bit 6 - HPC_SLOT_BUS_SPEED
// ignore
// bit 7 - HPC_SLOT_LATCH
if ((pslot->status & 0x80) != (poldslot->status & 0x80)) {
update = 1;
// OPEN -> CLOSE
if (pslot->status & 0x80) {
if (SLOT_PWRGD (pslot->status)) {
// power goes on and off after closing latch
// check again to make sure power is still ON
msleep(1000);
rc = ibmphp_hpc_readslot (pslot, READ_SLOTSTATUS, &status);
if (SLOT_PWRGD (status))
update = 1;
else // overwrite power in pslot to OFF
pslot->status &= ~HPC_SLOT_POWER;
}
}
// CLOSE -> OPEN
else if ((SLOT_PWRGD (poldslot->status) == HPC_SLOT_PWRGD_GOOD)
&& (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status))) {
disable = 1;
}
// else - ignore
}
// bit 4 - HPC_SLOT_BLINK_ATTN
if ((pslot->ext_status & 0x08) != (poldslot->ext_status & 0x08))
update = 1;
if (disable) {
debug ("process_changeinstatus - disable slot\n");
pslot->flag = 0;
rc = ibmphp_do_disable_slot (pslot);
}
if (update || disable) {
ibmphp_update_slot_info (pslot);
}
debug ("%s - Exit rc[%d] disable[%x] update[%x]\n", __func__, rc, disable, update);
return rc;
}
/*----------------------------------------------------------------------
* Name: process_changeinlatch
*
* Action: compare old and new latch reg status, process the change
*
* Input: old and current latch register status
*
* Return 0 or error codes
* Value:
*---------------------------------------------------------------------*/
static int process_changeinlatch (u8 old, u8 new, struct controller *ctrl)
{
struct slot myslot, *pslot;
u8 i;
u8 mask;
int rc = 0;
debug ("%s - Entry old[%x], new[%x]\n", __func__, old, new);
// bit 0 reserved, 0 is LSB, check bit 1-6 for 6 slots
for (i = ctrl->starting_slot_num; i <= ctrl->ending_slot_num; i++) {
mask = 0x01 << i;
if ((mask & old) != (mask & new)) {
pslot = ibmphp_get_slot_from_physical_num (i);
if (pslot) {
memcpy ((void *) &myslot, (void *) pslot, sizeof (struct slot));
rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL);
debug ("%s - call process_changeinstatus for slot[%d]\n", __func__, i);
process_changeinstatus (pslot, &myslot);
} else {
rc = -EINVAL;
err ("%s - Error bad pointer for slot[%d]\n", __func__, i);
}
}
}
debug ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_start_poll_thread
*
* Action: start polling thread
*---------------------------------------------------------------------*/
int __init ibmphp_hpc_start_poll_thread (void)
{
debug ("%s - Entry\n", __func__);
ibmphp_poll_thread = kthread_run(poll_hpc, NULL, "hpc_poll");
if (IS_ERR(ibmphp_poll_thread)) {
err ("%s - Error, thread not started\n", __func__);
return PTR_ERR(ibmphp_poll_thread);
}
return 0;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_stop_poll_thread
*
* Action: stop polling thread and cleanup
*---------------------------------------------------------------------*/
void __exit ibmphp_hpc_stop_poll_thread (void)
{
debug ("%s - Entry\n", __func__);
kthread_stop(ibmphp_poll_thread);
debug ("before locking operations \n");
ibmphp_lock_operations ();
debug ("after locking operations \n");
// wait for poll thread to exit
debug ("before sem_exit down \n");
down (&sem_exit);
debug ("after sem_exit down \n");
// cleanup
debug ("before free_hpc_access \n");
free_hpc_access ();
debug ("after free_hpc_access \n");
ibmphp_unlock_operations ();
debug ("after unlock operations \n");
up (&sem_exit);
debug ("after sem exit up\n");
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: hpc_wait_ctlr_notworking
*
* Action: wait until the controller is in a not working state
*
* Return 0, HPC_ERROR
* Value:
*---------------------------------------------------------------------*/
static int hpc_wait_ctlr_notworking (int timeout, struct controller *ctlr_ptr, void __iomem *wpg_bbar,
u8 * pstatus)
{
int rc = 0;
u8 done = 0;
debug_polling ("hpc_wait_ctlr_notworking - Entry timeout[%d]\n", timeout);
while (!done) {
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, WPG_CTLR_INDEX);
if (*pstatus == HPC_ERROR) {
rc = HPC_ERROR;
done = 1;
}
if (CTLR_WORKING (*pstatus) == HPC_CTLR_WORKING_NO)
done = 1;
if (!done) {
msleep(1000);
if (timeout < 1) {
done = 1;
err ("HPCreadslot - Error ctlr timeout\n");
rc = HPC_ERROR;
} else
timeout--;
}
}
debug_polling ("hpc_wait_ctlr_notworking - Exit rc[%x] status[%x]\n", rc, *pstatus);
return rc;
}
| gpl-2.0 |
Cheshkin/sprout_cm11_mt6589_kernel | arch/parisc/lib/checksum.c | 13524 | 3607 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* MIPS specific IP/TCP/UDP checksumming routines
*
* Authors: Ralf Baechle, <ralf@waldorf-gmbh.de>
* Lots of code moved from tcp.c and ip.c; see those files
* for more names.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <net/checksum.h>
#include <asm/byteorder.h>
#include <asm/string.h>
#include <asm/uaccess.h>
#define addc(_t,_r) \
__asm__ __volatile__ ( \
" add %0, %1, %0\n" \
" addc %0, %%r0, %0\n" \
: "=r"(_t) \
: "r"(_r), "0"(_t));
static inline unsigned short from32to16(unsigned int x)
{
/* 32 bits --> 16 bits + carry */
x = (x & 0xffff) + (x >> 16);
/* 16 bits + carry --> 16 bits including carry */
x = (x & 0xffff) + (x >> 16);
return (unsigned short)x;
}
static inline unsigned int do_csum(const unsigned char * buff, int len)
{
int odd, count;
unsigned int result = 0;
if (len <= 0)
goto out;
odd = 1 & (unsigned long) buff;
if (odd) {
result = be16_to_cpu(*buff);
len--;
buff++;
}
count = len >> 1; /* nr of 16-bit words.. */
if (count) {
if (2 & (unsigned long) buff) {
result += *(unsigned short *) buff;
count--;
len -= 2;
buff += 2;
}
count >>= 1; /* nr of 32-bit words.. */
if (count) {
while (count >= 4) {
unsigned int r1, r2, r3, r4;
r1 = *(unsigned int *)(buff + 0);
r2 = *(unsigned int *)(buff + 4);
r3 = *(unsigned int *)(buff + 8);
r4 = *(unsigned int *)(buff + 12);
addc(result, r1);
addc(result, r2);
addc(result, r3);
addc(result, r4);
count -= 4;
buff += 16;
}
while (count) {
unsigned int w = *(unsigned int *) buff;
count--;
buff += 4;
addc(result, w);
}
result = (result & 0xffff) + (result >> 16);
}
if (len & 2) {
result += *(unsigned short *) buff;
buff += 2;
}
}
if (len & 1)
result += le16_to_cpu(*buff);
result = from32to16(result);
if (odd)
result = swab16(result);
out:
return result;
}
/*
* computes a partial checksum, e.g. for TCP/UDP fragments
*/
/*
* why bother folding?
*/
__wsum csum_partial(const void *buff, int len, __wsum sum)
{
unsigned int result = do_csum(buff, len);
addc(result, sum);
return (__force __wsum)from32to16(result);
}
EXPORT_SYMBOL(csum_partial);
/*
* copy while checksumming, otherwise like csum_partial
*/
__wsum csum_partial_copy_nocheck(const void *src, void *dst,
int len, __wsum sum)
{
/*
* It's 2:30 am and I don't feel like doing it real ...
* This is lots slower than the real thing (tm)
*/
sum = csum_partial(src, len, sum);
memcpy(dst, src, len);
return sum;
}
EXPORT_SYMBOL(csum_partial_copy_nocheck);
/*
* Copy from userspace and compute checksum. If we catch an exception
* then zero the rest of the buffer.
*/
__wsum csum_partial_copy_from_user(const void __user *src,
void *dst, int len,
__wsum sum, int *err_ptr)
{
int missing;
missing = copy_from_user(dst, src, len);
if (missing) {
memset(dst + len - missing, 0, missing);
*err_ptr = -EFAULT;
}
return csum_partial(dst, len, sum);
}
EXPORT_SYMBOL(csum_partial_copy_from_user);
| gpl-2.0 |
percy215/common | arch/powerpc/boot/simple_alloc.c | 14548 | 3617 | /*
* Implement primitive realloc(3) functionality.
*
* Author: Mark A. Greer <mgreer@mvista.com>
*
* 2006 (c) MontaVista, Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <stddef.h>
#include "types.h"
#include "page.h"
#include "string.h"
#include "ops.h"
#define ENTRY_BEEN_USED 0x01
#define ENTRY_IN_USE 0x02
static struct alloc_info {
unsigned long flags;
unsigned long base;
unsigned long size;
} *alloc_tbl;
static unsigned long tbl_entries;
static unsigned long alloc_min;
static unsigned long next_base;
static unsigned long space_left;
/*
* First time an entry is used, its base and size are set.
* An entry can be freed and re-malloc'd but its base & size don't change.
* Should be smart enough for needs of bootwrapper.
*/
static void *simple_malloc(unsigned long size)
{
unsigned long i;
struct alloc_info *p = alloc_tbl;
if (size == 0)
goto err_out;
size = _ALIGN_UP(size, alloc_min);
for (i=0; i<tbl_entries; i++, p++)
if (!(p->flags & ENTRY_BEEN_USED)) { /* never been used */
if (size <= space_left) {
p->base = next_base;
p->size = size;
p->flags = ENTRY_BEEN_USED | ENTRY_IN_USE;
next_base += size;
space_left -= size;
return (void *)p->base;
}
goto err_out; /* not enough space left */
}
/* reuse an entry keeping same base & size */
else if (!(p->flags & ENTRY_IN_USE) && (size <= p->size)) {
p->flags |= ENTRY_IN_USE;
return (void *)p->base;
}
err_out:
return NULL;
}
static struct alloc_info *simple_find_entry(void *ptr)
{
unsigned long i;
struct alloc_info *p = alloc_tbl;
for (i=0; i<tbl_entries; i++,p++) {
if (!(p->flags & ENTRY_BEEN_USED))
break;
if ((p->flags & ENTRY_IN_USE) &&
(p->base == (unsigned long)ptr))
return p;
}
return NULL;
}
static void simple_free(void *ptr)
{
struct alloc_info *p = simple_find_entry(ptr);
if (p != NULL)
p->flags &= ~ENTRY_IN_USE;
}
/*
* Change size of area pointed to by 'ptr' to 'size'.
* If 'ptr' is NULL, then its a malloc(). If 'size' is 0, then its a free().
* 'ptr' must be NULL or a pointer to a non-freed area previously returned by
* simple_realloc() or simple_malloc().
*/
static void *simple_realloc(void *ptr, unsigned long size)
{
struct alloc_info *p;
void *new;
if (size == 0) {
simple_free(ptr);
return NULL;
}
if (ptr == NULL)
return simple_malloc(size);
p = simple_find_entry(ptr);
if (p == NULL) /* ptr not from simple_malloc/simple_realloc */
return NULL;
if (size <= p->size) /* fits in current block */
return ptr;
new = simple_malloc(size);
memcpy(new, ptr, p->size);
simple_free(ptr);
return new;
}
/*
* Returns addr of first byte after heap so caller can see if it took
* too much space. If so, change args & try again.
*/
void *simple_alloc_init(char *base, unsigned long heap_size,
unsigned long granularity, unsigned long max_allocs)
{
unsigned long heap_base, tbl_size;
heap_size = _ALIGN_UP(heap_size, granularity);
alloc_min = granularity;
tbl_entries = max_allocs;
tbl_size = tbl_entries * sizeof(struct alloc_info);
alloc_tbl = (struct alloc_info *)_ALIGN_UP((unsigned long)base, 8);
memset(alloc_tbl, 0, tbl_size);
heap_base = _ALIGN_UP((unsigned long)alloc_tbl + tbl_size, alloc_min);
next_base = heap_base;
space_left = heap_size;
platform_ops.malloc = simple_malloc;
platform_ops.free = simple_free;
platform_ops.realloc = simple_realloc;
return (void *)(heap_base + heap_size);
}
| gpl-2.0 |
varunfsl/fsl_pamu | arch/mips/loongson/loongson-3/numa.c | 213 | 8237 | /*
* Copyright (C) 2010 Loongson Inc. & Lemote Inc. &
* Insititute of Computing Technology
* Author: Xiang Gao, gaoxiang@ict.ac.cn
* Huacai Chen, chenhc@lemote.com
* Xiaofu Meng, Shuangshuang Zhang
*
* 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/kernel.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/nodemask.h>
#include <linux/swap.h>
#include <linux/memblock.h>
#include <linux/bootmem.h>
#include <linux/pfn.h>
#include <linux/highmem.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/sections.h>
#include <linux/irq.h>
#include <asm/bootinfo.h>
#include <asm/mc146818-time.h>
#include <asm/time.h>
#include <asm/wbflush.h>
#include <boot_param.h>
static struct node_data prealloc__node_data[MAX_NUMNODES];
unsigned char __node_distances[MAX_NUMNODES][MAX_NUMNODES];
EXPORT_SYMBOL(__node_distances);
struct node_data *__node_data[MAX_NUMNODES];
EXPORT_SYMBOL(__node_data);
static void enable_lpa(void)
{
unsigned long value;
value = __read_32bit_c0_register($16, 3);
value |= 0x00000080;
__write_32bit_c0_register($16, 3, value);
value = __read_32bit_c0_register($16, 3);
pr_info("CP0_Config3: CP0 16.3 (0x%lx)\n", value);
value = __read_32bit_c0_register($5, 1);
value |= 0x20000000;
__write_32bit_c0_register($5, 1, value);
value = __read_32bit_c0_register($5, 1);
pr_info("CP0_PageGrain: CP0 5.1 (0x%lx)\n", value);
}
static void cpu_node_probe(void)
{
int i;
nodes_clear(node_possible_map);
nodes_clear(node_online_map);
for (i = 0; i < loongson_sysconf.nr_nodes; i++) {
node_set_state(num_online_nodes(), N_POSSIBLE);
node_set_online(num_online_nodes());
}
pr_info("NUMA: Discovered %d cpus on %d nodes\n",
loongson_sysconf.nr_cpus, num_online_nodes());
}
static int __init compute_node_distance(int row, int col)
{
int package_row = row * loongson_sysconf.cores_per_node /
loongson_sysconf.cores_per_package;
int package_col = col * loongson_sysconf.cores_per_node /
loongson_sysconf.cores_per_package;
if (col == row)
return 0;
else if (package_row == package_col)
return 40;
else
return 100;
}
static void __init init_topology_matrix(void)
{
int row, col;
for (row = 0; row < MAX_NUMNODES; row++)
for (col = 0; col < MAX_NUMNODES; col++)
__node_distances[row][col] = -1;
for_each_online_node(row) {
for_each_online_node(col) {
__node_distances[row][col] =
compute_node_distance(row, col);
}
}
}
static unsigned long nid_to_addroffset(unsigned int nid)
{
unsigned long result;
switch (nid) {
case 0:
default:
result = NODE0_ADDRSPACE_OFFSET;
break;
case 1:
result = NODE1_ADDRSPACE_OFFSET;
break;
case 2:
result = NODE2_ADDRSPACE_OFFSET;
break;
case 3:
result = NODE3_ADDRSPACE_OFFSET;
break;
}
return result;
}
static void __init szmem(unsigned int node)
{
u32 i, mem_type;
static unsigned long num_physpages = 0;
u64 node_id, node_psize, start_pfn, end_pfn, mem_start, mem_size;
/* Parse memory information and activate */
for (i = 0; i < loongson_memmap->nr_map; i++) {
node_id = loongson_memmap->map[i].node_id;
if (node_id != node)
continue;
mem_type = loongson_memmap->map[i].mem_type;
mem_size = loongson_memmap->map[i].mem_size;
mem_start = loongson_memmap->map[i].mem_start;
switch (mem_type) {
case SYSTEM_RAM_LOW:
start_pfn = ((node_id << 44) + mem_start) >> PAGE_SHIFT;
node_psize = (mem_size << 20) >> PAGE_SHIFT;
end_pfn = start_pfn + node_psize;
num_physpages += node_psize;
pr_info("Node%d: mem_type:%d, mem_start:0x%llx, mem_size:0x%llx MB\n",
(u32)node_id, mem_type, mem_start, mem_size);
pr_info(" start_pfn:0x%llx, end_pfn:0x%llx, num_physpages:0x%lx\n",
start_pfn, end_pfn, num_physpages);
add_memory_region((node_id << 44) + mem_start,
(u64)mem_size << 20, BOOT_MEM_RAM);
memblock_add_node(PFN_PHYS(start_pfn),
PFN_PHYS(end_pfn - start_pfn), node);
break;
case SYSTEM_RAM_HIGH:
start_pfn = ((node_id << 44) + mem_start) >> PAGE_SHIFT;
node_psize = (mem_size << 20) >> PAGE_SHIFT;
end_pfn = start_pfn + node_psize;
num_physpages += node_psize;
pr_info("Node%d: mem_type:%d, mem_start:0x%llx, mem_size:0x%llx MB\n",
(u32)node_id, mem_type, mem_start, mem_size);
pr_info(" start_pfn:0x%llx, end_pfn:0x%llx, num_physpages:0x%lx\n",
start_pfn, end_pfn, num_physpages);
add_memory_region((node_id << 44) + mem_start,
(u64)mem_size << 20, BOOT_MEM_RAM);
memblock_add_node(PFN_PHYS(start_pfn),
PFN_PHYS(end_pfn - start_pfn), node);
break;
case MEM_RESERVED:
pr_info("Node%d: mem_type:%d, mem_start:0x%llx, mem_size:0x%llx MB\n",
(u32)node_id, mem_type, mem_start, mem_size);
add_memory_region((node_id << 44) + mem_start,
(u64)mem_size << 20, BOOT_MEM_RESERVED);
memblock_reserve(((node_id << 44) + mem_start),
mem_size << 20);
break;
}
}
}
static void __init node_mem_init(unsigned int node)
{
unsigned long bootmap_size;
unsigned long node_addrspace_offset;
unsigned long start_pfn, end_pfn, freepfn;
node_addrspace_offset = nid_to_addroffset(node);
pr_info("Node%d's addrspace_offset is 0x%lx\n",
node, node_addrspace_offset);
get_pfn_range_for_nid(node, &start_pfn, &end_pfn);
freepfn = start_pfn;
if (node == 0)
freepfn = PFN_UP(__pa_symbol(&_end)); /* kernel end address */
pr_info("Node%d: start_pfn=0x%lx, end_pfn=0x%lx, freepfn=0x%lx\n",
node, start_pfn, end_pfn, freepfn);
__node_data[node] = prealloc__node_data + node;
NODE_DATA(node)->bdata = &bootmem_node_data[node];
NODE_DATA(node)->node_start_pfn = start_pfn;
NODE_DATA(node)->node_spanned_pages = end_pfn - start_pfn;
bootmap_size = init_bootmem_node(NODE_DATA(node), freepfn,
start_pfn, end_pfn);
free_bootmem_with_active_regions(node, end_pfn);
if (node == 0) /* used by finalize_initrd() */
max_low_pfn = end_pfn;
/* This is reserved for the kernel and bdata->node_bootmem_map */
reserve_bootmem_node(NODE_DATA(node), start_pfn << PAGE_SHIFT,
((freepfn - start_pfn) << PAGE_SHIFT) + bootmap_size,
BOOTMEM_DEFAULT);
if (node == 0 && node_end_pfn(0) >= (0xffffffff >> PAGE_SHIFT)) {
/* Reserve 0xff800000~0xffffffff for RS780E integrated GPU */
reserve_bootmem_node(NODE_DATA(node),
(node_addrspace_offset | 0xff800000),
8 << 20, BOOTMEM_DEFAULT);
}
sparse_memory_present_with_active_regions(node);
}
static __init void prom_meminit(void)
{
unsigned int node, cpu, active_cpu = 0;
cpu_node_probe();
init_topology_matrix();
for (node = 0; node < loongson_sysconf.nr_nodes; node++) {
if (node_online(node)) {
szmem(node);
node_mem_init(node);
cpus_clear(__node_data[(node)]->cpumask);
}
}
for (cpu = 0; cpu < loongson_sysconf.nr_cpus; cpu++) {
node = cpu / loongson_sysconf.cores_per_node;
if (node >= num_online_nodes())
node = 0;
if (loongson_sysconf.reserved_cpus_mask & (1<<cpu))
continue;
cpu_set(active_cpu, __node_data[(node)]->cpumask);
pr_info("NUMA: set cpumask cpu %d on node %d\n", active_cpu, node);
active_cpu++;
}
}
void __init paging_init(void)
{
unsigned node;
unsigned long zones_size[MAX_NR_ZONES] = {0, };
pagetable_init();
for_each_online_node(node) {
unsigned long start_pfn, end_pfn;
get_pfn_range_for_nid(node, &start_pfn, &end_pfn);
if (end_pfn > max_low_pfn)
max_low_pfn = end_pfn;
}
#ifdef CONFIG_ZONE_DMA32
zones_size[ZONE_DMA32] = MAX_DMA32_PFN;
#endif
zones_size[ZONE_NORMAL] = max_low_pfn;
free_area_init_nodes(zones_size);
}
void __init mem_init(void)
{
high_memory = (void *) __va(get_num_physpages() << PAGE_SHIFT);
free_all_bootmem();
setup_zero_pages(); /* This comes from node 0 */
mem_init_print_info(NULL);
}
/* All PCI device belongs to logical Node-0 */
int pcibus_to_node(struct pci_bus *bus)
{
return 0;
}
EXPORT_SYMBOL(pcibus_to_node);
void __init prom_init_numa_memory(void)
{
enable_lpa();
prom_meminit();
}
EXPORT_SYMBOL(prom_init_numa_memory);
| gpl-2.0 |
fanyukui/linux3.12.10 | drivers/net/ethernet/chelsio/cxgb4/cxgb4_main.c | 213 | 164736 | /*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2003-2010 Chelsio Communications, 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/bitmap.h>
#include <linux/crc32.h>
#include <linux/ctype.h>
#include <linux/debugfs.h>
#include <linux/err.h>
#include <linux/etherdevice.h>
#include <linux/firmware.h>
#include <linux/if.h>
#include <linux/if_vlan.h>
#include <linux/init.h>
#include <linux/log2.h>
#include <linux/mdio.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/aer.h>
#include <linux/rtnetlink.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/sockios.h>
#include <linux/vmalloc.h>
#include <linux/workqueue.h>
#include <net/neighbour.h>
#include <net/netevent.h>
#include <net/addrconf.h>
#include <asm/uaccess.h>
#include "cxgb4.h"
#include "t4_regs.h"
#include "t4_msg.h"
#include "t4fw_api.h"
#include "l2t.h"
#include <../drivers/net/bonding/bonding.h>
#ifdef DRV_VERSION
#undef DRV_VERSION
#endif
#define DRV_VERSION "2.0.0-ko"
#define DRV_DESC "Chelsio T4/T5 Network Driver"
/*
* Max interrupt hold-off timer value in us. Queues fall back to this value
* under extreme memory pressure so it's largish to give the system time to
* recover.
*/
#define MAX_SGE_TIMERVAL 200U
enum {
/*
* Physical Function provisioning constants.
*/
PFRES_NVI = 4, /* # of Virtual Interfaces */
PFRES_NETHCTRL = 128, /* # of EQs used for ETH or CTRL Qs */
PFRES_NIQFLINT = 128, /* # of ingress Qs/w Free List(s)/intr
*/
PFRES_NEQ = 256, /* # of egress queues */
PFRES_NIQ = 0, /* # of ingress queues */
PFRES_TC = 0, /* PCI-E traffic class */
PFRES_NEXACTF = 128, /* # of exact MPS filters */
PFRES_R_CAPS = FW_CMD_CAP_PF,
PFRES_WX_CAPS = FW_CMD_CAP_PF,
#ifdef CONFIG_PCI_IOV
/*
* Virtual Function provisioning constants. We need two extra Ingress
* Queues with Interrupt capability to serve as the VF's Firmware
* Event Queue and Forwarded Interrupt Queue (when using MSI mode) --
* neither will have Free Lists associated with them). For each
* Ethernet/Control Egress Queue and for each Free List, we need an
* Egress Context.
*/
VFRES_NPORTS = 1, /* # of "ports" per VF */
VFRES_NQSETS = 2, /* # of "Queue Sets" per VF */
VFRES_NVI = VFRES_NPORTS, /* # of Virtual Interfaces */
VFRES_NETHCTRL = VFRES_NQSETS, /* # of EQs used for ETH or CTRL Qs */
VFRES_NIQFLINT = VFRES_NQSETS+2,/* # of ingress Qs/w Free List(s)/intr */
VFRES_NEQ = VFRES_NQSETS*2, /* # of egress queues */
VFRES_NIQ = 0, /* # of non-fl/int ingress queues */
VFRES_TC = 0, /* PCI-E traffic class */
VFRES_NEXACTF = 16, /* # of exact MPS filters */
VFRES_R_CAPS = FW_CMD_CAP_DMAQ|FW_CMD_CAP_VF|FW_CMD_CAP_PORT,
VFRES_WX_CAPS = FW_CMD_CAP_DMAQ|FW_CMD_CAP_VF,
#endif
};
/*
* Provide a Port Access Rights Mask for the specified PF/VF. This is very
* static and likely not to be useful in the long run. We really need to
* implement some form of persistent configuration which the firmware
* controls.
*/
static unsigned int pfvfres_pmask(struct adapter *adapter,
unsigned int pf, unsigned int vf)
{
unsigned int portn, portvec;
/*
* Give PF's access to all of the ports.
*/
if (vf == 0)
return FW_PFVF_CMD_PMASK_MASK;
/*
* For VFs, we'll assign them access to the ports based purely on the
* PF. We assign active ports in order, wrapping around if there are
* fewer active ports than PFs: e.g. active port[pf % nports].
* Unfortunately the adapter's port_info structs haven't been
* initialized yet so we have to compute this.
*/
if (adapter->params.nports == 0)
return 0;
portn = pf % adapter->params.nports;
portvec = adapter->params.portvec;
for (;;) {
/*
* Isolate the lowest set bit in the port vector. If we're at
* the port number that we want, return that as the pmask.
* otherwise mask that bit out of the port vector and
* decrement our port number ...
*/
unsigned int pmask = portvec ^ (portvec & (portvec-1));
if (portn == 0)
return pmask;
portn--;
portvec &= ~pmask;
}
/*NOTREACHED*/
}
enum {
MAX_TXQ_ENTRIES = 16384,
MAX_CTRL_TXQ_ENTRIES = 1024,
MAX_RSPQ_ENTRIES = 16384,
MAX_RX_BUFFERS = 16384,
MIN_TXQ_ENTRIES = 32,
MIN_CTRL_TXQ_ENTRIES = 32,
MIN_RSPQ_ENTRIES = 128,
MIN_FL_ENTRIES = 16
};
/* Host shadow copy of ingress filter entry. This is in host native format
* and doesn't match the ordering or bit order, etc. of the hardware of the
* firmware command. The use of bit-field structure elements is purely to
* remind ourselves of the field size limitations and save memory in the case
* where the filter table is large.
*/
struct filter_entry {
/* Administrative fields for filter.
*/
u32 valid:1; /* filter allocated and valid */
u32 locked:1; /* filter is administratively locked */
u32 pending:1; /* filter action is pending firmware reply */
u32 smtidx:8; /* Source MAC Table index for smac */
struct l2t_entry *l2t; /* Layer Two Table entry for dmac */
/* The filter itself. Most of this is a straight copy of information
* provided by the extended ioctl(). Some fields are translated to
* internal forms -- for instance the Ingress Queue ID passed in from
* the ioctl() is translated into the Absolute Ingress Queue ID.
*/
struct ch_filter_specification fs;
};
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
#define CH_DEVICE(devid, data) { PCI_VDEVICE(CHELSIO, devid), (data) }
static DEFINE_PCI_DEVICE_TABLE(cxgb4_pci_tbl) = {
CH_DEVICE(0xa000, 0), /* PE10K */
CH_DEVICE(0x4001, -1),
CH_DEVICE(0x4002, -1),
CH_DEVICE(0x4003, -1),
CH_DEVICE(0x4004, -1),
CH_DEVICE(0x4005, -1),
CH_DEVICE(0x4006, -1),
CH_DEVICE(0x4007, -1),
CH_DEVICE(0x4008, -1),
CH_DEVICE(0x4009, -1),
CH_DEVICE(0x400a, -1),
CH_DEVICE(0x4401, 4),
CH_DEVICE(0x4402, 4),
CH_DEVICE(0x4403, 4),
CH_DEVICE(0x4404, 4),
CH_DEVICE(0x4405, 4),
CH_DEVICE(0x4406, 4),
CH_DEVICE(0x4407, 4),
CH_DEVICE(0x4408, 4),
CH_DEVICE(0x4409, 4),
CH_DEVICE(0x440a, 4),
CH_DEVICE(0x440d, 4),
CH_DEVICE(0x440e, 4),
CH_DEVICE(0x5001, 4),
CH_DEVICE(0x5002, 4),
CH_DEVICE(0x5003, 4),
CH_DEVICE(0x5004, 4),
CH_DEVICE(0x5005, 4),
CH_DEVICE(0x5006, 4),
CH_DEVICE(0x5007, 4),
CH_DEVICE(0x5008, 4),
CH_DEVICE(0x5009, 4),
CH_DEVICE(0x500A, 4),
CH_DEVICE(0x500B, 4),
CH_DEVICE(0x500C, 4),
CH_DEVICE(0x500D, 4),
CH_DEVICE(0x500E, 4),
CH_DEVICE(0x500F, 4),
CH_DEVICE(0x5010, 4),
CH_DEVICE(0x5011, 4),
CH_DEVICE(0x5012, 4),
CH_DEVICE(0x5013, 4),
CH_DEVICE(0x5401, 4),
CH_DEVICE(0x5402, 4),
CH_DEVICE(0x5403, 4),
CH_DEVICE(0x5404, 4),
CH_DEVICE(0x5405, 4),
CH_DEVICE(0x5406, 4),
CH_DEVICE(0x5407, 4),
CH_DEVICE(0x5408, 4),
CH_DEVICE(0x5409, 4),
CH_DEVICE(0x540A, 4),
CH_DEVICE(0x540B, 4),
CH_DEVICE(0x540C, 4),
CH_DEVICE(0x540D, 4),
CH_DEVICE(0x540E, 4),
CH_DEVICE(0x540F, 4),
CH_DEVICE(0x5410, 4),
CH_DEVICE(0x5411, 4),
CH_DEVICE(0x5412, 4),
CH_DEVICE(0x5413, 4),
{ 0, }
};
#define FW4_FNAME "cxgb4/t4fw.bin"
#define FW5_FNAME "cxgb4/t5fw.bin"
#define FW4_CFNAME "cxgb4/t4-config.txt"
#define FW5_CFNAME "cxgb4/t5-config.txt"
MODULE_DESCRIPTION(DRV_DESC);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, cxgb4_pci_tbl);
MODULE_FIRMWARE(FW4_FNAME);
MODULE_FIRMWARE(FW5_FNAME);
/*
* Normally we're willing to become the firmware's Master PF but will be happy
* if another PF has already become the Master and initialized the adapter.
* Setting "force_init" will cause this driver to forcibly establish itself as
* the Master PF and initialize the adapter.
*/
static uint force_init;
module_param(force_init, uint, 0644);
MODULE_PARM_DESC(force_init, "Forcibly become Master PF and initialize adapter");
/*
* Normally if the firmware we connect to has Configuration File support, we
* use that and only fall back to the old Driver-based initialization if the
* Configuration File fails for some reason. If force_old_init is set, then
* we'll always use the old Driver-based initialization sequence.
*/
static uint force_old_init;
module_param(force_old_init, uint, 0644);
MODULE_PARM_DESC(force_old_init, "Force old initialization sequence");
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0644);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T4 default message enable bitmap");
/*
* The driver uses the best interrupt scheme available on a platform in the
* order MSI-X, MSI, legacy INTx interrupts. This parameter determines which
* of these schemes the driver may consider as follows:
*
* msi = 2: choose from among all three options
* msi = 1: only consider MSI and INTx interrupts
* msi = 0: force INTx interrupts
*/
static int msi = 2;
module_param(msi, int, 0644);
MODULE_PARM_DESC(msi, "whether to use INTx (0), MSI (1) or MSI-X (2)");
/*
* Queue interrupt hold-off timer values. Queues default to the first of these
* upon creation.
*/
static unsigned int intr_holdoff[SGE_NTIMERS - 1] = { 5, 10, 20, 50, 100 };
module_param_array(intr_holdoff, uint, NULL, 0644);
MODULE_PARM_DESC(intr_holdoff, "values for queue interrupt hold-off timers "
"0..4 in microseconds");
static unsigned int intr_cnt[SGE_NCOUNTERS - 1] = { 4, 8, 16 };
module_param_array(intr_cnt, uint, NULL, 0644);
MODULE_PARM_DESC(intr_cnt,
"thresholds 1..3 for queue interrupt packet counters");
/*
* Normally we tell the chip to deliver Ingress Packets into our DMA buffers
* offset by 2 bytes in order to have the IP headers line up on 4-byte
* boundaries. This is a requirement for many architectures which will throw
* a machine check fault if an attempt is made to access one of the 4-byte IP
* header fields on a non-4-byte boundary. And it's a major performance issue
* even on some architectures which allow it like some implementations of the
* x86 ISA. However, some architectures don't mind this and for some very
* edge-case performance sensitive applications (like forwarding large volumes
* of small packets), setting this DMA offset to 0 will decrease the number of
* PCI-E Bus transfers enough to measurably affect performance.
*/
static int rx_dma_offset = 2;
static bool vf_acls;
#ifdef CONFIG_PCI_IOV
module_param(vf_acls, bool, 0644);
MODULE_PARM_DESC(vf_acls, "if set enable virtualization L2 ACL enforcement");
/* Configure the number of PCI-E Virtual Function which are to be instantiated
* on SR-IOV Capable Physical Functions.
*/
static unsigned int num_vf[NUM_OF_PF_WITH_SRIOV];
module_param_array(num_vf, uint, NULL, 0644);
MODULE_PARM_DESC(num_vf, "number of VFs for each of PFs 0-3");
#endif
/*
* The filter TCAM has a fixed portion and a variable portion. The fixed
* portion can match on source/destination IP IPv4/IPv6 addresses and TCP/UDP
* ports. The variable portion is 36 bits which can include things like Exact
* Match MAC Index (9 bits), Ether Type (16 bits), IP Protocol (8 bits),
* [Inner] VLAN Tag (17 bits), etc. which, if all were somehow selected, would
* far exceed the 36-bit budget for this "compressed" header portion of the
* filter. Thus, we have a scarce resource which must be carefully managed.
*
* By default we set this up to mostly match the set of filter matching
* capabilities of T3 but with accommodations for some of T4's more
* interesting features:
*
* { IP Fragment (1), MPS Match Type (3), IP Protocol (8),
* [Inner] VLAN (17), Port (3), FCoE (1) }
*/
enum {
TP_VLAN_PRI_MAP_DEFAULT = HW_TPL_FR_MT_PR_IV_P_FC,
TP_VLAN_PRI_MAP_FIRST = FCOE_SHIFT,
TP_VLAN_PRI_MAP_LAST = FRAGMENTATION_SHIFT,
};
static unsigned int tp_vlan_pri_map = TP_VLAN_PRI_MAP_DEFAULT;
module_param(tp_vlan_pri_map, uint, 0644);
MODULE_PARM_DESC(tp_vlan_pri_map, "global compressed filter configuration");
static struct dentry *cxgb4_debugfs_root;
static LIST_HEAD(adapter_list);
static DEFINE_MUTEX(uld_mutex);
/* Adapter list to be accessed from atomic context */
static LIST_HEAD(adap_rcu_list);
static DEFINE_SPINLOCK(adap_rcu_lock);
static struct cxgb4_uld_info ulds[CXGB4_ULD_MAX];
static const char *uld_str[] = { "RDMA", "iSCSI" };
static void link_report(struct net_device *dev)
{
if (!netif_carrier_ok(dev))
netdev_info(dev, "link down\n");
else {
static const char *fc[] = { "no", "Rx", "Tx", "Tx/Rx" };
const char *s = "10Mbps";
const struct port_info *p = netdev_priv(dev);
switch (p->link_cfg.speed) {
case SPEED_10000:
s = "10Gbps";
break;
case SPEED_1000:
s = "1000Mbps";
break;
case SPEED_100:
s = "100Mbps";
break;
}
netdev_info(dev, "link up, %s, full-duplex, %s PAUSE\n", s,
fc[p->link_cfg.fc]);
}
}
void t4_os_link_changed(struct adapter *adapter, int port_id, int link_stat)
{
struct net_device *dev = adapter->port[port_id];
/* Skip changes from disabled ports. */
if (netif_running(dev) && link_stat != netif_carrier_ok(dev)) {
if (link_stat)
netif_carrier_on(dev);
else
netif_carrier_off(dev);
link_report(dev);
}
}
void t4_os_portmod_changed(const struct adapter *adap, int port_id)
{
static const char *mod_str[] = {
NULL, "LR", "SR", "ER", "passive DA", "active DA", "LRM"
};
const struct net_device *dev = adap->port[port_id];
const struct port_info *pi = netdev_priv(dev);
if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
netdev_info(dev, "port module unplugged\n");
else if (pi->mod_type < ARRAY_SIZE(mod_str))
netdev_info(dev, "%s module inserted\n", mod_str[pi->mod_type]);
}
/*
* Configure the exact and hash address filters to handle a port's multicast
* and secondary unicast MAC addresses.
*/
static int set_addr_filters(const struct net_device *dev, bool sleep)
{
u64 mhash = 0;
u64 uhash = 0;
bool free = true;
u16 filt_idx[7];
const u8 *addr[7];
int ret, naddr = 0;
const struct netdev_hw_addr *ha;
int uc_cnt = netdev_uc_count(dev);
int mc_cnt = netdev_mc_count(dev);
const struct port_info *pi = netdev_priv(dev);
unsigned int mb = pi->adapter->fn;
/* first do the secondary unicast addresses */
netdev_for_each_uc_addr(ha, dev) {
addr[naddr++] = ha->addr;
if (--uc_cnt == 0 || naddr >= ARRAY_SIZE(addr)) {
ret = t4_alloc_mac_filt(pi->adapter, mb, pi->viid, free,
naddr, addr, filt_idx, &uhash, sleep);
if (ret < 0)
return ret;
free = false;
naddr = 0;
}
}
/* next set up the multicast addresses */
netdev_for_each_mc_addr(ha, dev) {
addr[naddr++] = ha->addr;
if (--mc_cnt == 0 || naddr >= ARRAY_SIZE(addr)) {
ret = t4_alloc_mac_filt(pi->adapter, mb, pi->viid, free,
naddr, addr, filt_idx, &mhash, sleep);
if (ret < 0)
return ret;
free = false;
naddr = 0;
}
}
return t4_set_addr_hash(pi->adapter, mb, pi->viid, uhash != 0,
uhash | mhash, sleep);
}
int dbfifo_int_thresh = 10; /* 10 == 640 entry threshold */
module_param(dbfifo_int_thresh, int, 0644);
MODULE_PARM_DESC(dbfifo_int_thresh, "doorbell fifo interrupt threshold");
/*
* usecs to sleep while draining the dbfifo
*/
static int dbfifo_drain_delay = 1000;
module_param(dbfifo_drain_delay, int, 0644);
MODULE_PARM_DESC(dbfifo_drain_delay,
"usecs to sleep while draining the dbfifo");
/*
* Set Rx properties of a port, such as promiscruity, address filters, and MTU.
* If @mtu is -1 it is left unchanged.
*/
static int set_rxmode(struct net_device *dev, int mtu, bool sleep_ok)
{
int ret;
struct port_info *pi = netdev_priv(dev);
ret = set_addr_filters(dev, sleep_ok);
if (ret == 0)
ret = t4_set_rxmode(pi->adapter, pi->adapter->fn, pi->viid, mtu,
(dev->flags & IFF_PROMISC) ? 1 : 0,
(dev->flags & IFF_ALLMULTI) ? 1 : 0, 1, -1,
sleep_ok);
return ret;
}
static struct workqueue_struct *workq;
/**
* link_start - enable a port
* @dev: the port to enable
*
* Performs the MAC and PHY actions needed to enable a port.
*/
static int link_start(struct net_device *dev)
{
int ret;
struct port_info *pi = netdev_priv(dev);
unsigned int mb = pi->adapter->fn;
/*
* We do not set address filters and promiscuity here, the stack does
* that step explicitly.
*/
ret = t4_set_rxmode(pi->adapter, mb, pi->viid, dev->mtu, -1, -1, -1,
!!(dev->features & NETIF_F_HW_VLAN_CTAG_RX), true);
if (ret == 0) {
ret = t4_change_mac(pi->adapter, mb, pi->viid,
pi->xact_addr_filt, dev->dev_addr, true,
true);
if (ret >= 0) {
pi->xact_addr_filt = ret;
ret = 0;
}
}
if (ret == 0)
ret = t4_link_start(pi->adapter, mb, pi->tx_chan,
&pi->link_cfg);
if (ret == 0)
ret = t4_enable_vi(pi->adapter, mb, pi->viid, true, true);
return ret;
}
/* Clear a filter and release any of its resources that we own. This also
* clears the filter's "pending" status.
*/
static void clear_filter(struct adapter *adap, struct filter_entry *f)
{
/* If the new or old filter have loopback rewriteing rules then we'll
* need to free any existing Layer Two Table (L2T) entries of the old
* filter rule. The firmware will handle freeing up any Source MAC
* Table (SMT) entries used for rewriting Source MAC Addresses in
* loopback rules.
*/
if (f->l2t)
cxgb4_l2t_release(f->l2t);
/* The zeroing of the filter rule below clears the filter valid,
* pending, locked flags, l2t pointer, etc. so it's all we need for
* this operation.
*/
memset(f, 0, sizeof(*f));
}
/* Handle a filter write/deletion reply.
*/
static void filter_rpl(struct adapter *adap, const struct cpl_set_tcb_rpl *rpl)
{
unsigned int idx = GET_TID(rpl);
unsigned int nidx = idx - adap->tids.ftid_base;
unsigned int ret;
struct filter_entry *f;
if (idx >= adap->tids.ftid_base && nidx <
(adap->tids.nftids + adap->tids.nsftids)) {
idx = nidx;
ret = GET_TCB_COOKIE(rpl->cookie);
f = &adap->tids.ftid_tab[idx];
if (ret == FW_FILTER_WR_FLT_DELETED) {
/* Clear the filter when we get confirmation from the
* hardware that the filter has been deleted.
*/
clear_filter(adap, f);
} else if (ret == FW_FILTER_WR_SMT_TBL_FULL) {
dev_err(adap->pdev_dev, "filter %u setup failed due to full SMT\n",
idx);
clear_filter(adap, f);
} else if (ret == FW_FILTER_WR_FLT_ADDED) {
f->smtidx = (be64_to_cpu(rpl->oldval) >> 24) & 0xff;
f->pending = 0; /* asynchronous setup completed */
f->valid = 1;
} else {
/* Something went wrong. Issue a warning about the
* problem and clear everything out.
*/
dev_err(adap->pdev_dev, "filter %u setup failed with error %u\n",
idx, ret);
clear_filter(adap, f);
}
}
}
/* Response queue handler for the FW event queue.
*/
static int fwevtq_handler(struct sge_rspq *q, const __be64 *rsp,
const struct pkt_gl *gl)
{
u8 opcode = ((const struct rss_header *)rsp)->opcode;
rsp++; /* skip RSS header */
/* FW can send EGR_UPDATEs encapsulated in a CPL_FW4_MSG.
*/
if (unlikely(opcode == CPL_FW4_MSG &&
((const struct cpl_fw4_msg *)rsp)->type == FW_TYPE_RSSCPL)) {
rsp++;
opcode = ((const struct rss_header *)rsp)->opcode;
rsp++;
if (opcode != CPL_SGE_EGR_UPDATE) {
dev_err(q->adap->pdev_dev, "unexpected FW4/CPL %#x on FW event queue\n"
, opcode);
goto out;
}
}
if (likely(opcode == CPL_SGE_EGR_UPDATE)) {
const struct cpl_sge_egr_update *p = (void *)rsp;
unsigned int qid = EGR_QID(ntohl(p->opcode_qid));
struct sge_txq *txq;
txq = q->adap->sge.egr_map[qid - q->adap->sge.egr_start];
txq->restarts++;
if ((u8 *)txq < (u8 *)q->adap->sge.ofldtxq) {
struct sge_eth_txq *eq;
eq = container_of(txq, struct sge_eth_txq, q);
netif_tx_wake_queue(eq->txq);
} else {
struct sge_ofld_txq *oq;
oq = container_of(txq, struct sge_ofld_txq, q);
tasklet_schedule(&oq->qresume_tsk);
}
} else if (opcode == CPL_FW6_MSG || opcode == CPL_FW4_MSG) {
const struct cpl_fw6_msg *p = (void *)rsp;
if (p->type == 0)
t4_handle_fw_rpl(q->adap, p->data);
} else if (opcode == CPL_L2T_WRITE_RPL) {
const struct cpl_l2t_write_rpl *p = (void *)rsp;
do_l2t_write_rpl(q->adap, p);
} else if (opcode == CPL_SET_TCB_RPL) {
const struct cpl_set_tcb_rpl *p = (void *)rsp;
filter_rpl(q->adap, p);
} else
dev_err(q->adap->pdev_dev,
"unexpected CPL %#x on FW event queue\n", opcode);
out:
return 0;
}
/**
* uldrx_handler - response queue handler for ULD queues
* @q: the response queue that received the packet
* @rsp: the response queue descriptor holding the offload message
* @gl: the gather list of packet fragments
*
* Deliver an ingress offload packet to a ULD. All processing is done by
* the ULD, we just maintain statistics.
*/
static int uldrx_handler(struct sge_rspq *q, const __be64 *rsp,
const struct pkt_gl *gl)
{
struct sge_ofld_rxq *rxq = container_of(q, struct sge_ofld_rxq, rspq);
/* FW can send CPLs encapsulated in a CPL_FW4_MSG.
*/
if (((const struct rss_header *)rsp)->opcode == CPL_FW4_MSG &&
((const struct cpl_fw4_msg *)(rsp + 1))->type == FW_TYPE_RSSCPL)
rsp += 2;
if (ulds[q->uld].rx_handler(q->adap->uld_handle[q->uld], rsp, gl)) {
rxq->stats.nomem++;
return -1;
}
if (gl == NULL)
rxq->stats.imm++;
else if (gl == CXGB4_MSG_AN)
rxq->stats.an++;
else
rxq->stats.pkts++;
return 0;
}
static void disable_msi(struct adapter *adapter)
{
if (adapter->flags & USING_MSIX) {
pci_disable_msix(adapter->pdev);
adapter->flags &= ~USING_MSIX;
} else if (adapter->flags & USING_MSI) {
pci_disable_msi(adapter->pdev);
adapter->flags &= ~USING_MSI;
}
}
/*
* Interrupt handler for non-data events used with MSI-X.
*/
static irqreturn_t t4_nondata_intr(int irq, void *cookie)
{
struct adapter *adap = cookie;
u32 v = t4_read_reg(adap, MYPF_REG(PL_PF_INT_CAUSE));
if (v & PFSW) {
adap->swintr = 1;
t4_write_reg(adap, MYPF_REG(PL_PF_INT_CAUSE), v);
}
t4_slow_intr_handler(adap);
return IRQ_HANDLED;
}
/*
* Name the MSI-X interrupts.
*/
static void name_msix_vecs(struct adapter *adap)
{
int i, j, msi_idx = 2, n = sizeof(adap->msix_info[0].desc);
/* non-data interrupts */
snprintf(adap->msix_info[0].desc, n, "%s", adap->port[0]->name);
/* FW events */
snprintf(adap->msix_info[1].desc, n, "%s-FWeventq",
adap->port[0]->name);
/* Ethernet queues */
for_each_port(adap, j) {
struct net_device *d = adap->port[j];
const struct port_info *pi = netdev_priv(d);
for (i = 0; i < pi->nqsets; i++, msi_idx++)
snprintf(adap->msix_info[msi_idx].desc, n, "%s-Rx%d",
d->name, i);
}
/* offload queues */
for_each_ofldrxq(&adap->sge, i)
snprintf(adap->msix_info[msi_idx++].desc, n, "%s-ofld%d",
adap->port[0]->name, i);
for_each_rdmarxq(&adap->sge, i)
snprintf(adap->msix_info[msi_idx++].desc, n, "%s-rdma%d",
adap->port[0]->name, i);
}
static int request_msix_queue_irqs(struct adapter *adap)
{
struct sge *s = &adap->sge;
int err, ethqidx, ofldqidx = 0, rdmaqidx = 0, msi_index = 2;
err = request_irq(adap->msix_info[1].vec, t4_sge_intr_msix, 0,
adap->msix_info[1].desc, &s->fw_evtq);
if (err)
return err;
for_each_ethrxq(s, ethqidx) {
err = request_irq(adap->msix_info[msi_index].vec,
t4_sge_intr_msix, 0,
adap->msix_info[msi_index].desc,
&s->ethrxq[ethqidx].rspq);
if (err)
goto unwind;
msi_index++;
}
for_each_ofldrxq(s, ofldqidx) {
err = request_irq(adap->msix_info[msi_index].vec,
t4_sge_intr_msix, 0,
adap->msix_info[msi_index].desc,
&s->ofldrxq[ofldqidx].rspq);
if (err)
goto unwind;
msi_index++;
}
for_each_rdmarxq(s, rdmaqidx) {
err = request_irq(adap->msix_info[msi_index].vec,
t4_sge_intr_msix, 0,
adap->msix_info[msi_index].desc,
&s->rdmarxq[rdmaqidx].rspq);
if (err)
goto unwind;
msi_index++;
}
return 0;
unwind:
while (--rdmaqidx >= 0)
free_irq(adap->msix_info[--msi_index].vec,
&s->rdmarxq[rdmaqidx].rspq);
while (--ofldqidx >= 0)
free_irq(adap->msix_info[--msi_index].vec,
&s->ofldrxq[ofldqidx].rspq);
while (--ethqidx >= 0)
free_irq(adap->msix_info[--msi_index].vec,
&s->ethrxq[ethqidx].rspq);
free_irq(adap->msix_info[1].vec, &s->fw_evtq);
return err;
}
static void free_msix_queue_irqs(struct adapter *adap)
{
int i, msi_index = 2;
struct sge *s = &adap->sge;
free_irq(adap->msix_info[1].vec, &s->fw_evtq);
for_each_ethrxq(s, i)
free_irq(adap->msix_info[msi_index++].vec, &s->ethrxq[i].rspq);
for_each_ofldrxq(s, i)
free_irq(adap->msix_info[msi_index++].vec, &s->ofldrxq[i].rspq);
for_each_rdmarxq(s, i)
free_irq(adap->msix_info[msi_index++].vec, &s->rdmarxq[i].rspq);
}
/**
* write_rss - write the RSS table for a given port
* @pi: the port
* @queues: array of queue indices for RSS
*
* Sets up the portion of the HW RSS table for the port's VI to distribute
* packets to the Rx queues in @queues.
*/
static int write_rss(const struct port_info *pi, const u16 *queues)
{
u16 *rss;
int i, err;
const struct sge_eth_rxq *q = &pi->adapter->sge.ethrxq[pi->first_qset];
rss = kmalloc(pi->rss_size * sizeof(u16), GFP_KERNEL);
if (!rss)
return -ENOMEM;
/* map the queue indices to queue ids */
for (i = 0; i < pi->rss_size; i++, queues++)
rss[i] = q[*queues].rspq.abs_id;
err = t4_config_rss_range(pi->adapter, pi->adapter->fn, pi->viid, 0,
pi->rss_size, rss, pi->rss_size);
kfree(rss);
return err;
}
/**
* setup_rss - configure RSS
* @adap: the adapter
*
* Sets up RSS for each port.
*/
static int setup_rss(struct adapter *adap)
{
int i, err;
for_each_port(adap, i) {
const struct port_info *pi = adap2pinfo(adap, i);
err = write_rss(pi, pi->rss);
if (err)
return err;
}
return 0;
}
/*
* Return the channel of the ingress queue with the given qid.
*/
static unsigned int rxq_to_chan(const struct sge *p, unsigned int qid)
{
qid -= p->ingr_start;
return netdev2pinfo(p->ingr_map[qid]->netdev)->tx_chan;
}
/*
* Wait until all NAPI handlers are descheduled.
*/
static void quiesce_rx(struct adapter *adap)
{
int i;
for (i = 0; i < ARRAY_SIZE(adap->sge.ingr_map); i++) {
struct sge_rspq *q = adap->sge.ingr_map[i];
if (q && q->handler)
napi_disable(&q->napi);
}
}
/*
* Enable NAPI scheduling and interrupt generation for all Rx queues.
*/
static void enable_rx(struct adapter *adap)
{
int i;
for (i = 0; i < ARRAY_SIZE(adap->sge.ingr_map); i++) {
struct sge_rspq *q = adap->sge.ingr_map[i];
if (!q)
continue;
if (q->handler)
napi_enable(&q->napi);
/* 0-increment GTS to start the timer and enable interrupts */
t4_write_reg(adap, MYPF_REG(SGE_PF_GTS),
SEINTARM(q->intr_params) |
INGRESSQID(q->cntxt_id));
}
}
/**
* setup_sge_queues - configure SGE Tx/Rx/response queues
* @adap: the adapter
*
* Determines how many sets of SGE queues to use and initializes them.
* We support multiple queue sets per port if we have MSI-X, otherwise
* just one queue set per port.
*/
static int setup_sge_queues(struct adapter *adap)
{
int err, msi_idx, i, j;
struct sge *s = &adap->sge;
bitmap_zero(s->starving_fl, MAX_EGRQ);
bitmap_zero(s->txq_maperr, MAX_EGRQ);
if (adap->flags & USING_MSIX)
msi_idx = 1; /* vector 0 is for non-queue interrupts */
else {
err = t4_sge_alloc_rxq(adap, &s->intrq, false, adap->port[0], 0,
NULL, NULL);
if (err)
return err;
msi_idx = -((int)s->intrq.abs_id + 1);
}
err = t4_sge_alloc_rxq(adap, &s->fw_evtq, true, adap->port[0],
msi_idx, NULL, fwevtq_handler);
if (err) {
freeout: t4_free_sge_resources(adap);
return err;
}
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
struct port_info *pi = netdev_priv(dev);
struct sge_eth_rxq *q = &s->ethrxq[pi->first_qset];
struct sge_eth_txq *t = &s->ethtxq[pi->first_qset];
for (j = 0; j < pi->nqsets; j++, q++) {
if (msi_idx > 0)
msi_idx++;
err = t4_sge_alloc_rxq(adap, &q->rspq, false, dev,
msi_idx, &q->fl,
t4_ethrx_handler);
if (err)
goto freeout;
q->rspq.idx = j;
memset(&q->stats, 0, sizeof(q->stats));
}
for (j = 0; j < pi->nqsets; j++, t++) {
err = t4_sge_alloc_eth_txq(adap, t, dev,
netdev_get_tx_queue(dev, j),
s->fw_evtq.cntxt_id);
if (err)
goto freeout;
}
}
j = s->ofldqsets / adap->params.nports; /* ofld queues per channel */
for_each_ofldrxq(s, i) {
struct sge_ofld_rxq *q = &s->ofldrxq[i];
struct net_device *dev = adap->port[i / j];
if (msi_idx > 0)
msi_idx++;
err = t4_sge_alloc_rxq(adap, &q->rspq, false, dev, msi_idx,
&q->fl, uldrx_handler);
if (err)
goto freeout;
memset(&q->stats, 0, sizeof(q->stats));
s->ofld_rxq[i] = q->rspq.abs_id;
err = t4_sge_alloc_ofld_txq(adap, &s->ofldtxq[i], dev,
s->fw_evtq.cntxt_id);
if (err)
goto freeout;
}
for_each_rdmarxq(s, i) {
struct sge_ofld_rxq *q = &s->rdmarxq[i];
if (msi_idx > 0)
msi_idx++;
err = t4_sge_alloc_rxq(adap, &q->rspq, false, adap->port[i],
msi_idx, &q->fl, uldrx_handler);
if (err)
goto freeout;
memset(&q->stats, 0, sizeof(q->stats));
s->rdma_rxq[i] = q->rspq.abs_id;
}
for_each_port(adap, i) {
/*
* Note that ->rdmarxq[i].rspq.cntxt_id below is 0 if we don't
* have RDMA queues, and that's the right value.
*/
err = t4_sge_alloc_ctrl_txq(adap, &s->ctrlq[i], adap->port[i],
s->fw_evtq.cntxt_id,
s->rdmarxq[i].rspq.cntxt_id);
if (err)
goto freeout;
}
t4_write_reg(adap, MPS_TRC_RSS_CONTROL,
RSSCONTROL(netdev2pinfo(adap->port[0])->tx_chan) |
QUEUENUMBER(s->ethrxq[0].rspq.abs_id));
return 0;
}
/*
* Allocate a chunk of memory using kmalloc or, if that fails, vmalloc.
* The allocated memory is cleared.
*/
void *t4_alloc_mem(size_t size)
{
void *p = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
if (!p)
p = vzalloc(size);
return p;
}
/*
* Free memory allocated through alloc_mem().
*/
static void t4_free_mem(void *addr)
{
if (is_vmalloc_addr(addr))
vfree(addr);
else
kfree(addr);
}
/* Send a Work Request to write the filter at a specified index. We construct
* a Firmware Filter Work Request to have the work done and put the indicated
* filter into "pending" mode which will prevent any further actions against
* it till we get a reply from the firmware on the completion status of the
* request.
*/
static int set_filter_wr(struct adapter *adapter, int fidx)
{
struct filter_entry *f = &adapter->tids.ftid_tab[fidx];
struct sk_buff *skb;
struct fw_filter_wr *fwr;
unsigned int ftid;
/* If the new filter requires loopback Destination MAC and/or VLAN
* rewriting then we need to allocate a Layer 2 Table (L2T) entry for
* the filter.
*/
if (f->fs.newdmac || f->fs.newvlan) {
/* allocate L2T entry for new filter */
f->l2t = t4_l2t_alloc_switching(adapter->l2t);
if (f->l2t == NULL)
return -EAGAIN;
if (t4_l2t_set_switching(adapter, f->l2t, f->fs.vlan,
f->fs.eport, f->fs.dmac)) {
cxgb4_l2t_release(f->l2t);
f->l2t = NULL;
return -ENOMEM;
}
}
ftid = adapter->tids.ftid_base + fidx;
skb = alloc_skb(sizeof(*fwr), GFP_KERNEL | __GFP_NOFAIL);
fwr = (struct fw_filter_wr *)__skb_put(skb, sizeof(*fwr));
memset(fwr, 0, sizeof(*fwr));
/* It would be nice to put most of the following in t4_hw.c but most
* of the work is translating the cxgbtool ch_filter_specification
* into the Work Request and the definition of that structure is
* currently in cxgbtool.h which isn't appropriate to pull into the
* common code. We may eventually try to come up with a more neutral
* filter specification structure but for now it's easiest to simply
* put this fairly direct code in line ...
*/
fwr->op_pkd = htonl(FW_WR_OP(FW_FILTER_WR));
fwr->len16_pkd = htonl(FW_WR_LEN16(sizeof(*fwr)/16));
fwr->tid_to_iq =
htonl(V_FW_FILTER_WR_TID(ftid) |
V_FW_FILTER_WR_RQTYPE(f->fs.type) |
V_FW_FILTER_WR_NOREPLY(0) |
V_FW_FILTER_WR_IQ(f->fs.iq));
fwr->del_filter_to_l2tix =
htonl(V_FW_FILTER_WR_RPTTID(f->fs.rpttid) |
V_FW_FILTER_WR_DROP(f->fs.action == FILTER_DROP) |
V_FW_FILTER_WR_DIRSTEER(f->fs.dirsteer) |
V_FW_FILTER_WR_MASKHASH(f->fs.maskhash) |
V_FW_FILTER_WR_DIRSTEERHASH(f->fs.dirsteerhash) |
V_FW_FILTER_WR_LPBK(f->fs.action == FILTER_SWITCH) |
V_FW_FILTER_WR_DMAC(f->fs.newdmac) |
V_FW_FILTER_WR_SMAC(f->fs.newsmac) |
V_FW_FILTER_WR_INSVLAN(f->fs.newvlan == VLAN_INSERT ||
f->fs.newvlan == VLAN_REWRITE) |
V_FW_FILTER_WR_RMVLAN(f->fs.newvlan == VLAN_REMOVE ||
f->fs.newvlan == VLAN_REWRITE) |
V_FW_FILTER_WR_HITCNTS(f->fs.hitcnts) |
V_FW_FILTER_WR_TXCHAN(f->fs.eport) |
V_FW_FILTER_WR_PRIO(f->fs.prio) |
V_FW_FILTER_WR_L2TIX(f->l2t ? f->l2t->idx : 0));
fwr->ethtype = htons(f->fs.val.ethtype);
fwr->ethtypem = htons(f->fs.mask.ethtype);
fwr->frag_to_ovlan_vldm =
(V_FW_FILTER_WR_FRAG(f->fs.val.frag) |
V_FW_FILTER_WR_FRAGM(f->fs.mask.frag) |
V_FW_FILTER_WR_IVLAN_VLD(f->fs.val.ivlan_vld) |
V_FW_FILTER_WR_OVLAN_VLD(f->fs.val.ovlan_vld) |
V_FW_FILTER_WR_IVLAN_VLDM(f->fs.mask.ivlan_vld) |
V_FW_FILTER_WR_OVLAN_VLDM(f->fs.mask.ovlan_vld));
fwr->smac_sel = 0;
fwr->rx_chan_rx_rpl_iq =
htons(V_FW_FILTER_WR_RX_CHAN(0) |
V_FW_FILTER_WR_RX_RPL_IQ(adapter->sge.fw_evtq.abs_id));
fwr->maci_to_matchtypem =
htonl(V_FW_FILTER_WR_MACI(f->fs.val.macidx) |
V_FW_FILTER_WR_MACIM(f->fs.mask.macidx) |
V_FW_FILTER_WR_FCOE(f->fs.val.fcoe) |
V_FW_FILTER_WR_FCOEM(f->fs.mask.fcoe) |
V_FW_FILTER_WR_PORT(f->fs.val.iport) |
V_FW_FILTER_WR_PORTM(f->fs.mask.iport) |
V_FW_FILTER_WR_MATCHTYPE(f->fs.val.matchtype) |
V_FW_FILTER_WR_MATCHTYPEM(f->fs.mask.matchtype));
fwr->ptcl = f->fs.val.proto;
fwr->ptclm = f->fs.mask.proto;
fwr->ttyp = f->fs.val.tos;
fwr->ttypm = f->fs.mask.tos;
fwr->ivlan = htons(f->fs.val.ivlan);
fwr->ivlanm = htons(f->fs.mask.ivlan);
fwr->ovlan = htons(f->fs.val.ovlan);
fwr->ovlanm = htons(f->fs.mask.ovlan);
memcpy(fwr->lip, f->fs.val.lip, sizeof(fwr->lip));
memcpy(fwr->lipm, f->fs.mask.lip, sizeof(fwr->lipm));
memcpy(fwr->fip, f->fs.val.fip, sizeof(fwr->fip));
memcpy(fwr->fipm, f->fs.mask.fip, sizeof(fwr->fipm));
fwr->lp = htons(f->fs.val.lport);
fwr->lpm = htons(f->fs.mask.lport);
fwr->fp = htons(f->fs.val.fport);
fwr->fpm = htons(f->fs.mask.fport);
if (f->fs.newsmac)
memcpy(fwr->sma, f->fs.smac, sizeof(fwr->sma));
/* Mark the filter as "pending" and ship off the Filter Work Request.
* When we get the Work Request Reply we'll clear the pending status.
*/
f->pending = 1;
set_wr_txq(skb, CPL_PRIORITY_CONTROL, f->fs.val.iport & 0x3);
t4_ofld_send(adapter, skb);
return 0;
}
/* Delete the filter at a specified index.
*/
static int del_filter_wr(struct adapter *adapter, int fidx)
{
struct filter_entry *f = &adapter->tids.ftid_tab[fidx];
struct sk_buff *skb;
struct fw_filter_wr *fwr;
unsigned int len, ftid;
len = sizeof(*fwr);
ftid = adapter->tids.ftid_base + fidx;
skb = alloc_skb(len, GFP_KERNEL | __GFP_NOFAIL);
fwr = (struct fw_filter_wr *)__skb_put(skb, len);
t4_mk_filtdelwr(ftid, fwr, adapter->sge.fw_evtq.abs_id);
/* Mark the filter as "pending" and ship off the Filter Work Request.
* When we get the Work Request Reply we'll clear the pending status.
*/
f->pending = 1;
t4_mgmt_tx(adapter, skb);
return 0;
}
static inline int is_offload(const struct adapter *adap)
{
return adap->params.offload;
}
/*
* Implementation of ethtool operations.
*/
static u32 get_msglevel(struct net_device *dev)
{
return netdev2adap(dev)->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
netdev2adap(dev)->msg_enable = val;
}
static char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK ",
"TxFramesOK ",
"TxBroadcastFrames ",
"TxMulticastFrames ",
"TxUnicastFrames ",
"TxErrorFrames ",
"TxFrames64 ",
"TxFrames65To127 ",
"TxFrames128To255 ",
"TxFrames256To511 ",
"TxFrames512To1023 ",
"TxFrames1024To1518 ",
"TxFrames1519ToMax ",
"TxFramesDropped ",
"TxPauseFrames ",
"TxPPP0Frames ",
"TxPPP1Frames ",
"TxPPP2Frames ",
"TxPPP3Frames ",
"TxPPP4Frames ",
"TxPPP5Frames ",
"TxPPP6Frames ",
"TxPPP7Frames ",
"RxOctetsOK ",
"RxFramesOK ",
"RxBroadcastFrames ",
"RxMulticastFrames ",
"RxUnicastFrames ",
"RxFramesTooLong ",
"RxJabberErrors ",
"RxFCSErrors ",
"RxLengthErrors ",
"RxSymbolErrors ",
"RxRuntFrames ",
"RxFrames64 ",
"RxFrames65To127 ",
"RxFrames128To255 ",
"RxFrames256To511 ",
"RxFrames512To1023 ",
"RxFrames1024To1518 ",
"RxFrames1519ToMax ",
"RxPauseFrames ",
"RxPPP0Frames ",
"RxPPP1Frames ",
"RxPPP2Frames ",
"RxPPP3Frames ",
"RxPPP4Frames ",
"RxPPP5Frames ",
"RxPPP6Frames ",
"RxPPP7Frames ",
"RxBG0FramesDropped ",
"RxBG1FramesDropped ",
"RxBG2FramesDropped ",
"RxBG3FramesDropped ",
"RxBG0FramesTrunc ",
"RxBG1FramesTrunc ",
"RxBG2FramesTrunc ",
"RxBG3FramesTrunc ",
"TSO ",
"TxCsumOffload ",
"RxCsumGood ",
"VLANextractions ",
"VLANinsertions ",
"GROpackets ",
"GROmerged ",
"WriteCoalSuccess ",
"WriteCoalFail ",
};
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
#define T4_REGMAP_SIZE (160 * 1024)
#define T5_REGMAP_SIZE (332 * 1024)
static int get_regs_len(struct net_device *dev)
{
struct adapter *adap = netdev2adap(dev);
if (is_t4(adap->params.chip))
return T4_REGMAP_SIZE;
else
return T5_REGMAP_SIZE;
}
static int get_eeprom_len(struct net_device *dev)
{
return EEPROMSIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct adapter *adapter = netdev2adap(dev);
strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(adapter->pdev),
sizeof(info->bus_info));
if (adapter->params.fw_vers)
snprintf(info->fw_version, sizeof(info->fw_version),
"%u.%u.%u.%u, TP %u.%u.%u.%u",
FW_HDR_FW_VER_MAJOR_GET(adapter->params.fw_vers),
FW_HDR_FW_VER_MINOR_GET(adapter->params.fw_vers),
FW_HDR_FW_VER_MICRO_GET(adapter->params.fw_vers),
FW_HDR_FW_VER_BUILD_GET(adapter->params.fw_vers),
FW_HDR_FW_VER_MAJOR_GET(adapter->params.tp_vers),
FW_HDR_FW_VER_MINOR_GET(adapter->params.tp_vers),
FW_HDR_FW_VER_MICRO_GET(adapter->params.tp_vers),
FW_HDR_FW_VER_BUILD_GET(adapter->params.tp_vers));
}
static void get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
/*
* port stats maintained per queue of the port. They should be in the same
* order as in stats_strings above.
*/
struct queue_port_stats {
u64 tso;
u64 tx_csum;
u64 rx_csum;
u64 vlan_ex;
u64 vlan_ins;
u64 gro_pkts;
u64 gro_merged;
};
static void collect_sge_port_stats(const struct adapter *adap,
const struct port_info *p, struct queue_port_stats *s)
{
int i;
const struct sge_eth_txq *tx = &adap->sge.ethtxq[p->first_qset];
const struct sge_eth_rxq *rx = &adap->sge.ethrxq[p->first_qset];
memset(s, 0, sizeof(*s));
for (i = 0; i < p->nqsets; i++, rx++, tx++) {
s->tso += tx->tso;
s->tx_csum += tx->tx_cso;
s->rx_csum += rx->stats.rx_cso;
s->vlan_ex += rx->stats.vlan_ex;
s->vlan_ins += tx->vlan_ins;
s->gro_pkts += rx->stats.lro_pkts;
s->gro_merged += rx->stats.lro_merged;
}
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 val1, val2;
t4_get_port_stats(adapter, pi->tx_chan, (struct port_stats *)data);
data += sizeof(struct port_stats) / sizeof(u64);
collect_sge_port_stats(adapter, pi, (struct queue_port_stats *)data);
data += sizeof(struct queue_port_stats) / sizeof(u64);
if (!is_t4(adapter->params.chip)) {
t4_write_reg(adapter, SGE_STAT_CFG, STATSOURCE_T5(7));
val1 = t4_read_reg(adapter, SGE_STAT_TOTAL);
val2 = t4_read_reg(adapter, SGE_STAT_MATCH);
*data = val1 - val2;
data++;
*data = val2;
data++;
} else {
memset(data, 0, 2 * sizeof(u64));
*data += 2;
}
}
/*
* Return a version number to identify the type of adapter. The scheme is:
* - bits 0..9: chip version
* - bits 10..15: chip revision
* - bits 16..23: register dump version
*/
static inline unsigned int mk_adap_vers(const struct adapter *ap)
{
return CHELSIO_CHIP_VERSION(ap->params.chip) |
(CHELSIO_CHIP_RELEASE(ap->params.chip) << 10) | (1 << 16);
}
static void reg_block_dump(struct adapter *ap, void *buf, unsigned int start,
unsigned int end)
{
u32 *p = buf + start;
for ( ; start <= end; start += sizeof(u32))
*p++ = t4_read_reg(ap, start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
static const unsigned int t4_reg_ranges[] = {
0x1008, 0x1108,
0x1180, 0x11b4,
0x11fc, 0x123c,
0x1300, 0x173c,
0x1800, 0x18fc,
0x3000, 0x30d8,
0x30e0, 0x5924,
0x5960, 0x59d4,
0x5a00, 0x5af8,
0x6000, 0x6098,
0x6100, 0x6150,
0x6200, 0x6208,
0x6240, 0x6248,
0x6280, 0x6338,
0x6370, 0x638c,
0x6400, 0x643c,
0x6500, 0x6524,
0x6a00, 0x6a38,
0x6a60, 0x6a78,
0x6b00, 0x6b84,
0x6bf0, 0x6c84,
0x6cf0, 0x6d84,
0x6df0, 0x6e84,
0x6ef0, 0x6f84,
0x6ff0, 0x7084,
0x70f0, 0x7184,
0x71f0, 0x7284,
0x72f0, 0x7384,
0x73f0, 0x7450,
0x7500, 0x7530,
0x7600, 0x761c,
0x7680, 0x76cc,
0x7700, 0x7798,
0x77c0, 0x77fc,
0x7900, 0x79fc,
0x7b00, 0x7c38,
0x7d00, 0x7efc,
0x8dc0, 0x8e1c,
0x8e30, 0x8e78,
0x8ea0, 0x8f6c,
0x8fc0, 0x9074,
0x90fc, 0x90fc,
0x9400, 0x9458,
0x9600, 0x96bc,
0x9800, 0x9808,
0x9820, 0x983c,
0x9850, 0x9864,
0x9c00, 0x9c6c,
0x9c80, 0x9cec,
0x9d00, 0x9d6c,
0x9d80, 0x9dec,
0x9e00, 0x9e6c,
0x9e80, 0x9eec,
0x9f00, 0x9f6c,
0x9f80, 0x9fec,
0xd004, 0xd03c,
0xdfc0, 0xdfe0,
0xe000, 0xea7c,
0xf000, 0x11190,
0x19040, 0x1906c,
0x19078, 0x19080,
0x1908c, 0x19124,
0x19150, 0x191b0,
0x191d0, 0x191e8,
0x19238, 0x1924c,
0x193f8, 0x19474,
0x19490, 0x194f8,
0x19800, 0x19f30,
0x1a000, 0x1a06c,
0x1a0b0, 0x1a120,
0x1a128, 0x1a138,
0x1a190, 0x1a1c4,
0x1a1fc, 0x1a1fc,
0x1e040, 0x1e04c,
0x1e284, 0x1e28c,
0x1e2c0, 0x1e2c0,
0x1e2e0, 0x1e2e0,
0x1e300, 0x1e384,
0x1e3c0, 0x1e3c8,
0x1e440, 0x1e44c,
0x1e684, 0x1e68c,
0x1e6c0, 0x1e6c0,
0x1e6e0, 0x1e6e0,
0x1e700, 0x1e784,
0x1e7c0, 0x1e7c8,
0x1e840, 0x1e84c,
0x1ea84, 0x1ea8c,
0x1eac0, 0x1eac0,
0x1eae0, 0x1eae0,
0x1eb00, 0x1eb84,
0x1ebc0, 0x1ebc8,
0x1ec40, 0x1ec4c,
0x1ee84, 0x1ee8c,
0x1eec0, 0x1eec0,
0x1eee0, 0x1eee0,
0x1ef00, 0x1ef84,
0x1efc0, 0x1efc8,
0x1f040, 0x1f04c,
0x1f284, 0x1f28c,
0x1f2c0, 0x1f2c0,
0x1f2e0, 0x1f2e0,
0x1f300, 0x1f384,
0x1f3c0, 0x1f3c8,
0x1f440, 0x1f44c,
0x1f684, 0x1f68c,
0x1f6c0, 0x1f6c0,
0x1f6e0, 0x1f6e0,
0x1f700, 0x1f784,
0x1f7c0, 0x1f7c8,
0x1f840, 0x1f84c,
0x1fa84, 0x1fa8c,
0x1fac0, 0x1fac0,
0x1fae0, 0x1fae0,
0x1fb00, 0x1fb84,
0x1fbc0, 0x1fbc8,
0x1fc40, 0x1fc4c,
0x1fe84, 0x1fe8c,
0x1fec0, 0x1fec0,
0x1fee0, 0x1fee0,
0x1ff00, 0x1ff84,
0x1ffc0, 0x1ffc8,
0x20000, 0x2002c,
0x20100, 0x2013c,
0x20190, 0x201c8,
0x20200, 0x20318,
0x20400, 0x20528,
0x20540, 0x20614,
0x21000, 0x21040,
0x2104c, 0x21060,
0x210c0, 0x210ec,
0x21200, 0x21268,
0x21270, 0x21284,
0x212fc, 0x21388,
0x21400, 0x21404,
0x21500, 0x21518,
0x2152c, 0x2153c,
0x21550, 0x21554,
0x21600, 0x21600,
0x21608, 0x21628,
0x21630, 0x2163c,
0x21700, 0x2171c,
0x21780, 0x2178c,
0x21800, 0x21c38,
0x21c80, 0x21d7c,
0x21e00, 0x21e04,
0x22000, 0x2202c,
0x22100, 0x2213c,
0x22190, 0x221c8,
0x22200, 0x22318,
0x22400, 0x22528,
0x22540, 0x22614,
0x23000, 0x23040,
0x2304c, 0x23060,
0x230c0, 0x230ec,
0x23200, 0x23268,
0x23270, 0x23284,
0x232fc, 0x23388,
0x23400, 0x23404,
0x23500, 0x23518,
0x2352c, 0x2353c,
0x23550, 0x23554,
0x23600, 0x23600,
0x23608, 0x23628,
0x23630, 0x2363c,
0x23700, 0x2371c,
0x23780, 0x2378c,
0x23800, 0x23c38,
0x23c80, 0x23d7c,
0x23e00, 0x23e04,
0x24000, 0x2402c,
0x24100, 0x2413c,
0x24190, 0x241c8,
0x24200, 0x24318,
0x24400, 0x24528,
0x24540, 0x24614,
0x25000, 0x25040,
0x2504c, 0x25060,
0x250c0, 0x250ec,
0x25200, 0x25268,
0x25270, 0x25284,
0x252fc, 0x25388,
0x25400, 0x25404,
0x25500, 0x25518,
0x2552c, 0x2553c,
0x25550, 0x25554,
0x25600, 0x25600,
0x25608, 0x25628,
0x25630, 0x2563c,
0x25700, 0x2571c,
0x25780, 0x2578c,
0x25800, 0x25c38,
0x25c80, 0x25d7c,
0x25e00, 0x25e04,
0x26000, 0x2602c,
0x26100, 0x2613c,
0x26190, 0x261c8,
0x26200, 0x26318,
0x26400, 0x26528,
0x26540, 0x26614,
0x27000, 0x27040,
0x2704c, 0x27060,
0x270c0, 0x270ec,
0x27200, 0x27268,
0x27270, 0x27284,
0x272fc, 0x27388,
0x27400, 0x27404,
0x27500, 0x27518,
0x2752c, 0x2753c,
0x27550, 0x27554,
0x27600, 0x27600,
0x27608, 0x27628,
0x27630, 0x2763c,
0x27700, 0x2771c,
0x27780, 0x2778c,
0x27800, 0x27c38,
0x27c80, 0x27d7c,
0x27e00, 0x27e04
};
static const unsigned int t5_reg_ranges[] = {
0x1008, 0x1148,
0x1180, 0x11b4,
0x11fc, 0x123c,
0x1280, 0x173c,
0x1800, 0x18fc,
0x3000, 0x3028,
0x3060, 0x30d8,
0x30e0, 0x30fc,
0x3140, 0x357c,
0x35a8, 0x35cc,
0x35ec, 0x35ec,
0x3600, 0x5624,
0x56cc, 0x575c,
0x580c, 0x5814,
0x5890, 0x58bc,
0x5940, 0x59dc,
0x59fc, 0x5a18,
0x5a60, 0x5a9c,
0x5b9c, 0x5bfc,
0x6000, 0x6040,
0x6058, 0x614c,
0x7700, 0x7798,
0x77c0, 0x78fc,
0x7b00, 0x7c54,
0x7d00, 0x7efc,
0x8dc0, 0x8de0,
0x8df8, 0x8e84,
0x8ea0, 0x8f84,
0x8fc0, 0x90f8,
0x9400, 0x9470,
0x9600, 0x96f4,
0x9800, 0x9808,
0x9820, 0x983c,
0x9850, 0x9864,
0x9c00, 0x9c6c,
0x9c80, 0x9cec,
0x9d00, 0x9d6c,
0x9d80, 0x9dec,
0x9e00, 0x9e6c,
0x9e80, 0x9eec,
0x9f00, 0x9f6c,
0x9f80, 0xa020,
0xd004, 0xd03c,
0xdfc0, 0xdfe0,
0xe000, 0x11088,
0x1109c, 0x1117c,
0x11190, 0x11204,
0x19040, 0x1906c,
0x19078, 0x19080,
0x1908c, 0x19124,
0x19150, 0x191b0,
0x191d0, 0x191e8,
0x19238, 0x19290,
0x193f8, 0x19474,
0x19490, 0x194cc,
0x194f0, 0x194f8,
0x19c00, 0x19c60,
0x19c94, 0x19e10,
0x19e50, 0x19f34,
0x19f40, 0x19f50,
0x19f90, 0x19fe4,
0x1a000, 0x1a06c,
0x1a0b0, 0x1a120,
0x1a128, 0x1a138,
0x1a190, 0x1a1c4,
0x1a1fc, 0x1a1fc,
0x1e008, 0x1e00c,
0x1e040, 0x1e04c,
0x1e284, 0x1e290,
0x1e2c0, 0x1e2c0,
0x1e2e0, 0x1e2e0,
0x1e300, 0x1e384,
0x1e3c0, 0x1e3c8,
0x1e408, 0x1e40c,
0x1e440, 0x1e44c,
0x1e684, 0x1e690,
0x1e6c0, 0x1e6c0,
0x1e6e0, 0x1e6e0,
0x1e700, 0x1e784,
0x1e7c0, 0x1e7c8,
0x1e808, 0x1e80c,
0x1e840, 0x1e84c,
0x1ea84, 0x1ea90,
0x1eac0, 0x1eac0,
0x1eae0, 0x1eae0,
0x1eb00, 0x1eb84,
0x1ebc0, 0x1ebc8,
0x1ec08, 0x1ec0c,
0x1ec40, 0x1ec4c,
0x1ee84, 0x1ee90,
0x1eec0, 0x1eec0,
0x1eee0, 0x1eee0,
0x1ef00, 0x1ef84,
0x1efc0, 0x1efc8,
0x1f008, 0x1f00c,
0x1f040, 0x1f04c,
0x1f284, 0x1f290,
0x1f2c0, 0x1f2c0,
0x1f2e0, 0x1f2e0,
0x1f300, 0x1f384,
0x1f3c0, 0x1f3c8,
0x1f408, 0x1f40c,
0x1f440, 0x1f44c,
0x1f684, 0x1f690,
0x1f6c0, 0x1f6c0,
0x1f6e0, 0x1f6e0,
0x1f700, 0x1f784,
0x1f7c0, 0x1f7c8,
0x1f808, 0x1f80c,
0x1f840, 0x1f84c,
0x1fa84, 0x1fa90,
0x1fac0, 0x1fac0,
0x1fae0, 0x1fae0,
0x1fb00, 0x1fb84,
0x1fbc0, 0x1fbc8,
0x1fc08, 0x1fc0c,
0x1fc40, 0x1fc4c,
0x1fe84, 0x1fe90,
0x1fec0, 0x1fec0,
0x1fee0, 0x1fee0,
0x1ff00, 0x1ff84,
0x1ffc0, 0x1ffc8,
0x30000, 0x30030,
0x30100, 0x30144,
0x30190, 0x301d0,
0x30200, 0x30318,
0x30400, 0x3052c,
0x30540, 0x3061c,
0x30800, 0x30834,
0x308c0, 0x30908,
0x30910, 0x309ac,
0x30a00, 0x30a04,
0x30a0c, 0x30a2c,
0x30a44, 0x30a50,
0x30a74, 0x30c24,
0x30d08, 0x30d14,
0x30d1c, 0x30d20,
0x30d3c, 0x30d50,
0x31200, 0x3120c,
0x31220, 0x31220,
0x31240, 0x31240,
0x31600, 0x31600,
0x31608, 0x3160c,
0x31a00, 0x31a1c,
0x31e04, 0x31e20,
0x31e38, 0x31e3c,
0x31e80, 0x31e80,
0x31e88, 0x31ea8,
0x31eb0, 0x31eb4,
0x31ec8, 0x31ed4,
0x31fb8, 0x32004,
0x32208, 0x3223c,
0x32600, 0x32630,
0x32a00, 0x32abc,
0x32b00, 0x32b70,
0x33000, 0x33048,
0x33060, 0x3309c,
0x330f0, 0x33148,
0x33160, 0x3319c,
0x331f0, 0x332e4,
0x332f8, 0x333e4,
0x333f8, 0x33448,
0x33460, 0x3349c,
0x334f0, 0x33548,
0x33560, 0x3359c,
0x335f0, 0x336e4,
0x336f8, 0x337e4,
0x337f8, 0x337fc,
0x33814, 0x33814,
0x3382c, 0x3382c,
0x33880, 0x3388c,
0x338e8, 0x338ec,
0x33900, 0x33948,
0x33960, 0x3399c,
0x339f0, 0x33ae4,
0x33af8, 0x33b10,
0x33b28, 0x33b28,
0x33b3c, 0x33b50,
0x33bf0, 0x33c10,
0x33c28, 0x33c28,
0x33c3c, 0x33c50,
0x33cf0, 0x33cfc,
0x34000, 0x34030,
0x34100, 0x34144,
0x34190, 0x341d0,
0x34200, 0x34318,
0x34400, 0x3452c,
0x34540, 0x3461c,
0x34800, 0x34834,
0x348c0, 0x34908,
0x34910, 0x349ac,
0x34a00, 0x34a04,
0x34a0c, 0x34a2c,
0x34a44, 0x34a50,
0x34a74, 0x34c24,
0x34d08, 0x34d14,
0x34d1c, 0x34d20,
0x34d3c, 0x34d50,
0x35200, 0x3520c,
0x35220, 0x35220,
0x35240, 0x35240,
0x35600, 0x35600,
0x35608, 0x3560c,
0x35a00, 0x35a1c,
0x35e04, 0x35e20,
0x35e38, 0x35e3c,
0x35e80, 0x35e80,
0x35e88, 0x35ea8,
0x35eb0, 0x35eb4,
0x35ec8, 0x35ed4,
0x35fb8, 0x36004,
0x36208, 0x3623c,
0x36600, 0x36630,
0x36a00, 0x36abc,
0x36b00, 0x36b70,
0x37000, 0x37048,
0x37060, 0x3709c,
0x370f0, 0x37148,
0x37160, 0x3719c,
0x371f0, 0x372e4,
0x372f8, 0x373e4,
0x373f8, 0x37448,
0x37460, 0x3749c,
0x374f0, 0x37548,
0x37560, 0x3759c,
0x375f0, 0x376e4,
0x376f8, 0x377e4,
0x377f8, 0x377fc,
0x37814, 0x37814,
0x3782c, 0x3782c,
0x37880, 0x3788c,
0x378e8, 0x378ec,
0x37900, 0x37948,
0x37960, 0x3799c,
0x379f0, 0x37ae4,
0x37af8, 0x37b10,
0x37b28, 0x37b28,
0x37b3c, 0x37b50,
0x37bf0, 0x37c10,
0x37c28, 0x37c28,
0x37c3c, 0x37c50,
0x37cf0, 0x37cfc,
0x38000, 0x38030,
0x38100, 0x38144,
0x38190, 0x381d0,
0x38200, 0x38318,
0x38400, 0x3852c,
0x38540, 0x3861c,
0x38800, 0x38834,
0x388c0, 0x38908,
0x38910, 0x389ac,
0x38a00, 0x38a04,
0x38a0c, 0x38a2c,
0x38a44, 0x38a50,
0x38a74, 0x38c24,
0x38d08, 0x38d14,
0x38d1c, 0x38d20,
0x38d3c, 0x38d50,
0x39200, 0x3920c,
0x39220, 0x39220,
0x39240, 0x39240,
0x39600, 0x39600,
0x39608, 0x3960c,
0x39a00, 0x39a1c,
0x39e04, 0x39e20,
0x39e38, 0x39e3c,
0x39e80, 0x39e80,
0x39e88, 0x39ea8,
0x39eb0, 0x39eb4,
0x39ec8, 0x39ed4,
0x39fb8, 0x3a004,
0x3a208, 0x3a23c,
0x3a600, 0x3a630,
0x3aa00, 0x3aabc,
0x3ab00, 0x3ab70,
0x3b000, 0x3b048,
0x3b060, 0x3b09c,
0x3b0f0, 0x3b148,
0x3b160, 0x3b19c,
0x3b1f0, 0x3b2e4,
0x3b2f8, 0x3b3e4,
0x3b3f8, 0x3b448,
0x3b460, 0x3b49c,
0x3b4f0, 0x3b548,
0x3b560, 0x3b59c,
0x3b5f0, 0x3b6e4,
0x3b6f8, 0x3b7e4,
0x3b7f8, 0x3b7fc,
0x3b814, 0x3b814,
0x3b82c, 0x3b82c,
0x3b880, 0x3b88c,
0x3b8e8, 0x3b8ec,
0x3b900, 0x3b948,
0x3b960, 0x3b99c,
0x3b9f0, 0x3bae4,
0x3baf8, 0x3bb10,
0x3bb28, 0x3bb28,
0x3bb3c, 0x3bb50,
0x3bbf0, 0x3bc10,
0x3bc28, 0x3bc28,
0x3bc3c, 0x3bc50,
0x3bcf0, 0x3bcfc,
0x3c000, 0x3c030,
0x3c100, 0x3c144,
0x3c190, 0x3c1d0,
0x3c200, 0x3c318,
0x3c400, 0x3c52c,
0x3c540, 0x3c61c,
0x3c800, 0x3c834,
0x3c8c0, 0x3c908,
0x3c910, 0x3c9ac,
0x3ca00, 0x3ca04,
0x3ca0c, 0x3ca2c,
0x3ca44, 0x3ca50,
0x3ca74, 0x3cc24,
0x3cd08, 0x3cd14,
0x3cd1c, 0x3cd20,
0x3cd3c, 0x3cd50,
0x3d200, 0x3d20c,
0x3d220, 0x3d220,
0x3d240, 0x3d240,
0x3d600, 0x3d600,
0x3d608, 0x3d60c,
0x3da00, 0x3da1c,
0x3de04, 0x3de20,
0x3de38, 0x3de3c,
0x3de80, 0x3de80,
0x3de88, 0x3dea8,
0x3deb0, 0x3deb4,
0x3dec8, 0x3ded4,
0x3dfb8, 0x3e004,
0x3e208, 0x3e23c,
0x3e600, 0x3e630,
0x3ea00, 0x3eabc,
0x3eb00, 0x3eb70,
0x3f000, 0x3f048,
0x3f060, 0x3f09c,
0x3f0f0, 0x3f148,
0x3f160, 0x3f19c,
0x3f1f0, 0x3f2e4,
0x3f2f8, 0x3f3e4,
0x3f3f8, 0x3f448,
0x3f460, 0x3f49c,
0x3f4f0, 0x3f548,
0x3f560, 0x3f59c,
0x3f5f0, 0x3f6e4,
0x3f6f8, 0x3f7e4,
0x3f7f8, 0x3f7fc,
0x3f814, 0x3f814,
0x3f82c, 0x3f82c,
0x3f880, 0x3f88c,
0x3f8e8, 0x3f8ec,
0x3f900, 0x3f948,
0x3f960, 0x3f99c,
0x3f9f0, 0x3fae4,
0x3faf8, 0x3fb10,
0x3fb28, 0x3fb28,
0x3fb3c, 0x3fb50,
0x3fbf0, 0x3fc10,
0x3fc28, 0x3fc28,
0x3fc3c, 0x3fc50,
0x3fcf0, 0x3fcfc,
0x40000, 0x4000c,
0x40040, 0x40068,
0x40080, 0x40144,
0x40180, 0x4018c,
0x40200, 0x40298,
0x402ac, 0x4033c,
0x403f8, 0x403fc,
0x41300, 0x413c4,
0x41400, 0x4141c,
0x41480, 0x414d0,
0x44000, 0x44078,
0x440c0, 0x44278,
0x442c0, 0x44478,
0x444c0, 0x44678,
0x446c0, 0x44878,
0x448c0, 0x449fc,
0x45000, 0x45068,
0x45080, 0x45084,
0x450a0, 0x450b0,
0x45200, 0x45268,
0x45280, 0x45284,
0x452a0, 0x452b0,
0x460c0, 0x460e4,
0x47000, 0x4708c,
0x47200, 0x47250,
0x47400, 0x47420,
0x47600, 0x47618,
0x47800, 0x47814,
0x48000, 0x4800c,
0x48040, 0x48068,
0x48080, 0x48144,
0x48180, 0x4818c,
0x48200, 0x48298,
0x482ac, 0x4833c,
0x483f8, 0x483fc,
0x49300, 0x493c4,
0x49400, 0x4941c,
0x49480, 0x494d0,
0x4c000, 0x4c078,
0x4c0c0, 0x4c278,
0x4c2c0, 0x4c478,
0x4c4c0, 0x4c678,
0x4c6c0, 0x4c878,
0x4c8c0, 0x4c9fc,
0x4d000, 0x4d068,
0x4d080, 0x4d084,
0x4d0a0, 0x4d0b0,
0x4d200, 0x4d268,
0x4d280, 0x4d284,
0x4d2a0, 0x4d2b0,
0x4e0c0, 0x4e0e4,
0x4f000, 0x4f08c,
0x4f200, 0x4f250,
0x4f400, 0x4f420,
0x4f600, 0x4f618,
0x4f800, 0x4f814,
0x50000, 0x500cc,
0x50400, 0x50400,
0x50800, 0x508cc,
0x50c00, 0x50c00,
0x51000, 0x5101c,
0x51300, 0x51308,
};
int i;
struct adapter *ap = netdev2adap(dev);
static const unsigned int *reg_ranges;
int arr_size = 0, buf_size = 0;
if (is_t4(ap->params.chip)) {
reg_ranges = &t4_reg_ranges[0];
arr_size = ARRAY_SIZE(t4_reg_ranges);
buf_size = T4_REGMAP_SIZE;
} else {
reg_ranges = &t5_reg_ranges[0];
arr_size = ARRAY_SIZE(t5_reg_ranges);
buf_size = T5_REGMAP_SIZE;
}
regs->version = mk_adap_vers(ap);
memset(buf, 0, buf_size);
for (i = 0; i < arr_size; i += 2)
reg_block_dump(ap, buf, reg_ranges[i], reg_ranges[i + 1]);
}
static int restart_autoneg(struct net_device *dev)
{
struct port_info *p = netdev_priv(dev);
if (!netif_running(dev))
return -EAGAIN;
if (p->link_cfg.autoneg != AUTONEG_ENABLE)
return -EINVAL;
t4_restart_aneg(p->adapter, p->adapter->fn, p->tx_chan);
return 0;
}
static int identify_port(struct net_device *dev,
enum ethtool_phys_id_state state)
{
unsigned int val;
struct adapter *adap = netdev2adap(dev);
if (state == ETHTOOL_ID_ACTIVE)
val = 0xffff;
else if (state == ETHTOOL_ID_INACTIVE)
val = 0;
else
return -EINVAL;
return t4_identify_port(adap, adap->fn, netdev2pinfo(dev)->viid, val);
}
static unsigned int from_fw_linkcaps(unsigned int type, unsigned int caps)
{
unsigned int v = 0;
if (type == FW_PORT_TYPE_BT_SGMII || type == FW_PORT_TYPE_BT_XFI ||
type == FW_PORT_TYPE_BT_XAUI) {
v |= SUPPORTED_TP;
if (caps & FW_PORT_CAP_SPEED_100M)
v |= SUPPORTED_100baseT_Full;
if (caps & FW_PORT_CAP_SPEED_1G)
v |= SUPPORTED_1000baseT_Full;
if (caps & FW_PORT_CAP_SPEED_10G)
v |= SUPPORTED_10000baseT_Full;
} else if (type == FW_PORT_TYPE_KX4 || type == FW_PORT_TYPE_KX) {
v |= SUPPORTED_Backplane;
if (caps & FW_PORT_CAP_SPEED_1G)
v |= SUPPORTED_1000baseKX_Full;
if (caps & FW_PORT_CAP_SPEED_10G)
v |= SUPPORTED_10000baseKX4_Full;
} else if (type == FW_PORT_TYPE_KR)
v |= SUPPORTED_Backplane | SUPPORTED_10000baseKR_Full;
else if (type == FW_PORT_TYPE_BP_AP)
v |= SUPPORTED_Backplane | SUPPORTED_10000baseR_FEC |
SUPPORTED_10000baseKR_Full | SUPPORTED_1000baseKX_Full;
else if (type == FW_PORT_TYPE_BP4_AP)
v |= SUPPORTED_Backplane | SUPPORTED_10000baseR_FEC |
SUPPORTED_10000baseKR_Full | SUPPORTED_1000baseKX_Full |
SUPPORTED_10000baseKX4_Full;
else if (type == FW_PORT_TYPE_FIBER_XFI ||
type == FW_PORT_TYPE_FIBER_XAUI || type == FW_PORT_TYPE_SFP)
v |= SUPPORTED_FIBRE;
if (caps & FW_PORT_CAP_ANEG)
v |= SUPPORTED_Autoneg;
return v;
}
static unsigned int to_fw_linkcaps(unsigned int caps)
{
unsigned int v = 0;
if (caps & ADVERTISED_100baseT_Full)
v |= FW_PORT_CAP_SPEED_100M;
if (caps & ADVERTISED_1000baseT_Full)
v |= FW_PORT_CAP_SPEED_1G;
if (caps & ADVERTISED_10000baseT_Full)
v |= FW_PORT_CAP_SPEED_10G;
return v;
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
const struct port_info *p = netdev_priv(dev);
if (p->port_type == FW_PORT_TYPE_BT_SGMII ||
p->port_type == FW_PORT_TYPE_BT_XFI ||
p->port_type == FW_PORT_TYPE_BT_XAUI)
cmd->port = PORT_TP;
else if (p->port_type == FW_PORT_TYPE_FIBER_XFI ||
p->port_type == FW_PORT_TYPE_FIBER_XAUI)
cmd->port = PORT_FIBRE;
else if (p->port_type == FW_PORT_TYPE_SFP) {
if (p->mod_type == FW_PORT_MOD_TYPE_TWINAX_PASSIVE ||
p->mod_type == FW_PORT_MOD_TYPE_TWINAX_ACTIVE)
cmd->port = PORT_DA;
else
cmd->port = PORT_FIBRE;
} else
cmd->port = PORT_OTHER;
if (p->mdio_addr >= 0) {
cmd->phy_address = p->mdio_addr;
cmd->transceiver = XCVR_EXTERNAL;
cmd->mdio_support = p->port_type == FW_PORT_TYPE_BT_SGMII ?
MDIO_SUPPORTS_C22 : MDIO_SUPPORTS_C45;
} else {
cmd->phy_address = 0; /* not really, but no better option */
cmd->transceiver = XCVR_INTERNAL;
cmd->mdio_support = 0;
}
cmd->supported = from_fw_linkcaps(p->port_type, p->link_cfg.supported);
cmd->advertising = from_fw_linkcaps(p->port_type,
p->link_cfg.advertising);
ethtool_cmd_speed_set(cmd,
netif_carrier_ok(dev) ? p->link_cfg.speed : 0);
cmd->duplex = DUPLEX_FULL;
cmd->autoneg = p->link_cfg.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static unsigned int speed_to_caps(int speed)
{
if (speed == SPEED_100)
return FW_PORT_CAP_SPEED_100M;
if (speed == SPEED_1000)
return FW_PORT_CAP_SPEED_1G;
if (speed == SPEED_10000)
return FW_PORT_CAP_SPEED_10G;
return 0;
}
static int set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
unsigned int cap;
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_cfg;
u32 speed = ethtool_cmd_speed(cmd);
if (cmd->duplex != DUPLEX_FULL) /* only full-duplex supported */
return -EINVAL;
if (!(lc->supported & FW_PORT_CAP_ANEG)) {
/*
* PHY offers a single speed. See if that's what's
* being requested.
*/
if (cmd->autoneg == AUTONEG_DISABLE &&
(lc->supported & speed_to_caps(speed)))
return 0;
return -EINVAL;
}
if (cmd->autoneg == AUTONEG_DISABLE) {
cap = speed_to_caps(speed);
if (!(lc->supported & cap) || (speed == SPEED_1000) ||
(speed == SPEED_10000))
return -EINVAL;
lc->requested_speed = cap;
lc->advertising = 0;
} else {
cap = to_fw_linkcaps(cmd->advertising);
if (!(lc->supported & cap))
return -EINVAL;
lc->requested_speed = 0;
lc->advertising = cap | FW_PORT_CAP_ANEG;
}
lc->autoneg = cmd->autoneg;
if (netif_running(dev))
return t4_link_start(p->adapter, p->adapter->fn, p->tx_chan,
lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
epause->autoneg = (p->link_cfg.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_cfg.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_cfg.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_cfg;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & FW_PORT_CAP_ANEG)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (netif_running(dev))
return t4_link_start(p->adapter, p->adapter->fn, p->tx_chan,
lc);
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
const struct port_info *pi = netdev_priv(dev);
const struct sge *s = &pi->adapter->sge;
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_mini_max_pending = MAX_RSPQ_ENTRIES;
e->rx_jumbo_max_pending = 0;
e->tx_max_pending = MAX_TXQ_ENTRIES;
e->rx_pending = s->ethrxq[pi->first_qset].fl.size - 8;
e->rx_mini_pending = s->ethrxq[pi->first_qset].rspq.size;
e->rx_jumbo_pending = 0;
e->tx_pending = s->ethtxq[pi->first_qset].q.size;
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
int i;
const struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct sge *s = &adapter->sge;
if (e->rx_pending > MAX_RX_BUFFERS || e->rx_jumbo_pending ||
e->tx_pending > MAX_TXQ_ENTRIES ||
e->rx_mini_pending > MAX_RSPQ_ENTRIES ||
e->rx_mini_pending < MIN_RSPQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES || e->tx_pending < MIN_TXQ_ENTRIES)
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
for (i = 0; i < pi->nqsets; ++i) {
s->ethtxq[pi->first_qset + i].q.size = e->tx_pending;
s->ethrxq[pi->first_qset + i].fl.size = e->rx_pending + 8;
s->ethrxq[pi->first_qset + i].rspq.size = e->rx_mini_pending;
}
return 0;
}
static int closest_timer(const struct sge *s, int time)
{
int i, delta, match = 0, min_delta = INT_MAX;
for (i = 0; i < ARRAY_SIZE(s->timer_val); i++) {
delta = time - s->timer_val[i];
if (delta < 0)
delta = -delta;
if (delta < min_delta) {
min_delta = delta;
match = i;
}
}
return match;
}
static int closest_thres(const struct sge *s, int thres)
{
int i, delta, match = 0, min_delta = INT_MAX;
for (i = 0; i < ARRAY_SIZE(s->counter_val); i++) {
delta = thres - s->counter_val[i];
if (delta < 0)
delta = -delta;
if (delta < min_delta) {
min_delta = delta;
match = i;
}
}
return match;
}
/*
* Return a queue's interrupt hold-off time in us. 0 means no timer.
*/
static unsigned int qtimer_val(const struct adapter *adap,
const struct sge_rspq *q)
{
unsigned int idx = q->intr_params >> 1;
return idx < SGE_NTIMERS ? adap->sge.timer_val[idx] : 0;
}
/**
* set_rxq_intr_params - set a queue's interrupt holdoff parameters
* @adap: the adapter
* @q: the Rx queue
* @us: the hold-off time in us, or 0 to disable timer
* @cnt: the hold-off packet count, or 0 to disable counter
*
* Sets an Rx queue's interrupt hold-off time and packet count. At least
* one of the two needs to be enabled for the queue to generate interrupts.
*/
static int set_rxq_intr_params(struct adapter *adap, struct sge_rspq *q,
unsigned int us, unsigned int cnt)
{
if ((us | cnt) == 0)
cnt = 1;
if (cnt) {
int err;
u32 v, new_idx;
new_idx = closest_thres(&adap->sge, cnt);
if (q->desc && q->pktcnt_idx != new_idx) {
/* the queue has already been created, update it */
v = FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_IQ_INTCNTTHRESH) |
FW_PARAMS_PARAM_YZ(q->cntxt_id);
err = t4_set_params(adap, adap->fn, adap->fn, 0, 1, &v,
&new_idx);
if (err)
return err;
}
q->pktcnt_idx = new_idx;
}
us = us == 0 ? 6 : closest_timer(&adap->sge, us);
q->intr_params = QINTR_TIMER_IDX(us) | (cnt > 0 ? QINTR_CNT_EN : 0);
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
const struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
struct sge_rspq *q;
int i;
int r = 0;
for (i = pi->first_qset; i < pi->first_qset + pi->nqsets; i++) {
q = &adap->sge.ethrxq[i].rspq;
r = set_rxq_intr_params(adap, q, c->rx_coalesce_usecs,
c->rx_max_coalesced_frames);
if (r) {
dev_err(&dev->dev, "failed to set coalesce %d\n", r);
break;
}
}
return r;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
const struct port_info *pi = netdev_priv(dev);
const struct adapter *adap = pi->adapter;
const struct sge_rspq *rq = &adap->sge.ethrxq[pi->first_qset].rspq;
c->rx_coalesce_usecs = qtimer_val(adap, rq);
c->rx_max_coalesced_frames = (rq->intr_params & QINTR_CNT_EN) ?
adap->sge.counter_val[rq->pktcnt_idx] : 0;
return 0;
}
/**
* eeprom_ptov - translate a physical EEPROM address to virtual
* @phys_addr: the physical EEPROM address
* @fn: the PCI function number
* @sz: size of function-specific area
*
* Translate a physical EEPROM address to virtual. The first 1K is
* accessed through virtual addresses starting at 31K, the rest is
* accessed through virtual addresses starting at 0.
*
* The mapping is as follows:
* [0..1K) -> [31K..32K)
* [1K..1K+A) -> [31K-A..31K)
* [1K+A..ES) -> [0..ES-A-1K)
*
* where A = @fn * @sz, and ES = EEPROM size.
*/
static int eeprom_ptov(unsigned int phys_addr, unsigned int fn, unsigned int sz)
{
fn *= sz;
if (phys_addr < 1024)
return phys_addr + (31 << 10);
if (phys_addr < 1024 + fn)
return 31744 - fn + phys_addr - 1024;
if (phys_addr < EEPROMSIZE)
return phys_addr - 1024 - fn;
return -EINVAL;
}
/*
* The next two routines implement eeprom read/write from physical addresses.
*/
static int eeprom_rd_phys(struct adapter *adap, unsigned int phys_addr, u32 *v)
{
int vaddr = eeprom_ptov(phys_addr, adap->fn, EEPROMPFSIZE);
if (vaddr >= 0)
vaddr = pci_read_vpd(adap->pdev, vaddr, sizeof(u32), v);
return vaddr < 0 ? vaddr : 0;
}
static int eeprom_wr_phys(struct adapter *adap, unsigned int phys_addr, u32 v)
{
int vaddr = eeprom_ptov(phys_addr, adap->fn, EEPROMPFSIZE);
if (vaddr >= 0)
vaddr = pci_write_vpd(adap->pdev, vaddr, sizeof(u32), &v);
return vaddr < 0 ? vaddr : 0;
}
#define EEPROM_MAGIC 0x38E2F10C
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 *data)
{
int i, err = 0;
struct adapter *adapter = netdev2adap(dev);
u8 *buf = kmalloc(EEPROMSIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
e->magic = EEPROM_MAGIC;
for (i = e->offset & ~3; !err && i < e->offset + e->len; i += 4)
err = eeprom_rd_phys(adapter, i, (u32 *)&buf[i]);
if (!err)
memcpy(data, buf + e->offset, e->len);
kfree(buf);
return err;
}
static int set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 *data)
{
u8 *buf;
int err = 0;
u32 aligned_offset, aligned_len, *p;
struct adapter *adapter = netdev2adap(dev);
if (eeprom->magic != EEPROM_MAGIC)
return -EINVAL;
aligned_offset = eeprom->offset & ~3;
aligned_len = (eeprom->len + (eeprom->offset & 3) + 3) & ~3;
if (adapter->fn > 0) {
u32 start = 1024 + adapter->fn * EEPROMPFSIZE;
if (aligned_offset < start ||
aligned_offset + aligned_len > start + EEPROMPFSIZE)
return -EPERM;
}
if (aligned_offset != eeprom->offset || aligned_len != eeprom->len) {
/*
* RMW possibly needed for first or last words.
*/
buf = kmalloc(aligned_len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
err = eeprom_rd_phys(adapter, aligned_offset, (u32 *)buf);
if (!err && aligned_len > 4)
err = eeprom_rd_phys(adapter,
aligned_offset + aligned_len - 4,
(u32 *)&buf[aligned_len - 4]);
if (err)
goto out;
memcpy(buf + (eeprom->offset & 3), data, eeprom->len);
} else
buf = data;
err = t4_seeprom_wp(adapter, false);
if (err)
goto out;
for (p = (u32 *)buf; !err && aligned_len; aligned_len -= 4, p++) {
err = eeprom_wr_phys(adapter, aligned_offset, *p);
aligned_offset += 4;
}
if (!err)
err = t4_seeprom_wp(adapter, true);
out:
if (buf != data)
kfree(buf);
return err;
}
static int set_flash(struct net_device *netdev, struct ethtool_flash *ef)
{
int ret;
const struct firmware *fw;
struct adapter *adap = netdev2adap(netdev);
ef->data[sizeof(ef->data) - 1] = '\0';
ret = request_firmware(&fw, ef->data, adap->pdev_dev);
if (ret < 0)
return ret;
ret = t4_load_fw(adap, fw->data, fw->size);
release_firmware(fw);
if (!ret)
dev_info(adap->pdev_dev, "loaded firmware %s\n", ef->data);
return ret;
}
#define WOL_SUPPORTED (WAKE_BCAST | WAKE_MAGIC)
#define BCAST_CRC 0xa0ccc1a6
static void get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
wol->supported = WAKE_BCAST | WAKE_MAGIC;
wol->wolopts = netdev2adap(dev)->wol;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
int err = 0;
struct port_info *pi = netdev_priv(dev);
if (wol->wolopts & ~WOL_SUPPORTED)
return -EINVAL;
t4_wol_magic_enable(pi->adapter, pi->tx_chan,
(wol->wolopts & WAKE_MAGIC) ? dev->dev_addr : NULL);
if (wol->wolopts & WAKE_BCAST) {
err = t4_wol_pat_enable(pi->adapter, pi->tx_chan, 0xfe, ~0ULL,
~0ULL, 0, false);
if (!err)
err = t4_wol_pat_enable(pi->adapter, pi->tx_chan, 1,
~6ULL, ~0ULL, BCAST_CRC, true);
} else
t4_wol_pat_enable(pi->adapter, pi->tx_chan, 0, 0, 0, 0, false);
return err;
}
static int cxgb_set_features(struct net_device *dev, netdev_features_t features)
{
const struct port_info *pi = netdev_priv(dev);
netdev_features_t changed = dev->features ^ features;
int err;
if (!(changed & NETIF_F_HW_VLAN_CTAG_RX))
return 0;
err = t4_set_rxmode(pi->adapter, pi->adapter->fn, pi->viid, -1,
-1, -1, -1,
!!(features & NETIF_F_HW_VLAN_CTAG_RX), true);
if (unlikely(err))
dev->features = features ^ NETIF_F_HW_VLAN_CTAG_RX;
return err;
}
static u32 get_rss_table_size(struct net_device *dev)
{
const struct port_info *pi = netdev_priv(dev);
return pi->rss_size;
}
static int get_rss_table(struct net_device *dev, u32 *p)
{
const struct port_info *pi = netdev_priv(dev);
unsigned int n = pi->rss_size;
while (n--)
p[n] = pi->rss[n];
return 0;
}
static int set_rss_table(struct net_device *dev, const u32 *p)
{
unsigned int i;
struct port_info *pi = netdev_priv(dev);
for (i = 0; i < pi->rss_size; i++)
pi->rss[i] = p[i];
if (pi->adapter->flags & FULL_INIT_DONE)
return write_rss(pi, pi->rss);
return 0;
}
static int get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info,
u32 *rules)
{
const struct port_info *pi = netdev_priv(dev);
switch (info->cmd) {
case ETHTOOL_GRXFH: {
unsigned int v = pi->rss_mode;
info->data = 0;
switch (info->flow_type) {
case TCP_V4_FLOW:
if (v & FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST |
RXH_L4_B_0_1 | RXH_L4_B_2_3;
else if (v & FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
case UDP_V4_FLOW:
if ((v & FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN) &&
(v & FW_RSS_VI_CONFIG_CMD_UDPEN))
info->data = RXH_IP_SRC | RXH_IP_DST |
RXH_L4_B_0_1 | RXH_L4_B_2_3;
else if (v & FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
case SCTP_V4_FLOW:
case AH_ESP_V4_FLOW:
case IPV4_FLOW:
if (v & FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
case TCP_V6_FLOW:
if (v & FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST |
RXH_L4_B_0_1 | RXH_L4_B_2_3;
else if (v & FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
case UDP_V6_FLOW:
if ((v & FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN) &&
(v & FW_RSS_VI_CONFIG_CMD_UDPEN))
info->data = RXH_IP_SRC | RXH_IP_DST |
RXH_L4_B_0_1 | RXH_L4_B_2_3;
else if (v & FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
case SCTP_V6_FLOW:
case AH_ESP_V6_FLOW:
case IPV6_FLOW:
if (v & FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
info->data = RXH_IP_SRC | RXH_IP_DST;
break;
}
return 0;
}
case ETHTOOL_GRXRINGS:
info->data = pi->nqsets;
return 0;
}
return -EOPNOTSUPP;
}
static const struct ethtool_ops cxgb_ethtool_ops = {
.get_settings = get_settings,
.set_settings = set_settings,
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.set_eeprom = set_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.set_phys_id = identify_port,
.nway_reset = restart_autoneg,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
.get_wol = get_wol,
.set_wol = set_wol,
.get_rxnfc = get_rxnfc,
.get_rxfh_indir_size = get_rss_table_size,
.get_rxfh_indir = get_rss_table,
.set_rxfh_indir = set_rss_table,
.flash_device = set_flash,
};
/*
* debugfs support
*/
static ssize_t mem_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
loff_t pos = *ppos;
loff_t avail = file_inode(file)->i_size;
unsigned int mem = (uintptr_t)file->private_data & 3;
struct adapter *adap = file->private_data - mem;
if (pos < 0)
return -EINVAL;
if (pos >= avail)
return 0;
if (count > avail - pos)
count = avail - pos;
while (count) {
size_t len;
int ret, ofst;
__be32 data[16];
if ((mem == MEM_MC) || (mem == MEM_MC1))
ret = t4_mc_read(adap, mem % MEM_MC, pos, data, NULL);
else
ret = t4_edc_read(adap, mem, pos, data, NULL);
if (ret)
return ret;
ofst = pos % sizeof(data);
len = min(count, sizeof(data) - ofst);
if (copy_to_user(buf, (u8 *)data + ofst, len))
return -EFAULT;
buf += len;
pos += len;
count -= len;
}
count = pos - *ppos;
*ppos = pos;
return count;
}
static const struct file_operations mem_debugfs_fops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = mem_read,
.llseek = default_llseek,
};
static void add_debugfs_mem(struct adapter *adap, const char *name,
unsigned int idx, unsigned int size_mb)
{
struct dentry *de;
de = debugfs_create_file(name, S_IRUSR, adap->debugfs_root,
(void *)adap + idx, &mem_debugfs_fops);
if (de && de->d_inode)
de->d_inode->i_size = size_mb << 20;
}
static int setup_debugfs(struct adapter *adap)
{
int i;
u32 size;
if (IS_ERR_OR_NULL(adap->debugfs_root))
return -1;
i = t4_read_reg(adap, MA_TARGET_MEM_ENABLE);
if (i & EDRAM0_ENABLE) {
size = t4_read_reg(adap, MA_EDRAM0_BAR);
add_debugfs_mem(adap, "edc0", MEM_EDC0, EDRAM_SIZE_GET(size));
}
if (i & EDRAM1_ENABLE) {
size = t4_read_reg(adap, MA_EDRAM1_BAR);
add_debugfs_mem(adap, "edc1", MEM_EDC1, EDRAM_SIZE_GET(size));
}
if (is_t4(adap->params.chip)) {
size = t4_read_reg(adap, MA_EXT_MEMORY_BAR);
if (i & EXT_MEM_ENABLE)
add_debugfs_mem(adap, "mc", MEM_MC,
EXT_MEM_SIZE_GET(size));
} else {
if (i & EXT_MEM_ENABLE) {
size = t4_read_reg(adap, MA_EXT_MEMORY_BAR);
add_debugfs_mem(adap, "mc0", MEM_MC0,
EXT_MEM_SIZE_GET(size));
}
if (i & EXT_MEM1_ENABLE) {
size = t4_read_reg(adap, MA_EXT_MEMORY1_BAR);
add_debugfs_mem(adap, "mc1", MEM_MC1,
EXT_MEM_SIZE_GET(size));
}
}
if (adap->l2t)
debugfs_create_file("l2t", S_IRUSR, adap->debugfs_root, adap,
&t4_l2t_fops);
return 0;
}
/*
* upper-layer driver support
*/
/*
* Allocate an active-open TID and set it to the supplied value.
*/
int cxgb4_alloc_atid(struct tid_info *t, void *data)
{
int atid = -1;
spin_lock_bh(&t->atid_lock);
if (t->afree) {
union aopen_entry *p = t->afree;
atid = (p - t->atid_tab) + t->atid_base;
t->afree = p->next;
p->data = data;
t->atids_in_use++;
}
spin_unlock_bh(&t->atid_lock);
return atid;
}
EXPORT_SYMBOL(cxgb4_alloc_atid);
/*
* Release an active-open TID.
*/
void cxgb4_free_atid(struct tid_info *t, unsigned int atid)
{
union aopen_entry *p = &t->atid_tab[atid - t->atid_base];
spin_lock_bh(&t->atid_lock);
p->next = t->afree;
t->afree = p;
t->atids_in_use--;
spin_unlock_bh(&t->atid_lock);
}
EXPORT_SYMBOL(cxgb4_free_atid);
/*
* Allocate a server TID and set it to the supplied value.
*/
int cxgb4_alloc_stid(struct tid_info *t, int family, void *data)
{
int stid;
spin_lock_bh(&t->stid_lock);
if (family == PF_INET) {
stid = find_first_zero_bit(t->stid_bmap, t->nstids);
if (stid < t->nstids)
__set_bit(stid, t->stid_bmap);
else
stid = -1;
} else {
stid = bitmap_find_free_region(t->stid_bmap, t->nstids, 2);
if (stid < 0)
stid = -1;
}
if (stid >= 0) {
t->stid_tab[stid].data = data;
stid += t->stid_base;
/* IPv6 requires max of 520 bits or 16 cells in TCAM
* This is equivalent to 4 TIDs. With CLIP enabled it
* needs 2 TIDs.
*/
if (family == PF_INET)
t->stids_in_use++;
else
t->stids_in_use += 4;
}
spin_unlock_bh(&t->stid_lock);
return stid;
}
EXPORT_SYMBOL(cxgb4_alloc_stid);
/* Allocate a server filter TID and set it to the supplied value.
*/
int cxgb4_alloc_sftid(struct tid_info *t, int family, void *data)
{
int stid;
spin_lock_bh(&t->stid_lock);
if (family == PF_INET) {
stid = find_next_zero_bit(t->stid_bmap,
t->nstids + t->nsftids, t->nstids);
if (stid < (t->nstids + t->nsftids))
__set_bit(stid, t->stid_bmap);
else
stid = -1;
} else {
stid = -1;
}
if (stid >= 0) {
t->stid_tab[stid].data = data;
stid -= t->nstids;
stid += t->sftid_base;
t->stids_in_use++;
}
spin_unlock_bh(&t->stid_lock);
return stid;
}
EXPORT_SYMBOL(cxgb4_alloc_sftid);
/* Release a server TID.
*/
void cxgb4_free_stid(struct tid_info *t, unsigned int stid, int family)
{
/* Is it a server filter TID? */
if (t->nsftids && (stid >= t->sftid_base)) {
stid -= t->sftid_base;
stid += t->nstids;
} else {
stid -= t->stid_base;
}
spin_lock_bh(&t->stid_lock);
if (family == PF_INET)
__clear_bit(stid, t->stid_bmap);
else
bitmap_release_region(t->stid_bmap, stid, 2);
t->stid_tab[stid].data = NULL;
if (family == PF_INET)
t->stids_in_use--;
else
t->stids_in_use -= 4;
spin_unlock_bh(&t->stid_lock);
}
EXPORT_SYMBOL(cxgb4_free_stid);
/*
* Populate a TID_RELEASE WR. Caller must properly size the skb.
*/
static void mk_tid_release(struct sk_buff *skb, unsigned int chan,
unsigned int tid)
{
struct cpl_tid_release *req;
set_wr_txq(skb, CPL_PRIORITY_SETUP, chan);
req = (struct cpl_tid_release *)__skb_put(skb, sizeof(*req));
INIT_TP_WR(req, tid);
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_TID_RELEASE, tid));
}
/*
* Queue a TID release request and if necessary schedule a work queue to
* process it.
*/
static void cxgb4_queue_tid_release(struct tid_info *t, unsigned int chan,
unsigned int tid)
{
void **p = &t->tid_tab[tid];
struct adapter *adap = container_of(t, struct adapter, tids);
spin_lock_bh(&adap->tid_release_lock);
*p = adap->tid_release_head;
/* Low 2 bits encode the Tx channel number */
adap->tid_release_head = (void **)((uintptr_t)p | chan);
if (!adap->tid_release_task_busy) {
adap->tid_release_task_busy = true;
queue_work(workq, &adap->tid_release_task);
}
spin_unlock_bh(&adap->tid_release_lock);
}
/*
* Process the list of pending TID release requests.
*/
static void process_tid_release_list(struct work_struct *work)
{
struct sk_buff *skb;
struct adapter *adap;
adap = container_of(work, struct adapter, tid_release_task);
spin_lock_bh(&adap->tid_release_lock);
while (adap->tid_release_head) {
void **p = adap->tid_release_head;
unsigned int chan = (uintptr_t)p & 3;
p = (void *)p - chan;
adap->tid_release_head = *p;
*p = NULL;
spin_unlock_bh(&adap->tid_release_lock);
while (!(skb = alloc_skb(sizeof(struct cpl_tid_release),
GFP_KERNEL)))
schedule_timeout_uninterruptible(1);
mk_tid_release(skb, chan, p - adap->tids.tid_tab);
t4_ofld_send(adap, skb);
spin_lock_bh(&adap->tid_release_lock);
}
adap->tid_release_task_busy = false;
spin_unlock_bh(&adap->tid_release_lock);
}
/*
* Release a TID and inform HW. If we are unable to allocate the release
* message we defer to a work queue.
*/
void cxgb4_remove_tid(struct tid_info *t, unsigned int chan, unsigned int tid)
{
void *old;
struct sk_buff *skb;
struct adapter *adap = container_of(t, struct adapter, tids);
old = t->tid_tab[tid];
skb = alloc_skb(sizeof(struct cpl_tid_release), GFP_ATOMIC);
if (likely(skb)) {
t->tid_tab[tid] = NULL;
mk_tid_release(skb, chan, tid);
t4_ofld_send(adap, skb);
} else
cxgb4_queue_tid_release(t, chan, tid);
if (old)
atomic_dec(&t->tids_in_use);
}
EXPORT_SYMBOL(cxgb4_remove_tid);
/*
* Allocate and initialize the TID tables. Returns 0 on success.
*/
static int tid_init(struct tid_info *t)
{
size_t size;
unsigned int stid_bmap_size;
unsigned int natids = t->natids;
struct adapter *adap = container_of(t, struct adapter, tids);
stid_bmap_size = BITS_TO_LONGS(t->nstids + t->nsftids);
size = t->ntids * sizeof(*t->tid_tab) +
natids * sizeof(*t->atid_tab) +
t->nstids * sizeof(*t->stid_tab) +
t->nsftids * sizeof(*t->stid_tab) +
stid_bmap_size * sizeof(long) +
t->nftids * sizeof(*t->ftid_tab) +
t->nsftids * sizeof(*t->ftid_tab);
t->tid_tab = t4_alloc_mem(size);
if (!t->tid_tab)
return -ENOMEM;
t->atid_tab = (union aopen_entry *)&t->tid_tab[t->ntids];
t->stid_tab = (struct serv_entry *)&t->atid_tab[natids];
t->stid_bmap = (unsigned long *)&t->stid_tab[t->nstids + t->nsftids];
t->ftid_tab = (struct filter_entry *)&t->stid_bmap[stid_bmap_size];
spin_lock_init(&t->stid_lock);
spin_lock_init(&t->atid_lock);
t->stids_in_use = 0;
t->afree = NULL;
t->atids_in_use = 0;
atomic_set(&t->tids_in_use, 0);
/* Setup the free list for atid_tab and clear the stid bitmap. */
if (natids) {
while (--natids)
t->atid_tab[natids - 1].next = &t->atid_tab[natids];
t->afree = t->atid_tab;
}
bitmap_zero(t->stid_bmap, t->nstids + t->nsftids);
/* Reserve stid 0 for T4/T5 adapters */
if (!t->stid_base &&
(is_t4(adap->params.chip) || is_t5(adap->params.chip)))
__set_bit(0, t->stid_bmap);
return 0;
}
static int cxgb4_clip_get(const struct net_device *dev,
const struct in6_addr *lip)
{
struct adapter *adap;
struct fw_clip_cmd c;
adap = netdev2adap(dev);
memset(&c, 0, sizeof(c));
c.op_to_write = htonl(FW_CMD_OP(FW_CLIP_CMD) |
FW_CMD_REQUEST | FW_CMD_WRITE);
c.alloc_to_len16 = htonl(F_FW_CLIP_CMD_ALLOC | FW_LEN16(c));
*(__be64 *)&c.ip_hi = *(__be64 *)(lip->s6_addr);
*(__be64 *)&c.ip_lo = *(__be64 *)(lip->s6_addr + 8);
return t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, false);
}
static int cxgb4_clip_release(const struct net_device *dev,
const struct in6_addr *lip)
{
struct adapter *adap;
struct fw_clip_cmd c;
adap = netdev2adap(dev);
memset(&c, 0, sizeof(c));
c.op_to_write = htonl(FW_CMD_OP(FW_CLIP_CMD) |
FW_CMD_REQUEST | FW_CMD_READ);
c.alloc_to_len16 = htonl(F_FW_CLIP_CMD_FREE | FW_LEN16(c));
*(__be64 *)&c.ip_hi = *(__be64 *)(lip->s6_addr);
*(__be64 *)&c.ip_lo = *(__be64 *)(lip->s6_addr + 8);
return t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, false);
}
/**
* cxgb4_create_server - create an IP server
* @dev: the device
* @stid: the server TID
* @sip: local IP address to bind server to
* @sport: the server's TCP port
* @queue: queue to direct messages from this server to
*
* Create an IP server for the given port and address.
* Returns <0 on error and one of the %NET_XMIT_* values on success.
*/
int cxgb4_create_server(const struct net_device *dev, unsigned int stid,
__be32 sip, __be16 sport, __be16 vlan,
unsigned int queue)
{
unsigned int chan;
struct sk_buff *skb;
struct adapter *adap;
struct cpl_pass_open_req *req;
int ret;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
return -ENOMEM;
adap = netdev2adap(dev);
req = (struct cpl_pass_open_req *)__skb_put(skb, sizeof(*req));
INIT_TP_WR(req, 0);
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_PASS_OPEN_REQ, stid));
req->local_port = sport;
req->peer_port = htons(0);
req->local_ip = sip;
req->peer_ip = htonl(0);
chan = rxq_to_chan(&adap->sge, queue);
req->opt0 = cpu_to_be64(TX_CHAN(chan));
req->opt1 = cpu_to_be64(CONN_POLICY_ASK |
SYN_RSS_ENABLE | SYN_RSS_QUEUE(queue));
ret = t4_mgmt_tx(adap, skb);
return net_xmit_eval(ret);
}
EXPORT_SYMBOL(cxgb4_create_server);
/* cxgb4_create_server6 - create an IPv6 server
* @dev: the device
* @stid: the server TID
* @sip: local IPv6 address to bind server to
* @sport: the server's TCP port
* @queue: queue to direct messages from this server to
*
* Create an IPv6 server for the given port and address.
* Returns <0 on error and one of the %NET_XMIT_* values on success.
*/
int cxgb4_create_server6(const struct net_device *dev, unsigned int stid,
const struct in6_addr *sip, __be16 sport,
unsigned int queue)
{
unsigned int chan;
struct sk_buff *skb;
struct adapter *adap;
struct cpl_pass_open_req6 *req;
int ret;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
return -ENOMEM;
adap = netdev2adap(dev);
req = (struct cpl_pass_open_req6 *)__skb_put(skb, sizeof(*req));
INIT_TP_WR(req, 0);
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_PASS_OPEN_REQ6, stid));
req->local_port = sport;
req->peer_port = htons(0);
req->local_ip_hi = *(__be64 *)(sip->s6_addr);
req->local_ip_lo = *(__be64 *)(sip->s6_addr + 8);
req->peer_ip_hi = cpu_to_be64(0);
req->peer_ip_lo = cpu_to_be64(0);
chan = rxq_to_chan(&adap->sge, queue);
req->opt0 = cpu_to_be64(TX_CHAN(chan));
req->opt1 = cpu_to_be64(CONN_POLICY_ASK |
SYN_RSS_ENABLE | SYN_RSS_QUEUE(queue));
ret = t4_mgmt_tx(adap, skb);
return net_xmit_eval(ret);
}
EXPORT_SYMBOL(cxgb4_create_server6);
int cxgb4_remove_server(const struct net_device *dev, unsigned int stid,
unsigned int queue, bool ipv6)
{
struct sk_buff *skb;
struct adapter *adap;
struct cpl_close_listsvr_req *req;
int ret;
adap = netdev2adap(dev);
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
return -ENOMEM;
req = (struct cpl_close_listsvr_req *)__skb_put(skb, sizeof(*req));
INIT_TP_WR(req, 0);
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_CLOSE_LISTSRV_REQ, stid));
req->reply_ctrl = htons(NO_REPLY(0) | (ipv6 ? LISTSVR_IPV6(1) :
LISTSVR_IPV6(0)) | QUEUENO(queue));
ret = t4_mgmt_tx(adap, skb);
return net_xmit_eval(ret);
}
EXPORT_SYMBOL(cxgb4_remove_server);
/**
* cxgb4_best_mtu - find the entry in the MTU table closest to an MTU
* @mtus: the HW MTU table
* @mtu: the target MTU
* @idx: index of selected entry in the MTU table
*
* Returns the index and the value in the HW MTU table that is closest to
* but does not exceed @mtu, unless @mtu is smaller than any value in the
* table, in which case that smallest available value is selected.
*/
unsigned int cxgb4_best_mtu(const unsigned short *mtus, unsigned short mtu,
unsigned int *idx)
{
unsigned int i = 0;
while (i < NMTUS - 1 && mtus[i + 1] <= mtu)
++i;
if (idx)
*idx = i;
return mtus[i];
}
EXPORT_SYMBOL(cxgb4_best_mtu);
/**
* cxgb4_port_chan - get the HW channel of a port
* @dev: the net device for the port
*
* Return the HW Tx channel of the given port.
*/
unsigned int cxgb4_port_chan(const struct net_device *dev)
{
return netdev2pinfo(dev)->tx_chan;
}
EXPORT_SYMBOL(cxgb4_port_chan);
unsigned int cxgb4_dbfifo_count(const struct net_device *dev, int lpfifo)
{
struct adapter *adap = netdev2adap(dev);
u32 v1, v2, lp_count, hp_count;
v1 = t4_read_reg(adap, A_SGE_DBFIFO_STATUS);
v2 = t4_read_reg(adap, SGE_DBFIFO_STATUS2);
if (is_t4(adap->params.chip)) {
lp_count = G_LP_COUNT(v1);
hp_count = G_HP_COUNT(v1);
} else {
lp_count = G_LP_COUNT_T5(v1);
hp_count = G_HP_COUNT_T5(v2);
}
return lpfifo ? lp_count : hp_count;
}
EXPORT_SYMBOL(cxgb4_dbfifo_count);
/**
* cxgb4_port_viid - get the VI id of a port
* @dev: the net device for the port
*
* Return the VI id of the given port.
*/
unsigned int cxgb4_port_viid(const struct net_device *dev)
{
return netdev2pinfo(dev)->viid;
}
EXPORT_SYMBOL(cxgb4_port_viid);
/**
* cxgb4_port_idx - get the index of a port
* @dev: the net device for the port
*
* Return the index of the given port.
*/
unsigned int cxgb4_port_idx(const struct net_device *dev)
{
return netdev2pinfo(dev)->port_id;
}
EXPORT_SYMBOL(cxgb4_port_idx);
void cxgb4_get_tcp_stats(struct pci_dev *pdev, struct tp_tcp_stats *v4,
struct tp_tcp_stats *v6)
{
struct adapter *adap = pci_get_drvdata(pdev);
spin_lock(&adap->stats_lock);
t4_tp_get_tcp_stats(adap, v4, v6);
spin_unlock(&adap->stats_lock);
}
EXPORT_SYMBOL(cxgb4_get_tcp_stats);
void cxgb4_iscsi_init(struct net_device *dev, unsigned int tag_mask,
const unsigned int *pgsz_order)
{
struct adapter *adap = netdev2adap(dev);
t4_write_reg(adap, ULP_RX_ISCSI_TAGMASK, tag_mask);
t4_write_reg(adap, ULP_RX_ISCSI_PSZ, HPZ0(pgsz_order[0]) |
HPZ1(pgsz_order[1]) | HPZ2(pgsz_order[2]) |
HPZ3(pgsz_order[3]));
}
EXPORT_SYMBOL(cxgb4_iscsi_init);
int cxgb4_flush_eq_cache(struct net_device *dev)
{
struct adapter *adap = netdev2adap(dev);
int ret;
ret = t4_fwaddrspace_write(adap, adap->mbox,
0xe1000000 + A_SGE_CTXT_CMD, 0x20000000);
return ret;
}
EXPORT_SYMBOL(cxgb4_flush_eq_cache);
static int read_eq_indices(struct adapter *adap, u16 qid, u16 *pidx, u16 *cidx)
{
u32 addr = t4_read_reg(adap, A_SGE_DBQ_CTXT_BADDR) + 24 * qid + 8;
__be64 indices;
int ret;
ret = t4_mem_win_read_len(adap, addr, (__be32 *)&indices, 8);
if (!ret) {
*cidx = (be64_to_cpu(indices) >> 25) & 0xffff;
*pidx = (be64_to_cpu(indices) >> 9) & 0xffff;
}
return ret;
}
int cxgb4_sync_txq_pidx(struct net_device *dev, u16 qid, u16 pidx,
u16 size)
{
struct adapter *adap = netdev2adap(dev);
u16 hw_pidx, hw_cidx;
int ret;
ret = read_eq_indices(adap, qid, &hw_pidx, &hw_cidx);
if (ret)
goto out;
if (pidx != hw_pidx) {
u16 delta;
if (pidx >= hw_pidx)
delta = pidx - hw_pidx;
else
delta = size - hw_pidx + pidx;
wmb();
t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL),
QID(qid) | PIDX(delta));
}
out:
return ret;
}
EXPORT_SYMBOL(cxgb4_sync_txq_pidx);
void cxgb4_disable_db_coalescing(struct net_device *dev)
{
struct adapter *adap;
adap = netdev2adap(dev);
t4_set_reg_field(adap, A_SGE_DOORBELL_CONTROL, F_NOCOALESCE,
F_NOCOALESCE);
}
EXPORT_SYMBOL(cxgb4_disable_db_coalescing);
void cxgb4_enable_db_coalescing(struct net_device *dev)
{
struct adapter *adap;
adap = netdev2adap(dev);
t4_set_reg_field(adap, A_SGE_DOORBELL_CONTROL, F_NOCOALESCE, 0);
}
EXPORT_SYMBOL(cxgb4_enable_db_coalescing);
static struct pci_driver cxgb4_driver;
static void check_neigh_update(struct neighbour *neigh)
{
const struct device *parent;
const struct net_device *netdev = neigh->dev;
if (netdev->priv_flags & IFF_802_1Q_VLAN)
netdev = vlan_dev_real_dev(netdev);
parent = netdev->dev.parent;
if (parent && parent->driver == &cxgb4_driver.driver)
t4_l2t_update(dev_get_drvdata(parent), neigh);
}
static int netevent_cb(struct notifier_block *nb, unsigned long event,
void *data)
{
switch (event) {
case NETEVENT_NEIGH_UPDATE:
check_neigh_update(data);
break;
case NETEVENT_REDIRECT:
default:
break;
}
return 0;
}
static bool netevent_registered;
static struct notifier_block cxgb4_netevent_nb = {
.notifier_call = netevent_cb
};
static void drain_db_fifo(struct adapter *adap, int usecs)
{
u32 v1, v2, lp_count, hp_count;
do {
v1 = t4_read_reg(adap, A_SGE_DBFIFO_STATUS);
v2 = t4_read_reg(adap, SGE_DBFIFO_STATUS2);
if (is_t4(adap->params.chip)) {
lp_count = G_LP_COUNT(v1);
hp_count = G_HP_COUNT(v1);
} else {
lp_count = G_LP_COUNT_T5(v1);
hp_count = G_HP_COUNT_T5(v2);
}
if (lp_count == 0 && hp_count == 0)
break;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(usecs_to_jiffies(usecs));
} while (1);
}
static void disable_txq_db(struct sge_txq *q)
{
spin_lock_irq(&q->db_lock);
q->db_disabled = 1;
spin_unlock_irq(&q->db_lock);
}
static void enable_txq_db(struct sge_txq *q)
{
spin_lock_irq(&q->db_lock);
q->db_disabled = 0;
spin_unlock_irq(&q->db_lock);
}
static void disable_dbs(struct adapter *adap)
{
int i;
for_each_ethrxq(&adap->sge, i)
disable_txq_db(&adap->sge.ethtxq[i].q);
for_each_ofldrxq(&adap->sge, i)
disable_txq_db(&adap->sge.ofldtxq[i].q);
for_each_port(adap, i)
disable_txq_db(&adap->sge.ctrlq[i].q);
}
static void enable_dbs(struct adapter *adap)
{
int i;
for_each_ethrxq(&adap->sge, i)
enable_txq_db(&adap->sge.ethtxq[i].q);
for_each_ofldrxq(&adap->sge, i)
enable_txq_db(&adap->sge.ofldtxq[i].q);
for_each_port(adap, i)
enable_txq_db(&adap->sge.ctrlq[i].q);
}
static void sync_txq_pidx(struct adapter *adap, struct sge_txq *q)
{
u16 hw_pidx, hw_cidx;
int ret;
spin_lock_bh(&q->db_lock);
ret = read_eq_indices(adap, (u16)q->cntxt_id, &hw_pidx, &hw_cidx);
if (ret)
goto out;
if (q->db_pidx != hw_pidx) {
u16 delta;
if (q->db_pidx >= hw_pidx)
delta = q->db_pidx - hw_pidx;
else
delta = q->size - hw_pidx + q->db_pidx;
wmb();
t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL),
QID(q->cntxt_id) | PIDX(delta));
}
out:
q->db_disabled = 0;
spin_unlock_bh(&q->db_lock);
if (ret)
CH_WARN(adap, "DB drop recovery failed.\n");
}
static void recover_all_queues(struct adapter *adap)
{
int i;
for_each_ethrxq(&adap->sge, i)
sync_txq_pidx(adap, &adap->sge.ethtxq[i].q);
for_each_ofldrxq(&adap->sge, i)
sync_txq_pidx(adap, &adap->sge.ofldtxq[i].q);
for_each_port(adap, i)
sync_txq_pidx(adap, &adap->sge.ctrlq[i].q);
}
static void notify_rdma_uld(struct adapter *adap, enum cxgb4_control cmd)
{
mutex_lock(&uld_mutex);
if (adap->uld_handle[CXGB4_ULD_RDMA])
ulds[CXGB4_ULD_RDMA].control(adap->uld_handle[CXGB4_ULD_RDMA],
cmd);
mutex_unlock(&uld_mutex);
}
static void process_db_full(struct work_struct *work)
{
struct adapter *adap;
adap = container_of(work, struct adapter, db_full_task);
notify_rdma_uld(adap, CXGB4_CONTROL_DB_FULL);
drain_db_fifo(adap, dbfifo_drain_delay);
t4_set_reg_field(adap, SGE_INT_ENABLE3,
DBFIFO_HP_INT | DBFIFO_LP_INT,
DBFIFO_HP_INT | DBFIFO_LP_INT);
notify_rdma_uld(adap, CXGB4_CONTROL_DB_EMPTY);
}
static void process_db_drop(struct work_struct *work)
{
struct adapter *adap;
adap = container_of(work, struct adapter, db_drop_task);
if (is_t4(adap->params.chip)) {
disable_dbs(adap);
notify_rdma_uld(adap, CXGB4_CONTROL_DB_DROP);
drain_db_fifo(adap, 1);
recover_all_queues(adap);
enable_dbs(adap);
} else {
u32 dropped_db = t4_read_reg(adap, 0x010ac);
u16 qid = (dropped_db >> 15) & 0x1ffff;
u16 pidx_inc = dropped_db & 0x1fff;
unsigned int s_qpp;
unsigned short udb_density;
unsigned long qpshift;
int page;
u32 udb;
dev_warn(adap->pdev_dev,
"Dropped DB 0x%x qid %d bar2 %d coalesce %d pidx %d\n",
dropped_db, qid,
(dropped_db >> 14) & 1,
(dropped_db >> 13) & 1,
pidx_inc);
drain_db_fifo(adap, 1);
s_qpp = QUEUESPERPAGEPF1 * adap->fn;
udb_density = 1 << QUEUESPERPAGEPF0_GET(t4_read_reg(adap,
SGE_EGRESS_QUEUES_PER_PAGE_PF) >> s_qpp);
qpshift = PAGE_SHIFT - ilog2(udb_density);
udb = qid << qpshift;
udb &= PAGE_MASK;
page = udb / PAGE_SIZE;
udb += (qid - (page * udb_density)) * 128;
writel(PIDX(pidx_inc), adap->bar2 + udb + 8);
/* Re-enable BAR2 WC */
t4_set_reg_field(adap, 0x10b0, 1<<15, 1<<15);
}
t4_set_reg_field(adap, A_SGE_DOORBELL_CONTROL, F_DROPPED_DB, 0);
}
void t4_db_full(struct adapter *adap)
{
if (is_t4(adap->params.chip)) {
t4_set_reg_field(adap, SGE_INT_ENABLE3,
DBFIFO_HP_INT | DBFIFO_LP_INT, 0);
queue_work(workq, &adap->db_full_task);
}
}
void t4_db_dropped(struct adapter *adap)
{
if (is_t4(adap->params.chip))
queue_work(workq, &adap->db_drop_task);
}
static void uld_attach(struct adapter *adap, unsigned int uld)
{
void *handle;
struct cxgb4_lld_info lli;
unsigned short i;
lli.pdev = adap->pdev;
lli.l2t = adap->l2t;
lli.tids = &adap->tids;
lli.ports = adap->port;
lli.vr = &adap->vres;
lli.mtus = adap->params.mtus;
if (uld == CXGB4_ULD_RDMA) {
lli.rxq_ids = adap->sge.rdma_rxq;
lli.nrxq = adap->sge.rdmaqs;
} else if (uld == CXGB4_ULD_ISCSI) {
lli.rxq_ids = adap->sge.ofld_rxq;
lli.nrxq = adap->sge.ofldqsets;
}
lli.ntxq = adap->sge.ofldqsets;
lli.nchan = adap->params.nports;
lli.nports = adap->params.nports;
lli.wr_cred = adap->params.ofldq_wr_cred;
lli.adapter_type = adap->params.chip;
lli.iscsi_iolen = MAXRXDATA_GET(t4_read_reg(adap, TP_PARA_REG2));
lli.udb_density = 1 << QUEUESPERPAGEPF0_GET(
t4_read_reg(adap, SGE_EGRESS_QUEUES_PER_PAGE_PF) >>
(adap->fn * 4));
lli.ucq_density = 1 << QUEUESPERPAGEPF0_GET(
t4_read_reg(adap, SGE_INGRESS_QUEUES_PER_PAGE_PF) >>
(adap->fn * 4));
lli.filt_mode = adap->params.tp.vlan_pri_map;
/* MODQ_REQ_MAP sets queues 0-3 to chan 0-3 */
for (i = 0; i < NCHAN; i++)
lli.tx_modq[i] = i;
lli.gts_reg = adap->regs + MYPF_REG(SGE_PF_GTS);
lli.db_reg = adap->regs + MYPF_REG(SGE_PF_KDOORBELL);
lli.fw_vers = adap->params.fw_vers;
lli.dbfifo_int_thresh = dbfifo_int_thresh;
lli.sge_pktshift = adap->sge.pktshift;
lli.enable_fw_ofld_conn = adap->flags & FW_OFLD_CONN;
handle = ulds[uld].add(&lli);
if (IS_ERR(handle)) {
dev_warn(adap->pdev_dev,
"could not attach to the %s driver, error %ld\n",
uld_str[uld], PTR_ERR(handle));
return;
}
adap->uld_handle[uld] = handle;
if (!netevent_registered) {
register_netevent_notifier(&cxgb4_netevent_nb);
netevent_registered = true;
}
if (adap->flags & FULL_INIT_DONE)
ulds[uld].state_change(handle, CXGB4_STATE_UP);
}
static void attach_ulds(struct adapter *adap)
{
unsigned int i;
spin_lock(&adap_rcu_lock);
list_add_tail_rcu(&adap->rcu_node, &adap_rcu_list);
spin_unlock(&adap_rcu_lock);
mutex_lock(&uld_mutex);
list_add_tail(&adap->list_node, &adapter_list);
for (i = 0; i < CXGB4_ULD_MAX; i++)
if (ulds[i].add)
uld_attach(adap, i);
mutex_unlock(&uld_mutex);
}
static void detach_ulds(struct adapter *adap)
{
unsigned int i;
mutex_lock(&uld_mutex);
list_del(&adap->list_node);
for (i = 0; i < CXGB4_ULD_MAX; i++)
if (adap->uld_handle[i]) {
ulds[i].state_change(adap->uld_handle[i],
CXGB4_STATE_DETACH);
adap->uld_handle[i] = NULL;
}
if (netevent_registered && list_empty(&adapter_list)) {
unregister_netevent_notifier(&cxgb4_netevent_nb);
netevent_registered = false;
}
mutex_unlock(&uld_mutex);
spin_lock(&adap_rcu_lock);
list_del_rcu(&adap->rcu_node);
spin_unlock(&adap_rcu_lock);
}
static void notify_ulds(struct adapter *adap, enum cxgb4_state new_state)
{
unsigned int i;
mutex_lock(&uld_mutex);
for (i = 0; i < CXGB4_ULD_MAX; i++)
if (adap->uld_handle[i])
ulds[i].state_change(adap->uld_handle[i], new_state);
mutex_unlock(&uld_mutex);
}
/**
* cxgb4_register_uld - register an upper-layer driver
* @type: the ULD type
* @p: the ULD methods
*
* Registers an upper-layer driver with this driver and notifies the ULD
* about any presently available devices that support its type. Returns
* %-EBUSY if a ULD of the same type is already registered.
*/
int cxgb4_register_uld(enum cxgb4_uld type, const struct cxgb4_uld_info *p)
{
int ret = 0;
struct adapter *adap;
if (type >= CXGB4_ULD_MAX)
return -EINVAL;
mutex_lock(&uld_mutex);
if (ulds[type].add) {
ret = -EBUSY;
goto out;
}
ulds[type] = *p;
list_for_each_entry(adap, &adapter_list, list_node)
uld_attach(adap, type);
out: mutex_unlock(&uld_mutex);
return ret;
}
EXPORT_SYMBOL(cxgb4_register_uld);
/**
* cxgb4_unregister_uld - unregister an upper-layer driver
* @type: the ULD type
*
* Unregisters an existing upper-layer driver.
*/
int cxgb4_unregister_uld(enum cxgb4_uld type)
{
struct adapter *adap;
if (type >= CXGB4_ULD_MAX)
return -EINVAL;
mutex_lock(&uld_mutex);
list_for_each_entry(adap, &adapter_list, list_node)
adap->uld_handle[type] = NULL;
ulds[type].add = NULL;
mutex_unlock(&uld_mutex);
return 0;
}
EXPORT_SYMBOL(cxgb4_unregister_uld);
/* Check if netdev on which event is occured belongs to us or not. Return
* suceess (1) if it belongs otherwise failure (0).
*/
static int cxgb4_netdev(struct net_device *netdev)
{
struct adapter *adap;
int i;
spin_lock(&adap_rcu_lock);
list_for_each_entry_rcu(adap, &adap_rcu_list, rcu_node)
for (i = 0; i < MAX_NPORTS; i++)
if (adap->port[i] == netdev) {
spin_unlock(&adap_rcu_lock);
return 1;
}
spin_unlock(&adap_rcu_lock);
return 0;
}
static int clip_add(struct net_device *event_dev, struct inet6_ifaddr *ifa,
unsigned long event)
{
int ret = NOTIFY_DONE;
rcu_read_lock();
if (cxgb4_netdev(event_dev)) {
switch (event) {
case NETDEV_UP:
ret = cxgb4_clip_get(event_dev,
(const struct in6_addr *)ifa->addr.s6_addr);
if (ret < 0) {
rcu_read_unlock();
return ret;
}
ret = NOTIFY_OK;
break;
case NETDEV_DOWN:
cxgb4_clip_release(event_dev,
(const struct in6_addr *)ifa->addr.s6_addr);
ret = NOTIFY_OK;
break;
default:
break;
}
}
rcu_read_unlock();
return ret;
}
static int cxgb4_inet6addr_handler(struct notifier_block *this,
unsigned long event, void *data)
{
struct inet6_ifaddr *ifa = data;
struct net_device *event_dev;
int ret = NOTIFY_DONE;
struct bonding *bond = netdev_priv(ifa->idev->dev);
struct list_head *iter;
struct slave *slave;
struct pci_dev *first_pdev = NULL;
if (ifa->idev->dev->priv_flags & IFF_802_1Q_VLAN) {
event_dev = vlan_dev_real_dev(ifa->idev->dev);
ret = clip_add(event_dev, ifa, event);
} else if (ifa->idev->dev->flags & IFF_MASTER) {
/* It is possible that two different adapters are bonded in one
* bond. We need to find such different adapters and add clip
* in all of them only once.
*/
read_lock(&bond->lock);
bond_for_each_slave(bond, slave, iter) {
if (!first_pdev) {
ret = clip_add(slave->dev, ifa, event);
/* If clip_add is success then only initialize
* first_pdev since it means it is our device
*/
if (ret == NOTIFY_OK)
first_pdev = to_pci_dev(
slave->dev->dev.parent);
} else if (first_pdev !=
to_pci_dev(slave->dev->dev.parent))
ret = clip_add(slave->dev, ifa, event);
}
read_unlock(&bond->lock);
} else
ret = clip_add(ifa->idev->dev, ifa, event);
return ret;
}
static struct notifier_block cxgb4_inet6addr_notifier = {
.notifier_call = cxgb4_inet6addr_handler
};
/* Retrieves IPv6 addresses from a root device (bond, vlan) associated with
* a physical device.
* The physical device reference is needed to send the actul CLIP command.
*/
static int update_dev_clip(struct net_device *root_dev, struct net_device *dev)
{
struct inet6_dev *idev = NULL;
struct inet6_ifaddr *ifa;
int ret = 0;
idev = __in6_dev_get(root_dev);
if (!idev)
return ret;
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
ret = cxgb4_clip_get(dev,
(const struct in6_addr *)ifa->addr.s6_addr);
if (ret < 0)
break;
}
read_unlock_bh(&idev->lock);
return ret;
}
static int update_root_dev_clip(struct net_device *dev)
{
struct net_device *root_dev = NULL;
int i, ret = 0;
/* First populate the real net device's IPv6 addresses */
ret = update_dev_clip(dev, dev);
if (ret)
return ret;
/* Parse all bond and vlan devices layered on top of the physical dev */
for (i = 0; i < VLAN_N_VID; i++) {
root_dev = __vlan_find_dev_deep(dev, htons(ETH_P_8021Q), i);
if (!root_dev)
continue;
ret = update_dev_clip(root_dev, dev);
if (ret)
break;
}
return ret;
}
static void update_clip(const struct adapter *adap)
{
int i;
struct net_device *dev;
int ret;
rcu_read_lock();
for (i = 0; i < MAX_NPORTS; i++) {
dev = adap->port[i];
ret = 0;
if (dev)
ret = update_root_dev_clip(dev);
if (ret < 0)
break;
}
rcu_read_unlock();
}
/**
* cxgb_up - enable the adapter
* @adap: adapter being enabled
*
* Called when the first port is enabled, this function performs the
* actions necessary to make an adapter operational, such as completing
* the initialization of HW modules, and enabling interrupts.
*
* Must be called with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adap)
{
int err;
err = setup_sge_queues(adap);
if (err)
goto out;
err = setup_rss(adap);
if (err)
goto freeq;
if (adap->flags & USING_MSIX) {
name_msix_vecs(adap);
err = request_irq(adap->msix_info[0].vec, t4_nondata_intr, 0,
adap->msix_info[0].desc, adap);
if (err)
goto irq_err;
err = request_msix_queue_irqs(adap);
if (err) {
free_irq(adap->msix_info[0].vec, adap);
goto irq_err;
}
} else {
err = request_irq(adap->pdev->irq, t4_intr_handler(adap),
(adap->flags & USING_MSI) ? 0 : IRQF_SHARED,
adap->port[0]->name, adap);
if (err)
goto irq_err;
}
enable_rx(adap);
t4_sge_start(adap);
t4_intr_enable(adap);
adap->flags |= FULL_INIT_DONE;
notify_ulds(adap, CXGB4_STATE_UP);
update_clip(adap);
out:
return err;
irq_err:
dev_err(adap->pdev_dev, "request_irq failed, err %d\n", err);
freeq:
t4_free_sge_resources(adap);
goto out;
}
static void cxgb_down(struct adapter *adapter)
{
t4_intr_disable(adapter);
cancel_work_sync(&adapter->tid_release_task);
cancel_work_sync(&adapter->db_full_task);
cancel_work_sync(&adapter->db_drop_task);
adapter->tid_release_task_busy = false;
adapter->tid_release_head = NULL;
if (adapter->flags & USING_MSIX) {
free_msix_queue_irqs(adapter);
free_irq(adapter->msix_info[0].vec, adapter);
} else
free_irq(adapter->pdev->irq, adapter);
quiesce_rx(adapter);
t4_sge_stop(adapter);
t4_free_sge_resources(adapter);
adapter->flags &= ~FULL_INIT_DONE;
}
/*
* net_device operations
*/
static int cxgb_open(struct net_device *dev)
{
int err;
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
netif_carrier_off(dev);
if (!(adapter->flags & FULL_INIT_DONE)) {
err = cxgb_up(adapter);
if (err < 0)
return err;
}
err = link_start(dev);
if (!err)
netif_tx_start_all_queues(dev);
return err;
}
static int cxgb_close(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
netif_tx_stop_all_queues(dev);
netif_carrier_off(dev);
return t4_enable_vi(adapter, adapter->fn, pi->viid, false, false);
}
/* Return an error number if the indicated filter isn't writable ...
*/
static int writable_filter(struct filter_entry *f)
{
if (f->locked)
return -EPERM;
if (f->pending)
return -EBUSY;
return 0;
}
/* Delete the filter at the specified index (if valid). The checks for all
* the common problems with doing this like the filter being locked, currently
* pending in another operation, etc.
*/
static int delete_filter(struct adapter *adapter, unsigned int fidx)
{
struct filter_entry *f;
int ret;
if (fidx >= adapter->tids.nftids + adapter->tids.nsftids)
return -EINVAL;
f = &adapter->tids.ftid_tab[fidx];
ret = writable_filter(f);
if (ret)
return ret;
if (f->valid)
return del_filter_wr(adapter, fidx);
return 0;
}
int cxgb4_create_server_filter(const struct net_device *dev, unsigned int stid,
__be32 sip, __be16 sport, __be16 vlan,
unsigned int queue, unsigned char port, unsigned char mask)
{
int ret;
struct filter_entry *f;
struct adapter *adap;
int i;
u8 *val;
adap = netdev2adap(dev);
/* Adjust stid to correct filter index */
stid -= adap->tids.sftid_base;
stid += adap->tids.nftids;
/* Check to make sure the filter requested is writable ...
*/
f = &adap->tids.ftid_tab[stid];
ret = writable_filter(f);
if (ret)
return ret;
/* Clear out any old resources being used by the filter before
* we start constructing the new filter.
*/
if (f->valid)
clear_filter(adap, f);
/* Clear out filter specifications */
memset(&f->fs, 0, sizeof(struct ch_filter_specification));
f->fs.val.lport = cpu_to_be16(sport);
f->fs.mask.lport = ~0;
val = (u8 *)&sip;
if ((val[0] | val[1] | val[2] | val[3]) != 0) {
for (i = 0; i < 4; i++) {
f->fs.val.lip[i] = val[i];
f->fs.mask.lip[i] = ~0;
}
if (adap->params.tp.vlan_pri_map & F_PORT) {
f->fs.val.iport = port;
f->fs.mask.iport = mask;
}
}
if (adap->params.tp.vlan_pri_map & F_PROTOCOL) {
f->fs.val.proto = IPPROTO_TCP;
f->fs.mask.proto = ~0;
}
f->fs.dirsteer = 1;
f->fs.iq = queue;
/* Mark filter as locked */
f->locked = 1;
f->fs.rpttid = 1;
ret = set_filter_wr(adap, stid);
if (ret) {
clear_filter(adap, f);
return ret;
}
return 0;
}
EXPORT_SYMBOL(cxgb4_create_server_filter);
int cxgb4_remove_server_filter(const struct net_device *dev, unsigned int stid,
unsigned int queue, bool ipv6)
{
int ret;
struct filter_entry *f;
struct adapter *adap;
adap = netdev2adap(dev);
/* Adjust stid to correct filter index */
stid -= adap->tids.sftid_base;
stid += adap->tids.nftids;
f = &adap->tids.ftid_tab[stid];
/* Unlock the filter */
f->locked = 0;
ret = delete_filter(adap, stid);
if (ret)
return ret;
return 0;
}
EXPORT_SYMBOL(cxgb4_remove_server_filter);
static struct rtnl_link_stats64 *cxgb_get_stats(struct net_device *dev,
struct rtnl_link_stats64 *ns)
{
struct port_stats stats;
struct port_info *p = netdev_priv(dev);
struct adapter *adapter = p->adapter;
/* Block retrieving statistics during EEH error
* recovery. Otherwise, the recovery might fail
* and the PCI device will be removed permanently
*/
spin_lock(&adapter->stats_lock);
if (!netif_device_present(dev)) {
spin_unlock(&adapter->stats_lock);
return ns;
}
t4_get_port_stats(adapter, p->tx_chan, &stats);
spin_unlock(&adapter->stats_lock);
ns->tx_bytes = stats.tx_octets;
ns->tx_packets = stats.tx_frames;
ns->rx_bytes = stats.rx_octets;
ns->rx_packets = stats.rx_frames;
ns->multicast = stats.rx_mcast_frames;
/* detailed rx_errors */
ns->rx_length_errors = stats.rx_jabber + stats.rx_too_long +
stats.rx_runt;
ns->rx_over_errors = 0;
ns->rx_crc_errors = stats.rx_fcs_err;
ns->rx_frame_errors = stats.rx_symbol_err;
ns->rx_fifo_errors = stats.rx_ovflow0 + stats.rx_ovflow1 +
stats.rx_ovflow2 + stats.rx_ovflow3 +
stats.rx_trunc0 + stats.rx_trunc1 +
stats.rx_trunc2 + stats.rx_trunc3;
ns->rx_missed_errors = 0;
/* detailed tx_errors */
ns->tx_aborted_errors = 0;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = 0;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = 0;
ns->tx_errors = stats.tx_error_frames;
ns->rx_errors = stats.rx_symbol_err + stats.rx_fcs_err +
ns->rx_length_errors + stats.rx_len_err + ns->rx_fifo_errors;
return ns;
}
static int cxgb_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
unsigned int mbox;
int ret = 0, prtad, devad;
struct port_info *pi = netdev_priv(dev);
struct mii_ioctl_data *data = (struct mii_ioctl_data *)&req->ifr_data;
switch (cmd) {
case SIOCGMIIPHY:
if (pi->mdio_addr < 0)
return -EOPNOTSUPP;
data->phy_id = pi->mdio_addr;
break;
case SIOCGMIIREG:
case SIOCSMIIREG:
if (mdio_phy_id_is_c45(data->phy_id)) {
prtad = mdio_phy_id_prtad(data->phy_id);
devad = mdio_phy_id_devad(data->phy_id);
} else if (data->phy_id < 32) {
prtad = data->phy_id;
devad = 0;
data->reg_num &= 0x1f;
} else
return -EINVAL;
mbox = pi->adapter->fn;
if (cmd == SIOCGMIIREG)
ret = t4_mdio_rd(pi->adapter, mbox, prtad, devad,
data->reg_num, &data->val_out);
else
ret = t4_mdio_wr(pi->adapter, mbox, prtad, devad,
data->reg_num, data->val_in);
break;
default:
return -EOPNOTSUPP;
}
return ret;
}
static void cxgb_set_rxmode(struct net_device *dev)
{
/* unfortunately we can't return errors to the stack */
set_rxmode(dev, -1, false);
}
static int cxgb_change_mtu(struct net_device *dev, int new_mtu)
{
int ret;
struct port_info *pi = netdev_priv(dev);
if (new_mtu < 81 || new_mtu > MAX_MTU) /* accommodate SACK */
return -EINVAL;
ret = t4_set_rxmode(pi->adapter, pi->adapter->fn, pi->viid, new_mtu, -1,
-1, -1, -1, true);
if (!ret)
dev->mtu = new_mtu;
return ret;
}
static int cxgb_set_mac_addr(struct net_device *dev, void *p)
{
int ret;
struct sockaddr *addr = p;
struct port_info *pi = netdev_priv(dev);
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
ret = t4_change_mac(pi->adapter, pi->adapter->fn, pi->viid,
pi->xact_addr_filt, addr->sa_data, true, true);
if (ret < 0)
return ret;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
pi->xact_addr_filt = ret;
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void cxgb_netpoll(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
if (adap->flags & USING_MSIX) {
int i;
struct sge_eth_rxq *rx = &adap->sge.ethrxq[pi->first_qset];
for (i = pi->nqsets; i; i--, rx++)
t4_sge_intr_msix(0, &rx->rspq);
} else
t4_intr_handler(adap)(0, adap);
}
#endif
static const struct net_device_ops cxgb4_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t4_eth_xmit,
.ndo_get_stats64 = cxgb_get_stats,
.ndo_set_rx_mode = cxgb_set_rxmode,
.ndo_set_mac_address = cxgb_set_mac_addr,
.ndo_set_features = cxgb_set_features,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = cxgb_ioctl,
.ndo_change_mtu = cxgb_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = cxgb_netpoll,
#endif
};
void t4_fatal_err(struct adapter *adap)
{
t4_set_reg_field(adap, SGE_CONTROL, GLOBALENABLE, 0);
t4_intr_disable(adap);
dev_alert(adap->pdev_dev, "encountered fatal error, adapter stopped\n");
}
static void setup_memwin(struct adapter *adap)
{
u32 bar0, mem_win0_base, mem_win1_base, mem_win2_base;
bar0 = pci_resource_start(adap->pdev, 0); /* truncation intentional */
if (is_t4(adap->params.chip)) {
mem_win0_base = bar0 + MEMWIN0_BASE;
mem_win1_base = bar0 + MEMWIN1_BASE;
mem_win2_base = bar0 + MEMWIN2_BASE;
} else {
/* For T5, only relative offset inside the PCIe BAR is passed */
mem_win0_base = MEMWIN0_BASE;
mem_win1_base = MEMWIN1_BASE_T5;
mem_win2_base = MEMWIN2_BASE_T5;
}
t4_write_reg(adap, PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN, 0),
mem_win0_base | BIR(0) |
WINDOW(ilog2(MEMWIN0_APERTURE) - 10));
t4_write_reg(adap, PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN, 1),
mem_win1_base | BIR(0) |
WINDOW(ilog2(MEMWIN1_APERTURE) - 10));
t4_write_reg(adap, PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN, 2),
mem_win2_base | BIR(0) |
WINDOW(ilog2(MEMWIN2_APERTURE) - 10));
}
static void setup_memwin_rdma(struct adapter *adap)
{
if (adap->vres.ocq.size) {
unsigned int start, sz_kb;
start = pci_resource_start(adap->pdev, 2) +
OCQ_WIN_OFFSET(adap->pdev, &adap->vres);
sz_kb = roundup_pow_of_two(adap->vres.ocq.size) >> 10;
t4_write_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN, 3),
start | BIR(1) | WINDOW(ilog2(sz_kb)));
t4_write_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET, 3),
adap->vres.ocq.start);
t4_read_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET, 3));
}
}
static int adap_init1(struct adapter *adap, struct fw_caps_config_cmd *c)
{
u32 v;
int ret;
/* get device capabilities */
memset(c, 0, sizeof(*c));
c->op_to_write = htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_READ);
c->cfvalid_to_len16 = htonl(FW_LEN16(*c));
ret = t4_wr_mbox(adap, adap->fn, c, sizeof(*c), c);
if (ret < 0)
return ret;
/* select capabilities we'll be using */
if (c->niccaps & htons(FW_CAPS_CONFIG_NIC_VM)) {
if (!vf_acls)
c->niccaps ^= htons(FW_CAPS_CONFIG_NIC_VM);
else
c->niccaps = htons(FW_CAPS_CONFIG_NIC_VM);
} else if (vf_acls) {
dev_err(adap->pdev_dev, "virtualization ACLs not supported");
return ret;
}
c->op_to_write = htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_WRITE);
ret = t4_wr_mbox(adap, adap->fn, c, sizeof(*c), NULL);
if (ret < 0)
return ret;
ret = t4_config_glbl_rss(adap, adap->fn,
FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL,
FW_RSS_GLB_CONFIG_CMD_TNLMAPEN |
FW_RSS_GLB_CONFIG_CMD_TNLALLLKP);
if (ret < 0)
return ret;
ret = t4_cfg_pfvf(adap, adap->fn, adap->fn, 0, MAX_EGRQ, 64, MAX_INGQ,
0, 0, 4, 0xf, 0xf, 16, FW_CMD_CAP_PF, FW_CMD_CAP_PF);
if (ret < 0)
return ret;
t4_sge_init(adap);
/* tweak some settings */
t4_write_reg(adap, TP_SHIFT_CNT, 0x64f8849);
t4_write_reg(adap, ULP_RX_TDDP_PSZ, HPZ0(PAGE_SHIFT - 12));
t4_write_reg(adap, TP_PIO_ADDR, TP_INGRESS_CONFIG);
v = t4_read_reg(adap, TP_PIO_DATA);
t4_write_reg(adap, TP_PIO_DATA, v & ~CSUM_HAS_PSEUDO_HDR);
/* first 4 Tx modulation queues point to consecutive Tx channels */
adap->params.tp.tx_modq_map = 0xE4;
t4_write_reg(adap, A_TP_TX_MOD_QUEUE_REQ_MAP,
V_TX_MOD_QUEUE_REQ_MAP(adap->params.tp.tx_modq_map));
/* associate each Tx modulation queue with consecutive Tx channels */
v = 0x84218421;
t4_write_indirect(adap, TP_PIO_ADDR, TP_PIO_DATA,
&v, 1, A_TP_TX_SCHED_HDR);
t4_write_indirect(adap, TP_PIO_ADDR, TP_PIO_DATA,
&v, 1, A_TP_TX_SCHED_FIFO);
t4_write_indirect(adap, TP_PIO_ADDR, TP_PIO_DATA,
&v, 1, A_TP_TX_SCHED_PCMD);
#define T4_TX_MODQ_10G_WEIGHT_DEFAULT 16 /* in KB units */
if (is_offload(adap)) {
t4_write_reg(adap, A_TP_TX_MOD_QUEUE_WEIGHT0,
V_TX_MODQ_WEIGHT0(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT1(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT2(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT3(T4_TX_MODQ_10G_WEIGHT_DEFAULT));
t4_write_reg(adap, A_TP_TX_MOD_CHANNEL_WEIGHT,
V_TX_MODQ_WEIGHT0(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT1(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT2(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
V_TX_MODQ_WEIGHT3(T4_TX_MODQ_10G_WEIGHT_DEFAULT));
}
/* get basic stuff going */
return t4_early_init(adap, adap->fn);
}
/*
* Max # of ATIDs. The absolute HW max is 16K but we keep it lower.
*/
#define MAX_ATIDS 8192U
/*
* Phase 0 of initialization: contact FW, obtain config, perform basic init.
*
* If the firmware we're dealing with has Configuration File support, then
* we use that to perform all configuration
*/
/*
* Tweak configuration based on module parameters, etc. Most of these have
* defaults assigned to them by Firmware Configuration Files (if we're using
* them) but need to be explicitly set if we're using hard-coded
* initialization. But even in the case of using Firmware Configuration
* Files, we'd like to expose the ability to change these via module
* parameters so these are essentially common tweaks/settings for
* Configuration Files and hard-coded initialization ...
*/
static int adap_init0_tweaks(struct adapter *adapter)
{
/*
* Fix up various Host-Dependent Parameters like Page Size, Cache
* Line Size, etc. The firmware default is for a 4KB Page Size and
* 64B Cache Line Size ...
*/
t4_fixup_host_params(adapter, PAGE_SIZE, L1_CACHE_BYTES);
/*
* Process module parameters which affect early initialization.
*/
if (rx_dma_offset != 2 && rx_dma_offset != 0) {
dev_err(&adapter->pdev->dev,
"Ignoring illegal rx_dma_offset=%d, using 2\n",
rx_dma_offset);
rx_dma_offset = 2;
}
t4_set_reg_field(adapter, SGE_CONTROL,
PKTSHIFT_MASK,
PKTSHIFT(rx_dma_offset));
/*
* Don't include the "IP Pseudo Header" in CPL_RX_PKT checksums: Linux
* adds the pseudo header itself.
*/
t4_tp_wr_bits_indirect(adapter, TP_INGRESS_CONFIG,
CSUM_HAS_PSEUDO_HDR, 0);
return 0;
}
/*
* Attempt to initialize the adapter via a Firmware Configuration File.
*/
static int adap_init0_config(struct adapter *adapter, int reset)
{
struct fw_caps_config_cmd caps_cmd;
const struct firmware *cf;
unsigned long mtype = 0, maddr = 0;
u32 finiver, finicsum, cfcsum;
int ret;
int config_issued = 0;
char *fw_config_file, fw_config_file_path[256];
char *config_name = NULL;
/*
* Reset device if necessary.
*/
if (reset) {
ret = t4_fw_reset(adapter, adapter->mbox,
PIORSTMODE | PIORST);
if (ret < 0)
goto bye;
}
/*
* If we have a T4 configuration file under /lib/firmware/cxgb4/,
* then use that. Otherwise, use the configuration file stored
* in the adapter flash ...
*/
switch (CHELSIO_CHIP_VERSION(adapter->params.chip)) {
case CHELSIO_T4:
fw_config_file = FW4_CFNAME;
break;
case CHELSIO_T5:
fw_config_file = FW5_CFNAME;
break;
default:
dev_err(adapter->pdev_dev, "Device %d is not supported\n",
adapter->pdev->device);
ret = -EINVAL;
goto bye;
}
ret = request_firmware(&cf, fw_config_file, adapter->pdev_dev);
if (ret < 0) {
config_name = "On FLASH";
mtype = FW_MEMTYPE_CF_FLASH;
maddr = t4_flash_cfg_addr(adapter);
} else {
u32 params[7], val[7];
sprintf(fw_config_file_path,
"/lib/firmware/%s", fw_config_file);
config_name = fw_config_file_path;
if (cf->size >= FLASH_CFG_MAX_SIZE)
ret = -ENOMEM;
else {
params[0] = (FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_CF));
ret = t4_query_params(adapter, adapter->mbox,
adapter->fn, 0, 1, params, val);
if (ret == 0) {
/*
* For t4_memory_write() below addresses and
* sizes have to be in terms of multiples of 4
* bytes. So, if the Configuration File isn't
* a multiple of 4 bytes in length we'll have
* to write that out separately since we can't
* guarantee that the bytes following the
* residual byte in the buffer returned by
* request_firmware() are zeroed out ...
*/
size_t resid = cf->size & 0x3;
size_t size = cf->size & ~0x3;
__be32 *data = (__be32 *)cf->data;
mtype = FW_PARAMS_PARAM_Y_GET(val[0]);
maddr = FW_PARAMS_PARAM_Z_GET(val[0]) << 16;
ret = t4_memory_write(adapter, mtype, maddr,
size, data);
if (ret == 0 && resid != 0) {
union {
__be32 word;
char buf[4];
} last;
int i;
last.word = data[size >> 2];
for (i = resid; i < 4; i++)
last.buf[i] = 0;
ret = t4_memory_write(adapter, mtype,
maddr + size,
4, &last.word);
}
}
}
release_firmware(cf);
if (ret)
goto bye;
}
/*
* Issue a Capability Configuration command to the firmware to get it
* to parse the Configuration File. We don't use t4_fw_config_file()
* because we want the ability to modify various features after we've
* processed the configuration file ...
*/
memset(&caps_cmd, 0, sizeof(caps_cmd));
caps_cmd.op_to_write =
htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST |
FW_CMD_READ);
caps_cmd.cfvalid_to_len16 =
htonl(FW_CAPS_CONFIG_CMD_CFVALID |
FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(maddr >> 16) |
FW_LEN16(caps_cmd));
ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
&caps_cmd);
/* If the CAPS_CONFIG failed with an ENOENT (for a Firmware
* Configuration File in FLASH), our last gasp effort is to use the
* Firmware Configuration File which is embedded in the firmware. A
* very few early versions of the firmware didn't have one embedded
* but we can ignore those.
*/
if (ret == -ENOENT) {
memset(&caps_cmd, 0, sizeof(caps_cmd));
caps_cmd.op_to_write =
htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST |
FW_CMD_READ);
caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd,
sizeof(caps_cmd), &caps_cmd);
config_name = "Firmware Default";
}
config_issued = 1;
if (ret < 0)
goto bye;
finiver = ntohl(caps_cmd.finiver);
finicsum = ntohl(caps_cmd.finicsum);
cfcsum = ntohl(caps_cmd.cfcsum);
if (finicsum != cfcsum)
dev_warn(adapter->pdev_dev, "Configuration File checksum "\
"mismatch: [fini] csum=%#x, computed csum=%#x\n",
finicsum, cfcsum);
/*
* And now tell the firmware to use the configuration we just loaded.
*/
caps_cmd.op_to_write =
htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST |
FW_CMD_WRITE);
caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
NULL);
if (ret < 0)
goto bye;
/*
* Tweak configuration based on system architecture, module
* parameters, etc.
*/
ret = adap_init0_tweaks(adapter);
if (ret < 0)
goto bye;
/*
* And finally tell the firmware to initialize itself using the
* parameters from the Configuration File.
*/
ret = t4_fw_initialize(adapter, adapter->mbox);
if (ret < 0)
goto bye;
/*
* Return successfully and note that we're operating with parameters
* not supplied by the driver, rather than from hard-wired
* initialization constants burried in the driver.
*/
adapter->flags |= USING_SOFT_PARAMS;
dev_info(adapter->pdev_dev, "Successfully configured using Firmware "\
"Configuration File \"%s\", version %#x, computed checksum %#x\n",
config_name, finiver, cfcsum);
return 0;
/*
* Something bad happened. Return the error ... (If the "error"
* is that there's no Configuration File on the adapter we don't
* want to issue a warning since this is fairly common.)
*/
bye:
if (config_issued && ret != -ENOENT)
dev_warn(adapter->pdev_dev, "\"%s\" configuration file error %d\n",
config_name, -ret);
return ret;
}
/*
* Attempt to initialize the adapter via hard-coded, driver supplied
* parameters ...
*/
static int adap_init0_no_config(struct adapter *adapter, int reset)
{
struct sge *s = &adapter->sge;
struct fw_caps_config_cmd caps_cmd;
u32 v;
int i, ret;
/*
* Reset device if necessary
*/
if (reset) {
ret = t4_fw_reset(adapter, adapter->mbox,
PIORSTMODE | PIORST);
if (ret < 0)
goto bye;
}
/*
* Get device capabilities and select which we'll be using.
*/
memset(&caps_cmd, 0, sizeof(caps_cmd));
caps_cmd.op_to_write = htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_READ);
caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
&caps_cmd);
if (ret < 0)
goto bye;
if (caps_cmd.niccaps & htons(FW_CAPS_CONFIG_NIC_VM)) {
if (!vf_acls)
caps_cmd.niccaps ^= htons(FW_CAPS_CONFIG_NIC_VM);
else
caps_cmd.niccaps = htons(FW_CAPS_CONFIG_NIC_VM);
} else if (vf_acls) {
dev_err(adapter->pdev_dev, "virtualization ACLs not supported");
goto bye;
}
caps_cmd.op_to_write = htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_WRITE);
ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
NULL);
if (ret < 0)
goto bye;
/*
* Tweak configuration based on system architecture, module
* parameters, etc.
*/
ret = adap_init0_tweaks(adapter);
if (ret < 0)
goto bye;
/*
* Select RSS Global Mode we want to use. We use "Basic Virtual"
* mode which maps each Virtual Interface to its own section of
* the RSS Table and we turn on all map and hash enables ...
*/
adapter->flags |= RSS_TNLALLLOOKUP;
ret = t4_config_glbl_rss(adapter, adapter->mbox,
FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL,
FW_RSS_GLB_CONFIG_CMD_TNLMAPEN |
FW_RSS_GLB_CONFIG_CMD_HASHTOEPLITZ |
((adapter->flags & RSS_TNLALLLOOKUP) ?
FW_RSS_GLB_CONFIG_CMD_TNLALLLKP : 0));
if (ret < 0)
goto bye;
/*
* Set up our own fundamental resource provisioning ...
*/
ret = t4_cfg_pfvf(adapter, adapter->mbox, adapter->fn, 0,
PFRES_NEQ, PFRES_NETHCTRL,
PFRES_NIQFLINT, PFRES_NIQ,
PFRES_TC, PFRES_NVI,
FW_PFVF_CMD_CMASK_MASK,
pfvfres_pmask(adapter, adapter->fn, 0),
PFRES_NEXACTF,
PFRES_R_CAPS, PFRES_WX_CAPS);
if (ret < 0)
goto bye;
/*
* Perform low level SGE initialization. We need to do this before we
* send the firmware the INITIALIZE command because that will cause
* any other PF Drivers which are waiting for the Master
* Initialization to proceed forward.
*/
for (i = 0; i < SGE_NTIMERS - 1; i++)
s->timer_val[i] = min(intr_holdoff[i], MAX_SGE_TIMERVAL);
s->timer_val[SGE_NTIMERS - 1] = MAX_SGE_TIMERVAL;
s->counter_val[0] = 1;
for (i = 1; i < SGE_NCOUNTERS; i++)
s->counter_val[i] = min(intr_cnt[i - 1],
THRESHOLD_0_GET(THRESHOLD_0_MASK));
t4_sge_init(adapter);
#ifdef CONFIG_PCI_IOV
/*
* Provision resource limits for Virtual Functions. We currently
* grant them all the same static resource limits except for the Port
* Access Rights Mask which we're assigning based on the PF. All of
* the static provisioning stuff for both the PF and VF really needs
* to be managed in a persistent manner for each device which the
* firmware controls.
*/
{
int pf, vf;
for (pf = 0; pf < ARRAY_SIZE(num_vf); pf++) {
if (num_vf[pf] <= 0)
continue;
/* VF numbering starts at 1! */
for (vf = 1; vf <= num_vf[pf]; vf++) {
ret = t4_cfg_pfvf(adapter, adapter->mbox,
pf, vf,
VFRES_NEQ, VFRES_NETHCTRL,
VFRES_NIQFLINT, VFRES_NIQ,
VFRES_TC, VFRES_NVI,
FW_PFVF_CMD_CMASK_MASK,
pfvfres_pmask(
adapter, pf, vf),
VFRES_NEXACTF,
VFRES_R_CAPS, VFRES_WX_CAPS);
if (ret < 0)
dev_warn(adapter->pdev_dev,
"failed to "\
"provision pf/vf=%d/%d; "
"err=%d\n", pf, vf, ret);
}
}
}
#endif
/*
* Set up the default filter mode. Later we'll want to implement this
* via a firmware command, etc. ... This needs to be done before the
* firmare initialization command ... If the selected set of fields
* isn't equal to the default value, we'll need to make sure that the
* field selections will fit in the 36-bit budget.
*/
if (tp_vlan_pri_map != TP_VLAN_PRI_MAP_DEFAULT) {
int j, bits = 0;
for (j = TP_VLAN_PRI_MAP_FIRST; j <= TP_VLAN_PRI_MAP_LAST; j++)
switch (tp_vlan_pri_map & (1 << j)) {
case 0:
/* compressed filter field not enabled */
break;
case FCOE_MASK:
bits += 1;
break;
case PORT_MASK:
bits += 3;
break;
case VNIC_ID_MASK:
bits += 17;
break;
case VLAN_MASK:
bits += 17;
break;
case TOS_MASK:
bits += 8;
break;
case PROTOCOL_MASK:
bits += 8;
break;
case ETHERTYPE_MASK:
bits += 16;
break;
case MACMATCH_MASK:
bits += 9;
break;
case MPSHITTYPE_MASK:
bits += 3;
break;
case FRAGMENTATION_MASK:
bits += 1;
break;
}
if (bits > 36) {
dev_err(adapter->pdev_dev,
"tp_vlan_pri_map=%#x needs %d bits > 36;"\
" using %#x\n", tp_vlan_pri_map, bits,
TP_VLAN_PRI_MAP_DEFAULT);
tp_vlan_pri_map = TP_VLAN_PRI_MAP_DEFAULT;
}
}
v = tp_vlan_pri_map;
t4_write_indirect(adapter, TP_PIO_ADDR, TP_PIO_DATA,
&v, 1, TP_VLAN_PRI_MAP);
/*
* We need Five Tuple Lookup mode to be set in TP_GLOBAL_CONFIG order
* to support any of the compressed filter fields above. Newer
* versions of the firmware do this automatically but it doesn't hurt
* to set it here. Meanwhile, we do _not_ need to set Lookup Every
* Packet in TP_INGRESS_CONFIG to support matching non-TCP packets
* since the firmware automatically turns this on and off when we have
* a non-zero number of filters active (since it does have a
* performance impact).
*/
if (tp_vlan_pri_map)
t4_set_reg_field(adapter, TP_GLOBAL_CONFIG,
FIVETUPLELOOKUP_MASK,
FIVETUPLELOOKUP_MASK);
/*
* Tweak some settings.
*/
t4_write_reg(adapter, TP_SHIFT_CNT, SYNSHIFTMAX(6) |
RXTSHIFTMAXR1(4) | RXTSHIFTMAXR2(15) |
PERSHIFTBACKOFFMAX(8) | PERSHIFTMAX(8) |
KEEPALIVEMAXR1(4) | KEEPALIVEMAXR2(9));
/*
* Get basic stuff going by issuing the Firmware Initialize command.
* Note that this _must_ be after all PFVF commands ...
*/
ret = t4_fw_initialize(adapter, adapter->mbox);
if (ret < 0)
goto bye;
/*
* Return successfully!
*/
dev_info(adapter->pdev_dev, "Successfully configured using built-in "\
"driver parameters\n");
return 0;
/*
* Something bad happened. Return the error ...
*/
bye:
return ret;
}
static struct fw_info fw_info_array[] = {
{
.chip = CHELSIO_T4,
.fs_name = FW4_CFNAME,
.fw_mod_name = FW4_FNAME,
.fw_hdr = {
.chip = FW_HDR_CHIP_T4,
.fw_ver = __cpu_to_be32(FW_VERSION(T4)),
.intfver_nic = FW_INTFVER(T4, NIC),
.intfver_vnic = FW_INTFVER(T4, VNIC),
.intfver_ri = FW_INTFVER(T4, RI),
.intfver_iscsi = FW_INTFVER(T4, ISCSI),
.intfver_fcoe = FW_INTFVER(T4, FCOE),
},
}, {
.chip = CHELSIO_T5,
.fs_name = FW5_CFNAME,
.fw_mod_name = FW5_FNAME,
.fw_hdr = {
.chip = FW_HDR_CHIP_T5,
.fw_ver = __cpu_to_be32(FW_VERSION(T5)),
.intfver_nic = FW_INTFVER(T5, NIC),
.intfver_vnic = FW_INTFVER(T5, VNIC),
.intfver_ri = FW_INTFVER(T5, RI),
.intfver_iscsi = FW_INTFVER(T5, ISCSI),
.intfver_fcoe = FW_INTFVER(T5, FCOE),
},
}
};
static struct fw_info *find_fw_info(int chip)
{
int i;
for (i = 0; i < ARRAY_SIZE(fw_info_array); i++) {
if (fw_info_array[i].chip == chip)
return &fw_info_array[i];
}
return NULL;
}
/*
* Phase 0 of initialization: contact FW, obtain config, perform basic init.
*/
static int adap_init0(struct adapter *adap)
{
int ret;
u32 v, port_vec;
enum dev_state state;
u32 params[7], val[7];
struct fw_caps_config_cmd caps_cmd;
int reset = 1;
/*
* Contact FW, advertising Master capability (and potentially forcing
* ourselves as the Master PF if our module parameter force_init is
* set).
*/
ret = t4_fw_hello(adap, adap->mbox, adap->fn,
force_init ? MASTER_MUST : MASTER_MAY,
&state);
if (ret < 0) {
dev_err(adap->pdev_dev, "could not connect to FW, error %d\n",
ret);
return ret;
}
if (ret == adap->mbox)
adap->flags |= MASTER_PF;
if (force_init && state == DEV_STATE_INIT)
state = DEV_STATE_UNINIT;
/*
* If we're the Master PF Driver and the device is uninitialized,
* then let's consider upgrading the firmware ... (We always want
* to check the firmware version number in order to A. get it for
* later reporting and B. to warn if the currently loaded firmware
* is excessively mismatched relative to the driver.)
*/
t4_get_fw_version(adap, &adap->params.fw_vers);
t4_get_tp_version(adap, &adap->params.tp_vers);
if ((adap->flags & MASTER_PF) && state != DEV_STATE_INIT) {
struct fw_info *fw_info;
struct fw_hdr *card_fw;
const struct firmware *fw;
const u8 *fw_data = NULL;
unsigned int fw_size = 0;
/* This is the firmware whose headers the driver was compiled
* against
*/
fw_info = find_fw_info(CHELSIO_CHIP_VERSION(adap->params.chip));
if (fw_info == NULL) {
dev_err(adap->pdev_dev,
"unable to get firmware info for chip %d.\n",
CHELSIO_CHIP_VERSION(adap->params.chip));
return -EINVAL;
}
/* allocate memory to read the header of the firmware on the
* card
*/
card_fw = t4_alloc_mem(sizeof(*card_fw));
/* Get FW from from /lib/firmware/ */
ret = request_firmware(&fw, fw_info->fw_mod_name,
adap->pdev_dev);
if (ret < 0) {
dev_err(adap->pdev_dev,
"unable to load firmware image %s, error %d\n",
fw_info->fw_mod_name, ret);
} else {
fw_data = fw->data;
fw_size = fw->size;
}
/* upgrade FW logic */
ret = t4_prep_fw(adap, fw_info, fw_data, fw_size, card_fw,
state, &reset);
/* Cleaning up */
if (fw != NULL)
release_firmware(fw);
t4_free_mem(card_fw);
if (ret < 0)
goto bye;
}
/*
* Grab VPD parameters. This should be done after we establish a
* connection to the firmware since some of the VPD parameters
* (notably the Core Clock frequency) are retrieved via requests to
* the firmware. On the other hand, we need these fairly early on
* so we do this right after getting ahold of the firmware.
*/
ret = get_vpd_params(adap, &adap->params.vpd);
if (ret < 0)
goto bye;
/*
* Find out what ports are available to us. Note that we need to do
* this before calling adap_init0_no_config() since it needs nports
* and portvec ...
*/
v =
FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_PORTVEC);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 1, &v, &port_vec);
if (ret < 0)
goto bye;
adap->params.nports = hweight32(port_vec);
adap->params.portvec = port_vec;
/*
* If the firmware is initialized already (and we're not forcing a
* master initialization), note that we're living with existing
* adapter parameters. Otherwise, it's time to try initializing the
* adapter ...
*/
if (state == DEV_STATE_INIT) {
dev_info(adap->pdev_dev, "Coming up as %s: "\
"Adapter already initialized\n",
adap->flags & MASTER_PF ? "MASTER" : "SLAVE");
adap->flags |= USING_SOFT_PARAMS;
} else {
dev_info(adap->pdev_dev, "Coming up as MASTER: "\
"Initializing adapter\n");
/*
* If the firmware doesn't support Configuration
* Files warn user and exit,
*/
if (ret < 0)
dev_warn(adap->pdev_dev, "Firmware doesn't support "
"configuration file.\n");
if (force_old_init)
ret = adap_init0_no_config(adap, reset);
else {
/*
* Find out whether we're dealing with a version of
* the firmware which has configuration file support.
*/
params[0] = (FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_CF));
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 1,
params, val);
/*
* If the firmware doesn't support Configuration
* Files, use the old Driver-based, hard-wired
* initialization. Otherwise, try using the
* Configuration File support and fall back to the
* Driver-based initialization if there's no
* Configuration File found.
*/
if (ret < 0)
ret = adap_init0_no_config(adap, reset);
else {
/*
* The firmware provides us with a memory
* buffer where we can load a Configuration
* File from the host if we want to override
* the Configuration File in flash.
*/
ret = adap_init0_config(adap, reset);
if (ret == -ENOENT) {
dev_info(adap->pdev_dev,
"No Configuration File present "
"on adapter. Using hard-wired "
"configuration parameters.\n");
ret = adap_init0_no_config(adap, reset);
}
}
}
if (ret < 0) {
dev_err(adap->pdev_dev,
"could not initialize adapter, error %d\n",
-ret);
goto bye;
}
}
/*
* If we're living with non-hard-coded parameters (either from a
* Firmware Configuration File or values programmed by a different PF
* Driver), give the SGE code a chance to pull in anything that it
* needs ... Note that this must be called after we retrieve our VPD
* parameters in order to know how to convert core ticks to seconds.
*/
if (adap->flags & USING_SOFT_PARAMS) {
ret = t4_sge_init(adap);
if (ret < 0)
goto bye;
}
if (is_bypass_device(adap->pdev->device))
adap->params.bypass = 1;
/*
* Grab some of our basic fundamental operating parameters.
*/
#define FW_PARAM_DEV(param) \
(FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
#define FW_PARAM_PFVF(param) \
FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param)| \
FW_PARAMS_PARAM_Y(0) | \
FW_PARAMS_PARAM_Z(0)
params[0] = FW_PARAM_PFVF(EQ_START);
params[1] = FW_PARAM_PFVF(L2T_START);
params[2] = FW_PARAM_PFVF(L2T_END);
params[3] = FW_PARAM_PFVF(FILTER_START);
params[4] = FW_PARAM_PFVF(FILTER_END);
params[5] = FW_PARAM_PFVF(IQFLINT_START);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 6, params, val);
if (ret < 0)
goto bye;
adap->sge.egr_start = val[0];
adap->l2t_start = val[1];
adap->l2t_end = val[2];
adap->tids.ftid_base = val[3];
adap->tids.nftids = val[4] - val[3] + 1;
adap->sge.ingr_start = val[5];
/* query params related to active filter region */
params[0] = FW_PARAM_PFVF(ACTIVE_FILTER_START);
params[1] = FW_PARAM_PFVF(ACTIVE_FILTER_END);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 2, params, val);
/* If Active filter size is set we enable establishing
* offload connection through firmware work request
*/
if ((val[0] != val[1]) && (ret >= 0)) {
adap->flags |= FW_OFLD_CONN;
adap->tids.aftid_base = val[0];
adap->tids.aftid_end = val[1];
}
/* If we're running on newer firmware, let it know that we're
* prepared to deal with encapsulated CPL messages. Older
* firmware won't understand this and we'll just get
* unencapsulated messages ...
*/
params[0] = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
val[0] = 1;
(void) t4_set_params(adap, adap->mbox, adap->fn, 0, 1, params, val);
/*
* Get device capabilities so we can determine what resources we need
* to manage.
*/
memset(&caps_cmd, 0, sizeof(caps_cmd));
caps_cmd.op_to_write = htonl(FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_READ);
caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
ret = t4_wr_mbox(adap, adap->mbox, &caps_cmd, sizeof(caps_cmd),
&caps_cmd);
if (ret < 0)
goto bye;
if (caps_cmd.ofldcaps) {
/* query offload-related parameters */
params[0] = FW_PARAM_DEV(NTID);
params[1] = FW_PARAM_PFVF(SERVER_START);
params[2] = FW_PARAM_PFVF(SERVER_END);
params[3] = FW_PARAM_PFVF(TDDP_START);
params[4] = FW_PARAM_PFVF(TDDP_END);
params[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 6,
params, val);
if (ret < 0)
goto bye;
adap->tids.ntids = val[0];
adap->tids.natids = min(adap->tids.ntids / 2, MAX_ATIDS);
adap->tids.stid_base = val[1];
adap->tids.nstids = val[2] - val[1] + 1;
/*
* Setup server filter region. Divide the availble filter
* region into two parts. Regular filters get 1/3rd and server
* filters get 2/3rd part. This is only enabled if workarond
* path is enabled.
* 1. For regular filters.
* 2. Server filter: This are special filters which are used
* to redirect SYN packets to offload queue.
*/
if (adap->flags & FW_OFLD_CONN && !is_bypass(adap)) {
adap->tids.sftid_base = adap->tids.ftid_base +
DIV_ROUND_UP(adap->tids.nftids, 3);
adap->tids.nsftids = adap->tids.nftids -
DIV_ROUND_UP(adap->tids.nftids, 3);
adap->tids.nftids = adap->tids.sftid_base -
adap->tids.ftid_base;
}
adap->vres.ddp.start = val[3];
adap->vres.ddp.size = val[4] - val[3] + 1;
adap->params.ofldq_wr_cred = val[5];
adap->params.offload = 1;
}
if (caps_cmd.rdmacaps) {
params[0] = FW_PARAM_PFVF(STAG_START);
params[1] = FW_PARAM_PFVF(STAG_END);
params[2] = FW_PARAM_PFVF(RQ_START);
params[3] = FW_PARAM_PFVF(RQ_END);
params[4] = FW_PARAM_PFVF(PBL_START);
params[5] = FW_PARAM_PFVF(PBL_END);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 6,
params, val);
if (ret < 0)
goto bye;
adap->vres.stag.start = val[0];
adap->vres.stag.size = val[1] - val[0] + 1;
adap->vres.rq.start = val[2];
adap->vres.rq.size = val[3] - val[2] + 1;
adap->vres.pbl.start = val[4];
adap->vres.pbl.size = val[5] - val[4] + 1;
params[0] = FW_PARAM_PFVF(SQRQ_START);
params[1] = FW_PARAM_PFVF(SQRQ_END);
params[2] = FW_PARAM_PFVF(CQ_START);
params[3] = FW_PARAM_PFVF(CQ_END);
params[4] = FW_PARAM_PFVF(OCQ_START);
params[5] = FW_PARAM_PFVF(OCQ_END);
ret = t4_query_params(adap, 0, 0, 0, 6, params, val);
if (ret < 0)
goto bye;
adap->vres.qp.start = val[0];
adap->vres.qp.size = val[1] - val[0] + 1;
adap->vres.cq.start = val[2];
adap->vres.cq.size = val[3] - val[2] + 1;
adap->vres.ocq.start = val[4];
adap->vres.ocq.size = val[5] - val[4] + 1;
}
if (caps_cmd.iscsicaps) {
params[0] = FW_PARAM_PFVF(ISCSI_START);
params[1] = FW_PARAM_PFVF(ISCSI_END);
ret = t4_query_params(adap, adap->mbox, adap->fn, 0, 2,
params, val);
if (ret < 0)
goto bye;
adap->vres.iscsi.start = val[0];
adap->vres.iscsi.size = val[1] - val[0] + 1;
}
#undef FW_PARAM_PFVF
#undef FW_PARAM_DEV
/*
* These are finalized by FW initialization, load their values now.
*/
t4_read_mtu_tbl(adap, adap->params.mtus, NULL);
t4_load_mtus(adap, adap->params.mtus, adap->params.a_wnd,
adap->params.b_wnd);
t4_init_tp_params(adap);
adap->flags |= FW_OK;
return 0;
/*
* Something bad happened. If a command timed out or failed with EIO
* FW does not operate within its spec or something catastrophic
* happened to HW/FW, stop issuing commands.
*/
bye:
if (ret != -ETIMEDOUT && ret != -EIO)
t4_fw_bye(adap, adap->mbox);
return ret;
}
/* EEH callbacks */
static pci_ers_result_t eeh_err_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
int i;
struct adapter *adap = pci_get_drvdata(pdev);
if (!adap)
goto out;
rtnl_lock();
adap->flags &= ~FW_OK;
notify_ulds(adap, CXGB4_STATE_START_RECOVERY);
spin_lock(&adap->stats_lock);
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
netif_device_detach(dev);
netif_carrier_off(dev);
}
spin_unlock(&adap->stats_lock);
if (adap->flags & FULL_INIT_DONE)
cxgb_down(adap);
rtnl_unlock();
if ((adap->flags & DEV_ENABLED)) {
pci_disable_device(pdev);
adap->flags &= ~DEV_ENABLED;
}
out: return state == pci_channel_io_perm_failure ?
PCI_ERS_RESULT_DISCONNECT : PCI_ERS_RESULT_NEED_RESET;
}
static pci_ers_result_t eeh_slot_reset(struct pci_dev *pdev)
{
int i, ret;
struct fw_caps_config_cmd c;
struct adapter *adap = pci_get_drvdata(pdev);
if (!adap) {
pci_restore_state(pdev);
pci_save_state(pdev);
return PCI_ERS_RESULT_RECOVERED;
}
if (!(adap->flags & DEV_ENABLED)) {
if (pci_enable_device(pdev)) {
dev_err(&pdev->dev, "Cannot reenable PCI "
"device after reset\n");
return PCI_ERS_RESULT_DISCONNECT;
}
adap->flags |= DEV_ENABLED;
}
pci_set_master(pdev);
pci_restore_state(pdev);
pci_save_state(pdev);
pci_cleanup_aer_uncorrect_error_status(pdev);
if (t4_wait_dev_ready(adap) < 0)
return PCI_ERS_RESULT_DISCONNECT;
if (t4_fw_hello(adap, adap->fn, adap->fn, MASTER_MUST, NULL) < 0)
return PCI_ERS_RESULT_DISCONNECT;
adap->flags |= FW_OK;
if (adap_init1(adap, &c))
return PCI_ERS_RESULT_DISCONNECT;
for_each_port(adap, i) {
struct port_info *p = adap2pinfo(adap, i);
ret = t4_alloc_vi(adap, adap->fn, p->tx_chan, adap->fn, 0, 1,
NULL, NULL);
if (ret < 0)
return PCI_ERS_RESULT_DISCONNECT;
p->viid = ret;
p->xact_addr_filt = -1;
}
t4_load_mtus(adap, adap->params.mtus, adap->params.a_wnd,
adap->params.b_wnd);
setup_memwin(adap);
if (cxgb_up(adap))
return PCI_ERS_RESULT_DISCONNECT;
return PCI_ERS_RESULT_RECOVERED;
}
static void eeh_resume(struct pci_dev *pdev)
{
int i;
struct adapter *adap = pci_get_drvdata(pdev);
if (!adap)
return;
rtnl_lock();
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
if (netif_running(dev)) {
link_start(dev);
cxgb_set_rxmode(dev);
}
netif_device_attach(dev);
}
rtnl_unlock();
}
static const struct pci_error_handlers cxgb4_eeh = {
.error_detected = eeh_err_detected,
.slot_reset = eeh_slot_reset,
.resume = eeh_resume,
};
static inline bool is_10g_port(const struct link_config *lc)
{
return (lc->supported & FW_PORT_CAP_SPEED_10G) != 0;
}
static inline void init_rspq(struct sge_rspq *q, u8 timer_idx, u8 pkt_cnt_idx,
unsigned int size, unsigned int iqe_size)
{
q->intr_params = QINTR_TIMER_IDX(timer_idx) |
(pkt_cnt_idx < SGE_NCOUNTERS ? QINTR_CNT_EN : 0);
q->pktcnt_idx = pkt_cnt_idx < SGE_NCOUNTERS ? pkt_cnt_idx : 0;
q->iqe_len = iqe_size;
q->size = size;
}
/*
* Perform default configuration of DMA queues depending on the number and type
* of ports we found and the number of available CPUs. Most settings can be
* modified by the admin prior to actual use.
*/
static void cfg_queues(struct adapter *adap)
{
struct sge *s = &adap->sge;
int i, q10g = 0, n10g = 0, qidx = 0;
for_each_port(adap, i)
n10g += is_10g_port(&adap2pinfo(adap, i)->link_cfg);
/*
* We default to 1 queue per non-10G port and up to # of cores queues
* per 10G port.
*/
if (n10g)
q10g = (MAX_ETH_QSETS - (adap->params.nports - n10g)) / n10g;
if (q10g > netif_get_num_default_rss_queues())
q10g = netif_get_num_default_rss_queues();
for_each_port(adap, i) {
struct port_info *pi = adap2pinfo(adap, i);
pi->first_qset = qidx;
pi->nqsets = is_10g_port(&pi->link_cfg) ? q10g : 1;
qidx += pi->nqsets;
}
s->ethqsets = qidx;
s->max_ethqsets = qidx; /* MSI-X may lower it later */
if (is_offload(adap)) {
/*
* For offload we use 1 queue/channel if all ports are up to 1G,
* otherwise we divide all available queues amongst the channels
* capped by the number of available cores.
*/
if (n10g) {
i = min_t(int, ARRAY_SIZE(s->ofldrxq),
num_online_cpus());
s->ofldqsets = roundup(i, adap->params.nports);
} else
s->ofldqsets = adap->params.nports;
/* For RDMA one Rx queue per channel suffices */
s->rdmaqs = adap->params.nports;
}
for (i = 0; i < ARRAY_SIZE(s->ethrxq); i++) {
struct sge_eth_rxq *r = &s->ethrxq[i];
init_rspq(&r->rspq, 0, 0, 1024, 64);
r->fl.size = 72;
}
for (i = 0; i < ARRAY_SIZE(s->ethtxq); i++)
s->ethtxq[i].q.size = 1024;
for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++)
s->ctrlq[i].q.size = 512;
for (i = 0; i < ARRAY_SIZE(s->ofldtxq); i++)
s->ofldtxq[i].q.size = 1024;
for (i = 0; i < ARRAY_SIZE(s->ofldrxq); i++) {
struct sge_ofld_rxq *r = &s->ofldrxq[i];
init_rspq(&r->rspq, 0, 0, 1024, 64);
r->rspq.uld = CXGB4_ULD_ISCSI;
r->fl.size = 72;
}
for (i = 0; i < ARRAY_SIZE(s->rdmarxq); i++) {
struct sge_ofld_rxq *r = &s->rdmarxq[i];
init_rspq(&r->rspq, 0, 0, 511, 64);
r->rspq.uld = CXGB4_ULD_RDMA;
r->fl.size = 72;
}
init_rspq(&s->fw_evtq, 6, 0, 512, 64);
init_rspq(&s->intrq, 6, 0, 2 * MAX_INGQ, 64);
}
/*
* Reduce the number of Ethernet queues across all ports to at most n.
* n provides at least one queue per port.
*/
static void reduce_ethqs(struct adapter *adap, int n)
{
int i;
struct port_info *pi;
while (n < adap->sge.ethqsets)
for_each_port(adap, i) {
pi = adap2pinfo(adap, i);
if (pi->nqsets > 1) {
pi->nqsets--;
adap->sge.ethqsets--;
if (adap->sge.ethqsets <= n)
break;
}
}
n = 0;
for_each_port(adap, i) {
pi = adap2pinfo(adap, i);
pi->first_qset = n;
n += pi->nqsets;
}
}
/* 2 MSI-X vectors needed for the FW queue and non-data interrupts */
#define EXTRA_VECS 2
static int enable_msix(struct adapter *adap)
{
int ofld_need = 0;
int i, err, want, need;
struct sge *s = &adap->sge;
unsigned int nchan = adap->params.nports;
struct msix_entry entries[MAX_INGQ + 1];
for (i = 0; i < ARRAY_SIZE(entries); ++i)
entries[i].entry = i;
want = s->max_ethqsets + EXTRA_VECS;
if (is_offload(adap)) {
want += s->rdmaqs + s->ofldqsets;
/* need nchan for each possible ULD */
ofld_need = 2 * nchan;
}
need = adap->params.nports + EXTRA_VECS + ofld_need;
while ((err = pci_enable_msix(adap->pdev, entries, want)) >= need)
want = err;
if (!err) {
/*
* Distribute available vectors to the various queue groups.
* Every group gets its minimum requirement and NIC gets top
* priority for leftovers.
*/
i = want - EXTRA_VECS - ofld_need;
if (i < s->max_ethqsets) {
s->max_ethqsets = i;
if (i < s->ethqsets)
reduce_ethqs(adap, i);
}
if (is_offload(adap)) {
i = want - EXTRA_VECS - s->max_ethqsets;
i -= ofld_need - nchan;
s->ofldqsets = (i / nchan) * nchan; /* round down */
}
for (i = 0; i < want; ++i)
adap->msix_info[i].vec = entries[i].vector;
} else if (err > 0)
dev_info(adap->pdev_dev,
"only %d MSI-X vectors left, not using MSI-X\n", err);
return err;
}
#undef EXTRA_VECS
static int init_rss(struct adapter *adap)
{
unsigned int i, j;
for_each_port(adap, i) {
struct port_info *pi = adap2pinfo(adap, i);
pi->rss = kcalloc(pi->rss_size, sizeof(u16), GFP_KERNEL);
if (!pi->rss)
return -ENOMEM;
for (j = 0; j < pi->rss_size; j++)
pi->rss[j] = ethtool_rxfh_indir_default(j, pi->nqsets);
}
return 0;
}
static void print_port_info(const struct net_device *dev)
{
static const char *base[] = {
"R XFI", "R XAUI", "T SGMII", "T XFI", "T XAUI", "KX4", "CX4",
"KX", "KR", "R SFP+", "KR/KX", "KR/KX/KX4"
};
char buf[80];
char *bufp = buf;
const char *spd = "";
const struct port_info *pi = netdev_priv(dev);
const struct adapter *adap = pi->adapter;
if (adap->params.pci.speed == PCI_EXP_LNKSTA_CLS_2_5GB)
spd = " 2.5 GT/s";
else if (adap->params.pci.speed == PCI_EXP_LNKSTA_CLS_5_0GB)
spd = " 5 GT/s";
if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_100M)
bufp += sprintf(bufp, "100/");
if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_1G)
bufp += sprintf(bufp, "1000/");
if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_10G)
bufp += sprintf(bufp, "10G/");
if (bufp != buf)
--bufp;
sprintf(bufp, "BASE-%s", base[pi->port_type]);
netdev_info(dev, "Chelsio %s rev %d %s %sNIC PCIe x%d%s%s\n",
adap->params.vpd.id,
CHELSIO_CHIP_RELEASE(adap->params.chip), buf,
is_offload(adap) ? "R" : "", adap->params.pci.width, spd,
(adap->flags & USING_MSIX) ? " MSI-X" :
(adap->flags & USING_MSI) ? " MSI" : "");
netdev_info(dev, "S/N: %s, E/C: %s\n",
adap->params.vpd.sn, adap->params.vpd.ec);
}
static void enable_pcie_relaxed_ordering(struct pci_dev *dev)
{
pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_RELAX_EN);
}
/*
* Free the following resources:
* - memory used for tables
* - MSI/MSI-X
* - net devices
* - resources FW is holding for us
*/
static void free_some_resources(struct adapter *adapter)
{
unsigned int i;
t4_free_mem(adapter->l2t);
t4_free_mem(adapter->tids.tid_tab);
disable_msi(adapter);
for_each_port(adapter, i)
if (adapter->port[i]) {
kfree(adap2pinfo(adapter, i)->rss);
free_netdev(adapter->port[i]);
}
if (adapter->flags & FW_OK)
t4_fw_bye(adapter, adapter->fn);
}
#define TSO_FLAGS (NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN)
#define VLAN_FEAT (NETIF_F_SG | NETIF_F_IP_CSUM | TSO_FLAGS | \
NETIF_F_IPV6_CSUM | NETIF_F_HIGHDMA)
#define SEGMENT_SIZE 128
static int init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int func, i, err, s_qpp, qpp, num_seg;
struct port_info *pi;
bool highdma = false;
struct adapter *adapter = NULL;
printk_once(KERN_INFO "%s - version %s\n", DRV_DESC, DRV_VERSION);
err = pci_request_regions(pdev, KBUILD_MODNAME);
if (err) {
/* Just info, some other driver may have claimed the device. */
dev_info(&pdev->dev, "cannot obtain PCI resources\n");
return err;
}
/* We control everything through one PF */
func = PCI_FUNC(pdev->devfn);
if (func != ent->driver_data) {
pci_save_state(pdev); /* to restore SR-IOV later */
goto sriov;
}
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "cannot enable PCI device\n");
goto out_release_regions;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
highdma = true;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err) {
dev_err(&pdev->dev, "unable to obtain 64-bit DMA for "
"coherent allocations\n");
goto out_disable_device;
}
} else {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev, "no usable DMA configuration\n");
goto out_disable_device;
}
}
pci_enable_pcie_error_reporting(pdev);
enable_pcie_relaxed_ordering(pdev);
pci_set_master(pdev);
pci_save_state(pdev);
adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
if (!adapter) {
err = -ENOMEM;
goto out_disable_device;
}
/* PCI device has been enabled */
adapter->flags |= DEV_ENABLED;
adapter->regs = pci_ioremap_bar(pdev, 0);
if (!adapter->regs) {
dev_err(&pdev->dev, "cannot map device registers\n");
err = -ENOMEM;
goto out_free_adapter;
}
adapter->pdev = pdev;
adapter->pdev_dev = &pdev->dev;
adapter->mbox = func;
adapter->fn = func;
adapter->msg_enable = dflt_msg_enable;
memset(adapter->chan_map, 0xff, sizeof(adapter->chan_map));
spin_lock_init(&adapter->stats_lock);
spin_lock_init(&adapter->tid_release_lock);
INIT_WORK(&adapter->tid_release_task, process_tid_release_list);
INIT_WORK(&adapter->db_full_task, process_db_full);
INIT_WORK(&adapter->db_drop_task, process_db_drop);
err = t4_prep_adapter(adapter);
if (err)
goto out_unmap_bar0;
if (!is_t4(adapter->params.chip)) {
s_qpp = QUEUESPERPAGEPF1 * adapter->fn;
qpp = 1 << QUEUESPERPAGEPF0_GET(t4_read_reg(adapter,
SGE_EGRESS_QUEUES_PER_PAGE_PF) >> s_qpp);
num_seg = PAGE_SIZE / SEGMENT_SIZE;
/* Each segment size is 128B. Write coalescing is enabled only
* when SGE_EGRESS_QUEUES_PER_PAGE_PF reg value for the
* queue is less no of segments that can be accommodated in
* a page size.
*/
if (qpp > num_seg) {
dev_err(&pdev->dev,
"Incorrect number of egress queues per page\n");
err = -EINVAL;
goto out_unmap_bar0;
}
adapter->bar2 = ioremap_wc(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2));
if (!adapter->bar2) {
dev_err(&pdev->dev, "cannot map device bar2 region\n");
err = -ENOMEM;
goto out_unmap_bar0;
}
}
setup_memwin(adapter);
err = adap_init0(adapter);
setup_memwin_rdma(adapter);
if (err)
goto out_unmap_bar;
for_each_port(adapter, i) {
struct net_device *netdev;
netdev = alloc_etherdev_mq(sizeof(struct port_info),
MAX_ETH_QSETS);
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
adapter->port[i] = netdev;
pi = netdev_priv(netdev);
pi->adapter = adapter;
pi->xact_addr_filt = -1;
pi->port_id = i;
netdev->irq = pdev->irq;
netdev->hw_features = NETIF_F_SG | TSO_FLAGS |
NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_RXCSUM | NETIF_F_RXHASH |
NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX;
if (highdma)
netdev->hw_features |= NETIF_F_HIGHDMA;
netdev->features |= netdev->hw_features;
netdev->vlan_features = netdev->features & VLAN_FEAT;
netdev->priv_flags |= IFF_UNICAST_FLT;
netdev->netdev_ops = &cxgb4_netdev_ops;
SET_ETHTOOL_OPS(netdev, &cxgb_ethtool_ops);
}
pci_set_drvdata(pdev, adapter);
if (adapter->flags & FW_OK) {
err = t4_port_init(adapter, func, func, 0);
if (err)
goto out_free_dev;
}
/*
* Configure queues and allocate tables now, they can be needed as
* soon as the first register_netdev completes.
*/
cfg_queues(adapter);
adapter->l2t = t4_init_l2t();
if (!adapter->l2t) {
/* We tolerate a lack of L2T, giving up some functionality */
dev_warn(&pdev->dev, "could not allocate L2T, continuing\n");
adapter->params.offload = 0;
}
if (is_offload(adapter) && tid_init(&adapter->tids) < 0) {
dev_warn(&pdev->dev, "could not allocate TID table, "
"continuing\n");
adapter->params.offload = 0;
}
/* See what interrupts we'll be using */
if (msi > 1 && enable_msix(adapter) == 0)
adapter->flags |= USING_MSIX;
else if (msi > 0 && pci_enable_msi(pdev) == 0)
adapter->flags |= USING_MSI;
err = init_rss(adapter);
if (err)
goto out_free_dev;
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
netif_set_real_num_tx_queues(adapter->port[i], pi->nqsets);
netif_set_real_num_rx_queues(adapter->port[i], pi->nqsets);
err = register_netdev(adapter->port[i]);
if (err)
break;
adapter->chan_map[pi->tx_chan] = i;
print_port_info(adapter->port[i]);
}
if (i == 0) {
dev_err(&pdev->dev, "could not register any net devices\n");
goto out_free_dev;
}
if (err) {
dev_warn(&pdev->dev, "only %d net devices registered\n", i);
err = 0;
}
if (cxgb4_debugfs_root) {
adapter->debugfs_root = debugfs_create_dir(pci_name(pdev),
cxgb4_debugfs_root);
setup_debugfs(adapter);
}
/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
pdev->needs_freset = 1;
if (is_offload(adapter))
attach_ulds(adapter);
sriov:
#ifdef CONFIG_PCI_IOV
if (func < ARRAY_SIZE(num_vf) && num_vf[func] > 0)
if (pci_enable_sriov(pdev, num_vf[func]) == 0)
dev_info(&pdev->dev,
"instantiated %u virtual functions\n",
num_vf[func]);
#endif
return 0;
out_free_dev:
free_some_resources(adapter);
out_unmap_bar:
if (!is_t4(adapter->params.chip))
iounmap(adapter->bar2);
out_unmap_bar0:
iounmap(adapter->regs);
out_free_adapter:
kfree(adapter);
out_disable_device:
pci_disable_pcie_error_reporting(pdev);
pci_disable_device(pdev);
out_release_regions:
pci_release_regions(pdev);
return err;
}
static void remove_one(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
#ifdef CONFIG_PCI_IOV
pci_disable_sriov(pdev);
#endif
if (adapter) {
int i;
if (is_offload(adapter))
detach_ulds(adapter);
for_each_port(adapter, i)
if (adapter->port[i]->reg_state == NETREG_REGISTERED)
unregister_netdev(adapter->port[i]);
if (adapter->debugfs_root)
debugfs_remove_recursive(adapter->debugfs_root);
/* If we allocated filters, free up state associated with any
* valid filters ...
*/
if (adapter->tids.ftid_tab) {
struct filter_entry *f = &adapter->tids.ftid_tab[0];
for (i = 0; i < (adapter->tids.nftids +
adapter->tids.nsftids); i++, f++)
if (f->valid)
clear_filter(adapter, f);
}
if (adapter->flags & FULL_INIT_DONE)
cxgb_down(adapter);
free_some_resources(adapter);
iounmap(adapter->regs);
if (!is_t4(adapter->params.chip))
iounmap(adapter->bar2);
pci_disable_pcie_error_reporting(pdev);
if ((adapter->flags & DEV_ENABLED)) {
pci_disable_device(pdev);
adapter->flags &= ~DEV_ENABLED;
}
pci_release_regions(pdev);
kfree(adapter);
} else
pci_release_regions(pdev);
}
static struct pci_driver cxgb4_driver = {
.name = KBUILD_MODNAME,
.id_table = cxgb4_pci_tbl,
.probe = init_one,
.remove = remove_one,
.shutdown = remove_one,
.err_handler = &cxgb4_eeh,
};
static int __init cxgb4_init_module(void)
{
int ret;
workq = create_singlethread_workqueue("cxgb4");
if (!workq)
return -ENOMEM;
/* Debugfs support is optional, just warn if this fails */
cxgb4_debugfs_root = debugfs_create_dir(KBUILD_MODNAME, NULL);
if (!cxgb4_debugfs_root)
pr_warn("could not create debugfs entry, continuing\n");
ret = pci_register_driver(&cxgb4_driver);
if (ret < 0) {
debugfs_remove(cxgb4_debugfs_root);
destroy_workqueue(workq);
}
register_inet6addr_notifier(&cxgb4_inet6addr_notifier);
return ret;
}
static void __exit cxgb4_cleanup_module(void)
{
unregister_inet6addr_notifier(&cxgb4_inet6addr_notifier);
pci_unregister_driver(&cxgb4_driver);
debugfs_remove(cxgb4_debugfs_root); /* NULL ok */
flush_workqueue(workq);
destroy_workqueue(workq);
}
module_init(cxgb4_init_module);
module_exit(cxgb4_cleanup_module);
| gpl-2.0 |
oskarpearson/linux | arch/mips/kernel/signal.c | 213 | 22619 | /*
* 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) 1991, 1992 Linus Torvalds
* Copyright (C) 1994 - 2000 Ralf Baechle
* Copyright (C) 1999, 2000 Silicon Graphics, Inc.
* Copyright (C) 2014, Imagination Technologies Ltd.
*/
#include <linux/cache.h>
#include <linux/context_tracking.h>
#include <linux/irqflags.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/personality.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/uprobes.h>
#include <linux/compiler.h>
#include <linux/syscalls.h>
#include <linux/uaccess.h>
#include <linux/tracehook.h>
#include <asm/abi.h>
#include <asm/asm.h>
#include <linux/bitops.h>
#include <asm/cacheflush.h>
#include <asm/fpu.h>
#include <asm/sim.h>
#include <asm/ucontext.h>
#include <asm/cpu-features.h>
#include <asm/war.h>
#include <asm/vdso.h>
#include <asm/dsp.h>
#include <asm/inst.h>
#include <asm/msa.h>
#include "signal-common.h"
static int (*save_fp_context)(void __user *sc);
static int (*restore_fp_context)(void __user *sc);
struct sigframe {
u32 sf_ass[4]; /* argument save space for o32 */
u32 sf_pad[2]; /* Was: signal trampoline */
/* Matches struct ucontext from its uc_mcontext field onwards */
struct sigcontext sf_sc;
sigset_t sf_mask;
unsigned long long sf_extcontext[0];
};
struct rt_sigframe {
u32 rs_ass[4]; /* argument save space for o32 */
u32 rs_pad[2]; /* Was: signal trampoline */
struct siginfo rs_info;
struct ucontext rs_uc;
};
/*
* Thread saved context copy to/from a signal context presumed to be on the
* user stack, and therefore accessed with appropriate macros from uaccess.h.
*/
static int copy_fp_to_sigcontext(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
int i;
int err = 0;
int inc = test_thread_flag(TIF_32BIT_FPREGS) ? 2 : 1;
for (i = 0; i < NUM_FPU_REGS; i += inc) {
err |=
__put_user(get_fpr64(¤t->thread.fpu.fpr[i], 0),
&fpregs[i]);
}
err |= __put_user(current->thread.fpu.fcr31, csr);
return err;
}
static int copy_fp_from_sigcontext(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
int i;
int err = 0;
int inc = test_thread_flag(TIF_32BIT_FPREGS) ? 2 : 1;
u64 fpr_val;
for (i = 0; i < NUM_FPU_REGS; i += inc) {
err |= __get_user(fpr_val, &fpregs[i]);
set_fpr64(¤t->thread.fpu.fpr[i], 0, fpr_val);
}
err |= __get_user(current->thread.fpu.fcr31, csr);
return err;
}
/*
* Wrappers for the assembly _{save,restore}_fp_context functions.
*/
static int save_hw_fp_context(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
return _save_fp_context(fpregs, csr);
}
static int restore_hw_fp_context(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
return _restore_fp_context(fpregs, csr);
}
/*
* Extended context handling.
*/
static inline void __user *sc_to_extcontext(void __user *sc)
{
struct ucontext __user *uc;
/*
* We can just pretend the sigcontext is always embedded in a struct
* ucontext here, because the offset from sigcontext to extended
* context is the same in the struct sigframe case.
*/
uc = container_of(sc, struct ucontext, uc_mcontext);
return &uc->uc_extcontext;
}
static int save_msa_extcontext(void __user *buf)
{
struct msa_extcontext __user *msa = buf;
uint64_t val;
int i, err;
if (!thread_msa_context_live())
return 0;
/*
* Ensure that we can't lose the live MSA context between checking
* for it & writing it to memory.
*/
preempt_disable();
if (is_msa_enabled()) {
/*
* There are no EVA versions of the vector register load/store
* instructions, so MSA context has to be saved to kernel memory
* and then copied to user memory. The save to kernel memory
* should already have been done when handling scalar FP
* context.
*/
BUG_ON(config_enabled(CONFIG_EVA));
err = __put_user(read_msa_csr(), &msa->csr);
err |= _save_msa_all_upper(&msa->wr);
preempt_enable();
} else {
preempt_enable();
err = __put_user(current->thread.fpu.msacsr, &msa->csr);
for (i = 0; i < NUM_FPU_REGS; i++) {
val = get_fpr64(¤t->thread.fpu.fpr[i], 1);
err |= __put_user(val, &msa->wr[i]);
}
}
err |= __put_user(MSA_EXTCONTEXT_MAGIC, &msa->ext.magic);
err |= __put_user(sizeof(*msa), &msa->ext.size);
return err ? -EFAULT : sizeof(*msa);
}
static int restore_msa_extcontext(void __user *buf, unsigned int size)
{
struct msa_extcontext __user *msa = buf;
unsigned long long val;
unsigned int csr;
int i, err;
if (size != sizeof(*msa))
return -EINVAL;
err = get_user(csr, &msa->csr);
if (err)
return err;
preempt_disable();
if (is_msa_enabled()) {
/*
* There are no EVA versions of the vector register load/store
* instructions, so MSA context has to be copied to kernel
* memory and later loaded to registers. The same is true of
* scalar FP context, so FPU & MSA should have already been
* disabled whilst handling scalar FP context.
*/
BUG_ON(config_enabled(CONFIG_EVA));
write_msa_csr(csr);
err |= _restore_msa_all_upper(&msa->wr);
preempt_enable();
} else {
preempt_enable();
current->thread.fpu.msacsr = csr;
for (i = 0; i < NUM_FPU_REGS; i++) {
err |= __get_user(val, &msa->wr[i]);
set_fpr64(¤t->thread.fpu.fpr[i], 1, val);
}
}
return err;
}
static int save_extcontext(void __user *buf)
{
int sz;
sz = save_msa_extcontext(buf);
if (sz < 0)
return sz;
buf += sz;
/* If no context was saved then trivially return */
if (!sz)
return 0;
/* Write the end marker */
if (__put_user(END_EXTCONTEXT_MAGIC, (u32 *)buf))
return -EFAULT;
sz += sizeof(((struct extcontext *)NULL)->magic);
return sz;
}
static int restore_extcontext(void __user *buf)
{
struct extcontext ext;
int err;
while (1) {
err = __get_user(ext.magic, (unsigned int *)buf);
if (err)
return err;
if (ext.magic == END_EXTCONTEXT_MAGIC)
return 0;
err = __get_user(ext.size, (unsigned int *)(buf
+ offsetof(struct extcontext, size)));
if (err)
return err;
switch (ext.magic) {
case MSA_EXTCONTEXT_MAGIC:
err = restore_msa_extcontext(buf, ext.size);
break;
default:
err = -EINVAL;
break;
}
if (err)
return err;
buf += ext.size;
}
}
/*
* Helper routines
*/
int protected_save_fp_context(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
uint32_t __user *used_math = sc + abi->off_sc_used_math;
unsigned int used, ext_sz;
int err;
used = used_math() ? USED_FP : 0;
if (!used)
goto fp_done;
if (!test_thread_flag(TIF_32BIT_FPREGS))
used |= USED_FR1;
if (test_thread_flag(TIF_HYBRID_FPREGS))
used |= USED_HYBRID_FPRS;
/*
* EVA does not have userland equivalents of ldc1 or sdc1, so
* save to the kernel FP context & copy that to userland below.
*/
if (config_enabled(CONFIG_EVA))
lose_fpu(1);
while (1) {
lock_fpu_owner();
if (is_fpu_owner()) {
err = save_fp_context(sc);
unlock_fpu_owner();
} else {
unlock_fpu_owner();
err = copy_fp_to_sigcontext(sc);
}
if (likely(!err))
break;
/* touch the sigcontext and try again */
err = __put_user(0, &fpregs[0]) |
__put_user(0, &fpregs[31]) |
__put_user(0, csr);
if (err)
return err; /* really bad sigcontext */
}
fp_done:
ext_sz = err = save_extcontext(sc_to_extcontext(sc));
if (err < 0)
return err;
used |= ext_sz ? USED_EXTCONTEXT : 0;
return __put_user(used, used_math);
}
int protected_restore_fp_context(void __user *sc)
{
struct mips_abi *abi = current->thread.abi;
uint64_t __user *fpregs = sc + abi->off_sc_fpregs;
uint32_t __user *csr = sc + abi->off_sc_fpc_csr;
uint32_t __user *used_math = sc + abi->off_sc_used_math;
unsigned int used;
int err, sig = 0, tmp __maybe_unused;
err = __get_user(used, used_math);
conditional_used_math(used & USED_FP);
/*
* The signal handler may have used FPU; give it up if the program
* doesn't want it following sigreturn.
*/
if (err || !(used & USED_FP))
lose_fpu(0);
if (err)
return err;
if (!(used & USED_FP))
goto fp_done;
err = sig = fpcsr_pending(csr);
if (err < 0)
return err;
/*
* EVA does not have userland equivalents of ldc1 or sdc1, so we
* disable the FPU here such that the code below simply copies to
* the kernel FP context.
*/
if (config_enabled(CONFIG_EVA))
lose_fpu(0);
while (1) {
lock_fpu_owner();
if (is_fpu_owner()) {
err = restore_fp_context(sc);
unlock_fpu_owner();
} else {
unlock_fpu_owner();
err = copy_fp_from_sigcontext(sc);
}
if (likely(!err))
break;
/* touch the sigcontext and try again */
err = __get_user(tmp, &fpregs[0]) |
__get_user(tmp, &fpregs[31]) |
__get_user(tmp, csr);
if (err)
break; /* really bad sigcontext */
}
fp_done:
if (used & USED_EXTCONTEXT)
err |= restore_extcontext(sc_to_extcontext(sc));
return err ?: sig;
}
int setup_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc)
{
int err = 0;
int i;
err |= __put_user(regs->cp0_epc, &sc->sc_pc);
err |= __put_user(0, &sc->sc_regs[0]);
for (i = 1; i < 32; i++)
err |= __put_user(regs->regs[i], &sc->sc_regs[i]);
#ifdef CONFIG_CPU_HAS_SMARTMIPS
err |= __put_user(regs->acx, &sc->sc_acx);
#endif
err |= __put_user(regs->hi, &sc->sc_mdhi);
err |= __put_user(regs->lo, &sc->sc_mdlo);
if (cpu_has_dsp) {
err |= __put_user(mfhi1(), &sc->sc_hi1);
err |= __put_user(mflo1(), &sc->sc_lo1);
err |= __put_user(mfhi2(), &sc->sc_hi2);
err |= __put_user(mflo2(), &sc->sc_lo2);
err |= __put_user(mfhi3(), &sc->sc_hi3);
err |= __put_user(mflo3(), &sc->sc_lo3);
err |= __put_user(rddsp(DSP_MASK), &sc->sc_dsp);
}
/*
* Save FPU state to signal context. Signal handler
* will "inherit" current FPU state.
*/
err |= protected_save_fp_context(sc);
return err;
}
static size_t extcontext_max_size(void)
{
size_t sz = 0;
/*
* The assumption here is that between this point & the point at which
* the extended context is saved the size of the context should only
* ever be able to shrink (if the task is preempted), but never grow.
* That is, what this function returns is an upper bound on the size of
* the extended context for the current task at the current time.
*/
if (thread_msa_context_live())
sz += sizeof(struct msa_extcontext);
/* If any context is saved then we'll append the end marker */
if (sz)
sz += sizeof(((struct extcontext *)NULL)->magic);
return sz;
}
int fpcsr_pending(unsigned int __user *fpcsr)
{
int err, sig = 0;
unsigned int csr, enabled;
err = __get_user(csr, fpcsr);
enabled = FPU_CSR_UNI_X | ((csr & FPU_CSR_ALL_E) << 5);
/*
* If the signal handler set some FPU exceptions, clear it and
* send SIGFPE.
*/
if (csr & enabled) {
csr &= ~enabled;
err |= __put_user(csr, fpcsr);
sig = SIGFPE;
}
return err ?: sig;
}
int restore_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc)
{
unsigned long treg;
int err = 0;
int i;
/* Always make any pending restarted system calls return -EINTR */
current->restart_block.fn = do_no_restart_syscall;
err |= __get_user(regs->cp0_epc, &sc->sc_pc);
#ifdef CONFIG_CPU_HAS_SMARTMIPS
err |= __get_user(regs->acx, &sc->sc_acx);
#endif
err |= __get_user(regs->hi, &sc->sc_mdhi);
err |= __get_user(regs->lo, &sc->sc_mdlo);
if (cpu_has_dsp) {
err |= __get_user(treg, &sc->sc_hi1); mthi1(treg);
err |= __get_user(treg, &sc->sc_lo1); mtlo1(treg);
err |= __get_user(treg, &sc->sc_hi2); mthi2(treg);
err |= __get_user(treg, &sc->sc_lo2); mtlo2(treg);
err |= __get_user(treg, &sc->sc_hi3); mthi3(treg);
err |= __get_user(treg, &sc->sc_lo3); mtlo3(treg);
err |= __get_user(treg, &sc->sc_dsp); wrdsp(treg, DSP_MASK);
}
for (i = 1; i < 32; i++)
err |= __get_user(regs->regs[i], &sc->sc_regs[i]);
return err ?: protected_restore_fp_context(sc);
}
void __user *get_sigframe(struct ksignal *ksig, struct pt_regs *regs,
size_t frame_size)
{
unsigned long sp;
/* Leave space for potential extended context */
frame_size += extcontext_max_size();
/* Default to using normal stack */
sp = regs->regs[29];
/*
* FPU emulator may have it's own trampoline active just
* above the user stack, 16-bytes before the next lowest
* 16 byte boundary. Try to avoid trashing it.
*/
sp -= 32;
sp = sigsp(sp, ksig);
return (void __user *)((sp - frame_size) & (ICACHE_REFILLS_WORKAROUND_WAR ? ~(cpu_icache_line_size()-1) : ALMASK));
}
/*
* Atomically swap in the new signal mask, and wait for a signal.
*/
#ifdef CONFIG_TRAD_SIGNALS
SYSCALL_DEFINE1(sigsuspend, sigset_t __user *, uset)
{
return sys_rt_sigsuspend(uset, sizeof(sigset_t));
}
#endif
#ifdef CONFIG_TRAD_SIGNALS
SYSCALL_DEFINE3(sigaction, int, sig, const struct sigaction __user *, act,
struct sigaction __user *, oact)
{
struct k_sigaction new_ka, old_ka;
int ret;
int err = 0;
if (act) {
old_sigset_t mask;
if (!access_ok(VERIFY_READ, act, sizeof(*act)))
return -EFAULT;
err |= __get_user(new_ka.sa.sa_handler, &act->sa_handler);
err |= __get_user(new_ka.sa.sa_flags, &act->sa_flags);
err |= __get_user(mask, &act->sa_mask.sig[0]);
if (err)
return -EFAULT;
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)))
return -EFAULT;
err |= __put_user(old_ka.sa.sa_flags, &oact->sa_flags);
err |= __put_user(old_ka.sa.sa_handler, &oact->sa_handler);
err |= __put_user(old_ka.sa.sa_mask.sig[0], oact->sa_mask.sig);
err |= __put_user(0, &oact->sa_mask.sig[1]);
err |= __put_user(0, &oact->sa_mask.sig[2]);
err |= __put_user(0, &oact->sa_mask.sig[3]);
if (err)
return -EFAULT;
}
return ret;
}
#endif
#ifdef CONFIG_TRAD_SIGNALS
asmlinkage void sys_sigreturn(nabi_no_regargs struct pt_regs regs)
{
struct sigframe __user *frame;
sigset_t blocked;
int sig;
frame = (struct sigframe __user *) regs.regs[29];
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&blocked, &frame->sf_mask, sizeof(blocked)))
goto badframe;
set_current_blocked(&blocked);
sig = restore_sigcontext(®s, &frame->sf_sc);
if (sig < 0)
goto badframe;
else if (sig)
force_sig(sig, current);
/*
* Don't let your children do this ...
*/
__asm__ __volatile__(
"move\t$29, %0\n\t"
"j\tsyscall_exit"
:/* no outputs */
:"r" (®s));
/* Unreached */
badframe:
force_sig(SIGSEGV, current);
}
#endif /* CONFIG_TRAD_SIGNALS */
asmlinkage void sys_rt_sigreturn(nabi_no_regargs struct pt_regs regs)
{
struct rt_sigframe __user *frame;
sigset_t set;
int sig;
frame = (struct rt_sigframe __user *) regs.regs[29];
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->rs_uc.uc_sigmask, sizeof(set)))
goto badframe;
set_current_blocked(&set);
sig = restore_sigcontext(®s, &frame->rs_uc.uc_mcontext);
if (sig < 0)
goto badframe;
else if (sig)
force_sig(sig, current);
if (restore_altstack(&frame->rs_uc.uc_stack))
goto badframe;
/*
* Don't let your children do this ...
*/
__asm__ __volatile__(
"move\t$29, %0\n\t"
"j\tsyscall_exit"
:/* no outputs */
:"r" (®s));
/* Unreached */
badframe:
force_sig(SIGSEGV, current);
}
#ifdef CONFIG_TRAD_SIGNALS
static int setup_frame(void *sig_return, struct ksignal *ksig,
struct pt_regs *regs, sigset_t *set)
{
struct sigframe __user *frame;
int err = 0;
frame = get_sigframe(ksig, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame)))
return -EFAULT;
err |= setup_sigcontext(regs, &frame->sf_sc);
err |= __copy_to_user(&frame->sf_mask, set, sizeof(*set));
if (err)
return -EFAULT;
/*
* Arguments to signal handler:
*
* a0 = signal number
* a1 = 0 (should be cause)
* a2 = pointer to struct sigcontext
*
* $25 and c0_epc point to the signal handler, $29 points to the
* struct sigframe.
*/
regs->regs[ 4] = ksig->sig;
regs->regs[ 5] = 0;
regs->regs[ 6] = (unsigned long) &frame->sf_sc;
regs->regs[29] = (unsigned long) frame;
regs->regs[31] = (unsigned long) sig_return;
regs->cp0_epc = regs->regs[25] = (unsigned long) ksig->ka.sa.sa_handler;
DEBUGP("SIG deliver (%s:%d): sp=0x%p pc=0x%lx ra=0x%lx\n",
current->comm, current->pid,
frame, regs->cp0_epc, regs->regs[31]);
return 0;
}
#endif
static int setup_rt_frame(void *sig_return, struct ksignal *ksig,
struct pt_regs *regs, sigset_t *set)
{
struct rt_sigframe __user *frame;
int err = 0;
frame = get_sigframe(ksig, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame)))
return -EFAULT;
/* Create siginfo. */
err |= copy_siginfo_to_user(&frame->rs_info, &ksig->info);
/* Create the ucontext. */
err |= __put_user(0, &frame->rs_uc.uc_flags);
err |= __put_user(NULL, &frame->rs_uc.uc_link);
err |= __save_altstack(&frame->rs_uc.uc_stack, regs->regs[29]);
err |= setup_sigcontext(regs, &frame->rs_uc.uc_mcontext);
err |= __copy_to_user(&frame->rs_uc.uc_sigmask, set, sizeof(*set));
if (err)
return -EFAULT;
/*
* Arguments to signal handler:
*
* a0 = signal number
* a1 = 0 (should be cause)
* a2 = pointer to ucontext
*
* $25 and c0_epc point to the signal handler, $29 points to
* the struct rt_sigframe.
*/
regs->regs[ 4] = ksig->sig;
regs->regs[ 5] = (unsigned long) &frame->rs_info;
regs->regs[ 6] = (unsigned long) &frame->rs_uc;
regs->regs[29] = (unsigned long) frame;
regs->regs[31] = (unsigned long) sig_return;
regs->cp0_epc = regs->regs[25] = (unsigned long) ksig->ka.sa.sa_handler;
DEBUGP("SIG deliver (%s:%d): sp=0x%p pc=0x%lx ra=0x%lx\n",
current->comm, current->pid,
frame, regs->cp0_epc, regs->regs[31]);
return 0;
}
struct mips_abi mips_abi = {
#ifdef CONFIG_TRAD_SIGNALS
.setup_frame = setup_frame,
.signal_return_offset = offsetof(struct mips_vdso, signal_trampoline),
#endif
.setup_rt_frame = setup_rt_frame,
.rt_signal_return_offset =
offsetof(struct mips_vdso, rt_signal_trampoline),
.restart = __NR_restart_syscall,
.off_sc_fpregs = offsetof(struct sigcontext, sc_fpregs),
.off_sc_fpc_csr = offsetof(struct sigcontext, sc_fpc_csr),
.off_sc_used_math = offsetof(struct sigcontext, sc_used_math),
};
static void handle_signal(struct ksignal *ksig, struct pt_regs *regs)
{
sigset_t *oldset = sigmask_to_save();
int ret;
struct mips_abi *abi = current->thread.abi;
#ifdef CONFIG_CPU_MICROMIPS
void *vdso;
unsigned long tmp = (unsigned long)current->mm->context.vdso;
set_isa16_mode(tmp);
vdso = (void *)tmp;
#else
void *vdso = current->mm->context.vdso;
#endif
if (regs->regs[0]) {
switch(regs->regs[2]) {
case ERESTART_RESTARTBLOCK:
case ERESTARTNOHAND:
regs->regs[2] = EINTR;
break;
case ERESTARTSYS:
if (!(ksig->ka.sa.sa_flags & SA_RESTART)) {
regs->regs[2] = EINTR;
break;
}
/* fallthrough */
case ERESTARTNOINTR:
regs->regs[7] = regs->regs[26];
regs->regs[2] = regs->regs[0];
regs->cp0_epc -= 4;
}
regs->regs[0] = 0; /* Don't deal with this again. */
}
if (sig_uses_siginfo(&ksig->ka))
ret = abi->setup_rt_frame(vdso + abi->rt_signal_return_offset,
ksig, regs, oldset);
else
ret = abi->setup_frame(vdso + abi->signal_return_offset, ksig,
regs, oldset);
signal_setup_done(ret, ksig, 0);
}
static void do_signal(struct pt_regs *regs)
{
struct ksignal ksig;
if (get_signal(&ksig)) {
/* Whee! Actually deliver the signal. */
handle_signal(&ksig, regs);
return;
}
if (regs->regs[0]) {
switch (regs->regs[2]) {
case ERESTARTNOHAND:
case ERESTARTSYS:
case ERESTARTNOINTR:
regs->regs[2] = regs->regs[0];
regs->regs[7] = regs->regs[26];
regs->cp0_epc -= 4;
break;
case ERESTART_RESTARTBLOCK:
regs->regs[2] = current->thread.abi->restart;
regs->regs[7] = regs->regs[26];
regs->cp0_epc -= 4;
break;
}
regs->regs[0] = 0; /* Don't deal with this again. */
}
/*
* If there's no signal to deliver, we just put the saved sigmask
* back
*/
restore_saved_sigmask();
}
/*
* notification of userspace execution resumption
* - triggered by the TIF_WORK_MASK flags
*/
asmlinkage void do_notify_resume(struct pt_regs *regs, void *unused,
__u32 thread_info_flags)
{
local_irq_enable();
user_exit();
if (thread_info_flags & _TIF_UPROBE)
uprobe_notify_resume(regs);
/* deal with pending signal delivery */
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
}
user_enter();
}
#ifdef CONFIG_SMP
static int smp_save_fp_context(void __user *sc)
{
return raw_cpu_has_fpu
? save_hw_fp_context(sc)
: copy_fp_to_sigcontext(sc);
}
static int smp_restore_fp_context(void __user *sc)
{
return raw_cpu_has_fpu
? restore_hw_fp_context(sc)
: copy_fp_from_sigcontext(sc);
}
#endif
static int signal_setup(void)
{
/*
* The offset from sigcontext to extended context should be the same
* regardless of the type of signal, such that userland can always know
* where to look if it wishes to find the extended context structures.
*/
BUILD_BUG_ON((offsetof(struct sigframe, sf_extcontext) -
offsetof(struct sigframe, sf_sc)) !=
(offsetof(struct rt_sigframe, rs_uc.uc_extcontext) -
offsetof(struct rt_sigframe, rs_uc.uc_mcontext)));
#ifdef CONFIG_SMP
/* For now just do the cpu_has_fpu check when the functions are invoked */
save_fp_context = smp_save_fp_context;
restore_fp_context = smp_restore_fp_context;
#else
if (cpu_has_fpu) {
save_fp_context = save_hw_fp_context;
restore_fp_context = restore_hw_fp_context;
} else {
save_fp_context = copy_fp_to_sigcontext;
restore_fp_context = copy_fp_from_sigcontext;
}
#endif /* CONFIG_SMP */
return 0;
}
arch_initcall(signal_setup);
| gpl-2.0 |
rkollataj/linux-can-next | drivers/staging/rtl8192e/rtl8192e/r8190P_rtl8256.c | 469 | 6181 | /******************************************************************************
* Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
******************************************************************************/
#include "rtl_core.h"
#include "r8192E_phyreg.h"
#include "r8192E_phy.h"
#include "r8190P_rtl8256.h"
void rtl92e_set_bandwidth(struct net_device *dev,
enum ht_channel_width Bandwidth)
{
u8 eRFPath;
struct r8192_priv *priv = rtllib_priv(dev);
if (priv->card_8192_version != VERSION_8190_BD &&
priv->card_8192_version != VERSION_8190_BE) {
netdev_warn(dev, "%s(): Unknown HW version.\n", __func__);
return;
}
for (eRFPath = 0; eRFPath < priv->NumTotalRFPath; eRFPath++) {
if (!rtl92e_is_legal_rf_path(dev, eRFPath))
continue;
switch (Bandwidth) {
case HT_CHANNEL_WIDTH_20:
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x0b, bMask12Bits, 0x100);
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x2c, bMask12Bits, 0x3d7);
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x0e, bMask12Bits, 0x021);
break;
case HT_CHANNEL_WIDTH_20_40:
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x0b, bMask12Bits, 0x300);
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x2c, bMask12Bits, 0x3ff);
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath,
0x0e, bMask12Bits, 0x0e1);
break;
default:
netdev_err(dev, "%s(): Unknown bandwidth: %#X\n",
__func__, Bandwidth);
break;
}
}
}
bool rtl92e_config_rf(struct net_device *dev)
{
u32 u4RegValue = 0;
u8 eRFPath;
bool rtStatus = true;
struct bb_reg_definition *pPhyReg;
struct r8192_priv *priv = rtllib_priv(dev);
u32 RegOffSetToBeCheck = 0x3;
u32 RegValueToBeCheck = 0x7f1;
u32 RF3_Final_Value = 0;
u8 ConstRetryTimes = 5, RetryTimes = 5;
u8 ret = 0;
priv->NumTotalRFPath = RTL819X_TOTAL_RF_PATH;
for (eRFPath = (enum rf90_radio_path)RF90_PATH_A;
eRFPath < priv->NumTotalRFPath; eRFPath++) {
if (!rtl92e_is_legal_rf_path(dev, eRFPath))
continue;
pPhyReg = &priv->PHYRegDef[eRFPath];
switch (eRFPath) {
case RF90_PATH_A:
case RF90_PATH_C:
u4RegValue = rtl92e_get_bb_reg(dev, pPhyReg->rfintfs,
bRFSI_RFENV);
break;
case RF90_PATH_B:
case RF90_PATH_D:
u4RegValue = rtl92e_get_bb_reg(dev, pPhyReg->rfintfs,
bRFSI_RFENV<<16);
break;
}
rtl92e_set_bb_reg(dev, pPhyReg->rfintfe, bRFSI_RFENV<<16, 0x1);
rtl92e_set_bb_reg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0x1);
rtl92e_set_bb_reg(dev, pPhyReg->rfHSSIPara2,
b3WireAddressLength, 0x0);
rtl92e_set_bb_reg(dev, pPhyReg->rfHSSIPara2,
b3WireDataLength, 0x0);
rtl92e_set_rf_reg(dev, (enum rf90_radio_path)eRFPath, 0x0,
bMask12Bits, 0xbf);
rtStatus = rtl92e_check_bb_and_rf(dev, HW90_BLOCK_RF,
(enum rf90_radio_path)eRFPath);
if (!rtStatus) {
netdev_err(dev, "%s(): Failed to check RF Path %d.\n",
__func__, eRFPath);
goto fail;
}
RetryTimes = ConstRetryTimes;
RF3_Final_Value = 0;
while (RF3_Final_Value != RegValueToBeCheck &&
RetryTimes != 0) {
ret = rtl92e_config_rf_path(dev,
(enum rf90_radio_path)eRFPath);
RF3_Final_Value = rtl92e_get_rf_reg(dev,
(enum rf90_radio_path)eRFPath,
RegOffSetToBeCheck,
bMask12Bits);
RT_TRACE(COMP_RF,
"RF %d %d register final value: %x\n",
eRFPath, RegOffSetToBeCheck,
RF3_Final_Value);
RetryTimes--;
}
switch (eRFPath) {
case RF90_PATH_A:
case RF90_PATH_C:
rtl92e_set_bb_reg(dev, pPhyReg->rfintfs, bRFSI_RFENV,
u4RegValue);
break;
case RF90_PATH_B:
case RF90_PATH_D:
rtl92e_set_bb_reg(dev, pPhyReg->rfintfs,
bRFSI_RFENV<<16, u4RegValue);
break;
}
if (ret) {
netdev_err(dev,
"%s(): Failed to initialize RF Path %d.\n",
__func__, eRFPath);
goto fail;
}
}
RT_TRACE(COMP_PHY, "PHY Initialization Success\n");
return true;
fail:
return false;
}
void rtl92e_set_cck_tx_power(struct net_device *dev, u8 powerlevel)
{
u32 TxAGC = 0;
struct r8192_priv *priv = rtllib_priv(dev);
TxAGC = powerlevel;
if (priv->bDynamicTxLowPower) {
if (priv->CustomerID == RT_CID_819x_Netcore)
TxAGC = 0x22;
else
TxAGC += priv->CckPwEnl;
}
if (TxAGC > 0x24)
TxAGC = 0x24;
rtl92e_set_bb_reg(dev, rTxAGC_CCK_Mcs32, bTxAGCRateCCK, TxAGC);
}
void rtl92e_set_ofdm_tx_power(struct net_device *dev, u8 powerlevel)
{
struct r8192_priv *priv = rtllib_priv(dev);
u32 writeVal, powerBase0, powerBase1, writeVal_tmp;
u8 index = 0;
u16 RegOffset[6] = {0xe00, 0xe04, 0xe10, 0xe14, 0xe18, 0xe1c};
u8 byte0, byte1, byte2, byte3;
powerBase0 = powerlevel + priv->LegacyHTTxPowerDiff;
powerBase0 = (powerBase0 << 24) | (powerBase0 << 16) |
(powerBase0 << 8) | powerBase0;
powerBase1 = powerlevel;
powerBase1 = (powerBase1 << 24) | (powerBase1 << 16) |
(powerBase1 << 8) | powerBase1;
for (index = 0; index < 6; index++) {
writeVal = (u32)(priv->MCSTxPowerLevelOriginalOffset[index] +
((index < 2) ? powerBase0 : powerBase1));
byte0 = (u8)(writeVal & 0x7f);
byte1 = (u8)((writeVal & 0x7f00)>>8);
byte2 = (u8)((writeVal & 0x7f0000)>>16);
byte3 = (u8)((writeVal & 0x7f000000)>>24);
if (byte0 > 0x24)
byte0 = 0x24;
if (byte1 > 0x24)
byte1 = 0x24;
if (byte2 > 0x24)
byte2 = 0x24;
if (byte3 > 0x24)
byte3 = 0x24;
if (index == 3) {
writeVal_tmp = (byte3 << 24) | (byte2 << 16) |
(byte1 << 8) | byte0;
priv->Pwr_Track = writeVal_tmp;
}
if (priv->bDynamicTxHighPower)
writeVal = 0x03030303;
else
writeVal = (byte3 << 24) | (byte2 << 16) |
(byte1 << 8) | byte0;
rtl92e_set_bb_reg(dev, RegOffset[index], 0x7f7f7f7f, writeVal);
}
}
| gpl-2.0 |
garwedgess/LuPuS-CM-iCs | fs/xfs/linux-2.6/xfs_sysctl.c | 469 | 6851 | /*
* Copyright (c) 2001-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
static struct ctl_table_header *xfs_table_header;
#ifdef CONFIG_PROC_FS
STATIC int
xfs_stats_clear_proc_handler(
ctl_table *ctl,
int write,
void __user *buffer,
size_t *lenp,
loff_t *ppos)
{
int c, ret, *valp = ctl->data;
__uint32_t vn_active;
ret = proc_dointvec_minmax(ctl, write, buffer, lenp, ppos);
if (!ret && write && *valp) {
printk("XFS Clearing xfsstats\n");
for_each_possible_cpu(c) {
preempt_disable();
/* save vn_active, it's a universal truth! */
vn_active = per_cpu(xfsstats, c).vn_active;
memset(&per_cpu(xfsstats, c), 0,
sizeof(struct xfsstats));
per_cpu(xfsstats, c).vn_active = vn_active;
preempt_enable();
}
xfs_stats_clear = 0;
}
return ret;
}
#endif /* CONFIG_PROC_FS */
static ctl_table xfs_table[] = {
{
.ctl_name = XFS_SGID_INHERIT,
.procname = "irix_sgid_inherit",
.data = &xfs_params.sgid_inherit.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.sgid_inherit.min,
.extra2 = &xfs_params.sgid_inherit.max
},
{
.ctl_name = XFS_SYMLINK_MODE,
.procname = "irix_symlink_mode",
.data = &xfs_params.symlink_mode.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.symlink_mode.min,
.extra2 = &xfs_params.symlink_mode.max
},
{
.ctl_name = XFS_PANIC_MASK,
.procname = "panic_mask",
.data = &xfs_params.panic_mask.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.panic_mask.min,
.extra2 = &xfs_params.panic_mask.max
},
{
.ctl_name = XFS_ERRLEVEL,
.procname = "error_level",
.data = &xfs_params.error_level.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.error_level.min,
.extra2 = &xfs_params.error_level.max
},
{
.ctl_name = XFS_SYNCD_TIMER,
.procname = "xfssyncd_centisecs",
.data = &xfs_params.syncd_timer.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.syncd_timer.min,
.extra2 = &xfs_params.syncd_timer.max
},
{
.ctl_name = XFS_INHERIT_SYNC,
.procname = "inherit_sync",
.data = &xfs_params.inherit_sync.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.inherit_sync.min,
.extra2 = &xfs_params.inherit_sync.max
},
{
.ctl_name = XFS_INHERIT_NODUMP,
.procname = "inherit_nodump",
.data = &xfs_params.inherit_nodump.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.inherit_nodump.min,
.extra2 = &xfs_params.inherit_nodump.max
},
{
.ctl_name = XFS_INHERIT_NOATIME,
.procname = "inherit_noatime",
.data = &xfs_params.inherit_noatim.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.inherit_noatim.min,
.extra2 = &xfs_params.inherit_noatim.max
},
{
.ctl_name = XFS_BUF_TIMER,
.procname = "xfsbufd_centisecs",
.data = &xfs_params.xfs_buf_timer.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.xfs_buf_timer.min,
.extra2 = &xfs_params.xfs_buf_timer.max
},
{
.ctl_name = XFS_BUF_AGE,
.procname = "age_buffer_centisecs",
.data = &xfs_params.xfs_buf_age.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.xfs_buf_age.min,
.extra2 = &xfs_params.xfs_buf_age.max
},
{
.ctl_name = XFS_INHERIT_NOSYM,
.procname = "inherit_nosymlinks",
.data = &xfs_params.inherit_nosym.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.inherit_nosym.min,
.extra2 = &xfs_params.inherit_nosym.max
},
{
.ctl_name = XFS_ROTORSTEP,
.procname = "rotorstep",
.data = &xfs_params.rotorstep.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.rotorstep.min,
.extra2 = &xfs_params.rotorstep.max
},
{
.ctl_name = XFS_INHERIT_NODFRG,
.procname = "inherit_nodefrag",
.data = &xfs_params.inherit_nodfrg.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.inherit_nodfrg.min,
.extra2 = &xfs_params.inherit_nodfrg.max
},
{
.ctl_name = XFS_FILESTREAM_TIMER,
.procname = "filestream_centisecs",
.data = &xfs_params.fstrm_timer.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.fstrm_timer.min,
.extra2 = &xfs_params.fstrm_timer.max,
},
/* please keep this the last entry */
#ifdef CONFIG_PROC_FS
{
.ctl_name = XFS_STATS_CLEAR,
.procname = "stats_clear",
.data = &xfs_params.stats_clear.val,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &xfs_stats_clear_proc_handler,
.strategy = &sysctl_intvec,
.extra1 = &xfs_params.stats_clear.min,
.extra2 = &xfs_params.stats_clear.max
},
#endif /* CONFIG_PROC_FS */
{}
};
static ctl_table xfs_dir_table[] = {
{
.ctl_name = FS_XFS,
.procname = "xfs",
.mode = 0555,
.child = xfs_table
},
{}
};
static ctl_table xfs_root_table[] = {
{
.ctl_name = CTL_FS,
.procname = "fs",
.mode = 0555,
.child = xfs_dir_table
},
{}
};
int
xfs_sysctl_register(void)
{
xfs_table_header = register_sysctl_table(xfs_root_table);
if (!xfs_table_header)
return -ENOMEM;
return 0;
}
void
xfs_sysctl_unregister(void)
{
unregister_sysctl_table(xfs_table_header);
}
| gpl-2.0 |
Silentlys/android_kernel_zuk_msm8996 | drivers/media/usb/dvb-usb/pctv452e.c | 981 | 25216 | /*
* PCTV 452e DVB driver
*
* Copyright (c) 2006-2008 Dominik Kuhlen <dkuhlen@gmx.net>
*
* TT connect S2-3650-CI Common Interface support, MAC readout
* Copyright (C) 2008 Michael H. Schimek <mschimek@gmx.at>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*/
/* dvb usb framework */
#define DVB_USB_LOG_PREFIX "pctv452e"
#include "dvb-usb.h"
/* Demodulator */
#include "stb0899_drv.h"
#include "stb0899_reg.h"
#include "stb0899_cfg.h"
/* Tuner */
#include "stb6100.h"
#include "stb6100_cfg.h"
/* FE Power */
#include "lnbp22.h"
#include "dvb_ca_en50221.h"
#include "ttpci-eeprom.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define ISOC_INTERFACE_ALTERNATIVE 3
#define SYNC_BYTE_OUT 0xaa
#define SYNC_BYTE_IN 0x55
/* guessed: (copied from ttusb-budget) */
#define PCTV_CMD_RESET 0x15
/* command to poll IR receiver */
#define PCTV_CMD_IR 0x1b
/* command to send I2C */
#define PCTV_CMD_I2C 0x31
#define I2C_ADDR_STB0899 (0xd0 >> 1)
#define I2C_ADDR_STB6100 (0xc0 >> 1)
#define I2C_ADDR_LNBP22 (0x10 >> 1)
#define I2C_ADDR_24C16 (0xa0 >> 1)
#define I2C_ADDR_24C64 (0xa2 >> 1)
/* pctv452e sends us this amount of data for each issued usb-command */
#define PCTV_ANSWER_LEN 64
/* Wait up to 1000ms for device */
#define PCTV_TIMEOUT 1000
#define PCTV_LED_GPIO STB0899_GPIO01
#define PCTV_LED_GREEN 0x82
#define PCTV_LED_ORANGE 0x02
#define ci_dbg(format, arg...) \
do { \
if (0) \
printk(KERN_DEBUG DVB_USB_LOG_PREFIX \
": " format "\n" , ## arg); \
} while (0)
enum {
TT3650_CMD_CI_TEST = 0x40,
TT3650_CMD_CI_RD_CTRL,
TT3650_CMD_CI_WR_CTRL,
TT3650_CMD_CI_RD_ATTR,
TT3650_CMD_CI_WR_ATTR,
TT3650_CMD_CI_RESET,
TT3650_CMD_CI_SET_VIDEO_PORT
};
static struct stb0899_postproc pctv45e_postproc[] = {
{ PCTV_LED_GPIO, STB0899_GPIOPULLUP },
{ 0, 0 }
};
/*
* stores all private variables for communication with the PCTV452e DVB-S2
*/
struct pctv452e_state {
struct dvb_ca_en50221 ca;
struct mutex ca_mutex;
u8 c; /* transaction counter, wraps around... */
u8 initialized; /* set to 1 if 0x15 has been sent */
u16 last_rc_key;
};
static int tt3650_ci_msg(struct dvb_usb_device *d, u8 cmd, u8 *data,
unsigned int write_len, unsigned int read_len)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[64];
u8 id;
unsigned int rlen;
int ret;
BUG_ON(NULL == data && 0 != (write_len | read_len));
BUG_ON(write_len > 64 - 4);
BUG_ON(read_len > 64 - 4);
id = state->c++;
buf[0] = SYNC_BYTE_OUT;
buf[1] = id;
buf[2] = cmd;
buf[3] = write_len;
memcpy(buf + 4, data, write_len);
rlen = (read_len > 0) ? 64 : 0;
ret = dvb_usb_generic_rw(d, buf, 4 + write_len,
buf, rlen, /* delay_ms */ 0);
if (0 != ret)
goto failed;
ret = -EIO;
if (SYNC_BYTE_IN != buf[0] || id != buf[1])
goto failed;
memcpy(data, buf + 4, read_len);
return 0;
failed:
err("CI error %d; %02X %02X %02X -> %*ph.",
ret, SYNC_BYTE_OUT, id, cmd, 3, buf);
return ret;
}
static int tt3650_ci_msg_locked(struct dvb_ca_en50221 *ca,
u8 cmd, u8 *data, unsigned int write_len,
unsigned int read_len)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
int ret;
mutex_lock(&state->ca_mutex);
ret = tt3650_ci_msg(d, cmd, data, write_len, read_len);
mutex_unlock(&state->ca_mutex);
return ret;
}
static int tt3650_ci_read_attribute_mem(struct dvb_ca_en50221 *ca,
int slot, int address)
{
u8 buf[3];
int ret;
if (0 != slot)
return -EINVAL;
buf[0] = (address >> 8) & 0x0F;
buf[1] = address;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_RD_ATTR, buf, 2, 3);
ci_dbg("%s %04x -> %d 0x%02x",
__func__, address, ret, buf[2]);
if (ret < 0)
return ret;
return buf[2];
}
static int tt3650_ci_write_attribute_mem(struct dvb_ca_en50221 *ca,
int slot, int address, u8 value)
{
u8 buf[3];
ci_dbg("%s %d 0x%04x 0x%02x",
__func__, slot, address, value);
if (0 != slot)
return -EINVAL;
buf[0] = (address >> 8) & 0x0F;
buf[1] = address;
buf[2] = value;
return tt3650_ci_msg_locked(ca, TT3650_CMD_CI_WR_ATTR, buf, 3, 3);
}
static int tt3650_ci_read_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address)
{
u8 buf[2];
int ret;
if (0 != slot)
return -EINVAL;
buf[0] = address & 3;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_RD_CTRL, buf, 1, 2);
ci_dbg("%s 0x%02x -> %d 0x%02x",
__func__, address, ret, buf[1]);
if (ret < 0)
return ret;
return buf[1];
}
static int tt3650_ci_write_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address,
u8 value)
{
u8 buf[2];
ci_dbg("%s %d 0x%02x 0x%02x",
__func__, slot, address, value);
if (0 != slot)
return -EINVAL;
buf[0] = address;
buf[1] = value;
return tt3650_ci_msg_locked(ca, TT3650_CMD_CI_WR_CTRL, buf, 2, 2);
}
static int tt3650_ci_set_video_port(struct dvb_ca_en50221 *ca,
int slot,
int enable)
{
u8 buf[1];
int ret;
ci_dbg("%s %d %d", __func__, slot, enable);
if (0 != slot)
return -EINVAL;
enable = !!enable;
buf[0] = enable;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_SET_VIDEO_PORT, buf, 1, 1);
if (ret < 0)
return ret;
if (enable != buf[0]) {
err("CI not %sabled.", enable ? "en" : "dis");
return -EIO;
}
return 0;
}
static int tt3650_ci_slot_shutdown(struct dvb_ca_en50221 *ca, int slot)
{
return tt3650_ci_set_video_port(ca, slot, /* enable */ 0);
}
static int tt3650_ci_slot_ts_enable(struct dvb_ca_en50221 *ca, int slot)
{
return tt3650_ci_set_video_port(ca, slot, /* enable */ 1);
}
static int tt3650_ci_slot_reset(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[1];
int ret;
ci_dbg("%s %d", __func__, slot);
if (0 != slot)
return -EINVAL;
buf[0] = 0;
mutex_lock(&state->ca_mutex);
ret = tt3650_ci_msg(d, TT3650_CMD_CI_RESET, buf, 1, 1);
if (0 != ret)
goto failed;
msleep(500);
buf[0] = 1;
ret = tt3650_ci_msg(d, TT3650_CMD_CI_RESET, buf, 1, 1);
if (0 != ret)
goto failed;
msleep(500);
buf[0] = 0; /* FTA */
ret = tt3650_ci_msg(d, TT3650_CMD_CI_SET_VIDEO_PORT, buf, 1, 1);
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int tt3650_ci_poll_slot_status(struct dvb_ca_en50221 *ca,
int slot,
int open)
{
u8 buf[1];
int ret;
if (0 != slot)
return -EINVAL;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_TEST, buf, 0, 1);
if (0 != ret)
return ret;
if (1 == buf[0])
return DVB_CA_EN50221_POLL_CAM_PRESENT |
DVB_CA_EN50221_POLL_CAM_READY;
return 0;
}
static void tt3650_ci_uninit(struct dvb_usb_device *d)
{
struct pctv452e_state *state;
ci_dbg("%s", __func__);
if (NULL == d)
return;
state = (struct pctv452e_state *)d->priv;
if (NULL == state)
return;
if (NULL == state->ca.data)
return;
/* Error ignored. */
tt3650_ci_set_video_port(&state->ca, /* slot */ 0, /* enable */ 0);
dvb_ca_en50221_release(&state->ca);
memset(&state->ca, 0, sizeof(state->ca));
}
static int tt3650_ci_init(struct dvb_usb_adapter *a)
{
struct dvb_usb_device *d = a->dev;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
int ret;
ci_dbg("%s", __func__);
mutex_init(&state->ca_mutex);
state->ca.owner = THIS_MODULE;
state->ca.read_attribute_mem = tt3650_ci_read_attribute_mem;
state->ca.write_attribute_mem = tt3650_ci_write_attribute_mem;
state->ca.read_cam_control = tt3650_ci_read_cam_control;
state->ca.write_cam_control = tt3650_ci_write_cam_control;
state->ca.slot_reset = tt3650_ci_slot_reset;
state->ca.slot_shutdown = tt3650_ci_slot_shutdown;
state->ca.slot_ts_enable = tt3650_ci_slot_ts_enable;
state->ca.poll_slot_status = tt3650_ci_poll_slot_status;
state->ca.data = d;
ret = dvb_ca_en50221_init(&a->dvb_adap,
&state->ca,
/* flags */ 0,
/* n_slots */ 1);
if (0 != ret) {
err("Cannot initialize CI: Error %d.", ret);
memset(&state->ca, 0, sizeof(state->ca));
return ret;
}
info("CI initialized.");
return 0;
}
#define CMD_BUFFER_SIZE 0x28
static int pctv452e_i2c_msg(struct dvb_usb_device *d, u8 addr,
const u8 *snd_buf, u8 snd_len,
u8 *rcv_buf, u8 rcv_len)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[64];
u8 id;
int ret;
id = state->c++;
ret = -EINVAL;
if (snd_len > 64 - 7 || rcv_len > 64 - 7)
goto failed;
buf[0] = SYNC_BYTE_OUT;
buf[1] = id;
buf[2] = PCTV_CMD_I2C;
buf[3] = snd_len + 3;
buf[4] = addr << 1;
buf[5] = snd_len;
buf[6] = rcv_len;
memcpy(buf + 7, snd_buf, snd_len);
ret = dvb_usb_generic_rw(d, buf, 7 + snd_len,
buf, /* rcv_len */ 64,
/* delay_ms */ 0);
if (ret < 0)
goto failed;
/* TT USB protocol error. */
ret = -EIO;
if (SYNC_BYTE_IN != buf[0] || id != buf[1])
goto failed;
/* I2C device didn't respond as expected. */
ret = -EREMOTEIO;
if (buf[5] < snd_len || buf[6] < rcv_len)
goto failed;
memcpy(rcv_buf, buf + 7, rcv_len);
return rcv_len;
failed:
err("I2C error %d; %02X %02X %02X %02X %02X -> "
"%02X %02X %02X %02X %02X.",
ret, SYNC_BYTE_OUT, id, addr << 1, snd_len, rcv_len,
buf[0], buf[1], buf[4], buf[5], buf[6]);
return ret;
}
static int pctv452e_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msg,
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adapter);
int i;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
u8 addr, snd_len, rcv_len, *snd_buf, *rcv_buf;
int ret;
if (msg[i].flags & I2C_M_RD) {
addr = msg[i].addr;
snd_buf = NULL;
snd_len = 0;
rcv_buf = msg[i].buf;
rcv_len = msg[i].len;
} else {
addr = msg[i].addr;
snd_buf = msg[i].buf;
snd_len = msg[i].len;
rcv_buf = NULL;
rcv_len = 0;
}
ret = pctv452e_i2c_msg(d, addr, snd_buf, snd_len, rcv_buf,
rcv_len);
if (ret < rcv_len)
break;
}
mutex_unlock(&d->i2c_mutex);
return i;
}
static u32 pctv452e_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static int pctv452e_power_ctrl(struct dvb_usb_device *d, int i)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 b0[] = { 0xaa, 0, PCTV_CMD_RESET, 1, 0 };
u8 rx[PCTV_ANSWER_LEN];
int ret;
info("%s: %d\n", __func__, i);
if (!i)
return 0;
if (state->initialized)
return 0;
/* hmm where shoud this should go? */
ret = usb_set_interface(d->udev, 0, ISOC_INTERFACE_ALTERNATIVE);
if (ret != 0)
info("%s: Warning set interface returned: %d\n",
__func__, ret);
/* this is a one-time initialization, dont know where to put */
b0[1] = state->c++;
/* reset board */
ret = dvb_usb_generic_rw(d, b0, sizeof(b0), rx, PCTV_ANSWER_LEN, 0);
if (ret)
return ret;
b0[1] = state->c++;
b0[4] = 1;
/* reset board (again?) */
ret = dvb_usb_generic_rw(d, b0, sizeof(b0), rx, PCTV_ANSWER_LEN, 0);
if (ret)
return ret;
state->initialized = 1;
return 0;
}
static int pctv452e_rc_query(struct dvb_usb_device *d)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 b[CMD_BUFFER_SIZE];
u8 rx[PCTV_ANSWER_LEN];
int ret, i;
u8 id = state->c++;
/* prepare command header */
b[0] = SYNC_BYTE_OUT;
b[1] = id;
b[2] = PCTV_CMD_IR;
b[3] = 0;
/* send ir request */
ret = dvb_usb_generic_rw(d, b, 4, rx, PCTV_ANSWER_LEN, 0);
if (ret != 0)
return ret;
if (debug > 3) {
info("%s: read: %2d: %*ph: ", __func__, ret, 3, rx);
for (i = 0; (i < rx[3]) && ((i+3) < PCTV_ANSWER_LEN); i++)
info(" %02x", rx[i+3]);
info("\n");
}
if ((rx[3] == 9) && (rx[12] & 0x01)) {
/* got a "press" event */
state->last_rc_key = RC_SCANCODE_RC5(rx[7], rx[6]);
if (debug > 2)
info("%s: cmd=0x%02x sys=0x%02x\n",
__func__, rx[6], rx[7]);
rc_keydown(d->rc_dev, RC_TYPE_RC5, state->last_rc_key, 0);
} else if (state->last_rc_key) {
rc_keyup(d->rc_dev);
state->last_rc_key = 0;
}
return 0;
}
static int pctv452e_read_mac_address(struct dvb_usb_device *d, u8 mac[6])
{
const u8 mem_addr[] = { 0x1f, 0xcc };
u8 encoded_mac[20];
int ret;
ret = -EAGAIN;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
goto failed;
ret = pctv452e_i2c_msg(d, I2C_ADDR_24C16,
mem_addr + 1, /* snd_len */ 1,
encoded_mac, /* rcv_len */ 20);
if (-EREMOTEIO == ret)
/* Caution! A 24C16 interprets 0xA2 0x1F 0xCC as a
byte write if /WC is low. */
ret = pctv452e_i2c_msg(d, I2C_ADDR_24C64,
mem_addr, 2,
encoded_mac, 20);
mutex_unlock(&d->i2c_mutex);
if (20 != ret)
goto failed;
ret = ttpci_eeprom_decode_mac(mac, encoded_mac);
if (0 != ret)
goto failed;
return 0;
failed:
memset(mac, 0, 6);
return ret;
}
static const struct stb0899_s1_reg pctv452e_init_dev[] = {
{ STB0899_DISCNTRL1, 0x26 },
{ STB0899_DISCNTRL2, 0x80 },
{ STB0899_DISRX_ST0, 0x04 },
{ STB0899_DISRX_ST1, 0x20 },
{ STB0899_DISPARITY, 0x00 },
{ STB0899_DISFIFO, 0x00 },
{ STB0899_DISF22, 0x99 },
{ STB0899_DISF22RX, 0x85 }, /* 0xa8 */
{ STB0899_ACRPRESC, 0x11 },
{ STB0899_ACRDIV1, 0x0a },
{ STB0899_ACRDIV2, 0x05 },
{ STB0899_DACR1 , 0x00 },
{ STB0899_DACR2 , 0x00 },
{ STB0899_OUTCFG, 0x00 },
{ STB0899_MODECFG, 0x00 }, /* Inversion */
{ STB0899_IRQMSK_3, 0xf3 },
{ STB0899_IRQMSK_2, 0xfc },
{ STB0899_IRQMSK_1, 0xff },
{ STB0899_IRQMSK_0, 0xff },
{ STB0899_I2CCFG, 0x88 },
{ STB0899_I2CRPT, 0x58 },
{ STB0899_GPIO00CFG, 0x82 },
{ STB0899_GPIO01CFG, 0x82 }, /* LED: 0x02 green, 0x82 orange */
{ STB0899_GPIO02CFG, 0x82 },
{ STB0899_GPIO03CFG, 0x82 },
{ STB0899_GPIO04CFG, 0x82 },
{ STB0899_GPIO05CFG, 0x82 },
{ STB0899_GPIO06CFG, 0x82 },
{ STB0899_GPIO07CFG, 0x82 },
{ STB0899_GPIO08CFG, 0x82 },
{ STB0899_GPIO09CFG, 0x82 },
{ STB0899_GPIO10CFG, 0x82 },
{ STB0899_GPIO11CFG, 0x82 },
{ STB0899_GPIO12CFG, 0x82 },
{ STB0899_GPIO13CFG, 0x82 },
{ STB0899_GPIO14CFG, 0x82 },
{ STB0899_GPIO15CFG, 0x82 },
{ STB0899_GPIO16CFG, 0x82 },
{ STB0899_GPIO17CFG, 0x82 },
{ STB0899_GPIO18CFG, 0x82 },
{ STB0899_GPIO19CFG, 0x82 },
{ STB0899_GPIO20CFG, 0x82 },
{ STB0899_SDATCFG, 0xb8 },
{ STB0899_SCLTCFG, 0xba },
{ STB0899_AGCRFCFG, 0x1c }, /* 0x11 DVB-S; 0x1c DVB-S2 (1c, rjkm) */
{ STB0899_GPIO22, 0x82 },
{ STB0899_GPIO21, 0x91 },
{ STB0899_DIRCLKCFG, 0x82 },
{ STB0899_CLKOUT27CFG, 0x7e },
{ STB0899_STDBYCFG, 0x82 },
{ STB0899_CS0CFG, 0x82 },
{ STB0899_CS1CFG, 0x82 },
{ STB0899_DISEQCOCFG, 0x20 },
{ STB0899_NCOARSE, 0x15 }, /* 0x15 27Mhz, F/3 198MHz, F/6 108MHz */
{ STB0899_SYNTCTRL, 0x00 }, /* 0x00 CLKI, 0x02 XTALI */
{ STB0899_FILTCTRL, 0x00 },
{ STB0899_SYSCTRL, 0x00 },
{ STB0899_STOPCLK1, 0x20 }, /* orig: 0x00 budget-ci: 0x20 */
{ STB0899_STOPCLK2, 0x00 },
{ STB0899_INTBUFCTRL, 0x0a },
{ STB0899_AGC2I1, 0x00 },
{ STB0899_AGC2I2, 0x00 },
{ STB0899_AGCIQIN, 0x00 },
{ STB0899_TSTRES, 0x40 }, /* rjkm */
{ 0xffff, 0xff },
};
static const struct stb0899_s1_reg pctv452e_init_s1_demod[] = {
{ STB0899_DEMOD, 0x00 },
{ STB0899_RCOMPC, 0xc9 },
{ STB0899_AGC1CN, 0x01 },
{ STB0899_AGC1REF, 0x10 },
{ STB0899_RTC, 0x23 },
{ STB0899_TMGCFG, 0x4e },
{ STB0899_AGC2REF, 0x34 },
{ STB0899_TLSR, 0x84 },
{ STB0899_CFD, 0xf7 },
{ STB0899_ACLC, 0x87 },
{ STB0899_BCLC, 0x94 },
{ STB0899_EQON, 0x41 },
{ STB0899_LDT, 0xf1 },
{ STB0899_LDT2, 0xe3 },
{ STB0899_EQUALREF, 0xb4 },
{ STB0899_TMGRAMP, 0x10 },
{ STB0899_TMGTHD, 0x30 },
{ STB0899_IDCCOMP, 0xfd },
{ STB0899_QDCCOMP, 0xff },
{ STB0899_POWERI, 0x0c },
{ STB0899_POWERQ, 0x0f },
{ STB0899_RCOMP, 0x6c },
{ STB0899_AGCIQIN, 0x80 },
{ STB0899_AGC2I1, 0x06 },
{ STB0899_AGC2I2, 0x00 },
{ STB0899_TLIR, 0x30 },
{ STB0899_RTF, 0x7f },
{ STB0899_DSTATUS, 0x00 },
{ STB0899_LDI, 0xbc },
{ STB0899_CFRM, 0xea },
{ STB0899_CFRL, 0x31 },
{ STB0899_NIRM, 0x2b },
{ STB0899_NIRL, 0x80 },
{ STB0899_ISYMB, 0x1d },
{ STB0899_QSYMB, 0xa6 },
{ STB0899_SFRH, 0x2f },
{ STB0899_SFRM, 0x68 },
{ STB0899_SFRL, 0x40 },
{ STB0899_SFRUPH, 0x2f },
{ STB0899_SFRUPM, 0x68 },
{ STB0899_SFRUPL, 0x40 },
{ STB0899_EQUAI1, 0x02 },
{ STB0899_EQUAQ1, 0xff },
{ STB0899_EQUAI2, 0x04 },
{ STB0899_EQUAQ2, 0x05 },
{ STB0899_EQUAI3, 0x02 },
{ STB0899_EQUAQ3, 0xfd },
{ STB0899_EQUAI4, 0x03 },
{ STB0899_EQUAQ4, 0x07 },
{ STB0899_EQUAI5, 0x08 },
{ STB0899_EQUAQ5, 0xf5 },
{ STB0899_DSTATUS2, 0x00 },
{ STB0899_VSTATUS, 0x00 },
{ STB0899_VERROR, 0x86 },
{ STB0899_IQSWAP, 0x2a },
{ STB0899_ECNT1M, 0x00 },
{ STB0899_ECNT1L, 0x00 },
{ STB0899_ECNT2M, 0x00 },
{ STB0899_ECNT2L, 0x00 },
{ STB0899_ECNT3M, 0x0a },
{ STB0899_ECNT3L, 0xad },
{ STB0899_FECAUTO1, 0x06 },
{ STB0899_FECM, 0x01 },
{ STB0899_VTH12, 0xb0 },
{ STB0899_VTH23, 0x7a },
{ STB0899_VTH34, 0x58 },
{ STB0899_VTH56, 0x38 },
{ STB0899_VTH67, 0x34 },
{ STB0899_VTH78, 0x24 },
{ STB0899_PRVIT, 0xff },
{ STB0899_VITSYNC, 0x19 },
{ STB0899_RSULC, 0xb1 }, /* DVB = 0xb1, DSS = 0xa1 */
{ STB0899_TSULC, 0x42 },
{ STB0899_RSLLC, 0x41 },
{ STB0899_TSLPL, 0x12 },
{ STB0899_TSCFGH, 0x0c },
{ STB0899_TSCFGM, 0x00 },
{ STB0899_TSCFGL, 0x00 },
{ STB0899_TSOUT, 0x69 }, /* 0x0d for CAM */
{ STB0899_RSSYNCDEL, 0x00 },
{ STB0899_TSINHDELH, 0x02 },
{ STB0899_TSINHDELM, 0x00 },
{ STB0899_TSINHDELL, 0x00 },
{ STB0899_TSLLSTKM, 0x1b },
{ STB0899_TSLLSTKL, 0xb3 },
{ STB0899_TSULSTKM, 0x00 },
{ STB0899_TSULSTKL, 0x00 },
{ STB0899_PCKLENUL, 0xbc },
{ STB0899_PCKLENLL, 0xcc },
{ STB0899_RSPCKLEN, 0xbd },
{ STB0899_TSSTATUS, 0x90 },
{ STB0899_ERRCTRL1, 0xb6 },
{ STB0899_ERRCTRL2, 0x95 },
{ STB0899_ERRCTRL3, 0x8d },
{ STB0899_DMONMSK1, 0x27 },
{ STB0899_DMONMSK0, 0x03 },
{ STB0899_DEMAPVIT, 0x5c },
{ STB0899_PLPARM, 0x19 },
{ STB0899_PDELCTRL, 0x48 },
{ STB0899_PDELCTRL2, 0x00 },
{ STB0899_BBHCTRL1, 0x00 },
{ STB0899_BBHCTRL2, 0x00 },
{ STB0899_HYSTTHRESH, 0x77 },
{ STB0899_MATCSTM, 0x00 },
{ STB0899_MATCSTL, 0x00 },
{ STB0899_UPLCSTM, 0x00 },
{ STB0899_UPLCSTL, 0x00 },
{ STB0899_DFLCSTM, 0x00 },
{ STB0899_DFLCSTL, 0x00 },
{ STB0899_SYNCCST, 0x00 },
{ STB0899_SYNCDCSTM, 0x00 },
{ STB0899_SYNCDCSTL, 0x00 },
{ STB0899_ISI_ENTRY, 0x00 },
{ STB0899_ISI_BIT_EN, 0x00 },
{ STB0899_MATSTRM, 0xf0 },
{ STB0899_MATSTRL, 0x02 },
{ STB0899_UPLSTRM, 0x45 },
{ STB0899_UPLSTRL, 0x60 },
{ STB0899_DFLSTRM, 0xe3 },
{ STB0899_DFLSTRL, 0x00 },
{ STB0899_SYNCSTR, 0x47 },
{ STB0899_SYNCDSTRM, 0x05 },
{ STB0899_SYNCDSTRL, 0x18 },
{ STB0899_CFGPDELSTATUS1, 0x19 },
{ STB0899_CFGPDELSTATUS2, 0x2b },
{ STB0899_BBFERRORM, 0x00 },
{ STB0899_BBFERRORL, 0x01 },
{ STB0899_UPKTERRORM, 0x00 },
{ STB0899_UPKTERRORL, 0x00 },
{ 0xffff, 0xff },
};
static struct stb0899_config stb0899_config = {
.init_dev = pctv452e_init_dev,
.init_s2_demod = stb0899_s2_init_2,
.init_s1_demod = pctv452e_init_s1_demod,
.init_s2_fec = stb0899_s2_init_4,
.init_tst = stb0899_s1_init_5,
.demod_address = I2C_ADDR_STB0899, /* I2C Address */
.block_sync_mode = STB0899_SYNC_FORCED, /* ? */
.xtal_freq = 27000000, /* Assume Hz ? */
.inversion = IQ_SWAP_ON,
.lo_clk = 76500000,
.hi_clk = 99000000,
.ts_output_mode = 0, /* Use parallel mode */
.clock_polarity = 0,
.data_clk_parity = 0,
.fec_mode = 0,
.esno_ave = STB0899_DVBS2_ESNO_AVE,
.esno_quant = STB0899_DVBS2_ESNO_QUANT,
.avframes_coarse = STB0899_DVBS2_AVFRAMES_COARSE,
.avframes_fine = STB0899_DVBS2_AVFRAMES_FINE,
.miss_threshold = STB0899_DVBS2_MISS_THRESHOLD,
.uwp_threshold_acq = STB0899_DVBS2_UWP_THRESHOLD_ACQ,
.uwp_threshold_track = STB0899_DVBS2_UWP_THRESHOLD_TRACK,
.uwp_threshold_sof = STB0899_DVBS2_UWP_THRESHOLD_SOF,
.sof_search_timeout = STB0899_DVBS2_SOF_SEARCH_TIMEOUT,
.btr_nco_bits = STB0899_DVBS2_BTR_NCO_BITS,
.btr_gain_shift_offset = STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET,
.crl_nco_bits = STB0899_DVBS2_CRL_NCO_BITS,
.ldpc_max_iter = STB0899_DVBS2_LDPC_MAX_ITER,
.tuner_get_frequency = stb6100_get_frequency,
.tuner_set_frequency = stb6100_set_frequency,
.tuner_set_bandwidth = stb6100_set_bandwidth,
.tuner_get_bandwidth = stb6100_get_bandwidth,
.tuner_set_rfsiggain = NULL,
/* helper for switching LED green/orange */
.postproc = pctv45e_postproc
};
static struct stb6100_config stb6100_config = {
.tuner_address = I2C_ADDR_STB6100,
.refclock = 27000000
};
static struct i2c_algorithm pctv452e_i2c_algo = {
.master_xfer = pctv452e_i2c_xfer,
.functionality = pctv452e_i2c_func
};
static int pctv452e_frontend_attach(struct dvb_usb_adapter *a)
{
struct usb_device_id *id;
a->fe_adap[0].fe = dvb_attach(stb0899_attach, &stb0899_config,
&a->dev->i2c_adap);
if (!a->fe_adap[0].fe)
return -ENODEV;
if ((dvb_attach(lnbp22_attach, a->fe_adap[0].fe,
&a->dev->i2c_adap)) == NULL)
err("Cannot attach lnbp22\n");
id = a->dev->desc->warm_ids[0];
if (USB_VID_TECHNOTREND == id->idVendor
&& USB_PID_TECHNOTREND_CONNECT_S2_3650_CI == id->idProduct)
/* Error ignored. */
tt3650_ci_init(a);
return 0;
}
static int pctv452e_tuner_attach(struct dvb_usb_adapter *a)
{
if (!a->fe_adap[0].fe)
return -ENODEV;
if (dvb_attach(stb6100_attach, a->fe_adap[0].fe, &stb6100_config,
&a->dev->i2c_adap) == NULL) {
err("%s failed\n", __func__);
return -ENODEV;
}
return 0;
}
static struct usb_device_id pctv452e_usb_table[] = {
{USB_DEVICE(USB_VID_PINNACLE, USB_PID_PCTV_452E)},
{USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_S2_3600)},
{USB_DEVICE(USB_VID_TECHNOTREND,
USB_PID_TECHNOTREND_CONNECT_S2_3650_CI)},
{}
};
MODULE_DEVICE_TABLE(usb, pctv452e_usb_table);
static struct dvb_usb_device_properties pctv452e_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER, /* more ? */
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = sizeof(struct pctv452e_state),
.power_ctrl = pctv452e_power_ctrl,
.rc.core = {
.rc_codes = RC_MAP_DIB0700_RC5_TABLE,
.allowed_protos = RC_BIT_RC5,
.rc_query = pctv452e_rc_query,
.rc_interval = 100,
},
.num_adapters = 1,
.adapter = {{
.num_frontends = 1,
.fe = {{
.frontend_attach = pctv452e_frontend_attach,
.tuner_attach = pctv452e_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_ISOC,
.count = 4,
.endpoint = 0x02,
.u = {
.isoc = {
.framesperurb = 4,
.framesize = 940,
.interval = 1
}
}
},
} },
} },
.i2c_algo = &pctv452e_i2c_algo,
.generic_bulk_ctrl_endpoint = 1, /* allow generice rw function */
.num_device_descs = 1,
.devices = {
{ .name = "PCTV HDTV USB",
.cold_ids = { NULL, NULL }, /* this is a warm only device */
.warm_ids = { &pctv452e_usb_table[0], NULL }
},
{ NULL },
}
};
static struct dvb_usb_device_properties tt_connect_s2_3600_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER, /* more ? */
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = sizeof(struct pctv452e_state),
.power_ctrl = pctv452e_power_ctrl,
.read_mac_address = pctv452e_read_mac_address,
.rc.core = {
.rc_codes = RC_MAP_TT_1500,
.allowed_protos = RC_BIT_RC5,
.rc_query = pctv452e_rc_query,
.rc_interval = 100,
},
.num_adapters = 1,
.adapter = {{
.num_frontends = 1,
.fe = {{
.frontend_attach = pctv452e_frontend_attach,
.tuner_attach = pctv452e_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_ISOC,
.count = 7,
.endpoint = 0x02,
.u = {
.isoc = {
.framesperurb = 4,
.framesize = 940,
.interval = 1
}
}
},
} },
} },
.i2c_algo = &pctv452e_i2c_algo,
.generic_bulk_ctrl_endpoint = 1, /* allow generic rw function*/
.num_device_descs = 2,
.devices = {
{ .name = "Technotrend TT Connect S2-3600",
.cold_ids = { NULL, NULL }, /* this is a warm only device */
.warm_ids = { &pctv452e_usb_table[1], NULL }
},
{ .name = "Technotrend TT Connect S2-3650-CI",
.cold_ids = { NULL, NULL },
.warm_ids = { &pctv452e_usb_table[2], NULL }
},
{ NULL },
}
};
static void pctv452e_usb_disconnect(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
tt3650_ci_uninit(d);
dvb_usb_device_exit(intf);
}
static int pctv452e_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
if (0 == dvb_usb_device_init(intf, &pctv452e_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &tt_connect_s2_3600_properties,
THIS_MODULE, NULL, adapter_nr))
return 0;
return -ENODEV;
}
static struct usb_driver pctv452e_usb_driver = {
.name = "pctv452e",
.probe = pctv452e_usb_probe,
.disconnect = pctv452e_usb_disconnect,
.id_table = pctv452e_usb_table,
};
module_usb_driver(pctv452e_usb_driver);
MODULE_AUTHOR("Dominik Kuhlen <dkuhlen@gmx.net>");
MODULE_AUTHOR("Andre Weidemann <Andre.Weidemann@web.de>");
MODULE_AUTHOR("Michael H. Schimek <mschimek@gmx.at>");
MODULE_DESCRIPTION("Pinnacle PCTV HDTV USB DVB / TT connect S2-3600 Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
spezi77/kernel_msm | drivers/bluetooth/hci_ath.c | 1237 | 10727 | /*
* Atheros Communication Bluetooth HCIATH3K UART protocol
*
* HCIATH3K (HCI Atheros AR300x Protocol) is a Atheros Communication's
* power management protocol extension to H4 to support AR300x Bluetooth Chip.
*
* Copyright (c) 2009-2010 Atheros Communications Inc.
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Acknowledgements:
* This file is based on hci_h4.c, which was written
* by Maxim Krasnyansky and Marcel Holtmann.
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/errno.h>
#include <linux/ioctl.h>
#include <linux/skbuff.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "hci_uart.h"
unsigned int enableuartsleep = 1;
module_param(enableuartsleep, uint, 0644);
/*
* Global variables
*/
/** Global state flags */
static unsigned long flags;
/** Tasklet to respond to change in hostwake line */
static struct tasklet_struct hostwake_task;
/** Transmission timer */
static void bluesleep_tx_timer_expire(unsigned long data);
static DEFINE_TIMER(tx_timer, bluesleep_tx_timer_expire, 0, 0);
/** Lock for state transitions */
static spinlock_t rw_lock;
#define POLARITY_LOW 0
#define POLARITY_HIGH 1
struct bluesleep_info {
unsigned host_wake; /* wake up host */
unsigned ext_wake; /* wake up device */
unsigned host_wake_irq;
int irq_polarity;
};
/* 1 second timeout */
#define TX_TIMER_INTERVAL 1
/* state variable names and bit positions */
#define BT_TXEXPIRED 0x01
#define BT_SLEEPENABLE 0x02
#define BT_SLEEPCMD 0x03
/* global pointer to a single hci device. */
static struct bluesleep_info *bsi;
struct ath_struct {
struct hci_uart *hu;
unsigned int cur_sleep;
struct sk_buff_head txq;
struct work_struct ctxtsw;
};
static void hostwake_interrupt(unsigned long data)
{
BT_INFO(" wakeup host\n");
}
static void modify_timer_task(void)
{
spin_lock(&rw_lock);
mod_timer(&tx_timer, jiffies + (TX_TIMER_INTERVAL * HZ));
clear_bit(BT_TXEXPIRED, &flags);
spin_unlock(&rw_lock);
}
static int ath_wakeup_ar3k(struct tty_struct *tty)
{
int status = 0;
if (test_bit(BT_TXEXPIRED, &flags)) {
BT_INFO("wakeup device\n");
gpio_set_value(bsi->ext_wake, 0);
msleep(20);
gpio_set_value(bsi->ext_wake, 1);
}
modify_timer_task();
return status;
}
static void ath_hci_uart_work(struct work_struct *work)
{
int status;
struct ath_struct *ath;
struct hci_uart *hu;
struct tty_struct *tty;
ath = container_of(work, struct ath_struct, ctxtsw);
hu = ath->hu;
tty = hu->tty;
/* verify and wake up controller */
if (test_bit(BT_SLEEPENABLE, &flags))
status = ath_wakeup_ar3k(tty);
/* Ready to send Data */
clear_bit(HCI_UART_SENDING, &hu->tx_state);
hci_uart_tx_wakeup(hu);
}
static irqreturn_t bluesleep_hostwake_isr(int irq, void *dev_id)
{
/* schedule a tasklet to handle the change in the host wake line */
tasklet_schedule(&hostwake_task);
return IRQ_HANDLED;
}
static int ath_bluesleep_gpio_config(int on)
{
int ret = 0;
BT_INFO("%s config: %d", __func__, on);
if (!on) {
if (disable_irq_wake(bsi->host_wake_irq))
BT_ERR("Couldn't disable hostwake IRQ wakeup mode\n");
goto free_host_wake_irq;
}
ret = gpio_request(bsi->host_wake, "bt_host_wake");
if (ret < 0) {
BT_ERR("failed to request gpio pin %d, error %d\n",
bsi->host_wake, ret);
goto gpio_config_failed;
}
/* configure host_wake as input */
ret = gpio_direction_input(bsi->host_wake);
if (ret < 0) {
BT_ERR("failed to config GPIO %d as input pin, err %d\n",
bsi->host_wake, ret);
goto gpio_host_wake;
}
ret = gpio_request(bsi->ext_wake, "bt_ext_wake");
if (ret < 0) {
BT_ERR("failed to request gpio pin %d, error %d\n",
bsi->ext_wake, ret);
goto gpio_host_wake;
}
ret = gpio_direction_output(bsi->ext_wake, 1);
if (ret < 0) {
BT_ERR("failed to config GPIO %d as output pin, err %d\n",
bsi->ext_wake, ret);
goto gpio_ext_wake;
}
gpio_set_value(bsi->ext_wake, 1);
/* Initialize spinlock. */
spin_lock_init(&rw_lock);
/* Initialize timer */
init_timer(&tx_timer);
tx_timer.function = bluesleep_tx_timer_expire;
tx_timer.data = 0;
/* initialize host wake tasklet */
tasklet_init(&hostwake_task, hostwake_interrupt, 0);
if (bsi->irq_polarity == POLARITY_LOW) {
ret = request_irq(bsi->host_wake_irq, bluesleep_hostwake_isr,
IRQF_DISABLED | IRQF_TRIGGER_FALLING,
"bluetooth hostwake", NULL);
} else {
ret = request_irq(bsi->host_wake_irq, bluesleep_hostwake_isr,
IRQF_DISABLED | IRQF_TRIGGER_RISING,
"bluetooth hostwake", NULL);
}
if (ret < 0) {
BT_ERR("Couldn't acquire BT_HOST_WAKE IRQ");
goto delete_timer;
}
ret = enable_irq_wake(bsi->host_wake_irq);
if (ret < 0) {
BT_ERR("Couldn't enable BT_HOST_WAKE as wakeup interrupt");
goto free_host_wake_irq;
}
return 0;
free_host_wake_irq:
free_irq(bsi->host_wake_irq, NULL);
delete_timer:
del_timer(&tx_timer);
gpio_ext_wake:
gpio_free(bsi->ext_wake);
gpio_host_wake:
gpio_free(bsi->host_wake);
gpio_config_failed:
return ret;
}
/* Initialize protocol */
static int ath_open(struct hci_uart *hu)
{
struct ath_struct *ath;
BT_DBG("hu %p, bsi %p", hu, bsi);
if (!bsi)
return -EIO;
if (ath_bluesleep_gpio_config(1) < 0) {
BT_ERR("HCIATH3K GPIO Config failed");
return -EIO;
}
ath = kzalloc(sizeof(*ath), GFP_ATOMIC);
if (!ath)
return -ENOMEM;
skb_queue_head_init(&ath->txq);
hu->priv = ath;
ath->hu = hu;
ath->cur_sleep = enableuartsleep;
if (ath->cur_sleep == 1) {
set_bit(BT_SLEEPENABLE, &flags);
modify_timer_task();
}
INIT_WORK(&ath->ctxtsw, ath_hci_uart_work);
return 0;
}
/* Flush protocol data */
static int ath_flush(struct hci_uart *hu)
{
struct ath_struct *ath = hu->priv;
BT_DBG("hu %p", hu);
skb_queue_purge(&ath->txq);
return 0;
}
/* Close protocol */
static int ath_close(struct hci_uart *hu)
{
struct ath_struct *ath = hu->priv;
BT_DBG("hu %p", hu);
skb_queue_purge(&ath->txq);
cancel_work_sync(&ath->ctxtsw);
hu->priv = NULL;
kfree(ath);
if (bsi)
ath_bluesleep_gpio_config(0);
return 0;
}
#define HCI_OP_ATH_SLEEP 0xFC04
/* Enqueue frame for transmittion */
static int ath_enqueue(struct hci_uart *hu, struct sk_buff *skb)
{
struct ath_struct *ath = hu->priv;
BT_DBG("");
if (bt_cb(skb)->pkt_type == HCI_SCODATA_PKT) {
kfree_skb(skb);
return 0;
}
/*
* Update power management enable flag with parameters of
* HCI sleep enable vendor specific HCI command.
*/
if (bt_cb(skb)->pkt_type == HCI_COMMAND_PKT) {
struct hci_command_hdr *hdr = (void *)skb->data;
if (__le16_to_cpu(hdr->opcode) == HCI_OP_ATH_SLEEP) {
set_bit(BT_SLEEPCMD, &flags);
ath->cur_sleep = skb->data[HCI_COMMAND_HDR_SIZE];
}
}
BT_DBG("hu %p skb %p", hu, skb);
/* Prepend skb with frame type */
memcpy(skb_push(skb, 1), &bt_cb(skb)->pkt_type, 1);
skb_queue_tail(&ath->txq, skb);
set_bit(HCI_UART_SENDING, &hu->tx_state);
schedule_work(&ath->ctxtsw);
return 0;
}
static struct sk_buff *ath_dequeue(struct hci_uart *hu)
{
struct ath_struct *ath = hu->priv;
return skb_dequeue(&ath->txq);
}
/* Recv data */
static int ath_recv(struct hci_uart *hu, void *data, int count)
{
struct ath_struct *ath = hu->priv;
unsigned int type;
BT_DBG("");
if (hci_recv_stream_fragment(hu->hdev, data, count) < 0)
BT_ERR("Frame Reassembly Failed");
if (count & test_bit(BT_SLEEPCMD, &flags)) {
struct sk_buff *skb = hu->hdev->reassembly[0];
if (!skb) {
struct { char type; } *pkt;
/* Start of the frame */
pkt = data;
type = pkt->type;
} else
type = bt_cb(skb)->pkt_type;
if (type == HCI_EVENT_PKT) {
clear_bit(BT_SLEEPCMD, &flags);
BT_INFO("cur_sleep:%d\n", ath->cur_sleep);
if (ath->cur_sleep == 1)
set_bit(BT_SLEEPENABLE, &flags);
else
clear_bit(BT_SLEEPENABLE, &flags);
}
if (test_bit(BT_SLEEPENABLE, &flags))
modify_timer_task();
}
return count;
}
static void bluesleep_tx_timer_expire(unsigned long data)
{
if (!test_bit(BT_SLEEPENABLE, &flags))
return;
BT_INFO("Tx timer expired\n");
set_bit(BT_TXEXPIRED, &flags);
}
static struct hci_uart_proto athp = {
.id = HCI_UART_ATH3K,
.open = ath_open,
.close = ath_close,
.recv = ath_recv,
.enqueue = ath_enqueue,
.dequeue = ath_dequeue,
.flush = ath_flush,
};
static int __init bluesleep_probe(struct platform_device *pdev)
{
int ret;
struct resource *res;
BT_DBG("");
bsi = kzalloc(sizeof(struct bluesleep_info), GFP_KERNEL);
if (!bsi) {
ret = -ENOMEM;
goto failed;
}
res = platform_get_resource_byname(pdev, IORESOURCE_IO,
"gpio_host_wake");
if (!res) {
BT_ERR("couldn't find host_wake gpio\n");
ret = -ENODEV;
goto free_bsi;
}
bsi->host_wake = res->start;
res = platform_get_resource_byname(pdev, IORESOURCE_IO,
"gpio_ext_wake");
if (!res) {
BT_ERR("couldn't find ext_wake gpio\n");
ret = -ENODEV;
goto free_bsi;
}
bsi->ext_wake = res->start;
bsi->host_wake_irq = platform_get_irq_byname(pdev, "host_wake");
if (bsi->host_wake_irq < 0) {
BT_ERR("couldn't find host_wake irq\n");
ret = -ENODEV;
goto free_bsi;
}
bsi->irq_polarity = POLARITY_LOW; /* low edge (falling edge) */
return 0;
free_bsi:
kfree(bsi);
bsi = NULL;
failed:
return ret;
}
static int bluesleep_remove(struct platform_device *pdev)
{
kfree(bsi);
return 0;
}
static struct platform_driver bluesleep_driver = {
.remove = bluesleep_remove,
.driver = {
.name = "bluesleep",
.owner = THIS_MODULE,
},
};
int __init ath_init(void)
{
int ret;
ret = hci_uart_register_proto(&athp);
if (!ret)
BT_INFO("HCIATH3K protocol initialized");
else {
BT_ERR("HCIATH3K protocol registration failed");
return ret;
}
ret = platform_driver_probe(&bluesleep_driver, bluesleep_probe);
if (ret)
return ret;
return 0;
}
int __exit ath_deinit(void)
{
platform_driver_unregister(&bluesleep_driver);
return hci_uart_unregister_proto(&athp);
}
| gpl-2.0 |
desaishivam26/android_kernel_motorola_msm8916 | fs/nfs/direct.c | 1493 | 28511 | /*
* linux/fs/nfs/direct.c
*
* Copyright (C) 2003 by Chuck Lever <cel@netapp.com>
*
* High-performance uncached I/O for the Linux NFS client
*
* There are important applications whose performance or correctness
* depends on uncached access to file data. Database clusters
* (multiple copies of the same instance running on separate hosts)
* implement their own cache coherency protocol that subsumes file
* system cache protocols. Applications that process datasets
* considerably larger than the client's memory do not always benefit
* from a local cache. A streaming video server, for instance, has no
* need to cache the contents of a file.
*
* When an application requests uncached I/O, all read and write requests
* are made directly to the server; data stored or fetched via these
* requests is not cached in the Linux page cache. The client does not
* correct unaligned requests from applications. All requested bytes are
* held on permanent storage before a direct write system call returns to
* an application.
*
* Solaris implements an uncached I/O facility called directio() that
* is used for backups and sequential I/O to very large files. Solaris
* also supports uncaching whole NFS partitions with "-o forcedirectio,"
* an undocumented mount option.
*
* Designed by Jeff Kimmel, Chuck Lever, and Trond Myklebust, with
* help from Andrew Morton.
*
* 18 Dec 2001 Initial implementation for 2.4 --cel
* 08 Jul 2002 Version for 2.4.19, with bug fixes --trondmy
* 08 Jun 2003 Port to 2.5 APIs --cel
* 31 Mar 2004 Handle direct I/O without VFS support --cel
* 15 Sep 2004 Parallel async reads --cel
* 04 May 2005 support O_DIRECT with aio --cel
*
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/file.h>
#include <linux/pagemap.h>
#include <linux/kref.h>
#include <linux/slab.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/module.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_page.h>
#include <linux/sunrpc/clnt.h>
#include <asm/uaccess.h>
#include <linux/atomic.h>
#include "internal.h"
#include "iostat.h"
#include "pnfs.h"
#define NFSDBG_FACILITY NFSDBG_VFS
static struct kmem_cache *nfs_direct_cachep;
/*
* This represents a set of asynchronous requests that we're waiting on
*/
struct nfs_direct_req {
struct kref kref; /* release manager */
/* I/O parameters */
struct nfs_open_context *ctx; /* file open context info */
struct nfs_lock_context *l_ctx; /* Lock context info */
struct kiocb * iocb; /* controlling i/o request */
struct inode * inode; /* target file of i/o */
/* completion state */
atomic_t io_count; /* i/os we're waiting for */
spinlock_t lock; /* protect completion state */
ssize_t count, /* bytes actually processed */
bytes_left, /* bytes left to be sent */
error; /* any reported error */
struct completion completion; /* wait for i/o completion */
/* commit state */
struct nfs_mds_commit_info mds_cinfo; /* Storage for cinfo */
struct pnfs_ds_commit_info ds_cinfo; /* Storage for cinfo */
struct work_struct work;
int flags;
#define NFS_ODIRECT_DO_COMMIT (1) /* an unstable reply was received */
#define NFS_ODIRECT_RESCHED_WRITES (2) /* write verification failed */
struct nfs_writeverf verf; /* unstable write verifier */
};
static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops;
static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops;
static void nfs_direct_write_complete(struct nfs_direct_req *dreq, struct inode *inode);
static void nfs_direct_write_schedule_work(struct work_struct *work);
static inline void get_dreq(struct nfs_direct_req *dreq)
{
atomic_inc(&dreq->io_count);
}
static inline int put_dreq(struct nfs_direct_req *dreq)
{
return atomic_dec_and_test(&dreq->io_count);
}
/**
* nfs_direct_IO - NFS address space operation for direct I/O
* @rw: direction (read or write)
* @iocb: target I/O control block
* @iov: array of vectors that define I/O buffer
* @pos: offset in file to begin the operation
* @nr_segs: size of iovec array
*
* The presence of this routine in the address space ops vector means
* the NFS client supports direct I/O. However, for most direct IO, we
* shunt off direct read and write requests before the VFS gets them,
* so this method is only ever called for swap.
*/
ssize_t nfs_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t pos, unsigned long nr_segs)
{
#ifndef CONFIG_NFS_SWAP
dprintk("NFS: nfs_direct_IO (%s) off/no(%Ld/%lu) EINVAL\n",
iocb->ki_filp->f_path.dentry->d_name.name,
(long long) pos, nr_segs);
return -EINVAL;
#else
VM_BUG_ON(iocb->ki_left != PAGE_SIZE);
VM_BUG_ON(iocb->ki_nbytes != PAGE_SIZE);
if (rw == READ || rw == KERNEL_READ)
return nfs_file_direct_read(iocb, iov, nr_segs, pos,
rw == READ ? true : false);
return nfs_file_direct_write(iocb, iov, nr_segs, pos,
rw == WRITE ? true : false);
#endif /* CONFIG_NFS_SWAP */
}
static void nfs_direct_release_pages(struct page **pages, unsigned int npages)
{
unsigned int i;
for (i = 0; i < npages; i++)
page_cache_release(pages[i]);
}
void nfs_init_cinfo_from_dreq(struct nfs_commit_info *cinfo,
struct nfs_direct_req *dreq)
{
cinfo->lock = &dreq->lock;
cinfo->mds = &dreq->mds_cinfo;
cinfo->ds = &dreq->ds_cinfo;
cinfo->dreq = dreq;
cinfo->completion_ops = &nfs_direct_commit_completion_ops;
}
static inline struct nfs_direct_req *nfs_direct_req_alloc(void)
{
struct nfs_direct_req *dreq;
dreq = kmem_cache_zalloc(nfs_direct_cachep, GFP_KERNEL);
if (!dreq)
return NULL;
kref_init(&dreq->kref);
kref_get(&dreq->kref);
init_completion(&dreq->completion);
INIT_LIST_HEAD(&dreq->mds_cinfo.list);
INIT_WORK(&dreq->work, nfs_direct_write_schedule_work);
spin_lock_init(&dreq->lock);
return dreq;
}
static void nfs_direct_req_free(struct kref *kref)
{
struct nfs_direct_req *dreq = container_of(kref, struct nfs_direct_req, kref);
if (dreq->l_ctx != NULL)
nfs_put_lock_context(dreq->l_ctx);
if (dreq->ctx != NULL)
put_nfs_open_context(dreq->ctx);
kmem_cache_free(nfs_direct_cachep, dreq);
}
static void nfs_direct_req_release(struct nfs_direct_req *dreq)
{
kref_put(&dreq->kref, nfs_direct_req_free);
}
ssize_t nfs_dreq_bytes_left(struct nfs_direct_req *dreq)
{
return dreq->bytes_left;
}
EXPORT_SYMBOL_GPL(nfs_dreq_bytes_left);
/*
* Collects and returns the final error value/byte-count.
*/
static ssize_t nfs_direct_wait(struct nfs_direct_req *dreq)
{
ssize_t result = -EIOCBQUEUED;
/* Async requests don't wait here */
if (dreq->iocb)
goto out;
result = wait_for_completion_killable(&dreq->completion);
if (!result)
result = dreq->error;
if (!result)
result = dreq->count;
out:
return (ssize_t) result;
}
/*
* Synchronous I/O uses a stack-allocated iocb. Thus we can't trust
* the iocb is still valid here if this is a synchronous request.
*/
static void nfs_direct_complete(struct nfs_direct_req *dreq)
{
if (dreq->iocb) {
long res = (long) dreq->error;
if (!res)
res = (long) dreq->count;
aio_complete(dreq->iocb, res, 0);
}
complete_all(&dreq->completion);
nfs_direct_req_release(dreq);
}
static void nfs_direct_readpage_release(struct nfs_page *req)
{
dprintk("NFS: direct read done (%s/%lld %d@%lld)\n",
req->wb_context->dentry->d_inode->i_sb->s_id,
(long long)NFS_FILEID(req->wb_context->dentry->d_inode),
req->wb_bytes,
(long long)req_offset(req));
nfs_release_request(req);
}
static void nfs_direct_read_completion(struct nfs_pgio_header *hdr)
{
unsigned long bytes = 0;
struct nfs_direct_req *dreq = hdr->dreq;
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out_put;
spin_lock(&dreq->lock);
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) && (hdr->good_bytes == 0))
dreq->error = hdr->error;
else
dreq->count += hdr->good_bytes;
spin_unlock(&dreq->lock);
while (!list_empty(&hdr->pages)) {
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
struct page *page = req->wb_page;
if (!PageCompound(page) && bytes < hdr->good_bytes)
set_page_dirty(page);
bytes += req->wb_bytes;
nfs_list_remove_request(req);
nfs_direct_readpage_release(req);
}
out_put:
if (put_dreq(dreq))
nfs_direct_complete(dreq);
hdr->release(hdr);
}
static void nfs_read_sync_pgio_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_release_request(req);
}
}
static void nfs_direct_pgio_init(struct nfs_pgio_header *hdr)
{
get_dreq(hdr->dreq);
}
static const struct nfs_pgio_completion_ops nfs_direct_read_completion_ops = {
.error_cleanup = nfs_read_sync_pgio_error,
.init_hdr = nfs_direct_pgio_init,
.completion = nfs_direct_read_completion,
};
/*
* For each rsize'd chunk of the user's buffer, dispatch an NFS READ
* operation. If nfs_readdata_alloc() or get_user_pages() fails,
* bail and stop sending more reads. Read length accounting is
* handled automatically by nfs_direct_read_result(). Otherwise, if
* no requests have been sent, just return an error.
*/
static ssize_t nfs_direct_read_schedule_segment(struct nfs_pageio_descriptor *desc,
const struct iovec *iov,
loff_t pos, bool uio)
{
struct nfs_direct_req *dreq = desc->pg_dreq;
struct nfs_open_context *ctx = dreq->ctx;
struct inode *inode = ctx->dentry->d_inode;
unsigned long user_addr = (unsigned long)iov->iov_base;
size_t count = iov->iov_len;
size_t rsize = NFS_SERVER(inode)->rsize;
unsigned int pgbase;
int result;
ssize_t started = 0;
struct page **pagevec = NULL;
unsigned int npages;
do {
size_t bytes;
int i;
pgbase = user_addr & ~PAGE_MASK;
bytes = min(max_t(size_t, rsize, PAGE_SIZE), count);
result = -ENOMEM;
npages = nfs_page_array_len(pgbase, bytes);
if (!pagevec)
pagevec = kmalloc(npages * sizeof(struct page *),
GFP_KERNEL);
if (!pagevec)
break;
if (uio) {
down_read(¤t->mm->mmap_sem);
result = get_user_pages(current, current->mm, user_addr,
npages, 1, 0, pagevec, NULL);
up_read(¤t->mm->mmap_sem);
if (result < 0)
break;
} else {
WARN_ON(npages != 1);
result = get_kernel_page(user_addr, 1, pagevec);
if (WARN_ON(result != 1))
break;
}
if ((unsigned)result < npages) {
bytes = result * PAGE_SIZE;
if (bytes <= pgbase) {
nfs_direct_release_pages(pagevec, result);
break;
}
bytes -= pgbase;
npages = result;
}
for (i = 0; i < npages; i++) {
struct nfs_page *req;
unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
/* XXX do we need to do the eof zeroing found in async_filler? */
req = nfs_create_request(dreq->ctx, dreq->inode,
pagevec[i],
pgbase, req_len);
if (IS_ERR(req)) {
result = PTR_ERR(req);
break;
}
req->wb_index = pos >> PAGE_SHIFT;
req->wb_offset = pos & ~PAGE_MASK;
if (!nfs_pageio_add_request(desc, req)) {
result = desc->pg_error;
nfs_release_request(req);
break;
}
pgbase = 0;
bytes -= req_len;
started += req_len;
user_addr += req_len;
pos += req_len;
count -= req_len;
dreq->bytes_left -= req_len;
}
/* The nfs_page now hold references to these pages */
nfs_direct_release_pages(pagevec, npages);
} while (count != 0 && result >= 0);
kfree(pagevec);
if (started)
return started;
return result < 0 ? (ssize_t) result : -EFAULT;
}
static ssize_t nfs_direct_read_schedule_iovec(struct nfs_direct_req *dreq,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos, bool uio)
{
struct nfs_pageio_descriptor desc;
ssize_t result = -EINVAL;
size_t requested_bytes = 0;
unsigned long seg;
NFS_PROTO(dreq->inode)->read_pageio_init(&desc, dreq->inode,
&nfs_direct_read_completion_ops);
get_dreq(dreq);
desc.pg_dreq = dreq;
for (seg = 0; seg < nr_segs; seg++) {
const struct iovec *vec = &iov[seg];
result = nfs_direct_read_schedule_segment(&desc, vec, pos, uio);
if (result < 0)
break;
requested_bytes += result;
if ((size_t)result < vec->iov_len)
break;
pos += vec->iov_len;
}
nfs_pageio_complete(&desc);
/*
* If no bytes were started, return the error, and let the
* generic layer handle the completion.
*/
if (requested_bytes == 0) {
nfs_direct_req_release(dreq);
return result < 0 ? result : -EIO;
}
if (put_dreq(dreq))
nfs_direct_complete(dreq);
return 0;
}
static ssize_t nfs_direct_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos, bool uio)
{
ssize_t result = -ENOMEM;
struct inode *inode = iocb->ki_filp->f_mapping->host;
struct nfs_direct_req *dreq;
struct nfs_lock_context *l_ctx;
dreq = nfs_direct_req_alloc();
if (dreq == NULL)
goto out;
dreq->inode = inode;
dreq->bytes_left = iov_length(iov, nr_segs);
dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
l_ctx = nfs_get_lock_context(dreq->ctx);
if (IS_ERR(l_ctx)) {
result = PTR_ERR(l_ctx);
goto out_release;
}
dreq->l_ctx = l_ctx;
if (!is_sync_kiocb(iocb))
dreq->iocb = iocb;
NFS_I(inode)->read_io += iov_length(iov, nr_segs);
result = nfs_direct_read_schedule_iovec(dreq, iov, nr_segs, pos, uio);
if (!result)
result = nfs_direct_wait(dreq);
out_release:
nfs_direct_req_release(dreq);
out:
return result;
}
static void nfs_inode_dio_write_done(struct inode *inode)
{
nfs_zap_mapping(inode, inode->i_mapping);
inode_dio_done(inode);
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
static void nfs_direct_write_reschedule(struct nfs_direct_req *dreq)
{
struct nfs_pageio_descriptor desc;
struct nfs_page *req, *tmp;
LIST_HEAD(reqs);
struct nfs_commit_info cinfo;
LIST_HEAD(failed);
nfs_init_cinfo_from_dreq(&cinfo, dreq);
pnfs_recover_commit_reqs(dreq->inode, &reqs, &cinfo);
spin_lock(cinfo.lock);
nfs_scan_commit_list(&cinfo.mds->list, &reqs, &cinfo, 0);
spin_unlock(cinfo.lock);
dreq->count = 0;
get_dreq(dreq);
NFS_PROTO(dreq->inode)->write_pageio_init(&desc, dreq->inode, FLUSH_STABLE,
&nfs_direct_write_completion_ops);
desc.pg_dreq = dreq;
list_for_each_entry_safe(req, tmp, &reqs, wb_list) {
if (!nfs_pageio_add_request(&desc, req)) {
nfs_list_remove_request(req);
nfs_list_add_request(req, &failed);
spin_lock(cinfo.lock);
dreq->flags = 0;
dreq->error = -EIO;
spin_unlock(cinfo.lock);
}
nfs_release_request(req);
}
nfs_pageio_complete(&desc);
while (!list_empty(&failed)) {
req = nfs_list_entry(failed.next);
nfs_list_remove_request(req);
nfs_unlock_and_release_request(req);
}
if (put_dreq(dreq))
nfs_direct_write_complete(dreq, dreq->inode);
}
static void nfs_direct_commit_complete(struct nfs_commit_data *data)
{
struct nfs_direct_req *dreq = data->dreq;
struct nfs_commit_info cinfo;
struct nfs_page *req;
int status = data->task.tk_status;
nfs_init_cinfo_from_dreq(&cinfo, dreq);
if (status < 0) {
dprintk("NFS: %5u commit failed with error %d.\n",
data->task.tk_pid, status);
dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
} else if (memcmp(&dreq->verf, &data->verf, sizeof(data->verf))) {
dprintk("NFS: %5u commit verify failed\n", data->task.tk_pid);
dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
}
dprintk("NFS: %5u commit returned %d\n", data->task.tk_pid, status);
while (!list_empty(&data->pages)) {
req = nfs_list_entry(data->pages.next);
nfs_list_remove_request(req);
if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES) {
/* Note the rewrite will go through mds */
nfs_mark_request_commit(req, NULL, &cinfo);
} else
nfs_release_request(req);
nfs_unlock_and_release_request(req);
}
if (atomic_dec_and_test(&cinfo.mds->rpcs_out))
nfs_direct_write_complete(dreq, data->inode);
}
static void nfs_direct_error_cleanup(struct nfs_inode *nfsi)
{
/* There is no lock to clear */
}
static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops = {
.completion = nfs_direct_commit_complete,
.error_cleanup = nfs_direct_error_cleanup,
};
static void nfs_direct_commit_schedule(struct nfs_direct_req *dreq)
{
int res;
struct nfs_commit_info cinfo;
LIST_HEAD(mds_list);
nfs_init_cinfo_from_dreq(&cinfo, dreq);
nfs_scan_commit(dreq->inode, &mds_list, &cinfo);
res = nfs_generic_commit_list(dreq->inode, &mds_list, 0, &cinfo);
if (res < 0) /* res == -ENOMEM */
nfs_direct_write_reschedule(dreq);
}
static void nfs_direct_write_schedule_work(struct work_struct *work)
{
struct nfs_direct_req *dreq = container_of(work, struct nfs_direct_req, work);
int flags = dreq->flags;
dreq->flags = 0;
switch (flags) {
case NFS_ODIRECT_DO_COMMIT:
nfs_direct_commit_schedule(dreq);
break;
case NFS_ODIRECT_RESCHED_WRITES:
nfs_direct_write_reschedule(dreq);
break;
default:
nfs_inode_dio_write_done(dreq->inode);
nfs_direct_complete(dreq);
}
}
static void nfs_direct_write_complete(struct nfs_direct_req *dreq, struct inode *inode)
{
schedule_work(&dreq->work); /* Calls nfs_direct_write_schedule_work */
}
#else
static void nfs_direct_write_schedule_work(struct work_struct *work)
{
}
static void nfs_direct_write_complete(struct nfs_direct_req *dreq, struct inode *inode)
{
nfs_inode_dio_write_done(inode);
nfs_direct_complete(dreq);
}
#endif
/*
* NB: Return the value of the first error return code. Subsequent
* errors after the first one are ignored.
*/
/*
* For each wsize'd chunk of the user's buffer, dispatch an NFS WRITE
* operation. If nfs_writedata_alloc() or get_user_pages() fails,
* bail and stop sending more writes. Write length accounting is
* handled automatically by nfs_direct_write_result(). Otherwise, if
* no requests have been sent, just return an error.
*/
static ssize_t nfs_direct_write_schedule_segment(struct nfs_pageio_descriptor *desc,
const struct iovec *iov,
loff_t pos, bool uio)
{
struct nfs_direct_req *dreq = desc->pg_dreq;
struct nfs_open_context *ctx = dreq->ctx;
struct inode *inode = ctx->dentry->d_inode;
unsigned long user_addr = (unsigned long)iov->iov_base;
size_t count = iov->iov_len;
size_t wsize = NFS_SERVER(inode)->wsize;
unsigned int pgbase;
int result;
ssize_t started = 0;
struct page **pagevec = NULL;
unsigned int npages;
do {
size_t bytes;
int i;
pgbase = user_addr & ~PAGE_MASK;
bytes = min(max_t(size_t, wsize, PAGE_SIZE), count);
result = -ENOMEM;
npages = nfs_page_array_len(pgbase, bytes);
if (!pagevec)
pagevec = kmalloc(npages * sizeof(struct page *), GFP_KERNEL);
if (!pagevec)
break;
if (uio) {
down_read(¤t->mm->mmap_sem);
result = get_user_pages(current, current->mm, user_addr,
npages, 0, 0, pagevec, NULL);
up_read(¤t->mm->mmap_sem);
if (result < 0)
break;
} else {
WARN_ON(npages != 1);
result = get_kernel_page(user_addr, 0, pagevec);
if (WARN_ON(result != 1))
break;
}
if ((unsigned)result < npages) {
bytes = result * PAGE_SIZE;
if (bytes <= pgbase) {
nfs_direct_release_pages(pagevec, result);
break;
}
bytes -= pgbase;
npages = result;
}
for (i = 0; i < npages; i++) {
struct nfs_page *req;
unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
req = nfs_create_request(dreq->ctx, dreq->inode,
pagevec[i],
pgbase, req_len);
if (IS_ERR(req)) {
result = PTR_ERR(req);
break;
}
nfs_lock_request(req);
req->wb_index = pos >> PAGE_SHIFT;
req->wb_offset = pos & ~PAGE_MASK;
if (!nfs_pageio_add_request(desc, req)) {
result = desc->pg_error;
nfs_unlock_and_release_request(req);
break;
}
pgbase = 0;
bytes -= req_len;
started += req_len;
user_addr += req_len;
pos += req_len;
count -= req_len;
dreq->bytes_left -= req_len;
}
/* The nfs_page now hold references to these pages */
nfs_direct_release_pages(pagevec, npages);
} while (count != 0 && result >= 0);
kfree(pagevec);
if (started)
return started;
return result < 0 ? (ssize_t) result : -EFAULT;
}
static void nfs_direct_write_completion(struct nfs_pgio_header *hdr)
{
struct nfs_direct_req *dreq = hdr->dreq;
struct nfs_commit_info cinfo;
int bit = -1;
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out_put;
nfs_init_cinfo_from_dreq(&cinfo, dreq);
spin_lock(&dreq->lock);
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags)) {
dreq->flags = 0;
dreq->error = hdr->error;
}
if (dreq->error != 0)
bit = NFS_IOHDR_ERROR;
else {
dreq->count += hdr->good_bytes;
if (test_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags)) {
dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
bit = NFS_IOHDR_NEED_RESCHED;
} else if (test_bit(NFS_IOHDR_NEED_COMMIT, &hdr->flags)) {
if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES)
bit = NFS_IOHDR_NEED_RESCHED;
else if (dreq->flags == 0) {
memcpy(&dreq->verf, hdr->verf,
sizeof(dreq->verf));
bit = NFS_IOHDR_NEED_COMMIT;
dreq->flags = NFS_ODIRECT_DO_COMMIT;
} else if (dreq->flags == NFS_ODIRECT_DO_COMMIT) {
if (memcmp(&dreq->verf, hdr->verf, sizeof(dreq->verf))) {
dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
bit = NFS_IOHDR_NEED_RESCHED;
} else
bit = NFS_IOHDR_NEED_COMMIT;
}
}
}
spin_unlock(&dreq->lock);
while (!list_empty(&hdr->pages)) {
req = nfs_list_entry(hdr->pages.next);
nfs_list_remove_request(req);
switch (bit) {
case NFS_IOHDR_NEED_RESCHED:
case NFS_IOHDR_NEED_COMMIT:
kref_get(&req->wb_kref);
nfs_mark_request_commit(req, hdr->lseg, &cinfo);
}
nfs_unlock_and_release_request(req);
}
out_put:
if (put_dreq(dreq))
nfs_direct_write_complete(dreq, hdr->inode);
hdr->release(hdr);
}
static void nfs_write_sync_pgio_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_unlock_and_release_request(req);
}
}
static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops = {
.error_cleanup = nfs_write_sync_pgio_error,
.init_hdr = nfs_direct_pgio_init,
.completion = nfs_direct_write_completion,
};
static ssize_t nfs_direct_write_schedule_iovec(struct nfs_direct_req *dreq,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos, bool uio)
{
struct nfs_pageio_descriptor desc;
struct inode *inode = dreq->inode;
ssize_t result = 0;
size_t requested_bytes = 0;
unsigned long seg;
NFS_PROTO(inode)->write_pageio_init(&desc, inode, FLUSH_COND_STABLE,
&nfs_direct_write_completion_ops);
desc.pg_dreq = dreq;
get_dreq(dreq);
atomic_inc(&inode->i_dio_count);
NFS_I(dreq->inode)->write_io += iov_length(iov, nr_segs);
for (seg = 0; seg < nr_segs; seg++) {
const struct iovec *vec = &iov[seg];
result = nfs_direct_write_schedule_segment(&desc, vec, pos, uio);
if (result < 0)
break;
requested_bytes += result;
if ((size_t)result < vec->iov_len)
break;
pos += vec->iov_len;
}
nfs_pageio_complete(&desc);
/*
* If no bytes were started, return the error, and let the
* generic layer handle the completion.
*/
if (requested_bytes == 0) {
inode_dio_done(inode);
nfs_direct_req_release(dreq);
return result < 0 ? result : -EIO;
}
if (put_dreq(dreq))
nfs_direct_write_complete(dreq, dreq->inode);
return 0;
}
static ssize_t nfs_direct_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos,
size_t count, bool uio)
{
ssize_t result = -ENOMEM;
struct inode *inode = iocb->ki_filp->f_mapping->host;
struct nfs_direct_req *dreq;
struct nfs_lock_context *l_ctx;
dreq = nfs_direct_req_alloc();
if (!dreq)
goto out;
dreq->inode = inode;
dreq->bytes_left = count;
dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
l_ctx = nfs_get_lock_context(dreq->ctx);
if (IS_ERR(l_ctx)) {
result = PTR_ERR(l_ctx);
goto out_release;
}
dreq->l_ctx = l_ctx;
if (!is_sync_kiocb(iocb))
dreq->iocb = iocb;
result = nfs_direct_write_schedule_iovec(dreq, iov, nr_segs, pos, uio);
if (!result)
result = nfs_direct_wait(dreq);
out_release:
nfs_direct_req_release(dreq);
out:
return result;
}
/**
* nfs_file_direct_read - file direct read operation for NFS files
* @iocb: target I/O control block
* @iov: vector of user buffers into which to read data
* @nr_segs: size of iov vector
* @pos: byte offset in file where reading starts
*
* We use this function for direct reads instead of calling
* generic_file_aio_read() in order to avoid gfar's check to see if
* the request starts before the end of the file. For that check
* to work, we must generate a GETATTR before each direct read, and
* even then there is a window between the GETATTR and the subsequent
* READ where the file size could change. Our preference is simply
* to do all reads the application wants, and the server will take
* care of managing the end of file boundary.
*
* This function also eliminates unnecessarily updating the file's
* atime locally, as the NFS server sets the file's atime, and this
* client must read the updated atime from the server back into its
* cache.
*/
ssize_t nfs_file_direct_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos, bool uio)
{
ssize_t retval = -EINVAL;
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
size_t count;
count = iov_length(iov, nr_segs);
nfs_add_stats(mapping->host, NFSIOS_DIRECTREADBYTES, count);
dfprintk(FILE, "NFS: direct read(%s/%s, %zd@%Ld)\n",
file->f_path.dentry->d_parent->d_name.name,
file->f_path.dentry->d_name.name,
count, (long long) pos);
retval = 0;
if (!count)
goto out;
retval = nfs_sync_mapping(mapping);
if (retval)
goto out;
task_io_account_read(count);
retval = nfs_direct_read(iocb, iov, nr_segs, pos, uio);
if (retval > 0)
iocb->ki_pos = pos + retval;
out:
return retval;
}
/**
* nfs_file_direct_write - file direct write operation for NFS files
* @iocb: target I/O control block
* @iov: vector of user buffers from which to write data
* @nr_segs: size of iov vector
* @pos: byte offset in file where writing starts
*
* We use this function for direct writes instead of calling
* generic_file_aio_write() in order to avoid taking the inode
* semaphore and updating the i_size. The NFS server will set
* the new i_size and this client must read the updated size
* back into its cache. We let the server do generic write
* parameter checking and report problems.
*
* We eliminate local atime updates, see direct read above.
*
* We avoid unnecessary page cache invalidations for normal cached
* readers of this file.
*
* Note that O_APPEND is not supported for NFS direct writes, as there
* is no atomic O_APPEND write facility in the NFS protocol.
*/
ssize_t nfs_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos, bool uio)
{
ssize_t retval = -EINVAL;
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
size_t count;
count = iov_length(iov, nr_segs);
nfs_add_stats(mapping->host, NFSIOS_DIRECTWRITTENBYTES, count);
dfprintk(FILE, "NFS: direct write(%s/%s, %zd@%Ld)\n",
file->f_path.dentry->d_parent->d_name.name,
file->f_path.dentry->d_name.name,
count, (long long) pos);
retval = generic_write_checks(file, &pos, &count, 0);
if (retval)
goto out;
retval = -EINVAL;
if ((ssize_t) count < 0)
goto out;
retval = 0;
if (!count)
goto out;
retval = nfs_sync_mapping(mapping);
if (retval)
goto out;
task_io_account_write(count);
retval = nfs_direct_write(iocb, iov, nr_segs, pos, count, uio);
if (retval > 0) {
struct inode *inode = mapping->host;
iocb->ki_pos = pos + retval;
spin_lock(&inode->i_lock);
if (i_size_read(inode) < iocb->ki_pos)
i_size_write(inode, iocb->ki_pos);
spin_unlock(&inode->i_lock);
}
out:
return retval;
}
/**
* nfs_init_directcache - create a slab cache for nfs_direct_req structures
*
*/
int __init nfs_init_directcache(void)
{
nfs_direct_cachep = kmem_cache_create("nfs_direct_cache",
sizeof(struct nfs_direct_req),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
NULL);
if (nfs_direct_cachep == NULL)
return -ENOMEM;
return 0;
}
/**
* nfs_destroy_directcache - destroy the slab cache for nfs_direct_req structures
*
*/
void nfs_destroy_directcache(void)
{
kmem_cache_destroy(nfs_direct_cachep);
}
| gpl-2.0 |
nosnilwar/linux-raw-gov-2.6.38.8 | scripts/kconfig/expr.c | 2773 | 27270 | /*
* Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org>
* Released under the terms of the GNU GPL v2.0.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LKC_DIRECT_LINK
#include "lkc.h"
#define DEBUG_EXPR 0
struct expr *expr_alloc_symbol(struct symbol *sym)
{
struct expr *e = malloc(sizeof(*e));
memset(e, 0, sizeof(*e));
e->type = E_SYMBOL;
e->left.sym = sym;
return e;
}
struct expr *expr_alloc_one(enum expr_type type, struct expr *ce)
{
struct expr *e = malloc(sizeof(*e));
memset(e, 0, sizeof(*e));
e->type = type;
e->left.expr = ce;
return e;
}
struct expr *expr_alloc_two(enum expr_type type, struct expr *e1, struct expr *e2)
{
struct expr *e = malloc(sizeof(*e));
memset(e, 0, sizeof(*e));
e->type = type;
e->left.expr = e1;
e->right.expr = e2;
return e;
}
struct expr *expr_alloc_comp(enum expr_type type, struct symbol *s1, struct symbol *s2)
{
struct expr *e = malloc(sizeof(*e));
memset(e, 0, sizeof(*e));
e->type = type;
e->left.sym = s1;
e->right.sym = s2;
return e;
}
struct expr *expr_alloc_and(struct expr *e1, struct expr *e2)
{
if (!e1)
return e2;
return e2 ? expr_alloc_two(E_AND, e1, e2) : e1;
}
struct expr *expr_alloc_or(struct expr *e1, struct expr *e2)
{
if (!e1)
return e2;
return e2 ? expr_alloc_two(E_OR, e1, e2) : e1;
}
struct expr *expr_copy(const struct expr *org)
{
struct expr *e;
if (!org)
return NULL;
e = malloc(sizeof(*org));
memcpy(e, org, sizeof(*org));
switch (org->type) {
case E_SYMBOL:
e->left = org->left;
break;
case E_NOT:
e->left.expr = expr_copy(org->left.expr);
break;
case E_EQUAL:
case E_UNEQUAL:
e->left.sym = org->left.sym;
e->right.sym = org->right.sym;
break;
case E_AND:
case E_OR:
case E_LIST:
e->left.expr = expr_copy(org->left.expr);
e->right.expr = expr_copy(org->right.expr);
break;
default:
printf("can't copy type %d\n", e->type);
free(e);
e = NULL;
break;
}
return e;
}
void expr_free(struct expr *e)
{
if (!e)
return;
switch (e->type) {
case E_SYMBOL:
break;
case E_NOT:
expr_free(e->left.expr);
return;
case E_EQUAL:
case E_UNEQUAL:
break;
case E_OR:
case E_AND:
expr_free(e->left.expr);
expr_free(e->right.expr);
break;
default:
printf("how to free type %d?\n", e->type);
break;
}
free(e);
}
static int trans_count;
#define e1 (*ep1)
#define e2 (*ep2)
static void __expr_eliminate_eq(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
if (e1->type == type) {
__expr_eliminate_eq(type, &e1->left.expr, &e2);
__expr_eliminate_eq(type, &e1->right.expr, &e2);
return;
}
if (e2->type == type) {
__expr_eliminate_eq(type, &e1, &e2->left.expr);
__expr_eliminate_eq(type, &e1, &e2->right.expr);
return;
}
if (e1->type == E_SYMBOL && e2->type == E_SYMBOL &&
e1->left.sym == e2->left.sym &&
(e1->left.sym == &symbol_yes || e1->left.sym == &symbol_no))
return;
if (!expr_eq(e1, e2))
return;
trans_count++;
expr_free(e1); expr_free(e2);
switch (type) {
case E_OR:
e1 = expr_alloc_symbol(&symbol_no);
e2 = expr_alloc_symbol(&symbol_no);
break;
case E_AND:
e1 = expr_alloc_symbol(&symbol_yes);
e2 = expr_alloc_symbol(&symbol_yes);
break;
default:
;
}
}
void expr_eliminate_eq(struct expr **ep1, struct expr **ep2)
{
if (!e1 || !e2)
return;
switch (e1->type) {
case E_OR:
case E_AND:
__expr_eliminate_eq(e1->type, ep1, ep2);
default:
;
}
if (e1->type != e2->type) switch (e2->type) {
case E_OR:
case E_AND:
__expr_eliminate_eq(e2->type, ep1, ep2);
default:
;
}
e1 = expr_eliminate_yn(e1);
e2 = expr_eliminate_yn(e2);
}
#undef e1
#undef e2
int expr_eq(struct expr *e1, struct expr *e2)
{
int res, old_count;
if (e1->type != e2->type)
return 0;
switch (e1->type) {
case E_EQUAL:
case E_UNEQUAL:
return e1->left.sym == e2->left.sym && e1->right.sym == e2->right.sym;
case E_SYMBOL:
return e1->left.sym == e2->left.sym;
case E_NOT:
return expr_eq(e1->left.expr, e2->left.expr);
case E_AND:
case E_OR:
e1 = expr_copy(e1);
e2 = expr_copy(e2);
old_count = trans_count;
expr_eliminate_eq(&e1, &e2);
res = (e1->type == E_SYMBOL && e2->type == E_SYMBOL &&
e1->left.sym == e2->left.sym);
expr_free(e1);
expr_free(e2);
trans_count = old_count;
return res;
case E_LIST:
case E_RANGE:
case E_NONE:
/* panic */;
}
if (DEBUG_EXPR) {
expr_fprint(e1, stdout);
printf(" = ");
expr_fprint(e2, stdout);
printf(" ?\n");
}
return 0;
}
struct expr *expr_eliminate_yn(struct expr *e)
{
struct expr *tmp;
if (e) switch (e->type) {
case E_AND:
e->left.expr = expr_eliminate_yn(e->left.expr);
e->right.expr = expr_eliminate_yn(e->right.expr);
if (e->left.expr->type == E_SYMBOL) {
if (e->left.expr->left.sym == &symbol_no) {
expr_free(e->left.expr);
expr_free(e->right.expr);
e->type = E_SYMBOL;
e->left.sym = &symbol_no;
e->right.expr = NULL;
return e;
} else if (e->left.expr->left.sym == &symbol_yes) {
free(e->left.expr);
tmp = e->right.expr;
*e = *(e->right.expr);
free(tmp);
return e;
}
}
if (e->right.expr->type == E_SYMBOL) {
if (e->right.expr->left.sym == &symbol_no) {
expr_free(e->left.expr);
expr_free(e->right.expr);
e->type = E_SYMBOL;
e->left.sym = &symbol_no;
e->right.expr = NULL;
return e;
} else if (e->right.expr->left.sym == &symbol_yes) {
free(e->right.expr);
tmp = e->left.expr;
*e = *(e->left.expr);
free(tmp);
return e;
}
}
break;
case E_OR:
e->left.expr = expr_eliminate_yn(e->left.expr);
e->right.expr = expr_eliminate_yn(e->right.expr);
if (e->left.expr->type == E_SYMBOL) {
if (e->left.expr->left.sym == &symbol_no) {
free(e->left.expr);
tmp = e->right.expr;
*e = *(e->right.expr);
free(tmp);
return e;
} else if (e->left.expr->left.sym == &symbol_yes) {
expr_free(e->left.expr);
expr_free(e->right.expr);
e->type = E_SYMBOL;
e->left.sym = &symbol_yes;
e->right.expr = NULL;
return e;
}
}
if (e->right.expr->type == E_SYMBOL) {
if (e->right.expr->left.sym == &symbol_no) {
free(e->right.expr);
tmp = e->left.expr;
*e = *(e->left.expr);
free(tmp);
return e;
} else if (e->right.expr->left.sym == &symbol_yes) {
expr_free(e->left.expr);
expr_free(e->right.expr);
e->type = E_SYMBOL;
e->left.sym = &symbol_yes;
e->right.expr = NULL;
return e;
}
}
break;
default:
;
}
return e;
}
/*
* bool FOO!=n => FOO
*/
struct expr *expr_trans_bool(struct expr *e)
{
if (!e)
return NULL;
switch (e->type) {
case E_AND:
case E_OR:
case E_NOT:
e->left.expr = expr_trans_bool(e->left.expr);
e->right.expr = expr_trans_bool(e->right.expr);
break;
case E_UNEQUAL:
// FOO!=n -> FOO
if (e->left.sym->type == S_TRISTATE) {
if (e->right.sym == &symbol_no) {
e->type = E_SYMBOL;
e->right.sym = NULL;
}
}
break;
default:
;
}
return e;
}
/*
* e1 || e2 -> ?
*/
static struct expr *expr_join_or(struct expr *e1, struct expr *e2)
{
struct expr *tmp;
struct symbol *sym1, *sym2;
if (expr_eq(e1, e2))
return expr_copy(e1);
if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT)
return NULL;
if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT)
return NULL;
if (e1->type == E_NOT) {
tmp = e1->left.expr;
if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL)
return NULL;
sym1 = tmp->left.sym;
} else
sym1 = e1->left.sym;
if (e2->type == E_NOT) {
if (e2->left.expr->type != E_SYMBOL)
return NULL;
sym2 = e2->left.expr->left.sym;
} else
sym2 = e2->left.sym;
if (sym1 != sym2)
return NULL;
if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE)
return NULL;
if (sym1->type == S_TRISTATE) {
if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) ||
(e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) {
// (a='y') || (a='m') -> (a!='n')
return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_no);
}
if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) ||
(e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) {
// (a='y') || (a='n') -> (a!='m')
return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_mod);
}
if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) ||
(e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) {
// (a='m') || (a='n') -> (a!='y')
return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_yes);
}
}
if (sym1->type == S_BOOLEAN && sym1 == sym2) {
if ((e1->type == E_NOT && e1->left.expr->type == E_SYMBOL && e2->type == E_SYMBOL) ||
(e2->type == E_NOT && e2->left.expr->type == E_SYMBOL && e1->type == E_SYMBOL))
return expr_alloc_symbol(&symbol_yes);
}
if (DEBUG_EXPR) {
printf("optimize (");
expr_fprint(e1, stdout);
printf(") || (");
expr_fprint(e2, stdout);
printf(")?\n");
}
return NULL;
}
static struct expr *expr_join_and(struct expr *e1, struct expr *e2)
{
struct expr *tmp;
struct symbol *sym1, *sym2;
if (expr_eq(e1, e2))
return expr_copy(e1);
if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT)
return NULL;
if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT)
return NULL;
if (e1->type == E_NOT) {
tmp = e1->left.expr;
if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL)
return NULL;
sym1 = tmp->left.sym;
} else
sym1 = e1->left.sym;
if (e2->type == E_NOT) {
if (e2->left.expr->type != E_SYMBOL)
return NULL;
sym2 = e2->left.expr->left.sym;
} else
sym2 = e2->left.sym;
if (sym1 != sym2)
return NULL;
if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE)
return NULL;
if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_yes) ||
(e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_yes))
// (a) && (a='y') -> (a='y')
return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);
if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_no) ||
(e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_no))
// (a) && (a!='n') -> (a)
return expr_alloc_symbol(sym1);
if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_mod) ||
(e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_mod))
// (a) && (a!='m') -> (a='y')
return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);
if (sym1->type == S_TRISTATE) {
if (e1->type == E_EQUAL && e2->type == E_UNEQUAL) {
// (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b'
sym2 = e1->right.sym;
if ((e2->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST))
return sym2 != e2->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2)
: expr_alloc_symbol(&symbol_no);
}
if (e1->type == E_UNEQUAL && e2->type == E_EQUAL) {
// (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b'
sym2 = e2->right.sym;
if ((e1->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST))
return sym2 != e1->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2)
: expr_alloc_symbol(&symbol_no);
}
if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) ||
(e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes)))
// (a!='y') && (a!='n') -> (a='m')
return expr_alloc_comp(E_EQUAL, sym1, &symbol_mod);
if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) ||
(e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes)))
// (a!='y') && (a!='m') -> (a='n')
return expr_alloc_comp(E_EQUAL, sym1, &symbol_no);
if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) ||
(e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod)))
// (a!='m') && (a!='n') -> (a='m')
return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);
if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_mod) ||
(e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_mod) ||
(e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_yes) ||
(e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_yes))
return NULL;
}
if (DEBUG_EXPR) {
printf("optimize (");
expr_fprint(e1, stdout);
printf(") && (");
expr_fprint(e2, stdout);
printf(")?\n");
}
return NULL;
}
static void expr_eliminate_dups1(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
struct expr *tmp;
if (e1->type == type) {
expr_eliminate_dups1(type, &e1->left.expr, &e2);
expr_eliminate_dups1(type, &e1->right.expr, &e2);
return;
}
if (e2->type == type) {
expr_eliminate_dups1(type, &e1, &e2->left.expr);
expr_eliminate_dups1(type, &e1, &e2->right.expr);
return;
}
if (e1 == e2)
return;
switch (e1->type) {
case E_OR: case E_AND:
expr_eliminate_dups1(e1->type, &e1, &e1);
default:
;
}
switch (type) {
case E_OR:
tmp = expr_join_or(e1, e2);
if (tmp) {
expr_free(e1); expr_free(e2);
e1 = expr_alloc_symbol(&symbol_no);
e2 = tmp;
trans_count++;
}
break;
case E_AND:
tmp = expr_join_and(e1, e2);
if (tmp) {
expr_free(e1); expr_free(e2);
e1 = expr_alloc_symbol(&symbol_yes);
e2 = tmp;
trans_count++;
}
break;
default:
;
}
#undef e1
#undef e2
}
static void expr_eliminate_dups2(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
struct expr *tmp, *tmp1, *tmp2;
if (e1->type == type) {
expr_eliminate_dups2(type, &e1->left.expr, &e2);
expr_eliminate_dups2(type, &e1->right.expr, &e2);
return;
}
if (e2->type == type) {
expr_eliminate_dups2(type, &e1, &e2->left.expr);
expr_eliminate_dups2(type, &e1, &e2->right.expr);
}
if (e1 == e2)
return;
switch (e1->type) {
case E_OR:
expr_eliminate_dups2(e1->type, &e1, &e1);
// (FOO || BAR) && (!FOO && !BAR) -> n
tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1)));
tmp2 = expr_copy(e2);
tmp = expr_extract_eq_and(&tmp1, &tmp2);
if (expr_is_yes(tmp1)) {
expr_free(e1);
e1 = expr_alloc_symbol(&symbol_no);
trans_count++;
}
expr_free(tmp2);
expr_free(tmp1);
expr_free(tmp);
break;
case E_AND:
expr_eliminate_dups2(e1->type, &e1, &e1);
// (FOO && BAR) || (!FOO || !BAR) -> y
tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1)));
tmp2 = expr_copy(e2);
tmp = expr_extract_eq_or(&tmp1, &tmp2);
if (expr_is_no(tmp1)) {
expr_free(e1);
e1 = expr_alloc_symbol(&symbol_yes);
trans_count++;
}
expr_free(tmp2);
expr_free(tmp1);
expr_free(tmp);
break;
default:
;
}
#undef e1
#undef e2
}
struct expr *expr_eliminate_dups(struct expr *e)
{
int oldcount;
if (!e)
return e;
oldcount = trans_count;
while (1) {
trans_count = 0;
switch (e->type) {
case E_OR: case E_AND:
expr_eliminate_dups1(e->type, &e, &e);
expr_eliminate_dups2(e->type, &e, &e);
default:
;
}
if (!trans_count)
break;
e = expr_eliminate_yn(e);
}
trans_count = oldcount;
return e;
}
struct expr *expr_transform(struct expr *e)
{
struct expr *tmp;
if (!e)
return NULL;
switch (e->type) {
case E_EQUAL:
case E_UNEQUAL:
case E_SYMBOL:
case E_LIST:
break;
default:
e->left.expr = expr_transform(e->left.expr);
e->right.expr = expr_transform(e->right.expr);
}
switch (e->type) {
case E_EQUAL:
if (e->left.sym->type != S_BOOLEAN)
break;
if (e->right.sym == &symbol_no) {
e->type = E_NOT;
e->left.expr = expr_alloc_symbol(e->left.sym);
e->right.sym = NULL;
break;
}
if (e->right.sym == &symbol_mod) {
printf("boolean symbol %s tested for 'm'? test forced to 'n'\n", e->left.sym->name);
e->type = E_SYMBOL;
e->left.sym = &symbol_no;
e->right.sym = NULL;
break;
}
if (e->right.sym == &symbol_yes) {
e->type = E_SYMBOL;
e->right.sym = NULL;
break;
}
break;
case E_UNEQUAL:
if (e->left.sym->type != S_BOOLEAN)
break;
if (e->right.sym == &symbol_no) {
e->type = E_SYMBOL;
e->right.sym = NULL;
break;
}
if (e->right.sym == &symbol_mod) {
printf("boolean symbol %s tested for 'm'? test forced to 'y'\n", e->left.sym->name);
e->type = E_SYMBOL;
e->left.sym = &symbol_yes;
e->right.sym = NULL;
break;
}
if (e->right.sym == &symbol_yes) {
e->type = E_NOT;
e->left.expr = expr_alloc_symbol(e->left.sym);
e->right.sym = NULL;
break;
}
break;
case E_NOT:
switch (e->left.expr->type) {
case E_NOT:
// !!a -> a
tmp = e->left.expr->left.expr;
free(e->left.expr);
free(e);
e = tmp;
e = expr_transform(e);
break;
case E_EQUAL:
case E_UNEQUAL:
// !a='x' -> a!='x'
tmp = e->left.expr;
free(e);
e = tmp;
e->type = e->type == E_EQUAL ? E_UNEQUAL : E_EQUAL;
break;
case E_OR:
// !(a || b) -> !a && !b
tmp = e->left.expr;
e->type = E_AND;
e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr);
tmp->type = E_NOT;
tmp->right.expr = NULL;
e = expr_transform(e);
break;
case E_AND:
// !(a && b) -> !a || !b
tmp = e->left.expr;
e->type = E_OR;
e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr);
tmp->type = E_NOT;
tmp->right.expr = NULL;
e = expr_transform(e);
break;
case E_SYMBOL:
if (e->left.expr->left.sym == &symbol_yes) {
// !'y' -> 'n'
tmp = e->left.expr;
free(e);
e = tmp;
e->type = E_SYMBOL;
e->left.sym = &symbol_no;
break;
}
if (e->left.expr->left.sym == &symbol_mod) {
// !'m' -> 'm'
tmp = e->left.expr;
free(e);
e = tmp;
e->type = E_SYMBOL;
e->left.sym = &symbol_mod;
break;
}
if (e->left.expr->left.sym == &symbol_no) {
// !'n' -> 'y'
tmp = e->left.expr;
free(e);
e = tmp;
e->type = E_SYMBOL;
e->left.sym = &symbol_yes;
break;
}
break;
default:
;
}
break;
default:
;
}
return e;
}
int expr_contains_symbol(struct expr *dep, struct symbol *sym)
{
if (!dep)
return 0;
switch (dep->type) {
case E_AND:
case E_OR:
return expr_contains_symbol(dep->left.expr, sym) ||
expr_contains_symbol(dep->right.expr, sym);
case E_SYMBOL:
return dep->left.sym == sym;
case E_EQUAL:
case E_UNEQUAL:
return dep->left.sym == sym ||
dep->right.sym == sym;
case E_NOT:
return expr_contains_symbol(dep->left.expr, sym);
default:
;
}
return 0;
}
bool expr_depends_symbol(struct expr *dep, struct symbol *sym)
{
if (!dep)
return false;
switch (dep->type) {
case E_AND:
return expr_depends_symbol(dep->left.expr, sym) ||
expr_depends_symbol(dep->right.expr, sym);
case E_SYMBOL:
return dep->left.sym == sym;
case E_EQUAL:
if (dep->left.sym == sym) {
if (dep->right.sym == &symbol_yes || dep->right.sym == &symbol_mod)
return true;
}
break;
case E_UNEQUAL:
if (dep->left.sym == sym) {
if (dep->right.sym == &symbol_no)
return true;
}
break;
default:
;
}
return false;
}
struct expr *expr_extract_eq_and(struct expr **ep1, struct expr **ep2)
{
struct expr *tmp = NULL;
expr_extract_eq(E_AND, &tmp, ep1, ep2);
if (tmp) {
*ep1 = expr_eliminate_yn(*ep1);
*ep2 = expr_eliminate_yn(*ep2);
}
return tmp;
}
struct expr *expr_extract_eq_or(struct expr **ep1, struct expr **ep2)
{
struct expr *tmp = NULL;
expr_extract_eq(E_OR, &tmp, ep1, ep2);
if (tmp) {
*ep1 = expr_eliminate_yn(*ep1);
*ep2 = expr_eliminate_yn(*ep2);
}
return tmp;
}
void expr_extract_eq(enum expr_type type, struct expr **ep, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
if (e1->type == type) {
expr_extract_eq(type, ep, &e1->left.expr, &e2);
expr_extract_eq(type, ep, &e1->right.expr, &e2);
return;
}
if (e2->type == type) {
expr_extract_eq(type, ep, ep1, &e2->left.expr);
expr_extract_eq(type, ep, ep1, &e2->right.expr);
return;
}
if (expr_eq(e1, e2)) {
*ep = *ep ? expr_alloc_two(type, *ep, e1) : e1;
expr_free(e2);
if (type == E_AND) {
e1 = expr_alloc_symbol(&symbol_yes);
e2 = expr_alloc_symbol(&symbol_yes);
} else if (type == E_OR) {
e1 = expr_alloc_symbol(&symbol_no);
e2 = expr_alloc_symbol(&symbol_no);
}
}
#undef e1
#undef e2
}
struct expr *expr_trans_compare(struct expr *e, enum expr_type type, struct symbol *sym)
{
struct expr *e1, *e2;
if (!e) {
e = expr_alloc_symbol(sym);
if (type == E_UNEQUAL)
e = expr_alloc_one(E_NOT, e);
return e;
}
switch (e->type) {
case E_AND:
e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym);
e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym);
if (sym == &symbol_yes)
e = expr_alloc_two(E_AND, e1, e2);
if (sym == &symbol_no)
e = expr_alloc_two(E_OR, e1, e2);
if (type == E_UNEQUAL)
e = expr_alloc_one(E_NOT, e);
return e;
case E_OR:
e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym);
e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym);
if (sym == &symbol_yes)
e = expr_alloc_two(E_OR, e1, e2);
if (sym == &symbol_no)
e = expr_alloc_two(E_AND, e1, e2);
if (type == E_UNEQUAL)
e = expr_alloc_one(E_NOT, e);
return e;
case E_NOT:
return expr_trans_compare(e->left.expr, type == E_EQUAL ? E_UNEQUAL : E_EQUAL, sym);
case E_UNEQUAL:
case E_EQUAL:
if (type == E_EQUAL) {
if (sym == &symbol_yes)
return expr_copy(e);
if (sym == &symbol_mod)
return expr_alloc_symbol(&symbol_no);
if (sym == &symbol_no)
return expr_alloc_one(E_NOT, expr_copy(e));
} else {
if (sym == &symbol_yes)
return expr_alloc_one(E_NOT, expr_copy(e));
if (sym == &symbol_mod)
return expr_alloc_symbol(&symbol_yes);
if (sym == &symbol_no)
return expr_copy(e);
}
break;
case E_SYMBOL:
return expr_alloc_comp(type, e->left.sym, sym);
case E_LIST:
case E_RANGE:
case E_NONE:
/* panic */;
}
return NULL;
}
tristate expr_calc_value(struct expr *e)
{
tristate val1, val2;
const char *str1, *str2;
if (!e)
return yes;
switch (e->type) {
case E_SYMBOL:
sym_calc_value(e->left.sym);
return e->left.sym->curr.tri;
case E_AND:
val1 = expr_calc_value(e->left.expr);
val2 = expr_calc_value(e->right.expr);
return EXPR_AND(val1, val2);
case E_OR:
val1 = expr_calc_value(e->left.expr);
val2 = expr_calc_value(e->right.expr);
return EXPR_OR(val1, val2);
case E_NOT:
val1 = expr_calc_value(e->left.expr);
return EXPR_NOT(val1);
case E_EQUAL:
sym_calc_value(e->left.sym);
sym_calc_value(e->right.sym);
str1 = sym_get_string_value(e->left.sym);
str2 = sym_get_string_value(e->right.sym);
return !strcmp(str1, str2) ? yes : no;
case E_UNEQUAL:
sym_calc_value(e->left.sym);
sym_calc_value(e->right.sym);
str1 = sym_get_string_value(e->left.sym);
str2 = sym_get_string_value(e->right.sym);
return !strcmp(str1, str2) ? no : yes;
default:
printf("expr_calc_value: %d?\n", e->type);
return no;
}
}
int expr_compare_type(enum expr_type t1, enum expr_type t2)
{
#if 0
return 1;
#else
if (t1 == t2)
return 0;
switch (t1) {
case E_EQUAL:
case E_UNEQUAL:
if (t2 == E_NOT)
return 1;
case E_NOT:
if (t2 == E_AND)
return 1;
case E_AND:
if (t2 == E_OR)
return 1;
case E_OR:
if (t2 == E_LIST)
return 1;
case E_LIST:
if (t2 == 0)
return 1;
default:
return -1;
}
printf("[%dgt%d?]", t1, t2);
return 0;
#endif
}
static inline struct expr *
expr_get_leftmost_symbol(const struct expr *e)
{
if (e == NULL)
return NULL;
while (e->type != E_SYMBOL)
e = e->left.expr;
return expr_copy(e);
}
/*
* Given expression `e1' and `e2', returns the leaf of the longest
* sub-expression of `e1' not containing 'e2.
*/
struct expr *expr_simplify_unmet_dep(struct expr *e1, struct expr *e2)
{
struct expr *ret;
switch (e1->type) {
case E_OR:
return expr_alloc_and(
expr_simplify_unmet_dep(e1->left.expr, e2),
expr_simplify_unmet_dep(e1->right.expr, e2));
case E_AND: {
struct expr *e;
e = expr_alloc_and(expr_copy(e1), expr_copy(e2));
e = expr_eliminate_dups(e);
ret = (!expr_eq(e, e1)) ? e1 : NULL;
expr_free(e);
break;
}
default:
ret = e1;
break;
}
return expr_get_leftmost_symbol(ret);
}
void expr_print(struct expr *e, void (*fn)(void *, struct symbol *, const char *), void *data, int prevtoken)
{
if (!e) {
fn(data, NULL, "y");
return;
}
if (expr_compare_type(prevtoken, e->type) > 0)
fn(data, NULL, "(");
switch (e->type) {
case E_SYMBOL:
if (e->left.sym->name)
fn(data, e->left.sym, e->left.sym->name);
else
fn(data, NULL, "<choice>");
break;
case E_NOT:
fn(data, NULL, "!");
expr_print(e->left.expr, fn, data, E_NOT);
break;
case E_EQUAL:
if (e->left.sym->name)
fn(data, e->left.sym, e->left.sym->name);
else
fn(data, NULL, "<choice>");
fn(data, NULL, "=");
fn(data, e->right.sym, e->right.sym->name);
break;
case E_UNEQUAL:
if (e->left.sym->name)
fn(data, e->left.sym, e->left.sym->name);
else
fn(data, NULL, "<choice>");
fn(data, NULL, "!=");
fn(data, e->right.sym, e->right.sym->name);
break;
case E_OR:
expr_print(e->left.expr, fn, data, E_OR);
fn(data, NULL, " || ");
expr_print(e->right.expr, fn, data, E_OR);
break;
case E_AND:
expr_print(e->left.expr, fn, data, E_AND);
fn(data, NULL, " && ");
expr_print(e->right.expr, fn, data, E_AND);
break;
case E_LIST:
fn(data, e->right.sym, e->right.sym->name);
if (e->left.expr) {
fn(data, NULL, " ^ ");
expr_print(e->left.expr, fn, data, E_LIST);
}
break;
case E_RANGE:
fn(data, NULL, "[");
fn(data, e->left.sym, e->left.sym->name);
fn(data, NULL, " ");
fn(data, e->right.sym, e->right.sym->name);
fn(data, NULL, "]");
break;
default:
{
char buf[32];
sprintf(buf, "<unknown type %d>", e->type);
fn(data, NULL, buf);
break;
}
}
if (expr_compare_type(prevtoken, e->type) > 0)
fn(data, NULL, ")");
}
static void expr_print_file_helper(void *data, struct symbol *sym, const char *str)
{
xfwrite(str, strlen(str), 1, data);
}
void expr_fprint(struct expr *e, FILE *out)
{
expr_print(e, expr_print_file_helper, out, E_NONE);
}
static void expr_print_gstr_helper(void *data, struct symbol *sym, const char *str)
{
struct gstr *gs = (struct gstr*)data;
const char *sym_str = NULL;
if (sym)
sym_str = sym_get_string_value(sym);
if (gs->max_width) {
unsigned extra_length = strlen(str);
const char *last_cr = strrchr(gs->s, '\n');
unsigned last_line_length;
if (sym_str)
extra_length += 4 + strlen(sym_str);
if (!last_cr)
last_cr = gs->s;
last_line_length = strlen(gs->s) - (last_cr - gs->s);
if ((last_line_length + extra_length) > gs->max_width)
str_append(gs, "\\\n");
}
str_append(gs, str);
if (sym && sym->type != S_UNKNOWN)
str_printf(gs, " [=%s]", sym_str);
}
void expr_gstr_print(struct expr *e, struct gstr *gs)
{
expr_print(e, expr_print_gstr_helper, gs, E_NONE);
}
| gpl-2.0 |
Tim1928/DBK-3.0-4.2 | drivers/media/dvb/dvb-usb/friio.c | 2773 | 12715 | /* DVB USB compliant Linux driver for the Friio USB2.0 ISDB-T receiver.
*
* Copyright (C) 2009 Akihiro Tsukada <tskd2@yahoo.co.jp>
*
* This module is based off the the gl861 and vp702x modules.
*
* 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.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "friio.h"
/* debug */
int dvb_usb_friio_debug;
module_param_named(debug, dvb_usb_friio_debug, int, 0644);
MODULE_PARM_DESC(debug,
"set debugging level (1=info,2=xfer,4=rc,8=fe (or-able))."
DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
/**
* Indirect I2C access to the PLL via FE.
* whole I2C protocol data to the PLL is sent via the FE's I2C register.
* This is done by a control msg to the FE with the I2C data accompanied, and
* a specific USB request number is assigned for that purpose.
*
* this func sends wbuf[1..] to the I2C register wbuf[0] at addr (= at FE).
* TODO: refoctored, smarter i2c functions.
*/
static int gl861_i2c_ctrlmsg_data(struct dvb_usb_device *d, u8 addr,
u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen)
{
u16 index = wbuf[0]; /* must be JDVBT90502_2ND_I2C_REG(=0xFE) */
u16 value = addr << (8 + 1);
int wo = (rbuf == NULL || rlen == 0); /* write only */
u8 req, type;
deb_xfer("write to PLL:0x%02x via FE reg:0x%02x, len:%d\n",
wbuf[1], wbuf[0], wlen - 1);
if (wo && wlen >= 2) {
req = GL861_REQ_I2C_DATA_CTRL_WRITE;
type = GL861_WRITE;
udelay(20);
return usb_control_msg(d->udev, usb_sndctrlpipe(d->udev, 0),
req, type, value, index,
&wbuf[1], wlen - 1, 2000);
}
deb_xfer("not supported ctrl-msg, aborting.");
return -EINVAL;
}
/* normal I2C access (without extra data arguments).
* write to the register wbuf[0] at I2C address addr with the value wbuf[1],
* or read from the register wbuf[0].
* register address can be 16bit (wbuf[2]<<8 | wbuf[0]) if wlen==3
*/
static int gl861_i2c_msg(struct dvb_usb_device *d, u8 addr,
u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen)
{
u16 index;
u16 value = addr << (8 + 1);
int wo = (rbuf == NULL || rlen == 0); /* write-only */
u8 req, type;
unsigned int pipe;
/* special case for the indirect I2C access to the PLL via FE, */
if (addr == friio_fe_config.demod_address &&
wbuf[0] == JDVBT90502_2ND_I2C_REG)
return gl861_i2c_ctrlmsg_data(d, addr, wbuf, wlen, rbuf, rlen);
if (wo) {
req = GL861_REQ_I2C_WRITE;
type = GL861_WRITE;
pipe = usb_sndctrlpipe(d->udev, 0);
} else { /* rw */
req = GL861_REQ_I2C_READ;
type = GL861_READ;
pipe = usb_rcvctrlpipe(d->udev, 0);
}
switch (wlen) {
case 1:
index = wbuf[0];
break;
case 2:
index = wbuf[0];
value = value + wbuf[1];
break;
case 3:
/* special case for 16bit register-address */
index = (wbuf[2] << 8) | wbuf[0];
value = value + wbuf[1];
break;
default:
deb_xfer("wlen = %x, aborting.", wlen);
return -EINVAL;
}
msleep(1);
return usb_control_msg(d->udev, pipe, req, type,
value, index, rbuf, rlen, 2000);
}
/* I2C */
static int gl861_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i;
if (num > 2)
return -EINVAL;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
/* write/read request */
if (i + 1 < num && (msg[i + 1].flags & I2C_M_RD)) {
if (gl861_i2c_msg(d, msg[i].addr,
msg[i].buf, msg[i].len,
msg[i + 1].buf, msg[i + 1].len) < 0)
break;
i++;
} else
if (gl861_i2c_msg(d, msg[i].addr, msg[i].buf,
msg[i].len, NULL, 0) < 0)
break;
}
mutex_unlock(&d->i2c_mutex);
return i;
}
static u32 gl861_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static int friio_ext_ctl(struct dvb_usb_adapter *adap,
u32 sat_color, int lnb_on)
{
int i;
int ret;
struct i2c_msg msg;
u8 *buf;
u32 mask;
u8 lnb = (lnb_on) ? FRIIO_CTL_LNB : 0;
buf = kmalloc(2, GFP_KERNEL);
if (!buf)
return -ENOMEM;
msg.addr = 0x00;
msg.flags = 0;
msg.len = 2;
msg.buf = buf;
buf[0] = 0x00;
/* send 2bit header (&B10) */
buf[1] = lnb | FRIIO_CTL_LED | FRIIO_CTL_STROBE;
ret = gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
buf[1] |= FRIIO_CTL_CLK;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
buf[1] = lnb | FRIIO_CTL_STROBE;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
buf[1] |= FRIIO_CTL_CLK;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
/* send 32bit(satur, R, G, B) data in serial */
mask = 1 << 31;
for (i = 0; i < 32; i++) {
buf[1] = lnb | FRIIO_CTL_STROBE;
if (sat_color & mask)
buf[1] |= FRIIO_CTL_LED;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
buf[1] |= FRIIO_CTL_CLK;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
mask >>= 1;
}
/* set the strobe off */
buf[1] = lnb;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
buf[1] |= FRIIO_CTL_CLK;
ret += gl861_i2c_xfer(&adap->dev->i2c_adap, &msg, 1);
kfree(buf);
return (ret == 70);
}
static int friio_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff);
/* TODO: move these init cmds to the FE's init routine? */
static u8 streaming_init_cmds[][2] = {
{0x33, 0x08},
{0x37, 0x40},
{0x3A, 0x1F},
{0x3B, 0xFF},
{0x3C, 0x1F},
{0x3D, 0xFF},
{0x38, 0x00},
{0x35, 0x00},
{0x39, 0x00},
{0x36, 0x00},
};
static int cmdlen = sizeof(streaming_init_cmds) / 2;
/*
* Command sequence in this init function is a replay
* of the captured USB commands from the Windows proprietary driver.
*/
static int friio_initialize(struct dvb_usb_device *d)
{
int ret;
int i;
int retry = 0;
u8 *rbuf, *wbuf;
deb_info("%s called.\n", __func__);
wbuf = kmalloc(3, GFP_KERNEL);
if (!wbuf)
return -ENOMEM;
rbuf = kmalloc(2, GFP_KERNEL);
if (!rbuf) {
kfree(wbuf);
return -ENOMEM;
}
/* use gl861_i2c_msg instead of gl861_i2c_xfer(), */
/* because the i2c device is not set up yet. */
wbuf[0] = 0x11;
wbuf[1] = 0x02;
ret = gl861_i2c_msg(d, 0x00, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
msleep(2);
wbuf[0] = 0x11;
wbuf[1] = 0x00;
ret = gl861_i2c_msg(d, 0x00, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
msleep(1);
/* following msgs should be in the FE's init code? */
/* cmd sequence to identify the device type? (friio black/white) */
wbuf[0] = 0x03;
wbuf[1] = 0x80;
/* can't use gl861_i2c_cmd, as the register-addr is 16bit(0x0100) */
ret = usb_control_msg(d->udev, usb_sndctrlpipe(d->udev, 0),
GL861_REQ_I2C_DATA_CTRL_WRITE, GL861_WRITE,
0x1200, 0x0100, wbuf, 2, 2000);
if (ret < 0)
goto error;
msleep(2);
wbuf[0] = 0x00;
wbuf[2] = 0x01; /* reg.0x0100 */
wbuf[1] = 0x00;
ret = gl861_i2c_msg(d, 0x12 >> 1, wbuf, 3, rbuf, 2);
/* my Friio White returns 0xffff. */
if (ret < 0 || rbuf[0] != 0xff || rbuf[1] != 0xff)
goto error;
msleep(2);
wbuf[0] = 0x03;
wbuf[1] = 0x80;
ret = usb_control_msg(d->udev, usb_sndctrlpipe(d->udev, 0),
GL861_REQ_I2C_DATA_CTRL_WRITE, GL861_WRITE,
0x9000, 0x0100, wbuf, 2, 2000);
if (ret < 0)
goto error;
msleep(2);
wbuf[0] = 0x00;
wbuf[2] = 0x01; /* reg.0x0100 */
wbuf[1] = 0x00;
ret = gl861_i2c_msg(d, 0x90 >> 1, wbuf, 3, rbuf, 2);
/* my Friio White returns 0xffff again. */
if (ret < 0 || rbuf[0] != 0xff || rbuf[1] != 0xff)
goto error;
msleep(1);
restart:
/* ============ start DEMOD init cmds ================== */
/* read PLL status to clear the POR bit */
wbuf[0] = JDVBT90502_2ND_I2C_REG;
wbuf[1] = (FRIIO_PLL_ADDR << 1) + 1; /* +1 for reading */
ret = gl861_i2c_msg(d, FRIIO_DEMOD_ADDR, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
msleep(5);
/* note: DEMODULATOR has 16bit register-address. */
wbuf[0] = 0x00;
wbuf[2] = 0x01; /* reg addr: 0x0100 */
wbuf[1] = 0x00; /* val: not used */
ret = gl861_i2c_msg(d, FRIIO_DEMOD_ADDR, wbuf, 3, rbuf, 1);
if (ret < 0)
goto error;
/*
msleep(1);
wbuf[0] = 0x80;
wbuf[1] = 0x00;
ret = gl861_i2c_msg(d, FRIIO_DEMOD_ADDR, wbuf, 2, rbuf, 1);
if (ret < 0)
goto error;
*/
if (rbuf[0] & 0x80) { /* still in PowerOnReset state? */
if (++retry > 3) {
deb_info("failed to get the correct"
" FE demod status:0x%02x\n", rbuf[0]);
goto error;
}
msleep(100);
goto restart;
}
/* TODO: check return value in rbuf */
/* =========== end DEMOD init cmds ===================== */
msleep(1);
wbuf[0] = 0x30;
wbuf[1] = 0x04;
ret = gl861_i2c_msg(d, 0x00, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
msleep(2);
/* following 2 cmds unnecessary? */
wbuf[0] = 0x00;
wbuf[1] = 0x01;
ret = gl861_i2c_msg(d, 0x00, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
wbuf[0] = 0x06;
wbuf[1] = 0x0F;
ret = gl861_i2c_msg(d, 0x00, wbuf, 2, NULL, 0);
if (ret < 0)
goto error;
/* some streaming ctl cmds (maybe) */
msleep(10);
for (i = 0; i < cmdlen; i++) {
ret = gl861_i2c_msg(d, 0x00, streaming_init_cmds[i], 2,
NULL, 0);
if (ret < 0)
goto error;
msleep(1);
}
msleep(20);
/* change the LED color etc. */
ret = friio_streaming_ctrl(&d->adapter[0], 0);
if (ret < 0)
goto error;
return 0;
error:
kfree(wbuf);
kfree(rbuf);
deb_info("%s:ret == %d\n", __func__, ret);
return -EIO;
}
/* Callbacks for DVB USB */
static int friio_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
int ret;
deb_info("%s called.(%d)\n", __func__, onoff);
/* set the LED color and saturation (and LNB on) */
if (onoff)
ret = friio_ext_ctl(adap, 0x6400ff64, 1);
else
ret = friio_ext_ctl(adap, 0x96ff00ff, 1);
if (ret != 1) {
deb_info("%s failed to send cmdx. ret==%d\n", __func__, ret);
return -EREMOTEIO;
}
return 0;
}
static int friio_frontend_attach(struct dvb_usb_adapter *adap)
{
if (friio_initialize(adap->dev) < 0)
return -EIO;
adap->fe = jdvbt90502_attach(adap->dev);
if (adap->fe == NULL)
return -EIO;
return 0;
}
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties friio_properties;
static int friio_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct dvb_usb_device *d;
struct usb_host_interface *alt;
int ret;
if (intf->num_altsetting < GL861_ALTSETTING_COUNT)
return -ENODEV;
alt = usb_altnum_to_altsetting(intf, FRIIO_BULK_ALTSETTING);
if (alt == NULL) {
deb_rc("not alt found!\n");
return -ENODEV;
}
ret = usb_set_interface(interface_to_usbdev(intf),
alt->desc.bInterfaceNumber,
alt->desc.bAlternateSetting);
if (ret != 0) {
deb_rc("failed to set alt-setting!\n");
return ret;
}
ret = dvb_usb_device_init(intf, &friio_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0)
friio_streaming_ctrl(&d->adapter[0], 1);
return ret;
}
struct jdvbt90502_config friio_fe_config = {
.demod_address = FRIIO_DEMOD_ADDR,
.pll_address = FRIIO_PLL_ADDR,
};
static struct i2c_algorithm gl861_i2c_algo = {
.master_xfer = gl861_i2c_xfer,
.functionality = gl861_i2c_func,
};
static struct usb_device_id friio_table[] = {
{ USB_DEVICE(USB_VID_774, USB_PID_FRIIO_WHITE) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, friio_table);
static struct dvb_usb_device_properties friio_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = 0,
.num_adapters = 1,
.adapter = {
/* caps:0 => no pid filter, 188B TS packet */
/* GL861 has a HW pid filter, but no info available. */
{
.caps = 0,
.frontend_attach = friio_frontend_attach,
.streaming_ctrl = friio_streaming_ctrl,
.stream = {
.type = USB_BULK,
/* count <= MAX_NO_URBS_FOR_DATA_STREAM(10) */
.count = 8,
.endpoint = 0x01,
.u = {
/* GL861 has 6KB buf inside */
.bulk = {
.buffersize = 16384,
}
}
},
}
},
.i2c_algo = &gl861_i2c_algo,
.num_device_descs = 1,
.devices = {
{
.name = "774 Friio ISDB-T USB2.0",
.cold_ids = { NULL },
.warm_ids = { &friio_table[0], NULL },
},
}
};
static struct usb_driver friio_driver = {
.name = "dvb_usb_friio",
.probe = friio_probe,
.disconnect = dvb_usb_device_exit,
.id_table = friio_table,
};
/* module stuff */
static int __init friio_module_init(void)
{
int ret;
ret = usb_register(&friio_driver);
if (ret)
err("usb_register failed. Error number %d", ret);
return ret;
}
static void __exit friio_module_exit(void)
{
/* deregister this driver from the USB subsystem */
usb_deregister(&friio_driver);
}
module_init(friio_module_init);
module_exit(friio_module_exit);
MODULE_AUTHOR("Akihiro Tsukada <tskd2@yahoo.co.jp>");
MODULE_DESCRIPTION("Driver for Friio ISDB-T USB2.0 Receiver");
MODULE_VERSION("0.2");
MODULE_LICENSE("GPL");
| gpl-2.0 |
troth/linux-kernel | arch/xtensa/variants/s6000/irq.c | 3285 | 1545 | /*
* s6000 irq crossbar
*
* Copyright (c) 2009 emlix GmbH
* Authors: Johannes Weiner <hannes@cmpxchg.org>
* Oskar Schirmer <oskar@scara.com>
*/
#include <linux/io.h>
#include <asm/irq.h>
#include <variant/hardware.h>
/* S6_REG_INTC */
#define INTC_STATUS 0x000
#define INTC_RAW 0x010
#define INTC_STATUS_AG 0x100
#define INTC_CFG(n) (0x200 + 4 * (n))
/*
* The s6000 has a crossbar that multiplexes interrupt output lines
* from the peripherals to input lines on the xtensa core.
*
* We leave the mapping decisions to the platform as it depends on the
* actually connected peripherals which distribution makes sense.
*/
extern const signed char *platform_irq_mappings[NR_IRQS];
static unsigned long scp_to_intc_enable[] = {
#define TO_INTC_ENABLE(n) (((n) << 1) + 1)
TO_INTC_ENABLE(0),
TO_INTC_ENABLE(1),
TO_INTC_ENABLE(2),
TO_INTC_ENABLE(3),
TO_INTC_ENABLE(4),
TO_INTC_ENABLE(5),
TO_INTC_ENABLE(6),
TO_INTC_ENABLE(7),
TO_INTC_ENABLE(8),
TO_INTC_ENABLE(9),
TO_INTC_ENABLE(10),
TO_INTC_ENABLE(11),
TO_INTC_ENABLE(12),
-1,
-1,
TO_INTC_ENABLE(13),
-1,
TO_INTC_ENABLE(14),
-1,
TO_INTC_ENABLE(15),
#undef TO_INTC_ENABLE
};
static void irq_set(unsigned int irq, int enable)
{
unsigned long en;
const signed char *m = platform_irq_mappings[irq];
if (!m)
return;
en = enable ? scp_to_intc_enable[irq] : 0;
while (*m >= 0) {
writel(en, S6_REG_INTC + INTC_CFG(*m));
m++;
}
}
void variant_irq_enable(unsigned int irq)
{
irq_set(irq, 1);
}
void variant_irq_disable(unsigned int irq)
{
irq_set(irq, 0);
}
| gpl-2.0 |
CyanogenMod/zte-kernel-msm7x27 | drivers/net/wan/cycx_x25.c | 3541 | 45915 | /*
* cycx_x25.c Cyclom 2X WAN Link Driver. X.25 module.
*
* Author: Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* Copyright: (c) 1998-2003 Arnaldo Carvalho de Melo
*
* Based on sdla_x25.c by Gene Kozin <genek@compuserve.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.
* ============================================================================
* 2001/01/12 acme use dev_kfree_skb_irq on interrupt context
* 2000/04/02 acme dprintk, cycx_debug
* fixed the bug introduced in get_dev_by_lcn and
* get_dev_by_dte_addr by the anonymous hacker
* that converted this driver to softnet
* 2000/01/08 acme cleanup
* 1999/10/27 acme use ARPHRD_HWX25 so that the X.25 stack know
* that we have a X.25 stack implemented in
* firmware onboard
* 1999/10/18 acme support for X.25 sockets in if_send,
* beware: socket(AF_X25...) IS WORK IN PROGRESS,
* TCP/IP over X.25 via wanrouter not affected,
* working.
* 1999/10/09 acme chan_disc renamed to chan_disconnect,
* began adding support for X.25 sockets:
* conf->protocol in new_if
* 1999/10/05 acme fixed return E... to return -E...
* 1999/08/10 acme serialized access to the card thru a spinlock
* in x25_exec
* 1999/08/09 acme removed per channel spinlocks
* removed references to enable_tx_int
* 1999/05/28 acme fixed nibble_to_byte, ackvc now properly treated
* if_send simplified
* 1999/05/25 acme fixed t1, t2, t21 & t23 configuration
* use spinlocks instead of cli/sti in some points
* 1999/05/24 acme finished the x25_get_stat function
* 1999/05/23 acme dev->type = ARPHRD_X25 (tcpdump only works,
* AFAIT, with ARPHRD_ETHER). This seems to be
* needed to use socket(AF_X25)...
* Now the config file must specify a peer media
* address for svc channels over a crossover cable.
* Removed hold_timeout from x25_channel_t,
* not used.
* A little enhancement in the DEBUG processing
* 1999/05/22 acme go to DISCONNECTED in disconnect_confirm_intr,
* instead of chan_disc.
* 1999/05/16 marcelo fixed timer initialization in SVCs
* 1999/01/05 acme x25_configure now get (most of) all
* parameters...
* 1999/01/05 acme pktlen now (correctly) uses log2 (value
* configured)
* 1999/01/03 acme judicious use of data types (u8, u16, u32, etc)
* 1999/01/03 acme cyx_isr: reset dpmbase to acknowledge
* indication (interrupt from cyclom 2x)
* 1999/01/02 acme cyx_isr: first hackings...
* 1999/01/0203 acme when initializing an array don't give less
* elements than declared...
* example: char send_cmd[6] = "?\xFF\x10";
* you'll gonna lose a couple hours, 'cause your
* brain won't admit that there's an error in the
* above declaration... the side effect is that
* memset is put into the unresolved symbols
* instead of using the inline memset functions...
* 1999/01/02 acme began chan_connect, chan_send, x25_send
* 1998/12/31 acme x25_configure
* this code can be compiled as non module
* 1998/12/27 acme code cleanup
* IPX code wiped out! let's decrease code
* complexity for now, remember: I'm learning! :)
* bps_to_speed_code OK
* 1998/12/26 acme Minimal debug code cleanup
* 1998/08/08 acme Initial version.
*/
#define CYCLOMX_X25_DEBUG 1
#include <linux/ctype.h> /* isdigit() */
#include <linux/errno.h> /* return codes */
#include <linux/if_arp.h> /* ARPHRD_HWX25 */
#include <linux/kernel.h> /* printk(), and other useful stuff */
#include <linux/module.h>
#include <linux/string.h> /* inline memset(), etc. */
#include <linux/sched.h>
#include <linux/slab.h> /* kmalloc(), kfree() */
#include <linux/stddef.h> /* offsetof(), etc. */
#include <linux/wanrouter.h> /* WAN router definitions */
#include <asm/byteorder.h> /* htons(), etc. */
#include <linux/cyclomx.h> /* Cyclom 2X common user API definitions */
#include <linux/cycx_x25.h> /* X.25 firmware API definitions */
#include <net/x25device.h>
/* Defines & Macros */
#define CYCX_X25_MAX_CMD_RETRY 5
#define CYCX_X25_CHAN_MTU 2048 /* unfragmented logical channel MTU */
/* Data Structures */
/* This is an extension of the 'struct net_device' we create for each network
interface to keep the rest of X.25 channel-specific data. */
struct cycx_x25_channel {
/* This member must be first. */
struct net_device *slave; /* WAN slave */
char name[WAN_IFNAME_SZ+1]; /* interface name, ASCIIZ */
char addr[WAN_ADDRESS_SZ+1]; /* media address, ASCIIZ */
char *local_addr; /* local media address, ASCIIZ -
svc thru crossover cable */
s16 lcn; /* logical channel number/conn.req.key*/
u8 link;
struct timer_list timer; /* timer used for svc channel disc. */
u16 protocol; /* ethertype, 0 - multiplexed */
u8 svc; /* 0 - permanent, 1 - switched */
u8 state; /* channel state */
u8 drop_sequence; /* mark sequence for dropping */
u32 idle_tmout; /* sec, before disconnecting */
struct sk_buff *rx_skb; /* receive socket buffer */
struct cycx_device *card; /* -> owner */
struct net_device_stats ifstats;/* interface statistics */
};
/* Function Prototypes */
/* WAN link driver entry points. These are called by the WAN router module. */
static int cycx_wan_update(struct wan_device *wandev),
cycx_wan_new_if(struct wan_device *wandev, struct net_device *dev,
wanif_conf_t *conf),
cycx_wan_del_if(struct wan_device *wandev, struct net_device *dev);
/* Network device interface */
static int cycx_netdevice_init(struct net_device *dev);
static int cycx_netdevice_open(struct net_device *dev);
static int cycx_netdevice_stop(struct net_device *dev);
static int cycx_netdevice_hard_header(struct sk_buff *skb,
struct net_device *dev, u16 type,
const void *daddr, const void *saddr,
unsigned len);
static int cycx_netdevice_rebuild_header(struct sk_buff *skb);
static netdev_tx_t cycx_netdevice_hard_start_xmit(struct sk_buff *skb,
struct net_device *dev);
static struct net_device_stats *
cycx_netdevice_get_stats(struct net_device *dev);
/* Interrupt handlers */
static void cycx_x25_irq_handler(struct cycx_device *card),
cycx_x25_irq_tx(struct cycx_device *card, struct cycx_x25_cmd *cmd),
cycx_x25_irq_rx(struct cycx_device *card, struct cycx_x25_cmd *cmd),
cycx_x25_irq_log(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_stat(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_connect_confirm(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_disconnect_confirm(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_connect(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_disconnect(struct cycx_device *card,
struct cycx_x25_cmd *cmd),
cycx_x25_irq_spurious(struct cycx_device *card,
struct cycx_x25_cmd *cmd);
/* X.25 firmware interface functions */
static int cycx_x25_configure(struct cycx_device *card,
struct cycx_x25_config *conf),
cycx_x25_get_stats(struct cycx_device *card),
cycx_x25_send(struct cycx_device *card, u8 link, u8 lcn, u8 bitm,
int len, void *buf),
cycx_x25_connect_response(struct cycx_device *card,
struct cycx_x25_channel *chan),
cycx_x25_disconnect_response(struct cycx_device *card, u8 link,
u8 lcn);
/* channel functions */
static int cycx_x25_chan_connect(struct net_device *dev),
cycx_x25_chan_send(struct net_device *dev, struct sk_buff *skb);
static void cycx_x25_chan_disconnect(struct net_device *dev),
cycx_x25_chan_send_event(struct net_device *dev, u8 event);
/* Miscellaneous functions */
static void cycx_x25_set_chan_state(struct net_device *dev, u8 state),
cycx_x25_chan_timer(unsigned long d);
static void nibble_to_byte(u8 *s, u8 *d, u8 len, u8 nibble),
reset_timer(struct net_device *dev);
static u8 bps_to_speed_code(u32 bps);
static u8 cycx_log2(u32 n);
static unsigned dec_to_uint(u8 *str, int len);
static struct net_device *cycx_x25_get_dev_by_lcn(struct wan_device *wandev,
s16 lcn);
static struct net_device *
cycx_x25_get_dev_by_dte_addr(struct wan_device *wandev, char *dte);
static void cycx_x25_chan_setup(struct net_device *dev);
#ifdef CYCLOMX_X25_DEBUG
static void hex_dump(char *msg, unsigned char *p, int len);
static void cycx_x25_dump_config(struct cycx_x25_config *conf);
static void cycx_x25_dump_stats(struct cycx_x25_stats *stats);
static void cycx_x25_dump_devs(struct wan_device *wandev);
#else
#define hex_dump(msg, p, len)
#define cycx_x25_dump_config(conf)
#define cycx_x25_dump_stats(stats)
#define cycx_x25_dump_devs(wandev)
#endif
/* Public Functions */
/* X.25 Protocol Initialization routine.
*
* This routine is called by the main Cyclom 2X module during setup. At this
* point adapter is completely initialized and X.25 firmware is running.
* o configure adapter
* o initialize protocol-specific fields of the adapter data space.
*
* Return: 0 o.k.
* < 0 failure. */
int cycx_x25_wan_init(struct cycx_device *card, wandev_conf_t *conf)
{
struct cycx_x25_config cfg;
/* Verify configuration ID */
if (conf->config_id != WANCONFIG_X25) {
printk(KERN_INFO "%s: invalid configuration ID %u!\n",
card->devname, conf->config_id);
return -EINVAL;
}
/* Initialize protocol-specific fields */
card->mbox = card->hw.dpmbase + X25_MBOX_OFFS;
card->u.x.connection_keys = 0;
spin_lock_init(&card->u.x.lock);
/* Configure adapter. Here we set reasonable defaults, then parse
* device configuration structure and set configuration options.
* Most configuration options are verified and corrected (if
* necessary) since we can't rely on the adapter to do so and don't
* want it to fail either. */
memset(&cfg, 0, sizeof(cfg));
cfg.link = 0;
cfg.clock = conf->clocking == WANOPT_EXTERNAL ? 8 : 55;
cfg.speed = bps_to_speed_code(conf->bps);
cfg.n3win = 7;
cfg.n2win = 2;
cfg.n2 = 5;
cfg.nvc = 1;
cfg.npvc = 1;
cfg.flags = 0x02; /* default = V35 */
cfg.t1 = 10; /* line carrier timeout */
cfg.t2 = 29; /* tx timeout */
cfg.t21 = 180; /* CALL timeout */
cfg.t23 = 180; /* CLEAR timeout */
/* adjust MTU */
if (!conf->mtu || conf->mtu >= 512)
card->wandev.mtu = 512;
else if (conf->mtu >= 256)
card->wandev.mtu = 256;
else if (conf->mtu >= 128)
card->wandev.mtu = 128;
else
card->wandev.mtu = 64;
cfg.pktlen = cycx_log2(card->wandev.mtu);
if (conf->station == WANOPT_DTE) {
cfg.locaddr = 3; /* DTE */
cfg.remaddr = 1; /* DCE */
} else {
cfg.locaddr = 1; /* DCE */
cfg.remaddr = 3; /* DTE */
}
if (conf->interface == WANOPT_RS232)
cfg.flags = 0; /* FIXME just reset the 2nd bit */
if (conf->u.x25.hi_pvc) {
card->u.x.hi_pvc = min_t(unsigned int, conf->u.x25.hi_pvc, 4095);
card->u.x.lo_pvc = min_t(unsigned int, conf->u.x25.lo_pvc, card->u.x.hi_pvc);
}
if (conf->u.x25.hi_svc) {
card->u.x.hi_svc = min_t(unsigned int, conf->u.x25.hi_svc, 4095);
card->u.x.lo_svc = min_t(unsigned int, conf->u.x25.lo_svc, card->u.x.hi_svc);
}
if (card->u.x.lo_pvc == 255)
cfg.npvc = 0;
else
cfg.npvc = card->u.x.hi_pvc - card->u.x.lo_pvc + 1;
cfg.nvc = card->u.x.hi_svc - card->u.x.lo_svc + 1 + cfg.npvc;
if (conf->u.x25.hdlc_window)
cfg.n2win = min_t(unsigned int, conf->u.x25.hdlc_window, 7);
if (conf->u.x25.pkt_window)
cfg.n3win = min_t(unsigned int, conf->u.x25.pkt_window, 7);
if (conf->u.x25.t1)
cfg.t1 = min_t(unsigned int, conf->u.x25.t1, 30);
if (conf->u.x25.t2)
cfg.t2 = min_t(unsigned int, conf->u.x25.t2, 30);
if (conf->u.x25.t11_t21)
cfg.t21 = min_t(unsigned int, conf->u.x25.t11_t21, 30);
if (conf->u.x25.t13_t23)
cfg.t23 = min_t(unsigned int, conf->u.x25.t13_t23, 30);
if (conf->u.x25.n2)
cfg.n2 = min_t(unsigned int, conf->u.x25.n2, 30);
/* initialize adapter */
if (cycx_x25_configure(card, &cfg))
return -EIO;
/* Initialize protocol-specific fields of adapter data space */
card->wandev.bps = conf->bps;
card->wandev.interface = conf->interface;
card->wandev.clocking = conf->clocking;
card->wandev.station = conf->station;
card->isr = cycx_x25_irq_handler;
card->exec = NULL;
card->wandev.update = cycx_wan_update;
card->wandev.new_if = cycx_wan_new_if;
card->wandev.del_if = cycx_wan_del_if;
card->wandev.state = WAN_DISCONNECTED;
return 0;
}
/* WAN Device Driver Entry Points */
/* Update device status & statistics. */
static int cycx_wan_update(struct wan_device *wandev)
{
/* sanity checks */
if (!wandev || !wandev->private)
return -EFAULT;
if (wandev->state == WAN_UNCONFIGURED)
return -ENODEV;
cycx_x25_get_stats(wandev->private);
return 0;
}
/* Create new logical channel.
* This routine is called by the router when ROUTER_IFNEW IOCTL is being
* handled.
* o parse media- and hardware-specific configuration
* o make sure that a new channel can be created
* o allocate resources, if necessary
* o prepare network device structure for registration.
*
* Return: 0 o.k.
* < 0 failure (channel will not be created) */
static int cycx_wan_new_if(struct wan_device *wandev, struct net_device *dev,
wanif_conf_t *conf)
{
struct cycx_device *card = wandev->private;
struct cycx_x25_channel *chan;
int err = 0;
if (!conf->name[0] || strlen(conf->name) > WAN_IFNAME_SZ) {
printk(KERN_INFO "%s: invalid interface name!\n",
card->devname);
return -EINVAL;
}
dev = alloc_netdev(sizeof(struct cycx_x25_channel), conf->name,
cycx_x25_chan_setup);
if (!dev)
return -ENOMEM;
chan = netdev_priv(dev);
strcpy(chan->name, conf->name);
chan->card = card;
chan->link = conf->port;
chan->protocol = conf->protocol ? ETH_P_X25 : ETH_P_IP;
chan->rx_skb = NULL;
/* only used in svc connected thru crossover cable */
chan->local_addr = NULL;
if (conf->addr[0] == '@') { /* SVC */
int len = strlen(conf->local_addr);
if (len) {
if (len > WAN_ADDRESS_SZ) {
printk(KERN_ERR "%s: %s local addr too long!\n",
wandev->name, chan->name);
err = -EINVAL;
goto error;
} else {
chan->local_addr = kmalloc(len + 1, GFP_KERNEL);
if (!chan->local_addr) {
err = -ENOMEM;
goto error;
}
}
strncpy(chan->local_addr, conf->local_addr,
WAN_ADDRESS_SZ);
}
chan->svc = 1;
strncpy(chan->addr, &conf->addr[1], WAN_ADDRESS_SZ);
init_timer(&chan->timer);
chan->timer.function = cycx_x25_chan_timer;
chan->timer.data = (unsigned long)dev;
/* Set channel timeouts (default if not specified) */
chan->idle_tmout = conf->idle_timeout ? conf->idle_timeout : 90;
} else if (isdigit(conf->addr[0])) { /* PVC */
s16 lcn = dec_to_uint(conf->addr, 0);
if (lcn >= card->u.x.lo_pvc && lcn <= card->u.x.hi_pvc)
chan->lcn = lcn;
else {
printk(KERN_ERR
"%s: PVC %u is out of range on interface %s!\n",
wandev->name, lcn, chan->name);
err = -EINVAL;
goto error;
}
} else {
printk(KERN_ERR "%s: invalid media address on interface %s!\n",
wandev->name, chan->name);
err = -EINVAL;
goto error;
}
return 0;
error:
free_netdev(dev);
return err;
}
/* Delete logical channel. */
static int cycx_wan_del_if(struct wan_device *wandev, struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
if (chan->svc) {
kfree(chan->local_addr);
if (chan->state == WAN_CONNECTED)
del_timer(&chan->timer);
}
return 0;
}
/* Network Device Interface */
static const struct header_ops cycx_header_ops = {
.create = cycx_netdevice_hard_header,
.rebuild = cycx_netdevice_rebuild_header,
};
static const struct net_device_ops cycx_netdev_ops = {
.ndo_init = cycx_netdevice_init,
.ndo_open = cycx_netdevice_open,
.ndo_stop = cycx_netdevice_stop,
.ndo_start_xmit = cycx_netdevice_hard_start_xmit,
.ndo_get_stats = cycx_netdevice_get_stats,
};
static void cycx_x25_chan_setup(struct net_device *dev)
{
/* Initialize device driver entry points */
dev->netdev_ops = &cycx_netdev_ops;
dev->header_ops = &cycx_header_ops;
/* Initialize media-specific parameters */
dev->mtu = CYCX_X25_CHAN_MTU;
dev->type = ARPHRD_HWX25; /* ARP h/w type */
dev->hard_header_len = 0; /* media header length */
dev->addr_len = 0; /* hardware address length */
}
/* Initialize Linux network interface.
*
* This routine is called only once for each interface, during Linux network
* interface registration. Returning anything but zero will fail interface
* registration. */
static int cycx_netdevice_init(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
struct cycx_device *card = chan->card;
struct wan_device *wandev = &card->wandev;
if (!chan->svc)
*(__be16*)dev->dev_addr = htons(chan->lcn);
/* Initialize hardware parameters (just for reference) */
dev->irq = wandev->irq;
dev->dma = wandev->dma;
dev->base_addr = wandev->ioport;
dev->mem_start = (unsigned long)wandev->maddr;
dev->mem_end = (unsigned long)(wandev->maddr +
wandev->msize - 1);
dev->flags |= IFF_NOARP;
/* Set transmit buffer queue length */
dev->tx_queue_len = 10;
/* Initialize socket buffers */
cycx_x25_set_chan_state(dev, WAN_DISCONNECTED);
return 0;
}
/* Open network interface.
* o prevent module from unloading by incrementing use count
* o if link is disconnected then initiate connection
*
* Return 0 if O.k. or errno. */
static int cycx_netdevice_open(struct net_device *dev)
{
if (netif_running(dev))
return -EBUSY; /* only one open is allowed */
netif_start_queue(dev);
return 0;
}
/* Close network interface.
* o reset flags.
* o if there's no more open channels then disconnect physical link. */
static int cycx_netdevice_stop(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
netif_stop_queue(dev);
if (chan->state == WAN_CONNECTED || chan->state == WAN_CONNECTING)
cycx_x25_chan_disconnect(dev);
return 0;
}
/* Build media header.
* o encapsulate packet according to encapsulation type.
*
* The trick here is to put packet type (Ethertype) into 'protocol' field of
* the socket buffer, so that we don't forget it. If encapsulation fails,
* set skb->protocol to 0 and discard packet later.
*
* Return: media header length. */
static int cycx_netdevice_hard_header(struct sk_buff *skb,
struct net_device *dev, u16 type,
const void *daddr, const void *saddr,
unsigned len)
{
skb->protocol = htons(type);
return dev->hard_header_len;
}
/* * Re-build media header.
* Return: 1 physical address resolved.
* 0 physical address not resolved */
static int cycx_netdevice_rebuild_header(struct sk_buff *skb)
{
return 1;
}
/* Send a packet on a network interface.
* o set busy flag (marks start of the transmission).
* o check link state. If link is not up, then drop the packet.
* o check channel status. If it's down then initiate a call.
* o pass a packet to corresponding WAN device.
* o free socket buffer
*
* Return: 0 complete (socket buffer must be freed)
* non-0 packet may be re-transmitted (tbusy must be set)
*
* Notes:
* 1. This routine is called either by the protocol stack or by the "net
* bottom half" (with interrupts enabled).
* 2. Setting tbusy flag will inhibit further transmit requests from the
* protocol stack and can be used for flow control with protocol layer. */
static netdev_tx_t cycx_netdevice_hard_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
struct cycx_device *card = chan->card;
if (!chan->svc)
chan->protocol = ntohs(skb->protocol);
if (card->wandev.state != WAN_CONNECTED)
++chan->ifstats.tx_dropped;
else if (chan->svc && chan->protocol &&
chan->protocol != ntohs(skb->protocol)) {
printk(KERN_INFO
"%s: unsupported Ethertype 0x%04X on interface %s!\n",
card->devname, ntohs(skb->protocol), dev->name);
++chan->ifstats.tx_errors;
} else if (chan->protocol == ETH_P_IP) {
switch (chan->state) {
case WAN_DISCONNECTED:
if (cycx_x25_chan_connect(dev)) {
netif_stop_queue(dev);
return NETDEV_TX_BUSY;
}
/* fall thru */
case WAN_CONNECTED:
reset_timer(dev);
dev->trans_start = jiffies;
netif_stop_queue(dev);
if (cycx_x25_chan_send(dev, skb))
return NETDEV_TX_BUSY;
break;
default:
++chan->ifstats.tx_dropped;
++card->wandev.stats.tx_dropped;
}
} else { /* chan->protocol == ETH_P_X25 */
switch (skb->data[0]) {
case X25_IFACE_DATA:
break;
case X25_IFACE_CONNECT:
cycx_x25_chan_connect(dev);
goto free_packet;
case X25_IFACE_DISCONNECT:
cycx_x25_chan_disconnect(dev);
goto free_packet;
default:
printk(KERN_INFO
"%s: unknown %d x25-iface request on %s!\n",
card->devname, skb->data[0], dev->name);
++chan->ifstats.tx_errors;
goto free_packet;
}
skb_pull(skb, 1); /* Remove control byte */
reset_timer(dev);
dev->trans_start = jiffies;
netif_stop_queue(dev);
if (cycx_x25_chan_send(dev, skb)) {
/* prepare for future retransmissions */
skb_push(skb, 1);
return NETDEV_TX_BUSY;
}
}
free_packet:
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* Get Ethernet-style interface statistics.
* Return a pointer to struct net_device_stats */
static struct net_device_stats *cycx_netdevice_get_stats(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
return chan ? &chan->ifstats : NULL;
}
/* Interrupt Handlers */
/* X.25 Interrupt Service Routine. */
static void cycx_x25_irq_handler(struct cycx_device *card)
{
struct cycx_x25_cmd cmd;
u16 z = 0;
card->in_isr = 1;
card->buff_int_mode_unbusy = 0;
cycx_peek(&card->hw, X25_RXMBOX_OFFS, &cmd, sizeof(cmd));
switch (cmd.command) {
case X25_DATA_INDICATION:
cycx_x25_irq_rx(card, &cmd);
break;
case X25_ACK_FROM_VC:
cycx_x25_irq_tx(card, &cmd);
break;
case X25_LOG:
cycx_x25_irq_log(card, &cmd);
break;
case X25_STATISTIC:
cycx_x25_irq_stat(card, &cmd);
break;
case X25_CONNECT_CONFIRM:
cycx_x25_irq_connect_confirm(card, &cmd);
break;
case X25_CONNECT_INDICATION:
cycx_x25_irq_connect(card, &cmd);
break;
case X25_DISCONNECT_INDICATION:
cycx_x25_irq_disconnect(card, &cmd);
break;
case X25_DISCONNECT_CONFIRM:
cycx_x25_irq_disconnect_confirm(card, &cmd);
break;
case X25_LINE_ON:
cycx_set_state(card, WAN_CONNECTED);
break;
case X25_LINE_OFF:
cycx_set_state(card, WAN_DISCONNECTED);
break;
default:
cycx_x25_irq_spurious(card, &cmd);
break;
}
cycx_poke(&card->hw, 0, &z, sizeof(z));
cycx_poke(&card->hw, X25_RXMBOX_OFFS, &z, sizeof(z));
card->in_isr = 0;
}
/* Transmit interrupt handler.
* o Release socket buffer
* o Clear 'tbusy' flag */
static void cycx_x25_irq_tx(struct cycx_device *card, struct cycx_x25_cmd *cmd)
{
struct net_device *dev;
struct wan_device *wandev = &card->wandev;
u8 lcn;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
/* unbusy device and then dev_tint(); */
dev = cycx_x25_get_dev_by_lcn(wandev, lcn);
if (dev) {
card->buff_int_mode_unbusy = 1;
netif_wake_queue(dev);
} else
printk(KERN_ERR "%s:ackvc for inexistent lcn %d\n",
card->devname, lcn);
}
/* Receive interrupt handler.
* This routine handles fragmented IP packets using M-bit according to the
* RFC1356.
* o map logical channel number to network interface.
* o allocate socket buffer or append received packet to the existing one.
* o if M-bit is reset (i.e. it's the last packet in a sequence) then
* decapsulate packet and pass socket buffer to the protocol stack.
*
* Notes:
* 1. When allocating a socket buffer, if M-bit is set then more data is
* coming and we have to allocate buffer for the maximum IP packet size
* expected on this channel.
* 2. If something goes wrong and X.25 packet has to be dropped (e.g. no
* socket buffers available) the whole packet sequence must be discarded. */
static void cycx_x25_irq_rx(struct cycx_device *card, struct cycx_x25_cmd *cmd)
{
struct wan_device *wandev = &card->wandev;
struct net_device *dev;
struct cycx_x25_channel *chan;
struct sk_buff *skb;
u8 bitm, lcn;
int pktlen = cmd->len - 5;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
cycx_peek(&card->hw, cmd->buf + 4, &bitm, sizeof(bitm));
bitm &= 0x10;
dev = cycx_x25_get_dev_by_lcn(wandev, lcn);
if (!dev) {
/* Invalid channel, discard packet */
printk(KERN_INFO "%s: receiving on orphaned LCN %d!\n",
card->devname, lcn);
return;
}
chan = netdev_priv(dev);
reset_timer(dev);
if (chan->drop_sequence) {
if (!bitm)
chan->drop_sequence = 0;
else
return;
}
if ((skb = chan->rx_skb) == NULL) {
/* Allocate new socket buffer */
int bufsize = bitm ? dev->mtu : pktlen;
if ((skb = dev_alloc_skb((chan->protocol == ETH_P_X25 ? 1 : 0) +
bufsize +
dev->hard_header_len)) == NULL) {
printk(KERN_INFO "%s: no socket buffers available!\n",
card->devname);
chan->drop_sequence = 1;
++chan->ifstats.rx_dropped;
return;
}
if (chan->protocol == ETH_P_X25) /* X.25 socket layer control */
/* 0 = data packet (dev_alloc_skb zeroed skb->data) */
skb_put(skb, 1);
skb->dev = dev;
skb->protocol = htons(chan->protocol);
chan->rx_skb = skb;
}
if (skb_tailroom(skb) < pktlen) {
/* No room for the packet. Call off the whole thing! */
dev_kfree_skb_irq(skb);
chan->rx_skb = NULL;
if (bitm)
chan->drop_sequence = 1;
printk(KERN_INFO "%s: unexpectedly long packet sequence "
"on interface %s!\n", card->devname, dev->name);
++chan->ifstats.rx_length_errors;
return;
}
/* Append packet to the socket buffer */
cycx_peek(&card->hw, cmd->buf + 5, skb_put(skb, pktlen), pktlen);
if (bitm)
return; /* more data is coming */
chan->rx_skb = NULL; /* dequeue packet */
++chan->ifstats.rx_packets;
chan->ifstats.rx_bytes += pktlen;
skb_reset_mac_header(skb);
netif_rx(skb);
}
/* Connect interrupt handler. */
static void cycx_x25_irq_connect(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
struct wan_device *wandev = &card->wandev;
struct net_device *dev = NULL;
struct cycx_x25_channel *chan;
u8 d[32],
loc[24],
rem[24];
u8 lcn, sizeloc, sizerem;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
cycx_peek(&card->hw, cmd->buf + 5, &sizeloc, sizeof(sizeloc));
cycx_peek(&card->hw, cmd->buf + 6, d, cmd->len - 6);
sizerem = sizeloc >> 4;
sizeloc &= 0x0F;
loc[0] = rem[0] = '\0';
if (sizeloc)
nibble_to_byte(d, loc, sizeloc, 0);
if (sizerem)
nibble_to_byte(d + (sizeloc >> 1), rem, sizerem, sizeloc & 1);
dprintk(1, KERN_INFO "%s:lcn=%d, local=%s, remote=%s\n",
__func__, lcn, loc, rem);
dev = cycx_x25_get_dev_by_dte_addr(wandev, rem);
if (!dev) {
/* Invalid channel, discard packet */
printk(KERN_INFO "%s: connect not expected: remote %s!\n",
card->devname, rem);
return;
}
chan = netdev_priv(dev);
chan->lcn = lcn;
cycx_x25_connect_response(card, chan);
cycx_x25_set_chan_state(dev, WAN_CONNECTED);
}
/* Connect confirm interrupt handler. */
static void cycx_x25_irq_connect_confirm(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
struct wan_device *wandev = &card->wandev;
struct net_device *dev;
struct cycx_x25_channel *chan;
u8 lcn, key;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
cycx_peek(&card->hw, cmd->buf + 1, &key, sizeof(key));
dprintk(1, KERN_INFO "%s: %s:lcn=%d, key=%d\n",
card->devname, __func__, lcn, key);
dev = cycx_x25_get_dev_by_lcn(wandev, -key);
if (!dev) {
/* Invalid channel, discard packet */
clear_bit(--key, (void*)&card->u.x.connection_keys);
printk(KERN_INFO "%s: connect confirm not expected: lcn %d, "
"key=%d!\n", card->devname, lcn, key);
return;
}
clear_bit(--key, (void*)&card->u.x.connection_keys);
chan = netdev_priv(dev);
chan->lcn = lcn;
cycx_x25_set_chan_state(dev, WAN_CONNECTED);
}
/* Disconnect confirm interrupt handler. */
static void cycx_x25_irq_disconnect_confirm(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
struct wan_device *wandev = &card->wandev;
struct net_device *dev;
u8 lcn;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
dprintk(1, KERN_INFO "%s: %s:lcn=%d\n",
card->devname, __func__, lcn);
dev = cycx_x25_get_dev_by_lcn(wandev, lcn);
if (!dev) {
/* Invalid channel, discard packet */
printk(KERN_INFO "%s:disconnect confirm not expected!:lcn %d\n",
card->devname, lcn);
return;
}
cycx_x25_set_chan_state(dev, WAN_DISCONNECTED);
}
/* disconnect interrupt handler. */
static void cycx_x25_irq_disconnect(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
struct wan_device *wandev = &card->wandev;
struct net_device *dev;
u8 lcn;
cycx_peek(&card->hw, cmd->buf, &lcn, sizeof(lcn));
dprintk(1, KERN_INFO "%s:lcn=%d\n", __func__, lcn);
dev = cycx_x25_get_dev_by_lcn(wandev, lcn);
if (dev) {
struct cycx_x25_channel *chan = netdev_priv(dev);
cycx_x25_disconnect_response(card, chan->link, lcn);
cycx_x25_set_chan_state(dev, WAN_DISCONNECTED);
} else
cycx_x25_disconnect_response(card, 0, lcn);
}
/* LOG interrupt handler. */
static void cycx_x25_irq_log(struct cycx_device *card, struct cycx_x25_cmd *cmd)
{
#if CYCLOMX_X25_DEBUG
char bf[20];
u16 size, toread, link, msg_code;
u8 code, routine;
cycx_peek(&card->hw, cmd->buf, &msg_code, sizeof(msg_code));
cycx_peek(&card->hw, cmd->buf + 2, &link, sizeof(link));
cycx_peek(&card->hw, cmd->buf + 4, &size, sizeof(size));
/* at most 20 bytes are available... thanks to Daniela :) */
toread = size < 20 ? size : 20;
cycx_peek(&card->hw, cmd->buf + 10, &bf, toread);
cycx_peek(&card->hw, cmd->buf + 10 + toread, &code, 1);
cycx_peek(&card->hw, cmd->buf + 10 + toread + 1, &routine, 1);
printk(KERN_INFO "cycx_x25_irq_handler: X25_LOG (0x4500) indic.:\n");
printk(KERN_INFO "cmd->buf=0x%X\n", cmd->buf);
printk(KERN_INFO "Log message code=0x%X\n", msg_code);
printk(KERN_INFO "Link=%d\n", link);
printk(KERN_INFO "log code=0x%X\n", code);
printk(KERN_INFO "log routine=0x%X\n", routine);
printk(KERN_INFO "Message size=%d\n", size);
hex_dump("Message", bf, toread);
#endif
}
/* STATISTIC interrupt handler. */
static void cycx_x25_irq_stat(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
cycx_peek(&card->hw, cmd->buf, &card->u.x.stats,
sizeof(card->u.x.stats));
hex_dump("cycx_x25_irq_stat", (unsigned char*)&card->u.x.stats,
sizeof(card->u.x.stats));
cycx_x25_dump_stats(&card->u.x.stats);
wake_up_interruptible(&card->wait_stats);
}
/* Spurious interrupt handler.
* o print a warning
* If number of spurious interrupts exceeded some limit, then ??? */
static void cycx_x25_irq_spurious(struct cycx_device *card,
struct cycx_x25_cmd *cmd)
{
printk(KERN_INFO "%s: spurious interrupt (0x%X)!\n",
card->devname, cmd->command);
}
#ifdef CYCLOMX_X25_DEBUG
static void hex_dump(char *msg, unsigned char *p, int len)
{
unsigned char hex[1024],
* phex = hex;
if (len >= (sizeof(hex) / 2))
len = (sizeof(hex) / 2) - 1;
while (len--) {
sprintf(phex, "%02x", *p++);
phex += 2;
}
printk(KERN_INFO "%s: %s\n", msg, hex);
}
#endif
/* Cyclom 2X Firmware-Specific Functions */
/* Exec X.25 command. */
static int x25_exec(struct cycx_device *card, int command, int link,
void *d1, int len1, void *d2, int len2)
{
struct cycx_x25_cmd c;
unsigned long flags;
u32 addr = 0x1200 + 0x2E0 * link + 0x1E2;
u8 retry = CYCX_X25_MAX_CMD_RETRY;
int err = 0;
c.command = command;
c.link = link;
c.len = len1 + len2;
spin_lock_irqsave(&card->u.x.lock, flags);
/* write command */
cycx_poke(&card->hw, X25_MBOX_OFFS, &c, sizeof(c) - sizeof(c.buf));
/* write X.25 data */
if (d1) {
cycx_poke(&card->hw, addr, d1, len1);
if (d2) {
if (len2 > 254) {
u32 addr1 = 0xA00 + 0x400 * link;
cycx_poke(&card->hw, addr + len1, d2, 249);
cycx_poke(&card->hw, addr1, ((u8*)d2) + 249,
len2 - 249);
} else
cycx_poke(&card->hw, addr + len1, d2, len2);
}
}
/* generate interruption, executing command */
cycx_intr(&card->hw);
/* wait till card->mbox == 0 */
do {
err = cycx_exec(card->mbox);
} while (retry-- && err);
spin_unlock_irqrestore(&card->u.x.lock, flags);
return err;
}
/* Configure adapter. */
static int cycx_x25_configure(struct cycx_device *card,
struct cycx_x25_config *conf)
{
struct {
u16 nlinks;
struct cycx_x25_config conf[2];
} x25_cmd_conf;
memset(&x25_cmd_conf, 0, sizeof(x25_cmd_conf));
x25_cmd_conf.nlinks = 2;
x25_cmd_conf.conf[0] = *conf;
/* FIXME: we need to find a way in the wanrouter framework
to configure the second link, for now lets use it
with the same config from the first link, fixing
the interface type to RS232, the speed in 38400 and
the clock to external */
x25_cmd_conf.conf[1] = *conf;
x25_cmd_conf.conf[1].link = 1;
x25_cmd_conf.conf[1].speed = 5; /* 38400 */
x25_cmd_conf.conf[1].clock = 8;
x25_cmd_conf.conf[1].flags = 0; /* default = RS232 */
cycx_x25_dump_config(&x25_cmd_conf.conf[0]);
cycx_x25_dump_config(&x25_cmd_conf.conf[1]);
return x25_exec(card, X25_CONFIG, 0,
&x25_cmd_conf, sizeof(x25_cmd_conf), NULL, 0);
}
/* Get protocol statistics. */
static int cycx_x25_get_stats(struct cycx_device *card)
{
/* the firmware expects 20 in the size field!!!
thanks to Daniela */
int err = x25_exec(card, X25_STATISTIC, 0, NULL, 20, NULL, 0);
if (err)
return err;
interruptible_sleep_on(&card->wait_stats);
if (signal_pending(current))
return -EINTR;
card->wandev.stats.rx_packets = card->u.x.stats.n2_rx_frames;
card->wandev.stats.rx_over_errors = card->u.x.stats.rx_over_errors;
card->wandev.stats.rx_crc_errors = card->u.x.stats.rx_crc_errors;
card->wandev.stats.rx_length_errors = 0; /* not available from fw */
card->wandev.stats.rx_frame_errors = 0; /* not available from fw */
card->wandev.stats.rx_missed_errors = card->u.x.stats.rx_aborts;
card->wandev.stats.rx_dropped = 0; /* not available from fw */
card->wandev.stats.rx_errors = 0; /* not available from fw */
card->wandev.stats.tx_packets = card->u.x.stats.n2_tx_frames;
card->wandev.stats.tx_aborted_errors = card->u.x.stats.tx_aborts;
card->wandev.stats.tx_dropped = 0; /* not available from fw */
card->wandev.stats.collisions = 0; /* not available from fw */
card->wandev.stats.tx_errors = 0; /* not available from fw */
cycx_x25_dump_devs(&card->wandev);
return 0;
}
/* return the number of nibbles */
static int byte_to_nibble(u8 *s, u8 *d, char *nibble)
{
int i = 0;
if (*nibble && *s) {
d[i] |= *s++ - '0';
*nibble = 0;
++i;
}
while (*s) {
d[i] = (*s - '0') << 4;
if (*(s + 1))
d[i] |= *(s + 1) - '0';
else {
*nibble = 1;
break;
}
++i;
s += 2;
}
return i;
}
static void nibble_to_byte(u8 *s, u8 *d, u8 len, u8 nibble)
{
if (nibble) {
*d++ = '0' + (*s++ & 0x0F);
--len;
}
while (len) {
*d++ = '0' + (*s >> 4);
if (--len) {
*d++ = '0' + (*s & 0x0F);
--len;
} else break;
++s;
}
*d = '\0';
}
/* Place X.25 call. */
static int x25_place_call(struct cycx_device *card,
struct cycx_x25_channel *chan)
{
int err = 0,
len;
char d[64],
nibble = 0,
mylen = chan->local_addr ? strlen(chan->local_addr) : 0,
remotelen = strlen(chan->addr);
u8 key;
if (card->u.x.connection_keys == ~0U) {
printk(KERN_INFO "%s: too many simultaneous connection "
"requests!\n", card->devname);
return -EAGAIN;
}
key = ffz(card->u.x.connection_keys);
set_bit(key, (void*)&card->u.x.connection_keys);
++key;
dprintk(1, KERN_INFO "%s:x25_place_call:key=%d\n", card->devname, key);
memset(d, 0, sizeof(d));
d[1] = key; /* user key */
d[2] = 0x10;
d[4] = 0x0B;
len = byte_to_nibble(chan->addr, d + 6, &nibble);
if (chan->local_addr)
len += byte_to_nibble(chan->local_addr, d + 6 + len, &nibble);
if (nibble)
++len;
d[5] = mylen << 4 | remotelen;
d[6 + len + 1] = 0xCC; /* TCP/IP over X.25, thanks to Daniela :) */
if ((err = x25_exec(card, X25_CONNECT_REQUEST, chan->link,
&d, 7 + len + 1, NULL, 0)) != 0)
clear_bit(--key, (void*)&card->u.x.connection_keys);
else
chan->lcn = -key;
return err;
}
/* Place X.25 CONNECT RESPONSE. */
static int cycx_x25_connect_response(struct cycx_device *card,
struct cycx_x25_channel *chan)
{
u8 d[8];
memset(d, 0, sizeof(d));
d[0] = d[3] = chan->lcn;
d[2] = 0x10;
d[4] = 0x0F;
d[7] = 0xCC; /* TCP/IP over X.25, thanks Daniela */
return x25_exec(card, X25_CONNECT_RESPONSE, chan->link, &d, 8, NULL, 0);
}
/* Place X.25 DISCONNECT RESPONSE. */
static int cycx_x25_disconnect_response(struct cycx_device *card, u8 link,
u8 lcn)
{
char d[5];
memset(d, 0, sizeof(d));
d[0] = d[3] = lcn;
d[2] = 0x10;
d[4] = 0x17;
return x25_exec(card, X25_DISCONNECT_RESPONSE, link, &d, 5, NULL, 0);
}
/* Clear X.25 call. */
static int x25_clear_call(struct cycx_device *card, u8 link, u8 lcn, u8 cause,
u8 diagn)
{
u8 d[7];
memset(d, 0, sizeof(d));
d[0] = d[3] = lcn;
d[2] = 0x10;
d[4] = 0x13;
d[5] = cause;
d[6] = diagn;
return x25_exec(card, X25_DISCONNECT_REQUEST, link, d, 7, NULL, 0);
}
/* Send X.25 data packet. */
static int cycx_x25_send(struct cycx_device *card, u8 link, u8 lcn, u8 bitm,
int len, void *buf)
{
u8 d[] = "?\xFF\x10??";
d[0] = d[3] = lcn;
d[4] = bitm;
return x25_exec(card, X25_DATA_REQUEST, link, &d, 5, buf, len);
}
/* Miscellaneous */
/* Find network device by its channel number. */
static struct net_device *cycx_x25_get_dev_by_lcn(struct wan_device *wandev,
s16 lcn)
{
struct net_device *dev = wandev->dev;
struct cycx_x25_channel *chan;
while (dev) {
chan = netdev_priv(dev);
if (chan->lcn == lcn)
break;
dev = chan->slave;
}
return dev;
}
/* Find network device by its remote dte address. */
static struct net_device *
cycx_x25_get_dev_by_dte_addr(struct wan_device *wandev, char *dte)
{
struct net_device *dev = wandev->dev;
struct cycx_x25_channel *chan;
while (dev) {
chan = netdev_priv(dev);
if (!strcmp(chan->addr, dte))
break;
dev = chan->slave;
}
return dev;
}
/* Initiate connection on the logical channel.
* o for PVC we just get channel configuration
* o for SVCs place an X.25 call
*
* Return: 0 connected
* >0 connection in progress
* <0 failure */
static int cycx_x25_chan_connect(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
struct cycx_device *card = chan->card;
if (chan->svc) {
if (!chan->addr[0])
return -EINVAL; /* no destination address */
dprintk(1, KERN_INFO "%s: placing X.25 call to %s...\n",
card->devname, chan->addr);
if (x25_place_call(card, chan))
return -EIO;
cycx_x25_set_chan_state(dev, WAN_CONNECTING);
return 1;
} else
cycx_x25_set_chan_state(dev, WAN_CONNECTED);
return 0;
}
/* Disconnect logical channel.
* o if SVC then clear X.25 call */
static void cycx_x25_chan_disconnect(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
if (chan->svc) {
x25_clear_call(chan->card, chan->link, chan->lcn, 0, 0);
cycx_x25_set_chan_state(dev, WAN_DISCONNECTING);
} else
cycx_x25_set_chan_state(dev, WAN_DISCONNECTED);
}
/* Called by kernel timer */
static void cycx_x25_chan_timer(unsigned long d)
{
struct net_device *dev = (struct net_device *)d;
struct cycx_x25_channel *chan = netdev_priv(dev);
if (chan->state == WAN_CONNECTED)
cycx_x25_chan_disconnect(dev);
else
printk(KERN_ERR "%s: %s for svc (%s) not connected!\n",
chan->card->devname, __func__, dev->name);
}
/* Set logical channel state. */
static void cycx_x25_set_chan_state(struct net_device *dev, u8 state)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
struct cycx_device *card = chan->card;
unsigned long flags;
char *string_state = NULL;
spin_lock_irqsave(&card->lock, flags);
if (chan->state != state) {
if (chan->svc && chan->state == WAN_CONNECTED)
del_timer(&chan->timer);
switch (state) {
case WAN_CONNECTED:
string_state = "connected!";
*(__be16*)dev->dev_addr = htons(chan->lcn);
netif_wake_queue(dev);
reset_timer(dev);
if (chan->protocol == ETH_P_X25)
cycx_x25_chan_send_event(dev,
X25_IFACE_CONNECT);
break;
case WAN_CONNECTING:
string_state = "connecting...";
break;
case WAN_DISCONNECTING:
string_state = "disconnecting...";
break;
case WAN_DISCONNECTED:
string_state = "disconnected!";
if (chan->svc) {
*(unsigned short*)dev->dev_addr = 0;
chan->lcn = 0;
}
if (chan->protocol == ETH_P_X25)
cycx_x25_chan_send_event(dev,
X25_IFACE_DISCONNECT);
netif_wake_queue(dev);
break;
}
printk(KERN_INFO "%s: interface %s %s\n", card->devname,
dev->name, string_state);
chan->state = state;
}
spin_unlock_irqrestore(&card->lock, flags);
}
/* Send packet on a logical channel.
* When this function is called, tx_skb field of the channel data space
* points to the transmit socket buffer. When transmission is complete,
* release socket buffer and reset 'tbusy' flag.
*
* Return: 0 - transmission complete
* 1 - busy
*
* Notes:
* 1. If packet length is greater than MTU for this channel, we'll fragment
* the packet into 'complete sequence' using M-bit.
* 2. When transmission is complete, an event notification should be issued
* to the router. */
static int cycx_x25_chan_send(struct net_device *dev, struct sk_buff *skb)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
struct cycx_device *card = chan->card;
int bitm = 0; /* final packet */
unsigned len = skb->len;
if (skb->len > card->wandev.mtu) {
len = card->wandev.mtu;
bitm = 0x10; /* set M-bit (more data) */
}
if (cycx_x25_send(card, chan->link, chan->lcn, bitm, len, skb->data))
return 1;
if (bitm) {
skb_pull(skb, len);
return 1;
}
++chan->ifstats.tx_packets;
chan->ifstats.tx_bytes += len;
return 0;
}
/* Send event (connection, disconnection, etc) to X.25 socket layer */
static void cycx_x25_chan_send_event(struct net_device *dev, u8 event)
{
struct sk_buff *skb;
unsigned char *ptr;
if ((skb = dev_alloc_skb(1)) == NULL) {
printk(KERN_ERR "%s: out of memory\n", __func__);
return;
}
ptr = skb_put(skb, 1);
*ptr = event;
skb->protocol = x25_type_trans(skb, dev);
netif_rx(skb);
}
/* Convert line speed in bps to a number used by cyclom 2x code. */
static u8 bps_to_speed_code(u32 bps)
{
u8 number = 0; /* defaults to the lowest (1200) speed ;> */
if (bps >= 512000) number = 8;
else if (bps >= 256000) number = 7;
else if (bps >= 64000) number = 6;
else if (bps >= 38400) number = 5;
else if (bps >= 19200) number = 4;
else if (bps >= 9600) number = 3;
else if (bps >= 4800) number = 2;
else if (bps >= 2400) number = 1;
return number;
}
/* log base 2 */
static u8 cycx_log2(u32 n)
{
u8 log = 0;
if (!n)
return 0;
while (n > 1) {
n >>= 1;
++log;
}
return log;
}
/* Convert decimal string to unsigned integer.
* If len != 0 then only 'len' characters of the string are converted. */
static unsigned dec_to_uint(u8 *str, int len)
{
unsigned val = 0;
if (!len)
len = strlen(str);
for (; len && isdigit(*str); ++str, --len)
val = (val * 10) + (*str - (unsigned) '0');
return val;
}
static void reset_timer(struct net_device *dev)
{
struct cycx_x25_channel *chan = netdev_priv(dev);
if (chan->svc)
mod_timer(&chan->timer, jiffies+chan->idle_tmout*HZ);
}
#ifdef CYCLOMX_X25_DEBUG
static void cycx_x25_dump_config(struct cycx_x25_config *conf)
{
printk(KERN_INFO "X.25 configuration\n");
printk(KERN_INFO "-----------------\n");
printk(KERN_INFO "link number=%d\n", conf->link);
printk(KERN_INFO "line speed=%d\n", conf->speed);
printk(KERN_INFO "clock=%sternal\n", conf->clock == 8 ? "Ex" : "In");
printk(KERN_INFO "# level 2 retransm.=%d\n", conf->n2);
printk(KERN_INFO "level 2 window=%d\n", conf->n2win);
printk(KERN_INFO "level 3 window=%d\n", conf->n3win);
printk(KERN_INFO "# logical channels=%d\n", conf->nvc);
printk(KERN_INFO "level 3 pkt len=%d\n", conf->pktlen);
printk(KERN_INFO "my address=%d\n", conf->locaddr);
printk(KERN_INFO "remote address=%d\n", conf->remaddr);
printk(KERN_INFO "t1=%d seconds\n", conf->t1);
printk(KERN_INFO "t2=%d seconds\n", conf->t2);
printk(KERN_INFO "t21=%d seconds\n", conf->t21);
printk(KERN_INFO "# PVCs=%d\n", conf->npvc);
printk(KERN_INFO "t23=%d seconds\n", conf->t23);
printk(KERN_INFO "flags=0x%x\n", conf->flags);
}
static void cycx_x25_dump_stats(struct cycx_x25_stats *stats)
{
printk(KERN_INFO "X.25 statistics\n");
printk(KERN_INFO "--------------\n");
printk(KERN_INFO "rx_crc_errors=%d\n", stats->rx_crc_errors);
printk(KERN_INFO "rx_over_errors=%d\n", stats->rx_over_errors);
printk(KERN_INFO "n2_tx_frames=%d\n", stats->n2_tx_frames);
printk(KERN_INFO "n2_rx_frames=%d\n", stats->n2_rx_frames);
printk(KERN_INFO "tx_timeouts=%d\n", stats->tx_timeouts);
printk(KERN_INFO "rx_timeouts=%d\n", stats->rx_timeouts);
printk(KERN_INFO "n3_tx_packets=%d\n", stats->n3_tx_packets);
printk(KERN_INFO "n3_rx_packets=%d\n", stats->n3_rx_packets);
printk(KERN_INFO "tx_aborts=%d\n", stats->tx_aborts);
printk(KERN_INFO "rx_aborts=%d\n", stats->rx_aborts);
}
static void cycx_x25_dump_devs(struct wan_device *wandev)
{
struct net_device *dev = wandev->dev;
printk(KERN_INFO "X.25 dev states\n");
printk(KERN_INFO "name: addr: txoff: protocol:\n");
printk(KERN_INFO "---------------------------------------\n");
while(dev) {
struct cycx_x25_channel *chan = netdev_priv(dev);
printk(KERN_INFO "%-5.5s %-15.15s %d ETH_P_%s\n",
chan->name, chan->addr, netif_queue_stopped(dev),
chan->protocol == ETH_P_IP ? "IP" : "X25");
dev = chan->slave;
}
}
#endif /* CYCLOMX_X25_DEBUG */
/* End */
| gpl-2.0 |
up2wing/fox-kernel-comment | linux-3.10.89/drivers/isdn/mISDN/tei.c | 4565 | 34376 | /*
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "layer2.h"
#include <linux/random.h>
#include <linux/slab.h>
#include "core.h"
#define ID_REQUEST 1
#define ID_ASSIGNED 2
#define ID_DENIED 3
#define ID_CHK_REQ 4
#define ID_CHK_RES 5
#define ID_REMOVE 6
#define ID_VERIFY 7
#define TEI_ENTITY_ID 0xf
#define MGR_PH_ACTIVE 16
#define MGR_PH_NOTREADY 17
#define DATIMER_VAL 10000
static u_int *debug;
static struct Fsm deactfsm = {NULL, 0, 0, NULL, NULL};
static struct Fsm teifsmu = {NULL, 0, 0, NULL, NULL};
static struct Fsm teifsmn = {NULL, 0, 0, NULL, NULL};
enum {
ST_L1_DEACT,
ST_L1_DEACT_PENDING,
ST_L1_ACTIV,
};
#define DEACT_STATE_COUNT (ST_L1_ACTIV + 1)
static char *strDeactState[] =
{
"ST_L1_DEACT",
"ST_L1_DEACT_PENDING",
"ST_L1_ACTIV",
};
enum {
EV_ACTIVATE,
EV_ACTIVATE_IND,
EV_DEACTIVATE,
EV_DEACTIVATE_IND,
EV_UI,
EV_DATIMER,
};
#define DEACT_EVENT_COUNT (EV_DATIMER + 1)
static char *strDeactEvent[] =
{
"EV_ACTIVATE",
"EV_ACTIVATE_IND",
"EV_DEACTIVATE",
"EV_DEACTIVATE_IND",
"EV_UI",
"EV_DATIMER",
};
static void
da_debug(struct FsmInst *fi, char *fmt, ...)
{
struct manager *mgr = fi->userdata;
struct va_format vaf;
va_list va;
if (!(*debug & DEBUG_L2_TEIFSM))
return;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "mgr(%d): %pV\n", mgr->ch.st->dev->id, &vaf);
va_end(va);
}
static void
da_activate(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
if (fi->state == ST_L1_DEACT_PENDING)
mISDN_FsmDelTimer(&mgr->datimer, 1);
mISDN_FsmChangeState(fi, ST_L1_ACTIV);
}
static void
da_deactivate_ind(struct FsmInst *fi, int event, void *arg)
{
mISDN_FsmChangeState(fi, ST_L1_DEACT);
}
static void
da_deactivate(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
struct layer2 *l2;
u_long flags;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->l2m.state > ST_L2_4) {
/* have still activ TEI */
read_unlock_irqrestore(&mgr->lock, flags);
return;
}
}
read_unlock_irqrestore(&mgr->lock, flags);
/* All TEI are inactiv */
if (!test_bit(OPTION_L1_HOLD, &mgr->options)) {
mISDN_FsmAddTimer(&mgr->datimer, DATIMER_VAL, EV_DATIMER,
NULL, 1);
mISDN_FsmChangeState(fi, ST_L1_DEACT_PENDING);
}
}
static void
da_ui(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
/* restart da timer */
if (!test_bit(OPTION_L1_HOLD, &mgr->options)) {
mISDN_FsmDelTimer(&mgr->datimer, 2);
mISDN_FsmAddTimer(&mgr->datimer, DATIMER_VAL, EV_DATIMER,
NULL, 2);
}
}
static void
da_timer(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
struct layer2 *l2;
u_long flags;
/* check again */
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->l2m.state > ST_L2_4) {
/* have still activ TEI */
read_unlock_irqrestore(&mgr->lock, flags);
mISDN_FsmChangeState(fi, ST_L1_ACTIV);
return;
}
}
read_unlock_irqrestore(&mgr->lock, flags);
/* All TEI are inactiv */
mISDN_FsmChangeState(fi, ST_L1_DEACT);
_queue_data(&mgr->ch, PH_DEACTIVATE_REQ, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
}
static struct FsmNode DeactFnList[] =
{
{ST_L1_DEACT, EV_ACTIVATE_IND, da_activate},
{ST_L1_ACTIV, EV_DEACTIVATE_IND, da_deactivate_ind},
{ST_L1_ACTIV, EV_DEACTIVATE, da_deactivate},
{ST_L1_DEACT_PENDING, EV_ACTIVATE, da_activate},
{ST_L1_DEACT_PENDING, EV_UI, da_ui},
{ST_L1_DEACT_PENDING, EV_DATIMER, da_timer},
};
enum {
ST_TEI_NOP,
ST_TEI_IDREQ,
ST_TEI_IDVERIFY,
};
#define TEI_STATE_COUNT (ST_TEI_IDVERIFY + 1)
static char *strTeiState[] =
{
"ST_TEI_NOP",
"ST_TEI_IDREQ",
"ST_TEI_IDVERIFY",
};
enum {
EV_IDREQ,
EV_ASSIGN,
EV_ASSIGN_REQ,
EV_DENIED,
EV_CHKREQ,
EV_CHKRESP,
EV_REMOVE,
EV_VERIFY,
EV_TIMER,
};
#define TEI_EVENT_COUNT (EV_TIMER + 1)
static char *strTeiEvent[] =
{
"EV_IDREQ",
"EV_ASSIGN",
"EV_ASSIGN_REQ",
"EV_DENIED",
"EV_CHKREQ",
"EV_CHKRESP",
"EV_REMOVE",
"EV_VERIFY",
"EV_TIMER",
};
static void
tei_debug(struct FsmInst *fi, char *fmt, ...)
{
struct teimgr *tm = fi->userdata;
struct va_format vaf;
va_list va;
if (!(*debug & DEBUG_L2_TEIFSM))
return;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "sapi(%d) tei(%d): %pV\n",
tm->l2->sapi, tm->l2->tei, &vaf);
va_end(va);
}
static int
get_free_id(struct manager *mgr)
{
DECLARE_BITMAP(ids, 64) = { [0 ... BITS_TO_LONGS(64) - 1] = 0 };
int i;
struct layer2 *l2;
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->ch.nr > 63) {
printk(KERN_WARNING
"%s: more as 63 layer2 for one device\n",
__func__);
return -EBUSY;
}
__set_bit(l2->ch.nr, ids);
}
i = find_next_zero_bit(ids, 64, 1);
if (i < 64)
return i;
printk(KERN_WARNING "%s: more as 63 layer2 for one device\n",
__func__);
return -EBUSY;
}
static int
get_free_tei(struct manager *mgr)
{
DECLARE_BITMAP(ids, 64) = { [0 ... BITS_TO_LONGS(64) - 1] = 0 };
int i;
struct layer2 *l2;
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->ch.nr == 0)
continue;
if ((l2->ch.addr & 0xff) != 0)
continue;
i = l2->ch.addr >> 8;
if (i < 64)
continue;
i -= 64;
__set_bit(i, ids);
}
i = find_first_zero_bit(ids, 64);
if (i < 64)
return i + 64;
printk(KERN_WARNING "%s: more as 63 dynamic tei for one device\n",
__func__);
return -1;
}
static void
teiup_create(struct manager *mgr, u_int prim, int len, void *arg)
{
struct sk_buff *skb;
struct mISDNhead *hh;
int err;
skb = mI_alloc_skb(len, GFP_ATOMIC);
if (!skb)
return;
hh = mISDN_HEAD_P(skb);
hh->prim = prim;
hh->id = (mgr->ch.nr << 16) | mgr->ch.addr;
if (len)
memcpy(skb_put(skb, len), arg, len);
err = mgr->up->send(mgr->up, skb);
if (err) {
printk(KERN_WARNING "%s: err=%d\n", __func__, err);
dev_kfree_skb(skb);
}
}
static u_int
new_id(struct manager *mgr)
{
u_int id;
id = mgr->nextid++;
if (id == 0x7fff)
mgr->nextid = 1;
id <<= 16;
id |= GROUP_TEI << 8;
id |= TEI_SAPI;
return id;
}
static void
do_send(struct manager *mgr)
{
if (!test_bit(MGR_PH_ACTIVE, &mgr->options))
return;
if (!test_and_set_bit(MGR_PH_NOTREADY, &mgr->options)) {
struct sk_buff *skb = skb_dequeue(&mgr->sendq);
if (!skb) {
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
return;
}
mgr->lastid = mISDN_HEAD_ID(skb);
mISDN_FsmEvent(&mgr->deact, EV_UI, NULL);
if (mgr->ch.recv(mgr->ch.peer, skb)) {
dev_kfree_skb(skb);
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
mgr->lastid = MISDN_ID_NONE;
}
}
}
static void
do_ack(struct manager *mgr, u_int id)
{
if (test_bit(MGR_PH_NOTREADY, &mgr->options)) {
if (id == mgr->lastid) {
if (test_bit(MGR_PH_ACTIVE, &mgr->options)) {
struct sk_buff *skb;
skb = skb_dequeue(&mgr->sendq);
if (skb) {
mgr->lastid = mISDN_HEAD_ID(skb);
if (!mgr->ch.recv(mgr->ch.peer, skb))
return;
dev_kfree_skb(skb);
}
}
mgr->lastid = MISDN_ID_NONE;
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
}
}
}
static void
mgr_send_down(struct manager *mgr, struct sk_buff *skb)
{
skb_queue_tail(&mgr->sendq, skb);
if (!test_bit(MGR_PH_ACTIVE, &mgr->options)) {
_queue_data(&mgr->ch, PH_ACTIVATE_REQ, MISDN_ID_ANY, 0,
NULL, GFP_KERNEL);
} else {
do_send(mgr);
}
}
static int
dl_unit_data(struct manager *mgr, struct sk_buff *skb)
{
if (!test_bit(MGR_OPT_NETWORK, &mgr->options)) /* only net send UI */
return -EINVAL;
if (!test_bit(MGR_PH_ACTIVE, &mgr->options))
_queue_data(&mgr->ch, PH_ACTIVATE_REQ, MISDN_ID_ANY, 0,
NULL, GFP_KERNEL);
skb_push(skb, 3);
skb->data[0] = 0x02; /* SAPI 0 C/R = 1 */
skb->data[1] = 0xff; /* TEI 127 */
skb->data[2] = UI; /* UI frame */
mISDN_HEAD_PRIM(skb) = PH_DATA_REQ;
mISDN_HEAD_ID(skb) = new_id(mgr);
skb_queue_tail(&mgr->sendq, skb);
do_send(mgr);
return 0;
}
static unsigned int
random_ri(void)
{
u16 x;
get_random_bytes(&x, sizeof(x));
return x;
}
static struct layer2 *
findtei(struct manager *mgr, int tei)
{
struct layer2 *l2;
u_long flags;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if ((l2->sapi == 0) && (l2->tei > 0) &&
(l2->tei != GROUP_TEI) && (l2->tei == tei))
goto done;
}
l2 = NULL;
done:
read_unlock_irqrestore(&mgr->lock, flags);
return l2;
}
static void
put_tei_msg(struct manager *mgr, u_char m_id, unsigned int ri, int tei)
{
struct sk_buff *skb;
u_char bp[8];
bp[0] = (TEI_SAPI << 2);
if (test_bit(MGR_OPT_NETWORK, &mgr->options))
bp[0] |= 2; /* CR:=1 for net command */
bp[1] = (GROUP_TEI << 1) | 0x1;
bp[2] = UI;
bp[3] = TEI_ENTITY_ID;
bp[4] = ri >> 8;
bp[5] = ri & 0xff;
bp[6] = m_id;
bp[7] = ((tei << 1) & 0xff) | 1;
skb = _alloc_mISDN_skb(PH_DATA_REQ, new_id(mgr), 8, bp, GFP_ATOMIC);
if (!skb) {
printk(KERN_WARNING "%s: no skb for tei msg\n", __func__);
return;
}
mgr_send_down(mgr, skb);
}
static void
tei_id_request(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (tm->l2->tei != GROUP_TEI) {
tm->tei_m.printdebug(&tm->tei_m,
"assign request for already assigned tei %d",
tm->l2->tei);
return;
}
tm->ri = random_ri();
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m,
"assign request ri %d", tm->ri);
put_tei_msg(tm->mgr, ID_REQUEST, tm->ri, GROUP_TEI);
mISDN_FsmChangeState(fi, ST_TEI_IDREQ);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 1);
tm->nval = 3;
}
static void
tei_id_assign(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
struct layer2 *l2;
u_char *dp = arg;
int ri, tei;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity assign ri %d tei %d",
ri, tei);
l2 = findtei(tm->mgr, tei);
if (l2) { /* same tei is in use */
if (ri != l2->tm->ri) {
tm->tei_m.printdebug(fi,
"possible duplicate assignment tei %d", tei);
tei_l2(l2, MDL_ERROR_RSP, 0);
}
} else if (ri == tm->ri) {
mISDN_FsmDelTimer(&tm->timer, 1);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
tei_l2(tm->l2, MDL_ASSIGN_REQ, tei);
}
}
static void
tei_id_test_dup(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
struct layer2 *l2;
u_char *dp = arg;
int tei, ri;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "foreign identity assign ri %d tei %d",
ri, tei);
l2 = findtei(tm->mgr, tei);
if (l2) { /* same tei is in use */
if (ri != l2->tm->ri) { /* and it wasn't our request */
tm->tei_m.printdebug(fi,
"possible duplicate assignment tei %d", tei);
mISDN_FsmEvent(&l2->tm->tei_m, EV_VERIFY, NULL);
}
}
}
static void
tei_id_denied(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int ri, tei;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity denied ri %d tei %d",
ri, tei);
}
static void
tei_id_chk_req(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = *(dp + 3) >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity check req tei %d", tei);
if ((tm->l2->tei != GROUP_TEI) && ((tei == GROUP_TEI) ||
(tei == tm->l2->tei))) {
mISDN_FsmDelTimer(&tm->timer, 4);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_NOP);
put_tei_msg(tm->mgr, ID_CHK_RES, random_ri(), tm->l2->tei);
}
}
static void
tei_id_remove(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = *(dp + 3) >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity remove tei %d", tei);
if ((tm->l2->tei != GROUP_TEI) &&
((tei == GROUP_TEI) || (tei == tm->l2->tei))) {
mISDN_FsmDelTimer(&tm->timer, 5);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_NOP);
tei_l2(tm->l2, MDL_REMOVE_REQ, 0);
}
}
static void
tei_id_verify(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "id verify request for tei %d",
tm->l2->tei);
put_tei_msg(tm->mgr, ID_VERIFY, 0, tm->l2->tei);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_IDVERIFY);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 2);
tm->nval = 2;
}
static void
tei_id_req_tout(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (--tm->nval) {
tm->ri = random_ri();
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "assign req(%d) ri %d",
4 - tm->nval, tm->ri);
put_tei_msg(tm->mgr, ID_REQUEST, tm->ri, GROUP_TEI);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 3);
} else {
tm->tei_m.printdebug(fi, "assign req failed");
tei_l2(tm->l2, MDL_ERROR_RSP, 0);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
}
static void
tei_id_ver_tout(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (--tm->nval) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"id verify req(%d) for tei %d",
3 - tm->nval, tm->l2->tei);
put_tei_msg(tm->mgr, ID_VERIFY, 0, tm->l2->tei);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 4);
} else {
tm->tei_m.printdebug(fi, "verify req for tei %d failed",
tm->l2->tei);
tei_l2(tm->l2, MDL_REMOVE_REQ, 0);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
}
static struct FsmNode TeiFnListUser[] =
{
{ST_TEI_NOP, EV_IDREQ, tei_id_request},
{ST_TEI_NOP, EV_ASSIGN, tei_id_test_dup},
{ST_TEI_NOP, EV_VERIFY, tei_id_verify},
{ST_TEI_NOP, EV_REMOVE, tei_id_remove},
{ST_TEI_NOP, EV_CHKREQ, tei_id_chk_req},
{ST_TEI_IDREQ, EV_TIMER, tei_id_req_tout},
{ST_TEI_IDREQ, EV_ASSIGN, tei_id_assign},
{ST_TEI_IDREQ, EV_DENIED, tei_id_denied},
{ST_TEI_IDVERIFY, EV_TIMER, tei_id_ver_tout},
{ST_TEI_IDVERIFY, EV_REMOVE, tei_id_remove},
{ST_TEI_IDVERIFY, EV_CHKREQ, tei_id_chk_req},
};
static void
tei_l2remove(struct layer2 *l2)
{
put_tei_msg(l2->tm->mgr, ID_REMOVE, 0, l2->tei);
tei_l2(l2, MDL_REMOVE_REQ, 0);
list_del(&l2->ch.list);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
static void
tei_assign_req(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
if (tm->l2->tei == GROUP_TEI) {
tm->tei_m.printdebug(&tm->tei_m,
"net tei assign request without tei");
return;
}
tm->ri = ((unsigned int) *dp++ << 8);
tm->ri += *dp++;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m,
"net assign request ri %d teim %d", tm->ri, *dp);
put_tei_msg(tm->mgr, ID_ASSIGNED, tm->ri, tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
static void
tei_id_chk_req_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "id check request for tei %d",
tm->l2->tei);
tm->rcnt = 0;
put_tei_msg(tm->mgr, ID_CHK_REQ, 0, tm->l2->tei);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_IDVERIFY);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 2);
tm->nval = 2;
}
static void
tei_id_chk_resp(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = dp[3] >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity check resp tei %d", tei);
if (tei == tm->l2->tei)
tm->rcnt++;
}
static void
tei_id_verify_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = dp[3] >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity verify req tei %d/%d",
tei, tm->l2->tei);
if (tei == tm->l2->tei)
tei_id_chk_req_net(fi, event, arg);
}
static void
tei_id_ver_tout_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (tm->rcnt == 1) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"check req for tei %d successful\n", tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
} else if (tm->rcnt > 1) {
/* duplicate assignment; remove */
tei_l2remove(tm->l2);
} else if (--tm->nval) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"id check req(%d) for tei %d",
3 - tm->nval, tm->l2->tei);
put_tei_msg(tm->mgr, ID_CHK_REQ, 0, tm->l2->tei);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 4);
} else {
tm->tei_m.printdebug(fi, "check req for tei %d failed",
tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
tei_l2remove(tm->l2);
}
}
static struct FsmNode TeiFnListNet[] =
{
{ST_TEI_NOP, EV_ASSIGN_REQ, tei_assign_req},
{ST_TEI_NOP, EV_VERIFY, tei_id_verify_net},
{ST_TEI_NOP, EV_CHKREQ, tei_id_chk_req_net},
{ST_TEI_IDVERIFY, EV_TIMER, tei_id_ver_tout_net},
{ST_TEI_IDVERIFY, EV_CHKRESP, tei_id_chk_resp},
};
static void
tei_ph_data_ind(struct teimgr *tm, u_int mt, u_char *dp, int len)
{
if (test_bit(FLG_FIXED_TEI, &tm->l2->flag))
return;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m, "tei handler mt %x", mt);
if (mt == ID_ASSIGNED)
mISDN_FsmEvent(&tm->tei_m, EV_ASSIGN, dp);
else if (mt == ID_DENIED)
mISDN_FsmEvent(&tm->tei_m, EV_DENIED, dp);
else if (mt == ID_CHK_REQ)
mISDN_FsmEvent(&tm->tei_m, EV_CHKREQ, dp);
else if (mt == ID_REMOVE)
mISDN_FsmEvent(&tm->tei_m, EV_REMOVE, dp);
else if (mt == ID_VERIFY)
mISDN_FsmEvent(&tm->tei_m, EV_VERIFY, dp);
else if (mt == ID_CHK_RES)
mISDN_FsmEvent(&tm->tei_m, EV_CHKRESP, dp);
}
static struct layer2 *
create_new_tei(struct manager *mgr, int tei, int sapi)
{
unsigned long opt = 0;
unsigned long flags;
int id;
struct layer2 *l2;
struct channel_req rq;
if (!mgr->up)
return NULL;
if ((tei >= 0) && (tei < 64))
test_and_set_bit(OPTION_L2_FIXEDTEI, &opt);
if (mgr->ch.st->dev->Dprotocols & ((1 << ISDN_P_TE_E1) |
(1 << ISDN_P_NT_E1))) {
test_and_set_bit(OPTION_L2_PMX, &opt);
rq.protocol = ISDN_P_NT_E1;
} else {
rq.protocol = ISDN_P_NT_S0;
}
l2 = create_l2(mgr->up, ISDN_P_LAPD_NT, opt, tei, sapi);
if (!l2) {
printk(KERN_WARNING "%s:no memory for layer2\n", __func__);
return NULL;
}
l2->tm = kzalloc(sizeof(struct teimgr), GFP_KERNEL);
if (!l2->tm) {
kfree(l2);
printk(KERN_WARNING "%s:no memory for teimgr\n", __func__);
return NULL;
}
l2->tm->mgr = mgr;
l2->tm->l2 = l2;
l2->tm->tei_m.debug = *debug & DEBUG_L2_TEIFSM;
l2->tm->tei_m.userdata = l2->tm;
l2->tm->tei_m.printdebug = tei_debug;
l2->tm->tei_m.fsm = &teifsmn;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 2000; /* T202 2 sec */
mISDN_FsmInitTimer(&l2->tm->tei_m, &l2->tm->timer);
write_lock_irqsave(&mgr->lock, flags);
id = get_free_id(mgr);
list_add_tail(&l2->list, &mgr->layer2);
write_unlock_irqrestore(&mgr->lock, flags);
if (id < 0) {
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
printk(KERN_WARNING "%s:no free id\n", __func__);
return NULL;
} else {
l2->ch.nr = id;
__add_layer2(&l2->ch, mgr->ch.st);
l2->ch.recv = mgr->ch.recv;
l2->ch.peer = mgr->ch.peer;
l2->ch.ctrl(&l2->ch, OPEN_CHANNEL, NULL);
/* We need open here L1 for the manager as well (refcounting) */
rq.adr.dev = mgr->ch.st->dev->id;
id = mgr->ch.st->own.ctrl(&mgr->ch.st->own, OPEN_CHANNEL, &rq);
if (id < 0) {
printk(KERN_WARNING "%s: cannot open L1\n", __func__);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
l2 = NULL;
}
}
return l2;
}
static void
new_tei_req(struct manager *mgr, u_char *dp)
{
int tei, ri;
struct layer2 *l2;
ri = dp[0] << 8;
ri += dp[1];
if (!mgr->up)
goto denied;
if (!(dp[3] & 1)) /* Extension bit != 1 */
goto denied;
if (dp[3] != 0xff)
tei = dp[3] >> 1; /* 3GPP TS 08.56 6.1.11.2 */
else
tei = get_free_tei(mgr);
if (tei < 0) {
printk(KERN_WARNING "%s:No free tei\n", __func__);
goto denied;
}
l2 = create_new_tei(mgr, tei, CTRL_SAPI);
if (!l2)
goto denied;
else
mISDN_FsmEvent(&l2->tm->tei_m, EV_ASSIGN_REQ, dp);
return;
denied:
put_tei_msg(mgr, ID_DENIED, ri, GROUP_TEI);
}
static int
ph_data_ind(struct manager *mgr, struct sk_buff *skb)
{
int ret = -EINVAL;
struct layer2 *l2, *nl2;
u_char mt;
if (skb->len < 8) {
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: short mgr frame %d/8\n",
__func__, skb->len);
goto done;
}
if ((skb->data[0] >> 2) != TEI_SAPI) /* not for us */
goto done;
if (skb->data[0] & 1) /* EA0 formal error */
goto done;
if (!(skb->data[1] & 1)) /* EA1 formal error */
goto done;
if ((skb->data[1] >> 1) != GROUP_TEI) /* not for us */
goto done;
if ((skb->data[2] & 0xef) != UI) /* not UI */
goto done;
if (skb->data[3] != TEI_ENTITY_ID) /* not tei entity */
goto done;
mt = skb->data[6];
switch (mt) {
case ID_REQUEST:
case ID_CHK_RES:
case ID_VERIFY:
if (!test_bit(MGR_OPT_NETWORK, &mgr->options))
goto done;
break;
case ID_ASSIGNED:
case ID_DENIED:
case ID_CHK_REQ:
case ID_REMOVE:
if (test_bit(MGR_OPT_NETWORK, &mgr->options))
goto done;
break;
default:
goto done;
}
ret = 0;
if (mt == ID_REQUEST) {
new_tei_req(mgr, &skb->data[4]);
goto done;
}
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
tei_ph_data_ind(l2->tm, mt, &skb->data[4], skb->len - 4);
}
done:
return ret;
}
int
l2_tei(struct layer2 *l2, u_int cmd, u_long arg)
{
struct teimgr *tm = l2->tm;
if (test_bit(FLG_FIXED_TEI, &l2->flag))
return 0;
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: cmd(%x)\n", __func__, cmd);
switch (cmd) {
case MDL_ASSIGN_IND:
mISDN_FsmEvent(&tm->tei_m, EV_IDREQ, NULL);
break;
case MDL_ERROR_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->tei_m, EV_CHKREQ, &l2->tei);
if (test_bit(MGR_OPT_USER, &tm->mgr->options))
mISDN_FsmEvent(&tm->tei_m, EV_VERIFY, NULL);
break;
case MDL_STATUS_UP_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_ACTIVATE, NULL);
break;
case MDL_STATUS_DOWN_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_DEACTIVATE, NULL);
break;
case MDL_STATUS_UI_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_UI, NULL);
break;
}
return 0;
}
void
TEIrelease(struct layer2 *l2)
{
struct teimgr *tm = l2->tm;
u_long flags;
mISDN_FsmDelTimer(&tm->timer, 1);
write_lock_irqsave(&tm->mgr->lock, flags);
list_del(&l2->list);
write_unlock_irqrestore(&tm->mgr->lock, flags);
l2->tm = NULL;
kfree(tm);
}
static int
create_teimgr(struct manager *mgr, struct channel_req *crq)
{
struct layer2 *l2;
unsigned long opt = 0;
unsigned long flags;
int id;
struct channel_req l1rq;
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: %s proto(%x) adr(%d %d %d %d)\n",
__func__, dev_name(&mgr->ch.st->dev->dev),
crq->protocol, crq->adr.dev, crq->adr.channel,
crq->adr.sapi, crq->adr.tei);
if (crq->adr.tei > GROUP_TEI)
return -EINVAL;
if (crq->adr.tei < 64)
test_and_set_bit(OPTION_L2_FIXEDTEI, &opt);
if (crq->adr.tei == 0)
test_and_set_bit(OPTION_L2_PTP, &opt);
if (test_bit(MGR_OPT_NETWORK, &mgr->options)) {
if (crq->protocol == ISDN_P_LAPD_TE)
return -EPROTONOSUPPORT;
if ((crq->adr.tei != 0) && (crq->adr.tei != 127))
return -EINVAL;
if (mgr->up) {
printk(KERN_WARNING
"%s: only one network manager is allowed\n",
__func__);
return -EBUSY;
}
} else if (test_bit(MGR_OPT_USER, &mgr->options)) {
if (crq->protocol == ISDN_P_LAPD_NT)
return -EPROTONOSUPPORT;
if ((crq->adr.tei >= 64) && (crq->adr.tei < GROUP_TEI))
return -EINVAL; /* dyn tei */
} else {
if (crq->protocol == ISDN_P_LAPD_NT)
test_and_set_bit(MGR_OPT_NETWORK, &mgr->options);
if (crq->protocol == ISDN_P_LAPD_TE)
test_and_set_bit(MGR_OPT_USER, &mgr->options);
}
l1rq.adr = crq->adr;
if (mgr->ch.st->dev->Dprotocols
& ((1 << ISDN_P_TE_E1) | (1 << ISDN_P_NT_E1)))
test_and_set_bit(OPTION_L2_PMX, &opt);
if ((crq->protocol == ISDN_P_LAPD_NT) && (crq->adr.tei == 127)) {
mgr->up = crq->ch;
id = DL_INFO_L2_CONNECT;
teiup_create(mgr, DL_INFORMATION_IND, sizeof(id), &id);
if (test_bit(MGR_PH_ACTIVE, &mgr->options))
teiup_create(mgr, PH_ACTIVATE_IND, 0, NULL);
crq->ch = NULL;
if (!list_empty(&mgr->layer2)) {
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
l2->up = mgr->up;
l2->ch.ctrl(&l2->ch, OPEN_CHANNEL, NULL);
}
read_unlock_irqrestore(&mgr->lock, flags);
}
return 0;
}
l2 = create_l2(crq->ch, crq->protocol, opt,
crq->adr.tei, crq->adr.sapi);
if (!l2)
return -ENOMEM;
l2->tm = kzalloc(sizeof(struct teimgr), GFP_KERNEL);
if (!l2->tm) {
kfree(l2);
printk(KERN_ERR "kmalloc teimgr failed\n");
return -ENOMEM;
}
l2->tm->mgr = mgr;
l2->tm->l2 = l2;
l2->tm->tei_m.debug = *debug & DEBUG_L2_TEIFSM;
l2->tm->tei_m.userdata = l2->tm;
l2->tm->tei_m.printdebug = tei_debug;
if (crq->protocol == ISDN_P_LAPD_TE) {
l2->tm->tei_m.fsm = &teifsmu;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 1000; /* T201 1 sec */
if (test_bit(OPTION_L2_PMX, &opt))
l1rq.protocol = ISDN_P_TE_E1;
else
l1rq.protocol = ISDN_P_TE_S0;
} else {
l2->tm->tei_m.fsm = &teifsmn;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 2000; /* T202 2 sec */
if (test_bit(OPTION_L2_PMX, &opt))
l1rq.protocol = ISDN_P_NT_E1;
else
l1rq.protocol = ISDN_P_NT_S0;
}
mISDN_FsmInitTimer(&l2->tm->tei_m, &l2->tm->timer);
write_lock_irqsave(&mgr->lock, flags);
id = get_free_id(mgr);
list_add_tail(&l2->list, &mgr->layer2);
write_unlock_irqrestore(&mgr->lock, flags);
if (id >= 0) {
l2->ch.nr = id;
l2->up->nr = id;
crq->ch = &l2->ch;
/* We need open here L1 for the manager as well (refcounting) */
id = mgr->ch.st->own.ctrl(&mgr->ch.st->own, OPEN_CHANNEL,
&l1rq);
}
if (id < 0)
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
return id;
}
static int
mgr_send(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct manager *mgr;
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret = -EINVAL;
mgr = container_of(ch, struct manager, ch);
if (*debug & DEBUG_L2_RECV)
printk(KERN_DEBUG "%s: prim(%x) id(%x)\n",
__func__, hh->prim, hh->id);
switch (hh->prim) {
case PH_DATA_IND:
mISDN_FsmEvent(&mgr->deact, EV_UI, NULL);
ret = ph_data_ind(mgr, skb);
break;
case PH_DATA_CNF:
do_ack(mgr, hh->id);
ret = 0;
break;
case PH_ACTIVATE_IND:
test_and_set_bit(MGR_PH_ACTIVE, &mgr->options);
if (mgr->up)
teiup_create(mgr, PH_ACTIVATE_IND, 0, NULL);
mISDN_FsmEvent(&mgr->deact, EV_ACTIVATE_IND, NULL);
do_send(mgr);
ret = 0;
break;
case PH_DEACTIVATE_IND:
test_and_clear_bit(MGR_PH_ACTIVE, &mgr->options);
if (mgr->up)
teiup_create(mgr, PH_DEACTIVATE_IND, 0, NULL);
mISDN_FsmEvent(&mgr->deact, EV_DEACTIVATE_IND, NULL);
ret = 0;
break;
case DL_UNITDATA_REQ:
return dl_unit_data(mgr, skb);
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static int
free_teimanager(struct manager *mgr)
{
struct layer2 *l2, *nl2;
test_and_clear_bit(OPTION_L1_HOLD, &mgr->options);
if (test_bit(MGR_OPT_NETWORK, &mgr->options)) {
/* not locked lock is taken in release tei */
mgr->up = NULL;
if (test_bit(OPTION_L2_CLEANUP, &mgr->options)) {
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
put_tei_msg(mgr, ID_REMOVE, 0, l2->tei);
mutex_lock(&mgr->ch.st->lmutex);
list_del(&l2->ch.list);
mutex_unlock(&mgr->ch.st->lmutex);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
test_and_clear_bit(MGR_OPT_NETWORK, &mgr->options);
} else {
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
l2->up = NULL;
}
}
}
if (test_bit(MGR_OPT_USER, &mgr->options)) {
if (list_empty(&mgr->layer2))
test_and_clear_bit(MGR_OPT_USER, &mgr->options);
}
mgr->ch.st->dev->D.ctrl(&mgr->ch.st->dev->D, CLOSE_CHANNEL, NULL);
return 0;
}
static int
ctrl_teimanager(struct manager *mgr, void *arg)
{
/* currently we only have one option */
int *val = (int *)arg;
int ret = 0;
switch (val[0]) {
case IMCLEAR_L2:
if (val[1])
test_and_set_bit(OPTION_L2_CLEANUP, &mgr->options);
else
test_and_clear_bit(OPTION_L2_CLEANUP, &mgr->options);
break;
case IMHOLD_L1:
if (val[1])
test_and_set_bit(OPTION_L1_HOLD, &mgr->options);
else
test_and_clear_bit(OPTION_L1_HOLD, &mgr->options);
break;
default:
ret = -EINVAL;
}
return ret;
}
/* This function does create a L2 for fixed TEI in NT Mode */
static int
check_data(struct manager *mgr, struct sk_buff *skb)
{
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret, tei, sapi;
struct layer2 *l2;
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: prim(%x) id(%x)\n",
__func__, hh->prim, hh->id);
if (test_bit(MGR_OPT_USER, &mgr->options))
return -ENOTCONN;
if (hh->prim != PH_DATA_IND)
return -ENOTCONN;
if (skb->len != 3)
return -ENOTCONN;
if (skb->data[0] & 3) /* EA0 and CR must be 0 */
return -EINVAL;
sapi = skb->data[0] >> 2;
if (!(skb->data[1] & 1)) /* invalid EA1 */
return -EINVAL;
tei = skb->data[1] >> 1;
if (tei > 63) /* not a fixed tei */
return -ENOTCONN;
if ((skb->data[2] & ~0x10) != SABME)
return -ENOTCONN;
/* We got a SABME for a fixed TEI */
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: SABME sapi(%d) tei(%d)\n",
__func__, sapi, tei);
l2 = create_new_tei(mgr, tei, sapi);
if (!l2) {
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: failed to create new tei\n",
__func__);
return -ENOMEM;
}
ret = l2->ch.send(&l2->ch, skb);
return ret;
}
void
delete_teimanager(struct mISDNchannel *ch)
{
struct manager *mgr;
struct layer2 *l2, *nl2;
mgr = container_of(ch, struct manager, ch);
/* not locked lock is taken in release tei */
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
mutex_lock(&mgr->ch.st->lmutex);
list_del(&l2->ch.list);
mutex_unlock(&mgr->ch.st->lmutex);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
list_del(&mgr->ch.list);
list_del(&mgr->bcast.list);
skb_queue_purge(&mgr->sendq);
kfree(mgr);
}
static int
mgr_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct manager *mgr;
int ret = -EINVAL;
mgr = container_of(ch, struct manager, ch);
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s(%x, %p)\n", __func__, cmd, arg);
switch (cmd) {
case OPEN_CHANNEL:
ret = create_teimgr(mgr, arg);
break;
case CLOSE_CHANNEL:
ret = free_teimanager(mgr);
break;
case CONTROL_CHANNEL:
ret = ctrl_teimanager(mgr, arg);
break;
case CHECK_DATA:
ret = check_data(mgr, arg);
break;
}
return ret;
}
static int
mgr_bcast(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct manager *mgr = container_of(ch, struct manager, bcast);
struct mISDNhead *hhc, *hh = mISDN_HEAD_P(skb);
struct sk_buff *cskb = NULL;
struct layer2 *l2;
u_long flags;
int ret;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if ((hh->id & MISDN_ID_SAPI_MASK) ==
(l2->ch.addr & MISDN_ID_SAPI_MASK)) {
if (list_is_last(&l2->list, &mgr->layer2)) {
cskb = skb;
skb = NULL;
} else {
if (!cskb)
cskb = skb_copy(skb, GFP_ATOMIC);
}
if (cskb) {
hhc = mISDN_HEAD_P(cskb);
/* save original header behind normal header */
hhc++;
*hhc = *hh;
hhc--;
hhc->prim = DL_INTERN_MSG;
hhc->id = l2->ch.nr;
ret = ch->st->own.recv(&ch->st->own, cskb);
if (ret) {
if (*debug & DEBUG_SEND_ERR)
printk(KERN_DEBUG
"%s ch%d prim(%x) addr(%x)"
" err %d\n",
__func__, l2->ch.nr,
hh->prim, l2->ch.addr, ret);
} else
cskb = NULL;
} else {
printk(KERN_WARNING "%s ch%d addr %x no mem\n",
__func__, ch->nr, ch->addr);
goto out;
}
}
}
out:
read_unlock_irqrestore(&mgr->lock, flags);
if (cskb)
dev_kfree_skb(cskb);
if (skb)
dev_kfree_skb(skb);
return 0;
}
static int
mgr_bcast_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
return -EINVAL;
}
int
create_teimanager(struct mISDNdevice *dev)
{
struct manager *mgr;
mgr = kzalloc(sizeof(struct manager), GFP_KERNEL);
if (!mgr)
return -ENOMEM;
INIT_LIST_HEAD(&mgr->layer2);
rwlock_init(&mgr->lock);
skb_queue_head_init(&mgr->sendq);
mgr->nextid = 1;
mgr->lastid = MISDN_ID_NONE;
mgr->ch.send = mgr_send;
mgr->ch.ctrl = mgr_ctrl;
mgr->ch.st = dev->D.st;
set_channel_address(&mgr->ch, TEI_SAPI, GROUP_TEI);
add_layer2(&mgr->ch, dev->D.st);
mgr->bcast.send = mgr_bcast;
mgr->bcast.ctrl = mgr_bcast_ctrl;
mgr->bcast.st = dev->D.st;
set_channel_address(&mgr->bcast, 0, GROUP_TEI);
add_layer2(&mgr->bcast, dev->D.st);
mgr->deact.debug = *debug & DEBUG_MANAGER;
mgr->deact.userdata = mgr;
mgr->deact.printdebug = da_debug;
mgr->deact.fsm = &deactfsm;
mgr->deact.state = ST_L1_DEACT;
mISDN_FsmInitTimer(&mgr->deact, &mgr->datimer);
dev->teimgr = &mgr->ch;
return 0;
}
int TEIInit(u_int *deb)
{
debug = deb;
teifsmu.state_count = TEI_STATE_COUNT;
teifsmu.event_count = TEI_EVENT_COUNT;
teifsmu.strEvent = strTeiEvent;
teifsmu.strState = strTeiState;
mISDN_FsmNew(&teifsmu, TeiFnListUser, ARRAY_SIZE(TeiFnListUser));
teifsmn.state_count = TEI_STATE_COUNT;
teifsmn.event_count = TEI_EVENT_COUNT;
teifsmn.strEvent = strTeiEvent;
teifsmn.strState = strTeiState;
mISDN_FsmNew(&teifsmn, TeiFnListNet, ARRAY_SIZE(TeiFnListNet));
deactfsm.state_count = DEACT_STATE_COUNT;
deactfsm.event_count = DEACT_EVENT_COUNT;
deactfsm.strEvent = strDeactEvent;
deactfsm.strState = strDeactState;
mISDN_FsmNew(&deactfsm, DeactFnList, ARRAY_SIZE(DeactFnList));
return 0;
}
void TEIFree(void)
{
mISDN_FsmFree(&teifsmu);
mISDN_FsmFree(&teifsmn);
mISDN_FsmFree(&deactfsm);
}
| gpl-2.0 |
cholokei/android_kernel_msm | sound/mips/hal2.c | 5077 | 25703 | /*
* Driver for A2 audio system used in SGI machines
* Copyright (c) 2008 Thomas Bogendoerfer <tsbogend@alpha.fanken.de>
*
* Based on OSS code from Ladislav Michl <ladis@linux-mips.org>, which
* was based on code from Ulf Carlsson
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <asm/sgi/hpc3.h>
#include <asm/sgi/ip22.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/pcm-indirect.h>
#include <sound/initval.h>
#include "hal2.h"
static int index = SNDRV_DEFAULT_IDX1; /* Index 0-MAX */
static char *id = SNDRV_DEFAULT_STR1; /* ID for this card */
module_param(index, int, 0444);
MODULE_PARM_DESC(index, "Index value for SGI HAL2 soundcard.");
module_param(id, charp, 0444);
MODULE_PARM_DESC(id, "ID string for SGI HAL2 soundcard.");
MODULE_DESCRIPTION("ALSA driver for SGI HAL2 audio");
MODULE_AUTHOR("Thomas Bogendoerfer");
MODULE_LICENSE("GPL");
#define H2_BLOCK_SIZE 1024
#define H2_BUF_SIZE 16384
struct hal2_pbus {
struct hpc3_pbus_dmacregs *pbus;
int pbusnr;
unsigned int ctrl; /* Current state of pbus->pbdma_ctrl */
};
struct hal2_desc {
struct hpc_dma_desc desc;
u32 pad; /* padding */
};
struct hal2_codec {
struct snd_pcm_indirect pcm_indirect;
struct snd_pcm_substream *substream;
unsigned char *buffer;
dma_addr_t buffer_dma;
struct hal2_desc *desc;
dma_addr_t desc_dma;
int desc_count;
struct hal2_pbus pbus;
int voices; /* mono/stereo */
unsigned int sample_rate;
unsigned int master; /* Master frequency */
unsigned short mod; /* MOD value */
unsigned short inc; /* INC value */
};
#define H2_MIX_OUTPUT_ATT 0
#define H2_MIX_INPUT_GAIN 1
struct snd_hal2 {
struct snd_card *card;
struct hal2_ctl_regs *ctl_regs; /* HAL2 ctl registers */
struct hal2_aes_regs *aes_regs; /* HAL2 aes registers */
struct hal2_vol_regs *vol_regs; /* HAL2 vol registers */
struct hal2_syn_regs *syn_regs; /* HAL2 syn registers */
struct hal2_codec dac;
struct hal2_codec adc;
};
#define H2_INDIRECT_WAIT(regs) while (hal2_read(®s->isr) & H2_ISR_TSTATUS);
#define H2_READ_ADDR(addr) (addr | (1<<7))
#define H2_WRITE_ADDR(addr) (addr)
static inline u32 hal2_read(u32 *reg)
{
return __raw_readl(reg);
}
static inline void hal2_write(u32 val, u32 *reg)
{
__raw_writel(val, reg);
}
static u32 hal2_i_read32(struct snd_hal2 *hal2, u16 addr)
{
u32 ret;
struct hal2_ctl_regs *regs = hal2->ctl_regs;
hal2_write(H2_READ_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
ret = hal2_read(®s->idr0) & 0xffff;
hal2_write(H2_READ_ADDR(addr) | 0x1, ®s->iar);
H2_INDIRECT_WAIT(regs);
ret |= (hal2_read(®s->idr0) & 0xffff) << 16;
return ret;
}
static void hal2_i_write16(struct snd_hal2 *hal2, u16 addr, u16 val)
{
struct hal2_ctl_regs *regs = hal2->ctl_regs;
hal2_write(val, ®s->idr0);
hal2_write(0, ®s->idr1);
hal2_write(0, ®s->idr2);
hal2_write(0, ®s->idr3);
hal2_write(H2_WRITE_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
}
static void hal2_i_write32(struct snd_hal2 *hal2, u16 addr, u32 val)
{
struct hal2_ctl_regs *regs = hal2->ctl_regs;
hal2_write(val & 0xffff, ®s->idr0);
hal2_write(val >> 16, ®s->idr1);
hal2_write(0, ®s->idr2);
hal2_write(0, ®s->idr3);
hal2_write(H2_WRITE_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
}
static void hal2_i_setbit16(struct snd_hal2 *hal2, u16 addr, u16 bit)
{
struct hal2_ctl_regs *regs = hal2->ctl_regs;
hal2_write(H2_READ_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
hal2_write((hal2_read(®s->idr0) & 0xffff) | bit, ®s->idr0);
hal2_write(0, ®s->idr1);
hal2_write(0, ®s->idr2);
hal2_write(0, ®s->idr3);
hal2_write(H2_WRITE_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
}
static void hal2_i_clearbit16(struct snd_hal2 *hal2, u16 addr, u16 bit)
{
struct hal2_ctl_regs *regs = hal2->ctl_regs;
hal2_write(H2_READ_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
hal2_write((hal2_read(®s->idr0) & 0xffff) & ~bit, ®s->idr0);
hal2_write(0, ®s->idr1);
hal2_write(0, ®s->idr2);
hal2_write(0, ®s->idr3);
hal2_write(H2_WRITE_ADDR(addr), ®s->iar);
H2_INDIRECT_WAIT(regs);
}
static int hal2_gain_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
switch ((int)kcontrol->private_value) {
case H2_MIX_OUTPUT_ATT:
uinfo->value.integer.max = 31;
break;
case H2_MIX_INPUT_GAIN:
uinfo->value.integer.max = 15;
break;
}
return 0;
}
static int hal2_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_hal2 *hal2 = snd_kcontrol_chip(kcontrol);
u32 tmp;
int l, r;
switch ((int)kcontrol->private_value) {
case H2_MIX_OUTPUT_ATT:
tmp = hal2_i_read32(hal2, H2I_DAC_C2);
if (tmp & H2I_C2_MUTE) {
l = 0;
r = 0;
} else {
l = 31 - ((tmp >> H2I_C2_L_ATT_SHIFT) & 31);
r = 31 - ((tmp >> H2I_C2_R_ATT_SHIFT) & 31);
}
break;
case H2_MIX_INPUT_GAIN:
tmp = hal2_i_read32(hal2, H2I_ADC_C2);
l = (tmp >> H2I_C2_L_GAIN_SHIFT) & 15;
r = (tmp >> H2I_C2_R_GAIN_SHIFT) & 15;
break;
}
ucontrol->value.integer.value[0] = l;
ucontrol->value.integer.value[1] = r;
return 0;
}
static int hal2_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_hal2 *hal2 = snd_kcontrol_chip(kcontrol);
u32 old, new;
int l, r;
l = ucontrol->value.integer.value[0];
r = ucontrol->value.integer.value[1];
switch ((int)kcontrol->private_value) {
case H2_MIX_OUTPUT_ATT:
old = hal2_i_read32(hal2, H2I_DAC_C2);
new = old & ~(H2I_C2_L_ATT_M | H2I_C2_R_ATT_M | H2I_C2_MUTE);
if (l | r) {
l = 31 - l;
r = 31 - r;
new |= (l << H2I_C2_L_ATT_SHIFT);
new |= (r << H2I_C2_R_ATT_SHIFT);
} else
new |= H2I_C2_L_ATT_M | H2I_C2_R_ATT_M | H2I_C2_MUTE;
hal2_i_write32(hal2, H2I_DAC_C2, new);
break;
case H2_MIX_INPUT_GAIN:
old = hal2_i_read32(hal2, H2I_ADC_C2);
new = old & ~(H2I_C2_L_GAIN_M | H2I_C2_R_GAIN_M);
new |= (l << H2I_C2_L_GAIN_SHIFT);
new |= (r << H2I_C2_R_GAIN_SHIFT);
hal2_i_write32(hal2, H2I_ADC_C2, new);
break;
}
return old != new;
}
static struct snd_kcontrol_new hal2_ctrl_headphone __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Headphone Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = H2_MIX_OUTPUT_ATT,
.info = hal2_gain_info,
.get = hal2_gain_get,
.put = hal2_gain_put,
};
static struct snd_kcontrol_new hal2_ctrl_mic __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Mic Capture Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = H2_MIX_INPUT_GAIN,
.info = hal2_gain_info,
.get = hal2_gain_get,
.put = hal2_gain_put,
};
static int __devinit hal2_mixer_create(struct snd_hal2 *hal2)
{
int err;
/* mute DAC */
hal2_i_write32(hal2, H2I_DAC_C2,
H2I_C2_L_ATT_M | H2I_C2_R_ATT_M | H2I_C2_MUTE);
/* mute ADC */
hal2_i_write32(hal2, H2I_ADC_C2, 0);
err = snd_ctl_add(hal2->card,
snd_ctl_new1(&hal2_ctrl_headphone, hal2));
if (err < 0)
return err;
err = snd_ctl_add(hal2->card,
snd_ctl_new1(&hal2_ctrl_mic, hal2));
if (err < 0)
return err;
return 0;
}
static irqreturn_t hal2_interrupt(int irq, void *dev_id)
{
struct snd_hal2 *hal2 = dev_id;
irqreturn_t ret = IRQ_NONE;
/* decide what caused this interrupt */
if (hal2->dac.pbus.pbus->pbdma_ctrl & HPC3_PDMACTRL_INT) {
snd_pcm_period_elapsed(hal2->dac.substream);
ret = IRQ_HANDLED;
}
if (hal2->adc.pbus.pbus->pbdma_ctrl & HPC3_PDMACTRL_INT) {
snd_pcm_period_elapsed(hal2->adc.substream);
ret = IRQ_HANDLED;
}
return ret;
}
static int hal2_compute_rate(struct hal2_codec *codec, unsigned int rate)
{
unsigned short mod;
if (44100 % rate < 48000 % rate) {
mod = 4 * 44100 / rate;
codec->master = 44100;
} else {
mod = 4 * 48000 / rate;
codec->master = 48000;
}
codec->inc = 4;
codec->mod = mod;
rate = 4 * codec->master / mod;
return rate;
}
static void hal2_set_dac_rate(struct snd_hal2 *hal2)
{
unsigned int master = hal2->dac.master;
int inc = hal2->dac.inc;
int mod = hal2->dac.mod;
hal2_i_write16(hal2, H2I_BRES1_C1, (master == 44100) ? 1 : 0);
hal2_i_write32(hal2, H2I_BRES1_C2,
((0xffff & (inc - mod - 1)) << 16) | inc);
}
static void hal2_set_adc_rate(struct snd_hal2 *hal2)
{
unsigned int master = hal2->adc.master;
int inc = hal2->adc.inc;
int mod = hal2->adc.mod;
hal2_i_write16(hal2, H2I_BRES2_C1, (master == 44100) ? 1 : 0);
hal2_i_write32(hal2, H2I_BRES2_C2,
((0xffff & (inc - mod - 1)) << 16) | inc);
}
static void hal2_setup_dac(struct snd_hal2 *hal2)
{
unsigned int fifobeg, fifoend, highwater, sample_size;
struct hal2_pbus *pbus = &hal2->dac.pbus;
/* Now we set up some PBUS information. The PBUS needs information about
* what portion of the fifo it will use. If it's receiving or
* transmitting, and finally whether the stream is little endian or big
* endian. The information is written later, on the start call.
*/
sample_size = 2 * hal2->dac.voices;
/* Fifo should be set to hold exactly four samples. Highwater mark
* should be set to two samples. */
highwater = (sample_size * 2) >> 1; /* halfwords */
fifobeg = 0; /* playback is first */
fifoend = (sample_size * 4) >> 3; /* doublewords */
pbus->ctrl = HPC3_PDMACTRL_RT | HPC3_PDMACTRL_LD |
(highwater << 8) | (fifobeg << 16) | (fifoend << 24);
/* We disable everything before we do anything at all */
pbus->pbus->pbdma_ctrl = HPC3_PDMACTRL_LD;
hal2_i_clearbit16(hal2, H2I_DMA_PORT_EN, H2I_DMA_PORT_EN_CODECTX);
/* Setup the HAL2 for playback */
hal2_set_dac_rate(hal2);
/* Set endianess */
hal2_i_clearbit16(hal2, H2I_DMA_END, H2I_DMA_END_CODECTX);
/* Set DMA bus */
hal2_i_setbit16(hal2, H2I_DMA_DRV, (1 << pbus->pbusnr));
/* We are using 1st Bresenham clock generator for playback */
hal2_i_write16(hal2, H2I_DAC_C1, (pbus->pbusnr << H2I_C1_DMA_SHIFT)
| (1 << H2I_C1_CLKID_SHIFT)
| (hal2->dac.voices << H2I_C1_DATAT_SHIFT));
}
static void hal2_setup_adc(struct snd_hal2 *hal2)
{
unsigned int fifobeg, fifoend, highwater, sample_size;
struct hal2_pbus *pbus = &hal2->adc.pbus;
sample_size = 2 * hal2->adc.voices;
highwater = (sample_size * 2) >> 1; /* halfwords */
fifobeg = (4 * 4) >> 3; /* record is second */
fifoend = (4 * 4 + sample_size * 4) >> 3; /* doublewords */
pbus->ctrl = HPC3_PDMACTRL_RT | HPC3_PDMACTRL_RCV | HPC3_PDMACTRL_LD |
(highwater << 8) | (fifobeg << 16) | (fifoend << 24);
pbus->pbus->pbdma_ctrl = HPC3_PDMACTRL_LD;
hal2_i_clearbit16(hal2, H2I_DMA_PORT_EN, H2I_DMA_PORT_EN_CODECR);
/* Setup the HAL2 for record */
hal2_set_adc_rate(hal2);
/* Set endianess */
hal2_i_clearbit16(hal2, H2I_DMA_END, H2I_DMA_END_CODECR);
/* Set DMA bus */
hal2_i_setbit16(hal2, H2I_DMA_DRV, (1 << pbus->pbusnr));
/* We are using 2nd Bresenham clock generator for record */
hal2_i_write16(hal2, H2I_ADC_C1, (pbus->pbusnr << H2I_C1_DMA_SHIFT)
| (2 << H2I_C1_CLKID_SHIFT)
| (hal2->adc.voices << H2I_C1_DATAT_SHIFT));
}
static void hal2_start_dac(struct snd_hal2 *hal2)
{
struct hal2_pbus *pbus = &hal2->dac.pbus;
pbus->pbus->pbdma_dptr = hal2->dac.desc_dma;
pbus->pbus->pbdma_ctrl = pbus->ctrl | HPC3_PDMACTRL_ACT;
/* enable DAC */
hal2_i_setbit16(hal2, H2I_DMA_PORT_EN, H2I_DMA_PORT_EN_CODECTX);
}
static void hal2_start_adc(struct snd_hal2 *hal2)
{
struct hal2_pbus *pbus = &hal2->adc.pbus;
pbus->pbus->pbdma_dptr = hal2->adc.desc_dma;
pbus->pbus->pbdma_ctrl = pbus->ctrl | HPC3_PDMACTRL_ACT;
/* enable ADC */
hal2_i_setbit16(hal2, H2I_DMA_PORT_EN, H2I_DMA_PORT_EN_CODECR);
}
static inline void hal2_stop_dac(struct snd_hal2 *hal2)
{
hal2->dac.pbus.pbus->pbdma_ctrl = HPC3_PDMACTRL_LD;
/* The HAL2 itself may remain enabled safely */
}
static inline void hal2_stop_adc(struct snd_hal2 *hal2)
{
hal2->adc.pbus.pbus->pbdma_ctrl = HPC3_PDMACTRL_LD;
}
static int hal2_alloc_dmabuf(struct hal2_codec *codec)
{
struct hal2_desc *desc;
dma_addr_t desc_dma, buffer_dma;
int count = H2_BUF_SIZE / H2_BLOCK_SIZE;
int i;
codec->buffer = dma_alloc_noncoherent(NULL, H2_BUF_SIZE,
&buffer_dma, GFP_KERNEL);
if (!codec->buffer)
return -ENOMEM;
desc = dma_alloc_noncoherent(NULL, count * sizeof(struct hal2_desc),
&desc_dma, GFP_KERNEL);
if (!desc) {
dma_free_noncoherent(NULL, H2_BUF_SIZE,
codec->buffer, buffer_dma);
return -ENOMEM;
}
codec->buffer_dma = buffer_dma;
codec->desc_dma = desc_dma;
codec->desc = desc;
for (i = 0; i < count; i++) {
desc->desc.pbuf = buffer_dma + i * H2_BLOCK_SIZE;
desc->desc.cntinfo = HPCDMA_XIE | H2_BLOCK_SIZE;
desc->desc.pnext = (i == count - 1) ?
desc_dma : desc_dma + (i + 1) * sizeof(struct hal2_desc);
desc++;
}
dma_cache_sync(NULL, codec->desc, count * sizeof(struct hal2_desc),
DMA_TO_DEVICE);
codec->desc_count = count;
return 0;
}
static void hal2_free_dmabuf(struct hal2_codec *codec)
{
dma_free_noncoherent(NULL, codec->desc_count * sizeof(struct hal2_desc),
codec->desc, codec->desc_dma);
dma_free_noncoherent(NULL, H2_BUF_SIZE, codec->buffer,
codec->buffer_dma);
}
static struct snd_pcm_hardware hal2_pcm_hw = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = SNDRV_PCM_FMTBIT_S16_BE,
.rates = SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 65536,
.period_bytes_min = 1024,
.period_bytes_max = 65536,
.periods_min = 2,
.periods_max = 1024,
};
static int hal2_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
int err;
err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(params));
if (err < 0)
return err;
return 0;
}
static int hal2_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int hal2_playback_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
int err;
runtime->hw = hal2_pcm_hw;
err = hal2_alloc_dmabuf(&hal2->dac);
if (err)
return err;
return 0;
}
static int hal2_playback_close(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
hal2_free_dmabuf(&hal2->dac);
return 0;
}
static int hal2_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct hal2_codec *dac = &hal2->dac;
dac->voices = runtime->channels;
dac->sample_rate = hal2_compute_rate(dac, runtime->rate);
memset(&dac->pcm_indirect, 0, sizeof(dac->pcm_indirect));
dac->pcm_indirect.hw_buffer_size = H2_BUF_SIZE;
dac->pcm_indirect.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream);
dac->substream = substream;
hal2_setup_dac(hal2);
return 0;
}
static int hal2_playback_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
hal2->dac.pcm_indirect.hw_io = hal2->dac.buffer_dma;
hal2->dac.pcm_indirect.hw_data = 0;
substream->ops->ack(substream);
hal2_start_dac(hal2);
break;
case SNDRV_PCM_TRIGGER_STOP:
hal2_stop_dac(hal2);
break;
default:
return -EINVAL;
}
return 0;
}
static snd_pcm_uframes_t
hal2_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct hal2_codec *dac = &hal2->dac;
return snd_pcm_indirect_playback_pointer(substream, &dac->pcm_indirect,
dac->pbus.pbus->pbdma_bptr);
}
static void hal2_playback_transfer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, size_t bytes)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
unsigned char *buf = hal2->dac.buffer + rec->hw_data;
memcpy(buf, substream->runtime->dma_area + rec->sw_data, bytes);
dma_cache_sync(NULL, buf, bytes, DMA_TO_DEVICE);
}
static int hal2_playback_ack(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct hal2_codec *dac = &hal2->dac;
dac->pcm_indirect.hw_queue_size = H2_BUF_SIZE / 2;
snd_pcm_indirect_playback_transfer(substream,
&dac->pcm_indirect,
hal2_playback_transfer);
return 0;
}
static int hal2_capture_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct hal2_codec *adc = &hal2->adc;
int err;
runtime->hw = hal2_pcm_hw;
err = hal2_alloc_dmabuf(adc);
if (err)
return err;
return 0;
}
static int hal2_capture_close(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
hal2_free_dmabuf(&hal2->adc);
return 0;
}
static int hal2_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct hal2_codec *adc = &hal2->adc;
adc->voices = runtime->channels;
adc->sample_rate = hal2_compute_rate(adc, runtime->rate);
memset(&adc->pcm_indirect, 0, sizeof(adc->pcm_indirect));
adc->pcm_indirect.hw_buffer_size = H2_BUF_SIZE;
adc->pcm_indirect.hw_queue_size = H2_BUF_SIZE / 2;
adc->pcm_indirect.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream);
adc->substream = substream;
hal2_setup_adc(hal2);
return 0;
}
static int hal2_capture_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
hal2->adc.pcm_indirect.hw_io = hal2->adc.buffer_dma;
hal2->adc.pcm_indirect.hw_data = 0;
printk(KERN_DEBUG "buffer_dma %x\n", hal2->adc.buffer_dma);
hal2_start_adc(hal2);
break;
case SNDRV_PCM_TRIGGER_STOP:
hal2_stop_adc(hal2);
break;
default:
return -EINVAL;
}
return 0;
}
static snd_pcm_uframes_t
hal2_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct hal2_codec *adc = &hal2->adc;
return snd_pcm_indirect_capture_pointer(substream, &adc->pcm_indirect,
adc->pbus.pbus->pbdma_bptr);
}
static void hal2_capture_transfer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, size_t bytes)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
unsigned char *buf = hal2->adc.buffer + rec->hw_data;
dma_cache_sync(NULL, buf, bytes, DMA_FROM_DEVICE);
memcpy(substream->runtime->dma_area + rec->sw_data, buf, bytes);
}
static int hal2_capture_ack(struct snd_pcm_substream *substream)
{
struct snd_hal2 *hal2 = snd_pcm_substream_chip(substream);
struct hal2_codec *adc = &hal2->adc;
snd_pcm_indirect_capture_transfer(substream,
&adc->pcm_indirect,
hal2_capture_transfer);
return 0;
}
static struct snd_pcm_ops hal2_playback_ops = {
.open = hal2_playback_open,
.close = hal2_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = hal2_pcm_hw_params,
.hw_free = hal2_pcm_hw_free,
.prepare = hal2_playback_prepare,
.trigger = hal2_playback_trigger,
.pointer = hal2_playback_pointer,
.ack = hal2_playback_ack,
};
static struct snd_pcm_ops hal2_capture_ops = {
.open = hal2_capture_open,
.close = hal2_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = hal2_pcm_hw_params,
.hw_free = hal2_pcm_hw_free,
.prepare = hal2_capture_prepare,
.trigger = hal2_capture_trigger,
.pointer = hal2_capture_pointer,
.ack = hal2_capture_ack,
};
static int __devinit hal2_pcm_create(struct snd_hal2 *hal2)
{
struct snd_pcm *pcm;
int err;
/* create first pcm device with one outputs and one input */
err = snd_pcm_new(hal2->card, "SGI HAL2 Audio", 0, 1, 1, &pcm);
if (err < 0)
return err;
pcm->private_data = hal2;
strcpy(pcm->name, "SGI HAL2");
/* set operators */
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&hal2_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&hal2_capture_ops);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
snd_dma_continuous_data(GFP_KERNEL),
0, 1024 * 1024);
return 0;
}
static int hal2_dev_free(struct snd_device *device)
{
struct snd_hal2 *hal2 = device->device_data;
free_irq(SGI_HPCDMA_IRQ, hal2);
kfree(hal2);
return 0;
}
static struct snd_device_ops hal2_ops = {
.dev_free = hal2_dev_free,
};
static void hal2_init_codec(struct hal2_codec *codec, struct hpc3_regs *hpc3,
int index)
{
codec->pbus.pbusnr = index;
codec->pbus.pbus = &hpc3->pbdma[index];
}
static int hal2_detect(struct snd_hal2 *hal2)
{
unsigned short board, major, minor;
unsigned short rev;
/* reset HAL2 */
hal2_write(0, &hal2->ctl_regs->isr);
/* release reset */
hal2_write(H2_ISR_GLOBAL_RESET_N | H2_ISR_CODEC_RESET_N,
&hal2->ctl_regs->isr);
hal2_i_write16(hal2, H2I_RELAY_C, H2I_RELAY_C_STATE);
rev = hal2_read(&hal2->ctl_regs->rev);
if (rev & H2_REV_AUDIO_PRESENT)
return -ENODEV;
board = (rev & H2_REV_BOARD_M) >> 12;
major = (rev & H2_REV_MAJOR_CHIP_M) >> 4;
minor = (rev & H2_REV_MINOR_CHIP_M);
printk(KERN_INFO "SGI HAL2 revision %i.%i.%i\n",
board, major, minor);
return 0;
}
static int hal2_create(struct snd_card *card, struct snd_hal2 **rchip)
{
struct snd_hal2 *hal2;
struct hpc3_regs *hpc3 = hpc3c0;
int err;
hal2 = kzalloc(sizeof(struct snd_hal2), GFP_KERNEL);
if (!hal2)
return -ENOMEM;
hal2->card = card;
if (request_irq(SGI_HPCDMA_IRQ, hal2_interrupt, IRQF_SHARED,
"SGI HAL2", hal2)) {
printk(KERN_ERR "HAL2: Can't get irq %d\n", SGI_HPCDMA_IRQ);
kfree(hal2);
return -EAGAIN;
}
hal2->ctl_regs = (struct hal2_ctl_regs *)hpc3->pbus_extregs[0];
hal2->aes_regs = (struct hal2_aes_regs *)hpc3->pbus_extregs[1];
hal2->vol_regs = (struct hal2_vol_regs *)hpc3->pbus_extregs[2];
hal2->syn_regs = (struct hal2_syn_regs *)hpc3->pbus_extregs[3];
if (hal2_detect(hal2) < 0) {
kfree(hal2);
return -ENODEV;
}
hal2_init_codec(&hal2->dac, hpc3, 0);
hal2_init_codec(&hal2->adc, hpc3, 1);
/*
* All DMA channel interfaces in HAL2 are designed to operate with
* PBUS programmed for 2 cycles in D3, 2 cycles in D4 and 2 cycles
* in D5. HAL2 is a 16-bit device which can accept both big and little
* endian format. It assumes that even address bytes are on high
* portion of PBUS (15:8) and assumes that HPC3 is programmed to
* accept a live (unsynchronized) version of P_DREQ_N from HAL2.
*/
#define HAL2_PBUS_DMACFG ((0 << HPC3_DMACFG_D3R_SHIFT) | \
(2 << HPC3_DMACFG_D4R_SHIFT) | \
(2 << HPC3_DMACFG_D5R_SHIFT) | \
(0 << HPC3_DMACFG_D3W_SHIFT) | \
(2 << HPC3_DMACFG_D4W_SHIFT) | \
(2 << HPC3_DMACFG_D5W_SHIFT) | \
HPC3_DMACFG_DS16 | \
HPC3_DMACFG_EVENHI | \
HPC3_DMACFG_RTIME | \
(8 << HPC3_DMACFG_BURST_SHIFT) | \
HPC3_DMACFG_DRQLIVE)
/*
* Ignore what's mentioned in the specification and write value which
* works in The Real World (TM)
*/
hpc3->pbus_dmacfg[hal2->dac.pbus.pbusnr][0] = 0x8208844;
hpc3->pbus_dmacfg[hal2->adc.pbus.pbusnr][0] = 0x8208844;
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, hal2, &hal2_ops);
if (err < 0) {
free_irq(SGI_HPCDMA_IRQ, hal2);
kfree(hal2);
return err;
}
*rchip = hal2;
return 0;
}
static int __devinit hal2_probe(struct platform_device *pdev)
{
struct snd_card *card;
struct snd_hal2 *chip;
int err;
err = snd_card_create(index, id, THIS_MODULE, 0, &card);
if (err < 0)
return err;
err = hal2_create(card, &chip);
if (err < 0) {
snd_card_free(card);
return err;
}
snd_card_set_dev(card, &pdev->dev);
err = hal2_pcm_create(chip);
if (err < 0) {
snd_card_free(card);
return err;
}
err = hal2_mixer_create(chip);
if (err < 0) {
snd_card_free(card);
return err;
}
strcpy(card->driver, "SGI HAL2 Audio");
strcpy(card->shortname, "SGI HAL2 Audio");
sprintf(card->longname, "%s irq %i",
card->shortname,
SGI_HPCDMA_IRQ);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
return err;
}
platform_set_drvdata(pdev, card);
return 0;
}
static int __devexit hal2_remove(struct platform_device *pdev)
{
struct snd_card *card = platform_get_drvdata(pdev);
snd_card_free(card);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver hal2_driver = {
.probe = hal2_probe,
.remove = __devexit_p(hal2_remove),
.driver = {
.name = "sgihal2",
.owner = THIS_MODULE,
}
};
module_platform_driver(hal2_driver);
| gpl-2.0 |
bestmjh47/android_kernel_kttech_e100 | sound/isa/cs423x/cs4236.c | 5077 | 22579 | /*
* Driver for generic CS4232/CS4235/CS4236/CS4236B/CS4237B/CS4238B/CS4239 chips
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/pnp.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/wss.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cirrus Logic CS4232-9");
MODULE_SUPPORTED_DEVICE("{{Turtle Beach,TBS-2000},"
"{Turtle Beach,Tropez Plus},"
"{SIC CrystalWave 32},"
"{Hewlett Packard,Omnibook 5500},"
"{TerraTec,Maestro 32/96},"
"{Philips,PCA70PS}},"
"{{Crystal Semiconductors,CS4235},"
"{Crystal Semiconductors,CS4236},"
"{Crystal Semiconductors,CS4237},"
"{Crystal Semiconductors,CS4238},"
"{Crystal Semiconductors,CS4239},"
"{Acer,AW37},"
"{Acer,AW35/Pro},"
"{Crystal,3D},"
"{Crystal Computer,TidalWave128},"
"{Dell,Optiplex GX1},"
"{Dell,Workstation 400 sound},"
"{EliteGroup,P5TX-LA sound},"
"{Gallant,SC-70P},"
"{Gateway,E1000 Onboard CS4236B},"
"{Genius,Sound Maker 3DJ},"
"{Hewlett Packard,HP6330 sound},"
"{IBM,PC 300PL sound},"
"{IBM,Aptiva 2137 E24},"
"{IBM,IntelliStation M Pro},"
"{Intel,Marlin Spike Mobo CS4235},"
"{Intel PR440FX Onboard},"
"{Guillemot,MaxiSound 16 PnP},"
"{NewClear,3D},"
"{TerraTec,AudioSystem EWS64L/XL},"
"{Typhoon Soundsystem,CS4236B},"
"{Turtle Beach,Malibu},"
"{Unknown,Digital PC 5000 Onboard}}");
MODULE_ALIAS("snd_cs4232");
#define IDENT "CS4232+"
#define DEV_NAME "cs4232+"
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static bool isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long cport[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;/* PnP setup */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long sb_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,11,12,15 */
static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 9,11,12,15 */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " IDENT " soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " IDENT " soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable " IDENT " soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "ISA PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for " IDENT " driver.");
module_param_array(cport, long, NULL, 0444);
MODULE_PARM_DESC(cport, "Control port # for " IDENT " driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for " IDENT " driver.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for " IDENT " driver.");
module_param_array(sb_port, long, NULL, 0444);
MODULE_PARM_DESC(sb_port, "SB port # for " IDENT " driver (optional).");
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for " IDENT " driver.");
module_param_array(mpu_irq, int, NULL, 0444);
MODULE_PARM_DESC(mpu_irq, "MPU-401 IRQ # for " IDENT " driver.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA1 # for " IDENT " driver.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA2 # for " IDENT " driver.");
#ifdef CONFIG_PNP
static int isa_registered;
static int pnpc_registered;
static int pnp_registered;
#endif /* CONFIG_PNP */
struct snd_card_cs4236 {
struct snd_wss *chip;
struct resource *res_sb_port;
#ifdef CONFIG_PNP
struct pnp_dev *wss;
struct pnp_dev *ctrl;
struct pnp_dev *mpu;
#endif
};
#ifdef CONFIG_PNP
/*
* PNP BIOS
*/
static const struct pnp_device_id snd_cs423x_pnpbiosids[] = {
{ .id = "CSC0100" },
{ .id = "CSC0000" },
/* Guillemot Turtlebeach something appears to be cs4232 compatible
* (untested) */
{ .id = "GIM0100" },
{ .id = "" }
};
MODULE_DEVICE_TABLE(pnp, snd_cs423x_pnpbiosids);
#define CS423X_ISAPNP_DRIVER "cs4232_isapnp"
static struct pnp_card_device_id snd_cs423x_pnpids[] = {
/* Philips PCA70PS */
{ .id = "CSC0d32", .devs = { { "CSC0000" }, { "CSC0010" }, { "PNPb006" } } },
/* TerraTec Maestro 32/96 (CS4232) */
{ .id = "CSC1a32", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* HP Omnibook 5500 onboard */
{ .id = "CSC4232", .devs = { { "CSC0000" }, { "CSC0002" }, { "CSC0003" } } },
/* Unnamed CS4236 card (Made in Taiwan) */
{ .id = "CSC4236", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Turtle Beach TBS-2000 (CS4232) */
{ .id = "CSC7532", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSCb006" } } },
/* Turtle Beach Tropez Plus (CS4232) */
{ .id = "CSC7632", .devs = { { "CSC0000" }, { "CSC0010" }, { "PNPb006" } } },
/* SIC CrystalWave 32 (CS4232) */
{ .id = "CSCf032", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Netfinity 3000 on-board soundcard */
{ .id = "CSCe825", .devs = { { "CSC0100" }, { "CSC0110" }, { "CSC010f" } } },
/* Intel Marlin Spike Motherboard - CS4235 */
{ .id = "CSC0225", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Intel Marlin Spike Motherboard (#2) - CS4235 */
{ .id = "CSC0225", .devs = { { "CSC0100" }, { "CSC0110" }, { "CSC0103" } } },
/* Unknown Intel mainboard - CS4235 */
{ .id = "CSC0225", .devs = { { "CSC0100" }, { "CSC0110" } } },
/* Genius Sound Maker 3DJ - CS4237B */
{ .id = "CSC0437", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Digital PC 5000 Onboard - CS4236B */
{ .id = "CSC0735", .devs = { { "CSC0000" }, { "CSC0010" } } },
/* some unknown CS4236B */
{ .id = "CSC0b35", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Intel PR440FX Onboard sound */
{ .id = "CSC0b36", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* CS4235 on mainboard without MPU */
{ .id = "CSC1425", .devs = { { "CSC0100" }, { "CSC0110" } } },
/* Gateway E1000 Onboard CS4236B */
{ .id = "CSC1335", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* HP 6330 Onboard sound */
{ .id = "CSC1525", .devs = { { "CSC0100" }, { "CSC0110" }, { "CSC0103" } } },
/* Crystal Computer TidalWave128 */
{ .id = "CSC1e37", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* ACER AW37 - CS4235 */
{ .id = "CSC4236", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* build-in soundcard in EliteGroup P5TX-LA motherboard - CS4237B */
{ .id = "CSC4237", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Crystal 3D - CS4237B */
{ .id = "CSC4336", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Typhoon Soundsystem PnP - CS4236B */
{ .id = "CSC4536", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Crystal CX4235-XQ3 EP - CS4235 */
{ .id = "CSC4625", .devs = { { "CSC0100" }, { "CSC0110" }, { "CSC0103" } } },
/* Crystal Semiconductors CS4237B */
{ .id = "CSC4637", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* NewClear 3D - CX4237B-XQ3 */
{ .id = "CSC4837", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Dell Optiplex GX1 - CS4236B */
{ .id = "CSC6835", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Dell P410 motherboard - CS4236B */
{ .id = "CSC6835", .devs = { { "CSC0000" }, { "CSC0010" } } },
/* Dell Workstation 400 Onboard - CS4236B */
{ .id = "CSC6836", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Turtle Beach Malibu - CS4237B */
{ .id = "CSC7537", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* CS4235 - onboard */
{ .id = "CSC8025", .devs = { { "CSC0100" }, { "CSC0110" }, { "CSC0103" } } },
/* IBM Aptiva 2137 E24 Onboard - CS4237B */
{ .id = "CSC8037", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* IBM IntelliStation M Pro motherboard */
{ .id = "CSCc835", .devs = { { "CSC0000" }, { "CSC0010" } } },
/* Guillemot MaxiSound 16 PnP - CS4236B */
{ .id = "CSC9836", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Gallant SC-70P */
{ .id = "CSC9837", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* Techmakers MF-4236PW */
{ .id = "CSCa736", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* TerraTec AudioSystem EWS64XL - CS4236B */
{ .id = "CSCa836", .devs = { { "CSCa800" }, { "CSCa810" }, { "CSCa803" } } },
/* TerraTec AudioSystem EWS64XL - CS4236B */
{ .id = "CSCa836", .devs = { { "CSCa800" }, { "CSCa810" } } },
/* ACER AW37/Pro - CS4235 */
{ .id = "CSCd925", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* ACER AW35/Pro - CS4237B */
{ .id = "CSCd937", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* CS4235 without MPU401 */
{ .id = "CSCe825", .devs = { { "CSC0100" }, { "CSC0110" } } },
/* Unknown SiS530 - CS4235 */
{ .id = "CSC4825", .devs = { { "CSC0100" }, { "CSC0110" } } },
/* IBM IntelliStation M Pro 6898 11U - CS4236B */
{ .id = "CSCe835", .devs = { { "CSC0000" }, { "CSC0010" } } },
/* IBM PC 300PL Onboard - CS4236B */
{ .id = "CSCe836", .devs = { { "CSC0000" }, { "CSC0010" } } },
/* Some noname CS4236 based card */
{ .id = "CSCe936", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* CS4236B */
{ .id = "CSCf235", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* CS4236B */
{ .id = "CSCf238", .devs = { { "CSC0000" }, { "CSC0010" }, { "CSC0003" } } },
/* --- */
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_cs423x_pnpids);
/* WSS initialization */
static int __devinit snd_cs423x_pnp_init_wss(int dev, struct pnp_dev *pdev)
{
if (pnp_activate_dev(pdev) < 0) {
printk(KERN_ERR IDENT " WSS PnP configure failed for WSS (out of resources?)\n");
return -EBUSY;
}
port[dev] = pnp_port_start(pdev, 0);
if (fm_port[dev] > 0)
fm_port[dev] = pnp_port_start(pdev, 1);
sb_port[dev] = pnp_port_start(pdev, 2);
irq[dev] = pnp_irq(pdev, 0);
dma1[dev] = pnp_dma(pdev, 0);
dma2[dev] = pnp_dma(pdev, 1) == 4 ? -1 : (int)pnp_dma(pdev, 1);
snd_printdd("isapnp WSS: wss port=0x%lx, fm port=0x%lx, sb port=0x%lx\n",
port[dev], fm_port[dev], sb_port[dev]);
snd_printdd("isapnp WSS: irq=%i, dma1=%i, dma2=%i\n",
irq[dev], dma1[dev], dma2[dev]);
return 0;
}
/* CTRL initialization */
static int __devinit snd_cs423x_pnp_init_ctrl(int dev, struct pnp_dev *pdev)
{
if (pnp_activate_dev(pdev) < 0) {
printk(KERN_ERR IDENT " CTRL PnP configure failed for WSS (out of resources?)\n");
return -EBUSY;
}
cport[dev] = pnp_port_start(pdev, 0);
snd_printdd("isapnp CTRL: control port=0x%lx\n", cport[dev]);
return 0;
}
/* MPU initialization */
static int __devinit snd_cs423x_pnp_init_mpu(int dev, struct pnp_dev *pdev)
{
if (pnp_activate_dev(pdev) < 0) {
printk(KERN_ERR IDENT " MPU401 PnP configure failed for WSS (out of resources?)\n");
mpu_port[dev] = SNDRV_AUTO_PORT;
mpu_irq[dev] = SNDRV_AUTO_IRQ;
} else {
mpu_port[dev] = pnp_port_start(pdev, 0);
if (mpu_irq[dev] >= 0 &&
pnp_irq_valid(pdev, 0) && pnp_irq(pdev, 0) >= 0) {
mpu_irq[dev] = pnp_irq(pdev, 0);
} else {
mpu_irq[dev] = -1; /* disable interrupt */
}
}
snd_printdd("isapnp MPU: port=0x%lx, irq=%i\n", mpu_port[dev], mpu_irq[dev]);
return 0;
}
static int __devinit snd_card_cs423x_pnp(int dev, struct snd_card_cs4236 *acard,
struct pnp_dev *pdev,
struct pnp_dev *cdev)
{
acard->wss = pdev;
if (snd_cs423x_pnp_init_wss(dev, acard->wss) < 0)
return -EBUSY;
if (cdev)
cport[dev] = pnp_port_start(cdev, 0);
else
cport[dev] = -1;
return 0;
}
static int __devinit snd_card_cs423x_pnpc(int dev, struct snd_card_cs4236 *acard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
acard->wss = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->wss == NULL)
return -EBUSY;
acard->ctrl = pnp_request_card_device(card, id->devs[1].id, NULL);
if (acard->ctrl == NULL)
return -EBUSY;
if (id->devs[2].id[0]) {
acard->mpu = pnp_request_card_device(card, id->devs[2].id, NULL);
if (acard->mpu == NULL)
return -EBUSY;
}
/* WSS initialization */
if (snd_cs423x_pnp_init_wss(dev, acard->wss) < 0)
return -EBUSY;
/* CTRL initialization */
if (acard->ctrl && cport[dev] > 0) {
if (snd_cs423x_pnp_init_ctrl(dev, acard->ctrl) < 0)
return -EBUSY;
}
/* MPU initialization */
if (acard->mpu && mpu_port[dev] > 0) {
if (snd_cs423x_pnp_init_mpu(dev, acard->mpu) < 0)
return -EBUSY;
}
return 0;
}
#endif /* CONFIG_PNP */
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static void snd_card_cs4236_free(struct snd_card *card)
{
struct snd_card_cs4236 *acard = card->private_data;
release_and_free_resource(acard->res_sb_port);
}
static int snd_cs423x_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_card_cs4236), &card);
if (err < 0)
return err;
card->private_free = snd_card_cs4236_free;
*cardp = card;
return 0;
}
static int __devinit snd_cs423x_probe(struct snd_card *card, int dev)
{
struct snd_card_cs4236 *acard;
struct snd_pcm *pcm;
struct snd_wss *chip;
struct snd_opl3 *opl3;
int err;
acard = card->private_data;
if (sb_port[dev] > 0 && sb_port[dev] != SNDRV_AUTO_PORT)
if ((acard->res_sb_port = request_region(sb_port[dev], 16, IDENT " SB")) == NULL) {
printk(KERN_ERR IDENT ": unable to register SB port at 0x%lx\n", sb_port[dev]);
return -EBUSY;
}
err = snd_cs4236_create(card, port[dev], cport[dev],
irq[dev],
dma1[dev], dma2[dev],
WSS_HW_DETECT3, 0, &chip);
if (err < 0)
return err;
acard->chip = chip;
if (chip->hardware & WSS_HW_CS4236B_MASK) {
err = snd_cs4236_pcm(chip, 0, &pcm);
if (err < 0)
return err;
err = snd_cs4236_mixer(chip);
if (err < 0)
return err;
} else {
err = snd_wss_pcm(chip, 0, &pcm);
if (err < 0)
return err;
err = snd_wss_mixer(chip);
if (err < 0)
return err;
}
strcpy(card->driver, pcm->name);
strcpy(card->shortname, pcm->name);
sprintf(card->longname, "%s at 0x%lx, irq %i, dma %i",
pcm->name,
chip->port,
irq[dev],
dma1[dev]);
if (dma2[dev] >= 0)
sprintf(card->longname + strlen(card->longname), "&%d", dma2[dev]);
err = snd_wss_timer(chip, 0, NULL);
if (err < 0)
return err;
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
if (snd_opl3_create(card,
fm_port[dev], fm_port[dev] + 2,
OPL3_HW_OPL3_CS, 0, &opl3) < 0) {
printk(KERN_WARNING IDENT ": OPL3 not detected\n");
} else {
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0)
return err;
}
}
if (mpu_port[dev] > 0 && mpu_port[dev] != SNDRV_AUTO_PORT) {
if (mpu_irq[dev] == SNDRV_AUTO_IRQ)
mpu_irq[dev] = -1;
if (snd_mpu401_uart_new(card, 0, MPU401_HW_CS4232,
mpu_port[dev], 0,
mpu_irq[dev], NULL) < 0)
printk(KERN_WARNING IDENT ": MPU401 not detected\n");
}
return snd_card_register(card);
}
static int __devinit snd_cs423x_isa_match(struct device *pdev,
unsigned int dev)
{
if (!enable[dev] || is_isapnp_selected(dev))
return 0;
if (port[dev] == SNDRV_AUTO_PORT) {
dev_err(pdev, "please specify port\n");
return 0;
}
if (cport[dev] == SNDRV_AUTO_PORT) {
dev_err(pdev, "please specify cport\n");
return 0;
}
if (irq[dev] == SNDRV_AUTO_IRQ) {
dev_err(pdev, "please specify irq\n");
return 0;
}
if (dma1[dev] == SNDRV_AUTO_DMA) {
dev_err(pdev, "please specify dma1\n");
return 0;
}
return 1;
}
static int __devinit snd_cs423x_isa_probe(struct device *pdev,
unsigned int dev)
{
struct snd_card *card;
int err;
err = snd_cs423x_card_new(dev, &card);
if (err < 0)
return err;
snd_card_set_dev(card, pdev);
if ((err = snd_cs423x_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(pdev, card);
return 0;
}
static int __devexit snd_cs423x_isa_remove(struct device *pdev,
unsigned int dev)
{
snd_card_free(dev_get_drvdata(pdev));
dev_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_cs423x_suspend(struct snd_card *card)
{
struct snd_card_cs4236 *acard = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
acard->chip->suspend(acard->chip);
return 0;
}
static int snd_cs423x_resume(struct snd_card *card)
{
struct snd_card_cs4236 *acard = card->private_data;
acard->chip->resume(acard->chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
static int snd_cs423x_isa_suspend(struct device *dev, unsigned int n,
pm_message_t state)
{
return snd_cs423x_suspend(dev_get_drvdata(dev));
}
static int snd_cs423x_isa_resume(struct device *dev, unsigned int n)
{
return snd_cs423x_resume(dev_get_drvdata(dev));
}
#endif
static struct isa_driver cs423x_isa_driver = {
.match = snd_cs423x_isa_match,
.probe = snd_cs423x_isa_probe,
.remove = __devexit_p(snd_cs423x_isa_remove),
#ifdef CONFIG_PM
.suspend = snd_cs423x_isa_suspend,
.resume = snd_cs423x_isa_resume,
#endif
.driver = {
.name = DEV_NAME
},
};
#ifdef CONFIG_PNP
static int __devinit snd_cs423x_pnpbios_detect(struct pnp_dev *pdev,
const struct pnp_device_id *id)
{
static int dev;
int err;
struct snd_card *card;
struct pnp_dev *cdev;
char cid[PNP_ID_LEN];
if (pnp_device_is_isapnp(pdev))
return -ENOENT; /* we have another procedure - card */
for (; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
/* prepare second id */
strcpy(cid, pdev->id[0].id);
cid[5] = '1';
cdev = NULL;
list_for_each_entry(cdev, &(pdev->protocol->devices), protocol_list) {
if (!strcmp(cdev->id[0].id, cid))
break;
}
err = snd_cs423x_card_new(dev, &card);
if (err < 0)
return err;
err = snd_card_cs423x_pnp(dev, card->private_data, pdev, cdev);
if (err < 0) {
printk(KERN_ERR "PnP BIOS detection failed for " IDENT "\n");
snd_card_free(card);
return err;
}
snd_card_set_dev(card, &pdev->dev);
if ((err = snd_cs423x_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
pnp_set_drvdata(pdev, card);
dev++;
return 0;
}
static void __devexit snd_cs423x_pnp_remove(struct pnp_dev *pdev)
{
snd_card_free(pnp_get_drvdata(pdev));
pnp_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM
static int snd_cs423x_pnp_suspend(struct pnp_dev *pdev, pm_message_t state)
{
return snd_cs423x_suspend(pnp_get_drvdata(pdev));
}
static int snd_cs423x_pnp_resume(struct pnp_dev *pdev)
{
return snd_cs423x_resume(pnp_get_drvdata(pdev));
}
#endif
static struct pnp_driver cs423x_pnp_driver = {
.name = "cs423x-pnpbios",
.id_table = snd_cs423x_pnpbiosids,
.probe = snd_cs423x_pnpbios_detect,
.remove = __devexit_p(snd_cs423x_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_cs423x_pnp_suspend,
.resume = snd_cs423x_pnp_resume,
#endif
};
static int __devinit snd_cs423x_pnpc_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
static int dev;
struct snd_card *card;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
res = snd_cs423x_card_new(dev, &card);
if (res < 0)
return res;
if ((res = snd_card_cs423x_pnpc(dev, card->private_data, pcard, pid)) < 0) {
printk(KERN_ERR "isapnp detection failed and probing for " IDENT
" is not supported\n");
snd_card_free(card);
return res;
}
snd_card_set_dev(card, &pcard->card->dev);
if ((res = snd_cs423x_probe(card, dev)) < 0) {
snd_card_free(card);
return res;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
static void __devexit snd_cs423x_pnpc_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_cs423x_pnpc_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
return snd_cs423x_suspend(pnp_get_card_drvdata(pcard));
}
static int snd_cs423x_pnpc_resume(struct pnp_card_link *pcard)
{
return snd_cs423x_resume(pnp_get_card_drvdata(pcard));
}
#endif
static struct pnp_card_driver cs423x_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = CS423X_ISAPNP_DRIVER,
.id_table = snd_cs423x_pnpids,
.probe = snd_cs423x_pnpc_detect,
.remove = __devexit_p(snd_cs423x_pnpc_remove),
#ifdef CONFIG_PM
.suspend = snd_cs423x_pnpc_suspend,
.resume = snd_cs423x_pnpc_resume,
#endif
};
#endif /* CONFIG_PNP */
static int __init alsa_card_cs423x_init(void)
{
int err;
err = isa_register_driver(&cs423x_isa_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_driver(&cs423x_pnp_driver);
if (!err)
pnp_registered = 1;
err = pnp_register_card_driver(&cs423x_pnpc_driver);
if (!err)
pnpc_registered = 1;
if (pnp_registered)
err = 0;
if (isa_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_cs423x_exit(void)
{
#ifdef CONFIG_PNP
if (pnpc_registered)
pnp_unregister_card_driver(&cs423x_pnpc_driver);
if (pnp_registered)
pnp_unregister_driver(&cs423x_pnp_driver);
if (isa_registered)
#endif
isa_unregister_driver(&cs423x_isa_driver);
}
module_init(alsa_card_cs423x_init)
module_exit(alsa_card_cs423x_exit)
| gpl-2.0 |
cristianomatos/android_kernel_google_msm | drivers/staging/usbip/usbip_event.c | 5333 | 2853 | /*
* Copyright (C) 2003-2008 Takahiro Hirofuchi
*
* This 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 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/kthread.h>
#include <linux/export.h>
#include "usbip_common.h"
static int event_handler(struct usbip_device *ud)
{
usbip_dbg_eh("enter\n");
/*
* Events are handled by only this thread.
*/
while (usbip_event_happened(ud)) {
usbip_dbg_eh("pending event %lx\n", ud->event);
/*
* NOTE: shutdown must come first.
* Shutdown the device.
*/
if (ud->event & USBIP_EH_SHUTDOWN) {
ud->eh_ops.shutdown(ud);
ud->event &= ~USBIP_EH_SHUTDOWN;
}
/* Reset the device. */
if (ud->event & USBIP_EH_RESET) {
ud->eh_ops.reset(ud);
ud->event &= ~USBIP_EH_RESET;
}
/* Mark the device as unusable. */
if (ud->event & USBIP_EH_UNUSABLE) {
ud->eh_ops.unusable(ud);
ud->event &= ~USBIP_EH_UNUSABLE;
}
/* Stop the error handler. */
if (ud->event & USBIP_EH_BYE)
return -1;
}
return 0;
}
static int event_handler_loop(void *data)
{
struct usbip_device *ud = data;
while (!kthread_should_stop()) {
wait_event_interruptible(ud->eh_waitq,
usbip_event_happened(ud) ||
kthread_should_stop());
usbip_dbg_eh("wakeup\n");
if (event_handler(ud) < 0)
break;
}
return 0;
}
int usbip_start_eh(struct usbip_device *ud)
{
init_waitqueue_head(&ud->eh_waitq);
ud->event = 0;
ud->eh = kthread_run(event_handler_loop, ud, "usbip_eh");
if (IS_ERR(ud->eh)) {
pr_warning("Unable to start control thread\n");
return PTR_ERR(ud->eh);
}
return 0;
}
EXPORT_SYMBOL_GPL(usbip_start_eh);
void usbip_stop_eh(struct usbip_device *ud)
{
if (ud->eh == current)
return; /* do not wait for myself */
kthread_stop(ud->eh);
usbip_dbg_eh("usbip_eh has finished\n");
}
EXPORT_SYMBOL_GPL(usbip_stop_eh);
void usbip_event_add(struct usbip_device *ud, unsigned long event)
{
spin_lock(&ud->lock);
ud->event |= event;
wake_up(&ud->eh_waitq);
spin_unlock(&ud->lock);
}
EXPORT_SYMBOL_GPL(usbip_event_add);
int usbip_event_happened(struct usbip_device *ud)
{
int happened = 0;
spin_lock(&ud->lock);
if (ud->event != 0)
happened = 1;
spin_unlock(&ud->lock);
return happened;
}
EXPORT_SYMBOL_GPL(usbip_event_happened);
| gpl-2.0 |
TeamBliss-Devices/android_kernel_lge_hammerhead | drivers/media/rc/keymaps/rc-pinnacle-grey.c | 7637 | 1995 | /* pinnacle-grey.h - Keytable for pinnacle_grey Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
static struct rc_map_table pinnacle_grey[] = {
{ 0x3a, KEY_0 },
{ 0x31, KEY_1 },
{ 0x32, KEY_2 },
{ 0x33, KEY_3 },
{ 0x34, KEY_4 },
{ 0x35, KEY_5 },
{ 0x36, KEY_6 },
{ 0x37, KEY_7 },
{ 0x38, KEY_8 },
{ 0x39, KEY_9 },
{ 0x2f, KEY_POWER },
{ 0x2e, KEY_P },
{ 0x1f, KEY_L },
{ 0x2b, KEY_I },
{ 0x2d, KEY_SCREEN },
{ 0x1e, KEY_ZOOM },
{ 0x1b, KEY_VOLUMEUP },
{ 0x0f, KEY_VOLUMEDOWN },
{ 0x17, KEY_CHANNELUP },
{ 0x1c, KEY_CHANNELDOWN },
{ 0x25, KEY_INFO },
{ 0x3c, KEY_MUTE },
{ 0x3d, KEY_LEFT },
{ 0x3b, KEY_RIGHT },
{ 0x3f, KEY_UP },
{ 0x3e, KEY_DOWN },
{ 0x1a, KEY_ENTER },
{ 0x1d, KEY_MENU },
{ 0x19, KEY_AGAIN },
{ 0x16, KEY_PREVIOUSSONG },
{ 0x13, KEY_NEXTSONG },
{ 0x15, KEY_PAUSE },
{ 0x0e, KEY_REWIND },
{ 0x0d, KEY_PLAY },
{ 0x0b, KEY_STOP },
{ 0x07, KEY_FORWARD },
{ 0x27, KEY_RECORD },
{ 0x26, KEY_TUNER },
{ 0x29, KEY_TEXT },
{ 0x2a, KEY_MEDIA },
{ 0x18, KEY_EPG },
};
static struct rc_map_list pinnacle_grey_map = {
.map = {
.scan = pinnacle_grey,
.size = ARRAY_SIZE(pinnacle_grey),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_PINNACLE_GREY,
}
};
static int __init init_rc_map_pinnacle_grey(void)
{
return rc_map_register(&pinnacle_grey_map);
}
static void __exit exit_rc_map_pinnacle_grey(void)
{
rc_map_unregister(&pinnacle_grey_map);
}
module_init(init_rc_map_pinnacle_grey)
module_exit(exit_rc_map_pinnacle_grey)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
baran0119/kernel_samsung_baffinlitexx | drivers/media/rc/keymaps/rc-kworld-plus-tv-analog.c | 7637 | 2631 | /* kworld-plus-tv-analog.h - Keytable for kworld_plus_tv_analog Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
/* Kworld Plus TV Analog Lite PCI IR
Mauro Carvalho Chehab <mchehab@infradead.org>
*/
static struct rc_map_table kworld_plus_tv_analog[] = {
{ 0x0c, KEY_MEDIA }, /* Kworld key */
{ 0x16, KEY_CLOSECD }, /* -> ) */
{ 0x1d, KEY_POWER2 },
{ 0x00, KEY_1 },
{ 0x01, KEY_2 },
{ 0x02, KEY_3 }, /* Two keys have the same code: 3 and left */
{ 0x03, KEY_4 }, /* Two keys have the same code: 3 and right */
{ 0x04, KEY_5 },
{ 0x05, KEY_6 },
{ 0x06, KEY_7 },
{ 0x07, KEY_8 },
{ 0x08, KEY_9 },
{ 0x0a, KEY_0 },
{ 0x09, KEY_AGAIN },
{ 0x14, KEY_MUTE },
{ 0x20, KEY_UP },
{ 0x21, KEY_DOWN },
{ 0x0b, KEY_ENTER },
{ 0x10, KEY_CHANNELUP },
{ 0x11, KEY_CHANNELDOWN },
/* Couldn't map key left/key right since those
conflict with '3' and '4' scancodes
I dunno what the original driver does
*/
{ 0x13, KEY_VOLUMEUP },
{ 0x12, KEY_VOLUMEDOWN },
/* The lower part of the IR
There are several duplicated keycodes there.
Most of them conflict with digits.
Add mappings just to the unused scancodes.
Somehow, the original driver has a way to know,
but this doesn't seem to be on some GPIO.
Also, it is not related to the time between keyup
and keydown.
*/
{ 0x19, KEY_TIME}, /* Timeshift */
{ 0x1a, KEY_STOP},
{ 0x1b, KEY_RECORD},
{ 0x22, KEY_TEXT},
{ 0x15, KEY_AUDIO}, /* ((*)) */
{ 0x0f, KEY_ZOOM},
{ 0x1c, KEY_CAMERA}, /* snapshot */
{ 0x18, KEY_RED}, /* B */
{ 0x23, KEY_GREEN}, /* C */
};
static struct rc_map_list kworld_plus_tv_analog_map = {
.map = {
.scan = kworld_plus_tv_analog,
.size = ARRAY_SIZE(kworld_plus_tv_analog),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_KWORLD_PLUS_TV_ANALOG,
}
};
static int __init init_rc_map_kworld_plus_tv_analog(void)
{
return rc_map_register(&kworld_plus_tv_analog_map);
}
static void __exit exit_rc_map_kworld_plus_tv_analog(void)
{
rc_map_unregister(&kworld_plus_tv_analog_map);
}
module_init(init_rc_map_kworld_plus_tv_analog)
module_exit(exit_rc_map_kworld_plus_tv_analog)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
xboxfanj/android_kernel_oneplus_one | drivers/media/rc/keymaps/rc-behold-columbus.c | 7637 | 2967 | /* behold-columbus.h - Keytable for behold_columbus Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
/* Beholder Intl. Ltd. 2008
* Dmitry Belimov d.belimov@google.com
* Keytable is used by BeholdTV Columbus
* The "ascii-art picture" below (in comments, first row
* is the keycode in hex, and subsequent row(s) shows
* the button labels (several variants when appropriate)
* helps to descide which keycodes to assign to the buttons.
*/
static struct rc_map_table behold_columbus[] = {
/* 0x13 0x11 0x1C 0x12 *
* Mute Source TV/FM Power *
* */
{ 0x13, KEY_MUTE },
{ 0x11, KEY_VIDEO },
{ 0x1C, KEY_TUNER }, /* KEY_TV/KEY_RADIO */
{ 0x12, KEY_POWER },
/* 0x01 0x02 0x03 0x0D *
* 1 2 3 Stereo *
* *
* 0x04 0x05 0x06 0x19 *
* 4 5 6 Snapshot *
* *
* 0x07 0x08 0x09 0x10 *
* 7 8 9 Zoom *
* */
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
{ 0x03, KEY_3 },
{ 0x0D, KEY_SETUP }, /* Setup key */
{ 0x04, KEY_4 },
{ 0x05, KEY_5 },
{ 0x06, KEY_6 },
{ 0x19, KEY_CAMERA }, /* Snapshot key */
{ 0x07, KEY_7 },
{ 0x08, KEY_8 },
{ 0x09, KEY_9 },
{ 0x10, KEY_ZOOM },
/* 0x0A 0x00 0x0B 0x0C *
* RECALL 0 ChannelUp VolumeUp *
* */
{ 0x0A, KEY_AGAIN },
{ 0x00, KEY_0 },
{ 0x0B, KEY_CHANNELUP },
{ 0x0C, KEY_VOLUMEUP },
/* 0x1B 0x1D 0x15 0x18 *
* Timeshift Record ChannelDown VolumeDown *
* */
{ 0x1B, KEY_TIME },
{ 0x1D, KEY_RECORD },
{ 0x15, KEY_CHANNELDOWN },
{ 0x18, KEY_VOLUMEDOWN },
/* 0x0E 0x1E 0x0F 0x1A *
* Stop Pause Previouse Next *
* */
{ 0x0E, KEY_STOP },
{ 0x1E, KEY_PAUSE },
{ 0x0F, KEY_PREVIOUS },
{ 0x1A, KEY_NEXT },
};
static struct rc_map_list behold_columbus_map = {
.map = {
.scan = behold_columbus,
.size = ARRAY_SIZE(behold_columbus),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_BEHOLD_COLUMBUS,
}
};
static int __init init_rc_map_behold_columbus(void)
{
return rc_map_register(&behold_columbus_map);
}
static void __exit exit_rc_map_behold_columbus(void)
{
rc_map_unregister(&behold_columbus_map);
}
module_init(init_rc_map_behold_columbus)
module_exit(exit_rc_map_behold_columbus)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Hani-K/Simplicity_Kernel_Exynos5433_LL | drivers/media/rc/keymaps/rc-genius-tvgo-a11mce.c | 7637 | 2432 | /* genius-tvgo-a11mce.h - Keytable for genius_tvgo_a11mce Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
/*
* Remote control for the Genius TVGO A11MCE
* Adrian Pardini <pardo.bsso@gmail.com>
*/
static struct rc_map_table genius_tvgo_a11mce[] = {
/* Keys 0 to 9 */
{ 0x48, KEY_0 },
{ 0x09, KEY_1 },
{ 0x1d, KEY_2 },
{ 0x1f, KEY_3 },
{ 0x19, KEY_4 },
{ 0x1b, KEY_5 },
{ 0x11, KEY_6 },
{ 0x17, KEY_7 },
{ 0x12, KEY_8 },
{ 0x16, KEY_9 },
{ 0x54, KEY_RECORD }, /* recording */
{ 0x06, KEY_MUTE }, /* mute */
{ 0x10, KEY_POWER },
{ 0x40, KEY_LAST }, /* recall */
{ 0x4c, KEY_CHANNELUP }, /* channel / program + */
{ 0x00, KEY_CHANNELDOWN }, /* channel / program - */
{ 0x0d, KEY_VOLUMEUP },
{ 0x15, KEY_VOLUMEDOWN },
{ 0x4d, KEY_OK }, /* also labeled as Pause */
{ 0x1c, KEY_ZOOM }, /* full screen and Stop*/
{ 0x02, KEY_MODE }, /* AV Source or Rewind*/
{ 0x04, KEY_LIST }, /* -/-- */
/* small arrows above numbers */
{ 0x1a, KEY_NEXT }, /* also Fast Forward */
{ 0x0e, KEY_PREVIOUS }, /* also Rewind */
/* these are in a rather non standard layout and have
an alternate name written */
{ 0x1e, KEY_UP }, /* Video Setting */
{ 0x0a, KEY_DOWN }, /* Video Default */
{ 0x05, KEY_CAMERA }, /* Snapshot */
{ 0x0c, KEY_RIGHT }, /* Hide Panel */
/* Four buttons without label */
{ 0x49, KEY_RED },
{ 0x0b, KEY_GREEN },
{ 0x13, KEY_YELLOW },
{ 0x50, KEY_BLUE },
};
static struct rc_map_list genius_tvgo_a11mce_map = {
.map = {
.scan = genius_tvgo_a11mce,
.size = ARRAY_SIZE(genius_tvgo_a11mce),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_GENIUS_TVGO_A11MCE,
}
};
static int __init init_rc_map_genius_tvgo_a11mce(void)
{
return rc_map_register(&genius_tvgo_a11mce_map);
}
static void __exit exit_rc_map_genius_tvgo_a11mce(void)
{
rc_map_unregister(&genius_tvgo_a11mce_map);
}
module_init(init_rc_map_genius_tvgo_a11mce)
module_exit(exit_rc_map_genius_tvgo_a11mce)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
wiki05/android_kernel_oneplus_msm8994 | drivers/media/rc/keymaps/rc-avermedia-a16d.c | 7637 | 1828 | /* avermedia-a16d.h - Keytable for avermedia_a16d Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
static struct rc_map_table avermedia_a16d[] = {
{ 0x20, KEY_LIST},
{ 0x00, KEY_POWER},
{ 0x28, KEY_1},
{ 0x18, KEY_2},
{ 0x38, KEY_3},
{ 0x24, KEY_4},
{ 0x14, KEY_5},
{ 0x34, KEY_6},
{ 0x2c, KEY_7},
{ 0x1c, KEY_8},
{ 0x3c, KEY_9},
{ 0x12, KEY_SUBTITLE},
{ 0x22, KEY_0},
{ 0x32, KEY_REWIND},
{ 0x3a, KEY_SHUFFLE},
{ 0x02, KEY_PRINT},
{ 0x11, KEY_CHANNELDOWN},
{ 0x31, KEY_CHANNELUP},
{ 0x0c, KEY_ZOOM},
{ 0x1e, KEY_VOLUMEDOWN},
{ 0x3e, KEY_VOLUMEUP},
{ 0x0a, KEY_MUTE},
{ 0x04, KEY_AUDIO},
{ 0x26, KEY_RECORD},
{ 0x06, KEY_PLAY},
{ 0x36, KEY_STOP},
{ 0x16, KEY_PAUSE},
{ 0x2e, KEY_REWIND},
{ 0x0e, KEY_FASTFORWARD},
{ 0x30, KEY_TEXT},
{ 0x21, KEY_GREEN},
{ 0x01, KEY_BLUE},
{ 0x08, KEY_EPG},
{ 0x2a, KEY_MENU},
};
static struct rc_map_list avermedia_a16d_map = {
.map = {
.scan = avermedia_a16d,
.size = ARRAY_SIZE(avermedia_a16d),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_AVERMEDIA_A16D,
}
};
static int __init init_rc_map_avermedia_a16d(void)
{
return rc_map_register(&avermedia_a16d_map);
}
static void __exit exit_rc_map_avermedia_a16d(void)
{
rc_map_unregister(&avermedia_a16d_map);
}
module_init(init_rc_map_avermedia_a16d)
module_exit(exit_rc_map_avermedia_a16d)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.