repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
iyahman/android_kernel_samsung_jf | drivers/media/video/msm/imx074_reg.c | 1757 | 3058 | /* Copyright (c) 2010, 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 "imx074.h"
const struct reg_struct_init imx074_reg_init[1] = {
{
/* PLL setting */
0x02, /* pll_divider 0x0305 */
0x4B, /* plstatim 0x302b */
0x03, /* reg_3024 */
0x00, /* image_orientation 0x0101 */
0x80, /* vndmy_ablmgshlmt 0x300a*/
0x08, /* y_opbaddr_start_di 3014*/
0x37, /* 0x3015*/
0x01, /* 0x301c*/
0x05, /* 0x302c*/
0x26, /* 0x3031*/
0x60, /* 0x3041*/
0x24, /* 0x3051 CLK DIV*/
0x34, /* 0x3053*/
0xc0, /* 0x3057*/
0x09, /* 0x305c*/
0x07, /* 0x305d */
0x30, /* 0x3060 */
0x00, /* 0x3065 */
0x08, /* 0x30aa */
0x1c, /* 0x30ab */
0x32, /* 0x30b0 */
0x83, /* 0x30b2 */
0x04, /* 0x30d3 */
0x78, /* 0x3106 */
0x82, /* 0x310c */
0x05, /* 0x3304 */
0x04, /* 0x3305 */
0x11, /* 0x3306 */
0x02, /* 0x3307 */
0x0c, /* 0x3308 */
0x06, /* 0x3309 */
0x08, /* 0x330a */
0x04, /* 0x330b */
0x08, /* 0x330c */
0x06, /* 0x330d */
0x01, /* 0x330f */
0x00, /* 0x3381 */
}
};
/* Preview / Snapshot register settings */
const struct reg_struct imx074_reg_pat[2] = {
/*preview*/
{
0x2D, /*pll_multiplier*/
0x06, /*frame_length_lines_hi 0x0340*/
0x2D, /* frame_length_lines_lo 0x0341*/
0x00, /* y_addr_start 0x347 */
0x2F, /* y_add_end 0x034b */
0x08, /* x_output_size_msb0x034c */
0x38, /* x_output_size_lsb0x034d */
0x06, /* y_output_size_msb0x034e */
0x18, /* y_output_size_lsb0x034f */
0x01, /* x_even_inc 0x0381 */
0x03, /* x_odd_inc 0x0383 */
0x01, /* y_even_inc 0x0385 */
0x03, /* y_odd_inc 0x0387 */
0x80, /* hmodeadd0x3001 */
0x16, /* vmodeadd0x3016 */
0x24, /* vapplinepos_startox3069*/
0x53, /* vapplinepos_end306b*/
0x00,/* shutter 0x3086 */
0x80, /* haddave 0x30e8 */
0x83, /* lanesel 0x3301 */
},
/*snapshot*/
{
0x26, /*pll_multiplier*/
0x0C, /* frame_length_lines_hi 0x0340*/
0x90, /* frame_length_lines_lo 0x0341*/
0x00, /* y_addr_start 0x347 */
0x2F, /* y_add_end 0x034b */
0x10, /* x_output_size_msb0x034c */
0x70, /* x_output_size_lsb0x034d */
0x0c, /* y_output_size_msb0x034e */
0x30, /* y_output_size_lsb0x034f */
0x01, /* x_even_inc 0x0381 */
0x01, /* x_odd_inc 0x0383 */
0x01, /* y_even_inc 0x0385 */
0x01, /* y_odd_inc 0x0387 */
0x00, /* hmodeadd0x3001 */
0x06, /* vmodeadd0x3016 */
0x24, /* vapplinepos_startox3069*/
0x53, /* vapplinepos_end306b*/
0x00, /* shutter 0x3086 */
0x00, /* haddave 0x30e8 */
0x03, /* lanesel 0x3301 */
}
};
struct imx074_reg imx074_regs = {
.reg_pat_init = &imx074_reg_init[0],
.reg_pat = &imx074_reg_pat[0],
};
| gpl-2.0 |
wurikiji/ttFS | src/drivers/gpu/drm/nouveau/core/engine/vp/nve0.c | 2269 | 3346 | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <core/falcon.h>
#include <engine/vp.h>
struct nve0_vp_priv {
struct nouveau_falcon base;
};
/*******************************************************************************
* VP object classes
******************************************************************************/
static struct nouveau_oclass
nve0_vp_sclass[] = {
{ 0x95b2, &nouveau_object_ofuncs },
{},
};
/*******************************************************************************
* PVP context
******************************************************************************/
static struct nouveau_oclass
nve0_vp_cclass = {
.handle = NV_ENGCTX(VP, 0xe0),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = _nouveau_falcon_context_ctor,
.dtor = _nouveau_falcon_context_dtor,
.init = _nouveau_falcon_context_init,
.fini = _nouveau_falcon_context_fini,
.rd32 = _nouveau_falcon_context_rd32,
.wr32 = _nouveau_falcon_context_wr32,
},
};
/*******************************************************************************
* PVP engine/subdev functions
******************************************************************************/
static int
nve0_vp_init(struct nouveau_object *object)
{
struct nve0_vp_priv *priv = (void *)object;
int ret;
ret = nouveau_falcon_init(&priv->base);
if (ret)
return ret;
nv_wr32(priv, 0x085010, 0x0000fff2);
nv_wr32(priv, 0x08501c, 0x0000fff2);
return 0;
}
static int
nve0_vp_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nve0_vp_priv *priv;
int ret;
ret = nouveau_falcon_create(parent, engine, oclass, 0x085000, true,
"PVP", "vp", &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
nv_subdev(priv)->unit = 0x00020000;
nv_engine(priv)->cclass = &nve0_vp_cclass;
nv_engine(priv)->sclass = nve0_vp_sclass;
return 0;
}
struct nouveau_oclass
nve0_vp_oclass = {
.handle = NV_ENGINE(VP, 0xe0),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nve0_vp_ctor,
.dtor = _nouveau_falcon_dtor,
.init = nve0_vp_init,
.fini = _nouveau_falcon_fini,
.rd32 = _nouveau_falcon_rd32,
.wr32 = _nouveau_falcon_wr32,
},
};
| gpl-2.0 |
dsb9938/GT-N8013-JB-Kernel | drivers/staging/vme/bridges/vme_tsi148.c | 2525 | 71479 | /*
* Support for the Tundra TSI148 VME-PCI Bridge Chip
*
* Author: Martyn Welch <martyn.welch@ge.com>
* Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc.
*
* Based on work by Tom Armistead and Ajit Prem
* Copyright 2004 Motorola Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/pci.h>
#include <linux/poll.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include "../vme.h"
#include "../vme_bridge.h"
#include "vme_tsi148.h"
static int __init tsi148_init(void);
static int tsi148_probe(struct pci_dev *, const struct pci_device_id *);
static void tsi148_remove(struct pci_dev *);
static void __exit tsi148_exit(void);
/* Module parameter */
static int err_chk;
static int geoid;
static char driver_name[] = "vme_tsi148";
static DEFINE_PCI_DEVICE_TABLE(tsi148_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_TUNDRA, PCI_DEVICE_ID_TUNDRA_TSI148) },
{ },
};
static struct pci_driver tsi148_driver = {
.name = driver_name,
.id_table = tsi148_ids,
.probe = tsi148_probe,
.remove = tsi148_remove,
};
static void reg_join(unsigned int high, unsigned int low,
unsigned long long *variable)
{
*variable = (unsigned long long)high << 32;
*variable |= (unsigned long long)low;
}
static void reg_split(unsigned long long variable, unsigned int *high,
unsigned int *low)
{
*low = (unsigned int)variable & 0xFFFFFFFF;
*high = (unsigned int)(variable >> 32);
}
/*
* Wakes up DMA queue.
*/
static u32 tsi148_DMA_irqhandler(struct tsi148_driver *bridge,
int channel_mask)
{
u32 serviced = 0;
if (channel_mask & TSI148_LCSR_INTS_DMA0S) {
wake_up(&bridge->dma_queue[0]);
serviced |= TSI148_LCSR_INTC_DMA0C;
}
if (channel_mask & TSI148_LCSR_INTS_DMA1S) {
wake_up(&bridge->dma_queue[1]);
serviced |= TSI148_LCSR_INTC_DMA1C;
}
return serviced;
}
/*
* Wake up location monitor queue
*/
static u32 tsi148_LM_irqhandler(struct tsi148_driver *bridge, u32 stat)
{
int i;
u32 serviced = 0;
for (i = 0; i < 4; i++) {
if (stat & TSI148_LCSR_INTS_LMS[i]) {
/* We only enable interrupts if the callback is set */
bridge->lm_callback[i](i);
serviced |= TSI148_LCSR_INTC_LMC[i];
}
}
return serviced;
}
/*
* Wake up mail box queue.
*
* XXX This functionality is not exposed up though API.
*/
static u32 tsi148_MB_irqhandler(struct vme_bridge *tsi148_bridge, u32 stat)
{
int i;
u32 val;
u32 serviced = 0;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
for (i = 0; i < 4; i++) {
if (stat & TSI148_LCSR_INTS_MBS[i]) {
val = ioread32be(bridge->base + TSI148_GCSR_MBOX[i]);
dev_err(tsi148_bridge->parent, "VME Mailbox %d received"
": 0x%x\n", i, val);
serviced |= TSI148_LCSR_INTC_MBC[i];
}
}
return serviced;
}
/*
* Display error & status message when PERR (PCI) exception interrupt occurs.
*/
static u32 tsi148_PERR_irqhandler(struct vme_bridge *tsi148_bridge)
{
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
dev_err(tsi148_bridge->parent, "PCI Exception at address: 0x%08x:%08x, "
"attributes: %08x\n",
ioread32be(bridge->base + TSI148_LCSR_EDPAU),
ioread32be(bridge->base + TSI148_LCSR_EDPAL),
ioread32be(bridge->base + TSI148_LCSR_EDPAT));
dev_err(tsi148_bridge->parent, "PCI-X attribute reg: %08x, PCI-X split "
"completion reg: %08x\n",
ioread32be(bridge->base + TSI148_LCSR_EDPXA),
ioread32be(bridge->base + TSI148_LCSR_EDPXS));
iowrite32be(TSI148_LCSR_EDPAT_EDPCL, bridge->base + TSI148_LCSR_EDPAT);
return TSI148_LCSR_INTC_PERRC;
}
/*
* Save address and status when VME error interrupt occurs.
*/
static u32 tsi148_VERR_irqhandler(struct vme_bridge *tsi148_bridge)
{
unsigned int error_addr_high, error_addr_low;
unsigned long long error_addr;
u32 error_attrib;
struct vme_bus_error *error;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
error_addr_high = ioread32be(bridge->base + TSI148_LCSR_VEAU);
error_addr_low = ioread32be(bridge->base + TSI148_LCSR_VEAL);
error_attrib = ioread32be(bridge->base + TSI148_LCSR_VEAT);
reg_join(error_addr_high, error_addr_low, &error_addr);
/* Check for exception register overflow (we have lost error data) */
if (error_attrib & TSI148_LCSR_VEAT_VEOF) {
dev_err(tsi148_bridge->parent, "VME Bus Exception Overflow "
"Occurred\n");
}
error = kmalloc(sizeof(struct vme_bus_error), GFP_ATOMIC);
if (error) {
error->address = error_addr;
error->attributes = error_attrib;
list_add_tail(&error->list, &tsi148_bridge->vme_errors);
} else {
dev_err(tsi148_bridge->parent, "Unable to alloc memory for "
"VMEbus Error reporting\n");
dev_err(tsi148_bridge->parent, "VME Bus Error at address: "
"0x%llx, attributes: %08x\n", error_addr, error_attrib);
}
/* Clear Status */
iowrite32be(TSI148_LCSR_VEAT_VESCL, bridge->base + TSI148_LCSR_VEAT);
return TSI148_LCSR_INTC_VERRC;
}
/*
* Wake up IACK queue.
*/
static u32 tsi148_IACK_irqhandler(struct tsi148_driver *bridge)
{
wake_up(&bridge->iack_queue);
return TSI148_LCSR_INTC_IACKC;
}
/*
* Calling VME bus interrupt callback if provided.
*/
static u32 tsi148_VIRQ_irqhandler(struct vme_bridge *tsi148_bridge,
u32 stat)
{
int vec, i, serviced = 0;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
for (i = 7; i > 0; i--) {
if (stat & (1 << i)) {
/*
* Note: Even though the registers are defined as
* 32-bits in the spec, we only want to issue 8-bit
* IACK cycles on the bus, read from offset 3.
*/
vec = ioread8(bridge->base + TSI148_LCSR_VIACK[i] + 3);
vme_irq_handler(tsi148_bridge, i, vec);
serviced |= (1 << i);
}
}
return serviced;
}
/*
* Top level interrupt handler. Clears appropriate interrupt status bits and
* then calls appropriate sub handler(s).
*/
static irqreturn_t tsi148_irqhandler(int irq, void *ptr)
{
u32 stat, enable, serviced = 0;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = ptr;
bridge = tsi148_bridge->driver_priv;
/* Determine which interrupts are unmasked and set */
enable = ioread32be(bridge->base + TSI148_LCSR_INTEO);
stat = ioread32be(bridge->base + TSI148_LCSR_INTS);
/* Only look at unmasked interrupts */
stat &= enable;
if (unlikely(!stat))
return IRQ_NONE;
/* Call subhandlers as appropriate */
/* DMA irqs */
if (stat & (TSI148_LCSR_INTS_DMA1S | TSI148_LCSR_INTS_DMA0S))
serviced |= tsi148_DMA_irqhandler(bridge, stat);
/* Location monitor irqs */
if (stat & (TSI148_LCSR_INTS_LM3S | TSI148_LCSR_INTS_LM2S |
TSI148_LCSR_INTS_LM1S | TSI148_LCSR_INTS_LM0S))
serviced |= tsi148_LM_irqhandler(bridge, stat);
/* Mail box irqs */
if (stat & (TSI148_LCSR_INTS_MB3S | TSI148_LCSR_INTS_MB2S |
TSI148_LCSR_INTS_MB1S | TSI148_LCSR_INTS_MB0S))
serviced |= tsi148_MB_irqhandler(tsi148_bridge, stat);
/* PCI bus error */
if (stat & TSI148_LCSR_INTS_PERRS)
serviced |= tsi148_PERR_irqhandler(tsi148_bridge);
/* VME bus error */
if (stat & TSI148_LCSR_INTS_VERRS)
serviced |= tsi148_VERR_irqhandler(tsi148_bridge);
/* IACK irq */
if (stat & TSI148_LCSR_INTS_IACKS)
serviced |= tsi148_IACK_irqhandler(bridge);
/* VME bus irqs */
if (stat & (TSI148_LCSR_INTS_IRQ7S | TSI148_LCSR_INTS_IRQ6S |
TSI148_LCSR_INTS_IRQ5S | TSI148_LCSR_INTS_IRQ4S |
TSI148_LCSR_INTS_IRQ3S | TSI148_LCSR_INTS_IRQ2S |
TSI148_LCSR_INTS_IRQ1S))
serviced |= tsi148_VIRQ_irqhandler(tsi148_bridge, stat);
/* Clear serviced interrupts */
iowrite32be(serviced, bridge->base + TSI148_LCSR_INTC);
return IRQ_HANDLED;
}
static int tsi148_irq_init(struct vme_bridge *tsi148_bridge)
{
int result;
unsigned int tmp;
struct pci_dev *pdev;
struct tsi148_driver *bridge;
pdev = container_of(tsi148_bridge->parent, struct pci_dev, dev);
bridge = tsi148_bridge->driver_priv;
/* Initialise list for VME bus errors */
INIT_LIST_HEAD(&tsi148_bridge->vme_errors);
mutex_init(&tsi148_bridge->irq_mtx);
result = request_irq(pdev->irq,
tsi148_irqhandler,
IRQF_SHARED,
driver_name, tsi148_bridge);
if (result) {
dev_err(tsi148_bridge->parent, "Can't get assigned pci irq "
"vector %02X\n", pdev->irq);
return result;
}
/* Enable and unmask interrupts */
tmp = TSI148_LCSR_INTEO_DMA1EO | TSI148_LCSR_INTEO_DMA0EO |
TSI148_LCSR_INTEO_MB3EO | TSI148_LCSR_INTEO_MB2EO |
TSI148_LCSR_INTEO_MB1EO | TSI148_LCSR_INTEO_MB0EO |
TSI148_LCSR_INTEO_PERREO | TSI148_LCSR_INTEO_VERREO |
TSI148_LCSR_INTEO_IACKEO;
/* This leaves the following interrupts masked.
* TSI148_LCSR_INTEO_VIEEO
* TSI148_LCSR_INTEO_SYSFLEO
* TSI148_LCSR_INTEO_ACFLEO
*/
/* Don't enable Location Monitor interrupts here - they will be
* enabled when the location monitors are properly configured and
* a callback has been attached.
* TSI148_LCSR_INTEO_LM0EO
* TSI148_LCSR_INTEO_LM1EO
* TSI148_LCSR_INTEO_LM2EO
* TSI148_LCSR_INTEO_LM3EO
*/
/* Don't enable VME interrupts until we add a handler, else the board
* will respond to it and we don't want that unless it knows how to
* properly deal with it.
* TSI148_LCSR_INTEO_IRQ7EO
* TSI148_LCSR_INTEO_IRQ6EO
* TSI148_LCSR_INTEO_IRQ5EO
* TSI148_LCSR_INTEO_IRQ4EO
* TSI148_LCSR_INTEO_IRQ3EO
* TSI148_LCSR_INTEO_IRQ2EO
* TSI148_LCSR_INTEO_IRQ1EO
*/
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO);
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN);
return 0;
}
static void tsi148_irq_exit(struct vme_bridge *tsi148_bridge,
struct pci_dev *pdev)
{
struct tsi148_driver *bridge = tsi148_bridge->driver_priv;
/* Turn off interrupts */
iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEO);
iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEN);
/* Clear all interrupts */
iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_INTC);
/* Detach interrupt handler */
free_irq(pdev->irq, tsi148_bridge);
}
/*
* Check to see if an IACk has been received, return true (1) or false (0).
*/
static int tsi148_iack_received(struct tsi148_driver *bridge)
{
u32 tmp;
tmp = ioread32be(bridge->base + TSI148_LCSR_VICR);
if (tmp & TSI148_LCSR_VICR_IRQS)
return 0;
else
return 1;
}
/*
* Configure VME interrupt
*/
static void tsi148_irq_set(struct vme_bridge *tsi148_bridge, int level,
int state, int sync)
{
struct pci_dev *pdev;
u32 tmp;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
/* We need to do the ordering differently for enabling and disabling */
if (state == 0) {
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN);
tmp &= ~TSI148_LCSR_INTEN_IRQEN[level - 1];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN);
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO);
tmp &= ~TSI148_LCSR_INTEO_IRQEO[level - 1];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO);
if (sync != 0) {
pdev = container_of(tsi148_bridge->parent,
struct pci_dev, dev);
synchronize_irq(pdev->irq);
}
} else {
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO);
tmp |= TSI148_LCSR_INTEO_IRQEO[level - 1];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO);
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN);
tmp |= TSI148_LCSR_INTEN_IRQEN[level - 1];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN);
}
}
/*
* Generate a VME bus interrupt at the requested level & vector. Wait for
* interrupt to be acked.
*/
static int tsi148_irq_generate(struct vme_bridge *tsi148_bridge, int level,
int statid)
{
u32 tmp;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
mutex_lock(&bridge->vme_int);
/* Read VICR register */
tmp = ioread32be(bridge->base + TSI148_LCSR_VICR);
/* Set Status/ID */
tmp = (tmp & ~TSI148_LCSR_VICR_STID_M) |
(statid & TSI148_LCSR_VICR_STID_M);
iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR);
/* Assert VMEbus IRQ */
tmp = tmp | TSI148_LCSR_VICR_IRQL[level];
iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR);
/* XXX Consider implementing a timeout? */
wait_event_interruptible(bridge->iack_queue,
tsi148_iack_received(bridge));
mutex_unlock(&bridge->vme_int);
return 0;
}
/*
* Find the first error in this address range
*/
static struct vme_bus_error *tsi148_find_error(struct vme_bridge *tsi148_bridge,
vme_address_t aspace, unsigned long long address, size_t count)
{
struct list_head *err_pos;
struct vme_bus_error *vme_err, *valid = NULL;
unsigned long long bound;
bound = address + count;
/*
* XXX We are currently not looking at the address space when parsing
* for errors. This is because parsing the Address Modifier Codes
* is going to be quite resource intensive to do properly. We
* should be OK just looking at the addresses and this is certainly
* much better than what we had before.
*/
err_pos = NULL;
/* Iterate through errors */
list_for_each(err_pos, &tsi148_bridge->vme_errors) {
vme_err = list_entry(err_pos, struct vme_bus_error, list);
if ((vme_err->address >= address) &&
(vme_err->address < bound)) {
valid = vme_err;
break;
}
}
return valid;
}
/*
* Clear errors in the provided address range.
*/
static void tsi148_clear_errors(struct vme_bridge *tsi148_bridge,
vme_address_t aspace, unsigned long long address, size_t count)
{
struct list_head *err_pos, *temp;
struct vme_bus_error *vme_err;
unsigned long long bound;
bound = address + count;
/*
* XXX We are currently not looking at the address space when parsing
* for errors. This is because parsing the Address Modifier Codes
* is going to be quite resource intensive to do properly. We
* should be OK just looking at the addresses and this is certainly
* much better than what we had before.
*/
err_pos = NULL;
/* Iterate through errors */
list_for_each_safe(err_pos, temp, &tsi148_bridge->vme_errors) {
vme_err = list_entry(err_pos, struct vme_bus_error, list);
if ((vme_err->address >= address) &&
(vme_err->address < bound)) {
list_del(err_pos);
kfree(vme_err);
}
}
}
/*
* Initialize a slave window with the requested attributes.
*/
static int tsi148_slave_set(struct vme_slave_resource *image, int enabled,
unsigned long long vme_base, unsigned long long size,
dma_addr_t pci_base, vme_address_t aspace, vme_cycle_t cycle)
{
unsigned int i, addr = 0, granularity = 0;
unsigned int temp_ctl = 0;
unsigned int vme_base_low, vme_base_high;
unsigned int vme_bound_low, vme_bound_high;
unsigned int pci_offset_low, pci_offset_high;
unsigned long long vme_bound, pci_offset;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = image->parent;
bridge = tsi148_bridge->driver_priv;
i = image->number;
switch (aspace) {
case VME_A16:
granularity = 0x10;
addr |= TSI148_LCSR_ITAT_AS_A16;
break;
case VME_A24:
granularity = 0x1000;
addr |= TSI148_LCSR_ITAT_AS_A24;
break;
case VME_A32:
granularity = 0x10000;
addr |= TSI148_LCSR_ITAT_AS_A32;
break;
case VME_A64:
granularity = 0x10000;
addr |= TSI148_LCSR_ITAT_AS_A64;
break;
case VME_CRCSR:
case VME_USER1:
case VME_USER2:
case VME_USER3:
case VME_USER4:
default:
dev_err(tsi148_bridge->parent, "Invalid address space\n");
return -EINVAL;
break;
}
/* Convert 64-bit variables to 2x 32-bit variables */
reg_split(vme_base, &vme_base_high, &vme_base_low);
/*
* Bound address is a valid address for the window, adjust
* accordingly
*/
vme_bound = vme_base + size - granularity;
reg_split(vme_bound, &vme_bound_high, &vme_bound_low);
pci_offset = (unsigned long long)pci_base - vme_base;
reg_split(pci_offset, &pci_offset_high, &pci_offset_low);
if (vme_base_low & (granularity - 1)) {
dev_err(tsi148_bridge->parent, "Invalid VME base alignment\n");
return -EINVAL;
}
if (vme_bound_low & (granularity - 1)) {
dev_err(tsi148_bridge->parent, "Invalid VME bound alignment\n");
return -EINVAL;
}
if (pci_offset_low & (granularity - 1)) {
dev_err(tsi148_bridge->parent, "Invalid PCI Offset "
"alignment\n");
return -EINVAL;
}
/* Disable while we are mucking around */
temp_ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
temp_ctl &= ~TSI148_LCSR_ITAT_EN;
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
/* Setup mapping */
iowrite32be(vme_base_high, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITSAU);
iowrite32be(vme_base_low, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITSAL);
iowrite32be(vme_bound_high, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITEAU);
iowrite32be(vme_bound_low, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITEAL);
iowrite32be(pci_offset_high, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITOFU);
iowrite32be(pci_offset_low, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITOFL);
/* Setup 2eSST speeds */
temp_ctl &= ~TSI148_LCSR_ITAT_2eSSTM_M;
switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) {
case VME_2eSST160:
temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_160;
break;
case VME_2eSST267:
temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_267;
break;
case VME_2eSST320:
temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_320;
break;
}
/* Setup cycle types */
temp_ctl &= ~(0x1F << 7);
if (cycle & VME_BLT)
temp_ctl |= TSI148_LCSR_ITAT_BLT;
if (cycle & VME_MBLT)
temp_ctl |= TSI148_LCSR_ITAT_MBLT;
if (cycle & VME_2eVME)
temp_ctl |= TSI148_LCSR_ITAT_2eVME;
if (cycle & VME_2eSST)
temp_ctl |= TSI148_LCSR_ITAT_2eSST;
if (cycle & VME_2eSSTB)
temp_ctl |= TSI148_LCSR_ITAT_2eSSTB;
/* Setup address space */
temp_ctl &= ~TSI148_LCSR_ITAT_AS_M;
temp_ctl |= addr;
temp_ctl &= ~0xF;
if (cycle & VME_SUPER)
temp_ctl |= TSI148_LCSR_ITAT_SUPR ;
if (cycle & VME_USER)
temp_ctl |= TSI148_LCSR_ITAT_NPRIV;
if (cycle & VME_PROG)
temp_ctl |= TSI148_LCSR_ITAT_PGM;
if (cycle & VME_DATA)
temp_ctl |= TSI148_LCSR_ITAT_DATA;
/* Write ctl reg without enable */
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
if (enabled)
temp_ctl |= TSI148_LCSR_ITAT_EN;
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
return 0;
}
/*
* Get slave window configuration.
*/
static int tsi148_slave_get(struct vme_slave_resource *image, int *enabled,
unsigned long long *vme_base, unsigned long long *size,
dma_addr_t *pci_base, vme_address_t *aspace, vme_cycle_t *cycle)
{
unsigned int i, granularity = 0, ctl = 0;
unsigned int vme_base_low, vme_base_high;
unsigned int vme_bound_low, vme_bound_high;
unsigned int pci_offset_low, pci_offset_high;
unsigned long long vme_bound, pci_offset;
struct tsi148_driver *bridge;
bridge = image->parent->driver_priv;
i = image->number;
/* Read registers */
ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
vme_base_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITSAU);
vme_base_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITSAL);
vme_bound_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITEAU);
vme_bound_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITEAL);
pci_offset_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITOFU);
pci_offset_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITOFL);
/* Convert 64-bit variables to 2x 32-bit variables */
reg_join(vme_base_high, vme_base_low, vme_base);
reg_join(vme_bound_high, vme_bound_low, &vme_bound);
reg_join(pci_offset_high, pci_offset_low, &pci_offset);
*pci_base = (dma_addr_t)vme_base + pci_offset;
*enabled = 0;
*aspace = 0;
*cycle = 0;
if (ctl & TSI148_LCSR_ITAT_EN)
*enabled = 1;
if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A16) {
granularity = 0x10;
*aspace |= VME_A16;
}
if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A24) {
granularity = 0x1000;
*aspace |= VME_A24;
}
if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A32) {
granularity = 0x10000;
*aspace |= VME_A32;
}
if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A64) {
granularity = 0x10000;
*aspace |= VME_A64;
}
/* Need granularity before we set the size */
*size = (unsigned long long)((vme_bound - *vme_base) + granularity);
if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_160)
*cycle |= VME_2eSST160;
if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_267)
*cycle |= VME_2eSST267;
if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_320)
*cycle |= VME_2eSST320;
if (ctl & TSI148_LCSR_ITAT_BLT)
*cycle |= VME_BLT;
if (ctl & TSI148_LCSR_ITAT_MBLT)
*cycle |= VME_MBLT;
if (ctl & TSI148_LCSR_ITAT_2eVME)
*cycle |= VME_2eVME;
if (ctl & TSI148_LCSR_ITAT_2eSST)
*cycle |= VME_2eSST;
if (ctl & TSI148_LCSR_ITAT_2eSSTB)
*cycle |= VME_2eSSTB;
if (ctl & TSI148_LCSR_ITAT_SUPR)
*cycle |= VME_SUPER;
if (ctl & TSI148_LCSR_ITAT_NPRIV)
*cycle |= VME_USER;
if (ctl & TSI148_LCSR_ITAT_PGM)
*cycle |= VME_PROG;
if (ctl & TSI148_LCSR_ITAT_DATA)
*cycle |= VME_DATA;
return 0;
}
/*
* Allocate and map PCI Resource
*/
static int tsi148_alloc_resource(struct vme_master_resource *image,
unsigned long long size)
{
unsigned long long existing_size;
int retval = 0;
struct pci_dev *pdev;
struct vme_bridge *tsi148_bridge;
tsi148_bridge = image->parent;
pdev = container_of(tsi148_bridge->parent, struct pci_dev, dev);
existing_size = (unsigned long long)(image->bus_resource.end -
image->bus_resource.start);
/* If the existing size is OK, return */
if ((size != 0) && (existing_size == (size - 1)))
return 0;
if (existing_size != 0) {
iounmap(image->kern_base);
image->kern_base = NULL;
kfree(image->bus_resource.name);
release_resource(&image->bus_resource);
memset(&image->bus_resource, 0, sizeof(struct resource));
}
/* Exit here if size is zero */
if (size == 0)
return 0;
if (image->bus_resource.name == NULL) {
image->bus_resource.name = kmalloc(VMENAMSIZ+3, GFP_ATOMIC);
if (image->bus_resource.name == NULL) {
dev_err(tsi148_bridge->parent, "Unable to allocate "
"memory for resource name\n");
retval = -ENOMEM;
goto err_name;
}
}
sprintf((char *)image->bus_resource.name, "%s.%d", tsi148_bridge->name,
image->number);
image->bus_resource.start = 0;
image->bus_resource.end = (unsigned long)size;
image->bus_resource.flags = IORESOURCE_MEM;
retval = pci_bus_alloc_resource(pdev->bus,
&image->bus_resource, size, size, PCIBIOS_MIN_MEM,
0, NULL, NULL);
if (retval) {
dev_err(tsi148_bridge->parent, "Failed to allocate mem "
"resource for window %d size 0x%lx start 0x%lx\n",
image->number, (unsigned long)size,
(unsigned long)image->bus_resource.start);
goto err_resource;
}
image->kern_base = ioremap_nocache(
image->bus_resource.start, size);
if (image->kern_base == NULL) {
dev_err(tsi148_bridge->parent, "Failed to remap resource\n");
retval = -ENOMEM;
goto err_remap;
}
return 0;
err_remap:
release_resource(&image->bus_resource);
err_resource:
kfree(image->bus_resource.name);
memset(&image->bus_resource, 0, sizeof(struct resource));
err_name:
return retval;
}
/*
* Free and unmap PCI Resource
*/
static void tsi148_free_resource(struct vme_master_resource *image)
{
iounmap(image->kern_base);
image->kern_base = NULL;
release_resource(&image->bus_resource);
kfree(image->bus_resource.name);
memset(&image->bus_resource, 0, sizeof(struct resource));
}
/*
* Set the attributes of an outbound window.
*/
static int tsi148_master_set(struct vme_master_resource *image, int enabled,
unsigned long long vme_base, unsigned long long size,
vme_address_t aspace, vme_cycle_t cycle, vme_width_t dwidth)
{
int retval = 0;
unsigned int i;
unsigned int temp_ctl = 0;
unsigned int pci_base_low, pci_base_high;
unsigned int pci_bound_low, pci_bound_high;
unsigned int vme_offset_low, vme_offset_high;
unsigned long long pci_bound, vme_offset, pci_base;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = image->parent;
bridge = tsi148_bridge->driver_priv;
/* Verify input data */
if (vme_base & 0xFFFF) {
dev_err(tsi148_bridge->parent, "Invalid VME Window "
"alignment\n");
retval = -EINVAL;
goto err_window;
}
if ((size == 0) && (enabled != 0)) {
dev_err(tsi148_bridge->parent, "Size must be non-zero for "
"enabled windows\n");
retval = -EINVAL;
goto err_window;
}
spin_lock(&image->lock);
/* Let's allocate the resource here rather than further up the stack as
* it avoids pushing loads of bus dependent stuff up the stack. If size
* is zero, any existing resource will be freed.
*/
retval = tsi148_alloc_resource(image, size);
if (retval) {
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Unable to allocate memory for "
"resource\n");
goto err_res;
}
if (size == 0) {
pci_base = 0;
pci_bound = 0;
vme_offset = 0;
} else {
pci_base = (unsigned long long)image->bus_resource.start;
/*
* Bound address is a valid address for the window, adjust
* according to window granularity.
*/
pci_bound = pci_base + (size - 0x10000);
vme_offset = vme_base - pci_base;
}
/* Convert 64-bit variables to 2x 32-bit variables */
reg_split(pci_base, &pci_base_high, &pci_base_low);
reg_split(pci_bound, &pci_bound_high, &pci_bound_low);
reg_split(vme_offset, &vme_offset_high, &vme_offset_low);
if (pci_base_low & 0xFFFF) {
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Invalid PCI base alignment\n");
retval = -EINVAL;
goto err_gran;
}
if (pci_bound_low & 0xFFFF) {
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Invalid PCI bound alignment\n");
retval = -EINVAL;
goto err_gran;
}
if (vme_offset_low & 0xFFFF) {
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Invalid VME Offset "
"alignment\n");
retval = -EINVAL;
goto err_gran;
}
i = image->number;
/* Disable while we are mucking around */
temp_ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
temp_ctl &= ~TSI148_LCSR_OTAT_EN;
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
/* Setup 2eSST speeds */
temp_ctl &= ~TSI148_LCSR_OTAT_2eSSTM_M;
switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) {
case VME_2eSST160:
temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_160;
break;
case VME_2eSST267:
temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_267;
break;
case VME_2eSST320:
temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_320;
break;
}
/* Setup cycle types */
if (cycle & VME_BLT) {
temp_ctl &= ~TSI148_LCSR_OTAT_TM_M;
temp_ctl |= TSI148_LCSR_OTAT_TM_BLT;
}
if (cycle & VME_MBLT) {
temp_ctl &= ~TSI148_LCSR_OTAT_TM_M;
temp_ctl |= TSI148_LCSR_OTAT_TM_MBLT;
}
if (cycle & VME_2eVME) {
temp_ctl &= ~TSI148_LCSR_OTAT_TM_M;
temp_ctl |= TSI148_LCSR_OTAT_TM_2eVME;
}
if (cycle & VME_2eSST) {
temp_ctl &= ~TSI148_LCSR_OTAT_TM_M;
temp_ctl |= TSI148_LCSR_OTAT_TM_2eSST;
}
if (cycle & VME_2eSSTB) {
dev_warn(tsi148_bridge->parent, "Currently not setting "
"Broadcast Select Registers\n");
temp_ctl &= ~TSI148_LCSR_OTAT_TM_M;
temp_ctl |= TSI148_LCSR_OTAT_TM_2eSSTB;
}
/* Setup data width */
temp_ctl &= ~TSI148_LCSR_OTAT_DBW_M;
switch (dwidth) {
case VME_D16:
temp_ctl |= TSI148_LCSR_OTAT_DBW_16;
break;
case VME_D32:
temp_ctl |= TSI148_LCSR_OTAT_DBW_32;
break;
default:
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Invalid data width\n");
retval = -EINVAL;
goto err_dwidth;
}
/* Setup address space */
temp_ctl &= ~TSI148_LCSR_OTAT_AMODE_M;
switch (aspace) {
case VME_A16:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_A16;
break;
case VME_A24:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_A24;
break;
case VME_A32:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_A32;
break;
case VME_A64:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_A64;
break;
case VME_CRCSR:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_CRCSR;
break;
case VME_USER1:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER1;
break;
case VME_USER2:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER2;
break;
case VME_USER3:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER3;
break;
case VME_USER4:
temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER4;
break;
default:
spin_unlock(&image->lock);
dev_err(tsi148_bridge->parent, "Invalid address space\n");
retval = -EINVAL;
goto err_aspace;
break;
}
temp_ctl &= ~(3<<4);
if (cycle & VME_SUPER)
temp_ctl |= TSI148_LCSR_OTAT_SUP;
if (cycle & VME_PROG)
temp_ctl |= TSI148_LCSR_OTAT_PGM;
/* Setup mapping */
iowrite32be(pci_base_high, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAU);
iowrite32be(pci_base_low, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAL);
iowrite32be(pci_bound_high, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTEAU);
iowrite32be(pci_bound_low, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTEAL);
iowrite32be(vme_offset_high, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTOFU);
iowrite32be(vme_offset_low, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTOFL);
/* Write ctl reg without enable */
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
if (enabled)
temp_ctl |= TSI148_LCSR_OTAT_EN;
iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
spin_unlock(&image->lock);
return 0;
err_aspace:
err_dwidth:
err_gran:
tsi148_free_resource(image);
err_res:
err_window:
return retval;
}
/*
* Set the attributes of an outbound window.
*
* XXX Not parsing prefetch information.
*/
static int __tsi148_master_get(struct vme_master_resource *image, int *enabled,
unsigned long long *vme_base, unsigned long long *size,
vme_address_t *aspace, vme_cycle_t *cycle, vme_width_t *dwidth)
{
unsigned int i, ctl;
unsigned int pci_base_low, pci_base_high;
unsigned int pci_bound_low, pci_bound_high;
unsigned int vme_offset_low, vme_offset_high;
unsigned long long pci_base, pci_bound, vme_offset;
struct tsi148_driver *bridge;
bridge = image->parent->driver_priv;
i = image->number;
ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
pci_base_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAU);
pci_base_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAL);
pci_bound_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTEAU);
pci_bound_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTEAL);
vme_offset_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTOFU);
vme_offset_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTOFL);
/* Convert 64-bit variables to 2x 32-bit variables */
reg_join(pci_base_high, pci_base_low, &pci_base);
reg_join(pci_bound_high, pci_bound_low, &pci_bound);
reg_join(vme_offset_high, vme_offset_low, &vme_offset);
*vme_base = pci_base + vme_offset;
*size = (unsigned long long)(pci_bound - pci_base) + 0x10000;
*enabled = 0;
*aspace = 0;
*cycle = 0;
*dwidth = 0;
if (ctl & TSI148_LCSR_OTAT_EN)
*enabled = 1;
/* Setup address space */
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A16)
*aspace |= VME_A16;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A24)
*aspace |= VME_A24;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A32)
*aspace |= VME_A32;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A64)
*aspace |= VME_A64;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_CRCSR)
*aspace |= VME_CRCSR;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER1)
*aspace |= VME_USER1;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER2)
*aspace |= VME_USER2;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER3)
*aspace |= VME_USER3;
if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER4)
*aspace |= VME_USER4;
/* Setup 2eSST speeds */
if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_160)
*cycle |= VME_2eSST160;
if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_267)
*cycle |= VME_2eSST267;
if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_320)
*cycle |= VME_2eSST320;
/* Setup cycle types */
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_SCT)
*cycle |= VME_SCT;
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_BLT)
*cycle |= VME_BLT;
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_MBLT)
*cycle |= VME_MBLT;
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eVME)
*cycle |= VME_2eVME;
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSST)
*cycle |= VME_2eSST;
if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSSTB)
*cycle |= VME_2eSSTB;
if (ctl & TSI148_LCSR_OTAT_SUP)
*cycle |= VME_SUPER;
else
*cycle |= VME_USER;
if (ctl & TSI148_LCSR_OTAT_PGM)
*cycle |= VME_PROG;
else
*cycle |= VME_DATA;
/* Setup data width */
if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_16)
*dwidth = VME_D16;
if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_32)
*dwidth = VME_D32;
return 0;
}
static int tsi148_master_get(struct vme_master_resource *image, int *enabled,
unsigned long long *vme_base, unsigned long long *size,
vme_address_t *aspace, vme_cycle_t *cycle, vme_width_t *dwidth)
{
int retval;
spin_lock(&image->lock);
retval = __tsi148_master_get(image, enabled, vme_base, size, aspace,
cycle, dwidth);
spin_unlock(&image->lock);
return retval;
}
static ssize_t tsi148_master_read(struct vme_master_resource *image, void *buf,
size_t count, loff_t offset)
{
int retval, enabled;
unsigned long long vme_base, size;
vme_address_t aspace;
vme_cycle_t cycle;
vme_width_t dwidth;
struct vme_bus_error *vme_err = NULL;
struct vme_bridge *tsi148_bridge;
tsi148_bridge = image->parent;
spin_lock(&image->lock);
memcpy_fromio(buf, image->kern_base + offset, (unsigned int)count);
retval = count;
if (!err_chk)
goto skip_chk;
__tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, &cycle,
&dwidth);
vme_err = tsi148_find_error(tsi148_bridge, aspace, vme_base + offset,
count);
if (vme_err != NULL) {
dev_err(image->parent->parent, "First VME read error detected "
"an at address 0x%llx\n", vme_err->address);
retval = vme_err->address - (vme_base + offset);
/* Clear down save errors in this address range */
tsi148_clear_errors(tsi148_bridge, aspace, vme_base + offset,
count);
}
skip_chk:
spin_unlock(&image->lock);
return retval;
}
static ssize_t tsi148_master_write(struct vme_master_resource *image, void *buf,
size_t count, loff_t offset)
{
int retval = 0, enabled;
unsigned long long vme_base, size;
vme_address_t aspace;
vme_cycle_t cycle;
vme_width_t dwidth;
struct vme_bus_error *vme_err = NULL;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = image->parent;
bridge = tsi148_bridge->driver_priv;
spin_lock(&image->lock);
memcpy_toio(image->kern_base + offset, buf, (unsigned int)count);
retval = count;
/*
* Writes are posted. We need to do a read on the VME bus to flush out
* all of the writes before we check for errors. We can't guarantee
* that reading the data we have just written is safe. It is believed
* that there isn't any read, write re-ordering, so we can read any
* location in VME space, so lets read the Device ID from the tsi148's
* own registers as mapped into CR/CSR space.
*
* We check for saved errors in the written address range/space.
*/
if (!err_chk)
goto skip_chk;
/*
* Get window info first, to maximise the time that the buffers may
* fluch on their own
*/
__tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, &cycle,
&dwidth);
ioread16(bridge->flush_image->kern_base + 0x7F000);
vme_err = tsi148_find_error(tsi148_bridge, aspace, vme_base + offset,
count);
if (vme_err != NULL) {
dev_warn(tsi148_bridge->parent, "First VME write error detected"
" an at address 0x%llx\n", vme_err->address);
retval = vme_err->address - (vme_base + offset);
/* Clear down save errors in this address range */
tsi148_clear_errors(tsi148_bridge, aspace, vme_base + offset,
count);
}
skip_chk:
spin_unlock(&image->lock);
return retval;
}
/*
* Perform an RMW cycle on the VME bus.
*
* Requires a previously configured master window, returns final value.
*/
static unsigned int tsi148_master_rmw(struct vme_master_resource *image,
unsigned int mask, unsigned int compare, unsigned int swap,
loff_t offset)
{
unsigned long long pci_addr;
unsigned int pci_addr_high, pci_addr_low;
u32 tmp, result;
int i;
struct tsi148_driver *bridge;
bridge = image->parent->driver_priv;
/* Find the PCI address that maps to the desired VME address */
i = image->number;
/* Locking as we can only do one of these at a time */
mutex_lock(&bridge->vme_rmw);
/* Lock image */
spin_lock(&image->lock);
pci_addr_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAU);
pci_addr_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTSAL);
reg_join(pci_addr_high, pci_addr_low, &pci_addr);
reg_split(pci_addr + offset, &pci_addr_high, &pci_addr_low);
/* Configure registers */
iowrite32be(mask, bridge->base + TSI148_LCSR_RMWEN);
iowrite32be(compare, bridge->base + TSI148_LCSR_RMWC);
iowrite32be(swap, bridge->base + TSI148_LCSR_RMWS);
iowrite32be(pci_addr_high, bridge->base + TSI148_LCSR_RMWAU);
iowrite32be(pci_addr_low, bridge->base + TSI148_LCSR_RMWAL);
/* Enable RMW */
tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL);
tmp |= TSI148_LCSR_VMCTRL_RMWEN;
iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL);
/* Kick process off with a read to the required address. */
result = ioread32be(image->kern_base + offset);
/* Disable RMW */
tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL);
tmp &= ~TSI148_LCSR_VMCTRL_RMWEN;
iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL);
spin_unlock(&image->lock);
mutex_unlock(&bridge->vme_rmw);
return result;
}
static int tsi148_dma_set_vme_src_attributes(struct device *dev, u32 *attr,
vme_address_t aspace, vme_cycle_t cycle, vme_width_t dwidth)
{
/* Setup 2eSST speeds */
switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) {
case VME_2eSST160:
*attr |= TSI148_LCSR_DSAT_2eSSTM_160;
break;
case VME_2eSST267:
*attr |= TSI148_LCSR_DSAT_2eSSTM_267;
break;
case VME_2eSST320:
*attr |= TSI148_LCSR_DSAT_2eSSTM_320;
break;
}
/* Setup cycle types */
if (cycle & VME_SCT)
*attr |= TSI148_LCSR_DSAT_TM_SCT;
if (cycle & VME_BLT)
*attr |= TSI148_LCSR_DSAT_TM_BLT;
if (cycle & VME_MBLT)
*attr |= TSI148_LCSR_DSAT_TM_MBLT;
if (cycle & VME_2eVME)
*attr |= TSI148_LCSR_DSAT_TM_2eVME;
if (cycle & VME_2eSST)
*attr |= TSI148_LCSR_DSAT_TM_2eSST;
if (cycle & VME_2eSSTB) {
dev_err(dev, "Currently not setting Broadcast Select "
"Registers\n");
*attr |= TSI148_LCSR_DSAT_TM_2eSSTB;
}
/* Setup data width */
switch (dwidth) {
case VME_D16:
*attr |= TSI148_LCSR_DSAT_DBW_16;
break;
case VME_D32:
*attr |= TSI148_LCSR_DSAT_DBW_32;
break;
default:
dev_err(dev, "Invalid data width\n");
return -EINVAL;
}
/* Setup address space */
switch (aspace) {
case VME_A16:
*attr |= TSI148_LCSR_DSAT_AMODE_A16;
break;
case VME_A24:
*attr |= TSI148_LCSR_DSAT_AMODE_A24;
break;
case VME_A32:
*attr |= TSI148_LCSR_DSAT_AMODE_A32;
break;
case VME_A64:
*attr |= TSI148_LCSR_DSAT_AMODE_A64;
break;
case VME_CRCSR:
*attr |= TSI148_LCSR_DSAT_AMODE_CRCSR;
break;
case VME_USER1:
*attr |= TSI148_LCSR_DSAT_AMODE_USER1;
break;
case VME_USER2:
*attr |= TSI148_LCSR_DSAT_AMODE_USER2;
break;
case VME_USER3:
*attr |= TSI148_LCSR_DSAT_AMODE_USER3;
break;
case VME_USER4:
*attr |= TSI148_LCSR_DSAT_AMODE_USER4;
break;
default:
dev_err(dev, "Invalid address space\n");
return -EINVAL;
break;
}
if (cycle & VME_SUPER)
*attr |= TSI148_LCSR_DSAT_SUP;
if (cycle & VME_PROG)
*attr |= TSI148_LCSR_DSAT_PGM;
return 0;
}
static int tsi148_dma_set_vme_dest_attributes(struct device *dev, u32 *attr,
vme_address_t aspace, vme_cycle_t cycle, vme_width_t dwidth)
{
/* Setup 2eSST speeds */
switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) {
case VME_2eSST160:
*attr |= TSI148_LCSR_DDAT_2eSSTM_160;
break;
case VME_2eSST267:
*attr |= TSI148_LCSR_DDAT_2eSSTM_267;
break;
case VME_2eSST320:
*attr |= TSI148_LCSR_DDAT_2eSSTM_320;
break;
}
/* Setup cycle types */
if (cycle & VME_SCT)
*attr |= TSI148_LCSR_DDAT_TM_SCT;
if (cycle & VME_BLT)
*attr |= TSI148_LCSR_DDAT_TM_BLT;
if (cycle & VME_MBLT)
*attr |= TSI148_LCSR_DDAT_TM_MBLT;
if (cycle & VME_2eVME)
*attr |= TSI148_LCSR_DDAT_TM_2eVME;
if (cycle & VME_2eSST)
*attr |= TSI148_LCSR_DDAT_TM_2eSST;
if (cycle & VME_2eSSTB) {
dev_err(dev, "Currently not setting Broadcast Select "
"Registers\n");
*attr |= TSI148_LCSR_DDAT_TM_2eSSTB;
}
/* Setup data width */
switch (dwidth) {
case VME_D16:
*attr |= TSI148_LCSR_DDAT_DBW_16;
break;
case VME_D32:
*attr |= TSI148_LCSR_DDAT_DBW_32;
break;
default:
dev_err(dev, "Invalid data width\n");
return -EINVAL;
}
/* Setup address space */
switch (aspace) {
case VME_A16:
*attr |= TSI148_LCSR_DDAT_AMODE_A16;
break;
case VME_A24:
*attr |= TSI148_LCSR_DDAT_AMODE_A24;
break;
case VME_A32:
*attr |= TSI148_LCSR_DDAT_AMODE_A32;
break;
case VME_A64:
*attr |= TSI148_LCSR_DDAT_AMODE_A64;
break;
case VME_CRCSR:
*attr |= TSI148_LCSR_DDAT_AMODE_CRCSR;
break;
case VME_USER1:
*attr |= TSI148_LCSR_DDAT_AMODE_USER1;
break;
case VME_USER2:
*attr |= TSI148_LCSR_DDAT_AMODE_USER2;
break;
case VME_USER3:
*attr |= TSI148_LCSR_DDAT_AMODE_USER3;
break;
case VME_USER4:
*attr |= TSI148_LCSR_DDAT_AMODE_USER4;
break;
default:
dev_err(dev, "Invalid address space\n");
return -EINVAL;
break;
}
if (cycle & VME_SUPER)
*attr |= TSI148_LCSR_DDAT_SUP;
if (cycle & VME_PROG)
*attr |= TSI148_LCSR_DDAT_PGM;
return 0;
}
/*
* Add a link list descriptor to the list
*/
static int tsi148_dma_list_add(struct vme_dma_list *list,
struct vme_dma_attr *src, struct vme_dma_attr *dest, size_t count)
{
struct tsi148_dma_entry *entry, *prev;
u32 address_high, address_low;
struct vme_dma_pattern *pattern_attr;
struct vme_dma_pci *pci_attr;
struct vme_dma_vme *vme_attr;
dma_addr_t desc_ptr;
int retval = 0;
struct vme_bridge *tsi148_bridge;
tsi148_bridge = list->parent->parent;
/* Descriptor must be aligned on 64-bit boundaries */
entry = kmalloc(sizeof(struct tsi148_dma_entry), GFP_KERNEL);
if (entry == NULL) {
dev_err(tsi148_bridge->parent, "Failed to allocate memory for "
"dma resource structure\n");
retval = -ENOMEM;
goto err_mem;
}
/* Test descriptor alignment */
if ((unsigned long)&entry->descriptor & 0x7) {
dev_err(tsi148_bridge->parent, "Descriptor not aligned to 8 "
"byte boundary as required: %p\n",
&entry->descriptor);
retval = -EINVAL;
goto err_align;
}
/* Given we are going to fill out the structure, we probably don't
* need to zero it, but better safe than sorry for now.
*/
memset(&entry->descriptor, 0, sizeof(struct tsi148_dma_descriptor));
/* Fill out source part */
switch (src->type) {
case VME_DMA_PATTERN:
pattern_attr = src->private;
entry->descriptor.dsal = pattern_attr->pattern;
entry->descriptor.dsat = TSI148_LCSR_DSAT_TYP_PAT;
/* Default behaviour is 32 bit pattern */
if (pattern_attr->type & VME_DMA_PATTERN_BYTE)
entry->descriptor.dsat |= TSI148_LCSR_DSAT_PSZ;
/* It seems that the default behaviour is to increment */
if ((pattern_attr->type & VME_DMA_PATTERN_INCREMENT) == 0)
entry->descriptor.dsat |= TSI148_LCSR_DSAT_NIN;
break;
case VME_DMA_PCI:
pci_attr = src->private;
reg_split((unsigned long long)pci_attr->address, &address_high,
&address_low);
entry->descriptor.dsau = address_high;
entry->descriptor.dsal = address_low;
entry->descriptor.dsat = TSI148_LCSR_DSAT_TYP_PCI;
break;
case VME_DMA_VME:
vme_attr = src->private;
reg_split((unsigned long long)vme_attr->address, &address_high,
&address_low);
entry->descriptor.dsau = address_high;
entry->descriptor.dsal = address_low;
entry->descriptor.dsat = TSI148_LCSR_DSAT_TYP_VME;
retval = tsi148_dma_set_vme_src_attributes(
tsi148_bridge->parent, &entry->descriptor.dsat,
vme_attr->aspace, vme_attr->cycle, vme_attr->dwidth);
if (retval < 0)
goto err_source;
break;
default:
dev_err(tsi148_bridge->parent, "Invalid source type\n");
retval = -EINVAL;
goto err_source;
break;
}
/* Assume last link - this will be over-written by adding another */
entry->descriptor.dnlau = 0;
entry->descriptor.dnlal = TSI148_LCSR_DNLAL_LLA;
/* Fill out destination part */
switch (dest->type) {
case VME_DMA_PCI:
pci_attr = dest->private;
reg_split((unsigned long long)pci_attr->address, &address_high,
&address_low);
entry->descriptor.ddau = address_high;
entry->descriptor.ddal = address_low;
entry->descriptor.ddat = TSI148_LCSR_DDAT_TYP_PCI;
break;
case VME_DMA_VME:
vme_attr = dest->private;
reg_split((unsigned long long)vme_attr->address, &address_high,
&address_low);
entry->descriptor.ddau = address_high;
entry->descriptor.ddal = address_low;
entry->descriptor.ddat = TSI148_LCSR_DDAT_TYP_VME;
retval = tsi148_dma_set_vme_dest_attributes(
tsi148_bridge->parent, &entry->descriptor.ddat,
vme_attr->aspace, vme_attr->cycle, vme_attr->dwidth);
if (retval < 0)
goto err_dest;
break;
default:
dev_err(tsi148_bridge->parent, "Invalid destination type\n");
retval = -EINVAL;
goto err_dest;
break;
}
/* Fill out count */
entry->descriptor.dcnt = (u32)count;
/* Add to list */
list_add_tail(&entry->list, &list->entries);
/* Fill out previous descriptors "Next Address" */
if (entry->list.prev != &list->entries) {
prev = list_entry(entry->list.prev, struct tsi148_dma_entry,
list);
/* We need the bus address for the pointer */
desc_ptr = virt_to_bus(&entry->descriptor);
reg_split(desc_ptr, &prev->descriptor.dnlau,
&prev->descriptor.dnlal);
}
return 0;
err_dest:
err_source:
err_align:
kfree(entry);
err_mem:
return retval;
}
/*
* Check to see if the provided DMA channel is busy.
*/
static int tsi148_dma_busy(struct vme_bridge *tsi148_bridge, int channel)
{
u32 tmp;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
tmp = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] +
TSI148_LCSR_OFFSET_DSTA);
if (tmp & TSI148_LCSR_DSTA_BSY)
return 0;
else
return 1;
}
/*
* Execute a previously generated link list
*
* XXX Need to provide control register configuration.
*/
static int tsi148_dma_list_exec(struct vme_dma_list *list)
{
struct vme_dma_resource *ctrlr;
int channel, retval = 0;
struct tsi148_dma_entry *entry;
dma_addr_t bus_addr;
u32 bus_addr_high, bus_addr_low;
u32 val, dctlreg = 0;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
ctrlr = list->parent;
tsi148_bridge = ctrlr->parent;
bridge = tsi148_bridge->driver_priv;
mutex_lock(&ctrlr->mtx);
channel = ctrlr->number;
if (!list_empty(&ctrlr->running)) {
/*
* XXX We have an active DMA transfer and currently haven't
* sorted out the mechanism for "pending" DMA transfers.
* Return busy.
*/
/* Need to add to pending here */
mutex_unlock(&ctrlr->mtx);
return -EBUSY;
} else {
list_add(&list->list, &ctrlr->running);
}
/* Get first bus address and write into registers */
entry = list_first_entry(&list->entries, struct tsi148_dma_entry,
list);
bus_addr = virt_to_bus(&entry->descriptor);
mutex_unlock(&ctrlr->mtx);
reg_split(bus_addr, &bus_addr_high, &bus_addr_low);
iowrite32be(bus_addr_high, bridge->base +
TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAU);
iowrite32be(bus_addr_low, bridge->base +
TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAL);
/* Start the operation */
iowrite32be(dctlreg | TSI148_LCSR_DCTL_DGO, bridge->base +
TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DCTL);
wait_event_interruptible(bridge->dma_queue[channel],
tsi148_dma_busy(ctrlr->parent, channel));
/*
* Read status register, this register is valid until we kick off a
* new transfer.
*/
val = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] +
TSI148_LCSR_OFFSET_DSTA);
if (val & TSI148_LCSR_DSTA_VBE) {
dev_err(tsi148_bridge->parent, "DMA Error. DSTA=%08X\n", val);
retval = -EIO;
}
/* Remove list from running list */
mutex_lock(&ctrlr->mtx);
list_del(&list->list);
mutex_unlock(&ctrlr->mtx);
return retval;
}
/*
* Clean up a previously generated link list
*
* We have a separate function, don't assume that the chain can't be reused.
*/
static int tsi148_dma_list_empty(struct vme_dma_list *list)
{
struct list_head *pos, *temp;
struct tsi148_dma_entry *entry;
/* detach and free each entry */
list_for_each_safe(pos, temp, &list->entries) {
list_del(pos);
entry = list_entry(pos, struct tsi148_dma_entry, list);
kfree(entry);
}
return 0;
}
/*
* All 4 location monitors reside at the same base - this is therefore a
* system wide configuration.
*
* This does not enable the LM monitor - that should be done when the first
* callback is attached and disabled when the last callback is removed.
*/
static int tsi148_lm_set(struct vme_lm_resource *lm, unsigned long long lm_base,
vme_address_t aspace, vme_cycle_t cycle)
{
u32 lm_base_high, lm_base_low, lm_ctl = 0;
int i;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = lm->parent;
bridge = tsi148_bridge->driver_priv;
mutex_lock(&lm->mtx);
/* If we already have a callback attached, we can't move it! */
for (i = 0; i < lm->monitors; i++) {
if (bridge->lm_callback[i] != NULL) {
mutex_unlock(&lm->mtx);
dev_err(tsi148_bridge->parent, "Location monitor "
"callback attached, can't reset\n");
return -EBUSY;
}
}
switch (aspace) {
case VME_A16:
lm_ctl |= TSI148_LCSR_LMAT_AS_A16;
break;
case VME_A24:
lm_ctl |= TSI148_LCSR_LMAT_AS_A24;
break;
case VME_A32:
lm_ctl |= TSI148_LCSR_LMAT_AS_A32;
break;
case VME_A64:
lm_ctl |= TSI148_LCSR_LMAT_AS_A64;
break;
default:
mutex_unlock(&lm->mtx);
dev_err(tsi148_bridge->parent, "Invalid address space\n");
return -EINVAL;
break;
}
if (cycle & VME_SUPER)
lm_ctl |= TSI148_LCSR_LMAT_SUPR ;
if (cycle & VME_USER)
lm_ctl |= TSI148_LCSR_LMAT_NPRIV;
if (cycle & VME_PROG)
lm_ctl |= TSI148_LCSR_LMAT_PGM;
if (cycle & VME_DATA)
lm_ctl |= TSI148_LCSR_LMAT_DATA;
reg_split(lm_base, &lm_base_high, &lm_base_low);
iowrite32be(lm_base_high, bridge->base + TSI148_LCSR_LMBAU);
iowrite32be(lm_base_low, bridge->base + TSI148_LCSR_LMBAL);
iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT);
mutex_unlock(&lm->mtx);
return 0;
}
/* Get configuration of the callback monitor and return whether it is enabled
* or disabled.
*/
static int tsi148_lm_get(struct vme_lm_resource *lm,
unsigned long long *lm_base, vme_address_t *aspace, vme_cycle_t *cycle)
{
u32 lm_base_high, lm_base_low, lm_ctl, enabled = 0;
struct tsi148_driver *bridge;
bridge = lm->parent->driver_priv;
mutex_lock(&lm->mtx);
lm_base_high = ioread32be(bridge->base + TSI148_LCSR_LMBAU);
lm_base_low = ioread32be(bridge->base + TSI148_LCSR_LMBAL);
lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT);
reg_join(lm_base_high, lm_base_low, lm_base);
if (lm_ctl & TSI148_LCSR_LMAT_EN)
enabled = 1;
if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A16)
*aspace |= VME_A16;
if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A24)
*aspace |= VME_A24;
if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A32)
*aspace |= VME_A32;
if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A64)
*aspace |= VME_A64;
if (lm_ctl & TSI148_LCSR_LMAT_SUPR)
*cycle |= VME_SUPER;
if (lm_ctl & TSI148_LCSR_LMAT_NPRIV)
*cycle |= VME_USER;
if (lm_ctl & TSI148_LCSR_LMAT_PGM)
*cycle |= VME_PROG;
if (lm_ctl & TSI148_LCSR_LMAT_DATA)
*cycle |= VME_DATA;
mutex_unlock(&lm->mtx);
return enabled;
}
/*
* Attach a callback to a specific location monitor.
*
* Callback will be passed the monitor triggered.
*/
static int tsi148_lm_attach(struct vme_lm_resource *lm, int monitor,
void (*callback)(int))
{
u32 lm_ctl, tmp;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *bridge;
tsi148_bridge = lm->parent;
bridge = tsi148_bridge->driver_priv;
mutex_lock(&lm->mtx);
/* Ensure that the location monitor is configured - need PGM or DATA */
lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT);
if ((lm_ctl & (TSI148_LCSR_LMAT_PGM | TSI148_LCSR_LMAT_DATA)) == 0) {
mutex_unlock(&lm->mtx);
dev_err(tsi148_bridge->parent, "Location monitor not properly "
"configured\n");
return -EINVAL;
}
/* Check that a callback isn't already attached */
if (bridge->lm_callback[monitor] != NULL) {
mutex_unlock(&lm->mtx);
dev_err(tsi148_bridge->parent, "Existing callback attached\n");
return -EBUSY;
}
/* Attach callback */
bridge->lm_callback[monitor] = callback;
/* Enable Location Monitor interrupt */
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN);
tmp |= TSI148_LCSR_INTEN_LMEN[monitor];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN);
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO);
tmp |= TSI148_LCSR_INTEO_LMEO[monitor];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO);
/* Ensure that global Location Monitor Enable set */
if ((lm_ctl & TSI148_LCSR_LMAT_EN) == 0) {
lm_ctl |= TSI148_LCSR_LMAT_EN;
iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT);
}
mutex_unlock(&lm->mtx);
return 0;
}
/*
* Detach a callback function forn a specific location monitor.
*/
static int tsi148_lm_detach(struct vme_lm_resource *lm, int monitor)
{
u32 lm_en, tmp;
struct tsi148_driver *bridge;
bridge = lm->parent->driver_priv;
mutex_lock(&lm->mtx);
/* Disable Location Monitor and ensure previous interrupts are clear */
lm_en = ioread32be(bridge->base + TSI148_LCSR_INTEN);
lm_en &= ~TSI148_LCSR_INTEN_LMEN[monitor];
iowrite32be(lm_en, bridge->base + TSI148_LCSR_INTEN);
tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO);
tmp &= ~TSI148_LCSR_INTEO_LMEO[monitor];
iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO);
iowrite32be(TSI148_LCSR_INTC_LMC[monitor],
bridge->base + TSI148_LCSR_INTC);
/* Detach callback */
bridge->lm_callback[monitor] = NULL;
/* If all location monitors disabled, disable global Location Monitor */
if ((lm_en & (TSI148_LCSR_INTS_LM0S | TSI148_LCSR_INTS_LM1S |
TSI148_LCSR_INTS_LM2S | TSI148_LCSR_INTS_LM3S)) == 0) {
tmp = ioread32be(bridge->base + TSI148_LCSR_LMAT);
tmp &= ~TSI148_LCSR_LMAT_EN;
iowrite32be(tmp, bridge->base + TSI148_LCSR_LMAT);
}
mutex_unlock(&lm->mtx);
return 0;
}
/*
* Determine Geographical Addressing
*/
static int tsi148_slot_get(struct vme_bridge *tsi148_bridge)
{
u32 slot = 0;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
if (!geoid) {
slot = ioread32be(bridge->base + TSI148_LCSR_VSTAT);
slot = slot & TSI148_LCSR_VSTAT_GA_M;
} else
slot = geoid;
return (int)slot;
}
static int __init tsi148_init(void)
{
return pci_register_driver(&tsi148_driver);
}
/*
* Configure CR/CSR space
*
* Access to the CR/CSR can be configured at power-up. The location of the
* CR/CSR registers in the CR/CSR address space is determined by the boards
* Auto-ID or Geographic address. This function ensures that the window is
* enabled at an offset consistent with the boards geopgraphic address.
*
* Each board has a 512kB window, with the highest 4kB being used for the
* boards registers, this means there is a fix length 508kB window which must
* be mapped onto PCI memory.
*/
static int tsi148_crcsr_init(struct vme_bridge *tsi148_bridge,
struct pci_dev *pdev)
{
u32 cbar, crat, vstat;
u32 crcsr_bus_high, crcsr_bus_low;
int retval;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
/* Allocate mem for CR/CSR image */
bridge->crcsr_kernel = pci_alloc_consistent(pdev, VME_CRCSR_BUF_SIZE,
&bridge->crcsr_bus);
if (bridge->crcsr_kernel == NULL) {
dev_err(tsi148_bridge->parent, "Failed to allocate memory for "
"CR/CSR image\n");
return -ENOMEM;
}
memset(bridge->crcsr_kernel, 0, VME_CRCSR_BUF_SIZE);
reg_split(bridge->crcsr_bus, &crcsr_bus_high, &crcsr_bus_low);
iowrite32be(crcsr_bus_high, bridge->base + TSI148_LCSR_CROU);
iowrite32be(crcsr_bus_low, bridge->base + TSI148_LCSR_CROL);
/* Ensure that the CR/CSR is configured at the correct offset */
cbar = ioread32be(bridge->base + TSI148_CBAR);
cbar = (cbar & TSI148_CRCSR_CBAR_M)>>3;
vstat = tsi148_slot_get(tsi148_bridge);
if (cbar != vstat) {
cbar = vstat;
dev_info(tsi148_bridge->parent, "Setting CR/CSR offset\n");
iowrite32be(cbar<<3, bridge->base + TSI148_CBAR);
}
dev_info(tsi148_bridge->parent, "CR/CSR Offset: %d\n", cbar);
crat = ioread32be(bridge->base + TSI148_LCSR_CRAT);
if (crat & TSI148_LCSR_CRAT_EN) {
dev_info(tsi148_bridge->parent, "Enabling CR/CSR space\n");
iowrite32be(crat | TSI148_LCSR_CRAT_EN,
bridge->base + TSI148_LCSR_CRAT);
} else
dev_info(tsi148_bridge->parent, "CR/CSR already enabled\n");
/* If we want flushed, error-checked writes, set up a window
* over the CR/CSR registers. We read from here to safely flush
* through VME writes.
*/
if (err_chk) {
retval = tsi148_master_set(bridge->flush_image, 1,
(vstat * 0x80000), 0x80000, VME_CRCSR, VME_SCT,
VME_D16);
if (retval)
dev_err(tsi148_bridge->parent, "Configuring flush image"
" failed\n");
}
return 0;
}
static void tsi148_crcsr_exit(struct vme_bridge *tsi148_bridge,
struct pci_dev *pdev)
{
u32 crat;
struct tsi148_driver *bridge;
bridge = tsi148_bridge->driver_priv;
/* Turn off CR/CSR space */
crat = ioread32be(bridge->base + TSI148_LCSR_CRAT);
iowrite32be(crat & ~TSI148_LCSR_CRAT_EN,
bridge->base + TSI148_LCSR_CRAT);
/* Free image */
iowrite32be(0, bridge->base + TSI148_LCSR_CROU);
iowrite32be(0, bridge->base + TSI148_LCSR_CROL);
pci_free_consistent(pdev, VME_CRCSR_BUF_SIZE, bridge->crcsr_kernel,
bridge->crcsr_bus);
}
static int tsi148_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
int retval, i, master_num;
u32 data;
struct list_head *pos = NULL;
struct vme_bridge *tsi148_bridge;
struct tsi148_driver *tsi148_device;
struct vme_master_resource *master_image;
struct vme_slave_resource *slave_image;
struct vme_dma_resource *dma_ctrlr;
struct vme_lm_resource *lm;
/* If we want to support more than one of each bridge, we need to
* dynamically generate this so we get one per device
*/
tsi148_bridge = kzalloc(sizeof(struct vme_bridge), GFP_KERNEL);
if (tsi148_bridge == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for device "
"structure\n");
retval = -ENOMEM;
goto err_struct;
}
tsi148_device = kzalloc(sizeof(struct tsi148_driver), GFP_KERNEL);
if (tsi148_device == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for device "
"structure\n");
retval = -ENOMEM;
goto err_driver;
}
tsi148_bridge->driver_priv = tsi148_device;
/* Enable the device */
retval = pci_enable_device(pdev);
if (retval) {
dev_err(&pdev->dev, "Unable to enable device\n");
goto err_enable;
}
/* Map Registers */
retval = pci_request_regions(pdev, driver_name);
if (retval) {
dev_err(&pdev->dev, "Unable to reserve resources\n");
goto err_resource;
}
/* map registers in BAR 0 */
tsi148_device->base = ioremap_nocache(pci_resource_start(pdev, 0),
4096);
if (!tsi148_device->base) {
dev_err(&pdev->dev, "Unable to remap CRG region\n");
retval = -EIO;
goto err_remap;
}
/* Check to see if the mapping worked out */
data = ioread32(tsi148_device->base + TSI148_PCFS_ID) & 0x0000FFFF;
if (data != PCI_VENDOR_ID_TUNDRA) {
dev_err(&pdev->dev, "CRG region check failed\n");
retval = -EIO;
goto err_test;
}
/* Initialize wait queues & mutual exclusion flags */
init_waitqueue_head(&tsi148_device->dma_queue[0]);
init_waitqueue_head(&tsi148_device->dma_queue[1]);
init_waitqueue_head(&tsi148_device->iack_queue);
mutex_init(&tsi148_device->vme_int);
mutex_init(&tsi148_device->vme_rmw);
tsi148_bridge->parent = &pdev->dev;
strcpy(tsi148_bridge->name, driver_name);
/* Setup IRQ */
retval = tsi148_irq_init(tsi148_bridge);
if (retval != 0) {
dev_err(&pdev->dev, "Chip Initialization failed.\n");
goto err_irq;
}
/* If we are going to flush writes, we need to read from the VME bus.
* We need to do this safely, thus we read the devices own CR/CSR
* register. To do this we must set up a window in CR/CSR space and
* hence have one less master window resource available.
*/
master_num = TSI148_MAX_MASTER;
if (err_chk) {
master_num--;
tsi148_device->flush_image =
kmalloc(sizeof(struct vme_master_resource), GFP_KERNEL);
if (tsi148_device->flush_image == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for "
"flush resource structure\n");
retval = -ENOMEM;
goto err_master;
}
tsi148_device->flush_image->parent = tsi148_bridge;
spin_lock_init(&tsi148_device->flush_image->lock);
tsi148_device->flush_image->locked = 1;
tsi148_device->flush_image->number = master_num;
tsi148_device->flush_image->address_attr = VME_A16 | VME_A24 |
VME_A32 | VME_A64;
tsi148_device->flush_image->cycle_attr = VME_SCT | VME_BLT |
VME_MBLT | VME_2eVME | VME_2eSST | VME_2eSSTB |
VME_2eSST160 | VME_2eSST267 | VME_2eSST320 | VME_SUPER |
VME_USER | VME_PROG | VME_DATA;
tsi148_device->flush_image->width_attr = VME_D16 | VME_D32;
memset(&tsi148_device->flush_image->bus_resource, 0,
sizeof(struct resource));
tsi148_device->flush_image->kern_base = NULL;
}
/* Add master windows to list */
INIT_LIST_HEAD(&tsi148_bridge->master_resources);
for (i = 0; i < master_num; i++) {
master_image = kmalloc(sizeof(struct vme_master_resource),
GFP_KERNEL);
if (master_image == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for "
"master resource structure\n");
retval = -ENOMEM;
goto err_master;
}
master_image->parent = tsi148_bridge;
spin_lock_init(&master_image->lock);
master_image->locked = 0;
master_image->number = i;
master_image->address_attr = VME_A16 | VME_A24 | VME_A32 |
VME_A64;
master_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT |
VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 |
VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER |
VME_PROG | VME_DATA;
master_image->width_attr = VME_D16 | VME_D32;
memset(&master_image->bus_resource, 0,
sizeof(struct resource));
master_image->kern_base = NULL;
list_add_tail(&master_image->list,
&tsi148_bridge->master_resources);
}
/* Add slave windows to list */
INIT_LIST_HEAD(&tsi148_bridge->slave_resources);
for (i = 0; i < TSI148_MAX_SLAVE; i++) {
slave_image = kmalloc(sizeof(struct vme_slave_resource),
GFP_KERNEL);
if (slave_image == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for "
"slave resource structure\n");
retval = -ENOMEM;
goto err_slave;
}
slave_image->parent = tsi148_bridge;
mutex_init(&slave_image->mtx);
slave_image->locked = 0;
slave_image->number = i;
slave_image->address_attr = VME_A16 | VME_A24 | VME_A32 |
VME_A64 | VME_CRCSR | VME_USER1 | VME_USER2 |
VME_USER3 | VME_USER4;
slave_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT |
VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 |
VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER |
VME_PROG | VME_DATA;
list_add_tail(&slave_image->list,
&tsi148_bridge->slave_resources);
}
/* Add dma engines to list */
INIT_LIST_HEAD(&tsi148_bridge->dma_resources);
for (i = 0; i < TSI148_MAX_DMA; i++) {
dma_ctrlr = kmalloc(sizeof(struct vme_dma_resource),
GFP_KERNEL);
if (dma_ctrlr == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for "
"dma resource structure\n");
retval = -ENOMEM;
goto err_dma;
}
dma_ctrlr->parent = tsi148_bridge;
mutex_init(&dma_ctrlr->mtx);
dma_ctrlr->locked = 0;
dma_ctrlr->number = i;
dma_ctrlr->route_attr = VME_DMA_VME_TO_MEM |
VME_DMA_MEM_TO_VME | VME_DMA_VME_TO_VME |
VME_DMA_MEM_TO_MEM | VME_DMA_PATTERN_TO_VME |
VME_DMA_PATTERN_TO_MEM;
INIT_LIST_HEAD(&dma_ctrlr->pending);
INIT_LIST_HEAD(&dma_ctrlr->running);
list_add_tail(&dma_ctrlr->list,
&tsi148_bridge->dma_resources);
}
/* Add location monitor to list */
INIT_LIST_HEAD(&tsi148_bridge->lm_resources);
lm = kmalloc(sizeof(struct vme_lm_resource), GFP_KERNEL);
if (lm == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for "
"location monitor resource structure\n");
retval = -ENOMEM;
goto err_lm;
}
lm->parent = tsi148_bridge;
mutex_init(&lm->mtx);
lm->locked = 0;
lm->number = 1;
lm->monitors = 4;
list_add_tail(&lm->list, &tsi148_bridge->lm_resources);
tsi148_bridge->slave_get = tsi148_slave_get;
tsi148_bridge->slave_set = tsi148_slave_set;
tsi148_bridge->master_get = tsi148_master_get;
tsi148_bridge->master_set = tsi148_master_set;
tsi148_bridge->master_read = tsi148_master_read;
tsi148_bridge->master_write = tsi148_master_write;
tsi148_bridge->master_rmw = tsi148_master_rmw;
tsi148_bridge->dma_list_add = tsi148_dma_list_add;
tsi148_bridge->dma_list_exec = tsi148_dma_list_exec;
tsi148_bridge->dma_list_empty = tsi148_dma_list_empty;
tsi148_bridge->irq_set = tsi148_irq_set;
tsi148_bridge->irq_generate = tsi148_irq_generate;
tsi148_bridge->lm_set = tsi148_lm_set;
tsi148_bridge->lm_get = tsi148_lm_get;
tsi148_bridge->lm_attach = tsi148_lm_attach;
tsi148_bridge->lm_detach = tsi148_lm_detach;
tsi148_bridge->slot_get = tsi148_slot_get;
data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT);
dev_info(&pdev->dev, "Board is%s the VME system controller\n",
(data & TSI148_LCSR_VSTAT_SCONS) ? "" : " not");
if (!geoid)
dev_info(&pdev->dev, "VME geographical address is %d\n",
data & TSI148_LCSR_VSTAT_GA_M);
else
dev_info(&pdev->dev, "VME geographical address is set to %d\n",
geoid);
dev_info(&pdev->dev, "VME Write and flush and error check is %s\n",
err_chk ? "enabled" : "disabled");
if (tsi148_crcsr_init(tsi148_bridge, pdev)) {
dev_err(&pdev->dev, "CR/CSR configuration failed.\n");
goto err_crcsr;
}
retval = vme_register_bridge(tsi148_bridge);
if (retval != 0) {
dev_err(&pdev->dev, "Chip Registration failed.\n");
goto err_reg;
}
pci_set_drvdata(pdev, tsi148_bridge);
/* Clear VME bus "board fail", and "power-up reset" lines */
data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT);
data &= ~TSI148_LCSR_VSTAT_BRDFL;
data |= TSI148_LCSR_VSTAT_CPURST;
iowrite32be(data, tsi148_device->base + TSI148_LCSR_VSTAT);
return 0;
err_reg:
tsi148_crcsr_exit(tsi148_bridge, pdev);
err_crcsr:
err_lm:
/* resources are stored in link list */
list_for_each(pos, &tsi148_bridge->lm_resources) {
lm = list_entry(pos, struct vme_lm_resource, list);
list_del(pos);
kfree(lm);
}
err_dma:
/* resources are stored in link list */
list_for_each(pos, &tsi148_bridge->dma_resources) {
dma_ctrlr = list_entry(pos, struct vme_dma_resource, list);
list_del(pos);
kfree(dma_ctrlr);
}
err_slave:
/* resources are stored in link list */
list_for_each(pos, &tsi148_bridge->slave_resources) {
slave_image = list_entry(pos, struct vme_slave_resource, list);
list_del(pos);
kfree(slave_image);
}
err_master:
/* resources are stored in link list */
list_for_each(pos, &tsi148_bridge->master_resources) {
master_image = list_entry(pos, struct vme_master_resource,
list);
list_del(pos);
kfree(master_image);
}
tsi148_irq_exit(tsi148_bridge, pdev);
err_irq:
err_test:
iounmap(tsi148_device->base);
err_remap:
pci_release_regions(pdev);
err_resource:
pci_disable_device(pdev);
err_enable:
kfree(tsi148_device);
err_driver:
kfree(tsi148_bridge);
err_struct:
return retval;
}
static void tsi148_remove(struct pci_dev *pdev)
{
struct list_head *pos = NULL;
struct list_head *tmplist;
struct vme_master_resource *master_image;
struct vme_slave_resource *slave_image;
struct vme_dma_resource *dma_ctrlr;
int i;
struct tsi148_driver *bridge;
struct vme_bridge *tsi148_bridge = pci_get_drvdata(pdev);
bridge = tsi148_bridge->driver_priv;
dev_dbg(&pdev->dev, "Driver is being unloaded.\n");
/*
* Shutdown all inbound and outbound windows.
*/
for (i = 0; i < 8; i++) {
iowrite32be(0, bridge->base + TSI148_LCSR_IT[i] +
TSI148_LCSR_OFFSET_ITAT);
iowrite32be(0, bridge->base + TSI148_LCSR_OT[i] +
TSI148_LCSR_OFFSET_OTAT);
}
/*
* Shutdown Location monitor.
*/
iowrite32be(0, bridge->base + TSI148_LCSR_LMAT);
/*
* Shutdown CRG map.
*/
iowrite32be(0, bridge->base + TSI148_LCSR_CSRAT);
/*
* Clear error status.
*/
iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_EDPAT);
iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_VEAT);
iowrite32be(0x07000700, bridge->base + TSI148_LCSR_PSTAT);
/*
* Remove VIRQ interrupt (if any)
*/
if (ioread32be(bridge->base + TSI148_LCSR_VICR) & 0x800)
iowrite32be(0x8000, bridge->base + TSI148_LCSR_VICR);
/*
* Map all Interrupts to PCI INTA
*/
iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM1);
iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM2);
tsi148_irq_exit(tsi148_bridge, pdev);
vme_unregister_bridge(tsi148_bridge);
tsi148_crcsr_exit(tsi148_bridge, pdev);
/* resources are stored in link list */
list_for_each_safe(pos, tmplist, &tsi148_bridge->dma_resources) {
dma_ctrlr = list_entry(pos, struct vme_dma_resource, list);
list_del(pos);
kfree(dma_ctrlr);
}
/* resources are stored in link list */
list_for_each_safe(pos, tmplist, &tsi148_bridge->slave_resources) {
slave_image = list_entry(pos, struct vme_slave_resource, list);
list_del(pos);
kfree(slave_image);
}
/* resources are stored in link list */
list_for_each_safe(pos, tmplist, &tsi148_bridge->master_resources) {
master_image = list_entry(pos, struct vme_master_resource,
list);
list_del(pos);
kfree(master_image);
}
iounmap(bridge->base);
pci_release_regions(pdev);
pci_disable_device(pdev);
kfree(tsi148_bridge->driver_priv);
kfree(tsi148_bridge);
}
static void __exit tsi148_exit(void)
{
pci_unregister_driver(&tsi148_driver);
}
MODULE_PARM_DESC(err_chk, "Check for VME errors on reads and writes");
module_param(err_chk, bool, 0);
MODULE_PARM_DESC(geoid, "Override geographical addressing");
module_param(geoid, int, 0);
MODULE_DESCRIPTION("VME driver for the Tundra Tempe VME bridge");
MODULE_LICENSE("GPL");
module_init(tsi148_init);
module_exit(tsi148_exit);
| gpl-2.0 |
intervigilium/android_kernel_htc_msm8952 | arch/mips/pci/pci-xlr.c | 2525 | 9448 | /*
* Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). 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 NetLogic
* license below:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETLOGIC ``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 NETLOGIC 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/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/msi.h>
#include <linux/mm.h>
#include <linux/irq.h>
#include <linux/irqdesc.h>
#include <linux/console.h>
#include <linux/pci_regs.h>
#include <asm/io.h>
#include <asm/netlogic/interrupt.h>
#include <asm/netlogic/haldefs.h>
#include <asm/netlogic/common.h>
#include <asm/netlogic/xlr/msidef.h>
#include <asm/netlogic/xlr/iomap.h>
#include <asm/netlogic/xlr/pic.h>
#include <asm/netlogic/xlr/xlr.h>
static void *pci_config_base;
#define pci_cfg_addr(bus, devfn, off) (((bus) << 16) | ((devfn) << 8) | (off))
/* PCI ops */
static inline u32 pci_cfg_read_32bit(struct pci_bus *bus, unsigned int devfn,
int where)
{
u32 data;
u32 *cfgaddr;
cfgaddr = (u32 *)(pci_config_base +
pci_cfg_addr(bus->number, devfn, where & ~3));
data = *cfgaddr;
return cpu_to_le32(data);
}
static inline void pci_cfg_write_32bit(struct pci_bus *bus, unsigned int devfn,
int where, u32 data)
{
u32 *cfgaddr;
cfgaddr = (u32 *)(pci_config_base +
pci_cfg_addr(bus->number, devfn, where & ~3));
*cfgaddr = cpu_to_le32(data);
}
static int nlm_pcibios_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
u32 data;
if ((size == 2) && (where & 1))
return PCIBIOS_BAD_REGISTER_NUMBER;
else if ((size == 4) && (where & 3))
return PCIBIOS_BAD_REGISTER_NUMBER;
data = pci_cfg_read_32bit(bus, devfn, where);
if (size == 1)
*val = (data >> ((where & 3) << 3)) & 0xff;
else if (size == 2)
*val = (data >> ((where & 3) << 3)) & 0xffff;
else
*val = data;
return PCIBIOS_SUCCESSFUL;
}
static int nlm_pcibios_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
u32 data;
if ((size == 2) && (where & 1))
return PCIBIOS_BAD_REGISTER_NUMBER;
else if ((size == 4) && (where & 3))
return PCIBIOS_BAD_REGISTER_NUMBER;
data = pci_cfg_read_32bit(bus, devfn, where);
if (size == 1)
data = (data & ~(0xff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else if (size == 2)
data = (data & ~(0xffff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else
data = val;
pci_cfg_write_32bit(bus, devfn, where, data);
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops nlm_pci_ops = {
.read = nlm_pcibios_read,
.write = nlm_pcibios_write
};
static struct resource nlm_pci_mem_resource = {
.name = "XLR PCI MEM",
.start = 0xd0000000UL, /* 256MB PCI mem @ 0xd000_0000 */
.end = 0xdfffffffUL,
.flags = IORESOURCE_MEM,
};
static struct resource nlm_pci_io_resource = {
.name = "XLR IO MEM",
.start = 0x10000000UL, /* 16MB PCI IO @ 0x1000_0000 */
.end = 0x100fffffUL,
.flags = IORESOURCE_IO,
};
struct pci_controller nlm_pci_controller = {
.index = 0,
.pci_ops = &nlm_pci_ops,
.mem_resource = &nlm_pci_mem_resource,
.mem_offset = 0x00000000UL,
.io_resource = &nlm_pci_io_resource,
.io_offset = 0x00000000UL,
};
/*
* The top level PCIe links on the XLS PCIe controller appear as
* bridges. Given a device, this function finds which link it is
* on.
*/
static struct pci_dev *xls_get_pcie_link(const struct pci_dev *dev)
{
struct pci_bus *bus, *p;
/* Find the bridge on bus 0 */
bus = dev->bus;
for (p = bus->parent; p && p->number != 0; p = p->parent)
bus = p;
return p ? bus->self : NULL;
}
static int nlm_pci_link_to_irq(int link)
{
switch (link) {
case 0:
return PIC_PCIE_LINK0_IRQ;
case 1:
return PIC_PCIE_LINK1_IRQ;
case 2:
if (nlm_chip_is_xls_b())
return PIC_PCIE_XLSB0_LINK2_IRQ;
else
return PIC_PCIE_LINK2_IRQ;
case 3:
if (nlm_chip_is_xls_b())
return PIC_PCIE_XLSB0_LINK3_IRQ;
else
return PIC_PCIE_LINK3_IRQ;
}
WARN(1, "Unexpected link %d\n", link);
return 0;
}
static int get_irq_vector(const struct pci_dev *dev)
{
struct pci_dev *lnk;
int link;
if (!nlm_chip_is_xls())
return PIC_PCIX_IRQ; /* for XLR just one IRQ */
lnk = xls_get_pcie_link(dev);
if (lnk == NULL)
return 0;
link = PCI_SLOT(lnk->devfn);
return nlm_pci_link_to_irq(link);
}
#ifdef CONFIG_PCI_MSI
void destroy_irq(unsigned int irq)
{
/* nothing to do yet */
}
void arch_teardown_msi_irq(unsigned int irq)
{
destroy_irq(irq);
}
int arch_setup_msi_irq(struct pci_dev *dev, struct msi_desc *desc)
{
struct msi_msg msg;
struct pci_dev *lnk;
int irq, ret;
u16 val;
/* MSI not supported on XLR */
if (!nlm_chip_is_xls())
return 1;
/*
* Enable MSI on the XLS PCIe controller bridge which was disabled
* at enumeration, the bridge MSI capability is at 0x50
*/
lnk = xls_get_pcie_link(dev);
if (lnk == NULL)
return 1;
pci_read_config_word(lnk, 0x50 + PCI_MSI_FLAGS, &val);
if ((val & PCI_MSI_FLAGS_ENABLE) == 0) {
val |= PCI_MSI_FLAGS_ENABLE;
pci_write_config_word(lnk, 0x50 + PCI_MSI_FLAGS, val);
}
irq = get_irq_vector(dev);
if (irq <= 0)
return 1;
msg.address_hi = MSI_ADDR_BASE_HI;
msg.address_lo = MSI_ADDR_BASE_LO |
MSI_ADDR_DEST_MODE_PHYSICAL |
MSI_ADDR_REDIRECTION_CPU;
msg.data = MSI_DATA_TRIGGER_EDGE |
MSI_DATA_LEVEL_ASSERT |
MSI_DATA_DELIVERY_FIXED;
ret = irq_set_msi_desc(irq, desc);
if (ret < 0) {
destroy_irq(irq);
return ret;
}
write_msi_msg(irq, &msg);
return 0;
}
#endif
/* Extra ACK needed for XLR on chip PCI controller */
static void xlr_pci_ack(struct irq_data *d)
{
uint64_t pcibase = nlm_mmio_base(NETLOGIC_IO_PCIX_OFFSET);
nlm_read_reg(pcibase, (0x140 >> 2));
}
/* Extra ACK needed for XLS on chip PCIe controller */
static void xls_pcie_ack(struct irq_data *d)
{
uint64_t pciebase_le = nlm_mmio_base(NETLOGIC_IO_PCIE_1_OFFSET);
switch (d->irq) {
case PIC_PCIE_LINK0_IRQ:
nlm_write_reg(pciebase_le, (0x90 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK1_IRQ:
nlm_write_reg(pciebase_le, (0x94 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK2_IRQ:
nlm_write_reg(pciebase_le, (0x190 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK3_IRQ:
nlm_write_reg(pciebase_le, (0x194 >> 2), 0xffffffff);
break;
}
}
/* For XLS B silicon, the 3,4 PCI interrupts are different */
static void xls_pcie_ack_b(struct irq_data *d)
{
uint64_t pciebase_le = nlm_mmio_base(NETLOGIC_IO_PCIE_1_OFFSET);
switch (d->irq) {
case PIC_PCIE_LINK0_IRQ:
nlm_write_reg(pciebase_le, (0x90 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK1_IRQ:
nlm_write_reg(pciebase_le, (0x94 >> 2), 0xffffffff);
break;
case PIC_PCIE_XLSB0_LINK2_IRQ:
nlm_write_reg(pciebase_le, (0x190 >> 2), 0xffffffff);
break;
case PIC_PCIE_XLSB0_LINK3_IRQ:
nlm_write_reg(pciebase_le, (0x194 >> 2), 0xffffffff);
break;
}
}
int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
return get_irq_vector(dev);
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
return 0;
}
static int __init pcibios_init(void)
{
void (*extra_ack)(struct irq_data *);
int link, irq;
/* PSB assigns PCI resources */
pci_set_flags(PCI_PROBE_ONLY);
pci_config_base = ioremap(DEFAULT_PCI_CONFIG_BASE, 16 << 20);
/* Extend IO port for memory mapped io */
ioport_resource.start = 0;
ioport_resource.end = ~0;
set_io_port_base(CKSEG1);
nlm_pci_controller.io_map_base = CKSEG1;
pr_info("Registering XLR/XLS PCIX/PCIE Controller.\n");
register_pci_controller(&nlm_pci_controller);
/*
* For PCI interrupts, we need to ack the PCI controller too, overload
* irq handler data to do this
*/
if (!nlm_chip_is_xls()) {
/* XLR PCI controller ACK */
nlm_set_pic_extra_ack(0, PIC_PCIX_IRQ, xlr_pci_ack);
} else {
if (nlm_chip_is_xls_b())
extra_ack = xls_pcie_ack_b;
else
extra_ack = xls_pcie_ack;
for (link = 0; link < 4; link++) {
irq = nlm_pci_link_to_irq(link);
nlm_set_pic_extra_ack(0, irq, extra_ack);
}
}
return 0;
}
arch_initcall(pcibios_init);
| gpl-2.0 |
NoelMacwan/SXDMesona | drivers/mtd/maps/physmap.c | 2781 | 7347 | /*
* Normal mappings of chips in physical memory
*
* Copyright (C) 2003 MontaVista Software Inc.
* Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
*
* 031022 - [jsun] add run-time configure and partition setup
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/concat.h>
#include <linux/io.h>
#define MAX_RESOURCES 4
struct physmap_flash_info {
struct mtd_info *mtd[MAX_RESOURCES];
struct mtd_info *cmtd;
struct map_info map[MAX_RESOURCES];
int nr_parts;
struct mtd_partition *parts;
};
static int physmap_flash_remove(struct platform_device *dev)
{
struct physmap_flash_info *info;
struct physmap_flash_data *physmap_data;
int i;
info = platform_get_drvdata(dev);
if (info == NULL)
return 0;
platform_set_drvdata(dev, NULL);
physmap_data = dev->dev.platform_data;
if (info->cmtd) {
mtd_device_unregister(info->cmtd);
if (info->nr_parts)
kfree(info->parts);
if (info->cmtd != info->mtd[0])
mtd_concat_destroy(info->cmtd);
}
for (i = 0; i < MAX_RESOURCES; i++) {
if (info->mtd[i] != NULL)
map_destroy(info->mtd[i]);
}
if (physmap_data->exit)
physmap_data->exit(dev);
return 0;
}
static void physmap_set_vpp(struct map_info *map, int state)
{
struct platform_device *pdev;
struct physmap_flash_data *physmap_data;
pdev = (struct platform_device *)map->map_priv_1;
physmap_data = pdev->dev.platform_data;
if (physmap_data->set_vpp)
physmap_data->set_vpp(pdev, state);
}
static const char *rom_probe_types[] = {
"cfi_probe",
"jedec_probe",
"qinfo_probe",
"map_rom",
NULL };
static const char *part_probe_types[] = { "cmdlinepart", "RedBoot", "afs",
NULL };
static int physmap_flash_probe(struct platform_device *dev)
{
struct physmap_flash_data *physmap_data;
struct physmap_flash_info *info;
const char **probe_type;
int err = 0;
int i;
int devices_found = 0;
physmap_data = dev->dev.platform_data;
if (physmap_data == NULL)
return -ENODEV;
info = devm_kzalloc(&dev->dev, sizeof(struct physmap_flash_info),
GFP_KERNEL);
if (info == NULL) {
err = -ENOMEM;
goto err_out;
}
if (physmap_data->init) {
err = physmap_data->init(dev);
if (err)
goto err_out;
}
platform_set_drvdata(dev, info);
for (i = 0; i < dev->num_resources; i++) {
printk(KERN_NOTICE "physmap platform flash device: %.8llx at %.8llx\n",
(unsigned long long)resource_size(&dev->resource[i]),
(unsigned long long)dev->resource[i].start);
if (!devm_request_mem_region(&dev->dev,
dev->resource[i].start,
resource_size(&dev->resource[i]),
dev_name(&dev->dev))) {
dev_err(&dev->dev, "Could not reserve memory region\n");
err = -ENOMEM;
goto err_out;
}
info->map[i].name = dev_name(&dev->dev);
info->map[i].phys = dev->resource[i].start;
info->map[i].size = resource_size(&dev->resource[i]);
info->map[i].bankwidth = physmap_data->width;
info->map[i].set_vpp = physmap_set_vpp;
info->map[i].pfow_base = physmap_data->pfow_base;
info->map[i].map_priv_1 = (unsigned long)dev;
info->map[i].virt = devm_ioremap(&dev->dev, info->map[i].phys,
info->map[i].size);
if (info->map[i].virt == NULL) {
dev_err(&dev->dev, "Failed to ioremap flash region\n");
err = -EIO;
goto err_out;
}
simple_map_init(&info->map[i]);
probe_type = rom_probe_types;
if (physmap_data->probe_type == NULL) {
for (; info->mtd[i] == NULL && *probe_type != NULL; probe_type++)
info->mtd[i] = do_map_probe(*probe_type, &info->map[i]);
} else
info->mtd[i] = do_map_probe(physmap_data->probe_type, &info->map[i]);
if (info->mtd[i] == NULL) {
dev_err(&dev->dev, "map_probe failed\n");
err = -ENXIO;
goto err_out;
} else {
devices_found++;
}
info->mtd[i]->owner = THIS_MODULE;
info->mtd[i]->dev.parent = &dev->dev;
}
if (devices_found == 1) {
info->cmtd = info->mtd[0];
} else if (devices_found > 1) {
/*
* We detected multiple devices. Concatenate them together.
*/
info->cmtd = mtd_concat_create(info->mtd, devices_found, dev_name(&dev->dev));
if (info->cmtd == NULL)
err = -ENXIO;
}
if (err)
goto err_out;
err = parse_mtd_partitions(info->cmtd, part_probe_types,
&info->parts, 0);
if (err > 0) {
mtd_device_register(info->cmtd, info->parts, err);
info->nr_parts = err;
return 0;
}
if (physmap_data->nr_parts) {
printk(KERN_NOTICE "Using physmap partition information\n");
mtd_device_register(info->cmtd, physmap_data->parts,
physmap_data->nr_parts);
return 0;
}
mtd_device_register(info->cmtd, NULL, 0);
return 0;
err_out:
physmap_flash_remove(dev);
return err;
}
#ifdef CONFIG_PM
static void physmap_flash_shutdown(struct platform_device *dev)
{
struct physmap_flash_info *info = platform_get_drvdata(dev);
int i;
for (i = 0; i < MAX_RESOURCES && info->mtd[i]; i++)
if (info->mtd[i]->suspend && info->mtd[i]->resume)
if (info->mtd[i]->suspend(info->mtd[i]) == 0)
info->mtd[i]->resume(info->mtd[i]);
}
#else
#define physmap_flash_shutdown NULL
#endif
static struct platform_driver physmap_flash_driver = {
.probe = physmap_flash_probe,
.remove = physmap_flash_remove,
.shutdown = physmap_flash_shutdown,
.driver = {
.name = "physmap-flash",
.owner = THIS_MODULE,
},
};
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
static struct physmap_flash_data physmap_flash_data = {
.width = CONFIG_MTD_PHYSMAP_BANKWIDTH,
};
static struct resource physmap_flash_resource = {
.start = CONFIG_MTD_PHYSMAP_START,
.end = CONFIG_MTD_PHYSMAP_START + CONFIG_MTD_PHYSMAP_LEN - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device physmap_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &physmap_flash_data,
},
.num_resources = 1,
.resource = &physmap_flash_resource,
};
void physmap_configure(unsigned long addr, unsigned long size,
int bankwidth, void (*set_vpp)(struct map_info *, int))
{
physmap_flash_resource.start = addr;
physmap_flash_resource.end = addr + size - 1;
physmap_flash_data.width = bankwidth;
physmap_flash_data.set_vpp = set_vpp;
}
void physmap_set_partitions(struct mtd_partition *parts, int num_parts)
{
physmap_flash_data.nr_parts = num_parts;
physmap_flash_data.parts = parts;
}
#endif
static int __init physmap_init(void)
{
int err;
err = platform_driver_register(&physmap_flash_driver);
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
if (err == 0) {
err = platform_device_register(&physmap_flash);
if (err)
platform_driver_unregister(&physmap_flash_driver);
}
#endif
return err;
}
static void __exit physmap_exit(void)
{
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
platform_device_unregister(&physmap_flash);
#endif
platform_driver_unregister(&physmap_flash_driver);
}
module_init(physmap_init);
module_exit(physmap_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("Generic configurable MTD map driver");
/* legacy platform drivers can't hotplug or coldplg */
#ifndef CONFIG_MTD_PHYSMAP_COMPAT
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:physmap-flash");
#endif
| gpl-2.0 |
mathkid95/linux_samsung_ics | drivers/scsi/qla4xxx/ql4_isr.c | 2781 | 30630 | /*
* QLogic iSCSI HBA Driver
* Copyright (c) 2003-2010 QLogic Corporation
*
* See LICENSE.qla4xxx for copyright and licensing details.
*/
#include "ql4_def.h"
#include "ql4_glbl.h"
#include "ql4_dbg.h"
#include "ql4_inline.h"
/**
* qla4xxx_copy_sense - copy sense data into cmd sense buffer
* @ha: Pointer to host adapter structure.
* @sts_entry: Pointer to status entry structure.
* @srb: Pointer to srb structure.
**/
static void qla4xxx_copy_sense(struct scsi_qla_host *ha,
struct status_entry *sts_entry,
struct srb *srb)
{
struct scsi_cmnd *cmd = srb->cmd;
uint16_t sense_len;
memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
sense_len = le16_to_cpu(sts_entry->senseDataByteCnt);
if (sense_len == 0) {
DEBUG2(ql4_printk(KERN_INFO, ha, "scsi%ld:%d:%d:%d: %s:"
" sense len 0\n", ha->host_no,
cmd->device->channel, cmd->device->id,
cmd->device->lun, __func__));
ha->status_srb = NULL;
return;
}
/* Save total available sense length,
* not to exceed cmd's sense buffer size */
sense_len = min_t(uint16_t, sense_len, SCSI_SENSE_BUFFERSIZE);
srb->req_sense_ptr = cmd->sense_buffer;
srb->req_sense_len = sense_len;
/* Copy sense from sts_entry pkt */
sense_len = min_t(uint16_t, sense_len, IOCB_MAX_SENSEDATA_LEN);
memcpy(cmd->sense_buffer, sts_entry->senseData, sense_len);
DEBUG2(printk(KERN_INFO "scsi%ld:%d:%d:%d: %s: sense key = %x, "
"ASL= %02x, ASC/ASCQ = %02x/%02x\n", ha->host_no,
cmd->device->channel, cmd->device->id,
cmd->device->lun, __func__,
sts_entry->senseData[2] & 0x0f,
sts_entry->senseData[7],
sts_entry->senseData[12],
sts_entry->senseData[13]));
DEBUG5(qla4xxx_dump_buffer(cmd->sense_buffer, sense_len));
srb->flags |= SRB_GOT_SENSE;
/* Update srb, in case a sts_cont pkt follows */
srb->req_sense_ptr += sense_len;
srb->req_sense_len -= sense_len;
if (srb->req_sense_len != 0)
ha->status_srb = srb;
else
ha->status_srb = NULL;
}
/**
* qla4xxx_status_cont_entry - Process a Status Continuations entry.
* @ha: SCSI driver HA context
* @sts_cont: Entry pointer
*
* Extended sense data.
*/
static void
qla4xxx_status_cont_entry(struct scsi_qla_host *ha,
struct status_cont_entry *sts_cont)
{
struct srb *srb = ha->status_srb;
struct scsi_cmnd *cmd;
uint16_t sense_len;
if (srb == NULL)
return;
cmd = srb->cmd;
if (cmd == NULL) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: Cmd already returned "
"back to OS srb=%p srb->state:%d\n", ha->host_no,
__func__, srb, srb->state));
ha->status_srb = NULL;
return;
}
/* Copy sense data. */
sense_len = min_t(uint16_t, srb->req_sense_len,
IOCB_MAX_EXT_SENSEDATA_LEN);
memcpy(srb->req_sense_ptr, sts_cont->ext_sense_data, sense_len);
DEBUG5(qla4xxx_dump_buffer(srb->req_sense_ptr, sense_len));
srb->req_sense_ptr += sense_len;
srb->req_sense_len -= sense_len;
/* Place command on done queue. */
if (srb->req_sense_len == 0) {
kref_put(&srb->srb_ref, qla4xxx_srb_compl);
ha->status_srb = NULL;
}
}
/**
* qla4xxx_status_entry - processes status IOCBs
* @ha: Pointer to host adapter structure.
* @sts_entry: Pointer to status entry structure.
**/
static void qla4xxx_status_entry(struct scsi_qla_host *ha,
struct status_entry *sts_entry)
{
uint8_t scsi_status;
struct scsi_cmnd *cmd;
struct srb *srb;
struct ddb_entry *ddb_entry;
uint32_t residual;
srb = qla4xxx_del_from_active_array(ha, le32_to_cpu(sts_entry->handle));
if (!srb) {
DEBUG2(printk(KERN_WARNING "scsi%ld: %s: Status Entry invalid "
"handle 0x%x, sp=%p. This cmd may have already "
"been completed.\n", ha->host_no, __func__,
le32_to_cpu(sts_entry->handle), srb));
ql4_printk(KERN_WARNING, ha, "%s invalid status entry:"
" handle=0x%0x\n", __func__, sts_entry->handle);
set_bit(DPC_RESET_HA, &ha->dpc_flags);
return;
}
cmd = srb->cmd;
if (cmd == NULL) {
DEBUG2(printk("scsi%ld: %s: Command already returned back to "
"OS pkt->handle=%d srb=%p srb->state:%d\n",
ha->host_no, __func__, sts_entry->handle,
srb, srb->state));
ql4_printk(KERN_WARNING, ha, "Command is NULL:"
" already returned to OS (srb=%p)\n", srb);
return;
}
ddb_entry = srb->ddb;
if (ddb_entry == NULL) {
cmd->result = DID_NO_CONNECT << 16;
goto status_entry_exit;
}
residual = le32_to_cpu(sts_entry->residualByteCnt);
/* Translate ISP error to a Linux SCSI error. */
scsi_status = sts_entry->scsiStatus;
switch (sts_entry->completionStatus) {
case SCS_COMPLETE:
if (sts_entry->iscsiFlags & ISCSI_FLAG_RESIDUAL_OVER) {
cmd->result = DID_ERROR << 16;
break;
}
if (sts_entry->iscsiFlags &ISCSI_FLAG_RESIDUAL_UNDER) {
scsi_set_resid(cmd, residual);
if (!scsi_status && ((scsi_bufflen(cmd) - residual) <
cmd->underflow)) {
cmd->result = DID_ERROR << 16;
DEBUG2(printk("scsi%ld:%d:%d:%d: %s: "
"Mid-layer Data underrun0, "
"xferlen = 0x%x, "
"residual = 0x%x\n", ha->host_no,
cmd->device->channel,
cmd->device->id,
cmd->device->lun, __func__,
scsi_bufflen(cmd), residual));
break;
}
}
cmd->result = DID_OK << 16 | scsi_status;
if (scsi_status != SCSI_CHECK_CONDITION)
break;
/* Copy Sense Data into sense buffer. */
qla4xxx_copy_sense(ha, sts_entry, srb);
break;
case SCS_INCOMPLETE:
/* Always set the status to DID_ERROR, since
* all conditions result in that status anyway */
cmd->result = DID_ERROR << 16;
break;
case SCS_RESET_OCCURRED:
DEBUG2(printk("scsi%ld:%d:%d:%d: %s: Device RESET occurred\n",
ha->host_no, cmd->device->channel,
cmd->device->id, cmd->device->lun, __func__));
cmd->result = DID_RESET << 16;
break;
case SCS_ABORTED:
DEBUG2(printk("scsi%ld:%d:%d:%d: %s: Abort occurred\n",
ha->host_no, cmd->device->channel,
cmd->device->id, cmd->device->lun, __func__));
cmd->result = DID_RESET << 16;
break;
case SCS_TIMEOUT:
DEBUG2(printk(KERN_INFO "scsi%ld:%d:%d:%d: Timeout\n",
ha->host_no, cmd->device->channel,
cmd->device->id, cmd->device->lun));
cmd->result = DID_TRANSPORT_DISRUPTED << 16;
/*
* Mark device missing so that we won't continue to send
* I/O to this device. We should get a ddb state change
* AEN soon.
*/
if (atomic_read(&ddb_entry->state) == DDB_STATE_ONLINE)
qla4xxx_mark_device_missing(ha, ddb_entry);
break;
case SCS_DATA_UNDERRUN:
case SCS_DATA_OVERRUN:
if ((sts_entry->iscsiFlags & ISCSI_FLAG_RESIDUAL_OVER) ||
(sts_entry->completionStatus == SCS_DATA_OVERRUN)) {
DEBUG2(printk("scsi%ld:%d:%d:%d: %s: " "Data overrun\n",
ha->host_no,
cmd->device->channel, cmd->device->id,
cmd->device->lun, __func__));
cmd->result = DID_ERROR << 16;
break;
}
scsi_set_resid(cmd, residual);
/*
* If there is scsi_status, it takes precedense over
* underflow condition.
*/
if (scsi_status != 0) {
cmd->result = DID_OK << 16 | scsi_status;
if (scsi_status != SCSI_CHECK_CONDITION)
break;
/* Copy Sense Data into sense buffer. */
qla4xxx_copy_sense(ha, sts_entry, srb);
} else {
/*
* If RISC reports underrun and target does not
* report it then we must have a lost frame, so
* tell upper layer to retry it by reporting a
* bus busy.
*/
if ((sts_entry->iscsiFlags &
ISCSI_FLAG_RESIDUAL_UNDER) == 0) {
cmd->result = DID_BUS_BUSY << 16;
} else if ((scsi_bufflen(cmd) - residual) <
cmd->underflow) {
/*
* Handle mid-layer underflow???
*
* For kernels less than 2.4, the driver must
* return an error if an underflow is detected.
* For kernels equal-to and above 2.4, the
* mid-layer will appearantly handle the
* underflow by detecting the residual count --
* unfortunately, we do not see where this is
* actually being done. In the interim, we
* will return DID_ERROR.
*/
DEBUG2(printk("scsi%ld:%d:%d:%d: %s: "
"Mid-layer Data underrun1, "
"xferlen = 0x%x, "
"residual = 0x%x\n", ha->host_no,
cmd->device->channel,
cmd->device->id,
cmd->device->lun, __func__,
scsi_bufflen(cmd), residual));
cmd->result = DID_ERROR << 16;
} else {
cmd->result = DID_OK << 16;
}
}
break;
case SCS_DEVICE_LOGGED_OUT:
case SCS_DEVICE_UNAVAILABLE:
DEBUG2(printk(KERN_INFO "scsi%ld:%d:%d:%d: SCS_DEVICE "
"state: 0x%x\n", ha->host_no,
cmd->device->channel, cmd->device->id,
cmd->device->lun, sts_entry->completionStatus));
/*
* Mark device missing so that we won't continue to
* send I/O to this device. We should get a ddb
* state change AEN soon.
*/
if (atomic_read(&ddb_entry->state) == DDB_STATE_ONLINE)
qla4xxx_mark_device_missing(ha, ddb_entry);
cmd->result = DID_TRANSPORT_DISRUPTED << 16;
break;
case SCS_QUEUE_FULL:
/*
* SCSI Mid-Layer handles device queue full
*/
cmd->result = DID_OK << 16 | sts_entry->scsiStatus;
DEBUG2(printk("scsi%ld:%d:%d: %s: QUEUE FULL detected "
"compl=%02x, scsi=%02x, state=%02x, iFlags=%02x,"
" iResp=%02x\n", ha->host_no, cmd->device->id,
cmd->device->lun, __func__,
sts_entry->completionStatus,
sts_entry->scsiStatus, sts_entry->state_flags,
sts_entry->iscsiFlags,
sts_entry->iscsiResponse));
break;
default:
cmd->result = DID_ERROR << 16;
break;
}
status_entry_exit:
/* complete the request, if not waiting for status_continuation pkt */
srb->cc_stat = sts_entry->completionStatus;
if (ha->status_srb == NULL)
kref_put(&srb->srb_ref, qla4xxx_srb_compl);
}
/**
* qla4xxx_process_response_queue - process response queue completions
* @ha: Pointer to host adapter structure.
*
* This routine process response queue completions in interrupt context.
* Hardware_lock locked upon entry
**/
void qla4xxx_process_response_queue(struct scsi_qla_host *ha)
{
uint32_t count = 0;
struct srb *srb = NULL;
struct status_entry *sts_entry;
/* Process all responses from response queue */
while ((ha->response_ptr->signature != RESPONSE_PROCESSED)) {
sts_entry = (struct status_entry *) ha->response_ptr;
count++;
/* Advance pointers for next entry */
if (ha->response_out == (RESPONSE_QUEUE_DEPTH - 1)) {
ha->response_out = 0;
ha->response_ptr = ha->response_ring;
} else {
ha->response_out++;
ha->response_ptr++;
}
/* process entry */
switch (sts_entry->hdr.entryType) {
case ET_STATUS:
/* Common status */
qla4xxx_status_entry(ha, sts_entry);
break;
case ET_PASSTHRU_STATUS:
break;
case ET_STATUS_CONTINUATION:
qla4xxx_status_cont_entry(ha,
(struct status_cont_entry *) sts_entry);
break;
case ET_COMMAND:
/* ISP device queue is full. Command not
* accepted by ISP. Queue command for
* later */
srb = qla4xxx_del_from_active_array(ha,
le32_to_cpu(sts_entry->
handle));
if (srb == NULL)
goto exit_prq_invalid_handle;
DEBUG2(printk("scsi%ld: %s: FW device queue full, "
"srb %p\n", ha->host_no, __func__, srb));
/* ETRY normally by sending it back with
* DID_BUS_BUSY */
srb->cmd->result = DID_BUS_BUSY << 16;
kref_put(&srb->srb_ref, qla4xxx_srb_compl);
break;
case ET_CONTINUE:
/* Just throw away the continuation entries */
DEBUG2(printk("scsi%ld: %s: Continuation entry - "
"ignoring\n", ha->host_no, __func__));
break;
default:
/*
* Invalid entry in response queue, reset RISC
* firmware.
*/
DEBUG2(printk("scsi%ld: %s: Invalid entry %x in "
"response queue \n", ha->host_no,
__func__,
sts_entry->hdr.entryType));
goto exit_prq_error;
}
((struct response *)sts_entry)->signature = RESPONSE_PROCESSED;
wmb();
}
/*
* Tell ISP we're done with response(s). This also clears the interrupt.
*/
ha->isp_ops->complete_iocb(ha);
return;
exit_prq_invalid_handle:
DEBUG2(printk("scsi%ld: %s: Invalid handle(srb)=%p type=%x IOCS=%x\n",
ha->host_no, __func__, srb, sts_entry->hdr.entryType,
sts_entry->completionStatus));
exit_prq_error:
ha->isp_ops->complete_iocb(ha);
set_bit(DPC_RESET_HA, &ha->dpc_flags);
}
/**
* qla4xxx_isr_decode_mailbox - decodes mailbox status
* @ha: Pointer to host adapter structure.
* @mailbox_status: Mailbox status.
*
* This routine decodes the mailbox status during the ISR.
* Hardware_lock locked upon entry. runs in interrupt context.
**/
static void qla4xxx_isr_decode_mailbox(struct scsi_qla_host * ha,
uint32_t mbox_status)
{
int i;
uint32_t mbox_sts[MBOX_AEN_REG_COUNT];
if ((mbox_status == MBOX_STS_BUSY) ||
(mbox_status == MBOX_STS_INTERMEDIATE_COMPLETION) ||
(mbox_status >> 12 == MBOX_COMPLETION_STATUS)) {
ha->mbox_status[0] = mbox_status;
if (test_bit(AF_MBOX_COMMAND, &ha->flags)) {
/*
* Copy all mailbox registers to a temporary
* location and set mailbox command done flag
*/
for (i = 0; i < ha->mbox_status_count; i++)
ha->mbox_status[i] = is_qla8022(ha)
? readl(&ha->qla4_8xxx_reg->mailbox_out[i])
: readl(&ha->reg->mailbox[i]);
set_bit(AF_MBOX_COMMAND_DONE, &ha->flags);
if (test_bit(AF_MBOX_COMMAND_NOPOLL, &ha->flags))
complete(&ha->mbx_intr_comp);
}
} else if (mbox_status >> 12 == MBOX_ASYNC_EVENT_STATUS) {
for (i = 0; i < MBOX_AEN_REG_COUNT; i++)
mbox_sts[i] = is_qla8022(ha)
? readl(&ha->qla4_8xxx_reg->mailbox_out[i])
: readl(&ha->reg->mailbox[i]);
/* Immediately process the AENs that don't require much work.
* Only queue the database_changed AENs */
if (ha->aen_log.count < MAX_AEN_ENTRIES) {
for (i = 0; i < MBOX_AEN_REG_COUNT; i++)
ha->aen_log.entry[ha->aen_log.count].mbox_sts[i] =
mbox_sts[i];
ha->aen_log.count++;
}
switch (mbox_status) {
case MBOX_ASTS_SYSTEM_ERROR:
/* Log Mailbox registers */
ql4_printk(KERN_INFO, ha, "%s: System Err\n", __func__);
qla4xxx_dump_registers(ha);
if (ql4xdontresethba) {
DEBUG2(printk("scsi%ld: %s:Don't Reset HBA\n",
ha->host_no, __func__));
} else {
set_bit(AF_GET_CRASH_RECORD, &ha->flags);
set_bit(DPC_RESET_HA, &ha->dpc_flags);
}
break;
case MBOX_ASTS_REQUEST_TRANSFER_ERROR:
case MBOX_ASTS_RESPONSE_TRANSFER_ERROR:
case MBOX_ASTS_NVRAM_INVALID:
case MBOX_ASTS_IP_ADDRESS_CHANGED:
case MBOX_ASTS_DHCP_LEASE_EXPIRED:
DEBUG2(printk("scsi%ld: AEN %04x, ERROR Status, "
"Reset HA\n", ha->host_no, mbox_status));
set_bit(DPC_RESET_HA, &ha->dpc_flags);
break;
case MBOX_ASTS_LINK_UP:
set_bit(AF_LINK_UP, &ha->flags);
if (test_bit(AF_INIT_DONE, &ha->flags))
set_bit(DPC_LINK_CHANGED, &ha->dpc_flags);
ql4_printk(KERN_INFO, ha, "%s: LINK UP\n", __func__);
break;
case MBOX_ASTS_LINK_DOWN:
clear_bit(AF_LINK_UP, &ha->flags);
if (test_bit(AF_INIT_DONE, &ha->flags))
set_bit(DPC_LINK_CHANGED, &ha->dpc_flags);
ql4_printk(KERN_INFO, ha, "%s: LINK DOWN\n", __func__);
break;
case MBOX_ASTS_HEARTBEAT:
ha->seconds_since_last_heartbeat = 0;
break;
case MBOX_ASTS_DHCP_LEASE_ACQUIRED:
DEBUG2(printk("scsi%ld: AEN %04x DHCP LEASE "
"ACQUIRED\n", ha->host_no, mbox_status));
set_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags);
break;
case MBOX_ASTS_PROTOCOL_STATISTIC_ALARM:
case MBOX_ASTS_SCSI_COMMAND_PDU_REJECTED: /* Target
* mode
* only */
case MBOX_ASTS_UNSOLICITED_PDU_RECEIVED: /* Connection mode */
case MBOX_ASTS_IPSEC_SYSTEM_FATAL_ERROR:
case MBOX_ASTS_SUBNET_STATE_CHANGE:
case MBOX_ASTS_DUPLICATE_IP:
/* No action */
DEBUG2(printk("scsi%ld: AEN %04x\n", ha->host_no,
mbox_status));
break;
case MBOX_ASTS_IP_ADDR_STATE_CHANGED:
printk("scsi%ld: AEN %04x, mbox_sts[2]=%04x, "
"mbox_sts[3]=%04x\n", ha->host_no, mbox_sts[0],
mbox_sts[2], mbox_sts[3]);
/* mbox_sts[2] = Old ACB state
* mbox_sts[3] = new ACB state */
if ((mbox_sts[3] == ACB_STATE_VALID) &&
((mbox_sts[2] == ACB_STATE_TENTATIVE) ||
(mbox_sts[2] == ACB_STATE_ACQUIRING)))
set_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags);
else if ((mbox_sts[3] == ACB_STATE_ACQUIRING) &&
(mbox_sts[2] == ACB_STATE_VALID))
set_bit(DPC_RESET_HA, &ha->dpc_flags);
break;
case MBOX_ASTS_MAC_ADDRESS_CHANGED:
case MBOX_ASTS_DNS:
/* No action */
DEBUG2(printk(KERN_INFO "scsi%ld: AEN %04x, "
"mbox_sts[1]=%04x, mbox_sts[2]=%04x\n",
ha->host_no, mbox_sts[0],
mbox_sts[1], mbox_sts[2]));
break;
case MBOX_ASTS_SELF_TEST_FAILED:
case MBOX_ASTS_LOGIN_FAILED:
/* No action */
DEBUG2(printk("scsi%ld: AEN %04x, mbox_sts[1]=%04x, "
"mbox_sts[2]=%04x, mbox_sts[3]=%04x\n",
ha->host_no, mbox_sts[0], mbox_sts[1],
mbox_sts[2], mbox_sts[3]));
break;
case MBOX_ASTS_DATABASE_CHANGED:
/* Queue AEN information and process it in the DPC
* routine */
if (ha->aen_q_count > 0) {
/* decrement available counter */
ha->aen_q_count--;
for (i = 0; i < MBOX_AEN_REG_COUNT; i++)
ha->aen_q[ha->aen_in].mbox_sts[i] =
mbox_sts[i];
/* print debug message */
DEBUG2(printk("scsi%ld: AEN[%d] %04x queued "
"mb1:0x%x mb2:0x%x mb3:0x%x "
"mb4:0x%x mb5:0x%x\n",
ha->host_no, ha->aen_in,
mbox_sts[0], mbox_sts[1],
mbox_sts[2], mbox_sts[3],
mbox_sts[4], mbox_sts[5]));
/* advance pointer */
ha->aen_in++;
if (ha->aen_in == MAX_AEN_ENTRIES)
ha->aen_in = 0;
/* The DPC routine will process the aen */
set_bit(DPC_AEN, &ha->dpc_flags);
} else {
DEBUG2(printk("scsi%ld: %s: aen %04x, queue "
"overflowed! AEN LOST!!\n",
ha->host_no, __func__,
mbox_sts[0]));
DEBUG2(printk("scsi%ld: DUMP AEN QUEUE\n",
ha->host_no));
for (i = 0; i < MAX_AEN_ENTRIES; i++) {
DEBUG2(printk("AEN[%d] %04x %04x %04x "
"%04x\n", i, mbox_sts[0],
mbox_sts[1], mbox_sts[2],
mbox_sts[3]));
}
}
break;
case MBOX_ASTS_TXSCVR_INSERTED:
DEBUG2(printk(KERN_WARNING
"scsi%ld: AEN %04x Transceiver"
" inserted\n", ha->host_no, mbox_sts[0]));
break;
case MBOX_ASTS_TXSCVR_REMOVED:
DEBUG2(printk(KERN_WARNING
"scsi%ld: AEN %04x Transceiver"
" removed\n", ha->host_no, mbox_sts[0]));
break;
default:
DEBUG2(printk(KERN_WARNING
"scsi%ld: AEN %04x UNKNOWN\n",
ha->host_no, mbox_sts[0]));
break;
}
} else {
DEBUG2(printk("scsi%ld: Unknown mailbox status %08X\n",
ha->host_no, mbox_status));
ha->mbox_status[0] = mbox_status;
}
}
/**
* qla4_8xxx_interrupt_service_routine - isr
* @ha: pointer to host adapter structure.
*
* This is the main interrupt service routine.
* hardware_lock locked upon entry. runs in interrupt context.
**/
void qla4_8xxx_interrupt_service_routine(struct scsi_qla_host *ha,
uint32_t intr_status)
{
/* Process response queue interrupt. */
if (intr_status & HSRX_RISC_IOCB_INT)
qla4xxx_process_response_queue(ha);
/* Process mailbox/asynch event interrupt.*/
if (intr_status & HSRX_RISC_MB_INT)
qla4xxx_isr_decode_mailbox(ha,
readl(&ha->qla4_8xxx_reg->mailbox_out[0]));
/* clear the interrupt */
writel(0, &ha->qla4_8xxx_reg->host_int);
readl(&ha->qla4_8xxx_reg->host_int);
}
/**
* qla4xxx_interrupt_service_routine - isr
* @ha: pointer to host adapter structure.
*
* This is the main interrupt service routine.
* hardware_lock locked upon entry. runs in interrupt context.
**/
void qla4xxx_interrupt_service_routine(struct scsi_qla_host * ha,
uint32_t intr_status)
{
/* Process response queue interrupt. */
if (intr_status & CSR_SCSI_COMPLETION_INTR)
qla4xxx_process_response_queue(ha);
/* Process mailbox/asynch event interrupt.*/
if (intr_status & CSR_SCSI_PROCESSOR_INTR) {
qla4xxx_isr_decode_mailbox(ha,
readl(&ha->reg->mailbox[0]));
/* Clear Mailbox Interrupt */
writel(set_rmask(CSR_SCSI_PROCESSOR_INTR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
}
}
/**
* qla4_8xxx_spurious_interrupt - processes spurious interrupt
* @ha: pointer to host adapter structure.
* @reqs_count: .
*
**/
static void qla4_8xxx_spurious_interrupt(struct scsi_qla_host *ha,
uint8_t reqs_count)
{
if (reqs_count)
return;
DEBUG2(ql4_printk(KERN_INFO, ha, "Spurious Interrupt\n"));
if (is_qla8022(ha)) {
writel(0, &ha->qla4_8xxx_reg->host_int);
if (test_bit(AF_INTx_ENABLED, &ha->flags))
qla4_8xxx_wr_32(ha, ha->nx_legacy_intr.tgt_mask_reg,
0xfbff);
}
ha->spurious_int_count++;
}
/**
* qla4xxx_intr_handler - hardware interrupt handler.
* @irq: Unused
* @dev_id: Pointer to host adapter structure
**/
irqreturn_t qla4xxx_intr_handler(int irq, void *dev_id)
{
struct scsi_qla_host *ha;
uint32_t intr_status;
unsigned long flags = 0;
uint8_t reqs_count = 0;
ha = (struct scsi_qla_host *) dev_id;
if (!ha) {
DEBUG2(printk(KERN_INFO
"qla4xxx: Interrupt with NULL host ptr\n"));
return IRQ_NONE;
}
spin_lock_irqsave(&ha->hardware_lock, flags);
ha->isr_count++;
/*
* Repeatedly service interrupts up to a maximum of
* MAX_REQS_SERVICED_PER_INTR
*/
while (1) {
/*
* Read interrupt status
*/
if (ha->isp_ops->rd_shdw_rsp_q_in(ha) !=
ha->response_out)
intr_status = CSR_SCSI_COMPLETION_INTR;
else
intr_status = readl(&ha->reg->ctrl_status);
if ((intr_status &
(CSR_SCSI_RESET_INTR|CSR_FATAL_ERROR|INTR_PENDING)) == 0) {
if (reqs_count == 0)
ha->spurious_int_count++;
break;
}
if (intr_status & CSR_FATAL_ERROR) {
DEBUG2(printk(KERN_INFO "scsi%ld: Fatal Error, "
"Status 0x%04x\n", ha->host_no,
readl(isp_port_error_status (ha))));
/* Issue Soft Reset to clear this error condition.
* This will prevent the RISC from repeatedly
* interrupting the driver; thus, allowing the DPC to
* get scheduled to continue error recovery.
* NOTE: Disabling RISC interrupts does not work in
* this case, as CSR_FATAL_ERROR overrides
* CSR_SCSI_INTR_ENABLE */
if ((readl(&ha->reg->ctrl_status) &
CSR_SCSI_RESET_INTR) == 0) {
writel(set_rmask(CSR_SOFT_RESET),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
}
writel(set_rmask(CSR_FATAL_ERROR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
__qla4xxx_disable_intrs(ha);
set_bit(DPC_RESET_HA, &ha->dpc_flags);
break;
} else if (intr_status & CSR_SCSI_RESET_INTR) {
clear_bit(AF_ONLINE, &ha->flags);
__qla4xxx_disable_intrs(ha);
writel(set_rmask(CSR_SCSI_RESET_INTR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
if (!test_bit(AF_HA_REMOVAL, &ha->flags))
set_bit(DPC_RESET_HA_INTR, &ha->dpc_flags);
break;
} else if (intr_status & INTR_PENDING) {
ha->isp_ops->interrupt_service_routine(ha, intr_status);
ha->total_io_count++;
if (++reqs_count == MAX_REQS_SERVICED_PER_INTR)
break;
}
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
return IRQ_HANDLED;
}
/**
* qla4_8xxx_intr_handler - hardware interrupt handler.
* @irq: Unused
* @dev_id: Pointer to host adapter structure
**/
irqreturn_t qla4_8xxx_intr_handler(int irq, void *dev_id)
{
struct scsi_qla_host *ha = dev_id;
uint32_t intr_status;
uint32_t status;
unsigned long flags = 0;
uint8_t reqs_count = 0;
if (unlikely(pci_channel_offline(ha->pdev)))
return IRQ_HANDLED;
ha->isr_count++;
status = qla4_8xxx_rd_32(ha, ISR_INT_VECTOR);
if (!(status & ha->nx_legacy_intr.int_vec_bit))
return IRQ_NONE;
status = qla4_8xxx_rd_32(ha, ISR_INT_STATE_REG);
if (!ISR_IS_LEGACY_INTR_TRIGGERED(status)) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s legacy Int not triggered\n", __func__));
return IRQ_NONE;
}
/* clear the interrupt */
qla4_8xxx_wr_32(ha, ha->nx_legacy_intr.tgt_status_reg, 0xffffffff);
/* read twice to ensure write is flushed */
qla4_8xxx_rd_32(ha, ISR_INT_VECTOR);
qla4_8xxx_rd_32(ha, ISR_INT_VECTOR);
spin_lock_irqsave(&ha->hardware_lock, flags);
while (1) {
if (!(readl(&ha->qla4_8xxx_reg->host_int) &
ISRX_82XX_RISC_INT)) {
qla4_8xxx_spurious_interrupt(ha, reqs_count);
break;
}
intr_status = readl(&ha->qla4_8xxx_reg->host_status);
if ((intr_status &
(HSRX_RISC_MB_INT | HSRX_RISC_IOCB_INT)) == 0) {
qla4_8xxx_spurious_interrupt(ha, reqs_count);
break;
}
ha->isp_ops->interrupt_service_routine(ha, intr_status);
/* Enable Interrupt */
qla4_8xxx_wr_32(ha, ha->nx_legacy_intr.tgt_mask_reg, 0xfbff);
if (++reqs_count == MAX_REQS_SERVICED_PER_INTR)
break;
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
return IRQ_HANDLED;
}
irqreturn_t
qla4_8xxx_msi_handler(int irq, void *dev_id)
{
struct scsi_qla_host *ha;
ha = (struct scsi_qla_host *) dev_id;
if (!ha) {
DEBUG2(printk(KERN_INFO
"qla4xxx: MSIX: Interrupt with NULL host ptr\n"));
return IRQ_NONE;
}
ha->isr_count++;
/* clear the interrupt */
qla4_8xxx_wr_32(ha, ha->nx_legacy_intr.tgt_status_reg, 0xffffffff);
/* read twice to ensure write is flushed */
qla4_8xxx_rd_32(ha, ISR_INT_VECTOR);
qla4_8xxx_rd_32(ha, ISR_INT_VECTOR);
return qla4_8xxx_default_intr_handler(irq, dev_id);
}
/**
* qla4_8xxx_default_intr_handler - hardware interrupt handler.
* @irq: Unused
* @dev_id: Pointer to host adapter structure
*
* This interrupt handler is called directly for MSI-X, and
* called indirectly for MSI.
**/
irqreturn_t
qla4_8xxx_default_intr_handler(int irq, void *dev_id)
{
struct scsi_qla_host *ha = dev_id;
unsigned long flags;
uint32_t intr_status;
uint8_t reqs_count = 0;
spin_lock_irqsave(&ha->hardware_lock, flags);
while (1) {
if (!(readl(&ha->qla4_8xxx_reg->host_int) &
ISRX_82XX_RISC_INT)) {
qla4_8xxx_spurious_interrupt(ha, reqs_count);
break;
}
intr_status = readl(&ha->qla4_8xxx_reg->host_status);
if ((intr_status &
(HSRX_RISC_MB_INT | HSRX_RISC_IOCB_INT)) == 0) {
qla4_8xxx_spurious_interrupt(ha, reqs_count);
break;
}
ha->isp_ops->interrupt_service_routine(ha, intr_status);
if (++reqs_count == MAX_REQS_SERVICED_PER_INTR)
break;
}
ha->isr_count++;
spin_unlock_irqrestore(&ha->hardware_lock, flags);
return IRQ_HANDLED;
}
irqreturn_t
qla4_8xxx_msix_rsp_q(int irq, void *dev_id)
{
struct scsi_qla_host *ha = dev_id;
unsigned long flags;
spin_lock_irqsave(&ha->hardware_lock, flags);
qla4xxx_process_response_queue(ha);
writel(0, &ha->qla4_8xxx_reg->host_int);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
ha->isr_count++;
return IRQ_HANDLED;
}
/**
* qla4xxx_process_aen - processes AENs generated by firmware
* @ha: pointer to host adapter structure.
* @process_aen: type of AENs to process
*
* Processes specific types of Asynchronous Events generated by firmware.
* The type of AENs to process is specified by process_aen and can be
* PROCESS_ALL_AENS 0
* FLUSH_DDB_CHANGED_AENS 1
* RELOGIN_DDB_CHANGED_AENS 2
**/
void qla4xxx_process_aen(struct scsi_qla_host * ha, uint8_t process_aen)
{
uint32_t mbox_sts[MBOX_AEN_REG_COUNT];
struct aen *aen;
int i;
unsigned long flags;
spin_lock_irqsave(&ha->hardware_lock, flags);
while (ha->aen_out != ha->aen_in) {
aen = &ha->aen_q[ha->aen_out];
/* copy aen information to local structure */
for (i = 0; i < MBOX_AEN_REG_COUNT; i++)
mbox_sts[i] = aen->mbox_sts[i];
ha->aen_q_count++;
ha->aen_out++;
if (ha->aen_out == MAX_AEN_ENTRIES)
ha->aen_out = 0;
spin_unlock_irqrestore(&ha->hardware_lock, flags);
DEBUG2(printk("qla4xxx(%ld): AEN[%d]=0x%08x, mbx1=0x%08x mbx2=0x%08x"
" mbx3=0x%08x mbx4=0x%08x\n", ha->host_no,
(ha->aen_out ? (ha->aen_out-1): (MAX_AEN_ENTRIES-1)),
mbox_sts[0], mbox_sts[1], mbox_sts[2],
mbox_sts[3], mbox_sts[4]));
switch (mbox_sts[0]) {
case MBOX_ASTS_DATABASE_CHANGED:
if (process_aen == FLUSH_DDB_CHANGED_AENS) {
DEBUG2(printk("scsi%ld: AEN[%d] %04x, index "
"[%d] state=%04x FLUSHED!\n",
ha->host_no, ha->aen_out,
mbox_sts[0], mbox_sts[2],
mbox_sts[3]));
break;
}
case PROCESS_ALL_AENS:
default:
if (mbox_sts[1] == 0) { /* Global DB change. */
qla4xxx_reinitialize_ddb_list(ha);
} else if (mbox_sts[1] == 1) { /* Specific device. */
qla4xxx_process_ddb_changed(ha, mbox_sts[2],
mbox_sts[3], mbox_sts[4]);
}
break;
}
spin_lock_irqsave(&ha->hardware_lock, flags);
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
}
int qla4xxx_request_irqs(struct scsi_qla_host *ha)
{
int ret;
if (!is_qla8022(ha))
goto try_intx;
if (ql4xenablemsix == 2)
goto try_msi;
if (ql4xenablemsix == 0 || ql4xenablemsix != 1)
goto try_intx;
/* Trying MSI-X */
ret = qla4_8xxx_enable_msix(ha);
if (!ret) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"MSI-X: Enabled (0x%X).\n", ha->revision_id));
goto irq_attached;
}
ql4_printk(KERN_WARNING, ha,
"MSI-X: Falling back-to MSI mode -- %d.\n", ret);
try_msi:
/* Trying MSI */
ret = pci_enable_msi(ha->pdev);
if (!ret) {
ret = request_irq(ha->pdev->irq, qla4_8xxx_msi_handler,
0, DRIVER_NAME, ha);
if (!ret) {
DEBUG2(ql4_printk(KERN_INFO, ha, "MSI: Enabled.\n"));
set_bit(AF_MSI_ENABLED, &ha->flags);
goto irq_attached;
} else {
ql4_printk(KERN_WARNING, ha,
"MSI: Failed to reserve interrupt %d "
"already in use.\n", ha->pdev->irq);
pci_disable_msi(ha->pdev);
}
}
ql4_printk(KERN_WARNING, ha,
"MSI: Falling back-to INTx mode -- %d.\n", ret);
try_intx:
/* Trying INTx */
ret = request_irq(ha->pdev->irq, ha->isp_ops->intr_handler,
IRQF_SHARED, DRIVER_NAME, ha);
if (!ret) {
DEBUG2(ql4_printk(KERN_INFO, ha, "INTx: Enabled.\n"));
set_bit(AF_INTx_ENABLED, &ha->flags);
goto irq_attached;
} else {
ql4_printk(KERN_WARNING, ha,
"INTx: Failed to reserve interrupt %d already in"
" use.\n", ha->pdev->irq);
return ret;
}
irq_attached:
set_bit(AF_IRQ_ATTACHED, &ha->flags);
ha->host->irq = ha->pdev->irq;
ql4_printk(KERN_INFO, ha, "%s: irq %d attached\n",
__func__, ha->pdev->irq);
return ret;
}
void qla4xxx_free_irqs(struct scsi_qla_host *ha)
{
if (test_bit(AF_MSIX_ENABLED, &ha->flags))
qla4_8xxx_disable_msix(ha);
else if (test_and_clear_bit(AF_MSI_ENABLED, &ha->flags)) {
free_irq(ha->pdev->irq, ha);
pci_disable_msi(ha->pdev);
} else if (test_and_clear_bit(AF_INTx_ENABLED, &ha->flags))
free_irq(ha->pdev->irq, ha);
}
| gpl-2.0 |
derekcentrico/m6.kernel.3.x | drivers/media/video/tveeprom.c | 3037 | 26119 | /*
* tveeprom - eeprom decoder for tvcard configuration eeproms
*
* Data and decoding routines shamelessly borrowed from bttv-cards.c
* eeprom access routine shamelessly borrowed from bttv-if.c
* which are:
Copyright (C) 1996,97,98 Ralph Metzler (rjkm@thp.uni-koeln.de)
& Marcus Metzler (mocm@thp.uni-koeln.de)
(c) 1999-2001 Gerd Knorr <kraxel@goldbach.in-berlin.de>
* Adjustments to fit a more general model and all bugs:
Copyright (C) 2003 John Klar <linpvr at projectplasma.com>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <media/tuner.h>
#include <media/tveeprom.h>
#include <media/v4l2-common.h>
#include <media/v4l2-chip-ident.h>
MODULE_DESCRIPTION("i2c Hauppauge eeprom decoder driver");
MODULE_AUTHOR("John Klar");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
#define STRM(array, i) \
(i < sizeof(array) / sizeof(char *) ? array[i] : "unknown")
#define tveeprom_info(fmt, arg...) \
v4l_printk(KERN_INFO, "tveeprom", c->adapter, c->addr, fmt , ## arg)
#define tveeprom_warn(fmt, arg...) \
v4l_printk(KERN_WARNING, "tveeprom", c->adapter, c->addr, fmt , ## arg)
#define tveeprom_dbg(fmt, arg...) do { \
if (debug) \
v4l_printk(KERN_DEBUG, "tveeprom", \
c->adapter, c->addr, fmt , ## arg); \
} while (0)
/*
* The Hauppauge eeprom uses an 8bit field to determine which
* tuner formats the tuner supports.
*/
static struct HAUPPAUGE_TUNER_FMT
{
int id;
char *name;
}
hauppauge_tuner_fmt[] =
{
{ V4L2_STD_UNKNOWN, " UNKNOWN" },
{ V4L2_STD_UNKNOWN, " FM" },
{ V4L2_STD_B|V4L2_STD_GH, " PAL(B/G)" },
{ V4L2_STD_MN, " NTSC(M)" },
{ V4L2_STD_PAL_I, " PAL(I)" },
{ V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC, " SECAM(L/L')" },
{ V4L2_STD_DK, " PAL(D/D1/K)" },
{ V4L2_STD_ATSC, " ATSC/DVB Digital" },
};
/* This is the full list of possible tuners. Many thanks to Hauppauge for
supplying this information. Note that many tuners where only used for
testing and never made it to the outside world. So you will only see
a subset in actual produced cards. */
static struct HAUPPAUGE_TUNER
{
int id;
char *name;
}
hauppauge_tuner[] =
{
/* 0-9 */
{ TUNER_ABSENT, "None" },
{ TUNER_ABSENT, "External" },
{ TUNER_ABSENT, "Unspecified" },
{ TUNER_PHILIPS_PAL, "Philips FI1216" },
{ TUNER_PHILIPS_SECAM, "Philips FI1216MF" },
{ TUNER_PHILIPS_NTSC, "Philips FI1236" },
{ TUNER_PHILIPS_PAL_I, "Philips FI1246" },
{ TUNER_PHILIPS_PAL_DK, "Philips FI1256" },
{ TUNER_PHILIPS_PAL, "Philips FI1216 MK2" },
{ TUNER_PHILIPS_SECAM, "Philips FI1216MF MK2" },
/* 10-19 */
{ TUNER_PHILIPS_NTSC, "Philips FI1236 MK2" },
{ TUNER_PHILIPS_PAL_I, "Philips FI1246 MK2" },
{ TUNER_PHILIPS_PAL_DK, "Philips FI1256 MK2" },
{ TUNER_TEMIC_NTSC, "Temic 4032FY5" },
{ TUNER_TEMIC_PAL, "Temic 4002FH5" },
{ TUNER_TEMIC_PAL_I, "Temic 4062FY5" },
{ TUNER_PHILIPS_PAL, "Philips FR1216 MK2" },
{ TUNER_PHILIPS_SECAM, "Philips FR1216MF MK2" },
{ TUNER_PHILIPS_NTSC, "Philips FR1236 MK2" },
{ TUNER_PHILIPS_PAL_I, "Philips FR1246 MK2" },
/* 20-29 */
{ TUNER_PHILIPS_PAL_DK, "Philips FR1256 MK2" },
{ TUNER_PHILIPS_PAL, "Philips FM1216" },
{ TUNER_PHILIPS_SECAM, "Philips FM1216MF" },
{ TUNER_PHILIPS_NTSC, "Philips FM1236" },
{ TUNER_PHILIPS_PAL_I, "Philips FM1246" },
{ TUNER_PHILIPS_PAL_DK, "Philips FM1256" },
{ TUNER_TEMIC_4036FY5_NTSC, "Temic 4036FY5" },
{ TUNER_ABSENT, "Samsung TCPN9082D" },
{ TUNER_ABSENT, "Samsung TCPM9092P" },
{ TUNER_TEMIC_4006FH5_PAL, "Temic 4006FH5" },
/* 30-39 */
{ TUNER_ABSENT, "Samsung TCPN9085D" },
{ TUNER_ABSENT, "Samsung TCPB9085P" },
{ TUNER_ABSENT, "Samsung TCPL9091P" },
{ TUNER_TEMIC_4039FR5_NTSC, "Temic 4039FR5" },
{ TUNER_PHILIPS_FQ1216ME, "Philips FQ1216 ME" },
{ TUNER_TEMIC_4066FY5_PAL_I, "Temic 4066FY5" },
{ TUNER_PHILIPS_NTSC, "Philips TD1536" },
{ TUNER_PHILIPS_NTSC, "Philips TD1536D" },
{ TUNER_PHILIPS_NTSC, "Philips FMR1236" }, /* mono radio */
{ TUNER_ABSENT, "Philips FI1256MP" },
/* 40-49 */
{ TUNER_ABSENT, "Samsung TCPQ9091P" },
{ TUNER_TEMIC_4006FN5_MULTI_PAL, "Temic 4006FN5" },
{ TUNER_TEMIC_4009FR5_PAL, "Temic 4009FR5" },
{ TUNER_TEMIC_4046FM5, "Temic 4046FM5" },
{ TUNER_TEMIC_4009FN5_MULTI_PAL_FM, "Temic 4009FN5" },
{ TUNER_ABSENT, "Philips TD1536D FH 44"},
{ TUNER_LG_NTSC_FM, "LG TP18NSR01F"},
{ TUNER_LG_PAL_FM, "LG TP18PSB01D"},
{ TUNER_LG_PAL, "LG TP18PSB11D"},
{ TUNER_LG_PAL_I_FM, "LG TAPC-I001D"},
/* 50-59 */
{ TUNER_LG_PAL_I, "LG TAPC-I701D"},
{ TUNER_ABSENT, "Temic 4042FI5"},
{ TUNER_MICROTUNE_4049FM5, "Microtune 4049 FM5"},
{ TUNER_ABSENT, "LG TPI8NSR11F"},
{ TUNER_ABSENT, "Microtune 4049 FM5 Alt I2C"},
{ TUNER_PHILIPS_FM1216ME_MK3, "Philips FQ1216ME MK3"},
{ TUNER_ABSENT, "Philips FI1236 MK3"},
{ TUNER_PHILIPS_FM1216ME_MK3, "Philips FM1216 ME MK3"},
{ TUNER_PHILIPS_FM1236_MK3, "Philips FM1236 MK3"},
{ TUNER_ABSENT, "Philips FM1216MP MK3"},
/* 60-69 */
{ TUNER_PHILIPS_FM1216ME_MK3, "LG S001D MK3"},
{ TUNER_ABSENT, "LG M001D MK3"},
{ TUNER_PHILIPS_FM1216ME_MK3, "LG S701D MK3"},
{ TUNER_ABSENT, "LG M701D MK3"},
{ TUNER_ABSENT, "Temic 4146FM5"},
{ TUNER_ABSENT, "Temic 4136FY5"},
{ TUNER_ABSENT, "Temic 4106FH5"},
{ TUNER_ABSENT, "Philips FQ1216LMP MK3"},
{ TUNER_LG_NTSC_TAPE, "LG TAPE H001F MK3"},
{ TUNER_LG_NTSC_TAPE, "LG TAPE H701F MK3"},
/* 70-79 */
{ TUNER_ABSENT, "LG TALN H200T"},
{ TUNER_ABSENT, "LG TALN H250T"},
{ TUNER_ABSENT, "LG TALN M200T"},
{ TUNER_ABSENT, "LG TALN Z200T"},
{ TUNER_ABSENT, "LG TALN S200T"},
{ TUNER_ABSENT, "Thompson DTT7595"},
{ TUNER_ABSENT, "Thompson DTT7592"},
{ TUNER_ABSENT, "Silicon TDA8275C1 8290"},
{ TUNER_ABSENT, "Silicon TDA8275C1 8290 FM"},
{ TUNER_ABSENT, "Thompson DTT757"},
/* 80-89 */
{ TUNER_PHILIPS_FQ1216LME_MK3, "Philips FQ1216LME MK3"},
{ TUNER_LG_PAL_NEW_TAPC, "LG TAPC G701D"},
{ TUNER_LG_NTSC_NEW_TAPC, "LG TAPC H791F"},
{ TUNER_LG_PAL_NEW_TAPC, "TCL 2002MB 3"},
{ TUNER_LG_PAL_NEW_TAPC, "TCL 2002MI 3"},
{ TUNER_TCL_2002N, "TCL 2002N 6A"},
{ TUNER_PHILIPS_FM1236_MK3, "Philips FQ1236 MK3"},
{ TUNER_SAMSUNG_TCPN_2121P30A, "Samsung TCPN 2121P30A"},
{ TUNER_ABSENT, "Samsung TCPE 4121P30A"},
{ TUNER_PHILIPS_FM1216ME_MK3, "TCL MFPE05 2"},
/* 90-99 */
{ TUNER_ABSENT, "LG TALN H202T"},
{ TUNER_PHILIPS_FQ1216AME_MK4, "Philips FQ1216AME MK4"},
{ TUNER_PHILIPS_FQ1236A_MK4, "Philips FQ1236A MK4"},
{ TUNER_ABSENT, "Philips FQ1286A MK4"},
{ TUNER_ABSENT, "Philips FQ1216ME MK5"},
{ TUNER_ABSENT, "Philips FQ1236 MK5"},
{ TUNER_SAMSUNG_TCPG_6121P30A, "Samsung TCPG 6121P30A"},
{ TUNER_TCL_2002MB, "TCL 2002MB_3H"},
{ TUNER_ABSENT, "TCL 2002MI_3H"},
{ TUNER_TCL_2002N, "TCL 2002N 5H"},
/* 100-109 */
{ TUNER_PHILIPS_FMD1216ME_MK3, "Philips FMD1216ME"},
{ TUNER_TEA5767, "Philips TEA5768HL FM Radio"},
{ TUNER_ABSENT, "Panasonic ENV57H12D5"},
{ TUNER_PHILIPS_FM1236_MK3, "TCL MFNM05-4"},
{ TUNER_PHILIPS_FM1236_MK3, "TCL MNM05-4"},
{ TUNER_PHILIPS_FM1216ME_MK3, "TCL MPE05-2"},
{ TUNER_ABSENT, "TCL MQNM05-4"},
{ TUNER_ABSENT, "LG TAPC-W701D"},
{ TUNER_ABSENT, "TCL 9886P-WM"},
{ TUNER_ABSENT, "TCL 1676NM-WM"},
/* 110-119 */
{ TUNER_ABSENT, "Thompson DTT75105"},
{ TUNER_ABSENT, "Conexant_CX24109"},
{ TUNER_TCL_2002N, "TCL M2523_5N_E"},
{ TUNER_TCL_2002MB, "TCL M2523_3DB_E"},
{ TUNER_ABSENT, "Philips 8275A"},
{ TUNER_ABSENT, "Microtune MT2060"},
{ TUNER_PHILIPS_FM1236_MK3, "Philips FM1236 MK5"},
{ TUNER_PHILIPS_FM1216ME_MK3, "Philips FM1216ME MK5"},
{ TUNER_ABSENT, "TCL M2523_3DI_E"},
{ TUNER_ABSENT, "Samsung THPD5222FG30A"},
/* 120-129 */
{ TUNER_XC2028, "Xceive XC3028"},
{ TUNER_PHILIPS_FQ1216LME_MK3, "Philips FQ1216LME MK5"},
{ TUNER_ABSENT, "Philips FQD1216LME"},
{ TUNER_ABSENT, "Conexant CX24118A"},
{ TUNER_ABSENT, "TCL DMF11WIP"},
{ TUNER_ABSENT, "TCL MFNM05_4H_E"},
{ TUNER_ABSENT, "TCL MNM05_4H_E"},
{ TUNER_ABSENT, "TCL MPE05_2H_E"},
{ TUNER_ABSENT, "TCL MQNM05_4_U"},
{ TUNER_ABSENT, "TCL M2523_5NH_E"},
/* 130-139 */
{ TUNER_ABSENT, "TCL M2523_3DBH_E"},
{ TUNER_ABSENT, "TCL M2523_3DIH_E"},
{ TUNER_ABSENT, "TCL MFPE05_2_U"},
{ TUNER_PHILIPS_FMD1216MEX_MK3, "Philips FMD1216MEX"},
{ TUNER_ABSENT, "Philips FRH2036B"},
{ TUNER_ABSENT, "Panasonic ENGF75_01GF"},
{ TUNER_ABSENT, "MaxLinear MXL5005"},
{ TUNER_ABSENT, "MaxLinear MXL5003"},
{ TUNER_ABSENT, "Xceive XC2028"},
{ TUNER_ABSENT, "Microtune MT2131"},
/* 140-149 */
{ TUNER_ABSENT, "Philips 8275A_8295"},
{ TUNER_ABSENT, "TCL MF02GIP_5N_E"},
{ TUNER_ABSENT, "TCL MF02GIP_3DB_E"},
{ TUNER_ABSENT, "TCL MF02GIP_3DI_E"},
{ TUNER_ABSENT, "Microtune MT2266"},
{ TUNER_ABSENT, "TCL MF10WPP_4N_E"},
{ TUNER_ABSENT, "LG TAPQ_H702F"},
{ TUNER_ABSENT, "TCL M09WPP_4N_E"},
{ TUNER_ABSENT, "MaxLinear MXL5005_v2"},
{ TUNER_PHILIPS_TDA8290, "Philips 18271_8295"},
/* 150-159 */
{ TUNER_XC5000, "Xceive XC5000"},
{ TUNER_ABSENT, "Xceive XC3028L"},
{ TUNER_ABSENT, "NXP 18271C2_716x"},
{ TUNER_ABSENT, "Xceive XC4000"},
{ TUNER_ABSENT, "Dibcom 7070"},
{ TUNER_PHILIPS_TDA8290, "NXP 18271C2"},
{ TUNER_ABSENT, "Siano SMS1010"},
{ TUNER_ABSENT, "Siano SMS1150"},
{ TUNER_ABSENT, "MaxLinear 5007"},
{ TUNER_ABSENT, "TCL M09WPP_2P_E"},
/* 160-169 */
{ TUNER_ABSENT, "Siano SMS1180"},
{ TUNER_ABSENT, "Maxim_MAX2165"},
{ TUNER_ABSENT, "Siano SMS1140"},
{ TUNER_ABSENT, "Siano SMS1150 B1"},
{ TUNER_ABSENT, "MaxLinear 111"},
{ TUNER_ABSENT, "Dibcom 7770"},
{ TUNER_ABSENT, "Siano SMS1180VNS"},
{ TUNER_ABSENT, "Siano SMS1184"},
{ TUNER_PHILIPS_FQ1236_MK5, "TCL M30WTP-4N-E"},
{ TUNER_ABSENT, "TCL_M11WPP_2PN_E"},
/* 170-179 */
{ TUNER_ABSENT, "MaxLinear 301"},
{ TUNER_ABSENT, "Mirics MSi001"},
{ TUNER_ABSENT, "MaxLinear MxL241SF"},
{ TUNER_ABSENT, "Xceive XC5000C"},
{ TUNER_ABSENT, "Montage M68TS2020"},
};
/* Use V4L2_IDENT_AMBIGUOUS for those audio 'chips' that are
* internal to a video chip, i.e. not a separate audio chip. */
static struct HAUPPAUGE_AUDIOIC
{
u32 id;
char *name;
}
audioIC[] =
{
/* 0-4 */
{ V4L2_IDENT_NONE, "None" },
{ V4L2_IDENT_UNKNOWN, "TEA6300" },
{ V4L2_IDENT_UNKNOWN, "TEA6320" },
{ V4L2_IDENT_UNKNOWN, "TDA9850" },
{ V4L2_IDENT_MSPX4XX, "MSP3400C" },
/* 5-9 */
{ V4L2_IDENT_MSPX4XX, "MSP3410D" },
{ V4L2_IDENT_MSPX4XX, "MSP3415" },
{ V4L2_IDENT_MSPX4XX, "MSP3430" },
{ V4L2_IDENT_MSPX4XX, "MSP3438" },
{ V4L2_IDENT_UNKNOWN, "CS5331" },
/* 10-14 */
{ V4L2_IDENT_MSPX4XX, "MSP3435" },
{ V4L2_IDENT_MSPX4XX, "MSP3440" },
{ V4L2_IDENT_MSPX4XX, "MSP3445" },
{ V4L2_IDENT_MSPX4XX, "MSP3411" },
{ V4L2_IDENT_MSPX4XX, "MSP3416" },
/* 15-19 */
{ V4L2_IDENT_MSPX4XX, "MSP3425" },
{ V4L2_IDENT_MSPX4XX, "MSP3451" },
{ V4L2_IDENT_MSPX4XX, "MSP3418" },
{ V4L2_IDENT_UNKNOWN, "Type 0x12" },
{ V4L2_IDENT_UNKNOWN, "OKI7716" },
/* 20-24 */
{ V4L2_IDENT_MSPX4XX, "MSP4410" },
{ V4L2_IDENT_MSPX4XX, "MSP4420" },
{ V4L2_IDENT_MSPX4XX, "MSP4440" },
{ V4L2_IDENT_MSPX4XX, "MSP4450" },
{ V4L2_IDENT_MSPX4XX, "MSP4408" },
/* 25-29 */
{ V4L2_IDENT_MSPX4XX, "MSP4418" },
{ V4L2_IDENT_MSPX4XX, "MSP4428" },
{ V4L2_IDENT_MSPX4XX, "MSP4448" },
{ V4L2_IDENT_MSPX4XX, "MSP4458" },
{ V4L2_IDENT_MSPX4XX, "Type 0x1d" },
/* 30-34 */
{ V4L2_IDENT_AMBIGUOUS, "CX880" },
{ V4L2_IDENT_AMBIGUOUS, "CX881" },
{ V4L2_IDENT_AMBIGUOUS, "CX883" },
{ V4L2_IDENT_AMBIGUOUS, "CX882" },
{ V4L2_IDENT_AMBIGUOUS, "CX25840" },
/* 35-39 */
{ V4L2_IDENT_AMBIGUOUS, "CX25841" },
{ V4L2_IDENT_AMBIGUOUS, "CX25842" },
{ V4L2_IDENT_AMBIGUOUS, "CX25843" },
{ V4L2_IDENT_AMBIGUOUS, "CX23418" },
{ V4L2_IDENT_AMBIGUOUS, "CX23885" },
/* 40-44 */
{ V4L2_IDENT_AMBIGUOUS, "CX23888" },
{ V4L2_IDENT_AMBIGUOUS, "SAA7131" },
{ V4L2_IDENT_AMBIGUOUS, "CX23887" },
{ V4L2_IDENT_AMBIGUOUS, "SAA7164" },
{ V4L2_IDENT_AMBIGUOUS, "AU8522" },
};
/* This list is supplied by Hauppauge. Thanks! */
static const char *decoderIC[] = {
/* 0-4 */
"None", "BT815", "BT817", "BT819", "BT815A",
/* 5-9 */
"BT817A", "BT819A", "BT827", "BT829", "BT848",
/* 10-14 */
"BT848A", "BT849A", "BT829A", "BT827A", "BT878",
/* 15-19 */
"BT879", "BT880", "VPX3226E", "SAA7114", "SAA7115",
/* 20-24 */
"CX880", "CX881", "CX883", "SAA7111", "SAA7113",
/* 25-29 */
"CX882", "TVP5150A", "CX25840", "CX25841", "CX25842",
/* 30-34 */
"CX25843", "CX23418", "NEC61153", "CX23885", "CX23888",
/* 35-39 */
"SAA7131", "CX25837", "CX23887", "CX23885A", "CX23887A",
/* 40-42 */
"SAA7164", "CX23885B", "AU8522"
};
static int hasRadioTuner(int tunerType)
{
switch (tunerType) {
case 18: /* PNPEnv_TUNER_FR1236_MK2 */
case 23: /* PNPEnv_TUNER_FM1236 */
case 38: /* PNPEnv_TUNER_FMR1236 */
case 16: /* PNPEnv_TUNER_FR1216_MK2 */
case 19: /* PNPEnv_TUNER_FR1246_MK2 */
case 21: /* PNPEnv_TUNER_FM1216 */
case 24: /* PNPEnv_TUNER_FM1246 */
case 17: /* PNPEnv_TUNER_FR1216MF_MK2 */
case 22: /* PNPEnv_TUNER_FM1216MF */
case 20: /* PNPEnv_TUNER_FR1256_MK2 */
case 25: /* PNPEnv_TUNER_FM1256 */
case 33: /* PNPEnv_TUNER_4039FR5 */
case 42: /* PNPEnv_TUNER_4009FR5 */
case 52: /* PNPEnv_TUNER_4049FM5 */
case 54: /* PNPEnv_TUNER_4049FM5_AltI2C */
case 44: /* PNPEnv_TUNER_4009FN5 */
case 31: /* PNPEnv_TUNER_TCPB9085P */
case 30: /* PNPEnv_TUNER_TCPN9085D */
case 46: /* PNPEnv_TUNER_TP18NSR01F */
case 47: /* PNPEnv_TUNER_TP18PSB01D */
case 49: /* PNPEnv_TUNER_TAPC_I001D */
case 60: /* PNPEnv_TUNER_TAPE_S001D_MK3 */
case 57: /* PNPEnv_TUNER_FM1216ME_MK3 */
case 59: /* PNPEnv_TUNER_FM1216MP_MK3 */
case 58: /* PNPEnv_TUNER_FM1236_MK3 */
case 68: /* PNPEnv_TUNER_TAPE_H001F_MK3 */
case 61: /* PNPEnv_TUNER_TAPE_M001D_MK3 */
case 78: /* PNPEnv_TUNER_TDA8275C1_8290_FM */
case 89: /* PNPEnv_TUNER_TCL_MFPE05_2 */
case 92: /* PNPEnv_TUNER_PHILIPS_FQ1236A_MK4 */
case 105:
return 1;
}
return 0;
}
void tveeprom_hauppauge_analog(struct i2c_client *c, struct tveeprom *tvee,
unsigned char *eeprom_data)
{
/* ----------------------------------------------
** The hauppauge eeprom format is tagged
**
** if packet[0] == 0x84, then packet[0..1] == length
** else length = packet[0] & 3f;
** if packet[0] & f8 == f8, then EOD and packet[1] == checksum
**
** In our (ivtv) case we're interested in the following:
** tuner type: tag [00].05 or [0a].01 (index into hauppauge_tuner)
** tuner fmts: tag [00].04 or [0a].00 (bitmask index into
** hauppauge_tuner_fmt)
** radio: tag [00].{last} or [0e].00 (bitmask. bit2=FM)
** audio proc: tag [02].01 or [05].00 (mask with 0x7f)
** decoder proc: tag [09].01)
** Fun info:
** model: tag [00].07-08 or [06].00-01
** revision: tag [00].09-0b or [06].04-06
** serial#: tag [01].05-07 or [04].04-06
** # of inputs/outputs ???
*/
int i, j, len, done, beenhere, tag, start;
int tuner1 = 0, t_format1 = 0, audioic = -1;
char *t_name1 = NULL;
const char *t_fmt_name1[8] = { " none", "", "", "", "", "", "", "" };
int tuner2 = 0, t_format2 = 0;
char *t_name2 = NULL;
const char *t_fmt_name2[8] = { " none", "", "", "", "", "", "", "" };
memset(tvee, 0, sizeof(*tvee));
tvee->tuner_type = TUNER_ABSENT;
tvee->tuner2_type = TUNER_ABSENT;
done = len = beenhere = 0;
/* Different eeprom start offsets for em28xx, cx2388x and cx23418 */
if (eeprom_data[0] == 0x1a &&
eeprom_data[1] == 0xeb &&
eeprom_data[2] == 0x67 &&
eeprom_data[3] == 0x95)
start = 0xa0; /* Generic em28xx offset */
else if ((eeprom_data[0] & 0xe1) == 0x01 &&
eeprom_data[1] == 0x00 &&
eeprom_data[2] == 0x00 &&
eeprom_data[8] == 0x84)
start = 8; /* Generic cx2388x offset */
else if (eeprom_data[1] == 0x70 &&
eeprom_data[2] == 0x00 &&
eeprom_data[4] == 0x74 &&
eeprom_data[8] == 0x84)
start = 8; /* Generic cx23418 offset (models 74xxx) */
else
start = 0;
for (i = start; !done && i < 256; i += len) {
if (eeprom_data[i] == 0x84) {
len = eeprom_data[i + 1] + (eeprom_data[i + 2] << 8);
i += 3;
} else if ((eeprom_data[i] & 0xf0) == 0x70) {
if (eeprom_data[i] & 0x08) {
/* verify checksum! */
done = 1;
break;
}
len = eeprom_data[i] & 0x07;
++i;
} else {
tveeprom_warn("Encountered bad packet header [%02x]. "
"Corrupt or not a Hauppauge eeprom.\n",
eeprom_data[i]);
return;
}
if (debug) {
tveeprom_info("Tag [%02x] + %d bytes:",
eeprom_data[i], len - 1);
for (j = 1; j < len; j++)
printk(KERN_CONT " %02x", eeprom_data[i + j]);
printk(KERN_CONT "\n");
}
/* process by tag */
tag = eeprom_data[i];
switch (tag) {
case 0x00:
/* tag: 'Comprehensive' */
tuner1 = eeprom_data[i+6];
t_format1 = eeprom_data[i+5];
tvee->has_radio = eeprom_data[i+len-1];
/* old style tag, don't know how to detect
IR presence, mark as unknown. */
tvee->has_ir = 0;
tvee->model =
eeprom_data[i+8] +
(eeprom_data[i+9] << 8);
tvee->revision = eeprom_data[i+10] +
(eeprom_data[i+11] << 8) +
(eeprom_data[i+12] << 16);
break;
case 0x01:
/* tag: 'SerialID' */
tvee->serial_number =
eeprom_data[i+6] +
(eeprom_data[i+7] << 8) +
(eeprom_data[i+8] << 16);
break;
case 0x02:
/* tag 'AudioInfo'
Note mask with 0x7F, high bit used on some older models
to indicate 4052 mux was removed in favor of using MSP
inputs directly. */
audioic = eeprom_data[i+2] & 0x7f;
if (audioic < ARRAY_SIZE(audioIC))
tvee->audio_processor = audioIC[audioic].id;
else
tvee->audio_processor = V4L2_IDENT_UNKNOWN;
break;
/* case 0x03: tag 'EEInfo' */
case 0x04:
/* tag 'SerialID2' */
tvee->serial_number =
eeprom_data[i+5] +
(eeprom_data[i+6] << 8) +
(eeprom_data[i+7] << 16);
if ((eeprom_data[i + 8] & 0xf0) &&
(tvee->serial_number < 0xffffff)) {
tvee->MAC_address[0] = 0x00;
tvee->MAC_address[1] = 0x0D;
tvee->MAC_address[2] = 0xFE;
tvee->MAC_address[3] = eeprom_data[i + 7];
tvee->MAC_address[4] = eeprom_data[i + 6];
tvee->MAC_address[5] = eeprom_data[i + 5];
tvee->has_MAC_address = 1;
}
break;
case 0x05:
/* tag 'Audio2'
Note mask with 0x7F, high bit used on some older models
to indicate 4052 mux was removed in favor of using MSP
inputs directly. */
audioic = eeprom_data[i+1] & 0x7f;
if (audioic < ARRAY_SIZE(audioIC))
tvee->audio_processor = audioIC[audioic].id;
else
tvee->audio_processor = V4L2_IDENT_UNKNOWN;
break;
case 0x06:
/* tag 'ModelRev' */
tvee->model =
eeprom_data[i + 1] +
(eeprom_data[i + 2] << 8) +
(eeprom_data[i + 3] << 16) +
(eeprom_data[i + 4] << 24);
tvee->revision =
eeprom_data[i + 5] +
(eeprom_data[i + 6] << 8) +
(eeprom_data[i + 7] << 16);
break;
case 0x07:
/* tag 'Details': according to Hauppauge not interesting
on any PCI-era or later boards. */
break;
/* there is no tag 0x08 defined */
case 0x09:
/* tag 'Video' */
tvee->decoder_processor = eeprom_data[i + 1];
break;
case 0x0a:
/* tag 'Tuner' */
if (beenhere == 0) {
tuner1 = eeprom_data[i + 2];
t_format1 = eeprom_data[i + 1];
beenhere = 1;
} else {
/* a second (radio) tuner may be present */
tuner2 = eeprom_data[i + 2];
t_format2 = eeprom_data[i + 1];
/* not a TV tuner? */
if (t_format2 == 0)
tvee->has_radio = 1; /* must be radio */
}
break;
case 0x0b:
/* tag 'Inputs': according to Hauppauge this is specific
to each driver family, so no good assumptions can be
made. */
break;
/* case 0x0c: tag 'Balun' */
/* case 0x0d: tag 'Teletext' */
case 0x0e:
/* tag: 'Radio' */
tvee->has_radio = eeprom_data[i+1];
break;
case 0x0f:
/* tag 'IRInfo' */
tvee->has_ir = 1 | (eeprom_data[i+1] << 1);
break;
/* case 0x10: tag 'VBIInfo' */
/* case 0x11: tag 'QCInfo' */
/* case 0x12: tag 'InfoBits' */
default:
tveeprom_dbg("Not sure what to do with tag [%02x]\n",
tag);
/* dump the rest of the packet? */
}
}
if (!done) {
tveeprom_warn("Ran out of data!\n");
return;
}
if (tvee->revision != 0) {
tvee->rev_str[0] = 32 + ((tvee->revision >> 18) & 0x3f);
tvee->rev_str[1] = 32 + ((tvee->revision >> 12) & 0x3f);
tvee->rev_str[2] = 32 + ((tvee->revision >> 6) & 0x3f);
tvee->rev_str[3] = 32 + (tvee->revision & 0x3f);
tvee->rev_str[4] = 0;
}
if (hasRadioTuner(tuner1) && !tvee->has_radio) {
tveeprom_info("The eeprom says no radio is present, but the tuner type\n");
tveeprom_info("indicates otherwise. I will assume that radio is present.\n");
tvee->has_radio = 1;
}
if (tuner1 < ARRAY_SIZE(hauppauge_tuner)) {
tvee->tuner_type = hauppauge_tuner[tuner1].id;
t_name1 = hauppauge_tuner[tuner1].name;
} else {
t_name1 = "unknown";
}
if (tuner2 < ARRAY_SIZE(hauppauge_tuner)) {
tvee->tuner2_type = hauppauge_tuner[tuner2].id;
t_name2 = hauppauge_tuner[tuner2].name;
} else {
t_name2 = "unknown";
}
tvee->tuner_hauppauge_model = tuner1;
tvee->tuner2_hauppauge_model = tuner2;
tvee->tuner_formats = 0;
tvee->tuner2_formats = 0;
for (i = j = 0; i < 8; i++) {
if (t_format1 & (1 << i)) {
tvee->tuner_formats |= hauppauge_tuner_fmt[i].id;
t_fmt_name1[j++] = hauppauge_tuner_fmt[i].name;
}
}
for (i = j = 0; i < 8; i++) {
if (t_format2 & (1 << i)) {
tvee->tuner2_formats |= hauppauge_tuner_fmt[i].id;
t_fmt_name2[j++] = hauppauge_tuner_fmt[i].name;
}
}
tveeprom_info("Hauppauge model %d, rev %s, serial# %d\n",
tvee->model, tvee->rev_str, tvee->serial_number);
if (tvee->has_MAC_address == 1)
tveeprom_info("MAC address is %pM\n", tvee->MAC_address);
tveeprom_info("tuner model is %s (idx %d, type %d)\n",
t_name1, tuner1, tvee->tuner_type);
tveeprom_info("TV standards%s%s%s%s%s%s%s%s (eeprom 0x%02x)\n",
t_fmt_name1[0], t_fmt_name1[1], t_fmt_name1[2],
t_fmt_name1[3], t_fmt_name1[4], t_fmt_name1[5],
t_fmt_name1[6], t_fmt_name1[7], t_format1);
if (tuner2)
tveeprom_info("second tuner model is %s (idx %d, type %d)\n",
t_name2, tuner2, tvee->tuner2_type);
if (t_format2)
tveeprom_info("TV standards%s%s%s%s%s%s%s%s (eeprom 0x%02x)\n",
t_fmt_name2[0], t_fmt_name2[1], t_fmt_name2[2],
t_fmt_name2[3], t_fmt_name2[4], t_fmt_name2[5],
t_fmt_name2[6], t_fmt_name2[7], t_format2);
if (audioic < 0) {
tveeprom_info("audio processor is unknown (no idx)\n");
tvee->audio_processor = V4L2_IDENT_UNKNOWN;
} else {
if (audioic < ARRAY_SIZE(audioIC))
tveeprom_info("audio processor is %s (idx %d)\n",
audioIC[audioic].name, audioic);
else
tveeprom_info("audio processor is unknown (idx %d)\n",
audioic);
}
if (tvee->decoder_processor)
tveeprom_info("decoder processor is %s (idx %d)\n",
STRM(decoderIC, tvee->decoder_processor),
tvee->decoder_processor);
if (tvee->has_ir)
tveeprom_info("has %sradio, has %sIR receiver, has %sIR transmitter\n",
tvee->has_radio ? "" : "no ",
(tvee->has_ir & 2) ? "" : "no ",
(tvee->has_ir & 4) ? "" : "no ");
else
tveeprom_info("has %sradio\n",
tvee->has_radio ? "" : "no ");
}
EXPORT_SYMBOL(tveeprom_hauppauge_analog);
/* ----------------------------------------------------------------------- */
/* generic helper functions */
int tveeprom_read(struct i2c_client *c, unsigned char *eedata, int len)
{
unsigned char buf;
int err;
buf = 0;
err = i2c_master_send(c, &buf, 1);
if (err != 1) {
tveeprom_info("Huh, no eeprom present (err=%d)?\n", err);
return -1;
}
err = i2c_master_recv(c, eedata, len);
if (err != len) {
tveeprom_warn("i2c eeprom read error (err=%d)\n", err);
return -1;
}
if (debug) {
int i;
tveeprom_info("full 256-byte eeprom dump:\n");
for (i = 0; i < len; i++) {
if (0 == (i % 16))
tveeprom_info("%02x:", i);
printk(KERN_CONT " %02x", eedata[i]);
if (15 == (i % 16))
printk(KERN_CONT "\n");
}
}
return 0;
}
EXPORT_SYMBOL(tveeprom_read);
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
smac0628/kernel-htc-m8-gpe-stock | drivers/gpu/drm/via/via_map.c | 3293 | 3369 | /*
* Copyright 1998-2003 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2003 S3 Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, 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
* VIA, S3 GRAPHICS, AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "drmP.h"
#include "via_drm.h"
#include "via_drv.h"
static int via_do_init_map(struct drm_device *dev, drm_via_init_t *init)
{
drm_via_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
dev_priv->sarea = drm_getsarea(dev);
if (!dev_priv->sarea) {
DRM_ERROR("could not find sarea!\n");
dev->dev_private = (void *)dev_priv;
via_do_cleanup_map(dev);
return -EINVAL;
}
dev_priv->fb = drm_core_findmap(dev, init->fb_offset);
if (!dev_priv->fb) {
DRM_ERROR("could not find framebuffer!\n");
dev->dev_private = (void *)dev_priv;
via_do_cleanup_map(dev);
return -EINVAL;
}
dev_priv->mmio = drm_core_findmap(dev, init->mmio_offset);
if (!dev_priv->mmio) {
DRM_ERROR("could not find mmio region!\n");
dev->dev_private = (void *)dev_priv;
via_do_cleanup_map(dev);
return -EINVAL;
}
dev_priv->sarea_priv =
(drm_via_sarea_t *) ((u8 *) dev_priv->sarea->handle +
init->sarea_priv_offset);
dev_priv->agpAddr = init->agpAddr;
via_init_futex(dev_priv);
via_init_dmablit(dev);
dev->dev_private = (void *)dev_priv;
return 0;
}
int via_do_cleanup_map(struct drm_device *dev)
{
via_dma_cleanup(dev);
return 0;
}
int via_map_init(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_init_t *init = data;
DRM_DEBUG("\n");
switch (init->func) {
case VIA_INIT_MAP:
return via_do_init_map(dev, init);
case VIA_CLEANUP_MAP:
return via_do_cleanup_map(dev);
}
return -EINVAL;
}
int via_driver_load(struct drm_device *dev, unsigned long chipset)
{
drm_via_private_t *dev_priv;
int ret = 0;
dev_priv = kzalloc(sizeof(drm_via_private_t), GFP_KERNEL);
if (dev_priv == NULL)
return -ENOMEM;
dev->dev_private = (void *)dev_priv;
dev_priv->chipset = chipset;
idr_init(&dev->object_name_idr);
pci_set_master(dev->pdev);
ret = drm_vblank_init(dev, 1);
if (ret) {
kfree(dev_priv);
return ret;
}
return 0;
}
int via_driver_unload(struct drm_device *dev)
{
drm_via_private_t *dev_priv = dev->dev_private;
idr_remove_all(&dev_priv->object_idr);
idr_destroy(&dev_priv->object_idr);
kfree(dev_priv);
return 0;
}
| gpl-2.0 |
Sudokamikaze/Darkspell-taoshan | drivers/ata/libata-scsi.c | 3293 | 101562 | /*
* libata-scsi.c - helper library for ATA
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2004 Red Hat, Inc. All rights reserved.
* Copyright 2003-2004 Jeff Garzik
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available from
* - http://www.t10.org/
* - http://www.t13.org/
*
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/blkdev.h>
#include <linux/spinlock.h>
#include <linux/export.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_transport.h>
#include <linux/libata.h>
#include <linux/hdreg.h>
#include <linux/uaccess.h>
#include <linux/suspend.h>
#include <asm/unaligned.h>
#include "libata.h"
#include "libata-transport.h"
#define ATA_SCSI_RBUF_SIZE 4096
static DEFINE_SPINLOCK(ata_scsi_rbuf_lock);
static u8 ata_scsi_rbuf[ATA_SCSI_RBUF_SIZE];
typedef unsigned int (*ata_xlat_func_t)(struct ata_queued_cmd *qc);
static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
const struct scsi_device *scsidev);
static struct ata_device *ata_scsi_find_dev(struct ata_port *ap,
const struct scsi_device *scsidev);
#define RW_RECOVERY_MPAGE 0x1
#define RW_RECOVERY_MPAGE_LEN 12
#define CACHE_MPAGE 0x8
#define CACHE_MPAGE_LEN 20
#define CONTROL_MPAGE 0xa
#define CONTROL_MPAGE_LEN 12
#define ALL_MPAGES 0x3f
#define ALL_SUB_MPAGES 0xff
static const u8 def_rw_recovery_mpage[RW_RECOVERY_MPAGE_LEN] = {
RW_RECOVERY_MPAGE,
RW_RECOVERY_MPAGE_LEN - 2,
(1 << 7), /* AWRE */
0, /* read retry count */
0, 0, 0, 0,
0, /* write retry count */
0, 0, 0
};
static const u8 def_cache_mpage[CACHE_MPAGE_LEN] = {
CACHE_MPAGE,
CACHE_MPAGE_LEN - 2,
0, /* contains WCE, needs to be 0 for logic */
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, /* contains DRA, needs to be 0 for logic */
0, 0, 0, 0, 0, 0, 0
};
static const u8 def_control_mpage[CONTROL_MPAGE_LEN] = {
CONTROL_MPAGE,
CONTROL_MPAGE_LEN - 2,
2, /* DSENSE=0, GLTSD=1 */
0, /* [QAM+QERR may be 1, see 05-359r1] */
0, 0, 0, 0, 0xff, 0xff,
0, 30 /* extended self test time, see 05-359r1 */
};
static const char *ata_lpm_policy_names[] = {
[ATA_LPM_UNKNOWN] = "max_performance",
[ATA_LPM_MAX_POWER] = "max_performance",
[ATA_LPM_MED_POWER] = "medium_power",
[ATA_LPM_MIN_POWER] = "min_power",
};
static ssize_t ata_scsi_lpm_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
enum ata_lpm_policy policy;
unsigned long flags;
/* UNKNOWN is internal state, iterate from MAX_POWER */
for (policy = ATA_LPM_MAX_POWER;
policy < ARRAY_SIZE(ata_lpm_policy_names); policy++) {
const char *name = ata_lpm_policy_names[policy];
if (strncmp(name, buf, strlen(name)) == 0)
break;
}
if (policy == ARRAY_SIZE(ata_lpm_policy_names))
return -EINVAL;
spin_lock_irqsave(ap->lock, flags);
ap->target_lpm_policy = policy;
ata_port_schedule_eh(ap);
spin_unlock_irqrestore(ap->lock, flags);
return count;
}
static ssize_t ata_scsi_lpm_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
if (ap->target_lpm_policy >= ARRAY_SIZE(ata_lpm_policy_names))
return -EINVAL;
return snprintf(buf, PAGE_SIZE, "%s\n",
ata_lpm_policy_names[ap->target_lpm_policy]);
}
DEVICE_ATTR(link_power_management_policy, S_IRUGO | S_IWUSR,
ata_scsi_lpm_show, ata_scsi_lpm_store);
EXPORT_SYMBOL_GPL(dev_attr_link_power_management_policy);
static ssize_t ata_scsi_park_show(struct device *device,
struct device_attribute *attr, char *buf)
{
struct scsi_device *sdev = to_scsi_device(device);
struct ata_port *ap;
struct ata_link *link;
struct ata_device *dev;
unsigned long flags, now;
unsigned int uninitialized_var(msecs);
int rc = 0;
ap = ata_shost_to_port(sdev->host);
spin_lock_irqsave(ap->lock, flags);
dev = ata_scsi_find_dev(ap, sdev);
if (!dev) {
rc = -ENODEV;
goto unlock;
}
if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
rc = -EOPNOTSUPP;
goto unlock;
}
link = dev->link;
now = jiffies;
if (ap->pflags & ATA_PFLAG_EH_IN_PROGRESS &&
link->eh_context.unloaded_mask & (1 << dev->devno) &&
time_after(dev->unpark_deadline, now))
msecs = jiffies_to_msecs(dev->unpark_deadline - now);
else
msecs = 0;
unlock:
spin_unlock_irq(ap->lock);
return rc ? rc : snprintf(buf, 20, "%u\n", msecs);
}
static ssize_t ata_scsi_park_store(struct device *device,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct scsi_device *sdev = to_scsi_device(device);
struct ata_port *ap;
struct ata_device *dev;
long int input;
unsigned long flags;
int rc;
rc = strict_strtol(buf, 10, &input);
if (rc || input < -2)
return -EINVAL;
if (input > ATA_TMOUT_MAX_PARK) {
rc = -EOVERFLOW;
input = ATA_TMOUT_MAX_PARK;
}
ap = ata_shost_to_port(sdev->host);
spin_lock_irqsave(ap->lock, flags);
dev = ata_scsi_find_dev(ap, sdev);
if (unlikely(!dev)) {
rc = -ENODEV;
goto unlock;
}
if (dev->class != ATA_DEV_ATA) {
rc = -EOPNOTSUPP;
goto unlock;
}
if (input >= 0) {
if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
rc = -EOPNOTSUPP;
goto unlock;
}
dev->unpark_deadline = ata_deadline(jiffies, input);
dev->link->eh_info.dev_action[dev->devno] |= ATA_EH_PARK;
ata_port_schedule_eh(ap);
complete(&ap->park_req_pending);
} else {
switch (input) {
case -1:
dev->flags &= ~ATA_DFLAG_NO_UNLOAD;
break;
case -2:
dev->flags |= ATA_DFLAG_NO_UNLOAD;
break;
}
}
unlock:
spin_unlock_irqrestore(ap->lock, flags);
return rc ? rc : len;
}
DEVICE_ATTR(unload_heads, S_IRUGO | S_IWUSR,
ata_scsi_park_show, ata_scsi_park_store);
EXPORT_SYMBOL_GPL(dev_attr_unload_heads);
static void ata_scsi_set_sense(struct scsi_cmnd *cmd, u8 sk, u8 asc, u8 ascq)
{
cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
scsi_build_sense_buffer(0, cmd->sense_buffer, sk, asc, ascq);
}
static ssize_t
ata_scsi_em_message_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
if (ap->ops->em_store && (ap->flags & ATA_FLAG_EM))
return ap->ops->em_store(ap, buf, count);
return -EINVAL;
}
static ssize_t
ata_scsi_em_message_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
if (ap->ops->em_show && (ap->flags & ATA_FLAG_EM))
return ap->ops->em_show(ap, buf);
return -EINVAL;
}
DEVICE_ATTR(em_message, S_IRUGO | S_IWUSR,
ata_scsi_em_message_show, ata_scsi_em_message_store);
EXPORT_SYMBOL_GPL(dev_attr_em_message);
static ssize_t
ata_scsi_em_message_type_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
return snprintf(buf, 23, "%d\n", ap->em_message_type);
}
DEVICE_ATTR(em_message_type, S_IRUGO,
ata_scsi_em_message_type_show, NULL);
EXPORT_SYMBOL_GPL(dev_attr_em_message_type);
static ssize_t
ata_scsi_activity_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct scsi_device *sdev = to_scsi_device(dev);
struct ata_port *ap = ata_shost_to_port(sdev->host);
struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
if (ap->ops->sw_activity_show && (ap->flags & ATA_FLAG_SW_ACTIVITY))
return ap->ops->sw_activity_show(atadev, buf);
return -EINVAL;
}
static ssize_t
ata_scsi_activity_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct scsi_device *sdev = to_scsi_device(dev);
struct ata_port *ap = ata_shost_to_port(sdev->host);
struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
enum sw_activity val;
int rc;
if (ap->ops->sw_activity_store && (ap->flags & ATA_FLAG_SW_ACTIVITY)) {
val = simple_strtoul(buf, NULL, 0);
switch (val) {
case OFF: case BLINK_ON: case BLINK_OFF:
rc = ap->ops->sw_activity_store(atadev, val);
if (!rc)
return count;
else
return rc;
}
}
return -EINVAL;
}
DEVICE_ATTR(sw_activity, S_IWUSR | S_IRUGO, ata_scsi_activity_show,
ata_scsi_activity_store);
EXPORT_SYMBOL_GPL(dev_attr_sw_activity);
struct device_attribute *ata_common_sdev_attrs[] = {
&dev_attr_unload_heads,
NULL
};
EXPORT_SYMBOL_GPL(ata_common_sdev_attrs);
static void ata_scsi_invalid_field(struct scsi_cmnd *cmd)
{
ata_scsi_set_sense(cmd, ILLEGAL_REQUEST, 0x24, 0x0);
/* "Invalid field in cbd" */
cmd->scsi_done(cmd);
}
/**
* ata_std_bios_param - generic bios head/sector/cylinder calculator used by sd.
* @sdev: SCSI device for which BIOS geometry is to be determined
* @bdev: block device associated with @sdev
* @capacity: capacity of SCSI device
* @geom: location to which geometry will be output
*
* Generic bios head/sector/cylinder calculator
* used by sd. Most BIOSes nowadays expect a XXX/255/16 (CHS)
* mapping. Some situations may arise where the disk is not
* bootable if this is not used.
*
* LOCKING:
* Defined by the SCSI layer. We don't really care.
*
* RETURNS:
* Zero.
*/
int ata_std_bios_param(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int geom[])
{
geom[0] = 255;
geom[1] = 63;
sector_div(capacity, 255*63);
geom[2] = capacity;
return 0;
}
/**
* ata_scsi_unlock_native_capacity - unlock native capacity
* @sdev: SCSI device to adjust device capacity for
*
* This function is called if a partition on @sdev extends beyond
* the end of the device. It requests EH to unlock HPA.
*
* LOCKING:
* Defined by the SCSI layer. Might sleep.
*/
void ata_scsi_unlock_native_capacity(struct scsi_device *sdev)
{
struct ata_port *ap = ata_shost_to_port(sdev->host);
struct ata_device *dev;
unsigned long flags;
spin_lock_irqsave(ap->lock, flags);
dev = ata_scsi_find_dev(ap, sdev);
if (dev && dev->n_sectors < dev->n_native_sectors) {
dev->flags |= ATA_DFLAG_UNLOCK_HPA;
dev->link->eh_info.action |= ATA_EH_RESET;
ata_port_schedule_eh(ap);
}
spin_unlock_irqrestore(ap->lock, flags);
ata_port_wait_eh(ap);
}
/**
* ata_get_identity - Handler for HDIO_GET_IDENTITY ioctl
* @ap: target port
* @sdev: SCSI device to get identify data for
* @arg: User buffer area for identify data
*
* LOCKING:
* Defined by the SCSI layer. We don't really care.
*
* RETURNS:
* Zero on success, negative errno on error.
*/
static int ata_get_identity(struct ata_port *ap, struct scsi_device *sdev,
void __user *arg)
{
struct ata_device *dev = ata_scsi_find_dev(ap, sdev);
u16 __user *dst = arg;
char buf[40];
if (!dev)
return -ENOMSG;
if (copy_to_user(dst, dev->id, ATA_ID_WORDS * sizeof(u16)))
return -EFAULT;
ata_id_string(dev->id, buf, ATA_ID_PROD, ATA_ID_PROD_LEN);
if (copy_to_user(dst + ATA_ID_PROD, buf, ATA_ID_PROD_LEN))
return -EFAULT;
ata_id_string(dev->id, buf, ATA_ID_FW_REV, ATA_ID_FW_REV_LEN);
if (copy_to_user(dst + ATA_ID_FW_REV, buf, ATA_ID_FW_REV_LEN))
return -EFAULT;
ata_id_string(dev->id, buf, ATA_ID_SERNO, ATA_ID_SERNO_LEN);
if (copy_to_user(dst + ATA_ID_SERNO, buf, ATA_ID_SERNO_LEN))
return -EFAULT;
return 0;
}
/**
* ata_cmd_ioctl - Handler for HDIO_DRIVE_CMD ioctl
* @scsidev: Device to which we are issuing command
* @arg: User provided data for issuing command
*
* LOCKING:
* Defined by the SCSI layer. We don't really care.
*
* RETURNS:
* Zero on success, negative errno on error.
*/
int ata_cmd_ioctl(struct scsi_device *scsidev, void __user *arg)
{
int rc = 0;
u8 scsi_cmd[MAX_COMMAND_SIZE];
u8 args[4], *argbuf = NULL, *sensebuf = NULL;
int argsize = 0;
enum dma_data_direction data_dir;
int cmd_result;
if (arg == NULL)
return -EINVAL;
if (copy_from_user(args, arg, sizeof(args)))
return -EFAULT;
sensebuf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
if (!sensebuf)
return -ENOMEM;
memset(scsi_cmd, 0, sizeof(scsi_cmd));
if (args[3]) {
argsize = ATA_SECT_SIZE * args[3];
argbuf = kmalloc(argsize, GFP_KERNEL);
if (argbuf == NULL) {
rc = -ENOMEM;
goto error;
}
scsi_cmd[1] = (4 << 1); /* PIO Data-in */
scsi_cmd[2] = 0x0e; /* no off.line or cc, read from dev,
block count in sector count field */
data_dir = DMA_FROM_DEVICE;
} else {
scsi_cmd[1] = (3 << 1); /* Non-data */
scsi_cmd[2] = 0x20; /* cc but no off.line or data xfer */
data_dir = DMA_NONE;
}
scsi_cmd[0] = ATA_16;
scsi_cmd[4] = args[2];
if (args[0] == ATA_CMD_SMART) { /* hack -- ide driver does this too */
scsi_cmd[6] = args[3];
scsi_cmd[8] = args[1];
scsi_cmd[10] = 0x4f;
scsi_cmd[12] = 0xc2;
} else {
scsi_cmd[6] = args[1];
}
scsi_cmd[14] = args[0];
/* Good values for timeout and retries? Values below
from scsi_ioctl_send_command() for default case... */
cmd_result = scsi_execute(scsidev, scsi_cmd, data_dir, argbuf, argsize,
sensebuf, (10*HZ), 5, 0, NULL);
if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
u8 *desc = sensebuf + 8;
cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
/* If we set cc then ATA pass-through will cause a
* check condition even if no error. Filter that. */
if (cmd_result & SAM_STAT_CHECK_CONDITION) {
struct scsi_sense_hdr sshdr;
scsi_normalize_sense(sensebuf, SCSI_SENSE_BUFFERSIZE,
&sshdr);
if (sshdr.sense_key == 0 &&
sshdr.asc == 0 && sshdr.ascq == 0)
cmd_result &= ~SAM_STAT_CHECK_CONDITION;
}
/* Send userspace a few ATA registers (same as drivers/ide) */
if (sensebuf[0] == 0x72 && /* format is "descriptor" */
desc[0] == 0x09) { /* code is "ATA Descriptor" */
args[0] = desc[13]; /* status */
args[1] = desc[3]; /* error */
args[2] = desc[5]; /* sector count (0:7) */
if (copy_to_user(arg, args, sizeof(args)))
rc = -EFAULT;
}
}
if (cmd_result) {
rc = -EIO;
goto error;
}
if ((argbuf)
&& copy_to_user(arg + sizeof(args), argbuf, argsize))
rc = -EFAULT;
error:
kfree(sensebuf);
kfree(argbuf);
return rc;
}
/**
* ata_task_ioctl - Handler for HDIO_DRIVE_TASK ioctl
* @scsidev: Device to which we are issuing command
* @arg: User provided data for issuing command
*
* LOCKING:
* Defined by the SCSI layer. We don't really care.
*
* RETURNS:
* Zero on success, negative errno on error.
*/
int ata_task_ioctl(struct scsi_device *scsidev, void __user *arg)
{
int rc = 0;
u8 scsi_cmd[MAX_COMMAND_SIZE];
u8 args[7], *sensebuf = NULL;
int cmd_result;
if (arg == NULL)
return -EINVAL;
if (copy_from_user(args, arg, sizeof(args)))
return -EFAULT;
sensebuf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
if (!sensebuf)
return -ENOMEM;
memset(scsi_cmd, 0, sizeof(scsi_cmd));
scsi_cmd[0] = ATA_16;
scsi_cmd[1] = (3 << 1); /* Non-data */
scsi_cmd[2] = 0x20; /* cc but no off.line or data xfer */
scsi_cmd[4] = args[1];
scsi_cmd[6] = args[2];
scsi_cmd[8] = args[3];
scsi_cmd[10] = args[4];
scsi_cmd[12] = args[5];
scsi_cmd[13] = args[6] & 0x4f;
scsi_cmd[14] = args[0];
/* Good values for timeout and retries? Values below
from scsi_ioctl_send_command() for default case... */
cmd_result = scsi_execute(scsidev, scsi_cmd, DMA_NONE, NULL, 0,
sensebuf, (10*HZ), 5, 0, NULL);
if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
u8 *desc = sensebuf + 8;
cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
/* If we set cc then ATA pass-through will cause a
* check condition even if no error. Filter that. */
if (cmd_result & SAM_STAT_CHECK_CONDITION) {
struct scsi_sense_hdr sshdr;
scsi_normalize_sense(sensebuf, SCSI_SENSE_BUFFERSIZE,
&sshdr);
if (sshdr.sense_key == 0 &&
sshdr.asc == 0 && sshdr.ascq == 0)
cmd_result &= ~SAM_STAT_CHECK_CONDITION;
}
/* Send userspace ATA registers */
if (sensebuf[0] == 0x72 && /* format is "descriptor" */
desc[0] == 0x09) {/* code is "ATA Descriptor" */
args[0] = desc[13]; /* status */
args[1] = desc[3]; /* error */
args[2] = desc[5]; /* sector count (0:7) */
args[3] = desc[7]; /* lbal */
args[4] = desc[9]; /* lbam */
args[5] = desc[11]; /* lbah */
args[6] = desc[12]; /* select */
if (copy_to_user(arg, args, sizeof(args)))
rc = -EFAULT;
}
}
if (cmd_result) {
rc = -EIO;
goto error;
}
error:
kfree(sensebuf);
return rc;
}
static int ata_ioc32(struct ata_port *ap)
{
if (ap->flags & ATA_FLAG_PIO_DMA)
return 1;
if (ap->pflags & ATA_PFLAG_PIO32)
return 1;
return 0;
}
int ata_sas_scsi_ioctl(struct ata_port *ap, struct scsi_device *scsidev,
int cmd, void __user *arg)
{
int val = -EINVAL, rc = -EINVAL;
unsigned long flags;
switch (cmd) {
case ATA_IOC_GET_IO32:
spin_lock_irqsave(ap->lock, flags);
val = ata_ioc32(ap);
spin_unlock_irqrestore(ap->lock, flags);
if (copy_to_user(arg, &val, 1))
return -EFAULT;
return 0;
case ATA_IOC_SET_IO32:
val = (unsigned long) arg;
rc = 0;
spin_lock_irqsave(ap->lock, flags);
if (ap->pflags & ATA_PFLAG_PIO32CHANGE) {
if (val)
ap->pflags |= ATA_PFLAG_PIO32;
else
ap->pflags &= ~ATA_PFLAG_PIO32;
} else {
if (val != ata_ioc32(ap))
rc = -EINVAL;
}
spin_unlock_irqrestore(ap->lock, flags);
return rc;
case HDIO_GET_IDENTITY:
return ata_get_identity(ap, scsidev, arg);
case HDIO_DRIVE_CMD:
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
return ata_cmd_ioctl(scsidev, arg);
case HDIO_DRIVE_TASK:
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
return ata_task_ioctl(scsidev, arg);
default:
rc = -ENOTTY;
break;
}
return rc;
}
EXPORT_SYMBOL_GPL(ata_sas_scsi_ioctl);
int ata_scsi_ioctl(struct scsi_device *scsidev, int cmd, void __user *arg)
{
return ata_sas_scsi_ioctl(ata_shost_to_port(scsidev->host),
scsidev, cmd, arg);
}
EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
/**
* ata_scsi_qc_new - acquire new ata_queued_cmd reference
* @dev: ATA device to which the new command is attached
* @cmd: SCSI command that originated this ATA command
*
* Obtain a reference to an unused ata_queued_cmd structure,
* which is the basic libata structure representing a single
* ATA command sent to the hardware.
*
* If a command was available, fill in the SCSI-specific
* portions of the structure with information on the
* current command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Command allocated, or %NULL if none available.
*/
static struct ata_queued_cmd *ata_scsi_qc_new(struct ata_device *dev,
struct scsi_cmnd *cmd)
{
struct ata_queued_cmd *qc;
qc = ata_qc_new_init(dev);
if (qc) {
qc->scsicmd = cmd;
qc->scsidone = cmd->scsi_done;
qc->sg = scsi_sglist(cmd);
qc->n_elem = scsi_sg_count(cmd);
} else {
cmd->result = (DID_OK << 16) | (QUEUE_FULL << 1);
cmd->scsi_done(cmd);
}
return qc;
}
static void ata_qc_set_pc_nbytes(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *scmd = qc->scsicmd;
qc->extrabytes = scmd->request->extra_len;
qc->nbytes = scsi_bufflen(scmd) + qc->extrabytes;
}
/**
* ata_dump_status - user friendly display of error info
* @id: id of the port in question
* @tf: ptr to filled out taskfile
*
* Decode and dump the ATA error/status registers for the user so
* that they have some idea what really happened at the non
* make-believe layer.
*
* LOCKING:
* inherited from caller
*/
static void ata_dump_status(unsigned id, struct ata_taskfile *tf)
{
u8 stat = tf->command, err = tf->feature;
printk(KERN_WARNING "ata%u: status=0x%02x { ", id, stat);
if (stat & ATA_BUSY) {
printk("Busy }\n"); /* Data is not valid in this case */
} else {
if (stat & 0x40) printk("DriveReady ");
if (stat & 0x20) printk("DeviceFault ");
if (stat & 0x10) printk("SeekComplete ");
if (stat & 0x08) printk("DataRequest ");
if (stat & 0x04) printk("CorrectedError ");
if (stat & 0x02) printk("Index ");
if (stat & 0x01) printk("Error ");
printk("}\n");
if (err) {
printk(KERN_WARNING "ata%u: error=0x%02x { ", id, err);
if (err & 0x04) printk("DriveStatusError ");
if (err & 0x80) {
if (err & 0x04) printk("BadCRC ");
else printk("Sector ");
}
if (err & 0x40) printk("UncorrectableError ");
if (err & 0x10) printk("SectorIdNotFound ");
if (err & 0x02) printk("TrackZeroNotFound ");
if (err & 0x01) printk("AddrMarkNotFound ");
printk("}\n");
}
}
}
/**
* ata_to_sense_error - convert ATA error to SCSI error
* @id: ATA device number
* @drv_stat: value contained in ATA status register
* @drv_err: value contained in ATA error register
* @sk: the sense key we'll fill out
* @asc: the additional sense code we'll fill out
* @ascq: the additional sense code qualifier we'll fill out
* @verbose: be verbose
*
* Converts an ATA error into a SCSI error. Fill out pointers to
* SK, ASC, and ASCQ bytes for later use in fixed or descriptor
* format sense blocks.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static void ata_to_sense_error(unsigned id, u8 drv_stat, u8 drv_err, u8 *sk,
u8 *asc, u8 *ascq, int verbose)
{
int i;
/* Based on the 3ware driver translation table */
static const unsigned char sense_table[][4] = {
/* BBD|ECC|ID|MAR */
{0xd1, ABORTED_COMMAND, 0x00, 0x00}, // Device busy Aborted command
/* BBD|ECC|ID */
{0xd0, ABORTED_COMMAND, 0x00, 0x00}, // Device busy Aborted command
/* ECC|MC|MARK */
{0x61, HARDWARE_ERROR, 0x00, 0x00}, // Device fault Hardware error
/* ICRC|ABRT */ /* NB: ICRC & !ABRT is BBD */
{0x84, ABORTED_COMMAND, 0x47, 0x00}, // Data CRC error SCSI parity error
/* MC|ID|ABRT|TRK0|MARK */
{0x37, NOT_READY, 0x04, 0x00}, // Unit offline Not ready
/* MCR|MARK */
{0x09, NOT_READY, 0x04, 0x00}, // Unrecovered disk error Not ready
/* Bad address mark */
{0x01, MEDIUM_ERROR, 0x13, 0x00}, // Address mark not found Address mark not found for data field
/* TRK0 */
{0x02, HARDWARE_ERROR, 0x00, 0x00}, // Track 0 not found Hardware error
/* Abort & !ICRC */
{0x04, ABORTED_COMMAND, 0x00, 0x00}, // Aborted command Aborted command
/* Media change request */
{0x08, NOT_READY, 0x04, 0x00}, // Media change request FIXME: faking offline
/* SRV */
{0x10, ABORTED_COMMAND, 0x14, 0x00}, // ID not found Recorded entity not found
/* Media change */
{0x08, NOT_READY, 0x04, 0x00}, // Media change FIXME: faking offline
/* ECC */
{0x40, MEDIUM_ERROR, 0x11, 0x04}, // Uncorrectable ECC error Unrecovered read error
/* BBD - block marked bad */
{0x80, MEDIUM_ERROR, 0x11, 0x04}, // Block marked bad Medium error, unrecovered read error
{0xFF, 0xFF, 0xFF, 0xFF}, // END mark
};
static const unsigned char stat_table[][4] = {
/* Must be first because BUSY means no other bits valid */
{0x80, ABORTED_COMMAND, 0x47, 0x00}, // Busy, fake parity for now
{0x20, HARDWARE_ERROR, 0x00, 0x00}, // Device fault
{0x08, ABORTED_COMMAND, 0x47, 0x00}, // Timed out in xfer, fake parity for now
{0x04, RECOVERED_ERROR, 0x11, 0x00}, // Recovered ECC error Medium error, recovered
{0xFF, 0xFF, 0xFF, 0xFF}, // END mark
};
/*
* Is this an error we can process/parse
*/
if (drv_stat & ATA_BUSY) {
drv_err = 0; /* Ignore the err bits, they're invalid */
}
if (drv_err) {
/* Look for drv_err */
for (i = 0; sense_table[i][0] != 0xFF; i++) {
/* Look for best matches first */
if ((sense_table[i][0] & drv_err) ==
sense_table[i][0]) {
*sk = sense_table[i][1];
*asc = sense_table[i][2];
*ascq = sense_table[i][3];
goto translate_done;
}
}
/* No immediate match */
if (verbose)
printk(KERN_WARNING "ata%u: no sense translation for "
"error 0x%02x\n", id, drv_err);
}
/* Fall back to interpreting status bits */
for (i = 0; stat_table[i][0] != 0xFF; i++) {
if (stat_table[i][0] & drv_stat) {
*sk = stat_table[i][1];
*asc = stat_table[i][2];
*ascq = stat_table[i][3];
goto translate_done;
}
}
/* No error? Undecoded? */
if (verbose)
printk(KERN_WARNING "ata%u: no sense translation for "
"status: 0x%02x\n", id, drv_stat);
/* We need a sensible error return here, which is tricky, and one
that won't cause people to do things like return a disk wrongly */
*sk = ABORTED_COMMAND;
*asc = 0x00;
*ascq = 0x00;
translate_done:
if (verbose)
printk(KERN_ERR "ata%u: translated ATA stat/err 0x%02x/%02x "
"to SCSI SK/ASC/ASCQ 0x%x/%02x/%02x\n",
id, drv_stat, drv_err, *sk, *asc, *ascq);
return;
}
/*
* ata_gen_passthru_sense - Generate check condition sense block.
* @qc: Command that completed.
*
* This function is specific to the ATA descriptor format sense
* block specified for the ATA pass through commands. Regardless
* of whether the command errored or not, return a sense
* block. Copy all controller registers into the sense
* block. Clear sense key, ASC & ASCQ if there is no error.
*
* LOCKING:
* None.
*/
static void ata_gen_passthru_sense(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *cmd = qc->scsicmd;
struct ata_taskfile *tf = &qc->result_tf;
unsigned char *sb = cmd->sense_buffer;
unsigned char *desc = sb + 8;
int verbose = qc->ap->ops->error_handler == NULL;
memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
/*
* Use ata_to_sense_error() to map status register bits
* onto sense key, asc & ascq.
*/
if (qc->err_mask ||
tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
&sb[1], &sb[2], &sb[3], verbose);
sb[1] &= 0x0f;
}
/*
* Sense data is current and format is descriptor.
*/
sb[0] = 0x72;
desc[0] = 0x09;
/* set length of additional sense data */
sb[7] = 14;
desc[1] = 12;
/*
* Copy registers into sense buffer.
*/
desc[2] = 0x00;
desc[3] = tf->feature; /* == error reg */
desc[5] = tf->nsect;
desc[7] = tf->lbal;
desc[9] = tf->lbam;
desc[11] = tf->lbah;
desc[12] = tf->device;
desc[13] = tf->command; /* == status reg */
/*
* Fill in Extend bit, and the high order bytes
* if applicable.
*/
if (tf->flags & ATA_TFLAG_LBA48) {
desc[2] |= 0x01;
desc[4] = tf->hob_nsect;
desc[6] = tf->hob_lbal;
desc[8] = tf->hob_lbam;
desc[10] = tf->hob_lbah;
}
}
/**
* ata_gen_ata_sense - generate a SCSI fixed sense block
* @qc: Command that we are erroring out
*
* Generate sense block for a failed ATA command @qc. Descriptor
* format is used to accommodate LBA48 block address.
*
* LOCKING:
* None.
*/
static void ata_gen_ata_sense(struct ata_queued_cmd *qc)
{
struct ata_device *dev = qc->dev;
struct scsi_cmnd *cmd = qc->scsicmd;
struct ata_taskfile *tf = &qc->result_tf;
unsigned char *sb = cmd->sense_buffer;
unsigned char *desc = sb + 8;
int verbose = qc->ap->ops->error_handler == NULL;
u64 block;
memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
/* sense data is current and format is descriptor */
sb[0] = 0x72;
/* Use ata_to_sense_error() to map status register bits
* onto sense key, asc & ascq.
*/
if (qc->err_mask ||
tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
&sb[1], &sb[2], &sb[3], verbose);
sb[1] &= 0x0f;
}
block = ata_tf_read_block(&qc->result_tf, dev);
/* information sense data descriptor */
sb[7] = 12;
desc[0] = 0x00;
desc[1] = 10;
desc[2] |= 0x80; /* valid */
desc[6] = block >> 40;
desc[7] = block >> 32;
desc[8] = block >> 24;
desc[9] = block >> 16;
desc[10] = block >> 8;
desc[11] = block;
}
static void ata_scsi_sdev_config(struct scsi_device *sdev)
{
sdev->use_10_for_rw = 1;
sdev->use_10_for_ms = 1;
/* Schedule policy is determined by ->qc_defer() callback and
* it needs to see every deferred qc. Set dev_blocked to 1 to
* prevent SCSI midlayer from automatically deferring
* requests.
*/
sdev->max_device_blocked = 1;
}
/**
* atapi_drain_needed - Check whether data transfer may overflow
* @rq: request to be checked
*
* ATAPI commands which transfer variable length data to host
* might overflow due to application error or hardare bug. This
* function checks whether overflow should be drained and ignored
* for @request.
*
* LOCKING:
* None.
*
* RETURNS:
* 1 if ; otherwise, 0.
*/
static int atapi_drain_needed(struct request *rq)
{
if (likely(rq->cmd_type != REQ_TYPE_BLOCK_PC))
return 0;
if (!blk_rq_bytes(rq) || (rq->cmd_flags & REQ_WRITE))
return 0;
return atapi_cmd_type(rq->cmd[0]) == ATAPI_MISC;
}
static int ata_scsi_dev_config(struct scsi_device *sdev,
struct ata_device *dev)
{
struct request_queue *q = sdev->request_queue;
if (!ata_id_has_unload(dev->id))
dev->flags |= ATA_DFLAG_NO_UNLOAD;
/* configure max sectors */
blk_queue_max_hw_sectors(q, dev->max_sectors);
if (dev->class == ATA_DEV_ATAPI) {
void *buf;
sdev->sector_size = ATA_SECT_SIZE;
/* set DMA padding */
blk_queue_update_dma_pad(q, ATA_DMA_PAD_SZ - 1);
/* configure draining */
buf = kmalloc(ATAPI_MAX_DRAIN, q->bounce_gfp | GFP_KERNEL);
if (!buf) {
ata_dev_err(dev, "drain buffer allocation failed\n");
return -ENOMEM;
}
blk_queue_dma_drain(q, atapi_drain_needed, buf, ATAPI_MAX_DRAIN);
} else {
sdev->sector_size = ata_id_logical_sector_size(dev->id);
sdev->manage_start_stop = 1;
}
/*
* ata_pio_sectors() expects buffer for each sector to not cross
* page boundary. Enforce it by requiring buffers to be sector
* aligned, which works iff sector_size is not larger than
* PAGE_SIZE. ATAPI devices also need the alignment as
* IDENTIFY_PACKET is executed as ATA_PROT_PIO.
*/
if (sdev->sector_size > PAGE_SIZE)
ata_dev_warn(dev,
"sector_size=%u > PAGE_SIZE, PIO may malfunction\n",
sdev->sector_size);
blk_queue_update_dma_alignment(q, sdev->sector_size - 1);
if (dev->flags & ATA_DFLAG_AN)
set_bit(SDEV_EVT_MEDIA_CHANGE, sdev->supported_events);
if (dev->flags & ATA_DFLAG_NCQ) {
int depth;
depth = min(sdev->host->can_queue, ata_id_queue_depth(dev->id));
depth = min(ATA_MAX_QUEUE - 1, depth);
scsi_adjust_queue_depth(sdev, MSG_SIMPLE_TAG, depth);
}
blk_queue_flush_queueable(q, false);
dev->sdev = sdev;
return 0;
}
/**
* ata_scsi_slave_config - Set SCSI device attributes
* @sdev: SCSI device to examine
*
* This is called before we actually start reading
* and writing to the device, to configure certain
* SCSI mid-layer behaviors.
*
* LOCKING:
* Defined by SCSI layer. We don't really care.
*/
int ata_scsi_slave_config(struct scsi_device *sdev)
{
struct ata_port *ap = ata_shost_to_port(sdev->host);
struct ata_device *dev = __ata_scsi_find_dev(ap, sdev);
int rc = 0;
ata_scsi_sdev_config(sdev);
if (dev)
rc = ata_scsi_dev_config(sdev, dev);
return rc;
}
/**
* ata_scsi_slave_destroy - SCSI device is about to be destroyed
* @sdev: SCSI device to be destroyed
*
* @sdev is about to be destroyed for hot/warm unplugging. If
* this unplugging was initiated by libata as indicated by NULL
* dev->sdev, this function doesn't have to do anything.
* Otherwise, SCSI layer initiated warm-unplug is in progress.
* Clear dev->sdev, schedule the device for ATA detach and invoke
* EH.
*
* LOCKING:
* Defined by SCSI layer. We don't really care.
*/
void ata_scsi_slave_destroy(struct scsi_device *sdev)
{
struct ata_port *ap = ata_shost_to_port(sdev->host);
struct request_queue *q = sdev->request_queue;
unsigned long flags;
struct ata_device *dev;
if (!ap->ops->error_handler)
return;
spin_lock_irqsave(ap->lock, flags);
dev = __ata_scsi_find_dev(ap, sdev);
if (dev && dev->sdev) {
/* SCSI device already in CANCEL state, no need to offline it */
dev->sdev = NULL;
dev->flags |= ATA_DFLAG_DETACH;
ata_port_schedule_eh(ap);
}
spin_unlock_irqrestore(ap->lock, flags);
kfree(q->dma_drain_buffer);
q->dma_drain_buffer = NULL;
q->dma_drain_size = 0;
}
/**
* __ata_change_queue_depth - helper for ata_scsi_change_queue_depth
* @ap: ATA port to which the device change the queue depth
* @sdev: SCSI device to configure queue depth for
* @queue_depth: new queue depth
* @reason: calling context
*
* libsas and libata have different approaches for associating a sdev to
* its ata_port.
*
*/
int __ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev,
int queue_depth, int reason)
{
struct ata_device *dev;
unsigned long flags;
if (reason != SCSI_QDEPTH_DEFAULT)
return -EOPNOTSUPP;
if (queue_depth < 1 || queue_depth == sdev->queue_depth)
return sdev->queue_depth;
dev = ata_scsi_find_dev(ap, sdev);
if (!dev || !ata_dev_enabled(dev))
return sdev->queue_depth;
/* NCQ enabled? */
spin_lock_irqsave(ap->lock, flags);
dev->flags &= ~ATA_DFLAG_NCQ_OFF;
if (queue_depth == 1 || !ata_ncq_enabled(dev)) {
dev->flags |= ATA_DFLAG_NCQ_OFF;
queue_depth = 1;
}
spin_unlock_irqrestore(ap->lock, flags);
/* limit and apply queue depth */
queue_depth = min(queue_depth, sdev->host->can_queue);
queue_depth = min(queue_depth, ata_id_queue_depth(dev->id));
queue_depth = min(queue_depth, ATA_MAX_QUEUE - 1);
if (sdev->queue_depth == queue_depth)
return -EINVAL;
scsi_adjust_queue_depth(sdev, MSG_SIMPLE_TAG, queue_depth);
return queue_depth;
}
/**
* ata_scsi_change_queue_depth - SCSI callback for queue depth config
* @sdev: SCSI device to configure queue depth for
* @queue_depth: new queue depth
* @reason: calling context
*
* This is libata standard hostt->change_queue_depth callback.
* SCSI will call into this callback when user tries to set queue
* depth via sysfs.
*
* LOCKING:
* SCSI layer (we don't care)
*
* RETURNS:
* Newly configured queue depth.
*/
int ata_scsi_change_queue_depth(struct scsi_device *sdev, int queue_depth,
int reason)
{
struct ata_port *ap = ata_shost_to_port(sdev->host);
return __ata_change_queue_depth(ap, sdev, queue_depth, reason);
}
/**
* ata_scsi_start_stop_xlat - Translate SCSI START STOP UNIT command
* @qc: Storage for translated ATA taskfile
*
* Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
* (to start). Perhaps these commands should be preceded by
* CHECK POWER MODE to see what power mode the device is already in.
* [See SAT revision 5 at www.t10.org]
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, non-zero on error.
*/
static unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *scmd = qc->scsicmd;
struct ata_taskfile *tf = &qc->tf;
const u8 *cdb = scmd->cmnd;
if (scmd->cmd_len < 5)
goto invalid_fld;
tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
tf->protocol = ATA_PROT_NODATA;
if (cdb[1] & 0x1) {
; /* ignore IMMED bit, violates sat-r05 */
}
if (cdb[4] & 0x2)
goto invalid_fld; /* LOEJ bit set not supported */
if (((cdb[4] >> 4) & 0xf) != 0)
goto invalid_fld; /* power conditions not supported */
if (cdb[4] & 0x1) {
tf->nsect = 1; /* 1 sector, lba=0 */
if (qc->dev->flags & ATA_DFLAG_LBA) {
tf->flags |= ATA_TFLAG_LBA;
tf->lbah = 0x0;
tf->lbam = 0x0;
tf->lbal = 0x0;
tf->device |= ATA_LBA;
} else {
/* CHS */
tf->lbal = 0x1; /* sect */
tf->lbam = 0x0; /* cyl low */
tf->lbah = 0x0; /* cyl high */
}
tf->command = ATA_CMD_VERIFY; /* READ VERIFY */
} else {
/* Some odd clown BIOSen issue spindown on power off (ACPI S4
* or S5) causing some drives to spin up and down again.
*/
if ((qc->ap->flags & ATA_FLAG_NO_POWEROFF_SPINDOWN) &&
system_state == SYSTEM_POWER_OFF)
goto skip;
if ((qc->ap->flags & ATA_FLAG_NO_HIBERNATE_SPINDOWN) &&
system_entering_hibernation())
goto skip;
/* Issue ATA STANDBY IMMEDIATE command */
tf->command = ATA_CMD_STANDBYNOW1;
}
/*
* Standby and Idle condition timers could be implemented but that
* would require libata to implement the Power condition mode page
* and allow the user to change it. Changing mode pages requires
* MODE SELECT to be implemented.
*/
return 0;
invalid_fld:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
/* "Invalid field in cbd" */
return 1;
skip:
scmd->result = SAM_STAT_GOOD;
return 1;
}
/**
* ata_scsi_flush_xlat - Translate SCSI SYNCHRONIZE CACHE command
* @qc: Storage for translated ATA taskfile
*
* Sets up an ATA taskfile to issue FLUSH CACHE or
* FLUSH CACHE EXT.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, non-zero on error.
*/
static unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc)
{
struct ata_taskfile *tf = &qc->tf;
tf->flags |= ATA_TFLAG_DEVICE;
tf->protocol = ATA_PROT_NODATA;
if (qc->dev->flags & ATA_DFLAG_FLUSH_EXT)
tf->command = ATA_CMD_FLUSH_EXT;
else
tf->command = ATA_CMD_FLUSH;
/* flush is critical for IO integrity, consider it an IO command */
qc->flags |= ATA_QCFLAG_IO;
return 0;
}
/**
* scsi_6_lba_len - Get LBA and transfer length
* @cdb: SCSI command to translate
*
* Calculate LBA and transfer length for 6-byte commands.
*
* RETURNS:
* @plba: the LBA
* @plen: the transfer length
*/
static void scsi_6_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
{
u64 lba = 0;
u32 len;
VPRINTK("six-byte command\n");
lba |= ((u64)(cdb[1] & 0x1f)) << 16;
lba |= ((u64)cdb[2]) << 8;
lba |= ((u64)cdb[3]);
len = cdb[4];
*plba = lba;
*plen = len;
}
/**
* scsi_10_lba_len - Get LBA and transfer length
* @cdb: SCSI command to translate
*
* Calculate LBA and transfer length for 10-byte commands.
*
* RETURNS:
* @plba: the LBA
* @plen: the transfer length
*/
static void scsi_10_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
{
u64 lba = 0;
u32 len = 0;
VPRINTK("ten-byte command\n");
lba |= ((u64)cdb[2]) << 24;
lba |= ((u64)cdb[3]) << 16;
lba |= ((u64)cdb[4]) << 8;
lba |= ((u64)cdb[5]);
len |= ((u32)cdb[7]) << 8;
len |= ((u32)cdb[8]);
*plba = lba;
*plen = len;
}
/**
* scsi_16_lba_len - Get LBA and transfer length
* @cdb: SCSI command to translate
*
* Calculate LBA and transfer length for 16-byte commands.
*
* RETURNS:
* @plba: the LBA
* @plen: the transfer length
*/
static void scsi_16_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
{
u64 lba = 0;
u32 len = 0;
VPRINTK("sixteen-byte command\n");
lba |= ((u64)cdb[2]) << 56;
lba |= ((u64)cdb[3]) << 48;
lba |= ((u64)cdb[4]) << 40;
lba |= ((u64)cdb[5]) << 32;
lba |= ((u64)cdb[6]) << 24;
lba |= ((u64)cdb[7]) << 16;
lba |= ((u64)cdb[8]) << 8;
lba |= ((u64)cdb[9]);
len |= ((u32)cdb[10]) << 24;
len |= ((u32)cdb[11]) << 16;
len |= ((u32)cdb[12]) << 8;
len |= ((u32)cdb[13]);
*plba = lba;
*plen = len;
}
/**
* ata_scsi_verify_xlat - Translate SCSI VERIFY command into an ATA one
* @qc: Storage for translated ATA taskfile
*
* Converts SCSI VERIFY command to an ATA READ VERIFY command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, non-zero on error.
*/
static unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *scmd = qc->scsicmd;
struct ata_taskfile *tf = &qc->tf;
struct ata_device *dev = qc->dev;
u64 dev_sectors = qc->dev->n_sectors;
const u8 *cdb = scmd->cmnd;
u64 block;
u32 n_block;
tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
tf->protocol = ATA_PROT_NODATA;
if (cdb[0] == VERIFY) {
if (scmd->cmd_len < 10)
goto invalid_fld;
scsi_10_lba_len(cdb, &block, &n_block);
} else if (cdb[0] == VERIFY_16) {
if (scmd->cmd_len < 16)
goto invalid_fld;
scsi_16_lba_len(cdb, &block, &n_block);
} else
goto invalid_fld;
if (!n_block)
goto nothing_to_do;
if (block >= dev_sectors)
goto out_of_range;
if ((block + n_block) > dev_sectors)
goto out_of_range;
if (dev->flags & ATA_DFLAG_LBA) {
tf->flags |= ATA_TFLAG_LBA;
if (lba_28_ok(block, n_block)) {
/* use LBA28 */
tf->command = ATA_CMD_VERIFY;
tf->device |= (block >> 24) & 0xf;
} else if (lba_48_ok(block, n_block)) {
if (!(dev->flags & ATA_DFLAG_LBA48))
goto out_of_range;
/* use LBA48 */
tf->flags |= ATA_TFLAG_LBA48;
tf->command = ATA_CMD_VERIFY_EXT;
tf->hob_nsect = (n_block >> 8) & 0xff;
tf->hob_lbah = (block >> 40) & 0xff;
tf->hob_lbam = (block >> 32) & 0xff;
tf->hob_lbal = (block >> 24) & 0xff;
} else
/* request too large even for LBA48 */
goto out_of_range;
tf->nsect = n_block & 0xff;
tf->lbah = (block >> 16) & 0xff;
tf->lbam = (block >> 8) & 0xff;
tf->lbal = block & 0xff;
tf->device |= ATA_LBA;
} else {
/* CHS */
u32 sect, head, cyl, track;
if (!lba_28_ok(block, n_block))
goto out_of_range;
/* Convert LBA to CHS */
track = (u32)block / dev->sectors;
cyl = track / dev->heads;
head = track % dev->heads;
sect = (u32)block % dev->sectors + 1;
DPRINTK("block %u track %u cyl %u head %u sect %u\n",
(u32)block, track, cyl, head, sect);
/* Check whether the converted CHS can fit.
Cylinder: 0-65535
Head: 0-15
Sector: 1-255*/
if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
goto out_of_range;
tf->command = ATA_CMD_VERIFY;
tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
tf->lbal = sect;
tf->lbam = cyl;
tf->lbah = cyl >> 8;
tf->device |= head;
}
return 0;
invalid_fld:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
/* "Invalid field in cbd" */
return 1;
out_of_range:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x21, 0x0);
/* "Logical Block Address out of range" */
return 1;
nothing_to_do:
scmd->result = SAM_STAT_GOOD;
return 1;
}
/**
* ata_scsi_rw_xlat - Translate SCSI r/w command into an ATA one
* @qc: Storage for translated ATA taskfile
*
* Converts any of six SCSI read/write commands into the
* ATA counterpart, including starting sector (LBA),
* sector count, and taking into account the device's LBA48
* support.
*
* Commands %READ_6, %READ_10, %READ_16, %WRITE_6, %WRITE_10, and
* %WRITE_16 are currently supported.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, non-zero on error.
*/
static unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *scmd = qc->scsicmd;
const u8 *cdb = scmd->cmnd;
unsigned int tf_flags = 0;
u64 block;
u32 n_block;
int rc;
if (cdb[0] == WRITE_10 || cdb[0] == WRITE_6 || cdb[0] == WRITE_16)
tf_flags |= ATA_TFLAG_WRITE;
/* Calculate the SCSI LBA, transfer length and FUA. */
switch (cdb[0]) {
case READ_10:
case WRITE_10:
if (unlikely(scmd->cmd_len < 10))
goto invalid_fld;
scsi_10_lba_len(cdb, &block, &n_block);
if (unlikely(cdb[1] & (1 << 3)))
tf_flags |= ATA_TFLAG_FUA;
break;
case READ_6:
case WRITE_6:
if (unlikely(scmd->cmd_len < 6))
goto invalid_fld;
scsi_6_lba_len(cdb, &block, &n_block);
/* for 6-byte r/w commands, transfer length 0
* means 256 blocks of data, not 0 block.
*/
if (!n_block)
n_block = 256;
break;
case READ_16:
case WRITE_16:
if (unlikely(scmd->cmd_len < 16))
goto invalid_fld;
scsi_16_lba_len(cdb, &block, &n_block);
if (unlikely(cdb[1] & (1 << 3)))
tf_flags |= ATA_TFLAG_FUA;
break;
default:
DPRINTK("no-byte command\n");
goto invalid_fld;
}
/* Check and compose ATA command */
if (!n_block)
/* For 10-byte and 16-byte SCSI R/W commands, transfer
* length 0 means transfer 0 block of data.
* However, for ATA R/W commands, sector count 0 means
* 256 or 65536 sectors, not 0 sectors as in SCSI.
*
* WARNING: one or two older ATA drives treat 0 as 0...
*/
goto nothing_to_do;
qc->flags |= ATA_QCFLAG_IO;
qc->nbytes = n_block * scmd->device->sector_size;
rc = ata_build_rw_tf(&qc->tf, qc->dev, block, n_block, tf_flags,
qc->tag);
if (likely(rc == 0))
return 0;
if (rc == -ERANGE)
goto out_of_range;
/* treat all other errors as -EINVAL, fall through */
invalid_fld:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
/* "Invalid field in cbd" */
return 1;
out_of_range:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x21, 0x0);
/* "Logical Block Address out of range" */
return 1;
nothing_to_do:
scmd->result = SAM_STAT_GOOD;
return 1;
}
static void ata_scsi_qc_complete(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct scsi_cmnd *cmd = qc->scsicmd;
u8 *cdb = cmd->cmnd;
int need_sense = (qc->err_mask != 0);
/* For ATA pass thru (SAT) commands, generate a sense block if
* user mandated it or if there's an error. Note that if we
* generate because the user forced us to, a check condition
* is generated and the ATA register values are returned
* whether the command completed successfully or not. If there
* was no error, SK, ASC and ASCQ will all be zero.
*/
if (((cdb[0] == ATA_16) || (cdb[0] == ATA_12)) &&
((cdb[2] & 0x20) || need_sense)) {
ata_gen_passthru_sense(qc);
} else {
if (!need_sense) {
cmd->result = SAM_STAT_GOOD;
} else {
/* TODO: decide which descriptor format to use
* for 48b LBA devices and call that here
* instead of the fixed desc, which is only
* good for smaller LBA (and maybe CHS?)
* devices.
*/
ata_gen_ata_sense(qc);
}
}
if (need_sense && !ap->ops->error_handler)
ata_dump_status(ap->print_id, &qc->result_tf);
qc->scsidone(cmd);
ata_qc_free(qc);
}
/**
* ata_scsi_translate - Translate then issue SCSI command to ATA device
* @dev: ATA device to which the command is addressed
* @cmd: SCSI command to execute
* @xlat_func: Actor which translates @cmd to an ATA taskfile
*
* Our ->queuecommand() function has decided that the SCSI
* command issued can be directly translated into an ATA
* command, rather than handled internally.
*
* This function sets up an ata_queued_cmd structure for the
* SCSI command, and sends that ata_queued_cmd to the hardware.
*
* The xlat_func argument (actor) returns 0 if ready to execute
* ATA command, else 1 to finish translation. If 1 is returned
* then cmd->result (and possibly cmd->sense_buffer) are assumed
* to be set reflecting an error condition or clean (early)
* termination.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* 0 on success, SCSI_ML_QUEUE_DEVICE_BUSY if the command
* needs to be deferred.
*/
static int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd,
ata_xlat_func_t xlat_func)
{
struct ata_port *ap = dev->link->ap;
struct ata_queued_cmd *qc;
int rc;
VPRINTK("ENTER\n");
qc = ata_scsi_qc_new(dev, cmd);
if (!qc)
goto err_mem;
/* data is present; dma-map it */
if (cmd->sc_data_direction == DMA_FROM_DEVICE ||
cmd->sc_data_direction == DMA_TO_DEVICE) {
if (unlikely(scsi_bufflen(cmd) < 1)) {
ata_dev_warn(dev, "WARNING: zero len r/w req\n");
goto err_did;
}
ata_sg_init(qc, scsi_sglist(cmd), scsi_sg_count(cmd));
qc->dma_dir = cmd->sc_data_direction;
}
qc->complete_fn = ata_scsi_qc_complete;
if (xlat_func(qc))
goto early_finish;
if (ap->ops->qc_defer) {
if ((rc = ap->ops->qc_defer(qc)))
goto defer;
}
/* select device, send command to hardware */
ata_qc_issue(qc);
VPRINTK("EXIT\n");
return 0;
early_finish:
ata_qc_free(qc);
cmd->scsi_done(cmd);
DPRINTK("EXIT - early finish (good or error)\n");
return 0;
err_did:
ata_qc_free(qc);
cmd->result = (DID_ERROR << 16);
cmd->scsi_done(cmd);
err_mem:
DPRINTK("EXIT - internal\n");
return 0;
defer:
ata_qc_free(qc);
DPRINTK("EXIT - defer\n");
if (rc == ATA_DEFER_LINK)
return SCSI_MLQUEUE_DEVICE_BUSY;
else
return SCSI_MLQUEUE_HOST_BUSY;
}
/**
* ata_scsi_rbuf_get - Map response buffer.
* @cmd: SCSI command containing buffer to be mapped.
* @flags: unsigned long variable to store irq enable status
* @copy_in: copy in from user buffer
*
* Prepare buffer for simulated SCSI commands.
*
* LOCKING:
* spin_lock_irqsave(ata_scsi_rbuf_lock) on success
*
* RETURNS:
* Pointer to response buffer.
*/
static void *ata_scsi_rbuf_get(struct scsi_cmnd *cmd, bool copy_in,
unsigned long *flags)
{
spin_lock_irqsave(&ata_scsi_rbuf_lock, *flags);
memset(ata_scsi_rbuf, 0, ATA_SCSI_RBUF_SIZE);
if (copy_in)
sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
return ata_scsi_rbuf;
}
/**
* ata_scsi_rbuf_put - Unmap response buffer.
* @cmd: SCSI command containing buffer to be unmapped.
* @copy_out: copy out result
* @flags: @flags passed to ata_scsi_rbuf_get()
*
* Returns rbuf buffer. The result is copied to @cmd's buffer if
* @copy_back is true.
*
* LOCKING:
* Unlocks ata_scsi_rbuf_lock.
*/
static inline void ata_scsi_rbuf_put(struct scsi_cmnd *cmd, bool copy_out,
unsigned long *flags)
{
if (copy_out)
sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
spin_unlock_irqrestore(&ata_scsi_rbuf_lock, *flags);
}
/**
* ata_scsi_rbuf_fill - wrapper for SCSI command simulators
* @args: device IDENTIFY data / SCSI command of interest.
* @actor: Callback hook for desired SCSI command simulator
*
* Takes care of the hard work of simulating a SCSI command...
* Mapping the response buffer, calling the command's handler,
* and handling the handler's return value. This return value
* indicates whether the handler wishes the SCSI command to be
* completed successfully (0), or not (in which case cmd->result
* and sense buffer are assumed to be set).
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static void ata_scsi_rbuf_fill(struct ata_scsi_args *args,
unsigned int (*actor)(struct ata_scsi_args *args, u8 *rbuf))
{
u8 *rbuf;
unsigned int rc;
struct scsi_cmnd *cmd = args->cmd;
unsigned long flags;
rbuf = ata_scsi_rbuf_get(cmd, false, &flags);
rc = actor(args, rbuf);
ata_scsi_rbuf_put(cmd, rc == 0, &flags);
if (rc == 0)
cmd->result = SAM_STAT_GOOD;
args->done(cmd);
}
/**
* ata_scsiop_inq_std - Simulate INQUIRY command
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Returns standard device identification data associated
* with non-VPD INQUIRY command output.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_inq_std(struct ata_scsi_args *args, u8 *rbuf)
{
const u8 versions[] = {
0x60, /* SAM-3 (no version claimed) */
0x03,
0x20, /* SBC-2 (no version claimed) */
0x02,
0x60 /* SPC-3 (no version claimed) */
};
u8 hdr[] = {
TYPE_DISK,
0,
0x5, /* claim SPC-3 version compatibility */
2,
95 - 4
};
VPRINTK("ENTER\n");
/* set scsi removeable (RMB) bit per ata bit */
if (ata_id_removeable(args->id))
hdr[1] |= (1 << 7);
memcpy(rbuf, hdr, sizeof(hdr));
memcpy(&rbuf[8], "ATA ", 8);
ata_id_string(args->id, &rbuf[16], ATA_ID_PROD, 16);
ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV, 4);
if (rbuf[32] == 0 || rbuf[32] == ' ')
memcpy(&rbuf[32], "n/a ", 4);
memcpy(rbuf + 59, versions, sizeof(versions));
return 0;
}
/**
* ata_scsiop_inq_00 - Simulate INQUIRY VPD page 0, list of pages
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Returns list of inquiry VPD pages available.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_inq_00(struct ata_scsi_args *args, u8 *rbuf)
{
const u8 pages[] = {
0x00, /* page 0x00, this page */
0x80, /* page 0x80, unit serial no page */
0x83, /* page 0x83, device ident page */
0x89, /* page 0x89, ata info page */
0xb0, /* page 0xb0, block limits page */
0xb1, /* page 0xb1, block device characteristics page */
0xb2, /* page 0xb2, thin provisioning page */
};
rbuf[3] = sizeof(pages); /* number of supported VPD pages */
memcpy(rbuf + 4, pages, sizeof(pages));
return 0;
}
/**
* ata_scsiop_inq_80 - Simulate INQUIRY VPD page 80, device serial number
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Returns ATA device serial number.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_inq_80(struct ata_scsi_args *args, u8 *rbuf)
{
const u8 hdr[] = {
0,
0x80, /* this page code */
0,
ATA_ID_SERNO_LEN, /* page len */
};
memcpy(rbuf, hdr, sizeof(hdr));
ata_id_string(args->id, (unsigned char *) &rbuf[4],
ATA_ID_SERNO, ATA_ID_SERNO_LEN);
return 0;
}
/**
* ata_scsiop_inq_83 - Simulate INQUIRY VPD page 83, device identity
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Yields two logical unit device identification designators:
* - vendor specific ASCII containing the ATA serial number
* - SAT defined "t10 vendor id based" containing ASCII vendor
* name ("ATA "), model and serial numbers.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_inq_83(struct ata_scsi_args *args, u8 *rbuf)
{
const int sat_model_serial_desc_len = 68;
int num;
rbuf[1] = 0x83; /* this page code */
num = 4;
/* piv=0, assoc=lu, code_set=ACSII, designator=vendor */
rbuf[num + 0] = 2;
rbuf[num + 3] = ATA_ID_SERNO_LEN;
num += 4;
ata_id_string(args->id, (unsigned char *) rbuf + num,
ATA_ID_SERNO, ATA_ID_SERNO_LEN);
num += ATA_ID_SERNO_LEN;
/* SAT defined lu model and serial numbers descriptor */
/* piv=0, assoc=lu, code_set=ACSII, designator=t10 vendor id */
rbuf[num + 0] = 2;
rbuf[num + 1] = 1;
rbuf[num + 3] = sat_model_serial_desc_len;
num += 4;
memcpy(rbuf + num, "ATA ", 8);
num += 8;
ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_PROD,
ATA_ID_PROD_LEN);
num += ATA_ID_PROD_LEN;
ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_SERNO,
ATA_ID_SERNO_LEN);
num += ATA_ID_SERNO_LEN;
if (ata_id_has_wwn(args->id)) {
/* SAT defined lu world wide name */
/* piv=0, assoc=lu, code_set=binary, designator=NAA */
rbuf[num + 0] = 1;
rbuf[num + 1] = 3;
rbuf[num + 3] = ATA_ID_WWN_LEN;
num += 4;
ata_id_string(args->id, (unsigned char *) rbuf + num,
ATA_ID_WWN, ATA_ID_WWN_LEN);
num += ATA_ID_WWN_LEN;
}
rbuf[3] = num - 4; /* page len (assume less than 256 bytes) */
return 0;
}
/**
* ata_scsiop_inq_89 - Simulate INQUIRY VPD page 89, ATA info
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Yields SAT-specified ATA VPD page.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_inq_89(struct ata_scsi_args *args, u8 *rbuf)
{
struct ata_taskfile tf;
memset(&tf, 0, sizeof(tf));
rbuf[1] = 0x89; /* our page code */
rbuf[2] = (0x238 >> 8); /* page size fixed at 238h */
rbuf[3] = (0x238 & 0xff);
memcpy(&rbuf[8], "linux ", 8);
memcpy(&rbuf[16], "libata ", 16);
memcpy(&rbuf[32], DRV_VERSION, 4);
ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV, 4);
/* we don't store the ATA device signature, so we fake it */
tf.command = ATA_DRDY; /* really, this is Status reg */
tf.lbal = 0x1;
tf.nsect = 0x1;
ata_tf_to_fis(&tf, 0, 1, &rbuf[36]); /* TODO: PMP? */
rbuf[36] = 0x34; /* force D2H Reg FIS (34h) */
rbuf[56] = ATA_CMD_ID_ATA;
memcpy(&rbuf[60], &args->id[0], 512);
return 0;
}
static unsigned int ata_scsiop_inq_b0(struct ata_scsi_args *args, u8 *rbuf)
{
u16 min_io_sectors;
rbuf[1] = 0xb0;
rbuf[3] = 0x3c; /* required VPD size with unmap support */
/*
* Optimal transfer length granularity.
*
* This is always one physical block, but for disks with a smaller
* logical than physical sector size we need to figure out what the
* latter is.
*/
min_io_sectors = 1 << ata_id_log2_per_physical_sector(args->id);
put_unaligned_be16(min_io_sectors, &rbuf[6]);
/*
* Optimal unmap granularity.
*
* The ATA spec doesn't even know about a granularity or alignment
* for the TRIM command. We can leave away most of the unmap related
* VPD page entries, but we have specifify a granularity to signal
* that we support some form of unmap - in thise case via WRITE SAME
* with the unmap bit set.
*/
if (ata_id_has_trim(args->id)) {
put_unaligned_be64(65535 * 512 / 8, &rbuf[36]);
put_unaligned_be32(1, &rbuf[28]);
}
return 0;
}
static unsigned int ata_scsiop_inq_b1(struct ata_scsi_args *args, u8 *rbuf)
{
int form_factor = ata_id_form_factor(args->id);
int media_rotation_rate = ata_id_rotation_rate(args->id);
rbuf[1] = 0xb1;
rbuf[3] = 0x3c;
rbuf[4] = media_rotation_rate >> 8;
rbuf[5] = media_rotation_rate;
rbuf[7] = form_factor;
return 0;
}
static unsigned int ata_scsiop_inq_b2(struct ata_scsi_args *args, u8 *rbuf)
{
/* SCSI Thin Provisioning VPD page: SBC-3 rev 22 or later */
rbuf[1] = 0xb2;
rbuf[3] = 0x4;
rbuf[5] = 1 << 6; /* TPWS */
return 0;
}
/**
* ata_scsiop_noop - Command handler that simply returns success.
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* No operation. Simply returns success to caller, to indicate
* that the caller should successfully complete this SCSI command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_noop(struct ata_scsi_args *args, u8 *rbuf)
{
VPRINTK("ENTER\n");
return 0;
}
/**
* ata_msense_caching - Simulate MODE SENSE caching info page
* @id: device IDENTIFY data
* @buf: output buffer
*
* Generate a caching info page, which conditionally indicates
* write caching to the SCSI layer, depending on device
* capabilities.
*
* LOCKING:
* None.
*/
static unsigned int ata_msense_caching(u16 *id, u8 *buf)
{
memcpy(buf, def_cache_mpage, sizeof(def_cache_mpage));
if (ata_id_wcache_enabled(id))
buf[2] |= (1 << 2); /* write cache enable */
if (!ata_id_rahead_enabled(id))
buf[12] |= (1 << 5); /* disable read ahead */
return sizeof(def_cache_mpage);
}
/**
* ata_msense_ctl_mode - Simulate MODE SENSE control mode page
* @buf: output buffer
*
* Generate a generic MODE SENSE control mode page.
*
* LOCKING:
* None.
*/
static unsigned int ata_msense_ctl_mode(u8 *buf)
{
memcpy(buf, def_control_mpage, sizeof(def_control_mpage));
return sizeof(def_control_mpage);
}
/**
* ata_msense_rw_recovery - Simulate MODE SENSE r/w error recovery page
* @buf: output buffer
*
* Generate a generic MODE SENSE r/w error recovery page.
*
* LOCKING:
* None.
*/
static unsigned int ata_msense_rw_recovery(u8 *buf)
{
memcpy(buf, def_rw_recovery_mpage, sizeof(def_rw_recovery_mpage));
return sizeof(def_rw_recovery_mpage);
}
/*
* We can turn this into a real blacklist if it's needed, for now just
* blacklist any Maxtor BANC1G10 revision firmware
*/
static int ata_dev_supports_fua(u16 *id)
{
unsigned char model[ATA_ID_PROD_LEN + 1], fw[ATA_ID_FW_REV_LEN + 1];
if (!libata_fua)
return 0;
if (!ata_id_has_fua(id))
return 0;
ata_id_c_string(id, model, ATA_ID_PROD, sizeof(model));
ata_id_c_string(id, fw, ATA_ID_FW_REV, sizeof(fw));
if (strcmp(model, "Maxtor"))
return 1;
if (strcmp(fw, "BANC1G10"))
return 1;
return 0; /* blacklisted */
}
/**
* ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Simulate MODE SENSE commands. Assume this is invoked for direct
* access devices (e.g. disks) only. There should be no block
* descriptor for other device types.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_mode_sense(struct ata_scsi_args *args, u8 *rbuf)
{
struct ata_device *dev = args->dev;
u8 *scsicmd = args->cmd->cmnd, *p = rbuf;
const u8 sat_blk_desc[] = {
0, 0, 0, 0, /* number of blocks: sat unspecified */
0,
0, 0x2, 0x0 /* block length: 512 bytes */
};
u8 pg, spg;
unsigned int ebd, page_control, six_byte;
u8 dpofua;
VPRINTK("ENTER\n");
six_byte = (scsicmd[0] == MODE_SENSE);
ebd = !(scsicmd[1] & 0x8); /* dbd bit inverted == edb */
/*
* LLBA bit in msense(10) ignored (compliant)
*/
page_control = scsicmd[2] >> 6;
switch (page_control) {
case 0: /* current */
break; /* supported */
case 3: /* saved */
goto saving_not_supp;
case 1: /* changeable */
case 2: /* defaults */
default:
goto invalid_fld;
}
if (six_byte)
p += 4 + (ebd ? 8 : 0);
else
p += 8 + (ebd ? 8 : 0);
pg = scsicmd[2] & 0x3f;
spg = scsicmd[3];
/*
* No mode subpages supported (yet) but asking for _all_
* subpages may be valid
*/
if (spg && (spg != ALL_SUB_MPAGES))
goto invalid_fld;
switch(pg) {
case RW_RECOVERY_MPAGE:
p += ata_msense_rw_recovery(p);
break;
case CACHE_MPAGE:
p += ata_msense_caching(args->id, p);
break;
case CONTROL_MPAGE:
p += ata_msense_ctl_mode(p);
break;
case ALL_MPAGES:
p += ata_msense_rw_recovery(p);
p += ata_msense_caching(args->id, p);
p += ata_msense_ctl_mode(p);
break;
default: /* invalid page code */
goto invalid_fld;
}
dpofua = 0;
if (ata_dev_supports_fua(args->id) && (dev->flags & ATA_DFLAG_LBA48) &&
(!(dev->flags & ATA_DFLAG_PIO) || dev->multi_count))
dpofua = 1 << 4;
if (six_byte) {
rbuf[0] = p - rbuf - 1;
rbuf[2] |= dpofua;
if (ebd) {
rbuf[3] = sizeof(sat_blk_desc);
memcpy(rbuf + 4, sat_blk_desc, sizeof(sat_blk_desc));
}
} else {
unsigned int output_len = p - rbuf - 2;
rbuf[0] = output_len >> 8;
rbuf[1] = output_len;
rbuf[3] |= dpofua;
if (ebd) {
rbuf[7] = sizeof(sat_blk_desc);
memcpy(rbuf + 8, sat_blk_desc, sizeof(sat_blk_desc));
}
}
return 0;
invalid_fld:
ata_scsi_set_sense(args->cmd, ILLEGAL_REQUEST, 0x24, 0x0);
/* "Invalid field in cbd" */
return 1;
saving_not_supp:
ata_scsi_set_sense(args->cmd, ILLEGAL_REQUEST, 0x39, 0x0);
/* "Saving parameters not supported" */
return 1;
}
/**
* ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Simulate READ CAPACITY commands.
*
* LOCKING:
* None.
*/
static unsigned int ata_scsiop_read_cap(struct ata_scsi_args *args, u8 *rbuf)
{
struct ata_device *dev = args->dev;
u64 last_lba = dev->n_sectors - 1; /* LBA of the last block */
u32 sector_size; /* physical sector size in bytes */
u8 log2_per_phys;
u16 lowest_aligned;
sector_size = ata_id_logical_sector_size(dev->id);
log2_per_phys = ata_id_log2_per_physical_sector(dev->id);
lowest_aligned = ata_id_logical_sector_offset(dev->id, log2_per_phys);
VPRINTK("ENTER\n");
if (args->cmd->cmnd[0] == READ_CAPACITY) {
if (last_lba >= 0xffffffffULL)
last_lba = 0xffffffff;
/* sector count, 32-bit */
rbuf[0] = last_lba >> (8 * 3);
rbuf[1] = last_lba >> (8 * 2);
rbuf[2] = last_lba >> (8 * 1);
rbuf[3] = last_lba;
/* sector size */
rbuf[4] = sector_size >> (8 * 3);
rbuf[5] = sector_size >> (8 * 2);
rbuf[6] = sector_size >> (8 * 1);
rbuf[7] = sector_size;
} else {
/* sector count, 64-bit */
rbuf[0] = last_lba >> (8 * 7);
rbuf[1] = last_lba >> (8 * 6);
rbuf[2] = last_lba >> (8 * 5);
rbuf[3] = last_lba >> (8 * 4);
rbuf[4] = last_lba >> (8 * 3);
rbuf[5] = last_lba >> (8 * 2);
rbuf[6] = last_lba >> (8 * 1);
rbuf[7] = last_lba;
/* sector size */
rbuf[ 8] = sector_size >> (8 * 3);
rbuf[ 9] = sector_size >> (8 * 2);
rbuf[10] = sector_size >> (8 * 1);
rbuf[11] = sector_size;
rbuf[12] = 0;
rbuf[13] = log2_per_phys;
rbuf[14] = (lowest_aligned >> 8) & 0x3f;
rbuf[15] = lowest_aligned;
if (ata_id_has_trim(args->id)) {
rbuf[14] |= 0x80; /* TPE */
if (ata_id_has_zero_after_trim(args->id))
rbuf[14] |= 0x40; /* TPRZ */
}
}
return 0;
}
/**
* ata_scsiop_report_luns - Simulate REPORT LUNS command
* @args: device IDENTIFY data / SCSI command of interest.
* @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
*
* Simulate REPORT LUNS command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static unsigned int ata_scsiop_report_luns(struct ata_scsi_args *args, u8 *rbuf)
{
VPRINTK("ENTER\n");
rbuf[3] = 8; /* just one lun, LUN 0, size 8 bytes */
return 0;
}
static void atapi_sense_complete(struct ata_queued_cmd *qc)
{
if (qc->err_mask && ((qc->err_mask & AC_ERR_DEV) == 0)) {
/* FIXME: not quite right; we don't want the
* translation of taskfile registers into
* a sense descriptors, since that's only
* correct for ATA, not ATAPI
*/
ata_gen_passthru_sense(qc);
}
qc->scsidone(qc->scsicmd);
ata_qc_free(qc);
}
/* is it pointless to prefer PIO for "safety reasons"? */
static inline int ata_pio_use_silly(struct ata_port *ap)
{
return (ap->flags & ATA_FLAG_PIO_DMA);
}
static void atapi_request_sense(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct scsi_cmnd *cmd = qc->scsicmd;
DPRINTK("ATAPI request sense\n");
/* FIXME: is this needed? */
memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
#ifdef CONFIG_ATA_SFF
if (ap->ops->sff_tf_read)
ap->ops->sff_tf_read(ap, &qc->tf);
#endif
/* fill these in, for the case where they are -not- overwritten */
cmd->sense_buffer[0] = 0x70;
cmd->sense_buffer[2] = qc->tf.feature >> 4;
ata_qc_reinit(qc);
/* setup sg table and init transfer direction */
sg_init_one(&qc->sgent, cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
ata_sg_init(qc, &qc->sgent, 1);
qc->dma_dir = DMA_FROM_DEVICE;
memset(&qc->cdb, 0, qc->dev->cdb_len);
qc->cdb[0] = REQUEST_SENSE;
qc->cdb[4] = SCSI_SENSE_BUFFERSIZE;
qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
qc->tf.command = ATA_CMD_PACKET;
if (ata_pio_use_silly(ap)) {
qc->tf.protocol = ATAPI_PROT_DMA;
qc->tf.feature |= ATAPI_PKT_DMA;
} else {
qc->tf.protocol = ATAPI_PROT_PIO;
qc->tf.lbam = SCSI_SENSE_BUFFERSIZE;
qc->tf.lbah = 0;
}
qc->nbytes = SCSI_SENSE_BUFFERSIZE;
qc->complete_fn = atapi_sense_complete;
ata_qc_issue(qc);
DPRINTK("EXIT\n");
}
static void atapi_qc_complete(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *cmd = qc->scsicmd;
unsigned int err_mask = qc->err_mask;
VPRINTK("ENTER, err_mask 0x%X\n", err_mask);
/* handle completion from new EH */
if (unlikely(qc->ap->ops->error_handler &&
(err_mask || qc->flags & ATA_QCFLAG_SENSE_VALID))) {
if (!(qc->flags & ATA_QCFLAG_SENSE_VALID)) {
/* FIXME: not quite right; we don't want the
* translation of taskfile registers into a
* sense descriptors, since that's only
* correct for ATA, not ATAPI
*/
ata_gen_passthru_sense(qc);
}
/* SCSI EH automatically locks door if sdev->locked is
* set. Sometimes door lock request continues to
* fail, for example, when no media is present. This
* creates a loop - SCSI EH issues door lock which
* fails and gets invoked again to acquire sense data
* for the failed command.
*
* If door lock fails, always clear sdev->locked to
* avoid this infinite loop.
*
* This may happen before SCSI scan is complete. Make
* sure qc->dev->sdev isn't NULL before dereferencing.
*/
if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev)
qc->dev->sdev->locked = 0;
qc->scsicmd->result = SAM_STAT_CHECK_CONDITION;
qc->scsidone(cmd);
ata_qc_free(qc);
return;
}
/* successful completion or old EH failure path */
if (unlikely(err_mask & AC_ERR_DEV)) {
cmd->result = SAM_STAT_CHECK_CONDITION;
atapi_request_sense(qc);
return;
} else if (unlikely(err_mask)) {
/* FIXME: not quite right; we don't want the
* translation of taskfile registers into
* a sense descriptors, since that's only
* correct for ATA, not ATAPI
*/
ata_gen_passthru_sense(qc);
} else {
u8 *scsicmd = cmd->cmnd;
if ((scsicmd[0] == INQUIRY) && ((scsicmd[1] & 0x03) == 0)) {
unsigned long flags;
u8 *buf;
buf = ata_scsi_rbuf_get(cmd, true, &flags);
/* ATAPI devices typically report zero for their SCSI version,
* and sometimes deviate from the spec WRT response data
* format. If SCSI version is reported as zero like normal,
* then we make the following fixups: 1) Fake MMC-5 version,
* to indicate to the Linux scsi midlayer this is a modern
* device. 2) Ensure response data format / ATAPI information
* are always correct.
*/
if (buf[2] == 0) {
buf[2] = 0x5;
buf[3] = 0x32;
}
ata_scsi_rbuf_put(cmd, true, &flags);
}
cmd->result = SAM_STAT_GOOD;
}
qc->scsidone(cmd);
ata_qc_free(qc);
}
/**
* atapi_xlat - Initialize PACKET taskfile
* @qc: command structure to be initialized
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, non-zero on failure.
*/
static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
{
struct scsi_cmnd *scmd = qc->scsicmd;
struct ata_device *dev = qc->dev;
int nodata = (scmd->sc_data_direction == DMA_NONE);
int using_pio = !nodata && (dev->flags & ATA_DFLAG_PIO);
unsigned int nbytes;
memset(qc->cdb, 0, dev->cdb_len);
memcpy(qc->cdb, scmd->cmnd, scmd->cmd_len);
qc->complete_fn = atapi_qc_complete;
qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
if (scmd->sc_data_direction == DMA_TO_DEVICE) {
qc->tf.flags |= ATA_TFLAG_WRITE;
DPRINTK("direction: write\n");
}
qc->tf.command = ATA_CMD_PACKET;
ata_qc_set_pc_nbytes(qc);
/* check whether ATAPI DMA is safe */
if (!nodata && !using_pio && atapi_check_dma(qc))
using_pio = 1;
/* Some controller variants snoop this value for Packet
* transfers to do state machine and FIFO management. Thus we
* want to set it properly, and for DMA where it is
* effectively meaningless.
*/
nbytes = min(ata_qc_raw_nbytes(qc), (unsigned int)63 * 1024);
/* Most ATAPI devices which honor transfer chunk size don't
* behave according to the spec when odd chunk size which
* matches the transfer length is specified. If the number of
* bytes to transfer is 2n+1. According to the spec, what
* should happen is to indicate that 2n+1 is going to be
* transferred and transfer 2n+2 bytes where the last byte is
* padding.
*
* In practice, this doesn't happen. ATAPI devices first
* indicate and transfer 2n bytes and then indicate and
* transfer 2 bytes where the last byte is padding.
*
* This inconsistency confuses several controllers which
* perform PIO using DMA such as Intel AHCIs and sil3124/32.
* These controllers use actual number of transferred bytes to
* update DMA poitner and transfer of 4n+2 bytes make those
* controller push DMA pointer by 4n+4 bytes because SATA data
* FISes are aligned to 4 bytes. This causes data corruption
* and buffer overrun.
*
* Always setting nbytes to even number solves this problem
* because then ATAPI devices don't have to split data at 2n
* boundaries.
*/
if (nbytes & 0x1)
nbytes++;
qc->tf.lbam = (nbytes & 0xFF);
qc->tf.lbah = (nbytes >> 8);
if (nodata)
qc->tf.protocol = ATAPI_PROT_NODATA;
else if (using_pio)
qc->tf.protocol = ATAPI_PROT_PIO;
else {
/* DMA data xfer */
qc->tf.protocol = ATAPI_PROT_DMA;
qc->tf.feature |= ATAPI_PKT_DMA;
if ((dev->flags & ATA_DFLAG_DMADIR) &&
(scmd->sc_data_direction != DMA_TO_DEVICE))
/* some SATA bridges need us to indicate data xfer direction */
qc->tf.feature |= ATAPI_DMADIR;
}
/* FIXME: We need to translate 0x05 READ_BLOCK_LIMITS to a MODE_SENSE
as ATAPI tape drives don't get this right otherwise */
return 0;
}
static struct ata_device *ata_find_dev(struct ata_port *ap, int devno)
{
if (!sata_pmp_attached(ap)) {
if (likely(devno < ata_link_max_devices(&ap->link)))
return &ap->link.device[devno];
} else {
if (likely(devno < ap->nr_pmp_links))
return &ap->pmp_link[devno].device[0];
}
return NULL;
}
static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
const struct scsi_device *scsidev)
{
int devno;
/* skip commands not addressed to targets we simulate */
if (!sata_pmp_attached(ap)) {
if (unlikely(scsidev->channel || scsidev->lun))
return NULL;
devno = scsidev->id;
} else {
if (unlikely(scsidev->id || scsidev->lun))
return NULL;
devno = scsidev->channel;
}
return ata_find_dev(ap, devno);
}
/**
* ata_scsi_find_dev - lookup ata_device from scsi_cmnd
* @ap: ATA port to which the device is attached
* @scsidev: SCSI device from which we derive the ATA device
*
* Given various information provided in struct scsi_cmnd,
* map that onto an ATA bus, and using that mapping
* determine which ata_device is associated with the
* SCSI command to be sent.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Associated ATA device, or %NULL if not found.
*/
static struct ata_device *
ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
{
struct ata_device *dev = __ata_scsi_find_dev(ap, scsidev);
if (unlikely(!dev || !ata_dev_enabled(dev)))
return NULL;
return dev;
}
/*
* ata_scsi_map_proto - Map pass-thru protocol value to taskfile value.
* @byte1: Byte 1 from pass-thru CDB.
*
* RETURNS:
* ATA_PROT_UNKNOWN if mapping failed/unimplemented, protocol otherwise.
*/
static u8
ata_scsi_map_proto(u8 byte1)
{
switch((byte1 & 0x1e) >> 1) {
case 3: /* Non-data */
return ATA_PROT_NODATA;
case 6: /* DMA */
case 10: /* UDMA Data-in */
case 11: /* UDMA Data-Out */
return ATA_PROT_DMA;
case 4: /* PIO Data-in */
case 5: /* PIO Data-out */
return ATA_PROT_PIO;
case 0: /* Hard Reset */
case 1: /* SRST */
case 8: /* Device Diagnostic */
case 9: /* Device Reset */
case 7: /* DMA Queued */
case 12: /* FPDMA */
case 15: /* Return Response Info */
default: /* Reserved */
break;
}
return ATA_PROT_UNKNOWN;
}
/**
* ata_scsi_pass_thru - convert ATA pass-thru CDB to taskfile
* @qc: command structure to be initialized
*
* Handles either 12 or 16-byte versions of the CDB.
*
* RETURNS:
* Zero on success, non-zero on failure.
*/
static unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
{
struct ata_taskfile *tf = &(qc->tf);
struct scsi_cmnd *scmd = qc->scsicmd;
struct ata_device *dev = qc->dev;
const u8 *cdb = scmd->cmnd;
if ((tf->protocol = ata_scsi_map_proto(cdb[1])) == ATA_PROT_UNKNOWN)
goto invalid_fld;
/*
* 12 and 16 byte CDBs use different offsets to
* provide the various register values.
*/
if (cdb[0] == ATA_16) {
/*
* 16-byte CDB - may contain extended commands.
*
* If that is the case, copy the upper byte register values.
*/
if (cdb[1] & 0x01) {
tf->hob_feature = cdb[3];
tf->hob_nsect = cdb[5];
tf->hob_lbal = cdb[7];
tf->hob_lbam = cdb[9];
tf->hob_lbah = cdb[11];
tf->flags |= ATA_TFLAG_LBA48;
} else
tf->flags &= ~ATA_TFLAG_LBA48;
/*
* Always copy low byte, device and command registers.
*/
tf->feature = cdb[4];
tf->nsect = cdb[6];
tf->lbal = cdb[8];
tf->lbam = cdb[10];
tf->lbah = cdb[12];
tf->device = cdb[13];
tf->command = cdb[14];
} else {
/*
* 12-byte CDB - incapable of extended commands.
*/
tf->flags &= ~ATA_TFLAG_LBA48;
tf->feature = cdb[3];
tf->nsect = cdb[4];
tf->lbal = cdb[5];
tf->lbam = cdb[6];
tf->lbah = cdb[7];
tf->device = cdb[8];
tf->command = cdb[9];
}
/* enforce correct master/slave bit */
tf->device = dev->devno ?
tf->device | ATA_DEV1 : tf->device & ~ATA_DEV1;
switch (tf->command) {
/* READ/WRITE LONG use a non-standard sect_size */
case ATA_CMD_READ_LONG:
case ATA_CMD_READ_LONG_ONCE:
case ATA_CMD_WRITE_LONG:
case ATA_CMD_WRITE_LONG_ONCE:
if (tf->protocol != ATA_PROT_PIO || tf->nsect != 1)
goto invalid_fld;
qc->sect_size = scsi_bufflen(scmd);
break;
/* commands using reported Logical Block size (e.g. 512 or 4K) */
case ATA_CMD_CFA_WRITE_NE:
case ATA_CMD_CFA_TRANS_SECT:
case ATA_CMD_CFA_WRITE_MULT_NE:
/* XXX: case ATA_CMD_CFA_WRITE_SECTORS_WITHOUT_ERASE: */
case ATA_CMD_READ:
case ATA_CMD_READ_EXT:
case ATA_CMD_READ_QUEUED:
/* XXX: case ATA_CMD_READ_QUEUED_EXT: */
case ATA_CMD_FPDMA_READ:
case ATA_CMD_READ_MULTI:
case ATA_CMD_READ_MULTI_EXT:
case ATA_CMD_PIO_READ:
case ATA_CMD_PIO_READ_EXT:
case ATA_CMD_READ_STREAM_DMA_EXT:
case ATA_CMD_READ_STREAM_EXT:
case ATA_CMD_VERIFY:
case ATA_CMD_VERIFY_EXT:
case ATA_CMD_WRITE:
case ATA_CMD_WRITE_EXT:
case ATA_CMD_WRITE_FUA_EXT:
case ATA_CMD_WRITE_QUEUED:
case ATA_CMD_WRITE_QUEUED_FUA_EXT:
case ATA_CMD_FPDMA_WRITE:
case ATA_CMD_WRITE_MULTI:
case ATA_CMD_WRITE_MULTI_EXT:
case ATA_CMD_WRITE_MULTI_FUA_EXT:
case ATA_CMD_PIO_WRITE:
case ATA_CMD_PIO_WRITE_EXT:
case ATA_CMD_WRITE_STREAM_DMA_EXT:
case ATA_CMD_WRITE_STREAM_EXT:
qc->sect_size = scmd->device->sector_size;
break;
/* Everything else uses 512 byte "sectors" */
default:
qc->sect_size = ATA_SECT_SIZE;
}
/*
* Set flags so that all registers will be written, pass on
* write indication (used for PIO/DMA setup), result TF is
* copied back and we don't whine too much about its failure.
*/
tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
if (scmd->sc_data_direction == DMA_TO_DEVICE)
tf->flags |= ATA_TFLAG_WRITE;
qc->flags |= ATA_QCFLAG_RESULT_TF | ATA_QCFLAG_QUIET;
/*
* Set transfer length.
*
* TODO: find out if we need to do more here to
* cover scatter/gather case.
*/
ata_qc_set_pc_nbytes(qc);
/* We may not issue DMA commands if no DMA mode is set */
if (tf->protocol == ATA_PROT_DMA && dev->dma_mode == 0)
goto invalid_fld;
/* sanity check for pio multi commands */
if ((cdb[1] & 0xe0) && !is_multi_taskfile(tf))
goto invalid_fld;
if (is_multi_taskfile(tf)) {
unsigned int multi_count = 1 << (cdb[1] >> 5);
/* compare the passed through multi_count
* with the cached multi_count of libata
*/
if (multi_count != dev->multi_count)
ata_dev_warn(dev, "invalid multi_count %u ignored\n",
multi_count);
}
/*
* Filter SET_FEATURES - XFER MODE command -- otherwise,
* SET_FEATURES - XFER MODE must be preceded/succeeded
* by an update to hardware-specific registers for each
* controller (i.e. the reason for ->set_piomode(),
* ->set_dmamode(), and ->post_set_mode() hooks).
*/
if (tf->command == ATA_CMD_SET_FEATURES &&
tf->feature == SETFEATURES_XFER)
goto invalid_fld;
/*
* Filter TPM commands by default. These provide an
* essentially uncontrolled encrypted "back door" between
* applications and the disk. Set libata.allow_tpm=1 if you
* have a real reason for wanting to use them. This ensures
* that installed software cannot easily mess stuff up without
* user intent. DVR type users will probably ship with this enabled
* for movie content management.
*
* Note that for ATA8 we can issue a DCS change and DCS freeze lock
* for this and should do in future but that it is not sufficient as
* DCS is an optional feature set. Thus we also do the software filter
* so that we comply with the TC consortium stated goal that the user
* can turn off TC features of their system.
*/
if (tf->command >= 0x5C && tf->command <= 0x5F && !libata_allow_tpm)
goto invalid_fld;
return 0;
invalid_fld:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x00);
/* "Invalid field in cdb" */
return 1;
}
static unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
{
struct ata_taskfile *tf = &qc->tf;
struct scsi_cmnd *scmd = qc->scsicmd;
struct ata_device *dev = qc->dev;
const u8 *cdb = scmd->cmnd;
u64 block;
u32 n_block;
u32 size;
void *buf;
/* we may not issue DMA commands if no DMA mode is set */
if (unlikely(!dev->dma_mode))
goto invalid_fld;
if (unlikely(scmd->cmd_len < 16))
goto invalid_fld;
scsi_16_lba_len(cdb, &block, &n_block);
/* for now we only support WRITE SAME with the unmap bit set */
if (unlikely(!(cdb[1] & 0x8)))
goto invalid_fld;
/*
* WRITE SAME always has a sector sized buffer as payload, this
* should never be a multiple entry S/G list.
*/
if (!scsi_sg_count(scmd))
goto invalid_fld;
buf = page_address(sg_page(scsi_sglist(scmd)));
size = ata_set_lba_range_entries(buf, 512, block, n_block);
tf->protocol = ATA_PROT_DMA;
tf->hob_feature = 0;
tf->feature = ATA_DSM_TRIM;
tf->hob_nsect = (size / 512) >> 8;
tf->nsect = size / 512;
tf->command = ATA_CMD_DSM;
tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48 |
ATA_TFLAG_WRITE;
ata_qc_set_pc_nbytes(qc);
return 0;
invalid_fld:
ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x00);
/* "Invalid field in cdb" */
return 1;
}
/**
* ata_get_xlat_func - check if SCSI to ATA translation is possible
* @dev: ATA device
* @cmd: SCSI command opcode to consider
*
* Look up the SCSI command given, and determine whether the
* SCSI command is to be translated or simulated.
*
* RETURNS:
* Pointer to translation function if possible, %NULL if not.
*/
static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
{
switch (cmd) {
case READ_6:
case READ_10:
case READ_16:
case WRITE_6:
case WRITE_10:
case WRITE_16:
return ata_scsi_rw_xlat;
case WRITE_SAME_16:
return ata_scsi_write_same_xlat;
case SYNCHRONIZE_CACHE:
if (ata_try_flush_cache(dev))
return ata_scsi_flush_xlat;
break;
case VERIFY:
case VERIFY_16:
return ata_scsi_verify_xlat;
case ATA_12:
case ATA_16:
return ata_scsi_pass_thru;
case START_STOP:
return ata_scsi_start_stop_xlat;
}
return NULL;
}
/**
* ata_scsi_dump_cdb - dump SCSI command contents to dmesg
* @ap: ATA port to which the command was being sent
* @cmd: SCSI command to dump
*
* Prints the contents of a SCSI command via printk().
*/
static inline void ata_scsi_dump_cdb(struct ata_port *ap,
struct scsi_cmnd *cmd)
{
#ifdef ATA_DEBUG
struct scsi_device *scsidev = cmd->device;
u8 *scsicmd = cmd->cmnd;
DPRINTK("CDB (%u:%d,%d,%d) %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
ap->print_id,
scsidev->channel, scsidev->id, scsidev->lun,
scsicmd[0], scsicmd[1], scsicmd[2], scsicmd[3],
scsicmd[4], scsicmd[5], scsicmd[6], scsicmd[7],
scsicmd[8]);
#endif
}
static inline int __ata_scsi_queuecmd(struct scsi_cmnd *scmd,
struct ata_device *dev)
{
u8 scsi_op = scmd->cmnd[0];
ata_xlat_func_t xlat_func;
int rc = 0;
if (dev->class == ATA_DEV_ATA) {
if (unlikely(!scmd->cmd_len || scmd->cmd_len > dev->cdb_len))
goto bad_cdb_len;
xlat_func = ata_get_xlat_func(dev, scsi_op);
} else {
if (unlikely(!scmd->cmd_len))
goto bad_cdb_len;
xlat_func = NULL;
if (likely((scsi_op != ATA_16) || !atapi_passthru16)) {
/* relay SCSI command to ATAPI device */
int len = COMMAND_SIZE(scsi_op);
if (unlikely(len > scmd->cmd_len || len > dev->cdb_len))
goto bad_cdb_len;
xlat_func = atapi_xlat;
} else {
/* ATA_16 passthru, treat as an ATA command */
if (unlikely(scmd->cmd_len > 16))
goto bad_cdb_len;
xlat_func = ata_get_xlat_func(dev, scsi_op);
}
}
if (xlat_func)
rc = ata_scsi_translate(dev, scmd, xlat_func);
else
ata_scsi_simulate(dev, scmd);
return rc;
bad_cdb_len:
DPRINTK("bad CDB len=%u, scsi_op=0x%02x, max=%u\n",
scmd->cmd_len, scsi_op, dev->cdb_len);
scmd->result = DID_ERROR << 16;
scmd->scsi_done(scmd);
return 0;
}
/**
* ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
* @shost: SCSI host of command to be sent
* @cmd: SCSI command to be sent
*
* In some cases, this function translates SCSI commands into
* ATA taskfiles, and queues the taskfiles to be sent to
* hardware. In other cases, this function simulates a
* SCSI device by evaluating and responding to certain
* SCSI commands. This creates the overall effect of
* ATA and ATAPI devices appearing as SCSI devices.
*
* LOCKING:
* ATA host lock
*
* RETURNS:
* Return value from __ata_scsi_queuecmd() if @cmd can be queued,
* 0 otherwise.
*/
int ata_scsi_queuecmd(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
{
struct ata_port *ap;
struct ata_device *dev;
struct scsi_device *scsidev = cmd->device;
int rc = 0;
unsigned long irq_flags;
ap = ata_shost_to_port(shost);
spin_lock_irqsave(ap->lock, irq_flags);
ata_scsi_dump_cdb(ap, cmd);
dev = ata_scsi_find_dev(ap, scsidev);
if (likely(dev))
rc = __ata_scsi_queuecmd(cmd, dev);
else {
cmd->result = (DID_BAD_TARGET << 16);
cmd->scsi_done(cmd);
}
spin_unlock_irqrestore(ap->lock, irq_flags);
return rc;
}
/**
* ata_scsi_simulate - simulate SCSI command on ATA device
* @dev: the target device
* @cmd: SCSI command being sent to device.
*
* Interprets and directly executes a select list of SCSI commands
* that can be handled internally.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
{
struct ata_scsi_args args;
const u8 *scsicmd = cmd->cmnd;
u8 tmp8;
args.dev = dev;
args.id = dev->id;
args.cmd = cmd;
args.done = cmd->scsi_done;
switch(scsicmd[0]) {
/* TODO: worth improving? */
case FORMAT_UNIT:
ata_scsi_invalid_field(cmd);
break;
case INQUIRY:
if (scsicmd[1] & 2) /* is CmdDt set? */
ata_scsi_invalid_field(cmd);
else if ((scsicmd[1] & 1) == 0) /* is EVPD clear? */
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_std);
else switch (scsicmd[2]) {
case 0x00:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_00);
break;
case 0x80:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_80);
break;
case 0x83:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_83);
break;
case 0x89:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_89);
break;
case 0xb0:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b0);
break;
case 0xb1:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b1);
break;
case 0xb2:
ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b2);
break;
default:
ata_scsi_invalid_field(cmd);
break;
}
break;
case MODE_SENSE:
case MODE_SENSE_10:
ata_scsi_rbuf_fill(&args, ata_scsiop_mode_sense);
break;
case MODE_SELECT: /* unconditionally return */
case MODE_SELECT_10: /* bad-field-in-cdb */
ata_scsi_invalid_field(cmd);
break;
case READ_CAPACITY:
ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
break;
case SERVICE_ACTION_IN:
if ((scsicmd[1] & 0x1f) == SAI_READ_CAPACITY_16)
ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
else
ata_scsi_invalid_field(cmd);
break;
case REPORT_LUNS:
ata_scsi_rbuf_fill(&args, ata_scsiop_report_luns);
break;
case REQUEST_SENSE:
ata_scsi_set_sense(cmd, 0, 0, 0);
cmd->result = (DRIVER_SENSE << 24);
cmd->scsi_done(cmd);
break;
/* if we reach this, then writeback caching is disabled,
* turning this into a no-op.
*/
case SYNCHRONIZE_CACHE:
/* fall through */
/* no-op's, complete with success */
case REZERO_UNIT:
case SEEK_6:
case SEEK_10:
case TEST_UNIT_READY:
ata_scsi_rbuf_fill(&args, ata_scsiop_noop);
break;
case SEND_DIAGNOSTIC:
tmp8 = scsicmd[1] & ~(1 << 3);
if ((tmp8 == 0x4) && (!scsicmd[3]) && (!scsicmd[4]))
ata_scsi_rbuf_fill(&args, ata_scsiop_noop);
else
ata_scsi_invalid_field(cmd);
break;
/* all other commands */
default:
ata_scsi_set_sense(cmd, ILLEGAL_REQUEST, 0x20, 0x0);
/* "Invalid command operation code" */
cmd->scsi_done(cmd);
break;
}
}
int ata_scsi_add_hosts(struct ata_host *host, struct scsi_host_template *sht)
{
int i, rc;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
struct Scsi_Host *shost;
rc = -ENOMEM;
shost = scsi_host_alloc(sht, sizeof(struct ata_port *));
if (!shost)
goto err_alloc;
shost->eh_noresume = 1;
*(struct ata_port **)&shost->hostdata[0] = ap;
ap->scsi_host = shost;
shost->transportt = ata_scsi_transport_template;
shost->unique_id = ap->print_id;
shost->max_id = 16;
shost->max_lun = 1;
shost->max_channel = 1;
shost->max_cmd_len = 16;
/* Schedule policy is determined by ->qc_defer()
* callback and it needs to see every deferred qc.
* Set host_blocked to 1 to prevent SCSI midlayer from
* automatically deferring requests.
*/
shost->max_host_blocked = 1;
rc = scsi_add_host_with_dma(ap->scsi_host,
&ap->tdev, ap->host->dev);
if (rc)
goto err_add;
}
return 0;
err_add:
scsi_host_put(host->ports[i]->scsi_host);
err_alloc:
while (--i >= 0) {
struct Scsi_Host *shost = host->ports[i]->scsi_host;
scsi_remove_host(shost);
scsi_host_put(shost);
}
return rc;
}
void ata_scsi_scan_host(struct ata_port *ap, int sync)
{
int tries = 5;
struct ata_device *last_failed_dev = NULL;
struct ata_link *link;
struct ata_device *dev;
repeat:
ata_for_each_link(link, ap, EDGE) {
ata_for_each_dev(dev, link, ENABLED) {
struct scsi_device *sdev;
int channel = 0, id = 0;
if (dev->sdev)
continue;
if (ata_is_host_link(link))
id = dev->devno;
else
channel = link->pmp;
sdev = __scsi_add_device(ap->scsi_host, channel, id, 0,
NULL);
if (!IS_ERR(sdev)) {
dev->sdev = sdev;
scsi_device_put(sdev);
} else {
dev->sdev = NULL;
}
}
}
/* If we scanned while EH was in progress or allocation
* failure occurred, scan would have failed silently. Check
* whether all devices are attached.
*/
ata_for_each_link(link, ap, EDGE) {
ata_for_each_dev(dev, link, ENABLED) {
if (!dev->sdev)
goto exit_loop;
}
}
exit_loop:
if (!link)
return;
/* we're missing some SCSI devices */
if (sync) {
/* If caller requested synchrnous scan && we've made
* any progress, sleep briefly and repeat.
*/
if (dev != last_failed_dev) {
msleep(100);
last_failed_dev = dev;
goto repeat;
}
/* We might be failing to detect boot device, give it
* a few more chances.
*/
if (--tries) {
msleep(100);
goto repeat;
}
ata_port_err(ap,
"WARNING: synchronous SCSI scan failed without making any progress, switching to async\n");
}
queue_delayed_work(system_long_wq, &ap->hotplug_task,
round_jiffies_relative(HZ));
}
/**
* ata_scsi_offline_dev - offline attached SCSI device
* @dev: ATA device to offline attached SCSI device for
*
* This function is called from ata_eh_hotplug() and responsible
* for taking the SCSI device attached to @dev offline. This
* function is called with host lock which protects dev->sdev
* against clearing.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* 1 if attached SCSI device exists, 0 otherwise.
*/
int ata_scsi_offline_dev(struct ata_device *dev)
{
if (dev->sdev) {
scsi_device_set_state(dev->sdev, SDEV_OFFLINE);
return 1;
}
return 0;
}
/**
* ata_scsi_remove_dev - remove attached SCSI device
* @dev: ATA device to remove attached SCSI device for
*
* This function is called from ata_eh_scsi_hotplug() and
* responsible for removing the SCSI device attached to @dev.
*
* LOCKING:
* Kernel thread context (may sleep).
*/
static void ata_scsi_remove_dev(struct ata_device *dev)
{
struct ata_port *ap = dev->link->ap;
struct scsi_device *sdev;
unsigned long flags;
/* Alas, we need to grab scan_mutex to ensure SCSI device
* state doesn't change underneath us and thus
* scsi_device_get() always succeeds. The mutex locking can
* be removed if there is __scsi_device_get() interface which
* increments reference counts regardless of device state.
*/
mutex_lock(&ap->scsi_host->scan_mutex);
spin_lock_irqsave(ap->lock, flags);
/* clearing dev->sdev is protected by host lock */
sdev = dev->sdev;
dev->sdev = NULL;
if (sdev) {
/* If user initiated unplug races with us, sdev can go
* away underneath us after the host lock and
* scan_mutex are released. Hold onto it.
*/
if (scsi_device_get(sdev) == 0) {
/* The following ensures the attached sdev is
* offline on return from ata_scsi_offline_dev()
* regardless it wins or loses the race
* against this function.
*/
scsi_device_set_state(sdev, SDEV_OFFLINE);
} else {
WARN_ON(1);
sdev = NULL;
}
}
spin_unlock_irqrestore(ap->lock, flags);
mutex_unlock(&ap->scsi_host->scan_mutex);
if (sdev) {
ata_dev_info(dev, "detaching (SCSI %s)\n",
dev_name(&sdev->sdev_gendev));
scsi_remove_device(sdev);
scsi_device_put(sdev);
}
}
static void ata_scsi_handle_link_detach(struct ata_link *link)
{
struct ata_port *ap = link->ap;
struct ata_device *dev;
ata_for_each_dev(dev, link, ALL) {
unsigned long flags;
if (!(dev->flags & ATA_DFLAG_DETACHED))
continue;
spin_lock_irqsave(ap->lock, flags);
dev->flags &= ~ATA_DFLAG_DETACHED;
spin_unlock_irqrestore(ap->lock, flags);
ata_scsi_remove_dev(dev);
}
}
/**
* ata_scsi_media_change_notify - send media change event
* @dev: Pointer to the disk device with media change event
*
* Tell the block layer to send a media change notification
* event.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_scsi_media_change_notify(struct ata_device *dev)
{
if (dev->sdev)
sdev_evt_send_simple(dev->sdev, SDEV_EVT_MEDIA_CHANGE,
GFP_ATOMIC);
}
/**
* ata_scsi_hotplug - SCSI part of hotplug
* @work: Pointer to ATA port to perform SCSI hotplug on
*
* Perform SCSI part of hotplug. It's executed from a separate
* workqueue after EH completes. This is necessary because SCSI
* hot plugging requires working EH and hot unplugging is
* synchronized with hot plugging with a mutex.
*
* LOCKING:
* Kernel thread context (may sleep).
*/
void ata_scsi_hotplug(struct work_struct *work)
{
struct ata_port *ap =
container_of(work, struct ata_port, hotplug_task.work);
int i;
if (ap->pflags & ATA_PFLAG_UNLOADING) {
DPRINTK("ENTER/EXIT - unloading\n");
return;
}
DPRINTK("ENTER\n");
mutex_lock(&ap->scsi_scan_mutex);
/* Unplug detached devices. We cannot use link iterator here
* because PMP links have to be scanned even if PMP is
* currently not attached. Iterate manually.
*/
ata_scsi_handle_link_detach(&ap->link);
if (ap->pmp_link)
for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
ata_scsi_handle_link_detach(&ap->pmp_link[i]);
/* scan for new ones */
ata_scsi_scan_host(ap, 0);
mutex_unlock(&ap->scsi_scan_mutex);
DPRINTK("EXIT\n");
}
/**
* ata_scsi_user_scan - indication for user-initiated bus scan
* @shost: SCSI host to scan
* @channel: Channel to scan
* @id: ID to scan
* @lun: LUN to scan
*
* This function is called when user explicitly requests bus
* scan. Set probe pending flag and invoke EH.
*
* LOCKING:
* SCSI layer (we don't care)
*
* RETURNS:
* Zero.
*/
int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
unsigned int id, unsigned int lun)
{
struct ata_port *ap = ata_shost_to_port(shost);
unsigned long flags;
int devno, rc = 0;
if (!ap->ops->error_handler)
return -EOPNOTSUPP;
if (lun != SCAN_WILD_CARD && lun)
return -EINVAL;
if (!sata_pmp_attached(ap)) {
if (channel != SCAN_WILD_CARD && channel)
return -EINVAL;
devno = id;
} else {
if (id != SCAN_WILD_CARD && id)
return -EINVAL;
devno = channel;
}
spin_lock_irqsave(ap->lock, flags);
if (devno == SCAN_WILD_CARD) {
struct ata_link *link;
ata_for_each_link(link, ap, EDGE) {
struct ata_eh_info *ehi = &link->eh_info;
ehi->probe_mask |= ATA_ALL_DEVICES;
ehi->action |= ATA_EH_RESET;
}
} else {
struct ata_device *dev = ata_find_dev(ap, devno);
if (dev) {
struct ata_eh_info *ehi = &dev->link->eh_info;
ehi->probe_mask |= 1 << dev->devno;
ehi->action |= ATA_EH_RESET;
} else
rc = -EINVAL;
}
if (rc == 0) {
ata_port_schedule_eh(ap);
spin_unlock_irqrestore(ap->lock, flags);
ata_port_wait_eh(ap);
} else
spin_unlock_irqrestore(ap->lock, flags);
return rc;
}
/**
* ata_scsi_dev_rescan - initiate scsi_rescan_device()
* @work: Pointer to ATA port to perform scsi_rescan_device()
*
* After ATA pass thru (SAT) commands are executed successfully,
* libata need to propagate the changes to SCSI layer.
*
* LOCKING:
* Kernel thread context (may sleep).
*/
void ata_scsi_dev_rescan(struct work_struct *work)
{
struct ata_port *ap =
container_of(work, struct ata_port, scsi_rescan_task);
struct ata_link *link;
struct ata_device *dev;
unsigned long flags;
mutex_lock(&ap->scsi_scan_mutex);
spin_lock_irqsave(ap->lock, flags);
ata_for_each_link(link, ap, EDGE) {
ata_for_each_dev(dev, link, ENABLED) {
struct scsi_device *sdev = dev->sdev;
if (!sdev)
continue;
if (scsi_device_get(sdev))
continue;
spin_unlock_irqrestore(ap->lock, flags);
scsi_rescan_device(&(sdev->sdev_gendev));
scsi_device_put(sdev);
spin_lock_irqsave(ap->lock, flags);
}
}
spin_unlock_irqrestore(ap->lock, flags);
mutex_unlock(&ap->scsi_scan_mutex);
}
/**
* ata_sas_port_alloc - Allocate port for a SAS attached SATA device
* @host: ATA host container for all SAS ports
* @port_info: Information from low-level host driver
* @shost: SCSI host that the scsi device is attached to
*
* LOCKING:
* PCI/etc. bus probe sem.
*
* RETURNS:
* ata_port pointer on success / NULL on failure.
*/
struct ata_port *ata_sas_port_alloc(struct ata_host *host,
struct ata_port_info *port_info,
struct Scsi_Host *shost)
{
struct ata_port *ap;
ap = ata_port_alloc(host);
if (!ap)
return NULL;
ap->port_no = 0;
ap->lock = &host->lock;
ap->pio_mask = port_info->pio_mask;
ap->mwdma_mask = port_info->mwdma_mask;
ap->udma_mask = port_info->udma_mask;
ap->flags |= port_info->flags;
ap->ops = port_info->port_ops;
ap->cbl = ATA_CBL_SATA;
return ap;
}
EXPORT_SYMBOL_GPL(ata_sas_port_alloc);
/**
* ata_sas_port_start - Set port up for dma.
* @ap: Port to initialize
*
* Called just after data structures for each port are
* initialized.
*
* May be used as the port_start() entry in ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
int ata_sas_port_start(struct ata_port *ap)
{
/*
* the port is marked as frozen at allocation time, but if we don't
* have new eh, we won't thaw it
*/
if (!ap->ops->error_handler)
ap->pflags &= ~ATA_PFLAG_FROZEN;
return 0;
}
EXPORT_SYMBOL_GPL(ata_sas_port_start);
/**
* ata_port_stop - Undo ata_sas_port_start()
* @ap: Port to shut down
*
* May be used as the port_stop() entry in ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sas_port_stop(struct ata_port *ap)
{
}
EXPORT_SYMBOL_GPL(ata_sas_port_stop);
/**
* ata_sas_async_probe - simply schedule probing and return
* @ap: Port to probe
*
* For batch scheduling of probe for sas attached ata devices, assumes
* the port has already been through ata_sas_port_init()
*/
void ata_sas_async_probe(struct ata_port *ap)
{
__ata_port_probe(ap);
}
EXPORT_SYMBOL_GPL(ata_sas_async_probe);
int ata_sas_sync_probe(struct ata_port *ap)
{
return ata_port_probe(ap);
}
EXPORT_SYMBOL_GPL(ata_sas_sync_probe);
/**
* ata_sas_port_init - Initialize a SATA device
* @ap: SATA port to initialize
*
* LOCKING:
* PCI/etc. bus probe sem.
*
* RETURNS:
* Zero on success, non-zero on error.
*/
int ata_sas_port_init(struct ata_port *ap)
{
int rc = ap->ops->port_start(ap);
if (rc)
return rc;
ap->print_id = atomic_inc_return(&ata_print_id);
return 0;
}
EXPORT_SYMBOL_GPL(ata_sas_port_init);
/**
* ata_sas_port_destroy - Destroy a SATA port allocated by ata_sas_port_alloc
* @ap: SATA port to destroy
*
*/
void ata_sas_port_destroy(struct ata_port *ap)
{
if (ap->ops->port_stop)
ap->ops->port_stop(ap);
kfree(ap);
}
EXPORT_SYMBOL_GPL(ata_sas_port_destroy);
/**
* ata_sas_slave_configure - Default slave_config routine for libata devices
* @sdev: SCSI device to configure
* @ap: ATA port to which SCSI device is attached
*
* RETURNS:
* Zero.
*/
int ata_sas_slave_configure(struct scsi_device *sdev, struct ata_port *ap)
{
ata_scsi_sdev_config(sdev);
ata_scsi_dev_config(sdev, ap->link.device);
return 0;
}
EXPORT_SYMBOL_GPL(ata_sas_slave_configure);
/**
* ata_sas_queuecmd - Issue SCSI cdb to libata-managed device
* @cmd: SCSI command to be sent
* @ap: ATA port to which the command is being sent
*
* RETURNS:
* Return value from __ata_scsi_queuecmd() if @cmd can be queued,
* 0 otherwise.
*/
int ata_sas_queuecmd(struct scsi_cmnd *cmd, struct ata_port *ap)
{
int rc = 0;
ata_scsi_dump_cdb(ap, cmd);
if (likely(ata_dev_enabled(ap->link.device)))
rc = __ata_scsi_queuecmd(cmd, ap->link.device);
else {
cmd->result = (DID_BAD_TARGET << 16);
cmd->scsi_done(cmd);
}
return rc;
}
EXPORT_SYMBOL_GPL(ata_sas_queuecmd);
| gpl-2.0 |
fergy/optimus-l3_e400_kernel | arch/xtensa/oprofile/backtrace.c | 3549 | 3919 | /**
* @file backtrace.c
*
* @remark Copyright 2008 Tensilica Inc.
* @remark Read the file COPYING
*
*/
#include <linux/oprofile.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <asm/ptrace.h>
#include <asm/uaccess.h>
#include <asm/traps.h>
/* Address of common_exception_return, used to check the
* transition from kernel to user space.
*/
extern int common_exception_return;
/* A struct that maps to the part of the frame containing the a0 and
* a1 registers.
*/
struct frame_start {
unsigned long a0;
unsigned long a1;
};
static void xtensa_backtrace_user(struct pt_regs *regs, unsigned int depth)
{
unsigned long windowstart = regs->windowstart;
unsigned long windowbase = regs->windowbase;
unsigned long a0 = regs->areg[0];
unsigned long a1 = regs->areg[1];
unsigned long pc = MAKE_PC_FROM_RA(a0, regs->pc);
int index;
/* First add the current PC to the trace. */
if (pc != 0 && pc <= TASK_SIZE)
oprofile_add_trace(pc);
else
return;
/* Two steps:
*
* 1. Look through the register window for the
* previous PCs in the call trace.
*
* 2. Look on the stack.
*/
/* Step 1. */
/* Rotate WINDOWSTART to move the bit corresponding to
* the current window to the bit #0.
*/
windowstart = (windowstart << WSBITS | windowstart) >> windowbase;
/* Look for bits that are set, they correspond to
* valid windows.
*/
for (index = WSBITS - 1; (index > 0) && depth; depth--, index--)
if (windowstart & (1 << index)) {
/* Read a0 and a1 from the
* corresponding position in AREGs.
*/
a0 = regs->areg[index * 4];
a1 = regs->areg[index * 4 + 1];
/* Get the PC from a0 and a1. */
pc = MAKE_PC_FROM_RA(a0, pc);
/* Add the PC to the trace. */
if (pc != 0 && pc <= TASK_SIZE)
oprofile_add_trace(pc);
else
return;
}
/* Step 2. */
/* We are done with the register window, we need to
* look through the stack.
*/
if (depth > 0) {
/* Start from the a1 register. */
/* a1 = regs->areg[1]; */
while (a0 != 0 && depth--) {
struct frame_start frame_start;
/* Get the location for a1, a0 for the
* previous frame from the current a1.
*/
unsigned long *psp = (unsigned long *)a1;
psp -= 4;
/* Check if the region is OK to access. */
if (!access_ok(VERIFY_READ, psp, sizeof(frame_start)))
return;
/* Copy a1, a0 from user space stack frame. */
if (__copy_from_user_inatomic(&frame_start, psp,
sizeof(frame_start)))
return;
a0 = frame_start.a0;
a1 = frame_start.a1;
pc = MAKE_PC_FROM_RA(a0, pc);
if (pc != 0 && pc <= TASK_SIZE)
oprofile_add_trace(pc);
else
return;
}
}
}
static void xtensa_backtrace_kernel(struct pt_regs *regs, unsigned int depth)
{
unsigned long pc = regs->pc;
unsigned long *psp;
unsigned long sp_start, sp_end;
unsigned long a0 = regs->areg[0];
unsigned long a1 = regs->areg[1];
sp_start = a1 & ~(THREAD_SIZE-1);
sp_end = sp_start + THREAD_SIZE;
/* Spill the register window to the stack first. */
spill_registers();
/* Read the stack frames one by one and create the PC
* from the a0 and a1 registers saved there.
*/
while (a1 > sp_start && a1 < sp_end && depth--) {
pc = MAKE_PC_FROM_RA(a0, pc);
/* Add the PC to the trace. */
oprofile_add_trace(pc);
if (pc == (unsigned long) &common_exception_return) {
regs = (struct pt_regs *)a1;
if (user_mode(regs)) {
pc = regs->pc;
if (pc != 0 && pc <= TASK_SIZE)
oprofile_add_trace(pc);
else
return;
return xtensa_backtrace_user(regs, depth);
}
a0 = regs->areg[0];
a1 = regs->areg[1];
continue;
}
psp = (unsigned long *)a1;
a0 = *(psp - 4);
a1 = *(psp - 3);
if (a1 <= (unsigned long)psp)
return;
}
return;
}
void xtensa_backtrace(struct pt_regs * const regs, unsigned int depth)
{
if (user_mode(regs))
xtensa_backtrace_user(regs, depth);
else
xtensa_backtrace_kernel(regs, depth);
}
| gpl-2.0 |
LGaljo/android_kernel_samsung_msm8226-common | drivers/ata/libata-sff.c | 4573 | 85882 | /*
* libata-sff.c - helper library for PCI IDE BMDMA
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2006 Red Hat, Inc. All rights reserved.
* Copyright 2003-2006 Jeff Garzik
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available from http://www.t13.org/ and
* http://www.sata-io.org/
*
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/libata.h>
#include <linux/highmem.h>
#include "libata.h"
static struct workqueue_struct *ata_sff_wq;
const struct ata_port_operations ata_sff_port_ops = {
.inherits = &ata_base_port_ops,
.qc_prep = ata_noop_qc_prep,
.qc_issue = ata_sff_qc_issue,
.qc_fill_rtf = ata_sff_qc_fill_rtf,
.freeze = ata_sff_freeze,
.thaw = ata_sff_thaw,
.prereset = ata_sff_prereset,
.softreset = ata_sff_softreset,
.hardreset = sata_sff_hardreset,
.postreset = ata_sff_postreset,
.error_handler = ata_sff_error_handler,
.sff_dev_select = ata_sff_dev_select,
.sff_check_status = ata_sff_check_status,
.sff_tf_load = ata_sff_tf_load,
.sff_tf_read = ata_sff_tf_read,
.sff_exec_command = ata_sff_exec_command,
.sff_data_xfer = ata_sff_data_xfer,
.sff_drain_fifo = ata_sff_drain_fifo,
.lost_interrupt = ata_sff_lost_interrupt,
};
EXPORT_SYMBOL_GPL(ata_sff_port_ops);
/**
* ata_sff_check_status - Read device status reg & clear interrupt
* @ap: port where the device is
*
* Reads ATA taskfile status register for currently-selected device
* and return its value. This also clears pending interrupts
* from this device
*
* LOCKING:
* Inherited from caller.
*/
u8 ata_sff_check_status(struct ata_port *ap)
{
return ioread8(ap->ioaddr.status_addr);
}
EXPORT_SYMBOL_GPL(ata_sff_check_status);
/**
* ata_sff_altstatus - Read device alternate status reg
* @ap: port where the device is
*
* Reads ATA taskfile alternate status register for
* currently-selected device and return its value.
*
* Note: may NOT be used as the check_altstatus() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
static u8 ata_sff_altstatus(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus)
return ap->ops->sff_check_altstatus(ap);
return ioread8(ap->ioaddr.altstatus_addr);
}
/**
* ata_sff_irq_status - Check if the device is busy
* @ap: port where the device is
*
* Determine if the port is currently busy. Uses altstatus
* if available in order to avoid clearing shared IRQ status
* when finding an IRQ source. Non ctl capable devices don't
* share interrupt lines fortunately for us.
*
* LOCKING:
* Inherited from caller.
*/
static u8 ata_sff_irq_status(struct ata_port *ap)
{
u8 status;
if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
status = ata_sff_altstatus(ap);
/* Not us: We are busy */
if (status & ATA_BUSY)
return status;
}
/* Clear INTRQ latch */
status = ap->ops->sff_check_status(ap);
return status;
}
/**
* ata_sff_sync - Flush writes
* @ap: Port to wait for.
*
* CAUTION:
* If we have an mmio device with no ctl and no altstatus
* method this will fail. No such devices are known to exist.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_sff_sync(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus)
ap->ops->sff_check_altstatus(ap);
else if (ap->ioaddr.altstatus_addr)
ioread8(ap->ioaddr.altstatus_addr);
}
/**
* ata_sff_pause - Flush writes and wait 400nS
* @ap: Port to pause for.
*
* CAUTION:
* If we have an mmio device with no ctl and no altstatus
* method this will fail. No such devices are known to exist.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_pause(struct ata_port *ap)
{
ata_sff_sync(ap);
ndelay(400);
}
EXPORT_SYMBOL_GPL(ata_sff_pause);
/**
* ata_sff_dma_pause - Pause before commencing DMA
* @ap: Port to pause for.
*
* Perform I/O fencing and ensure sufficient cycle delays occur
* for the HDMA1:0 transition
*/
void ata_sff_dma_pause(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
/* An altstatus read will cause the needed delay without
messing up the IRQ status */
ata_sff_altstatus(ap);
return;
}
/* There are no DMA controllers without ctl. BUG here to ensure
we never violate the HDMA1:0 transition timing and risk
corruption. */
BUG();
}
EXPORT_SYMBOL_GPL(ata_sff_dma_pause);
/**
* ata_sff_busy_sleep - sleep until BSY clears, or timeout
* @ap: port containing status register to be polled
* @tmout_pat: impatience timeout in msecs
* @tmout: overall timeout in msecs
*
* Sleep until ATA Status register bit BSY clears,
* or a timeout occurs.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_busy_sleep(struct ata_port *ap,
unsigned long tmout_pat, unsigned long tmout)
{
unsigned long timer_start, timeout;
u8 status;
status = ata_sff_busy_wait(ap, ATA_BUSY, 300);
timer_start = jiffies;
timeout = ata_deadline(timer_start, tmout_pat);
while (status != 0xff && (status & ATA_BUSY) &&
time_before(jiffies, timeout)) {
ata_msleep(ap, 50);
status = ata_sff_busy_wait(ap, ATA_BUSY, 3);
}
if (status != 0xff && (status & ATA_BUSY))
ata_port_warn(ap,
"port is slow to respond, please be patient (Status 0x%x)\n",
status);
timeout = ata_deadline(timer_start, tmout);
while (status != 0xff && (status & ATA_BUSY) &&
time_before(jiffies, timeout)) {
ata_msleep(ap, 50);
status = ap->ops->sff_check_status(ap);
}
if (status == 0xff)
return -ENODEV;
if (status & ATA_BUSY) {
ata_port_err(ap,
"port failed to respond (%lu secs, Status 0x%x)\n",
DIV_ROUND_UP(tmout, 1000), status);
return -EBUSY;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_busy_sleep);
static int ata_sff_check_ready(struct ata_link *link)
{
u8 status = link->ap->ops->sff_check_status(link->ap);
return ata_check_ready(status);
}
/**
* ata_sff_wait_ready - sleep until BSY clears, or timeout
* @link: SFF link to wait ready status for
* @deadline: deadline jiffies for the operation
*
* Sleep until ATA Status register bit BSY clears, or timeout
* occurs.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_wait_ready(struct ata_link *link, unsigned long deadline)
{
return ata_wait_ready(link, deadline, ata_sff_check_ready);
}
EXPORT_SYMBOL_GPL(ata_sff_wait_ready);
/**
* ata_sff_set_devctl - Write device control reg
* @ap: port where the device is
* @ctl: value to write
*
* Writes ATA taskfile device control register.
*
* Note: may NOT be used as the sff_set_devctl() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_sff_set_devctl(struct ata_port *ap, u8 ctl)
{
if (ap->ops->sff_set_devctl)
ap->ops->sff_set_devctl(ap, ctl);
else
iowrite8(ctl, ap->ioaddr.ctl_addr);
}
/**
* ata_sff_dev_select - Select device 0/1 on ATA bus
* @ap: ATA channel to manipulate
* @device: ATA device (numbered from zero) to select
*
* Use the method defined in the ATA specification to
* make either device 0, or device 1, active on the
* ATA channel. Works with both PIO and MMIO.
*
* May be used as the dev_select() entry in ata_port_operations.
*
* LOCKING:
* caller.
*/
void ata_sff_dev_select(struct ata_port *ap, unsigned int device)
{
u8 tmp;
if (device == 0)
tmp = ATA_DEVICE_OBS;
else
tmp = ATA_DEVICE_OBS | ATA_DEV1;
iowrite8(tmp, ap->ioaddr.device_addr);
ata_sff_pause(ap); /* needed; also flushes, for mmio */
}
EXPORT_SYMBOL_GPL(ata_sff_dev_select);
/**
* ata_dev_select - Select device 0/1 on ATA bus
* @ap: ATA channel to manipulate
* @device: ATA device (numbered from zero) to select
* @wait: non-zero to wait for Status register BSY bit to clear
* @can_sleep: non-zero if context allows sleeping
*
* Use the method defined in the ATA specification to
* make either device 0, or device 1, active on the
* ATA channel.
*
* This is a high-level version of ata_sff_dev_select(), which
* additionally provides the services of inserting the proper
* pauses and status polling, where needed.
*
* LOCKING:
* caller.
*/
static void ata_dev_select(struct ata_port *ap, unsigned int device,
unsigned int wait, unsigned int can_sleep)
{
if (ata_msg_probe(ap))
ata_port_info(ap, "ata_dev_select: ENTER, device %u, wait %u\n",
device, wait);
if (wait)
ata_wait_idle(ap);
ap->ops->sff_dev_select(ap, device);
if (wait) {
if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
ata_msleep(ap, 150);
ata_wait_idle(ap);
}
}
/**
* ata_sff_irq_on - Enable interrupts on a port.
* @ap: Port on which interrupts are enabled.
*
* Enable interrupts on a legacy IDE device using MMIO or PIO,
* wait for idle, clear any pending interrupts.
*
* Note: may NOT be used as the sff_irq_on() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_irq_on(struct ata_port *ap)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
if (ap->ops->sff_irq_on) {
ap->ops->sff_irq_on(ap);
return;
}
ap->ctl &= ~ATA_NIEN;
ap->last_ctl = ap->ctl;
if (ap->ops->sff_set_devctl || ioaddr->ctl_addr)
ata_sff_set_devctl(ap, ap->ctl);
ata_wait_idle(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_irq_on);
/**
* ata_sff_tf_load - send taskfile registers to host controller
* @ap: Port to which output is sent
* @tf: ATA taskfile register set
*
* Outputs ATA taskfile to standard ATA host controller.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
if (tf->ctl != ap->last_ctl) {
if (ioaddr->ctl_addr)
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
ata_wait_idle(ap);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
WARN_ON_ONCE(!ioaddr->ctl_addr);
iowrite8(tf->hob_feature, ioaddr->feature_addr);
iowrite8(tf->hob_nsect, ioaddr->nsect_addr);
iowrite8(tf->hob_lbal, ioaddr->lbal_addr);
iowrite8(tf->hob_lbam, ioaddr->lbam_addr);
iowrite8(tf->hob_lbah, ioaddr->lbah_addr);
VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
tf->hob_feature,
tf->hob_nsect,
tf->hob_lbal,
tf->hob_lbam,
tf->hob_lbah);
}
if (is_addr) {
iowrite8(tf->feature, ioaddr->feature_addr);
iowrite8(tf->nsect, ioaddr->nsect_addr);
iowrite8(tf->lbal, ioaddr->lbal_addr);
iowrite8(tf->lbam, ioaddr->lbam_addr);
iowrite8(tf->lbah, ioaddr->lbah_addr);
VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
tf->feature,
tf->nsect,
tf->lbal,
tf->lbam,
tf->lbah);
}
if (tf->flags & ATA_TFLAG_DEVICE) {
iowrite8(tf->device, ioaddr->device_addr);
VPRINTK("device 0x%X\n", tf->device);
}
ata_wait_idle(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_tf_load);
/**
* ata_sff_tf_read - input device's ATA taskfile shadow registers
* @ap: Port from which input is read
* @tf: ATA taskfile register set for storing input
*
* Reads ATA taskfile registers for currently-selected device
* into @tf. Assumes the device has a fully SFF compliant task file
* layout and behaviour. If you device does not (eg has a different
* status method) then you will need to provide a replacement tf_read
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
tf->command = ata_sff_check_status(ap);
tf->feature = ioread8(ioaddr->error_addr);
tf->nsect = ioread8(ioaddr->nsect_addr);
tf->lbal = ioread8(ioaddr->lbal_addr);
tf->lbam = ioread8(ioaddr->lbam_addr);
tf->lbah = ioread8(ioaddr->lbah_addr);
tf->device = ioread8(ioaddr->device_addr);
if (tf->flags & ATA_TFLAG_LBA48) {
if (likely(ioaddr->ctl_addr)) {
iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
tf->hob_feature = ioread8(ioaddr->error_addr);
tf->hob_nsect = ioread8(ioaddr->nsect_addr);
tf->hob_lbal = ioread8(ioaddr->lbal_addr);
tf->hob_lbam = ioread8(ioaddr->lbam_addr);
tf->hob_lbah = ioread8(ioaddr->lbah_addr);
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
} else
WARN_ON_ONCE(1);
}
}
EXPORT_SYMBOL_GPL(ata_sff_tf_read);
/**
* ata_sff_exec_command - issue ATA command to host controller
* @ap: port to which command is being issued
* @tf: ATA taskfile register set
*
* Issues ATA command, with proper synchronization with interrupt
* handler / other threads.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_sff_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
{
DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command);
iowrite8(tf->command, ap->ioaddr.command_addr);
ata_sff_pause(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_exec_command);
/**
* ata_tf_to_host - issue ATA taskfile to host controller
* @ap: port to which command is being issued
* @tf: ATA taskfile register set
*
* Issues ATA taskfile register set to ATA host controller,
* with proper synchronization with interrupt handler and
* other threads.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static inline void ata_tf_to_host(struct ata_port *ap,
const struct ata_taskfile *tf)
{
ap->ops->sff_tf_load(ap, tf);
ap->ops->sff_exec_command(ap, tf);
}
/**
* ata_sff_data_xfer - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
struct ata_port *ap = dev->link->ap;
void __iomem *data_addr = ap->ioaddr.data_addr;
unsigned int words = buflen >> 1;
/* Transfer multiple of 2 bytes */
if (rw == READ)
ioread16_rep(data_addr, buf, words);
else
iowrite16_rep(data_addr, buf, words);
/* Transfer trailing byte, if any. */
if (unlikely(buflen & 0x01)) {
unsigned char pad[2] = { };
/* Point buf to the tail of buffer */
buf += buflen - 1;
/*
* Use io*16_rep() accessors here as well to avoid pointlessly
* swapping bytes to and from on the big endian machines...
*/
if (rw == READ) {
ioread16_rep(data_addr, pad, 1);
*buf = pad[0];
} else {
pad[0] = *buf;
iowrite16_rep(data_addr, pad, 1);
}
words++;
}
return words << 1;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer);
/**
* ata_sff_data_xfer32 - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO using 32bit
* I/O operations.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer32(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
struct ata_port *ap = dev->link->ap;
void __iomem *data_addr = ap->ioaddr.data_addr;
unsigned int words = buflen >> 2;
int slop = buflen & 3;
if (!(ap->pflags & ATA_PFLAG_PIO32))
return ata_sff_data_xfer(dev, buf, buflen, rw);
/* Transfer multiple of 4 bytes */
if (rw == READ)
ioread32_rep(data_addr, buf, words);
else
iowrite32_rep(data_addr, buf, words);
/* Transfer trailing bytes, if any */
if (unlikely(slop)) {
unsigned char pad[4] = { };
/* Point buf to the tail of buffer */
buf += buflen - slop;
/*
* Use io*_rep() accessors here as well to avoid pointlessly
* swapping bytes to and from on the big endian machines...
*/
if (rw == READ) {
if (slop < 3)
ioread16_rep(data_addr, pad, 1);
else
ioread32_rep(data_addr, pad, 1);
memcpy(buf, pad, slop);
} else {
memcpy(pad, buf, slop);
if (slop < 3)
iowrite16_rep(data_addr, pad, 1);
else
iowrite32_rep(data_addr, pad, 1);
}
}
return (buflen + 1) & ~1;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer32);
/**
* ata_sff_data_xfer_noirq - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO. Do the
* transfer with interrupts disabled.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer_noirq(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
unsigned long flags;
unsigned int consumed;
local_irq_save(flags);
consumed = ata_sff_data_xfer32(dev, buf, buflen, rw);
local_irq_restore(flags);
return consumed;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer_noirq);
/**
* ata_pio_sector - Transfer a sector of data.
* @qc: Command on going
*
* Transfer qc->sect_size bytes of data from/to the ATA device.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_pio_sector(struct ata_queued_cmd *qc)
{
int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
struct ata_port *ap = qc->ap;
struct page *page;
unsigned int offset;
unsigned char *buf;
if (qc->curbytes == qc->nbytes - qc->sect_size)
ap->hsm_task_state = HSM_ST_LAST;
page = sg_page(qc->cursg);
offset = qc->cursg->offset + qc->cursg_ofs;
/* get the current page and offset */
page = nth_page(page, (offset >> PAGE_SHIFT));
offset %= PAGE_SIZE;
DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
if (PageHighMem(page)) {
unsigned long flags;
/* FIXME: use a bounce buffer */
local_irq_save(flags);
buf = kmap_atomic(page);
/* do the actual data transfer */
ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
do_write);
kunmap_atomic(buf);
local_irq_restore(flags);
} else {
buf = page_address(page);
ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
do_write);
}
if (!do_write && !PageSlab(page))
flush_dcache_page(page);
qc->curbytes += qc->sect_size;
qc->cursg_ofs += qc->sect_size;
if (qc->cursg_ofs == qc->cursg->length) {
qc->cursg = sg_next(qc->cursg);
qc->cursg_ofs = 0;
}
}
/**
* ata_pio_sectors - Transfer one or many sectors.
* @qc: Command on going
*
* Transfer one or many sectors of data from/to the
* ATA device for the DRQ request.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_pio_sectors(struct ata_queued_cmd *qc)
{
if (is_multi_taskfile(&qc->tf)) {
/* READ/WRITE MULTIPLE */
unsigned int nsect;
WARN_ON_ONCE(qc->dev->multi_count == 0);
nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
qc->dev->multi_count);
while (nsect--)
ata_pio_sector(qc);
} else
ata_pio_sector(qc);
ata_sff_sync(qc->ap); /* flush */
}
/**
* atapi_send_cdb - Write CDB bytes to hardware
* @ap: Port to which ATAPI device is attached.
* @qc: Taskfile currently active
*
* When device has indicated its readiness to accept
* a CDB, this function is called. Send the CDB.
*
* LOCKING:
* caller.
*/
static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
{
/* send SCSI cdb */
DPRINTK("send cdb\n");
WARN_ON_ONCE(qc->dev->cdb_len < 12);
ap->ops->sff_data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
ata_sff_sync(ap);
/* FIXME: If the CDB is for DMA do we need to do the transition delay
or is bmdma_start guaranteed to do it ? */
switch (qc->tf.protocol) {
case ATAPI_PROT_PIO:
ap->hsm_task_state = HSM_ST;
break;
case ATAPI_PROT_NODATA:
ap->hsm_task_state = HSM_ST_LAST;
break;
#ifdef CONFIG_ATA_BMDMA
case ATAPI_PROT_DMA:
ap->hsm_task_state = HSM_ST_LAST;
/* initiate bmdma */
ap->ops->bmdma_start(qc);
break;
#endif /* CONFIG_ATA_BMDMA */
default:
BUG();
}
}
/**
* __atapi_pio_bytes - Transfer data from/to the ATAPI device.
* @qc: Command on going
* @bytes: number of bytes
*
* Transfer Transfer data from/to the ATAPI device.
*
* LOCKING:
* Inherited from caller.
*
*/
static int __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
{
int rw = (qc->tf.flags & ATA_TFLAG_WRITE) ? WRITE : READ;
struct ata_port *ap = qc->ap;
struct ata_device *dev = qc->dev;
struct ata_eh_info *ehi = &dev->link->eh_info;
struct scatterlist *sg;
struct page *page;
unsigned char *buf;
unsigned int offset, count, consumed;
next_sg:
sg = qc->cursg;
if (unlikely(!sg)) {
ata_ehi_push_desc(ehi, "unexpected or too much trailing data "
"buf=%u cur=%u bytes=%u",
qc->nbytes, qc->curbytes, bytes);
return -1;
}
page = sg_page(sg);
offset = sg->offset + qc->cursg_ofs;
/* get the current page and offset */
page = nth_page(page, (offset >> PAGE_SHIFT));
offset %= PAGE_SIZE;
/* don't overrun current sg */
count = min(sg->length - qc->cursg_ofs, bytes);
/* don't cross page boundaries */
count = min(count, (unsigned int)PAGE_SIZE - offset);
DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
if (PageHighMem(page)) {
unsigned long flags;
/* FIXME: use bounce buffer */
local_irq_save(flags);
buf = kmap_atomic(page);
/* do the actual data transfer */
consumed = ap->ops->sff_data_xfer(dev, buf + offset,
count, rw);
kunmap_atomic(buf);
local_irq_restore(flags);
} else {
buf = page_address(page);
consumed = ap->ops->sff_data_xfer(dev, buf + offset,
count, rw);
}
bytes -= min(bytes, consumed);
qc->curbytes += count;
qc->cursg_ofs += count;
if (qc->cursg_ofs == sg->length) {
qc->cursg = sg_next(qc->cursg);
qc->cursg_ofs = 0;
}
/*
* There used to be a WARN_ON_ONCE(qc->cursg && count != consumed);
* Unfortunately __atapi_pio_bytes doesn't know enough to do the WARN
* check correctly as it doesn't know if it is the last request being
* made. Somebody should implement a proper sanity check.
*/
if (bytes)
goto next_sg;
return 0;
}
/**
* atapi_pio_bytes - Transfer data from/to the ATAPI device.
* @qc: Command on going
*
* Transfer Transfer data from/to the ATAPI device.
*
* LOCKING:
* Inherited from caller.
*/
static void atapi_pio_bytes(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *dev = qc->dev;
struct ata_eh_info *ehi = &dev->link->eh_info;
unsigned int ireason, bc_lo, bc_hi, bytes;
int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
/* Abuse qc->result_tf for temp storage of intermediate TF
* here to save some kernel stack usage.
* For normal completion, qc->result_tf is not relevant. For
* error, qc->result_tf is later overwritten by ata_qc_complete().
* So, the correctness of qc->result_tf is not affected.
*/
ap->ops->sff_tf_read(ap, &qc->result_tf);
ireason = qc->result_tf.nsect;
bc_lo = qc->result_tf.lbam;
bc_hi = qc->result_tf.lbah;
bytes = (bc_hi << 8) | bc_lo;
/* shall be cleared to zero, indicating xfer of data */
if (unlikely(ireason & ATAPI_COD))
goto atapi_check;
/* make sure transfer direction matches expected */
i_write = ((ireason & ATAPI_IO) == 0) ? 1 : 0;
if (unlikely(do_write != i_write))
goto atapi_check;
if (unlikely(!bytes))
goto atapi_check;
VPRINTK("ata%u: xfering %d bytes\n", ap->print_id, bytes);
if (unlikely(__atapi_pio_bytes(qc, bytes)))
goto err_out;
ata_sff_sync(ap); /* flush */
return;
atapi_check:
ata_ehi_push_desc(ehi, "ATAPI check failed (ireason=0x%x bytes=%u)",
ireason, bytes);
err_out:
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
}
/**
* ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
* @ap: the target ata_port
* @qc: qc on going
*
* RETURNS:
* 1 if ok in workqueue, 0 otherwise.
*/
static inline int ata_hsm_ok_in_wq(struct ata_port *ap,
struct ata_queued_cmd *qc)
{
if (qc->tf.flags & ATA_TFLAG_POLLING)
return 1;
if (ap->hsm_task_state == HSM_ST_FIRST) {
if (qc->tf.protocol == ATA_PROT_PIO &&
(qc->tf.flags & ATA_TFLAG_WRITE))
return 1;
if (ata_is_atapi(qc->tf.protocol) &&
!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
return 1;
}
return 0;
}
/**
* ata_hsm_qc_complete - finish a qc running on standard HSM
* @qc: Command to complete
* @in_wq: 1 if called from workqueue, 0 otherwise
*
* Finish @qc which is running on standard HSM.
*
* LOCKING:
* If @in_wq is zero, spin_lock_irqsave(host lock).
* Otherwise, none on entry and grabs host lock.
*/
static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
{
struct ata_port *ap = qc->ap;
unsigned long flags;
if (ap->ops->error_handler) {
if (in_wq) {
spin_lock_irqsave(ap->lock, flags);
/* EH might have kicked in while host lock is
* released.
*/
qc = ata_qc_from_tag(ap, qc->tag);
if (qc) {
if (likely(!(qc->err_mask & AC_ERR_HSM))) {
ata_sff_irq_on(ap);
ata_qc_complete(qc);
} else
ata_port_freeze(ap);
}
spin_unlock_irqrestore(ap->lock, flags);
} else {
if (likely(!(qc->err_mask & AC_ERR_HSM)))
ata_qc_complete(qc);
else
ata_port_freeze(ap);
}
} else {
if (in_wq) {
spin_lock_irqsave(ap->lock, flags);
ata_sff_irq_on(ap);
ata_qc_complete(qc);
spin_unlock_irqrestore(ap->lock, flags);
} else
ata_qc_complete(qc);
}
}
/**
* ata_sff_hsm_move - move the HSM to the next state.
* @ap: the target ata_port
* @qc: qc on going
* @status: current device status
* @in_wq: 1 if called from workqueue, 0 otherwise
*
* RETURNS:
* 1 when poll next status needed, 0 otherwise.
*/
int ata_sff_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
u8 status, int in_wq)
{
struct ata_link *link = qc->dev->link;
struct ata_eh_info *ehi = &link->eh_info;
unsigned long flags = 0;
int poll_next;
WARN_ON_ONCE((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
/* Make sure ata_sff_qc_issue() does not throw things
* like DMA polling into the workqueue. Notice that
* in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
*/
WARN_ON_ONCE(in_wq != ata_hsm_ok_in_wq(ap, qc));
fsm_start:
DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
ap->print_id, qc->tf.protocol, ap->hsm_task_state, status);
switch (ap->hsm_task_state) {
case HSM_ST_FIRST:
/* Send first data block or PACKET CDB */
/* If polling, we will stay in the work queue after
* sending the data. Otherwise, interrupt handler
* takes over after sending the data.
*/
poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
/* check device status */
if (unlikely((status & ATA_DRQ) == 0)) {
/* handle BSY=0, DRQ=0 as error */
if (likely(status & (ATA_ERR | ATA_DF)))
/* device stops HSM for abort/error */
qc->err_mask |= AC_ERR_DEV;
else {
/* HSM violation. Let EH handle this */
ata_ehi_push_desc(ehi,
"ST_FIRST: !(DRQ|ERR|DF)");
qc->err_mask |= AC_ERR_HSM;
}
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* Device should not ask for data transfer (DRQ=1)
* when it finds something wrong.
* We ignore DRQ here and stop the HSM by
* changing hsm_task_state to HSM_ST_ERR and
* let the EH abort the command or reset the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
/* Some ATAPI tape drives forget to clear the ERR bit
* when doing the next command (mostly request sense).
* We ignore ERR here to workaround and proceed sending
* the CDB.
*/
if (!(qc->dev->horkage & ATA_HORKAGE_STUCK_ERR)) {
ata_ehi_push_desc(ehi, "ST_FIRST: "
"DRQ=1 with device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
}
/* Send the CDB (atapi) or the first data block (ata pio out).
* During the state transition, interrupt handler shouldn't
* be invoked before the data transfer is complete and
* hsm_task_state is changed. Hence, the following locking.
*/
if (in_wq)
spin_lock_irqsave(ap->lock, flags);
if (qc->tf.protocol == ATA_PROT_PIO) {
/* PIO data out protocol.
* send first data block.
*/
/* ata_pio_sectors() might change the state
* to HSM_ST_LAST. so, the state is changed here
* before ata_pio_sectors().
*/
ap->hsm_task_state = HSM_ST;
ata_pio_sectors(qc);
} else
/* send CDB */
atapi_send_cdb(ap, qc);
if (in_wq)
spin_unlock_irqrestore(ap->lock, flags);
/* if polling, ata_sff_pio_task() handles the rest.
* otherwise, interrupt handler takes over from here.
*/
break;
case HSM_ST:
/* complete command or read/write the data register */
if (qc->tf.protocol == ATAPI_PROT_PIO) {
/* ATAPI PIO protocol */
if ((status & ATA_DRQ) == 0) {
/* No more data to transfer or device error.
* Device error will be tagged in HSM_ST_LAST.
*/
ap->hsm_task_state = HSM_ST_LAST;
goto fsm_start;
}
/* Device should not ask for data transfer (DRQ=1)
* when it finds something wrong.
* We ignore DRQ here and stop the HSM by
* changing hsm_task_state to HSM_ST_ERR and
* let the EH abort the command or reset the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
ata_ehi_push_desc(ehi, "ST-ATAPI: "
"DRQ=1 with device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
atapi_pio_bytes(qc);
if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
/* bad ireason reported by device */
goto fsm_start;
} else {
/* ATA PIO protocol */
if (unlikely((status & ATA_DRQ) == 0)) {
/* handle BSY=0, DRQ=0 as error */
if (likely(status & (ATA_ERR | ATA_DF))) {
/* device stops HSM for abort/error */
qc->err_mask |= AC_ERR_DEV;
/* If diagnostic failed and this is
* IDENTIFY, it's likely a phantom
* device. Mark hint.
*/
if (qc->dev->horkage &
ATA_HORKAGE_DIAGNOSTIC)
qc->err_mask |=
AC_ERR_NODEV_HINT;
} else {
/* HSM violation. Let EH handle this.
* Phantom devices also trigger this
* condition. Mark hint.
*/
ata_ehi_push_desc(ehi, "ST-ATA: "
"DRQ=0 without device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM |
AC_ERR_NODEV_HINT;
}
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* For PIO reads, some devices may ask for
* data transfer (DRQ=1) alone with ERR=1.
* We respect DRQ here and transfer one
* block of junk data before changing the
* hsm_task_state to HSM_ST_ERR.
*
* For PIO writes, ERR=1 DRQ=1 doesn't make
* sense since the data block has been
* transferred to the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
/* data might be corrputed */
qc->err_mask |= AC_ERR_DEV;
if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
ata_pio_sectors(qc);
status = ata_wait_idle(ap);
}
if (status & (ATA_BUSY | ATA_DRQ)) {
ata_ehi_push_desc(ehi, "ST-ATA: "
"BUSY|DRQ persists on ERR|DF, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
}
/* There are oddball controllers with
* status register stuck at 0x7f and
* lbal/m/h at zero which makes it
* pass all other presence detection
* mechanisms we have. Set NODEV_HINT
* for it. Kernel bz#7241.
*/
if (status == 0x7f)
qc->err_mask |= AC_ERR_NODEV_HINT;
/* ata_pio_sectors() might change the
* state to HSM_ST_LAST. so, the state
* is changed after ata_pio_sectors().
*/
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
ata_pio_sectors(qc);
if (ap->hsm_task_state == HSM_ST_LAST &&
(!(qc->tf.flags & ATA_TFLAG_WRITE))) {
/* all data read */
status = ata_wait_idle(ap);
goto fsm_start;
}
}
poll_next = 1;
break;
case HSM_ST_LAST:
if (unlikely(!ata_ok(status))) {
qc->err_mask |= __ac_err_mask(status);
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* no more data to transfer */
DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
ap->print_id, qc->dev->devno, status);
WARN_ON_ONCE(qc->err_mask & (AC_ERR_DEV | AC_ERR_HSM));
ap->hsm_task_state = HSM_ST_IDLE;
/* complete taskfile transaction */
ata_hsm_qc_complete(qc, in_wq);
poll_next = 0;
break;
case HSM_ST_ERR:
ap->hsm_task_state = HSM_ST_IDLE;
/* complete taskfile transaction */
ata_hsm_qc_complete(qc, in_wq);
poll_next = 0;
break;
default:
poll_next = 0;
BUG();
}
return poll_next;
}
EXPORT_SYMBOL_GPL(ata_sff_hsm_move);
void ata_sff_queue_work(struct work_struct *work)
{
queue_work(ata_sff_wq, work);
}
EXPORT_SYMBOL_GPL(ata_sff_queue_work);
void ata_sff_queue_delayed_work(struct delayed_work *dwork, unsigned long delay)
{
queue_delayed_work(ata_sff_wq, dwork, delay);
}
EXPORT_SYMBOL_GPL(ata_sff_queue_delayed_work);
void ata_sff_queue_pio_task(struct ata_link *link, unsigned long delay)
{
struct ata_port *ap = link->ap;
WARN_ON((ap->sff_pio_task_link != NULL) &&
(ap->sff_pio_task_link != link));
ap->sff_pio_task_link = link;
/* may fail if ata_sff_flush_pio_task() in progress */
ata_sff_queue_delayed_work(&ap->sff_pio_task, msecs_to_jiffies(delay));
}
EXPORT_SYMBOL_GPL(ata_sff_queue_pio_task);
void ata_sff_flush_pio_task(struct ata_port *ap)
{
DPRINTK("ENTER\n");
cancel_delayed_work_sync(&ap->sff_pio_task);
ap->hsm_task_state = HSM_ST_IDLE;
ap->sff_pio_task_link = NULL;
if (ata_msg_ctl(ap))
ata_port_dbg(ap, "%s: EXIT\n", __func__);
}
static void ata_sff_pio_task(struct work_struct *work)
{
struct ata_port *ap =
container_of(work, struct ata_port, sff_pio_task.work);
struct ata_link *link = ap->sff_pio_task_link;
struct ata_queued_cmd *qc;
u8 status;
int poll_next;
BUG_ON(ap->sff_pio_task_link == NULL);
/* qc can be NULL if timeout occurred */
qc = ata_qc_from_tag(ap, link->active_tag);
if (!qc) {
ap->sff_pio_task_link = NULL;
return;
}
fsm_start:
WARN_ON_ONCE(ap->hsm_task_state == HSM_ST_IDLE);
/*
* This is purely heuristic. This is a fast path.
* Sometimes when we enter, BSY will be cleared in
* a chk-status or two. If not, the drive is probably seeking
* or something. Snooze for a couple msecs, then
* chk-status again. If still busy, queue delayed work.
*/
status = ata_sff_busy_wait(ap, ATA_BUSY, 5);
if (status & ATA_BUSY) {
ata_msleep(ap, 2);
status = ata_sff_busy_wait(ap, ATA_BUSY, 10);
if (status & ATA_BUSY) {
ata_sff_queue_pio_task(link, ATA_SHORT_PAUSE);
return;
}
}
/*
* hsm_move() may trigger another command to be processed.
* clean the link beforehand.
*/
ap->sff_pio_task_link = NULL;
/* move the HSM */
poll_next = ata_sff_hsm_move(ap, qc, status, 1);
/* another command or interrupt handler
* may be running at this point.
*/
if (poll_next)
goto fsm_start;
}
/**
* ata_sff_qc_issue - issue taskfile to a SFF controller
* @qc: command to issue to device
*
* This function issues a PIO or NODATA command to a SFF
* controller.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, AC_ERR_* mask on failure
*/
unsigned int ata_sff_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_link *link = qc->dev->link;
/* Use polling pio if the LLD doesn't handle
* interrupt driven pio and atapi CDB interrupt.
*/
if (ap->flags & ATA_FLAG_PIO_POLLING)
qc->tf.flags |= ATA_TFLAG_POLLING;
/* select the device */
ata_dev_select(ap, qc->dev->devno, 1, 0);
/* start the command */
switch (qc->tf.protocol) {
case ATA_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
ap->hsm_task_state = HSM_ST_LAST;
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_sff_queue_pio_task(link, 0);
break;
case ATA_PROT_PIO:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
if (qc->tf.flags & ATA_TFLAG_WRITE) {
/* PIO data out protocol */
ap->hsm_task_state = HSM_ST_FIRST;
ata_sff_queue_pio_task(link, 0);
/* always send first data block using the
* ata_sff_pio_task() codepath.
*/
} else {
/* PIO data in protocol */
ap->hsm_task_state = HSM_ST;
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_sff_queue_pio_task(link, 0);
/* if polling, ata_sff_pio_task() handles the
* rest. otherwise, interrupt handler takes
* over from here.
*/
}
break;
case ATAPI_PROT_PIO:
case ATAPI_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
ap->hsm_task_state = HSM_ST_FIRST;
/* send cdb by polling if no cdb interrupt */
if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
(qc->tf.flags & ATA_TFLAG_POLLING))
ata_sff_queue_pio_task(link, 0);
break;
default:
WARN_ON_ONCE(1);
return AC_ERR_SYSTEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_qc_issue);
/**
* ata_sff_qc_fill_rtf - fill result TF using ->sff_tf_read
* @qc: qc to fill result TF for
*
* @qc is finished and result TF needs to be filled. Fill it
* using ->sff_tf_read.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* true indicating that result TF is successfully filled.
*/
bool ata_sff_qc_fill_rtf(struct ata_queued_cmd *qc)
{
qc->ap->ops->sff_tf_read(qc->ap, &qc->result_tf);
return true;
}
EXPORT_SYMBOL_GPL(ata_sff_qc_fill_rtf);
static unsigned int ata_sff_idle_irq(struct ata_port *ap)
{
ap->stats.idle_irq++;
#ifdef ATA_IRQ_TRAP
if ((ap->stats.idle_irq % 1000) == 0) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_port_warn(ap, "irq trap\n");
return 1;
}
#endif
return 0; /* irq not handled */
}
static unsigned int __ata_sff_port_intr(struct ata_port *ap,
struct ata_queued_cmd *qc,
bool hsmv_on_idle)
{
u8 status;
VPRINTK("ata%u: protocol %d task_state %d\n",
ap->print_id, qc->tf.protocol, ap->hsm_task_state);
/* Check whether we are expecting interrupt in this state */
switch (ap->hsm_task_state) {
case HSM_ST_FIRST:
/* Some pre-ATAPI-4 devices assert INTRQ
* at this state when ready to receive CDB.
*/
/* Check the ATA_DFLAG_CDB_INTR flag is enough here.
* The flag was turned on only for atapi devices. No
* need to check ata_is_atapi(qc->tf.protocol) again.
*/
if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
return ata_sff_idle_irq(ap);
break;
case HSM_ST_IDLE:
return ata_sff_idle_irq(ap);
default:
break;
}
/* check main status, clearing INTRQ if needed */
status = ata_sff_irq_status(ap);
if (status & ATA_BUSY) {
if (hsmv_on_idle) {
/* BMDMA engine is already stopped, we're screwed */
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
} else
return ata_sff_idle_irq(ap);
}
/* clear irq events */
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_sff_hsm_move(ap, qc, status, 0);
return 1; /* irq handled */
}
/**
* ata_sff_port_intr - Handle SFF port interrupt
* @ap: Port on which interrupt arrived (possibly...)
* @qc: Taskfile currently active in engine
*
* Handle port interrupt for given queued command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* One if interrupt was handled, zero if not (shared irq).
*/
unsigned int ata_sff_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
{
return __ata_sff_port_intr(ap, qc, false);
}
EXPORT_SYMBOL_GPL(ata_sff_port_intr);
static inline irqreturn_t __ata_sff_interrupt(int irq, void *dev_instance,
unsigned int (*port_intr)(struct ata_port *, struct ata_queued_cmd *))
{
struct ata_host *host = dev_instance;
bool retried = false;
unsigned int i;
unsigned int handled, idle, polling;
unsigned long flags;
/* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
spin_lock_irqsave(&host->lock, flags);
retry:
handled = idle = polling = 0;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc) {
if (!(qc->tf.flags & ATA_TFLAG_POLLING))
handled |= port_intr(ap, qc);
else
polling |= 1 << i;
} else
idle |= 1 << i;
}
/*
* If no port was expecting IRQ but the controller is actually
* asserting IRQ line, nobody cared will ensue. Check IRQ
* pending status if available and clear spurious IRQ.
*/
if (!handled && !retried) {
bool retry = false;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
if (polling & (1 << i))
continue;
if (!ap->ops->sff_irq_check ||
!ap->ops->sff_irq_check(ap))
continue;
if (idle & (1 << i)) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
} else {
/* clear INTRQ and check if BUSY cleared */
if (!(ap->ops->sff_check_status(ap) & ATA_BUSY))
retry |= true;
/*
* With command in flight, we can't do
* sff_irq_clear() w/o racing with completion.
*/
}
}
if (retry) {
retried = true;
goto retry;
}
}
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_RETVAL(handled);
}
/**
* ata_sff_interrupt - Default SFF ATA host interrupt handler
* @irq: irq line (unused)
* @dev_instance: pointer to our ata_host information structure
*
* Default interrupt handler for PCI IDE devices. Calls
* ata_sff_port_intr() for each port that is not disabled.
*
* LOCKING:
* Obtains host lock during operation.
*
* RETURNS:
* IRQ_NONE or IRQ_HANDLED.
*/
irqreturn_t ata_sff_interrupt(int irq, void *dev_instance)
{
return __ata_sff_interrupt(irq, dev_instance, ata_sff_port_intr);
}
EXPORT_SYMBOL_GPL(ata_sff_interrupt);
/**
* ata_sff_lost_interrupt - Check for an apparent lost interrupt
* @ap: port that appears to have timed out
*
* Called from the libata error handlers when the core code suspects
* an interrupt has been lost. If it has complete anything we can and
* then return. Interface must support altstatus for this faster
* recovery to occur.
*
* Locking:
* Caller holds host lock
*/
void ata_sff_lost_interrupt(struct ata_port *ap)
{
u8 status;
struct ata_queued_cmd *qc;
/* Only one outstanding command per SFF channel */
qc = ata_qc_from_tag(ap, ap->link.active_tag);
/* We cannot lose an interrupt on a non-existent or polled command */
if (!qc || qc->tf.flags & ATA_TFLAG_POLLING)
return;
/* See if the controller thinks it is still busy - if so the command
isn't a lost IRQ but is still in progress */
status = ata_sff_altstatus(ap);
if (status & ATA_BUSY)
return;
/* There was a command running, we are no longer busy and we have
no interrupt. */
ata_port_warn(ap, "lost interrupt (Status 0x%x)\n",
status);
/* Run the host interrupt logic as if the interrupt had not been
lost */
ata_sff_port_intr(ap, qc);
}
EXPORT_SYMBOL_GPL(ata_sff_lost_interrupt);
/**
* ata_sff_freeze - Freeze SFF controller port
* @ap: port to freeze
*
* Freeze SFF controller port.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_freeze(struct ata_port *ap)
{
ap->ctl |= ATA_NIEN;
ap->last_ctl = ap->ctl;
if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr)
ata_sff_set_devctl(ap, ap->ctl);
/* Under certain circumstances, some controllers raise IRQ on
* ATA_NIEN manipulation. Also, many controllers fail to mask
* previously pending IRQ on ATA_NIEN assertion. Clear it.
*/
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_freeze);
/**
* ata_sff_thaw - Thaw SFF controller port
* @ap: port to thaw
*
* Thaw SFF controller port.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_thaw(struct ata_port *ap)
{
/* clear & re-enable interrupts */
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_sff_irq_on(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_thaw);
/**
* ata_sff_prereset - prepare SFF link for reset
* @link: SFF link to be reset
* @deadline: deadline jiffies for the operation
*
* SFF link @link is about to be reset. Initialize it. It first
* calls ata_std_prereset() and wait for !BSY if the port is
* being softreset.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_prereset(struct ata_link *link, unsigned long deadline)
{
struct ata_eh_context *ehc = &link->eh_context;
int rc;
rc = ata_std_prereset(link, deadline);
if (rc)
return rc;
/* if we're about to do hardreset, nothing more to do */
if (ehc->i.action & ATA_EH_HARDRESET)
return 0;
/* wait for !BSY if we don't know that no device is attached */
if (!ata_link_offline(link)) {
rc = ata_sff_wait_ready(link, deadline);
if (rc && rc != -ENODEV) {
ata_link_warn(link,
"device not ready (errno=%d), forcing hardreset\n",
rc);
ehc->i.action |= ATA_EH_HARDRESET;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_prereset);
/**
* ata_devchk - PATA device presence detection
* @ap: ATA channel to examine
* @device: Device to examine (starting at zero)
*
* This technique was originally described in
* Hale Landis's ATADRVR (www.ata-atapi.com), and
* later found its way into the ATA/ATAPI spec.
*
* Write a pattern to the ATA shadow registers,
* and if a device is present, it will respond by
* correctly storing and echoing back the
* ATA shadow register contents.
*
* LOCKING:
* caller.
*/
static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u8 nsect, lbal;
ap->ops->sff_dev_select(ap, device);
iowrite8(0x55, ioaddr->nsect_addr);
iowrite8(0xaa, ioaddr->lbal_addr);
iowrite8(0xaa, ioaddr->nsect_addr);
iowrite8(0x55, ioaddr->lbal_addr);
iowrite8(0x55, ioaddr->nsect_addr);
iowrite8(0xaa, ioaddr->lbal_addr);
nsect = ioread8(ioaddr->nsect_addr);
lbal = ioread8(ioaddr->lbal_addr);
if ((nsect == 0x55) && (lbal == 0xaa))
return 1; /* we found a device */
return 0; /* nothing found */
}
/**
* ata_sff_dev_classify - Parse returned ATA device signature
* @dev: ATA device to classify (starting at zero)
* @present: device seems present
* @r_err: Value of error register on completion
*
* After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
* an ATA/ATAPI-defined set of values is placed in the ATA
* shadow registers, indicating the results of device detection
* and diagnostics.
*
* Select the ATA device, and read the values from the ATA shadow
* registers. Then parse according to the Error register value,
* and the spec-defined values examined by ata_dev_classify().
*
* LOCKING:
* caller.
*
* RETURNS:
* Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
*/
unsigned int ata_sff_dev_classify(struct ata_device *dev, int present,
u8 *r_err)
{
struct ata_port *ap = dev->link->ap;
struct ata_taskfile tf;
unsigned int class;
u8 err;
ap->ops->sff_dev_select(ap, dev->devno);
memset(&tf, 0, sizeof(tf));
ap->ops->sff_tf_read(ap, &tf);
err = tf.feature;
if (r_err)
*r_err = err;
/* see if device passed diags: continue and warn later */
if (err == 0)
/* diagnostic fail : do nothing _YET_ */
dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
else if (err == 1)
/* do nothing */ ;
else if ((dev->devno == 0) && (err == 0x81))
/* do nothing */ ;
else
return ATA_DEV_NONE;
/* determine if device is ATA or ATAPI */
class = ata_dev_classify(&tf);
if (class == ATA_DEV_UNKNOWN) {
/* If the device failed diagnostic, it's likely to
* have reported incorrect device signature too.
* Assume ATA device if the device seems present but
* device signature is invalid with diagnostic
* failure.
*/
if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
class = ATA_DEV_ATA;
else
class = ATA_DEV_NONE;
} else if ((class == ATA_DEV_ATA) &&
(ap->ops->sff_check_status(ap) == 0))
class = ATA_DEV_NONE;
return class;
}
EXPORT_SYMBOL_GPL(ata_sff_dev_classify);
/**
* ata_sff_wait_after_reset - wait for devices to become ready after reset
* @link: SFF link which is just reset
* @devmask: mask of present devices
* @deadline: deadline jiffies for the operation
*
* Wait devices attached to SFF @link to become ready after
* reset. It contains preceding 150ms wait to avoid accessing TF
* status register too early.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -ENODEV if some or all of devices in @devmask
* don't seem to exist. -errno on other errors.
*/
int ata_sff_wait_after_reset(struct ata_link *link, unsigned int devmask,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int dev0 = devmask & (1 << 0);
unsigned int dev1 = devmask & (1 << 1);
int rc, ret = 0;
ata_msleep(ap, ATA_WAIT_AFTER_RESET);
/* always check readiness of the master device */
rc = ata_sff_wait_ready(link, deadline);
/* -ENODEV means the odd clown forgot the D7 pulldown resistor
* and TF status is 0xff, bail out on it too.
*/
if (rc)
return rc;
/* if device 1 was found in ata_devchk, wait for register
* access briefly, then wait for BSY to clear.
*/
if (dev1) {
int i;
ap->ops->sff_dev_select(ap, 1);
/* Wait for register access. Some ATAPI devices fail
* to set nsect/lbal after reset, so don't waste too
* much time on it. We're gonna wait for !BSY anyway.
*/
for (i = 0; i < 2; i++) {
u8 nsect, lbal;
nsect = ioread8(ioaddr->nsect_addr);
lbal = ioread8(ioaddr->lbal_addr);
if ((nsect == 1) && (lbal == 1))
break;
ata_msleep(ap, 50); /* give drive a breather */
}
rc = ata_sff_wait_ready(link, deadline);
if (rc) {
if (rc != -ENODEV)
return rc;
ret = rc;
}
}
/* is all this really necessary? */
ap->ops->sff_dev_select(ap, 0);
if (dev1)
ap->ops->sff_dev_select(ap, 1);
if (dev0)
ap->ops->sff_dev_select(ap, 0);
return ret;
}
EXPORT_SYMBOL_GPL(ata_sff_wait_after_reset);
static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
unsigned long deadline)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
/* software reset. causes dev0 to be selected */
iowrite8(ap->ctl, ioaddr->ctl_addr);
udelay(20); /* FIXME: flush */
iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
udelay(20); /* FIXME: flush */
iowrite8(ap->ctl, ioaddr->ctl_addr);
ap->last_ctl = ap->ctl;
/* wait the port to become ready */
return ata_sff_wait_after_reset(&ap->link, devmask, deadline);
}
/**
* ata_sff_softreset - reset host port via ATA SRST
* @link: ATA link to reset
* @classes: resulting classes of attached devices
* @deadline: deadline jiffies for the operation
*
* Reset host port using ATA SRST.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_softreset(struct ata_link *link, unsigned int *classes,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
unsigned int devmask = 0;
int rc;
u8 err;
DPRINTK("ENTER\n");
/* determine if device 0/1 are present */
if (ata_devchk(ap, 0))
devmask |= (1 << 0);
if (slave_possible && ata_devchk(ap, 1))
devmask |= (1 << 1);
/* select device 0 again */
ap->ops->sff_dev_select(ap, 0);
/* issue bus reset */
DPRINTK("about to softreset, devmask=%x\n", devmask);
rc = ata_bus_softreset(ap, devmask, deadline);
/* if link is occupied, -ENODEV too is an error */
if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
ata_link_err(link, "SRST failed (errno=%d)\n", rc);
return rc;
}
/* determine by signature whether we have ATA or ATAPI devices */
classes[0] = ata_sff_dev_classify(&link->device[0],
devmask & (1 << 0), &err);
if (slave_possible && err != 0x81)
classes[1] = ata_sff_dev_classify(&link->device[1],
devmask & (1 << 1), &err);
DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_softreset);
/**
* sata_sff_hardreset - reset host port via SATA phy reset
* @link: link to reset
* @class: resulting class of attached device
* @deadline: deadline jiffies for the operation
*
* SATA phy-reset host port using DET bits of SControl register,
* wait for !BSY and classify the attached device.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int sata_sff_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_eh_context *ehc = &link->eh_context;
const unsigned long *timing = sata_ehc_deb_timing(ehc);
bool online;
int rc;
rc = sata_link_hardreset(link, timing, deadline, &online,
ata_sff_check_ready);
if (online)
*class = ata_sff_dev_classify(link->device, 1, NULL);
DPRINTK("EXIT, class=%u\n", *class);
return rc;
}
EXPORT_SYMBOL_GPL(sata_sff_hardreset);
/**
* ata_sff_postreset - SFF postreset callback
* @link: the target SFF ata_link
* @classes: classes of attached devices
*
* This function is invoked after a successful reset. It first
* calls ata_std_postreset() and performs SFF specific postreset
* processing.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_sff_postreset(struct ata_link *link, unsigned int *classes)
{
struct ata_port *ap = link->ap;
ata_std_postreset(link, classes);
/* is double-select really necessary? */
if (classes[0] != ATA_DEV_NONE)
ap->ops->sff_dev_select(ap, 1);
if (classes[1] != ATA_DEV_NONE)
ap->ops->sff_dev_select(ap, 0);
/* bail out if no device is present */
if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
DPRINTK("EXIT, no device\n");
return;
}
/* set up device control */
if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr) {
ata_sff_set_devctl(ap, ap->ctl);
ap->last_ctl = ap->ctl;
}
}
EXPORT_SYMBOL_GPL(ata_sff_postreset);
/**
* ata_sff_drain_fifo - Stock FIFO drain logic for SFF controllers
* @qc: command
*
* Drain the FIFO and device of any stuck data following a command
* failing to complete. In some cases this is necessary before a
* reset will recover the device.
*
*/
void ata_sff_drain_fifo(struct ata_queued_cmd *qc)
{
int count;
struct ata_port *ap;
/* We only need to flush incoming data when a command was running */
if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE)
return;
ap = qc->ap;
/* Drain up to 64K of data before we give up this recovery method */
for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ)
&& count < 65536; count += 2)
ioread16(ap->ioaddr.data_addr);
/* Can become DEBUG later */
if (count)
ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count);
}
EXPORT_SYMBOL_GPL(ata_sff_drain_fifo);
/**
* ata_sff_error_handler - Stock error handler for SFF controller
* @ap: port to handle error for
*
* Stock error handler for SFF controller. It can handle both
* PATA and SATA controllers. Many controllers should be able to
* use this EH as-is or with some added handling before and
* after.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_sff_error_handler(struct ata_port *ap)
{
ata_reset_fn_t softreset = ap->ops->softreset;
ata_reset_fn_t hardreset = ap->ops->hardreset;
struct ata_queued_cmd *qc;
unsigned long flags;
qc = __ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
qc = NULL;
spin_lock_irqsave(ap->lock, flags);
/*
* We *MUST* do FIFO draining before we issue a reset as
* several devices helpfully clear their internal state and
* will lock solid if we touch the data port post reset. Pass
* qc in case anyone wants to do different PIO/DMA recovery or
* has per command fixups
*/
if (ap->ops->sff_drain_fifo)
ap->ops->sff_drain_fifo(qc);
spin_unlock_irqrestore(ap->lock, flags);
/* ignore ata_sff_softreset if ctl isn't accessible */
if (softreset == ata_sff_softreset && !ap->ioaddr.ctl_addr)
softreset = NULL;
/* ignore built-in hardresets if SCR access is not available */
if ((hardreset == sata_std_hardreset ||
hardreset == sata_sff_hardreset) && !sata_scr_valid(&ap->link))
hardreset = NULL;
ata_do_eh(ap, ap->ops->prereset, softreset, hardreset,
ap->ops->postreset);
}
EXPORT_SYMBOL_GPL(ata_sff_error_handler);
/**
* ata_sff_std_ports - initialize ioaddr with standard port offsets.
* @ioaddr: IO address structure to be initialized
*
* Utility function which initializes data_addr, error_addr,
* feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
* device_addr, status_addr, and command_addr to standard offsets
* relative to cmd_addr.
*
* Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
*/
void ata_sff_std_ports(struct ata_ioports *ioaddr)
{
ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
}
EXPORT_SYMBOL_GPL(ata_sff_std_ports);
#ifdef CONFIG_PCI
static int ata_resources_present(struct pci_dev *pdev, int port)
{
int i;
/* Check the PCI resources for this channel are enabled */
port = port * 2;
for (i = 0; i < 2; i++) {
if (pci_resource_start(pdev, port + i) == 0 ||
pci_resource_len(pdev, port + i) == 0)
return 0;
}
return 1;
}
/**
* ata_pci_sff_init_host - acquire native PCI ATA resources and init host
* @host: target ATA host
*
* Acquire native PCI ATA resources for @host and initialize the
* first two ports of @host accordingly. Ports marked dummy are
* skipped and allocation failure makes the port dummy.
*
* Note that native PCI resources are valid even for legacy hosts
* as we fix up pdev resources array early in boot, so this
* function can be used for both native and legacy SFF hosts.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 if at least one port is initialized, -ENODEV if no port is
* available.
*/
int ata_pci_sff_init_host(struct ata_host *host)
{
struct device *gdev = host->dev;
struct pci_dev *pdev = to_pci_dev(gdev);
unsigned int mask = 0;
int i, rc;
/* request, iomap BARs and init port addresses accordingly */
for (i = 0; i < 2; i++) {
struct ata_port *ap = host->ports[i];
int base = i * 2;
void __iomem * const *iomap;
if (ata_port_is_dummy(ap))
continue;
/* Discard disabled ports. Some controllers show
* their unused channels this way. Disabled ports are
* made dummy.
*/
if (!ata_resources_present(pdev, i)) {
ap->ops = &ata_dummy_port_ops;
continue;
}
rc = pcim_iomap_regions(pdev, 0x3 << base,
dev_driver_string(gdev));
if (rc) {
dev_warn(gdev,
"failed to request/iomap BARs for port %d (errno=%d)\n",
i, rc);
if (rc == -EBUSY)
pcim_pin_device(pdev);
ap->ops = &ata_dummy_port_ops;
continue;
}
host->iomap = iomap = pcim_iomap_table(pdev);
ap->ioaddr.cmd_addr = iomap[base];
ap->ioaddr.altstatus_addr =
ap->ioaddr.ctl_addr = (void __iomem *)
((unsigned long)iomap[base + 1] | ATA_PCI_CTL_OFS);
ata_sff_std_ports(&ap->ioaddr);
ata_port_desc(ap, "cmd 0x%llx ctl 0x%llx",
(unsigned long long)pci_resource_start(pdev, base),
(unsigned long long)pci_resource_start(pdev, base + 1));
mask |= 1 << i;
}
if (!mask) {
dev_err(gdev, "no available native port\n");
return -ENODEV;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_init_host);
/**
* ata_pci_sff_prepare_host - helper to prepare PCI PIO-only SFF ATA host
* @pdev: target PCI device
* @ppi: array of port_info, must be enough for two ports
* @r_host: out argument for the initialized ATA host
*
* Helper to allocate PIO-only SFF ATA host for @pdev, acquire
* all PCI resources and initialize it accordingly in one go.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_sff_prepare_host(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct ata_host **r_host)
{
struct ata_host *host;
int rc;
if (!devres_open_group(&pdev->dev, NULL, GFP_KERNEL))
return -ENOMEM;
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2);
if (!host) {
dev_err(&pdev->dev, "failed to allocate ATA host\n");
rc = -ENOMEM;
goto err_out;
}
rc = ata_pci_sff_init_host(host);
if (rc)
goto err_out;
devres_remove_group(&pdev->dev, NULL);
*r_host = host;
return 0;
err_out:
devres_release_group(&pdev->dev, NULL);
return rc;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_prepare_host);
/**
* ata_pci_sff_activate_host - start SFF host, request IRQ and register it
* @host: target SFF ATA host
* @irq_handler: irq_handler used when requesting IRQ(s)
* @sht: scsi_host_template to use when registering the host
*
* This is the counterpart of ata_host_activate() for SFF ATA
* hosts. This separate helper is necessary because SFF hosts
* use two separate interrupts in legacy mode.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_sff_activate_host(struct ata_host *host,
irq_handler_t irq_handler,
struct scsi_host_template *sht)
{
struct device *dev = host->dev;
struct pci_dev *pdev = to_pci_dev(dev);
const char *drv_name = dev_driver_string(host->dev);
int legacy_mode = 0, rc;
rc = ata_host_start(host);
if (rc)
return rc;
if ((pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
u8 tmp8, mask;
/* TODO: What if one channel is in native mode ... */
pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
mask = (1 << 2) | (1 << 0);
if ((tmp8 & mask) != mask)
legacy_mode = 1;
#if defined(CONFIG_NO_ATA_LEGACY)
/* Some platforms with PCI limits cannot address compat
port space. In that case we punt if their firmware has
left a device in compatibility mode */
if (legacy_mode) {
printk(KERN_ERR "ata: Compatibility mode ATA is not supported on this platform, skipping.\n");
return -EOPNOTSUPP;
}
#endif
}
if (!devres_open_group(dev, NULL, GFP_KERNEL))
return -ENOMEM;
if (!legacy_mode && pdev->irq) {
int i;
rc = devm_request_irq(dev, pdev->irq, irq_handler,
IRQF_SHARED, drv_name, host);
if (rc)
goto out;
for (i = 0; i < 2; i++) {
if (ata_port_is_dummy(host->ports[i]))
continue;
ata_port_desc(host->ports[i], "irq %d", pdev->irq);
}
} else if (legacy_mode) {
if (!ata_port_is_dummy(host->ports[0])) {
rc = devm_request_irq(dev, ATA_PRIMARY_IRQ(pdev),
irq_handler, IRQF_SHARED,
drv_name, host);
if (rc)
goto out;
ata_port_desc(host->ports[0], "irq %d",
ATA_PRIMARY_IRQ(pdev));
}
if (!ata_port_is_dummy(host->ports[1])) {
rc = devm_request_irq(dev, ATA_SECONDARY_IRQ(pdev),
irq_handler, IRQF_SHARED,
drv_name, host);
if (rc)
goto out;
ata_port_desc(host->ports[1], "irq %d",
ATA_SECONDARY_IRQ(pdev));
}
}
rc = ata_host_register(host, sht);
out:
if (rc == 0)
devres_remove_group(dev, NULL);
else
devres_release_group(dev, NULL);
return rc;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_activate_host);
static const struct ata_port_info *ata_sff_find_valid_pi(
const struct ata_port_info * const *ppi)
{
int i;
/* look up the first valid port_info */
for (i = 0; i < 2 && ppi[i]; i++)
if (ppi[i]->port_ops != &ata_dummy_port_ops)
return ppi[i];
return NULL;
}
static int ata_pci_init_one(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct scsi_host_template *sht, void *host_priv,
int hflags, bool bmdma)
{
struct device *dev = &pdev->dev;
const struct ata_port_info *pi;
struct ata_host *host = NULL;
int rc;
DPRINTK("ENTER\n");
pi = ata_sff_find_valid_pi(ppi);
if (!pi) {
dev_err(&pdev->dev, "no valid port_info specified\n");
return -EINVAL;
}
if (!devres_open_group(dev, NULL, GFP_KERNEL))
return -ENOMEM;
rc = pcim_enable_device(pdev);
if (rc)
goto out;
#ifdef CONFIG_ATA_BMDMA
if (bmdma)
/* prepare and activate BMDMA host */
rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host);
else
#endif
/* prepare and activate SFF host */
rc = ata_pci_sff_prepare_host(pdev, ppi, &host);
if (rc)
goto out;
host->private_data = host_priv;
host->flags |= hflags;
#ifdef CONFIG_ATA_BMDMA
if (bmdma) {
pci_set_master(pdev);
rc = ata_pci_sff_activate_host(host, ata_bmdma_interrupt, sht);
} else
#endif
rc = ata_pci_sff_activate_host(host, ata_sff_interrupt, sht);
out:
if (rc == 0)
devres_remove_group(&pdev->dev, NULL);
else
devres_release_group(&pdev->dev, NULL);
return rc;
}
/**
* ata_pci_sff_init_one - Initialize/register PIO-only PCI IDE controller
* @pdev: Controller to be initialized
* @ppi: array of port_info, must be enough for two ports
* @sht: scsi_host_template to use when registering the host
* @host_priv: host private_data
* @hflag: host flags
*
* This is a helper function which can be called from a driver's
* xxx_init_one() probe function if the hardware uses traditional
* IDE taskfile registers and is PIO only.
*
* ASSUMPTION:
* Nobody makes a single channel controller that appears solely as
* the secondary legacy port on PCI.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, negative on errno-based value on error.
*/
int ata_pci_sff_init_one(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct scsi_host_template *sht, void *host_priv, int hflag)
{
return ata_pci_init_one(pdev, ppi, sht, host_priv, hflag, 0);
}
EXPORT_SYMBOL_GPL(ata_pci_sff_init_one);
#endif /* CONFIG_PCI */
/*
* BMDMA support
*/
#ifdef CONFIG_ATA_BMDMA
const struct ata_port_operations ata_bmdma_port_ops = {
.inherits = &ata_sff_port_ops,
.error_handler = ata_bmdma_error_handler,
.post_internal_cmd = ata_bmdma_post_internal_cmd,
.qc_prep = ata_bmdma_qc_prep,
.qc_issue = ata_bmdma_qc_issue,
.sff_irq_clear = ata_bmdma_irq_clear,
.bmdma_setup = ata_bmdma_setup,
.bmdma_start = ata_bmdma_start,
.bmdma_stop = ata_bmdma_stop,
.bmdma_status = ata_bmdma_status,
.port_start = ata_bmdma_port_start,
};
EXPORT_SYMBOL_GPL(ata_bmdma_port_ops);
const struct ata_port_operations ata_bmdma32_port_ops = {
.inherits = &ata_bmdma_port_ops,
.sff_data_xfer = ata_sff_data_xfer32,
.port_start = ata_bmdma_port_start32,
};
EXPORT_SYMBOL_GPL(ata_bmdma32_port_ops);
/**
* ata_bmdma_fill_sg - Fill PCI IDE PRD table
* @qc: Metadata associated with taskfile to be transferred
*
* Fill PCI IDE PRD (scatter-gather) table with segments
* associated with the current disk command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
*/
static void ata_bmdma_fill_sg(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_bmdma_prd *prd = ap->bmdma_prd;
struct scatterlist *sg;
unsigned int si, pi;
pi = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u32 addr, offset;
u32 sg_len, len;
/* determine if physical DMA addr spans 64K boundary.
* Note h/w doesn't support 64-bit, so we unconditionally
* truncate dma_addr_t to u32.
*/
addr = (u32) sg_dma_address(sg);
sg_len = sg_dma_len(sg);
while (sg_len) {
offset = addr & 0xffff;
len = sg_len;
if ((offset + sg_len) > 0x10000)
len = 0x10000 - offset;
prd[pi].addr = cpu_to_le32(addr);
prd[pi].flags_len = cpu_to_le32(len & 0xffff);
VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
pi++;
sg_len -= len;
addr += len;
}
}
prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
}
/**
* ata_bmdma_fill_sg_dumb - Fill PCI IDE PRD table
* @qc: Metadata associated with taskfile to be transferred
*
* Fill PCI IDE PRD (scatter-gather) table with segments
* associated with the current disk command. Perform the fill
* so that we avoid writing any length 64K records for
* controllers that don't follow the spec.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
*/
static void ata_bmdma_fill_sg_dumb(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_bmdma_prd *prd = ap->bmdma_prd;
struct scatterlist *sg;
unsigned int si, pi;
pi = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u32 addr, offset;
u32 sg_len, len, blen;
/* determine if physical DMA addr spans 64K boundary.
* Note h/w doesn't support 64-bit, so we unconditionally
* truncate dma_addr_t to u32.
*/
addr = (u32) sg_dma_address(sg);
sg_len = sg_dma_len(sg);
while (sg_len) {
offset = addr & 0xffff;
len = sg_len;
if ((offset + sg_len) > 0x10000)
len = 0x10000 - offset;
blen = len & 0xffff;
prd[pi].addr = cpu_to_le32(addr);
if (blen == 0) {
/* Some PATA chipsets like the CS5530 can't
cope with 0x0000 meaning 64K as the spec
says */
prd[pi].flags_len = cpu_to_le32(0x8000);
blen = 0x8000;
prd[++pi].addr = cpu_to_le32(addr + 0x8000);
}
prd[pi].flags_len = cpu_to_le32(blen);
VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
pi++;
sg_len -= len;
addr += len;
}
}
prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
}
/**
* ata_bmdma_qc_prep - Prepare taskfile for submission
* @qc: Metadata associated with taskfile to be prepared
*
* Prepare ATA taskfile for submission.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_qc_prep(struct ata_queued_cmd *qc)
{
if (!(qc->flags & ATA_QCFLAG_DMAMAP))
return;
ata_bmdma_fill_sg(qc);
}
EXPORT_SYMBOL_GPL(ata_bmdma_qc_prep);
/**
* ata_bmdma_dumb_qc_prep - Prepare taskfile for submission
* @qc: Metadata associated with taskfile to be prepared
*
* Prepare ATA taskfile for submission.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_dumb_qc_prep(struct ata_queued_cmd *qc)
{
if (!(qc->flags & ATA_QCFLAG_DMAMAP))
return;
ata_bmdma_fill_sg_dumb(qc);
}
EXPORT_SYMBOL_GPL(ata_bmdma_dumb_qc_prep);
/**
* ata_bmdma_qc_issue - issue taskfile to a BMDMA controller
* @qc: command to issue to device
*
* This function issues a PIO, NODATA or DMA command to a
* SFF/BMDMA controller. PIO and NODATA are handled by
* ata_sff_qc_issue().
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, AC_ERR_* mask on failure
*/
unsigned int ata_bmdma_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_link *link = qc->dev->link;
/* defer PIO handling to sff_qc_issue */
if (!ata_is_dma(qc->tf.protocol))
return ata_sff_qc_issue(qc);
/* select the device */
ata_dev_select(ap, qc->dev->devno, 1, 0);
/* start the command */
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
ap->ops->sff_tf_load(ap, &qc->tf); /* load tf registers */
ap->ops->bmdma_setup(qc); /* set up bmdma */
ap->ops->bmdma_start(qc); /* initiate bmdma */
ap->hsm_task_state = HSM_ST_LAST;
break;
case ATAPI_PROT_DMA:
WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
ap->ops->sff_tf_load(ap, &qc->tf); /* load tf registers */
ap->ops->bmdma_setup(qc); /* set up bmdma */
ap->hsm_task_state = HSM_ST_FIRST;
/* send cdb by polling if no cdb interrupt */
if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
ata_sff_queue_pio_task(link, 0);
break;
default:
WARN_ON(1);
return AC_ERR_SYSTEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_bmdma_qc_issue);
/**
* ata_bmdma_port_intr - Handle BMDMA port interrupt
* @ap: Port on which interrupt arrived (possibly...)
* @qc: Taskfile currently active in engine
*
* Handle port interrupt for given queued command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* One if interrupt was handled, zero if not (shared irq).
*/
unsigned int ata_bmdma_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
{
struct ata_eh_info *ehi = &ap->link.eh_info;
u8 host_stat = 0;
bool bmdma_stopped = false;
unsigned int handled;
if (ap->hsm_task_state == HSM_ST_LAST && ata_is_dma(qc->tf.protocol)) {
/* check status of DMA engine */
host_stat = ap->ops->bmdma_status(ap);
VPRINTK("ata%u: host_stat 0x%X\n", ap->print_id, host_stat);
/* if it's not our irq... */
if (!(host_stat & ATA_DMA_INTR))
return ata_sff_idle_irq(ap);
/* before we do anything else, clear DMA-Start bit */
ap->ops->bmdma_stop(qc);
bmdma_stopped = true;
if (unlikely(host_stat & ATA_DMA_ERR)) {
/* error when transferring data to/from memory */
qc->err_mask |= AC_ERR_HOST_BUS;
ap->hsm_task_state = HSM_ST_ERR;
}
}
handled = __ata_sff_port_intr(ap, qc, bmdma_stopped);
if (unlikely(qc->err_mask) && ata_is_dma(qc->tf.protocol))
ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
return handled;
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_intr);
/**
* ata_bmdma_interrupt - Default BMDMA ATA host interrupt handler
* @irq: irq line (unused)
* @dev_instance: pointer to our ata_host information structure
*
* Default interrupt handler for PCI IDE devices. Calls
* ata_bmdma_port_intr() for each port that is not disabled.
*
* LOCKING:
* Obtains host lock during operation.
*
* RETURNS:
* IRQ_NONE or IRQ_HANDLED.
*/
irqreturn_t ata_bmdma_interrupt(int irq, void *dev_instance)
{
return __ata_sff_interrupt(irq, dev_instance, ata_bmdma_port_intr);
}
EXPORT_SYMBOL_GPL(ata_bmdma_interrupt);
/**
* ata_bmdma_error_handler - Stock error handler for BMDMA controller
* @ap: port to handle error for
*
* Stock error handler for BMDMA controller. It can handle both
* PATA and SATA controllers. Most BMDMA controllers should be
* able to use this EH as-is or with some added handling before
* and after.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_bmdma_error_handler(struct ata_port *ap)
{
struct ata_queued_cmd *qc;
unsigned long flags;
bool thaw = false;
qc = __ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
qc = NULL;
/* reset PIO HSM and stop DMA engine */
spin_lock_irqsave(ap->lock, flags);
if (qc && ata_is_dma(qc->tf.protocol)) {
u8 host_stat;
host_stat = ap->ops->bmdma_status(ap);
/* BMDMA controllers indicate host bus error by
* setting DMA_ERR bit and timing out. As it wasn't
* really a timeout event, adjust error mask and
* cancel frozen state.
*/
if (qc->err_mask == AC_ERR_TIMEOUT && (host_stat & ATA_DMA_ERR)) {
qc->err_mask = AC_ERR_HOST_BUS;
thaw = true;
}
ap->ops->bmdma_stop(qc);
/* if we're gonna thaw, make sure IRQ is clear */
if (thaw) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
}
spin_unlock_irqrestore(ap->lock, flags);
if (thaw)
ata_eh_thaw_port(ap);
ata_sff_error_handler(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
/**
* ata_bmdma_post_internal_cmd - Stock post_internal_cmd for BMDMA
* @qc: internal command to clean up
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_bmdma_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned long flags;
if (ata_is_dma(qc->tf.protocol)) {
spin_lock_irqsave(ap->lock, flags);
ap->ops->bmdma_stop(qc);
spin_unlock_irqrestore(ap->lock, flags);
}
}
EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
/**
* ata_bmdma_irq_clear - Clear PCI IDE BMDMA interrupt.
* @ap: Port associated with this ATA transaction.
*
* Clear interrupt and error flags in DMA status register.
*
* May be used as the irq_clear() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_irq_clear(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.bmdma_addr;
if (!mmio)
return;
iowrite8(ioread8(mmio + ATA_DMA_STATUS), mmio + ATA_DMA_STATUS);
}
EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
/**
* ata_bmdma_setup - Set up PCI IDE BMDMA transaction
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 dmactl;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
/* specify data direction, triple-check start bit is clear */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
if (!rw)
dmactl |= ATA_DMA_WR;
iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
EXPORT_SYMBOL_GPL(ata_bmdma_setup);
/**
* ata_bmdma_start - Start a PCI IDE BMDMA transaction
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
u8 dmactl;
/* start host DMA transaction */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
iowrite8(dmactl | ATA_DMA_START, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* Strictly, one may wish to issue an ioread8() here, to
* flush the mmio write. However, control also passes
* to the hardware at this point, and it will interrupt
* us when we are to resume control. So, in effect,
* we don't care when the mmio write flushes.
* Further, a read of the DMA status register _immediately_
* following the write may not be what certain flaky hardware
* is expected, so I think it is best to not add a readb()
* without first all the MMIO ATA cards/mobos.
* Or maybe I'm just being paranoid.
*
* FIXME: The posting of this write means I/O starts are
* unnecessarily delayed for MMIO
*/
}
EXPORT_SYMBOL_GPL(ata_bmdma_start);
/**
* ata_bmdma_stop - Stop PCI IDE BMDMA transfer
* @qc: Command we are ending DMA for
*
* Clears the ATA_DMA_START flag in the dma control register
*
* May be used as the bmdma_stop() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
void __iomem *mmio = ap->ioaddr.bmdma_addr;
/* clear start/stop bit */
iowrite8(ioread8(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
mmio + ATA_DMA_CMD);
/* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
ata_sff_dma_pause(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_stop);
/**
* ata_bmdma_status - Read PCI IDE BMDMA status
* @ap: Port associated with this ATA transaction.
*
* Read and return BMDMA status register.
*
* May be used as the bmdma_status() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
u8 ata_bmdma_status(struct ata_port *ap)
{
return ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
}
EXPORT_SYMBOL_GPL(ata_bmdma_status);
/**
* ata_bmdma_port_start - Set port up for bmdma.
* @ap: Port to initialize
*
* Called just after data structures for each port are
* initialized. Allocates space for PRD table.
*
* May be used as the port_start() entry in ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
int ata_bmdma_port_start(struct ata_port *ap)
{
if (ap->mwdma_mask || ap->udma_mask) {
ap->bmdma_prd =
dmam_alloc_coherent(ap->host->dev, ATA_PRD_TBL_SZ,
&ap->bmdma_prd_dma, GFP_KERNEL);
if (!ap->bmdma_prd)
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_start);
/**
* ata_bmdma_port_start32 - Set port up for dma.
* @ap: Port to initialize
*
* Called just after data structures for each port are
* initialized. Enables 32bit PIO and allocates space for PRD
* table.
*
* May be used as the port_start() entry in ata_port_operations for
* devices that are capable of 32bit PIO.
*
* LOCKING:
* Inherited from caller.
*/
int ata_bmdma_port_start32(struct ata_port *ap)
{
ap->pflags |= ATA_PFLAG_PIO32 | ATA_PFLAG_PIO32CHANGE;
return ata_bmdma_port_start(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_start32);
#ifdef CONFIG_PCI
/**
* ata_pci_bmdma_clear_simplex - attempt to kick device out of simplex
* @pdev: PCI device
*
* Some PCI ATA devices report simplex mode but in fact can be told to
* enter non simplex mode. This implements the necessary logic to
* perform the task on such devices. Calling it on other devices will
* have -undefined- behaviour.
*/
int ata_pci_bmdma_clear_simplex(struct pci_dev *pdev)
{
unsigned long bmdma = pci_resource_start(pdev, 4);
u8 simplex;
if (bmdma == 0)
return -ENOENT;
simplex = inb(bmdma + 0x02);
outb(simplex & 0x60, bmdma + 0x02);
simplex = inb(bmdma + 0x02);
if (simplex & 0x80)
return -EOPNOTSUPP;
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_clear_simplex);
static void ata_bmdma_nodma(struct ata_host *host, const char *reason)
{
int i;
dev_err(host->dev, "BMDMA: %s, falling back to PIO\n", reason);
for (i = 0; i < 2; i++) {
host->ports[i]->mwdma_mask = 0;
host->ports[i]->udma_mask = 0;
}
}
/**
* ata_pci_bmdma_init - acquire PCI BMDMA resources and init ATA host
* @host: target ATA host
*
* Acquire PCI BMDMA resources and initialize @host accordingly.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*/
void ata_pci_bmdma_init(struct ata_host *host)
{
struct device *gdev = host->dev;
struct pci_dev *pdev = to_pci_dev(gdev);
int i, rc;
/* No BAR4 allocation: No DMA */
if (pci_resource_start(pdev, 4) == 0) {
ata_bmdma_nodma(host, "BAR4 is zero");
return;
}
/*
* Some controllers require BMDMA region to be initialized
* even if DMA is not in use to clear IRQ status via
* ->sff_irq_clear method. Try to initialize bmdma_addr
* regardless of dma masks.
*/
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
ata_bmdma_nodma(host, "failed to set dma mask");
if (!rc) {
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
ata_bmdma_nodma(host,
"failed to set consistent dma mask");
}
/* request and iomap DMA region */
rc = pcim_iomap_regions(pdev, 1 << 4, dev_driver_string(gdev));
if (rc) {
ata_bmdma_nodma(host, "failed to request/iomap BAR4");
return;
}
host->iomap = pcim_iomap_table(pdev);
for (i = 0; i < 2; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *bmdma = host->iomap[4] + 8 * i;
if (ata_port_is_dummy(ap))
continue;
ap->ioaddr.bmdma_addr = bmdma;
if ((!(ap->flags & ATA_FLAG_IGN_SIMPLEX)) &&
(ioread8(bmdma + 2) & 0x80))
host->flags |= ATA_HOST_SIMPLEX;
ata_port_desc(ap, "bmdma 0x%llx",
(unsigned long long)pci_resource_start(pdev, 4) + 8 * i);
}
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_init);
/**
* ata_pci_bmdma_prepare_host - helper to prepare PCI BMDMA ATA host
* @pdev: target PCI device
* @ppi: array of port_info, must be enough for two ports
* @r_host: out argument for the initialized ATA host
*
* Helper to allocate BMDMA ATA host for @pdev, acquire all PCI
* resources and initialize it accordingly in one go.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_bmdma_prepare_host(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct ata_host **r_host)
{
int rc;
rc = ata_pci_sff_prepare_host(pdev, ppi, r_host);
if (rc)
return rc;
ata_pci_bmdma_init(*r_host);
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_prepare_host);
/**
* ata_pci_bmdma_init_one - Initialize/register BMDMA PCI IDE controller
* @pdev: Controller to be initialized
* @ppi: array of port_info, must be enough for two ports
* @sht: scsi_host_template to use when registering the host
* @host_priv: host private_data
* @hflags: host flags
*
* This function is similar to ata_pci_sff_init_one() but also
* takes care of BMDMA initialization.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, negative on errno-based value on error.
*/
int ata_pci_bmdma_init_one(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct scsi_host_template *sht, void *host_priv,
int hflags)
{
return ata_pci_init_one(pdev, ppi, sht, host_priv, hflags, 1);
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_init_one);
#endif /* CONFIG_PCI */
#endif /* CONFIG_ATA_BMDMA */
/**
* ata_sff_port_init - Initialize SFF/BMDMA ATA port
* @ap: Port to initialize
*
* Called on port allocation to initialize SFF/BMDMA specific
* fields.
*
* LOCKING:
* None.
*/
void ata_sff_port_init(struct ata_port *ap)
{
INIT_DELAYED_WORK(&ap->sff_pio_task, ata_sff_pio_task);
ap->ctl = ATA_DEVCTL_OBS;
ap->last_ctl = 0xFF;
}
int __init ata_sff_init(void)
{
ata_sff_wq = alloc_workqueue("ata_sff", WQ_MEM_RECLAIM, WQ_MAX_ACTIVE);
if (!ata_sff_wq)
return -ENOMEM;
return 0;
}
void ata_sff_exit(void)
{
destroy_workqueue(ata_sff_wq);
}
| gpl-2.0 |
adrset/kernel | drivers/net/wireless/wl1251/main.c | 4829 | 33065 | /*
* This file is part of wl1251
*
* Copyright (C) 2008-2009 Nokia Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/firmware.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/crc32.h>
#include <linux/etherdevice.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include "wl1251.h"
#include "wl12xx_80211.h"
#include "reg.h"
#include "io.h"
#include "cmd.h"
#include "event.h"
#include "tx.h"
#include "rx.h"
#include "ps.h"
#include "init.h"
#include "debugfs.h"
#include "boot.h"
void wl1251_enable_interrupts(struct wl1251 *wl)
{
wl->if_ops->enable_irq(wl);
}
void wl1251_disable_interrupts(struct wl1251 *wl)
{
wl->if_ops->disable_irq(wl);
}
static int wl1251_power_off(struct wl1251 *wl)
{
return wl->if_ops->power(wl, false);
}
static int wl1251_power_on(struct wl1251 *wl)
{
return wl->if_ops->power(wl, true);
}
static int wl1251_fetch_firmware(struct wl1251 *wl)
{
const struct firmware *fw;
struct device *dev = wiphy_dev(wl->hw->wiphy);
int ret;
ret = request_firmware(&fw, WL1251_FW_NAME, dev);
if (ret < 0) {
wl1251_error("could not get firmware: %d", ret);
return ret;
}
if (fw->size % 4) {
wl1251_error("firmware size is not multiple of 32 bits: %zu",
fw->size);
ret = -EILSEQ;
goto out;
}
wl->fw_len = fw->size;
wl->fw = vmalloc(wl->fw_len);
if (!wl->fw) {
wl1251_error("could not allocate memory for the firmware");
ret = -ENOMEM;
goto out;
}
memcpy(wl->fw, fw->data, wl->fw_len);
ret = 0;
out:
release_firmware(fw);
return ret;
}
static int wl1251_fetch_nvs(struct wl1251 *wl)
{
const struct firmware *fw;
struct device *dev = wiphy_dev(wl->hw->wiphy);
int ret;
ret = request_firmware(&fw, WL1251_NVS_NAME, dev);
if (ret < 0) {
wl1251_error("could not get nvs file: %d", ret);
return ret;
}
if (fw->size % 4) {
wl1251_error("nvs size is not multiple of 32 bits: %zu",
fw->size);
ret = -EILSEQ;
goto out;
}
wl->nvs_len = fw->size;
wl->nvs = kmemdup(fw->data, wl->nvs_len, GFP_KERNEL);
if (!wl->nvs) {
wl1251_error("could not allocate memory for the nvs file");
ret = -ENOMEM;
goto out;
}
ret = 0;
out:
release_firmware(fw);
return ret;
}
static void wl1251_fw_wakeup(struct wl1251 *wl)
{
u32 elp_reg;
elp_reg = ELPCTRL_WAKE_UP;
wl1251_write_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, elp_reg);
elp_reg = wl1251_read_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR);
if (!(elp_reg & ELPCTRL_WLAN_READY))
wl1251_warning("WLAN not ready");
}
static int wl1251_chip_wakeup(struct wl1251 *wl)
{
int ret;
ret = wl1251_power_on(wl);
if (ret < 0)
return ret;
msleep(WL1251_POWER_ON_SLEEP);
wl->if_ops->reset(wl);
/* We don't need a real memory partition here, because we only want
* to use the registers at this point. */
wl1251_set_partition(wl,
0x00000000,
0x00000000,
REGISTERS_BASE,
REGISTERS_DOWN_SIZE);
/* ELP module wake up */
wl1251_fw_wakeup(wl);
/* whal_FwCtrl_BootSm() */
/* 0. read chip id from CHIP_ID */
wl->chip_id = wl1251_reg_read32(wl, CHIP_ID_B);
/* 1. check if chip id is valid */
switch (wl->chip_id) {
case CHIP_ID_1251_PG12:
wl1251_debug(DEBUG_BOOT, "chip id 0x%x (1251 PG12)",
wl->chip_id);
break;
case CHIP_ID_1251_PG11:
wl1251_debug(DEBUG_BOOT, "chip id 0x%x (1251 PG11)",
wl->chip_id);
break;
case CHIP_ID_1251_PG10:
default:
wl1251_error("unsupported chip id: 0x%x", wl->chip_id);
ret = -ENODEV;
goto out;
}
if (wl->fw == NULL) {
ret = wl1251_fetch_firmware(wl);
if (ret < 0)
goto out;
}
if (wl->nvs == NULL && !wl->use_eeprom) {
/* No NVS from netlink, try to get it from the filesystem */
ret = wl1251_fetch_nvs(wl);
if (ret < 0)
goto out;
}
out:
return ret;
}
#define WL1251_IRQ_LOOP_COUNT 10
static void wl1251_irq_work(struct work_struct *work)
{
u32 intr, ctr = WL1251_IRQ_LOOP_COUNT;
struct wl1251 *wl =
container_of(work, struct wl1251, irq_work);
int ret;
mutex_lock(&wl->mutex);
wl1251_debug(DEBUG_IRQ, "IRQ work");
if (wl->state == WL1251_STATE_OFF)
goto out;
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1251_reg_write32(wl, ACX_REG_INTERRUPT_MASK, WL1251_ACX_INTR_ALL);
intr = wl1251_reg_read32(wl, ACX_REG_INTERRUPT_CLEAR);
wl1251_debug(DEBUG_IRQ, "intr: 0x%x", intr);
do {
if (wl->data_path) {
wl->rx_counter = wl1251_mem_read32(
wl, wl->data_path->rx_control_addr);
/* We handle a frmware bug here */
switch ((wl->rx_counter - wl->rx_handled) & 0xf) {
case 0:
wl1251_debug(DEBUG_IRQ,
"RX: FW and host in sync");
intr &= ~WL1251_ACX_INTR_RX0_DATA;
intr &= ~WL1251_ACX_INTR_RX1_DATA;
break;
case 1:
wl1251_debug(DEBUG_IRQ, "RX: FW +1");
intr |= WL1251_ACX_INTR_RX0_DATA;
intr &= ~WL1251_ACX_INTR_RX1_DATA;
break;
case 2:
wl1251_debug(DEBUG_IRQ, "RX: FW +2");
intr |= WL1251_ACX_INTR_RX0_DATA;
intr |= WL1251_ACX_INTR_RX1_DATA;
break;
default:
wl1251_warning(
"RX: FW and host out of sync: %d",
wl->rx_counter - wl->rx_handled);
break;
}
wl->rx_handled = wl->rx_counter;
wl1251_debug(DEBUG_IRQ, "RX counter: %d",
wl->rx_counter);
}
intr &= wl->intr_mask;
if (intr == 0) {
wl1251_debug(DEBUG_IRQ, "INTR is 0");
goto out_sleep;
}
if (intr & WL1251_ACX_INTR_RX0_DATA) {
wl1251_debug(DEBUG_IRQ, "WL1251_ACX_INTR_RX0_DATA");
wl1251_rx(wl);
}
if (intr & WL1251_ACX_INTR_RX1_DATA) {
wl1251_debug(DEBUG_IRQ, "WL1251_ACX_INTR_RX1_DATA");
wl1251_rx(wl);
}
if (intr & WL1251_ACX_INTR_TX_RESULT) {
wl1251_debug(DEBUG_IRQ, "WL1251_ACX_INTR_TX_RESULT");
wl1251_tx_complete(wl);
}
if (intr & WL1251_ACX_INTR_EVENT_A) {
wl1251_debug(DEBUG_IRQ, "WL1251_ACX_INTR_EVENT_A");
wl1251_event_handle(wl, 0);
}
if (intr & WL1251_ACX_INTR_EVENT_B) {
wl1251_debug(DEBUG_IRQ, "WL1251_ACX_INTR_EVENT_B");
wl1251_event_handle(wl, 1);
}
if (intr & WL1251_ACX_INTR_INIT_COMPLETE)
wl1251_debug(DEBUG_IRQ,
"WL1251_ACX_INTR_INIT_COMPLETE");
if (--ctr == 0)
break;
intr = wl1251_reg_read32(wl, ACX_REG_INTERRUPT_CLEAR);
} while (intr);
out_sleep:
wl1251_reg_write32(wl, ACX_REG_INTERRUPT_MASK, ~(wl->intr_mask));
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1251_join(struct wl1251 *wl, u8 bss_type, u8 channel,
u16 beacon_interval, u8 dtim_period)
{
int ret;
ret = wl1251_acx_frame_rates(wl, DEFAULT_HW_GEN_TX_RATE,
DEFAULT_HW_GEN_MODULATION_TYPE,
wl->tx_mgmt_frm_rate,
wl->tx_mgmt_frm_mod);
if (ret < 0)
goto out;
ret = wl1251_cmd_join(wl, bss_type, channel, beacon_interval,
dtim_period);
if (ret < 0)
goto out;
ret = wl1251_event_wait(wl, JOIN_EVENT_COMPLETE_ID, 100);
if (ret < 0)
wl1251_warning("join timeout");
out:
return ret;
}
static void wl1251_filter_work(struct work_struct *work)
{
struct wl1251 *wl =
container_of(work, struct wl1251, filter_work);
int ret;
mutex_lock(&wl->mutex);
if (wl->state == WL1251_STATE_OFF)
goto out;
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1251_join(wl, wl->bss_type, wl->channel, wl->beacon_int,
wl->dtim_period);
if (ret < 0)
goto out_sleep;
out_sleep:
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1251_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct wl1251 *wl = hw->priv;
unsigned long flags;
skb_queue_tail(&wl->tx_queue, skb);
/*
* The chip specific setup must run before the first TX packet -
* before that, the tx_work will not be initialized!
*/
ieee80211_queue_work(wl->hw, &wl->tx_work);
/*
* The workqueue is slow to process the tx_queue and we need stop
* the queue here, otherwise the queue will get too long.
*/
if (skb_queue_len(&wl->tx_queue) >= WL1251_TX_QUEUE_HIGH_WATERMARK) {
wl1251_debug(DEBUG_TX, "op_tx: tx_queue full, stop queues");
spin_lock_irqsave(&wl->wl_lock, flags);
ieee80211_stop_queues(wl->hw);
wl->tx_queue_stopped = true;
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
}
static int wl1251_op_start(struct ieee80211_hw *hw)
{
struct wl1251 *wl = hw->priv;
struct wiphy *wiphy = hw->wiphy;
int ret = 0;
wl1251_debug(DEBUG_MAC80211, "mac80211 start");
mutex_lock(&wl->mutex);
if (wl->state != WL1251_STATE_OFF) {
wl1251_error("cannot start because not in off state: %d",
wl->state);
ret = -EBUSY;
goto out;
}
ret = wl1251_chip_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1251_boot(wl);
if (ret < 0)
goto out;
ret = wl1251_hw_init(wl);
if (ret < 0)
goto out;
ret = wl1251_acx_station_id(wl);
if (ret < 0)
goto out;
wl->state = WL1251_STATE_ON;
wl1251_info("firmware booted (%s)", wl->fw_ver);
/* update hw/fw version info in wiphy struct */
wiphy->hw_version = wl->chip_id;
strncpy(wiphy->fw_version, wl->fw_ver, sizeof(wiphy->fw_version));
out:
if (ret < 0)
wl1251_power_off(wl);
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1251_op_stop(struct ieee80211_hw *hw)
{
struct wl1251 *wl = hw->priv;
wl1251_info("down");
wl1251_debug(DEBUG_MAC80211, "mac80211 stop");
mutex_lock(&wl->mutex);
WARN_ON(wl->state != WL1251_STATE_ON);
if (wl->scanning) {
ieee80211_scan_completed(wl->hw, true);
wl->scanning = false;
}
wl->state = WL1251_STATE_OFF;
wl1251_disable_interrupts(wl);
mutex_unlock(&wl->mutex);
cancel_work_sync(&wl->irq_work);
cancel_work_sync(&wl->tx_work);
cancel_work_sync(&wl->filter_work);
cancel_delayed_work_sync(&wl->elp_work);
mutex_lock(&wl->mutex);
/* let's notify MAC80211 about the remaining pending TX frames */
wl1251_tx_flush(wl);
wl1251_power_off(wl);
memset(wl->bssid, 0, ETH_ALEN);
wl->listen_int = 1;
wl->bss_type = MAX_BSS_TYPE;
wl->data_in_count = 0;
wl->rx_counter = 0;
wl->rx_handled = 0;
wl->rx_current_buffer = 0;
wl->rx_last_id = 0;
wl->next_tx_complete = 0;
wl->elp = false;
wl->station_mode = STATION_ACTIVE_MODE;
wl->tx_queue_stopped = false;
wl->power_level = WL1251_DEFAULT_POWER_LEVEL;
wl->rssi_thold = 0;
wl->channel = WL1251_DEFAULT_CHANNEL;
wl1251_debugfs_reset(wl);
mutex_unlock(&wl->mutex);
}
static int wl1251_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1251 *wl = hw->priv;
int ret = 0;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER |
IEEE80211_VIF_SUPPORTS_CQM_RSSI;
wl1251_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM",
vif->type, vif->addr);
mutex_lock(&wl->mutex);
if (wl->vif) {
ret = -EBUSY;
goto out;
}
wl->vif = vif;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
wl->bss_type = BSS_TYPE_STA_BSS;
break;
case NL80211_IFTYPE_ADHOC:
wl->bss_type = BSS_TYPE_IBSS;
break;
default:
ret = -EOPNOTSUPP;
goto out;
}
if (memcmp(wl->mac_addr, vif->addr, ETH_ALEN)) {
memcpy(wl->mac_addr, vif->addr, ETH_ALEN);
SET_IEEE80211_PERM_ADDR(wl->hw, wl->mac_addr);
ret = wl1251_acx_station_id(wl);
if (ret < 0)
goto out;
}
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1251_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1251 *wl = hw->priv;
mutex_lock(&wl->mutex);
wl1251_debug(DEBUG_MAC80211, "mac80211 remove interface");
wl->vif = NULL;
mutex_unlock(&wl->mutex);
}
static int wl1251_build_qos_null_data(struct wl1251 *wl)
{
struct ieee80211_qos_hdr template;
memset(&template, 0, sizeof(template));
memcpy(template.addr1, wl->bssid, ETH_ALEN);
memcpy(template.addr2, wl->mac_addr, ETH_ALEN);
memcpy(template.addr3, wl->bssid, ETH_ALEN);
template.frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_QOS_NULLFUNC |
IEEE80211_FCTL_TODS);
/* FIXME: not sure what priority to use here */
template.qos_ctrl = cpu_to_le16(0);
return wl1251_cmd_template_set(wl, CMD_QOS_NULL_DATA, &template,
sizeof(template));
}
static int wl1251_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct wl1251 *wl = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
int channel, ret = 0;
channel = ieee80211_frequency_to_channel(conf->channel->center_freq);
wl1251_debug(DEBUG_MAC80211, "mac80211 config ch %d psm %s power %d",
channel,
conf->flags & IEEE80211_CONF_PS ? "on" : "off",
conf->power_level);
mutex_lock(&wl->mutex);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (channel != wl->channel) {
wl->channel = channel;
ret = wl1251_join(wl, wl->bss_type, wl->channel,
wl->beacon_int, wl->dtim_period);
if (ret < 0)
goto out_sleep;
}
if (conf->flags & IEEE80211_CONF_PS && !wl->psm_requested) {
wl1251_debug(DEBUG_PSM, "psm enabled");
wl->psm_requested = true;
wl->dtim_period = conf->ps_dtim_period;
ret = wl1251_acx_wr_tbtt_and_dtim(wl, wl->beacon_int,
wl->dtim_period);
/*
* mac80211 enables PSM only if we're already associated.
*/
ret = wl1251_ps_set_mode(wl, STATION_POWER_SAVE_MODE);
if (ret < 0)
goto out_sleep;
} else if (!(conf->flags & IEEE80211_CONF_PS) &&
wl->psm_requested) {
wl1251_debug(DEBUG_PSM, "psm disabled");
wl->psm_requested = false;
if (wl->station_mode != STATION_ACTIVE_MODE) {
ret = wl1251_ps_set_mode(wl, STATION_ACTIVE_MODE);
if (ret < 0)
goto out_sleep;
}
}
if (changed & IEEE80211_CONF_CHANGE_IDLE) {
if (conf->flags & IEEE80211_CONF_IDLE) {
ret = wl1251_ps_set_mode(wl, STATION_IDLE);
if (ret < 0)
goto out_sleep;
} else {
ret = wl1251_ps_set_mode(wl, STATION_ACTIVE_MODE);
if (ret < 0)
goto out_sleep;
ret = wl1251_join(wl, wl->bss_type, wl->channel,
wl->beacon_int, wl->dtim_period);
if (ret < 0)
goto out_sleep;
}
}
if (conf->power_level != wl->power_level) {
ret = wl1251_acx_tx_power(wl, conf->power_level);
if (ret < 0)
goto out_sleep;
wl->power_level = conf->power_level;
}
out_sleep:
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
#define WL1251_SUPPORTED_FILTERS (FIF_PROMISC_IN_BSS | \
FIF_ALLMULTI | \
FIF_FCSFAIL | \
FIF_BCN_PRBRESP_PROMISC | \
FIF_CONTROL | \
FIF_OTHER_BSS)
static void wl1251_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed,
unsigned int *total,u64 multicast)
{
struct wl1251 *wl = hw->priv;
wl1251_debug(DEBUG_MAC80211, "mac80211 configure filter");
*total &= WL1251_SUPPORTED_FILTERS;
changed &= WL1251_SUPPORTED_FILTERS;
if (changed == 0)
/* no filters which we support changed */
return;
/* FIXME: wl->rx_config and wl->rx_filter are not protected */
wl->rx_config = WL1251_DEFAULT_RX_CONFIG;
wl->rx_filter = WL1251_DEFAULT_RX_FILTER;
if (*total & FIF_PROMISC_IN_BSS) {
wl->rx_config |= CFG_BSSID_FILTER_EN;
wl->rx_config |= CFG_RX_ALL_GOOD;
}
if (*total & FIF_ALLMULTI)
/*
* CFG_MC_FILTER_EN in rx_config needs to be 0 to receive
* all multicast frames
*/
wl->rx_config &= ~CFG_MC_FILTER_EN;
if (*total & FIF_FCSFAIL)
wl->rx_filter |= CFG_RX_FCS_ERROR;
if (*total & FIF_BCN_PRBRESP_PROMISC) {
wl->rx_config &= ~CFG_BSSID_FILTER_EN;
wl->rx_config &= ~CFG_SSID_FILTER_EN;
}
if (*total & FIF_CONTROL)
wl->rx_filter |= CFG_RX_CTL_EN;
if (*total & FIF_OTHER_BSS)
wl->rx_filter &= ~CFG_BSSID_FILTER_EN;
/*
* FIXME: workqueues need to be properly cancelled on stop(), for
* now let's just disable changing the filter settings. They will
* be updated any on config().
*/
/* schedule_work(&wl->filter_work); */
}
/* HW encryption */
static int wl1251_set_key_type(struct wl1251 *wl,
struct wl1251_cmd_set_keys *key,
enum set_key_cmd cmd,
struct ieee80211_key_conf *mac80211_key,
const u8 *addr)
{
switch (mac80211_key->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
if (is_broadcast_ether_addr(addr))
key->key_type = KEY_WEP_DEFAULT;
else
key->key_type = KEY_WEP_ADDR;
mac80211_key->hw_key_idx = mac80211_key->keyidx;
break;
case WLAN_CIPHER_SUITE_TKIP:
if (is_broadcast_ether_addr(addr))
key->key_type = KEY_TKIP_MIC_GROUP;
else
key->key_type = KEY_TKIP_MIC_PAIRWISE;
mac80211_key->hw_key_idx = mac80211_key->keyidx;
break;
case WLAN_CIPHER_SUITE_CCMP:
if (is_broadcast_ether_addr(addr))
key->key_type = KEY_AES_GROUP;
else
key->key_type = KEY_AES_PAIRWISE;
mac80211_key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
break;
default:
wl1251_error("Unknown key cipher 0x%x", mac80211_key->cipher);
return -EOPNOTSUPP;
}
return 0;
}
static int wl1251_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct wl1251 *wl = hw->priv;
struct wl1251_cmd_set_keys *wl_cmd;
const u8 *addr;
int ret;
static const u8 bcast_addr[ETH_ALEN] =
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
wl1251_debug(DEBUG_MAC80211, "mac80211 set key");
wl_cmd = kzalloc(sizeof(*wl_cmd), GFP_KERNEL);
if (!wl_cmd) {
ret = -ENOMEM;
goto out;
}
addr = sta ? sta->addr : bcast_addr;
wl1251_debug(DEBUG_CRYPT, "CMD: 0x%x", cmd);
wl1251_dump(DEBUG_CRYPT, "ADDR: ", addr, ETH_ALEN);
wl1251_debug(DEBUG_CRYPT, "Key: algo:0x%x, id:%d, len:%d flags 0x%x",
key->cipher, key->keyidx, key->keylen, key->flags);
wl1251_dump(DEBUG_CRYPT, "KEY: ", key->key, key->keylen);
if (is_zero_ether_addr(addr)) {
/* We dont support TX only encryption */
ret = -EOPNOTSUPP;
goto out;
}
mutex_lock(&wl->mutex);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
switch (cmd) {
case SET_KEY:
wl_cmd->key_action = KEY_ADD_OR_REPLACE;
break;
case DISABLE_KEY:
wl_cmd->key_action = KEY_REMOVE;
break;
default:
wl1251_error("Unsupported key cmd 0x%x", cmd);
break;
}
ret = wl1251_set_key_type(wl, wl_cmd, cmd, key, addr);
if (ret < 0) {
wl1251_error("Set KEY type failed");
goto out_sleep;
}
if (wl_cmd->key_type != KEY_WEP_DEFAULT)
memcpy(wl_cmd->addr, addr, ETH_ALEN);
if ((wl_cmd->key_type == KEY_TKIP_MIC_GROUP) ||
(wl_cmd->key_type == KEY_TKIP_MIC_PAIRWISE)) {
/*
* We get the key in the following form:
* TKIP (16 bytes) - TX MIC (8 bytes) - RX MIC (8 bytes)
* but the target is expecting:
* TKIP - RX MIC - TX MIC
*/
memcpy(wl_cmd->key, key->key, 16);
memcpy(wl_cmd->key + 16, key->key + 24, 8);
memcpy(wl_cmd->key + 24, key->key + 16, 8);
} else {
memcpy(wl_cmd->key, key->key, key->keylen);
}
wl_cmd->key_size = key->keylen;
wl_cmd->id = key->keyidx;
wl_cmd->ssid_profile = 0;
wl1251_dump(DEBUG_CRYPT, "TARGET KEY: ", wl_cmd, sizeof(*wl_cmd));
ret = wl1251_cmd_send(wl, CMD_SET_KEYS, wl_cmd, sizeof(*wl_cmd));
if (ret < 0) {
wl1251_warning("could not set keys");
goto out_sleep;
}
out_sleep:
wl1251_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
out:
kfree(wl_cmd);
return ret;
}
static int wl1251_op_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_scan_request *req)
{
struct wl1251 *wl = hw->priv;
struct sk_buff *skb;
size_t ssid_len = 0;
u8 *ssid = NULL;
int ret;
wl1251_debug(DEBUG_MAC80211, "mac80211 hw scan");
if (req->n_ssids) {
ssid = req->ssids[0].ssid;
ssid_len = req->ssids[0].ssid_len;
}
mutex_lock(&wl->mutex);
if (wl->scanning) {
wl1251_debug(DEBUG_SCAN, "scan already in progress");
ret = -EINVAL;
goto out;
}
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
skb = ieee80211_probereq_get(wl->hw, wl->vif, ssid, ssid_len,
req->ie, req->ie_len);
if (!skb) {
ret = -ENOMEM;
goto out;
}
ret = wl1251_cmd_template_set(wl, CMD_PROBE_REQ, skb->data,
skb->len);
dev_kfree_skb(skb);
if (ret < 0)
goto out_sleep;
ret = wl1251_cmd_trigger_scan_to(wl, 0);
if (ret < 0)
goto out_sleep;
wl->scanning = true;
ret = wl1251_cmd_scan(wl, ssid, ssid_len, req->channels,
req->n_channels, WL1251_SCAN_NUM_PROBES);
if (ret < 0) {
wl->scanning = false;
goto out_sleep;
}
out_sleep:
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1251_op_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
{
struct wl1251 *wl = hw->priv;
int ret;
mutex_lock(&wl->mutex);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1251_acx_rts_threshold(wl, (u16) value);
if (ret < 0)
wl1251_warning("wl1251_op_set_rts_threshold failed: %d", ret);
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1251_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl1251 *wl = hw->priv;
struct sk_buff *beacon, *skb;
int ret;
wl1251_debug(DEBUG_MAC80211, "mac80211 bss info changed");
mutex_lock(&wl->mutex);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (changed & BSS_CHANGED_CQM) {
ret = wl1251_acx_low_rssi(wl, bss_conf->cqm_rssi_thold,
WL1251_DEFAULT_LOW_RSSI_WEIGHT,
WL1251_DEFAULT_LOW_RSSI_DEPTH,
WL1251_ACX_LOW_RSSI_TYPE_EDGE);
if (ret < 0)
goto out;
wl->rssi_thold = bss_conf->cqm_rssi_thold;
}
if (changed & BSS_CHANGED_BSSID) {
memcpy(wl->bssid, bss_conf->bssid, ETH_ALEN);
skb = ieee80211_nullfunc_get(wl->hw, wl->vif);
if (!skb)
goto out_sleep;
ret = wl1251_cmd_template_set(wl, CMD_NULL_DATA,
skb->data, skb->len);
dev_kfree_skb(skb);
if (ret < 0)
goto out_sleep;
ret = wl1251_build_qos_null_data(wl);
if (ret < 0)
goto out;
if (wl->bss_type != BSS_TYPE_IBSS) {
ret = wl1251_join(wl, wl->bss_type, wl->channel,
wl->beacon_int, wl->dtim_period);
if (ret < 0)
goto out_sleep;
}
}
if (changed & BSS_CHANGED_ASSOC) {
if (bss_conf->assoc) {
wl->beacon_int = bss_conf->beacon_int;
skb = ieee80211_pspoll_get(wl->hw, wl->vif);
if (!skb)
goto out_sleep;
ret = wl1251_cmd_template_set(wl, CMD_PS_POLL,
skb->data,
skb->len);
dev_kfree_skb(skb);
if (ret < 0)
goto out_sleep;
ret = wl1251_acx_aid(wl, bss_conf->aid);
if (ret < 0)
goto out_sleep;
} else {
/* use defaults when not associated */
wl->beacon_int = WL1251_DEFAULT_BEACON_INT;
wl->dtim_period = WL1251_DEFAULT_DTIM_PERIOD;
}
}
if (changed & BSS_CHANGED_ERP_SLOT) {
if (bss_conf->use_short_slot)
ret = wl1251_acx_slot(wl, SLOT_TIME_SHORT);
else
ret = wl1251_acx_slot(wl, SLOT_TIME_LONG);
if (ret < 0) {
wl1251_warning("Set slot time failed %d", ret);
goto out_sleep;
}
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (bss_conf->use_short_preamble)
wl1251_acx_set_preamble(wl, ACX_PREAMBLE_SHORT);
else
wl1251_acx_set_preamble(wl, ACX_PREAMBLE_LONG);
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
if (bss_conf->use_cts_prot)
ret = wl1251_acx_cts_protect(wl, CTSPROTECT_ENABLE);
else
ret = wl1251_acx_cts_protect(wl, CTSPROTECT_DISABLE);
if (ret < 0) {
wl1251_warning("Set ctsprotect failed %d", ret);
goto out_sleep;
}
}
if (changed & BSS_CHANGED_BEACON) {
beacon = ieee80211_beacon_get(hw, vif);
if (!beacon)
goto out_sleep;
ret = wl1251_cmd_template_set(wl, CMD_BEACON, beacon->data,
beacon->len);
if (ret < 0) {
dev_kfree_skb(beacon);
goto out_sleep;
}
ret = wl1251_cmd_template_set(wl, CMD_PROBE_RESP, beacon->data,
beacon->len);
dev_kfree_skb(beacon);
if (ret < 0)
goto out_sleep;
ret = wl1251_join(wl, wl->bss_type, wl->beacon_int,
wl->channel, wl->dtim_period);
if (ret < 0)
goto out_sleep;
}
out_sleep:
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
/* can't be const, mac80211 writes to this */
static struct ieee80211_rate wl1251_rates[] = {
{ .bitrate = 10,
.hw_value = 0x1,
.hw_value_short = 0x1, },
{ .bitrate = 20,
.hw_value = 0x2,
.hw_value_short = 0x2,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55,
.hw_value = 0x4,
.hw_value_short = 0x4,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110,
.hw_value = 0x20,
.hw_value_short = 0x20,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60,
.hw_value = 0x8,
.hw_value_short = 0x8, },
{ .bitrate = 90,
.hw_value = 0x10,
.hw_value_short = 0x10, },
{ .bitrate = 120,
.hw_value = 0x40,
.hw_value_short = 0x40, },
{ .bitrate = 180,
.hw_value = 0x80,
.hw_value_short = 0x80, },
{ .bitrate = 240,
.hw_value = 0x200,
.hw_value_short = 0x200, },
{ .bitrate = 360,
.hw_value = 0x400,
.hw_value_short = 0x400, },
{ .bitrate = 480,
.hw_value = 0x800,
.hw_value_short = 0x800, },
{ .bitrate = 540,
.hw_value = 0x1000,
.hw_value_short = 0x1000, },
};
/* can't be const, mac80211 writes to this */
static struct ieee80211_channel wl1251_channels[] = {
{ .hw_value = 1, .center_freq = 2412},
{ .hw_value = 2, .center_freq = 2417},
{ .hw_value = 3, .center_freq = 2422},
{ .hw_value = 4, .center_freq = 2427},
{ .hw_value = 5, .center_freq = 2432},
{ .hw_value = 6, .center_freq = 2437},
{ .hw_value = 7, .center_freq = 2442},
{ .hw_value = 8, .center_freq = 2447},
{ .hw_value = 9, .center_freq = 2452},
{ .hw_value = 10, .center_freq = 2457},
{ .hw_value = 11, .center_freq = 2462},
{ .hw_value = 12, .center_freq = 2467},
{ .hw_value = 13, .center_freq = 2472},
};
static int wl1251_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
enum wl1251_acx_ps_scheme ps_scheme;
struct wl1251 *wl = hw->priv;
int ret;
mutex_lock(&wl->mutex);
wl1251_debug(DEBUG_MAC80211, "mac80211 conf tx %d", queue);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
/* mac80211 uses units of 32 usec */
ret = wl1251_acx_ac_cfg(wl, wl1251_tx_get_queue(queue),
params->cw_min, params->cw_max,
params->aifs, params->txop * 32);
if (ret < 0)
goto out_sleep;
if (params->uapsd)
ps_scheme = WL1251_ACX_PS_SCHEME_UPSD_TRIGGER;
else
ps_scheme = WL1251_ACX_PS_SCHEME_LEGACY;
ret = wl1251_acx_tid_cfg(wl, wl1251_tx_get_queue(queue),
CHANNEL_TYPE_EDCF,
wl1251_tx_get_queue(queue), ps_scheme,
WL1251_ACX_ACK_POLICY_LEGACY);
if (ret < 0)
goto out_sleep;
out_sleep:
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1251_op_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct wl1251 *wl = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
if (idx != 0)
return -ENOENT;
survey->channel = conf->channel;
survey->filled = SURVEY_INFO_NOISE_DBM;
survey->noise = wl->noise;
return 0;
}
/* can't be const, mac80211 writes to this */
static struct ieee80211_supported_band wl1251_band_2ghz = {
.channels = wl1251_channels,
.n_channels = ARRAY_SIZE(wl1251_channels),
.bitrates = wl1251_rates,
.n_bitrates = ARRAY_SIZE(wl1251_rates),
};
static const struct ieee80211_ops wl1251_ops = {
.start = wl1251_op_start,
.stop = wl1251_op_stop,
.add_interface = wl1251_op_add_interface,
.remove_interface = wl1251_op_remove_interface,
.config = wl1251_op_config,
.configure_filter = wl1251_op_configure_filter,
.tx = wl1251_op_tx,
.set_key = wl1251_op_set_key,
.hw_scan = wl1251_op_hw_scan,
.bss_info_changed = wl1251_op_bss_info_changed,
.set_rts_threshold = wl1251_op_set_rts_threshold,
.conf_tx = wl1251_op_conf_tx,
.get_survey = wl1251_op_get_survey,
};
static int wl1251_read_eeprom_byte(struct wl1251 *wl, off_t offset, u8 *data)
{
unsigned long timeout;
wl1251_reg_write32(wl, EE_ADDR, offset);
wl1251_reg_write32(wl, EE_CTL, EE_CTL_READ);
/* EE_CTL_READ clears when data is ready */
timeout = jiffies + msecs_to_jiffies(100);
while (1) {
if (!(wl1251_reg_read32(wl, EE_CTL) & EE_CTL_READ))
break;
if (time_after(jiffies, timeout))
return -ETIMEDOUT;
msleep(1);
}
*data = wl1251_reg_read32(wl, EE_DATA);
return 0;
}
static int wl1251_read_eeprom(struct wl1251 *wl, off_t offset,
u8 *data, size_t len)
{
size_t i;
int ret;
wl1251_reg_write32(wl, EE_START, 0);
for (i = 0; i < len; i++) {
ret = wl1251_read_eeprom_byte(wl, offset + i, &data[i]);
if (ret < 0)
return ret;
}
return 0;
}
static int wl1251_read_eeprom_mac(struct wl1251 *wl)
{
u8 mac[ETH_ALEN];
int i, ret;
wl1251_set_partition(wl, 0, 0, REGISTERS_BASE, REGISTERS_DOWN_SIZE);
ret = wl1251_read_eeprom(wl, 0x1c, mac, sizeof(mac));
if (ret < 0) {
wl1251_warning("failed to read MAC address from EEPROM");
return ret;
}
/* MAC is stored in reverse order */
for (i = 0; i < ETH_ALEN; i++)
wl->mac_addr[i] = mac[ETH_ALEN - i - 1];
return 0;
}
static int wl1251_register_hw(struct wl1251 *wl)
{
int ret;
if (wl->mac80211_registered)
return 0;
SET_IEEE80211_PERM_ADDR(wl->hw, wl->mac_addr);
ret = ieee80211_register_hw(wl->hw);
if (ret < 0) {
wl1251_error("unable to register mac80211 hw: %d", ret);
return ret;
}
wl->mac80211_registered = true;
wl1251_notice("loaded");
return 0;
}
int wl1251_init_ieee80211(struct wl1251 *wl)
{
int ret;
/* The tx descriptor buffer and the TKIP space */
wl->hw->extra_tx_headroom = sizeof(struct tx_double_buffer_desc)
+ WL1251_TKIP_IV_SPACE;
/* unit us */
/* FIXME: find a proper value */
wl->hw->channel_change_time = 10000;
wl->hw->flags = IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_SUPPORTS_UAPSD;
wl->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC);
wl->hw->wiphy->max_scan_ssids = 1;
wl->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &wl1251_band_2ghz;
wl->hw->queues = 4;
if (wl->use_eeprom)
wl1251_read_eeprom_mac(wl);
ret = wl1251_register_hw(wl);
if (ret)
goto out;
wl1251_debugfs_init(wl);
wl1251_notice("initialized");
ret = 0;
out:
return ret;
}
EXPORT_SYMBOL_GPL(wl1251_init_ieee80211);
struct ieee80211_hw *wl1251_alloc_hw(void)
{
struct ieee80211_hw *hw;
struct wl1251 *wl;
int i;
static const u8 nokia_oui[3] = {0x00, 0x1f, 0xdf};
hw = ieee80211_alloc_hw(sizeof(*wl), &wl1251_ops);
if (!hw) {
wl1251_error("could not alloc ieee80211_hw");
return ERR_PTR(-ENOMEM);
}
wl = hw->priv;
memset(wl, 0, sizeof(*wl));
wl->hw = hw;
wl->data_in_count = 0;
skb_queue_head_init(&wl->tx_queue);
INIT_WORK(&wl->filter_work, wl1251_filter_work);
INIT_DELAYED_WORK(&wl->elp_work, wl1251_elp_work);
wl->channel = WL1251_DEFAULT_CHANNEL;
wl->scanning = false;
wl->default_key = 0;
wl->listen_int = 1;
wl->rx_counter = 0;
wl->rx_handled = 0;
wl->rx_current_buffer = 0;
wl->rx_last_id = 0;
wl->rx_config = WL1251_DEFAULT_RX_CONFIG;
wl->rx_filter = WL1251_DEFAULT_RX_FILTER;
wl->elp = false;
wl->station_mode = STATION_ACTIVE_MODE;
wl->psm_requested = false;
wl->tx_queue_stopped = false;
wl->power_level = WL1251_DEFAULT_POWER_LEVEL;
wl->rssi_thold = 0;
wl->beacon_int = WL1251_DEFAULT_BEACON_INT;
wl->dtim_period = WL1251_DEFAULT_DTIM_PERIOD;
wl->vif = NULL;
for (i = 0; i < FW_TX_CMPLT_BLOCK_SIZE; i++)
wl->tx_frames[i] = NULL;
wl->next_tx_complete = 0;
INIT_WORK(&wl->irq_work, wl1251_irq_work);
INIT_WORK(&wl->tx_work, wl1251_tx_work);
/*
* In case our MAC address is not correctly set,
* we use a random but Nokia MAC.
*/
memcpy(wl->mac_addr, nokia_oui, 3);
get_random_bytes(wl->mac_addr + 3, 3);
wl->state = WL1251_STATE_OFF;
mutex_init(&wl->mutex);
wl->tx_mgmt_frm_rate = DEFAULT_HW_GEN_TX_RATE;
wl->tx_mgmt_frm_mod = DEFAULT_HW_GEN_MODULATION_TYPE;
wl->rx_descriptor = kmalloc(sizeof(*wl->rx_descriptor), GFP_KERNEL);
if (!wl->rx_descriptor) {
wl1251_error("could not allocate memory for rx descriptor");
ieee80211_free_hw(hw);
return ERR_PTR(-ENOMEM);
}
return hw;
}
EXPORT_SYMBOL_GPL(wl1251_alloc_hw);
int wl1251_free_hw(struct wl1251 *wl)
{
ieee80211_unregister_hw(wl->hw);
wl1251_debugfs_exit(wl);
kfree(wl->target_mem_map);
kfree(wl->data_path);
vfree(wl->fw);
wl->fw = NULL;
kfree(wl->nvs);
wl->nvs = NULL;
kfree(wl->rx_descriptor);
wl->rx_descriptor = NULL;
ieee80211_free_hw(wl->hw);
return 0;
}
EXPORT_SYMBOL_GPL(wl1251_free_hw);
MODULE_DESCRIPTION("TI wl1251 Wireles LAN Driver Core");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kalle Valo <kvalo@adurom.com>");
MODULE_FIRMWARE(WL1251_FW_NAME);
| gpl-2.0 |
USA-RedDragon/Werewolf-hammerhead | drivers/md/dm-region-hash.c | 5597 | 18485 | /*
* Copyright (C) 2003 Sistina Software Limited.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*
* This file is released under the GPL.
*/
#include <linux/dm-dirty-log.h>
#include <linux/dm-region-hash.h>
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include "dm.h"
#define DM_MSG_PREFIX "region hash"
/*-----------------------------------------------------------------
* Region hash
*
* The mirror splits itself up into discrete regions. Each
* region can be in one of three states: clean, dirty,
* nosync. There is no need to put clean regions in the hash.
*
* In addition to being present in the hash table a region _may_
* be present on one of three lists.
*
* clean_regions: Regions on this list have no io pending to
* them, they are in sync, we are no longer interested in them,
* they are dull. dm_rh_update_states() will remove them from the
* hash table.
*
* quiesced_regions: These regions have been spun down, ready
* for recovery. rh_recovery_start() will remove regions from
* this list and hand them to kmirrord, which will schedule the
* recovery io with kcopyd.
*
* recovered_regions: Regions that kcopyd has successfully
* recovered. dm_rh_update_states() will now schedule any delayed
* io, up the recovery_count, and remove the region from the
* hash.
*
* There are 2 locks:
* A rw spin lock 'hash_lock' protects just the hash table,
* this is never held in write mode from interrupt context,
* which I believe means that we only have to disable irqs when
* doing a write lock.
*
* An ordinary spin lock 'region_lock' that protects the three
* lists in the region_hash, with the 'state', 'list' and
* 'delayed_bios' fields of the regions. This is used from irq
* context, so all other uses will have to suspend local irqs.
*---------------------------------------------------------------*/
struct dm_region_hash {
uint32_t region_size;
unsigned region_shift;
/* holds persistent region state */
struct dm_dirty_log *log;
/* hash table */
rwlock_t hash_lock;
mempool_t *region_pool;
unsigned mask;
unsigned nr_buckets;
unsigned prime;
unsigned shift;
struct list_head *buckets;
unsigned max_recovery; /* Max # of regions to recover in parallel */
spinlock_t region_lock;
atomic_t recovery_in_flight;
struct semaphore recovery_count;
struct list_head clean_regions;
struct list_head quiesced_regions;
struct list_head recovered_regions;
struct list_head failed_recovered_regions;
/*
* If there was a flush failure no regions can be marked clean.
*/
int flush_failure;
void *context;
sector_t target_begin;
/* Callback function to schedule bios writes */
void (*dispatch_bios)(void *context, struct bio_list *bios);
/* Callback function to wakeup callers worker thread. */
void (*wakeup_workers)(void *context);
/* Callback function to wakeup callers recovery waiters. */
void (*wakeup_all_recovery_waiters)(void *context);
};
struct dm_region {
struct dm_region_hash *rh; /* FIXME: can we get rid of this ? */
region_t key;
int state;
struct list_head hash_list;
struct list_head list;
atomic_t pending;
struct bio_list delayed_bios;
};
/*
* Conversion fns
*/
static region_t dm_rh_sector_to_region(struct dm_region_hash *rh, sector_t sector)
{
return sector >> rh->region_shift;
}
sector_t dm_rh_region_to_sector(struct dm_region_hash *rh, region_t region)
{
return region << rh->region_shift;
}
EXPORT_SYMBOL_GPL(dm_rh_region_to_sector);
region_t dm_rh_bio_to_region(struct dm_region_hash *rh, struct bio *bio)
{
return dm_rh_sector_to_region(rh, bio->bi_sector - rh->target_begin);
}
EXPORT_SYMBOL_GPL(dm_rh_bio_to_region);
void *dm_rh_region_context(struct dm_region *reg)
{
return reg->rh->context;
}
EXPORT_SYMBOL_GPL(dm_rh_region_context);
region_t dm_rh_get_region_key(struct dm_region *reg)
{
return reg->key;
}
EXPORT_SYMBOL_GPL(dm_rh_get_region_key);
sector_t dm_rh_get_region_size(struct dm_region_hash *rh)
{
return rh->region_size;
}
EXPORT_SYMBOL_GPL(dm_rh_get_region_size);
/*
* FIXME: shall we pass in a structure instead of all these args to
* dm_region_hash_create()????
*/
#define RH_HASH_MULT 2654435387U
#define RH_HASH_SHIFT 12
#define MIN_REGIONS 64
struct dm_region_hash *dm_region_hash_create(
void *context, void (*dispatch_bios)(void *context,
struct bio_list *bios),
void (*wakeup_workers)(void *context),
void (*wakeup_all_recovery_waiters)(void *context),
sector_t target_begin, unsigned max_recovery,
struct dm_dirty_log *log, uint32_t region_size,
region_t nr_regions)
{
struct dm_region_hash *rh;
unsigned nr_buckets, max_buckets;
size_t i;
/*
* Calculate a suitable number of buckets for our hash
* table.
*/
max_buckets = nr_regions >> 6;
for (nr_buckets = 128u; nr_buckets < max_buckets; nr_buckets <<= 1)
;
nr_buckets >>= 1;
rh = kmalloc(sizeof(*rh), GFP_KERNEL);
if (!rh) {
DMERR("unable to allocate region hash memory");
return ERR_PTR(-ENOMEM);
}
rh->context = context;
rh->dispatch_bios = dispatch_bios;
rh->wakeup_workers = wakeup_workers;
rh->wakeup_all_recovery_waiters = wakeup_all_recovery_waiters;
rh->target_begin = target_begin;
rh->max_recovery = max_recovery;
rh->log = log;
rh->region_size = region_size;
rh->region_shift = ffs(region_size) - 1;
rwlock_init(&rh->hash_lock);
rh->mask = nr_buckets - 1;
rh->nr_buckets = nr_buckets;
rh->shift = RH_HASH_SHIFT;
rh->prime = RH_HASH_MULT;
rh->buckets = vmalloc(nr_buckets * sizeof(*rh->buckets));
if (!rh->buckets) {
DMERR("unable to allocate region hash bucket memory");
kfree(rh);
return ERR_PTR(-ENOMEM);
}
for (i = 0; i < nr_buckets; i++)
INIT_LIST_HEAD(rh->buckets + i);
spin_lock_init(&rh->region_lock);
sema_init(&rh->recovery_count, 0);
atomic_set(&rh->recovery_in_flight, 0);
INIT_LIST_HEAD(&rh->clean_regions);
INIT_LIST_HEAD(&rh->quiesced_regions);
INIT_LIST_HEAD(&rh->recovered_regions);
INIT_LIST_HEAD(&rh->failed_recovered_regions);
rh->flush_failure = 0;
rh->region_pool = mempool_create_kmalloc_pool(MIN_REGIONS,
sizeof(struct dm_region));
if (!rh->region_pool) {
vfree(rh->buckets);
kfree(rh);
rh = ERR_PTR(-ENOMEM);
}
return rh;
}
EXPORT_SYMBOL_GPL(dm_region_hash_create);
void dm_region_hash_destroy(struct dm_region_hash *rh)
{
unsigned h;
struct dm_region *reg, *nreg;
BUG_ON(!list_empty(&rh->quiesced_regions));
for (h = 0; h < rh->nr_buckets; h++) {
list_for_each_entry_safe(reg, nreg, rh->buckets + h,
hash_list) {
BUG_ON(atomic_read(®->pending));
mempool_free(reg, rh->region_pool);
}
}
if (rh->log)
dm_dirty_log_destroy(rh->log);
if (rh->region_pool)
mempool_destroy(rh->region_pool);
vfree(rh->buckets);
kfree(rh);
}
EXPORT_SYMBOL_GPL(dm_region_hash_destroy);
struct dm_dirty_log *dm_rh_dirty_log(struct dm_region_hash *rh)
{
return rh->log;
}
EXPORT_SYMBOL_GPL(dm_rh_dirty_log);
static unsigned rh_hash(struct dm_region_hash *rh, region_t region)
{
return (unsigned) ((region * rh->prime) >> rh->shift) & rh->mask;
}
static struct dm_region *__rh_lookup(struct dm_region_hash *rh, region_t region)
{
struct dm_region *reg;
struct list_head *bucket = rh->buckets + rh_hash(rh, region);
list_for_each_entry(reg, bucket, hash_list)
if (reg->key == region)
return reg;
return NULL;
}
static void __rh_insert(struct dm_region_hash *rh, struct dm_region *reg)
{
list_add(®->hash_list, rh->buckets + rh_hash(rh, reg->key));
}
static struct dm_region *__rh_alloc(struct dm_region_hash *rh, region_t region)
{
struct dm_region *reg, *nreg;
nreg = mempool_alloc(rh->region_pool, GFP_ATOMIC);
if (unlikely(!nreg))
nreg = kmalloc(sizeof(*nreg), GFP_NOIO | __GFP_NOFAIL);
nreg->state = rh->log->type->in_sync(rh->log, region, 1) ?
DM_RH_CLEAN : DM_RH_NOSYNC;
nreg->rh = rh;
nreg->key = region;
INIT_LIST_HEAD(&nreg->list);
atomic_set(&nreg->pending, 0);
bio_list_init(&nreg->delayed_bios);
write_lock_irq(&rh->hash_lock);
reg = __rh_lookup(rh, region);
if (reg)
/* We lost the race. */
mempool_free(nreg, rh->region_pool);
else {
__rh_insert(rh, nreg);
if (nreg->state == DM_RH_CLEAN) {
spin_lock(&rh->region_lock);
list_add(&nreg->list, &rh->clean_regions);
spin_unlock(&rh->region_lock);
}
reg = nreg;
}
write_unlock_irq(&rh->hash_lock);
return reg;
}
static struct dm_region *__rh_find(struct dm_region_hash *rh, region_t region)
{
struct dm_region *reg;
reg = __rh_lookup(rh, region);
if (!reg) {
read_unlock(&rh->hash_lock);
reg = __rh_alloc(rh, region);
read_lock(&rh->hash_lock);
}
return reg;
}
int dm_rh_get_state(struct dm_region_hash *rh, region_t region, int may_block)
{
int r;
struct dm_region *reg;
read_lock(&rh->hash_lock);
reg = __rh_lookup(rh, region);
read_unlock(&rh->hash_lock);
if (reg)
return reg->state;
/*
* The region wasn't in the hash, so we fall back to the
* dirty log.
*/
r = rh->log->type->in_sync(rh->log, region, may_block);
/*
* Any error from the dirty log (eg. -EWOULDBLOCK) gets
* taken as a DM_RH_NOSYNC
*/
return r == 1 ? DM_RH_CLEAN : DM_RH_NOSYNC;
}
EXPORT_SYMBOL_GPL(dm_rh_get_state);
static void complete_resync_work(struct dm_region *reg, int success)
{
struct dm_region_hash *rh = reg->rh;
rh->log->type->set_region_sync(rh->log, reg->key, success);
/*
* Dispatch the bios before we call 'wake_up_all'.
* This is important because if we are suspending,
* we want to know that recovery is complete and
* the work queue is flushed. If we wake_up_all
* before we dispatch_bios (queue bios and call wake()),
* then we risk suspending before the work queue
* has been properly flushed.
*/
rh->dispatch_bios(rh->context, ®->delayed_bios);
if (atomic_dec_and_test(&rh->recovery_in_flight))
rh->wakeup_all_recovery_waiters(rh->context);
up(&rh->recovery_count);
}
/* dm_rh_mark_nosync
* @ms
* @bio
*
* The bio was written on some mirror(s) but failed on other mirror(s).
* We can successfully endio the bio but should avoid the region being
* marked clean by setting the state DM_RH_NOSYNC.
*
* This function is _not_ safe in interrupt context!
*/
void dm_rh_mark_nosync(struct dm_region_hash *rh, struct bio *bio)
{
unsigned long flags;
struct dm_dirty_log *log = rh->log;
struct dm_region *reg;
region_t region = dm_rh_bio_to_region(rh, bio);
int recovering = 0;
if (bio->bi_rw & REQ_FLUSH) {
rh->flush_failure = 1;
return;
}
if (bio->bi_rw & REQ_DISCARD)
return;
/* We must inform the log that the sync count has changed. */
log->type->set_region_sync(log, region, 0);
read_lock(&rh->hash_lock);
reg = __rh_find(rh, region);
read_unlock(&rh->hash_lock);
/* region hash entry should exist because write was in-flight */
BUG_ON(!reg);
BUG_ON(!list_empty(®->list));
spin_lock_irqsave(&rh->region_lock, flags);
/*
* Possible cases:
* 1) DM_RH_DIRTY
* 2) DM_RH_NOSYNC: was dirty, other preceding writes failed
* 3) DM_RH_RECOVERING: flushing pending writes
* Either case, the region should have not been connected to list.
*/
recovering = (reg->state == DM_RH_RECOVERING);
reg->state = DM_RH_NOSYNC;
BUG_ON(!list_empty(®->list));
spin_unlock_irqrestore(&rh->region_lock, flags);
if (recovering)
complete_resync_work(reg, 0);
}
EXPORT_SYMBOL_GPL(dm_rh_mark_nosync);
void dm_rh_update_states(struct dm_region_hash *rh, int errors_handled)
{
struct dm_region *reg, *next;
LIST_HEAD(clean);
LIST_HEAD(recovered);
LIST_HEAD(failed_recovered);
/*
* Quickly grab the lists.
*/
write_lock_irq(&rh->hash_lock);
spin_lock(&rh->region_lock);
if (!list_empty(&rh->clean_regions)) {
list_splice_init(&rh->clean_regions, &clean);
list_for_each_entry(reg, &clean, list)
list_del(®->hash_list);
}
if (!list_empty(&rh->recovered_regions)) {
list_splice_init(&rh->recovered_regions, &recovered);
list_for_each_entry(reg, &recovered, list)
list_del(®->hash_list);
}
if (!list_empty(&rh->failed_recovered_regions)) {
list_splice_init(&rh->failed_recovered_regions,
&failed_recovered);
list_for_each_entry(reg, &failed_recovered, list)
list_del(®->hash_list);
}
spin_unlock(&rh->region_lock);
write_unlock_irq(&rh->hash_lock);
/*
* All the regions on the recovered and clean lists have
* now been pulled out of the system, so no need to do
* any more locking.
*/
list_for_each_entry_safe(reg, next, &recovered, list) {
rh->log->type->clear_region(rh->log, reg->key);
complete_resync_work(reg, 1);
mempool_free(reg, rh->region_pool);
}
list_for_each_entry_safe(reg, next, &failed_recovered, list) {
complete_resync_work(reg, errors_handled ? 0 : 1);
mempool_free(reg, rh->region_pool);
}
list_for_each_entry_safe(reg, next, &clean, list) {
rh->log->type->clear_region(rh->log, reg->key);
mempool_free(reg, rh->region_pool);
}
rh->log->type->flush(rh->log);
}
EXPORT_SYMBOL_GPL(dm_rh_update_states);
static void rh_inc(struct dm_region_hash *rh, region_t region)
{
struct dm_region *reg;
read_lock(&rh->hash_lock);
reg = __rh_find(rh, region);
spin_lock_irq(&rh->region_lock);
atomic_inc(®->pending);
if (reg->state == DM_RH_CLEAN) {
reg->state = DM_RH_DIRTY;
list_del_init(®->list); /* take off the clean list */
spin_unlock_irq(&rh->region_lock);
rh->log->type->mark_region(rh->log, reg->key);
} else
spin_unlock_irq(&rh->region_lock);
read_unlock(&rh->hash_lock);
}
void dm_rh_inc_pending(struct dm_region_hash *rh, struct bio_list *bios)
{
struct bio *bio;
for (bio = bios->head; bio; bio = bio->bi_next) {
if (bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))
continue;
rh_inc(rh, dm_rh_bio_to_region(rh, bio));
}
}
EXPORT_SYMBOL_GPL(dm_rh_inc_pending);
void dm_rh_dec(struct dm_region_hash *rh, region_t region)
{
unsigned long flags;
struct dm_region *reg;
int should_wake = 0;
read_lock(&rh->hash_lock);
reg = __rh_lookup(rh, region);
read_unlock(&rh->hash_lock);
spin_lock_irqsave(&rh->region_lock, flags);
if (atomic_dec_and_test(®->pending)) {
/*
* There is no pending I/O for this region.
* We can move the region to corresponding list for next action.
* At this point, the region is not yet connected to any list.
*
* If the state is DM_RH_NOSYNC, the region should be kept off
* from clean list.
* The hash entry for DM_RH_NOSYNC will remain in memory
* until the region is recovered or the map is reloaded.
*/
/* do nothing for DM_RH_NOSYNC */
if (unlikely(rh->flush_failure)) {
/*
* If a write flush failed some time ago, we
* don't know whether or not this write made it
* to the disk, so we must resync the device.
*/
reg->state = DM_RH_NOSYNC;
} else if (reg->state == DM_RH_RECOVERING) {
list_add_tail(®->list, &rh->quiesced_regions);
} else if (reg->state == DM_RH_DIRTY) {
reg->state = DM_RH_CLEAN;
list_add(®->list, &rh->clean_regions);
}
should_wake = 1;
}
spin_unlock_irqrestore(&rh->region_lock, flags);
if (should_wake)
rh->wakeup_workers(rh->context);
}
EXPORT_SYMBOL_GPL(dm_rh_dec);
/*
* Starts quiescing a region in preparation for recovery.
*/
static int __rh_recovery_prepare(struct dm_region_hash *rh)
{
int r;
region_t region;
struct dm_region *reg;
/*
* Ask the dirty log what's next.
*/
r = rh->log->type->get_resync_work(rh->log, ®ion);
if (r <= 0)
return r;
/*
* Get this region, and start it quiescing by setting the
* recovering flag.
*/
read_lock(&rh->hash_lock);
reg = __rh_find(rh, region);
read_unlock(&rh->hash_lock);
spin_lock_irq(&rh->region_lock);
reg->state = DM_RH_RECOVERING;
/* Already quiesced ? */
if (atomic_read(®->pending))
list_del_init(®->list);
else
list_move(®->list, &rh->quiesced_regions);
spin_unlock_irq(&rh->region_lock);
return 1;
}
void dm_rh_recovery_prepare(struct dm_region_hash *rh)
{
/* Extra reference to avoid race with dm_rh_stop_recovery */
atomic_inc(&rh->recovery_in_flight);
while (!down_trylock(&rh->recovery_count)) {
atomic_inc(&rh->recovery_in_flight);
if (__rh_recovery_prepare(rh) <= 0) {
atomic_dec(&rh->recovery_in_flight);
up(&rh->recovery_count);
break;
}
}
/* Drop the extra reference */
if (atomic_dec_and_test(&rh->recovery_in_flight))
rh->wakeup_all_recovery_waiters(rh->context);
}
EXPORT_SYMBOL_GPL(dm_rh_recovery_prepare);
/*
* Returns any quiesced regions.
*/
struct dm_region *dm_rh_recovery_start(struct dm_region_hash *rh)
{
struct dm_region *reg = NULL;
spin_lock_irq(&rh->region_lock);
if (!list_empty(&rh->quiesced_regions)) {
reg = list_entry(rh->quiesced_regions.next,
struct dm_region, list);
list_del_init(®->list); /* remove from the quiesced list */
}
spin_unlock_irq(&rh->region_lock);
return reg;
}
EXPORT_SYMBOL_GPL(dm_rh_recovery_start);
void dm_rh_recovery_end(struct dm_region *reg, int success)
{
struct dm_region_hash *rh = reg->rh;
spin_lock_irq(&rh->region_lock);
if (success)
list_add(®->list, ®->rh->recovered_regions);
else
list_add(®->list, ®->rh->failed_recovered_regions);
spin_unlock_irq(&rh->region_lock);
rh->wakeup_workers(rh->context);
}
EXPORT_SYMBOL_GPL(dm_rh_recovery_end);
/* Return recovery in flight count. */
int dm_rh_recovery_in_flight(struct dm_region_hash *rh)
{
return atomic_read(&rh->recovery_in_flight);
}
EXPORT_SYMBOL_GPL(dm_rh_recovery_in_flight);
int dm_rh_flush(struct dm_region_hash *rh)
{
return rh->log->type->flush(rh->log);
}
EXPORT_SYMBOL_GPL(dm_rh_flush);
void dm_rh_delay(struct dm_region_hash *rh, struct bio *bio)
{
struct dm_region *reg;
read_lock(&rh->hash_lock);
reg = __rh_find(rh, dm_rh_bio_to_region(rh, bio));
bio_list_add(®->delayed_bios, bio);
read_unlock(&rh->hash_lock);
}
EXPORT_SYMBOL_GPL(dm_rh_delay);
void dm_rh_stop_recovery(struct dm_region_hash *rh)
{
int i;
/* wait for any recovering regions */
for (i = 0; i < rh->max_recovery; i++)
down(&rh->recovery_count);
}
EXPORT_SYMBOL_GPL(dm_rh_stop_recovery);
void dm_rh_start_recovery(struct dm_region_hash *rh)
{
int i;
for (i = 0; i < rh->max_recovery; i++)
up(&rh->recovery_count);
rh->wakeup_workers(rh->context);
}
EXPORT_SYMBOL_GPL(dm_rh_start_recovery);
MODULE_DESCRIPTION(DM_NAME " region hash");
MODULE_AUTHOR("Joe Thornber/Heinz Mauelshagen <dm-devel@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
NhlalukoG/android_samsung_j7e3g | drivers/media/rc/keymaps/rc-kworld-pc150u.c | 7389 | 2366 | /* kworld-pc150u.c - Keytable for kworld_pc150u Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Kyle Strickland
* (based on kworld-plus-tv-analog.c 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 PC150-U
Kyle Strickland <kyle@kyle.strickland.name>
*/
static struct rc_map_table kworld_pc150u[] = {
{ 0x0c, KEY_MEDIA }, /* Kworld key */
{ 0x16, KEY_EJECTCLOSECD }, /* -> ) */
{ 0x1d, KEY_POWER2 },
{ 0x00, KEY_1 },
{ 0x01, KEY_2 },
{ 0x02, KEY_3 },
{ 0x03, KEY_4 },
{ 0x04, KEY_5 },
{ 0x05, KEY_6 },
{ 0x06, KEY_7 },
{ 0x07, KEY_8 },
{ 0x08, KEY_9 },
{ 0x0a, KEY_0 },
{ 0x09, KEY_AGAIN },
{ 0x14, KEY_MUTE },
{ 0x1e, KEY_LAST },
{ 0x17, KEY_ZOOM },
{ 0x1f, KEY_HOMEPAGE },
{ 0x0e, KEY_ESC },
{ 0x20, KEY_UP },
{ 0x21, KEY_DOWN },
{ 0x42, KEY_LEFT },
{ 0x43, KEY_RIGHT },
{ 0x0b, KEY_ENTER },
{ 0x10, KEY_CHANNELUP },
{ 0x11, KEY_CHANNELDOWN },
{ 0x13, KEY_VOLUMEUP },
{ 0x12, KEY_VOLUMEDOWN },
{ 0x19, KEY_TIME}, /* Timeshift */
{ 0x1a, KEY_STOP},
{ 0x1b, KEY_RECORD},
{ 0x4b, KEY_EMAIL},
{ 0x40, KEY_REWIND},
{ 0x44, KEY_PLAYPAUSE},
{ 0x41, KEY_FORWARD},
{ 0x22, KEY_TEXT},
{ 0x15, KEY_AUDIO}, /* ((*)) */
{ 0x0f, KEY_MODE}, /* display ratio */
{ 0x1c, KEY_SYSRQ}, /* snapshot */
{ 0x4a, KEY_SLEEP}, /* sleep timer */
{ 0x48, KEY_SOUND}, /* switch theater mode */
{ 0x49, KEY_BLUE}, /* A */
{ 0x18, KEY_RED}, /* B */
{ 0x23, KEY_GREEN}, /* C */
};
static struct rc_map_list kworld_pc150u_map = {
.map = {
.scan = kworld_pc150u,
.size = ARRAY_SIZE(kworld_pc150u),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_KWORLD_PC150U,
}
};
static int __init init_rc_map_kworld_pc150u(void)
{
return rc_map_register(&kworld_pc150u_map);
}
static void __exit exit_rc_map_kworld_pc150u(void)
{
rc_map_unregister(&kworld_pc150u_map);
}
module_init(init_rc_map_kworld_pc150u)
module_exit(exit_rc_map_kworld_pc150u)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kyle Strickland <kyle@kyle.strickland.name>");
| gpl-2.0 |
MoKee/android_kernel_sony_tianchi | drivers/staging/octeon/ethernet-mem.c | 7389 | 5110 | /**********************************************************************
* Author: Cavium Networks
*
* Contact: support@caviumnetworks.com
* This file is part of the OCTEON SDK
*
* Copyright (c) 2003-2010 Cavium Networks
*
* This file 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 file is distributed in the hope that it will be useful, but
* AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
* NONINFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* or visit http://www.gnu.org/licenses/.
*
* This file may also be available under a different license from Cavium.
* Contact Cavium Networks for more information
**********************************************************************/
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <asm/octeon/octeon.h>
#include "ethernet-defines.h"
#include <asm/octeon/cvmx-fpa.h>
/**
* cvm_oct_fill_hw_skbuff - fill the supplied hardware pool with skbuffs
* @pool: Pool to allocate an skbuff for
* @size: Size of the buffer needed for the pool
* @elements: Number of buffers to allocate
*
* Returns the actual number of buffers allocated.
*/
static int cvm_oct_fill_hw_skbuff(int pool, int size, int elements)
{
int freed = elements;
while (freed) {
struct sk_buff *skb = dev_alloc_skb(size + 256);
if (unlikely(skb == NULL)) {
pr_warning
("Failed to allocate skb for hardware pool %d\n",
pool);
break;
}
skb_reserve(skb, 256 - (((unsigned long)skb->data) & 0x7f));
*(struct sk_buff **)(skb->data - sizeof(void *)) = skb;
cvmx_fpa_free(skb->data, pool, DONT_WRITEBACK(size / 128));
freed--;
}
return elements - freed;
}
/**
* cvm_oct_free_hw_skbuff- free hardware pool skbuffs
* @pool: Pool to allocate an skbuff for
* @size: Size of the buffer needed for the pool
* @elements: Number of buffers to allocate
*/
static void cvm_oct_free_hw_skbuff(int pool, int size, int elements)
{
char *memory;
do {
memory = cvmx_fpa_alloc(pool);
if (memory) {
struct sk_buff *skb =
*(struct sk_buff **)(memory - sizeof(void *));
elements--;
dev_kfree_skb(skb);
}
} while (memory);
if (elements < 0)
pr_warning("Freeing of pool %u had too many skbuffs (%d)\n",
pool, elements);
else if (elements > 0)
pr_warning("Freeing of pool %u is missing %d skbuffs\n",
pool, elements);
}
/**
* cvm_oct_fill_hw_memory - fill a hardware pool with memory.
* @pool: Pool to populate
* @size: Size of each buffer in the pool
* @elements: Number of buffers to allocate
*
* Returns the actual number of buffers allocated.
*/
static int cvm_oct_fill_hw_memory(int pool, int size, int elements)
{
char *memory;
char *fpa;
int freed = elements;
while (freed) {
/*
* FPA memory must be 128 byte aligned. Since we are
* aligning we need to save the original pointer so we
* can feed it to kfree when the memory is returned to
* the kernel.
*
* We allocate an extra 256 bytes to allow for
* alignment and space for the original pointer saved
* just before the block.
*/
memory = kmalloc(size + 256, GFP_ATOMIC);
if (unlikely(memory == NULL)) {
pr_warning("Unable to allocate %u bytes for FPA pool %d\n",
elements * size, pool);
break;
}
fpa = (char *)(((unsigned long)memory + 256) & ~0x7fUL);
*((char **)fpa - 1) = memory;
cvmx_fpa_free(fpa, pool, 0);
freed--;
}
return elements - freed;
}
/**
* cvm_oct_free_hw_memory - Free memory allocated by cvm_oct_fill_hw_memory
* @pool: FPA pool to free
* @size: Size of each buffer in the pool
* @elements: Number of buffers that should be in the pool
*/
static void cvm_oct_free_hw_memory(int pool, int size, int elements)
{
char *memory;
char *fpa;
do {
fpa = cvmx_fpa_alloc(pool);
if (fpa) {
elements--;
fpa = (char *)phys_to_virt(cvmx_ptr_to_phys(fpa));
memory = *((char **)fpa - 1);
kfree(memory);
}
} while (fpa);
if (elements < 0)
pr_warning("Freeing of pool %u had too many buffers (%d)\n",
pool, elements);
else if (elements > 0)
pr_warning("Warning: Freeing of pool %u is missing %d buffers\n",
pool, elements);
}
int cvm_oct_mem_fill_fpa(int pool, int size, int elements)
{
int freed;
if (USE_SKBUFFS_IN_HW && pool == CVMX_FPA_PACKET_POOL)
freed = cvm_oct_fill_hw_skbuff(pool, size, elements);
else
freed = cvm_oct_fill_hw_memory(pool, size, elements);
return freed;
}
void cvm_oct_mem_empty_fpa(int pool, int size, int elements)
{
if (USE_SKBUFFS_IN_HW && pool == CVMX_FPA_PACKET_POOL)
cvm_oct_free_hw_skbuff(pool, size, elements);
else
cvm_oct_free_hw_memory(pool, size, elements);
}
| gpl-2.0 |
sssemil/linux-3.3.0-a31 | drivers/infiniband/core/sa_query.c | 8157 | 30120 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Voltaire, Inc. All rights reserved.
* Copyright (c) 2006 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/init.h>
#include <linux/err.h>
#include <linux/random.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/kref.h>
#include <linux/idr.h>
#include <linux/workqueue.h>
#include <rdma/ib_pack.h>
#include <rdma/ib_cache.h>
#include "sa.h"
MODULE_AUTHOR("Roland Dreier");
MODULE_DESCRIPTION("InfiniBand subnet administration query support");
MODULE_LICENSE("Dual BSD/GPL");
struct ib_sa_sm_ah {
struct ib_ah *ah;
struct kref ref;
u16 pkey_index;
u8 src_path_mask;
};
struct ib_sa_port {
struct ib_mad_agent *agent;
struct ib_sa_sm_ah *sm_ah;
struct work_struct update_task;
spinlock_t ah_lock;
u8 port_num;
};
struct ib_sa_device {
int start_port, end_port;
struct ib_event_handler event_handler;
struct ib_sa_port port[0];
};
struct ib_sa_query {
void (*callback)(struct ib_sa_query *, int, struct ib_sa_mad *);
void (*release)(struct ib_sa_query *);
struct ib_sa_client *client;
struct ib_sa_port *port;
struct ib_mad_send_buf *mad_buf;
struct ib_sa_sm_ah *sm_ah;
int id;
};
struct ib_sa_service_query {
void (*callback)(int, struct ib_sa_service_rec *, void *);
void *context;
struct ib_sa_query sa_query;
};
struct ib_sa_path_query {
void (*callback)(int, struct ib_sa_path_rec *, void *);
void *context;
struct ib_sa_query sa_query;
};
struct ib_sa_mcmember_query {
void (*callback)(int, struct ib_sa_mcmember_rec *, void *);
void *context;
struct ib_sa_query sa_query;
};
static void ib_sa_add_one(struct ib_device *device);
static void ib_sa_remove_one(struct ib_device *device);
static struct ib_client sa_client = {
.name = "sa",
.add = ib_sa_add_one,
.remove = ib_sa_remove_one
};
static DEFINE_SPINLOCK(idr_lock);
static DEFINE_IDR(query_idr);
static DEFINE_SPINLOCK(tid_lock);
static u32 tid;
#define PATH_REC_FIELD(field) \
.struct_offset_bytes = offsetof(struct ib_sa_path_rec, field), \
.struct_size_bytes = sizeof ((struct ib_sa_path_rec *) 0)->field, \
.field_name = "sa_path_rec:" #field
static const struct ib_field path_rec_table[] = {
{ PATH_REC_FIELD(service_id),
.offset_words = 0,
.offset_bits = 0,
.size_bits = 64 },
{ PATH_REC_FIELD(dgid),
.offset_words = 2,
.offset_bits = 0,
.size_bits = 128 },
{ PATH_REC_FIELD(sgid),
.offset_words = 6,
.offset_bits = 0,
.size_bits = 128 },
{ PATH_REC_FIELD(dlid),
.offset_words = 10,
.offset_bits = 0,
.size_bits = 16 },
{ PATH_REC_FIELD(slid),
.offset_words = 10,
.offset_bits = 16,
.size_bits = 16 },
{ PATH_REC_FIELD(raw_traffic),
.offset_words = 11,
.offset_bits = 0,
.size_bits = 1 },
{ RESERVED,
.offset_words = 11,
.offset_bits = 1,
.size_bits = 3 },
{ PATH_REC_FIELD(flow_label),
.offset_words = 11,
.offset_bits = 4,
.size_bits = 20 },
{ PATH_REC_FIELD(hop_limit),
.offset_words = 11,
.offset_bits = 24,
.size_bits = 8 },
{ PATH_REC_FIELD(traffic_class),
.offset_words = 12,
.offset_bits = 0,
.size_bits = 8 },
{ PATH_REC_FIELD(reversible),
.offset_words = 12,
.offset_bits = 8,
.size_bits = 1 },
{ PATH_REC_FIELD(numb_path),
.offset_words = 12,
.offset_bits = 9,
.size_bits = 7 },
{ PATH_REC_FIELD(pkey),
.offset_words = 12,
.offset_bits = 16,
.size_bits = 16 },
{ PATH_REC_FIELD(qos_class),
.offset_words = 13,
.offset_bits = 0,
.size_bits = 12 },
{ PATH_REC_FIELD(sl),
.offset_words = 13,
.offset_bits = 12,
.size_bits = 4 },
{ PATH_REC_FIELD(mtu_selector),
.offset_words = 13,
.offset_bits = 16,
.size_bits = 2 },
{ PATH_REC_FIELD(mtu),
.offset_words = 13,
.offset_bits = 18,
.size_bits = 6 },
{ PATH_REC_FIELD(rate_selector),
.offset_words = 13,
.offset_bits = 24,
.size_bits = 2 },
{ PATH_REC_FIELD(rate),
.offset_words = 13,
.offset_bits = 26,
.size_bits = 6 },
{ PATH_REC_FIELD(packet_life_time_selector),
.offset_words = 14,
.offset_bits = 0,
.size_bits = 2 },
{ PATH_REC_FIELD(packet_life_time),
.offset_words = 14,
.offset_bits = 2,
.size_bits = 6 },
{ PATH_REC_FIELD(preference),
.offset_words = 14,
.offset_bits = 8,
.size_bits = 8 },
{ RESERVED,
.offset_words = 14,
.offset_bits = 16,
.size_bits = 48 },
};
#define MCMEMBER_REC_FIELD(field) \
.struct_offset_bytes = offsetof(struct ib_sa_mcmember_rec, field), \
.struct_size_bytes = sizeof ((struct ib_sa_mcmember_rec *) 0)->field, \
.field_name = "sa_mcmember_rec:" #field
static const struct ib_field mcmember_rec_table[] = {
{ MCMEMBER_REC_FIELD(mgid),
.offset_words = 0,
.offset_bits = 0,
.size_bits = 128 },
{ MCMEMBER_REC_FIELD(port_gid),
.offset_words = 4,
.offset_bits = 0,
.size_bits = 128 },
{ MCMEMBER_REC_FIELD(qkey),
.offset_words = 8,
.offset_bits = 0,
.size_bits = 32 },
{ MCMEMBER_REC_FIELD(mlid),
.offset_words = 9,
.offset_bits = 0,
.size_bits = 16 },
{ MCMEMBER_REC_FIELD(mtu_selector),
.offset_words = 9,
.offset_bits = 16,
.size_bits = 2 },
{ MCMEMBER_REC_FIELD(mtu),
.offset_words = 9,
.offset_bits = 18,
.size_bits = 6 },
{ MCMEMBER_REC_FIELD(traffic_class),
.offset_words = 9,
.offset_bits = 24,
.size_bits = 8 },
{ MCMEMBER_REC_FIELD(pkey),
.offset_words = 10,
.offset_bits = 0,
.size_bits = 16 },
{ MCMEMBER_REC_FIELD(rate_selector),
.offset_words = 10,
.offset_bits = 16,
.size_bits = 2 },
{ MCMEMBER_REC_FIELD(rate),
.offset_words = 10,
.offset_bits = 18,
.size_bits = 6 },
{ MCMEMBER_REC_FIELD(packet_life_time_selector),
.offset_words = 10,
.offset_bits = 24,
.size_bits = 2 },
{ MCMEMBER_REC_FIELD(packet_life_time),
.offset_words = 10,
.offset_bits = 26,
.size_bits = 6 },
{ MCMEMBER_REC_FIELD(sl),
.offset_words = 11,
.offset_bits = 0,
.size_bits = 4 },
{ MCMEMBER_REC_FIELD(flow_label),
.offset_words = 11,
.offset_bits = 4,
.size_bits = 20 },
{ MCMEMBER_REC_FIELD(hop_limit),
.offset_words = 11,
.offset_bits = 24,
.size_bits = 8 },
{ MCMEMBER_REC_FIELD(scope),
.offset_words = 12,
.offset_bits = 0,
.size_bits = 4 },
{ MCMEMBER_REC_FIELD(join_state),
.offset_words = 12,
.offset_bits = 4,
.size_bits = 4 },
{ MCMEMBER_REC_FIELD(proxy_join),
.offset_words = 12,
.offset_bits = 8,
.size_bits = 1 },
{ RESERVED,
.offset_words = 12,
.offset_bits = 9,
.size_bits = 23 },
};
#define SERVICE_REC_FIELD(field) \
.struct_offset_bytes = offsetof(struct ib_sa_service_rec, field), \
.struct_size_bytes = sizeof ((struct ib_sa_service_rec *) 0)->field, \
.field_name = "sa_service_rec:" #field
static const struct ib_field service_rec_table[] = {
{ SERVICE_REC_FIELD(id),
.offset_words = 0,
.offset_bits = 0,
.size_bits = 64 },
{ SERVICE_REC_FIELD(gid),
.offset_words = 2,
.offset_bits = 0,
.size_bits = 128 },
{ SERVICE_REC_FIELD(pkey),
.offset_words = 6,
.offset_bits = 0,
.size_bits = 16 },
{ SERVICE_REC_FIELD(lease),
.offset_words = 7,
.offset_bits = 0,
.size_bits = 32 },
{ SERVICE_REC_FIELD(key),
.offset_words = 8,
.offset_bits = 0,
.size_bits = 128 },
{ SERVICE_REC_FIELD(name),
.offset_words = 12,
.offset_bits = 0,
.size_bits = 64*8 },
{ SERVICE_REC_FIELD(data8),
.offset_words = 28,
.offset_bits = 0,
.size_bits = 16*8 },
{ SERVICE_REC_FIELD(data16),
.offset_words = 32,
.offset_bits = 0,
.size_bits = 8*16 },
{ SERVICE_REC_FIELD(data32),
.offset_words = 36,
.offset_bits = 0,
.size_bits = 4*32 },
{ SERVICE_REC_FIELD(data64),
.offset_words = 40,
.offset_bits = 0,
.size_bits = 2*64 },
};
static void free_sm_ah(struct kref *kref)
{
struct ib_sa_sm_ah *sm_ah = container_of(kref, struct ib_sa_sm_ah, ref);
ib_destroy_ah(sm_ah->ah);
kfree(sm_ah);
}
static void update_sm_ah(struct work_struct *work)
{
struct ib_sa_port *port =
container_of(work, struct ib_sa_port, update_task);
struct ib_sa_sm_ah *new_ah;
struct ib_port_attr port_attr;
struct ib_ah_attr ah_attr;
if (ib_query_port(port->agent->device, port->port_num, &port_attr)) {
printk(KERN_WARNING "Couldn't query port\n");
return;
}
new_ah = kmalloc(sizeof *new_ah, GFP_KERNEL);
if (!new_ah) {
printk(KERN_WARNING "Couldn't allocate new SM AH\n");
return;
}
kref_init(&new_ah->ref);
new_ah->src_path_mask = (1 << port_attr.lmc) - 1;
new_ah->pkey_index = 0;
if (ib_find_pkey(port->agent->device, port->port_num,
IB_DEFAULT_PKEY_FULL, &new_ah->pkey_index))
printk(KERN_ERR "Couldn't find index for default PKey\n");
memset(&ah_attr, 0, sizeof ah_attr);
ah_attr.dlid = port_attr.sm_lid;
ah_attr.sl = port_attr.sm_sl;
ah_attr.port_num = port->port_num;
new_ah->ah = ib_create_ah(port->agent->qp->pd, &ah_attr);
if (IS_ERR(new_ah->ah)) {
printk(KERN_WARNING "Couldn't create new SM AH\n");
kfree(new_ah);
return;
}
spin_lock_irq(&port->ah_lock);
if (port->sm_ah)
kref_put(&port->sm_ah->ref, free_sm_ah);
port->sm_ah = new_ah;
spin_unlock_irq(&port->ah_lock);
}
static void ib_sa_event(struct ib_event_handler *handler, struct ib_event *event)
{
if (event->event == IB_EVENT_PORT_ERR ||
event->event == IB_EVENT_PORT_ACTIVE ||
event->event == IB_EVENT_LID_CHANGE ||
event->event == IB_EVENT_PKEY_CHANGE ||
event->event == IB_EVENT_SM_CHANGE ||
event->event == IB_EVENT_CLIENT_REREGISTER) {
unsigned long flags;
struct ib_sa_device *sa_dev =
container_of(handler, typeof(*sa_dev), event_handler);
struct ib_sa_port *port =
&sa_dev->port[event->element.port_num - sa_dev->start_port];
if (rdma_port_get_link_layer(handler->device, port->port_num) != IB_LINK_LAYER_INFINIBAND)
return;
spin_lock_irqsave(&port->ah_lock, flags);
if (port->sm_ah)
kref_put(&port->sm_ah->ref, free_sm_ah);
port->sm_ah = NULL;
spin_unlock_irqrestore(&port->ah_lock, flags);
queue_work(ib_wq, &sa_dev->port[event->element.port_num -
sa_dev->start_port].update_task);
}
}
void ib_sa_register_client(struct ib_sa_client *client)
{
atomic_set(&client->users, 1);
init_completion(&client->comp);
}
EXPORT_SYMBOL(ib_sa_register_client);
void ib_sa_unregister_client(struct ib_sa_client *client)
{
ib_sa_client_put(client);
wait_for_completion(&client->comp);
}
EXPORT_SYMBOL(ib_sa_unregister_client);
/**
* ib_sa_cancel_query - try to cancel an SA query
* @id:ID of query to cancel
* @query:query pointer to cancel
*
* Try to cancel an SA query. If the id and query don't match up or
* the query has already completed, nothing is done. Otherwise the
* query is canceled and will complete with a status of -EINTR.
*/
void ib_sa_cancel_query(int id, struct ib_sa_query *query)
{
unsigned long flags;
struct ib_mad_agent *agent;
struct ib_mad_send_buf *mad_buf;
spin_lock_irqsave(&idr_lock, flags);
if (idr_find(&query_idr, id) != query) {
spin_unlock_irqrestore(&idr_lock, flags);
return;
}
agent = query->port->agent;
mad_buf = query->mad_buf;
spin_unlock_irqrestore(&idr_lock, flags);
ib_cancel_mad(agent, mad_buf);
}
EXPORT_SYMBOL(ib_sa_cancel_query);
static u8 get_src_path_mask(struct ib_device *device, u8 port_num)
{
struct ib_sa_device *sa_dev;
struct ib_sa_port *port;
unsigned long flags;
u8 src_path_mask;
sa_dev = ib_get_client_data(device, &sa_client);
if (!sa_dev)
return 0x7f;
port = &sa_dev->port[port_num - sa_dev->start_port];
spin_lock_irqsave(&port->ah_lock, flags);
src_path_mask = port->sm_ah ? port->sm_ah->src_path_mask : 0x7f;
spin_unlock_irqrestore(&port->ah_lock, flags);
return src_path_mask;
}
int ib_init_ah_from_path(struct ib_device *device, u8 port_num,
struct ib_sa_path_rec *rec, struct ib_ah_attr *ah_attr)
{
int ret;
u16 gid_index;
int force_grh;
memset(ah_attr, 0, sizeof *ah_attr);
ah_attr->dlid = be16_to_cpu(rec->dlid);
ah_attr->sl = rec->sl;
ah_attr->src_path_bits = be16_to_cpu(rec->slid) &
get_src_path_mask(device, port_num);
ah_attr->port_num = port_num;
ah_attr->static_rate = rec->rate;
force_grh = rdma_port_get_link_layer(device, port_num) == IB_LINK_LAYER_ETHERNET;
if (rec->hop_limit > 1 || force_grh) {
ah_attr->ah_flags = IB_AH_GRH;
ah_attr->grh.dgid = rec->dgid;
ret = ib_find_cached_gid(device, &rec->sgid, &port_num,
&gid_index);
if (ret)
return ret;
ah_attr->grh.sgid_index = gid_index;
ah_attr->grh.flow_label = be32_to_cpu(rec->flow_label);
ah_attr->grh.hop_limit = rec->hop_limit;
ah_attr->grh.traffic_class = rec->traffic_class;
}
return 0;
}
EXPORT_SYMBOL(ib_init_ah_from_path);
static int alloc_mad(struct ib_sa_query *query, gfp_t gfp_mask)
{
unsigned long flags;
spin_lock_irqsave(&query->port->ah_lock, flags);
if (!query->port->sm_ah) {
spin_unlock_irqrestore(&query->port->ah_lock, flags);
return -EAGAIN;
}
kref_get(&query->port->sm_ah->ref);
query->sm_ah = query->port->sm_ah;
spin_unlock_irqrestore(&query->port->ah_lock, flags);
query->mad_buf = ib_create_send_mad(query->port->agent, 1,
query->sm_ah->pkey_index,
0, IB_MGMT_SA_HDR, IB_MGMT_SA_DATA,
gfp_mask);
if (IS_ERR(query->mad_buf)) {
kref_put(&query->sm_ah->ref, free_sm_ah);
return -ENOMEM;
}
query->mad_buf->ah = query->sm_ah->ah;
return 0;
}
static void free_mad(struct ib_sa_query *query)
{
ib_free_send_mad(query->mad_buf);
kref_put(&query->sm_ah->ref, free_sm_ah);
}
static void init_mad(struct ib_sa_mad *mad, struct ib_mad_agent *agent)
{
unsigned long flags;
memset(mad, 0, sizeof *mad);
mad->mad_hdr.base_version = IB_MGMT_BASE_VERSION;
mad->mad_hdr.mgmt_class = IB_MGMT_CLASS_SUBN_ADM;
mad->mad_hdr.class_version = IB_SA_CLASS_VERSION;
spin_lock_irqsave(&tid_lock, flags);
mad->mad_hdr.tid =
cpu_to_be64(((u64) agent->hi_tid) << 32 | tid++);
spin_unlock_irqrestore(&tid_lock, flags);
}
static int send_mad(struct ib_sa_query *query, int timeout_ms, gfp_t gfp_mask)
{
unsigned long flags;
int ret, id;
retry:
if (!idr_pre_get(&query_idr, gfp_mask))
return -ENOMEM;
spin_lock_irqsave(&idr_lock, flags);
ret = idr_get_new(&query_idr, query, &id);
spin_unlock_irqrestore(&idr_lock, flags);
if (ret == -EAGAIN)
goto retry;
if (ret)
return ret;
query->mad_buf->timeout_ms = timeout_ms;
query->mad_buf->context[0] = query;
query->id = id;
ret = ib_post_send_mad(query->mad_buf, NULL);
if (ret) {
spin_lock_irqsave(&idr_lock, flags);
idr_remove(&query_idr, id);
spin_unlock_irqrestore(&idr_lock, flags);
}
/*
* It's not safe to dereference query any more, because the
* send may already have completed and freed the query in
* another context.
*/
return ret ? ret : id;
}
void ib_sa_unpack_path(void *attribute, struct ib_sa_path_rec *rec)
{
ib_unpack(path_rec_table, ARRAY_SIZE(path_rec_table), attribute, rec);
}
EXPORT_SYMBOL(ib_sa_unpack_path);
static void ib_sa_path_rec_callback(struct ib_sa_query *sa_query,
int status,
struct ib_sa_mad *mad)
{
struct ib_sa_path_query *query =
container_of(sa_query, struct ib_sa_path_query, sa_query);
if (mad) {
struct ib_sa_path_rec rec;
ib_unpack(path_rec_table, ARRAY_SIZE(path_rec_table),
mad->data, &rec);
query->callback(status, &rec, query->context);
} else
query->callback(status, NULL, query->context);
}
static void ib_sa_path_rec_release(struct ib_sa_query *sa_query)
{
kfree(container_of(sa_query, struct ib_sa_path_query, sa_query));
}
/**
* ib_sa_path_rec_get - Start a Path get query
* @client:SA client
* @device:device to send query on
* @port_num: port number to send query on
* @rec:Path Record to send in query
* @comp_mask:component mask to send in query
* @timeout_ms:time to wait for response
* @gfp_mask:GFP mask to use for internal allocations
* @callback:function called when query completes, times out or is
* canceled
* @context:opaque user context passed to callback
* @sa_query:query context, used to cancel query
*
* Send a Path Record Get query to the SA to look up a path. The
* callback function will be called when the query completes (or
* fails); status is 0 for a successful response, -EINTR if the query
* is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
* occurred sending the query. The resp parameter of the callback is
* only valid if status is 0.
*
* If the return value of ib_sa_path_rec_get() is negative, it is an
* error code. Otherwise it is a query ID that can be used to cancel
* the query.
*/
int ib_sa_path_rec_get(struct ib_sa_client *client,
struct ib_device *device, u8 port_num,
struct ib_sa_path_rec *rec,
ib_sa_comp_mask comp_mask,
int timeout_ms, gfp_t gfp_mask,
void (*callback)(int status,
struct ib_sa_path_rec *resp,
void *context),
void *context,
struct ib_sa_query **sa_query)
{
struct ib_sa_path_query *query;
struct ib_sa_device *sa_dev = ib_get_client_data(device, &sa_client);
struct ib_sa_port *port;
struct ib_mad_agent *agent;
struct ib_sa_mad *mad;
int ret;
if (!sa_dev)
return -ENODEV;
port = &sa_dev->port[port_num - sa_dev->start_port];
agent = port->agent;
query = kmalloc(sizeof *query, gfp_mask);
if (!query)
return -ENOMEM;
query->sa_query.port = port;
ret = alloc_mad(&query->sa_query, gfp_mask);
if (ret)
goto err1;
ib_sa_client_get(client);
query->sa_query.client = client;
query->callback = callback;
query->context = context;
mad = query->sa_query.mad_buf->mad;
init_mad(mad, agent);
query->sa_query.callback = callback ? ib_sa_path_rec_callback : NULL;
query->sa_query.release = ib_sa_path_rec_release;
mad->mad_hdr.method = IB_MGMT_METHOD_GET;
mad->mad_hdr.attr_id = cpu_to_be16(IB_SA_ATTR_PATH_REC);
mad->sa_hdr.comp_mask = comp_mask;
ib_pack(path_rec_table, ARRAY_SIZE(path_rec_table), rec, mad->data);
*sa_query = &query->sa_query;
ret = send_mad(&query->sa_query, timeout_ms, gfp_mask);
if (ret < 0)
goto err2;
return ret;
err2:
*sa_query = NULL;
ib_sa_client_put(query->sa_query.client);
free_mad(&query->sa_query);
err1:
kfree(query);
return ret;
}
EXPORT_SYMBOL(ib_sa_path_rec_get);
static void ib_sa_service_rec_callback(struct ib_sa_query *sa_query,
int status,
struct ib_sa_mad *mad)
{
struct ib_sa_service_query *query =
container_of(sa_query, struct ib_sa_service_query, sa_query);
if (mad) {
struct ib_sa_service_rec rec;
ib_unpack(service_rec_table, ARRAY_SIZE(service_rec_table),
mad->data, &rec);
query->callback(status, &rec, query->context);
} else
query->callback(status, NULL, query->context);
}
static void ib_sa_service_rec_release(struct ib_sa_query *sa_query)
{
kfree(container_of(sa_query, struct ib_sa_service_query, sa_query));
}
/**
* ib_sa_service_rec_query - Start Service Record operation
* @client:SA client
* @device:device to send request on
* @port_num: port number to send request on
* @method:SA method - should be get, set, or delete
* @rec:Service Record to send in request
* @comp_mask:component mask to send in request
* @timeout_ms:time to wait for response
* @gfp_mask:GFP mask to use for internal allocations
* @callback:function called when request completes, times out or is
* canceled
* @context:opaque user context passed to callback
* @sa_query:request context, used to cancel request
*
* Send a Service Record set/get/delete to the SA to register,
* unregister or query a service record.
* The callback function will be called when the request completes (or
* fails); status is 0 for a successful response, -EINTR if the query
* is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
* occurred sending the query. The resp parameter of the callback is
* only valid if status is 0.
*
* If the return value of ib_sa_service_rec_query() is negative, it is an
* error code. Otherwise it is a request ID that can be used to cancel
* the query.
*/
int ib_sa_service_rec_query(struct ib_sa_client *client,
struct ib_device *device, u8 port_num, u8 method,
struct ib_sa_service_rec *rec,
ib_sa_comp_mask comp_mask,
int timeout_ms, gfp_t gfp_mask,
void (*callback)(int status,
struct ib_sa_service_rec *resp,
void *context),
void *context,
struct ib_sa_query **sa_query)
{
struct ib_sa_service_query *query;
struct ib_sa_device *sa_dev = ib_get_client_data(device, &sa_client);
struct ib_sa_port *port;
struct ib_mad_agent *agent;
struct ib_sa_mad *mad;
int ret;
if (!sa_dev)
return -ENODEV;
port = &sa_dev->port[port_num - sa_dev->start_port];
agent = port->agent;
if (method != IB_MGMT_METHOD_GET &&
method != IB_MGMT_METHOD_SET &&
method != IB_SA_METHOD_DELETE)
return -EINVAL;
query = kmalloc(sizeof *query, gfp_mask);
if (!query)
return -ENOMEM;
query->sa_query.port = port;
ret = alloc_mad(&query->sa_query, gfp_mask);
if (ret)
goto err1;
ib_sa_client_get(client);
query->sa_query.client = client;
query->callback = callback;
query->context = context;
mad = query->sa_query.mad_buf->mad;
init_mad(mad, agent);
query->sa_query.callback = callback ? ib_sa_service_rec_callback : NULL;
query->sa_query.release = ib_sa_service_rec_release;
mad->mad_hdr.method = method;
mad->mad_hdr.attr_id = cpu_to_be16(IB_SA_ATTR_SERVICE_REC);
mad->sa_hdr.comp_mask = comp_mask;
ib_pack(service_rec_table, ARRAY_SIZE(service_rec_table),
rec, mad->data);
*sa_query = &query->sa_query;
ret = send_mad(&query->sa_query, timeout_ms, gfp_mask);
if (ret < 0)
goto err2;
return ret;
err2:
*sa_query = NULL;
ib_sa_client_put(query->sa_query.client);
free_mad(&query->sa_query);
err1:
kfree(query);
return ret;
}
EXPORT_SYMBOL(ib_sa_service_rec_query);
static void ib_sa_mcmember_rec_callback(struct ib_sa_query *sa_query,
int status,
struct ib_sa_mad *mad)
{
struct ib_sa_mcmember_query *query =
container_of(sa_query, struct ib_sa_mcmember_query, sa_query);
if (mad) {
struct ib_sa_mcmember_rec rec;
ib_unpack(mcmember_rec_table, ARRAY_SIZE(mcmember_rec_table),
mad->data, &rec);
query->callback(status, &rec, query->context);
} else
query->callback(status, NULL, query->context);
}
static void ib_sa_mcmember_rec_release(struct ib_sa_query *sa_query)
{
kfree(container_of(sa_query, struct ib_sa_mcmember_query, sa_query));
}
int ib_sa_mcmember_rec_query(struct ib_sa_client *client,
struct ib_device *device, u8 port_num,
u8 method,
struct ib_sa_mcmember_rec *rec,
ib_sa_comp_mask comp_mask,
int timeout_ms, gfp_t gfp_mask,
void (*callback)(int status,
struct ib_sa_mcmember_rec *resp,
void *context),
void *context,
struct ib_sa_query **sa_query)
{
struct ib_sa_mcmember_query *query;
struct ib_sa_device *sa_dev = ib_get_client_data(device, &sa_client);
struct ib_sa_port *port;
struct ib_mad_agent *agent;
struct ib_sa_mad *mad;
int ret;
if (!sa_dev)
return -ENODEV;
port = &sa_dev->port[port_num - sa_dev->start_port];
agent = port->agent;
query = kmalloc(sizeof *query, gfp_mask);
if (!query)
return -ENOMEM;
query->sa_query.port = port;
ret = alloc_mad(&query->sa_query, gfp_mask);
if (ret)
goto err1;
ib_sa_client_get(client);
query->sa_query.client = client;
query->callback = callback;
query->context = context;
mad = query->sa_query.mad_buf->mad;
init_mad(mad, agent);
query->sa_query.callback = callback ? ib_sa_mcmember_rec_callback : NULL;
query->sa_query.release = ib_sa_mcmember_rec_release;
mad->mad_hdr.method = method;
mad->mad_hdr.attr_id = cpu_to_be16(IB_SA_ATTR_MC_MEMBER_REC);
mad->sa_hdr.comp_mask = comp_mask;
ib_pack(mcmember_rec_table, ARRAY_SIZE(mcmember_rec_table),
rec, mad->data);
*sa_query = &query->sa_query;
ret = send_mad(&query->sa_query, timeout_ms, gfp_mask);
if (ret < 0)
goto err2;
return ret;
err2:
*sa_query = NULL;
ib_sa_client_put(query->sa_query.client);
free_mad(&query->sa_query);
err1:
kfree(query);
return ret;
}
static void send_handler(struct ib_mad_agent *agent,
struct ib_mad_send_wc *mad_send_wc)
{
struct ib_sa_query *query = mad_send_wc->send_buf->context[0];
unsigned long flags;
if (query->callback)
switch (mad_send_wc->status) {
case IB_WC_SUCCESS:
/* No callback -- already got recv */
break;
case IB_WC_RESP_TIMEOUT_ERR:
query->callback(query, -ETIMEDOUT, NULL);
break;
case IB_WC_WR_FLUSH_ERR:
query->callback(query, -EINTR, NULL);
break;
default:
query->callback(query, -EIO, NULL);
break;
}
spin_lock_irqsave(&idr_lock, flags);
idr_remove(&query_idr, query->id);
spin_unlock_irqrestore(&idr_lock, flags);
free_mad(query);
ib_sa_client_put(query->client);
query->release(query);
}
static void recv_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_sa_query *query;
struct ib_mad_send_buf *mad_buf;
mad_buf = (void *) (unsigned long) mad_recv_wc->wc->wr_id;
query = mad_buf->context[0];
if (query->callback) {
if (mad_recv_wc->wc->status == IB_WC_SUCCESS)
query->callback(query,
mad_recv_wc->recv_buf.mad->mad_hdr.status ?
-EINVAL : 0,
(struct ib_sa_mad *) mad_recv_wc->recv_buf.mad);
else
query->callback(query, -EIO, NULL);
}
ib_free_recv_mad(mad_recv_wc);
}
static void ib_sa_add_one(struct ib_device *device)
{
struct ib_sa_device *sa_dev;
int s, e, i;
if (rdma_node_get_transport(device->node_type) != RDMA_TRANSPORT_IB)
return;
if (device->node_type == RDMA_NODE_IB_SWITCH)
s = e = 0;
else {
s = 1;
e = device->phys_port_cnt;
}
sa_dev = kzalloc(sizeof *sa_dev +
(e - s + 1) * sizeof (struct ib_sa_port),
GFP_KERNEL);
if (!sa_dev)
return;
sa_dev->start_port = s;
sa_dev->end_port = e;
for (i = 0; i <= e - s; ++i) {
spin_lock_init(&sa_dev->port[i].ah_lock);
if (rdma_port_get_link_layer(device, i + 1) != IB_LINK_LAYER_INFINIBAND)
continue;
sa_dev->port[i].sm_ah = NULL;
sa_dev->port[i].port_num = i + s;
sa_dev->port[i].agent =
ib_register_mad_agent(device, i + s, IB_QPT_GSI,
NULL, 0, send_handler,
recv_handler, sa_dev);
if (IS_ERR(sa_dev->port[i].agent))
goto err;
INIT_WORK(&sa_dev->port[i].update_task, update_sm_ah);
}
ib_set_client_data(device, &sa_client, sa_dev);
/*
* We register our event handler after everything is set up,
* and then update our cached info after the event handler is
* registered to avoid any problems if a port changes state
* during our initialization.
*/
INIT_IB_EVENT_HANDLER(&sa_dev->event_handler, device, ib_sa_event);
if (ib_register_event_handler(&sa_dev->event_handler))
goto err;
for (i = 0; i <= e - s; ++i)
if (rdma_port_get_link_layer(device, i + 1) == IB_LINK_LAYER_INFINIBAND)
update_sm_ah(&sa_dev->port[i].update_task);
return;
err:
while (--i >= 0)
if (rdma_port_get_link_layer(device, i + 1) == IB_LINK_LAYER_INFINIBAND)
ib_unregister_mad_agent(sa_dev->port[i].agent);
kfree(sa_dev);
return;
}
static void ib_sa_remove_one(struct ib_device *device)
{
struct ib_sa_device *sa_dev = ib_get_client_data(device, &sa_client);
int i;
if (!sa_dev)
return;
ib_unregister_event_handler(&sa_dev->event_handler);
flush_workqueue(ib_wq);
for (i = 0; i <= sa_dev->end_port - sa_dev->start_port; ++i) {
if (rdma_port_get_link_layer(device, i + 1) == IB_LINK_LAYER_INFINIBAND) {
ib_unregister_mad_agent(sa_dev->port[i].agent);
if (sa_dev->port[i].sm_ah)
kref_put(&sa_dev->port[i].sm_ah->ref, free_sm_ah);
}
}
kfree(sa_dev);
}
static int __init ib_sa_init(void)
{
int ret;
get_random_bytes(&tid, sizeof tid);
ret = ib_register_client(&sa_client);
if (ret) {
printk(KERN_ERR "Couldn't register ib_sa client\n");
goto err1;
}
ret = mcast_init();
if (ret) {
printk(KERN_ERR "Couldn't initialize multicast handling\n");
goto err2;
}
return 0;
err2:
ib_unregister_client(&sa_client);
err1:
return ret;
}
static void __exit ib_sa_cleanup(void)
{
mcast_cleanup();
ib_unregister_client(&sa_client);
idr_destroy(&query_idr);
}
module_init(ib_sa_init);
module_exit(ib_sa_cleanup);
| gpl-2.0 |
atinm/android_kernel_samsung_manta | sound/pci/au88x0/au88x0_eq.c | 8157 | 23099 | /***************************************************************************
* au88x0_eq.c
* Aureal Vortex Hardware EQ control/access.
*
* Sun Jun 8 18:19:19 2003
* 2003 Manuel Jander (mjander@users.sourceforge.net)
*
* 02 July 2003: First time something works :)
* November 2003: A3D Bypass code completed but untested.
*
* TODO:
* - Debug (testing)
* - Test peak visualization support.
*
****************************************************************************/
/*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
The Aureal Hardware EQ is found on AU8810 and AU8830 chips only.
it has 4 inputs (2 for general mix, 2 for A3D) and 2 outputs (supposed
to be routed to the codec).
*/
#include "au88x0.h"
#include "au88x0_eq.h"
#include "au88x0_eqdata.c"
#define VORTEX_EQ_BASE 0x2b000
#define VORTEX_EQ_DEST (VORTEX_EQ_BASE + 0x410)
#define VORTEX_EQ_SOURCE (VORTEX_EQ_BASE + 0x430)
#define VORTEX_EQ_CTRL (VORTEX_EQ_BASE + 0x440)
#define VORTEX_BAND_COEFF_SIZE 0x30
/* CEqHw.s */
static void vortex_EqHw_SetTimeConsts(vortex_t * vortex, u16 gain, u16 level)
{
hwwrite(vortex->mmio, 0x2b3c4, gain);
hwwrite(vortex->mmio, 0x2b3c8, level);
}
static inline u16 sign_invert(u16 a)
{
/* -(-32768) -> -32768 so we do -(-32768) -> 32767 to make the result positive */
if (a == (u16)-32768)
return 32767;
else
return -a;
}
static void vortex_EqHw_SetLeftCoefs(vortex_t * vortex, u16 coefs[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i = 0, n /*esp2c */;
for (n = 0; n < eqhw->this04; n++) {
hwwrite(vortex->mmio, 0x2b000 + n * 0x30, coefs[i + 0]);
hwwrite(vortex->mmio, 0x2b004 + n * 0x30, coefs[i + 1]);
if (eqhw->this08 == 0) {
hwwrite(vortex->mmio, 0x2b008 + n * 0x30, coefs[i + 2]);
hwwrite(vortex->mmio, 0x2b00c + n * 0x30, coefs[i + 3]);
hwwrite(vortex->mmio, 0x2b010 + n * 0x30, coefs[i + 4]);
} else {
hwwrite(vortex->mmio, 0x2b008 + n * 0x30, sign_invert(coefs[2 + i]));
hwwrite(vortex->mmio, 0x2b00c + n * 0x30, sign_invert(coefs[3 + i]));
hwwrite(vortex->mmio, 0x2b010 + n * 0x30, sign_invert(coefs[4 + i]));
}
i += 5;
}
}
static void vortex_EqHw_SetRightCoefs(vortex_t * vortex, u16 coefs[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i = 0, n /*esp2c */;
for (n = 0; n < eqhw->this04; n++) {
hwwrite(vortex->mmio, 0x2b1e0 + n * 0x30, coefs[0 + i]);
hwwrite(vortex->mmio, 0x2b1e4 + n * 0x30, coefs[1 + i]);
if (eqhw->this08 == 0) {
hwwrite(vortex->mmio, 0x2b1e8 + n * 0x30, coefs[2 + i]);
hwwrite(vortex->mmio, 0x2b1ec + n * 0x30, coefs[3 + i]);
hwwrite(vortex->mmio, 0x2b1f0 + n * 0x30, coefs[4 + i]);
} else {
hwwrite(vortex->mmio, 0x2b1e8 + n * 0x30, sign_invert(coefs[2 + i]));
hwwrite(vortex->mmio, 0x2b1ec + n * 0x30, sign_invert(coefs[3 + i]));
hwwrite(vortex->mmio, 0x2b1f0 + n * 0x30, sign_invert(coefs[4 + i]));
}
i += 5;
}
}
static void vortex_EqHw_SetLeftStates(vortex_t * vortex, u16 a[], u16 b[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i = 0, ebx;
hwwrite(vortex->mmio, 0x2b3fc, a[0]);
hwwrite(vortex->mmio, 0x2b400, a[1]);
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b014 + (i * 0xc), b[i]);
hwwrite(vortex->mmio, 0x2b018 + (i * 0xc), b[1 + i]);
hwwrite(vortex->mmio, 0x2b01c + (i * 0xc), b[2 + i]);
hwwrite(vortex->mmio, 0x2b020 + (i * 0xc), b[3 + i]);
i += 4;
}
}
static void vortex_EqHw_SetRightStates(vortex_t * vortex, u16 a[], u16 b[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i = 0, ebx;
hwwrite(vortex->mmio, 0x2b404, a[0]);
hwwrite(vortex->mmio, 0x2b408, a[1]);
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b1f4 + (i * 0xc), b[i]);
hwwrite(vortex->mmio, 0x2b1f8 + (i * 0xc), b[1 + i]);
hwwrite(vortex->mmio, 0x2b1fc + (i * 0xc), b[2 + i]);
hwwrite(vortex->mmio, 0x2b200 + (i * 0xc), b[3 + i]);
i += 4;
}
}
#if 0
static void vortex_EqHw_GetTimeConsts(vortex_t * vortex, u16 * a, u16 * b)
{
*a = hwread(vortex->mmio, 0x2b3c4);
*b = hwread(vortex->mmio, 0x2b3c8);
}
static void vortex_EqHw_GetLeftCoefs(vortex_t * vortex, u16 a[])
{
}
static void vortex_EqHw_GetRightCoefs(vortex_t * vortex, u16 a[])
{
}
static void vortex_EqHw_GetLeftStates(vortex_t * vortex, u16 * a, u16 b[])
{
}
static void vortex_EqHw_GetRightStates(vortex_t * vortex, u16 * a, u16 b[])
{
}
#endif
/* Mix Gains */
static void vortex_EqHw_SetBypassGain(vortex_t * vortex, u16 a, u16 b)
{
eqhw_t *eqhw = &(vortex->eq.this04);
if (eqhw->this08 == 0) {
hwwrite(vortex->mmio, 0x2b3d4, a);
hwwrite(vortex->mmio, 0x2b3ec, b);
} else {
hwwrite(vortex->mmio, 0x2b3d4, sign_invert(a));
hwwrite(vortex->mmio, 0x2b3ec, sign_invert(b));
}
}
static void vortex_EqHw_SetA3DBypassGain(vortex_t * vortex, u16 a, u16 b)
{
hwwrite(vortex->mmio, 0x2b3e0, a);
hwwrite(vortex->mmio, 0x2b3f8, b);
}
#if 0
static void vortex_EqHw_SetCurrBypassGain(vortex_t * vortex, u16 a, u16 b)
{
hwwrite(vortex->mmio, 0x2b3d0, a);
hwwrite(vortex->mmio, 0x2b3e8, b);
}
static void vortex_EqHw_SetCurrA3DBypassGain(vortex_t * vortex, u16 a, u16 b)
{
hwwrite(vortex->mmio, 0x2b3dc, a);
hwwrite(vortex->mmio, 0x2b3f4, b);
}
#endif
static void
vortex_EqHw_SetLeftGainsSingleTarget(vortex_t * vortex, u16 index, u16 b)
{
hwwrite(vortex->mmio, 0x2b02c + (index * 0x30), b);
}
static void
vortex_EqHw_SetRightGainsSingleTarget(vortex_t * vortex, u16 index, u16 b)
{
hwwrite(vortex->mmio, 0x2b20c + (index * 0x30), b);
}
static void vortex_EqHw_SetLeftGainsTarget(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx;
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b02c + ebx * 0x30, a[ebx]);
}
}
static void vortex_EqHw_SetRightGainsTarget(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx;
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b20c + ebx * 0x30, a[ebx]);
}
}
static void vortex_EqHw_SetLeftGainsCurrent(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx;
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b028 + ebx * 0x30, a[ebx]);
}
}
static void vortex_EqHw_SetRightGainsCurrent(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx;
for (ebx = 0; ebx < eqhw->this04; ebx++) {
hwwrite(vortex->mmio, 0x2b208 + ebx * 0x30, a[ebx]);
}
}
#if 0
static void vortex_EqHw_GetLeftGainsTarget(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx = 0;
if (eqhw->this04 < 0)
return;
do {
a[ebx] = hwread(vortex->mmio, 0x2b02c + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
}
static void vortex_EqHw_GetRightGainsTarget(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx = 0;
if (eqhw->this04 < 0)
return;
do {
a[ebx] = hwread(vortex->mmio, 0x2b20c + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
}
static void vortex_EqHw_GetLeftGainsCurrent(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx = 0;
if (eqhw->this04 < 0)
return;
do {
a[ebx] = hwread(vortex->mmio, 0x2b028 + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
}
static void vortex_EqHw_GetRightGainsCurrent(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx = 0;
if (eqhw->this04 < 0)
return;
do {
a[ebx] = hwread(vortex->mmio, 0x2b208 + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
}
#endif
/* EQ band levels settings */
static void vortex_EqHw_SetLevels(vortex_t * vortex, u16 peaks[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i;
/* set left peaks */
for (i = 0; i < eqhw->this04; i++) {
hwwrite(vortex->mmio, 0x2b024 + i * VORTEX_BAND_COEFF_SIZE, peaks[i]);
}
hwwrite(vortex->mmio, 0x2b3cc, peaks[eqhw->this04]);
hwwrite(vortex->mmio, 0x2b3d8, peaks[eqhw->this04 + 1]);
/* set right peaks */
for (i = 0; i < eqhw->this04; i++) {
hwwrite(vortex->mmio, 0x2b204 + i * VORTEX_BAND_COEFF_SIZE,
peaks[i + (eqhw->this04 + 2)]);
}
hwwrite(vortex->mmio, 0x2b3e4, peaks[2 + (eqhw->this04 * 2)]);
hwwrite(vortex->mmio, 0x2b3f0, peaks[3 + (eqhw->this04 * 2)]);
}
#if 0
static void vortex_EqHw_GetLevels(vortex_t * vortex, u16 a[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int ebx;
if (eqhw->this04 < 0)
return;
ebx = 0;
do {
a[ebx] = hwread(vortex->mmio, 0x2b024 + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
a[eqhw->this04] = hwread(vortex->mmio, 0x2b3cc);
a[eqhw->this04 + 1] = hwread(vortex->mmio, 0x2b3d8);
ebx = 0;
do {
a[ebx + (eqhw->this04 + 2)] =
hwread(vortex->mmio, 0x2b204 + ebx * 0x30);
ebx++;
}
while (ebx < eqhw->this04);
a[2 + (eqhw->this04 * 2)] = hwread(vortex->mmio, 0x2b3e4);
a[3 + (eqhw->this04 * 2)] = hwread(vortex->mmio, 0x2b3f0);
}
#endif
/* Global Control */
static void vortex_EqHw_SetControlReg(vortex_t * vortex, u32 reg)
{
hwwrite(vortex->mmio, 0x2b440, reg);
}
static void vortex_EqHw_SetSampleRate(vortex_t * vortex, u32 sr)
{
hwwrite(vortex->mmio, 0x2b440, ((sr & 0x1f) << 3) | 0xb800);
}
#if 0
static void vortex_EqHw_GetControlReg(vortex_t * vortex, u32 *reg)
{
*reg = hwread(vortex->mmio, 0x2b440);
}
static void vortex_EqHw_GetSampleRate(vortex_t * vortex, u32 *sr)
{
*sr = (hwread(vortex->mmio, 0x2b440) >> 3) & 0x1f;
}
#endif
static void vortex_EqHw_Enable(vortex_t * vortex)
{
hwwrite(vortex->mmio, VORTEX_EQ_CTRL, 0xf001);
}
static void vortex_EqHw_Disable(vortex_t * vortex)
{
hwwrite(vortex->mmio, VORTEX_EQ_CTRL, 0xf000);
}
/* Reset (zero) buffers */
static void vortex_EqHw_ZeroIO(vortex_t * vortex)
{
int i;
for (i = 0; i < 0x8; i++)
hwwrite(vortex->mmio, VORTEX_EQ_DEST + (i << 2), 0x0);
for (i = 0; i < 0x4; i++)
hwwrite(vortex->mmio, VORTEX_EQ_SOURCE + (i << 2), 0x0);
}
static void vortex_EqHw_ZeroA3DIO(vortex_t * vortex)
{
int i;
for (i = 0; i < 0x4; i++)
hwwrite(vortex->mmio, VORTEX_EQ_DEST + (i << 2), 0x0);
}
static void vortex_EqHw_ZeroState(vortex_t * vortex)
{
vortex_EqHw_SetControlReg(vortex, 0);
vortex_EqHw_ZeroIO(vortex);
hwwrite(vortex->mmio, 0x2b3c0, 0);
vortex_EqHw_SetTimeConsts(vortex, 0, 0);
vortex_EqHw_SetLeftCoefs(vortex, asEqCoefsZeros);
vortex_EqHw_SetRightCoefs(vortex, asEqCoefsZeros);
vortex_EqHw_SetLeftGainsCurrent(vortex, eq_gains_zero);
vortex_EqHw_SetRightGainsCurrent(vortex, eq_gains_zero);
vortex_EqHw_SetLeftGainsTarget(vortex, eq_gains_zero);
vortex_EqHw_SetRightGainsTarget(vortex, eq_gains_zero);
vortex_EqHw_SetBypassGain(vortex, 0, 0);
//vortex_EqHw_SetCurrBypassGain(vortex, 0, 0);
vortex_EqHw_SetA3DBypassGain(vortex, 0, 0);
//vortex_EqHw_SetCurrA3DBypassGain(vortex, 0, 0);
vortex_EqHw_SetLeftStates(vortex, eq_states_zero, asEqOutStateZeros);
vortex_EqHw_SetRightStates(vortex, eq_states_zero, asEqOutStateZeros);
vortex_EqHw_SetLevels(vortex, (u16 *) eq_levels);
}
/* Program coeficients as pass through */
static void vortex_EqHw_ProgramPipe(vortex_t * vortex)
{
vortex_EqHw_SetTimeConsts(vortex, 0, 0);
vortex_EqHw_SetLeftCoefs(vortex, asEqCoefsPipes);
vortex_EqHw_SetRightCoefs(vortex, asEqCoefsPipes);
vortex_EqHw_SetLeftGainsCurrent(vortex, eq_gains_current);
vortex_EqHw_SetRightGainsCurrent(vortex, eq_gains_current);
vortex_EqHw_SetLeftGainsTarget(vortex, eq_gains_current);
vortex_EqHw_SetRightGainsTarget(vortex, eq_gains_current);
}
/* Program EQ block as 10 band Equalizer */
static void
vortex_EqHw_Program10Band(vortex_t * vortex, auxxEqCoeffSet_t * coefset)
{
vortex_EqHw_SetTimeConsts(vortex, 0xc, 0x7fe0);
vortex_EqHw_SetLeftCoefs(vortex, coefset->LeftCoefs);
vortex_EqHw_SetRightCoefs(vortex, coefset->RightCoefs);
vortex_EqHw_SetLeftGainsCurrent(vortex, coefset->LeftGains);
vortex_EqHw_SetRightGainsTarget(vortex, coefset->RightGains);
vortex_EqHw_SetLeftGainsTarget(vortex, coefset->LeftGains);
vortex_EqHw_SetRightGainsCurrent(vortex, coefset->RightGains);
}
/* Read all EQ peaks. (think VU meter) */
static void vortex_EqHw_GetTenBandLevels(vortex_t * vortex, u16 peaks[])
{
eqhw_t *eqhw = &(vortex->eq.this04);
int i;
if (eqhw->this04 <= 0)
return;
for (i = 0; i < eqhw->this04; i++)
peaks[i] = hwread(vortex->mmio, 0x2B024 + i * 0x30);
for (i = 0; i < eqhw->this04; i++)
peaks[i + eqhw->this04] =
hwread(vortex->mmio, 0x2B204 + i * 0x30);
}
/* CEqlzr.s */
static int vortex_Eqlzr_GetLeftGain(vortex_t * vortex, u16 index, u16 * gain)
{
eqlzr_t *eq = &(vortex->eq);
if (eq->this28) {
*gain = eq->this130[index];
return 0;
}
return 1;
}
static void vortex_Eqlzr_SetLeftGain(vortex_t * vortex, u16 index, u16 gain)
{
eqlzr_t *eq = &(vortex->eq);
if (eq->this28 == 0)
return;
eq->this130[index] = gain;
if (eq->this54)
return;
vortex_EqHw_SetLeftGainsSingleTarget(vortex, index, gain);
}
static int vortex_Eqlzr_GetRightGain(vortex_t * vortex, u16 index, u16 * gain)
{
eqlzr_t *eq = &(vortex->eq);
if (eq->this28) {
*gain = eq->this130[index + eq->this10];
return 0;
}
return 1;
}
static void vortex_Eqlzr_SetRightGain(vortex_t * vortex, u16 index, u16 gain)
{
eqlzr_t *eq = &(vortex->eq);
if (eq->this28 == 0)
return;
eq->this130[index + eq->this10] = gain;
if (eq->this54)
return;
vortex_EqHw_SetRightGainsSingleTarget(vortex, index, gain);
}
#if 0
static int
vortex_Eqlzr_GetAllBands(vortex_t * vortex, u16 * gains, s32 *cnt)
{
eqlzr_t *eq = &(vortex->eq);
int si = 0;
if (eq->this10 == 0)
return 1;
{
if (vortex_Eqlzr_GetLeftGain(vortex, si, &gains[si]))
return 1;
if (vortex_Eqlzr_GetRightGain
(vortex, si, &gains[si + eq->this10]))
return 1;
si++;
}
while (eq->this10 > si) ;
*cnt = si * 2;
return 0;
}
#endif
static int vortex_Eqlzr_SetAllBandsFromActiveCoeffSet(vortex_t * vortex)
{
eqlzr_t *eq = &(vortex->eq);
vortex_EqHw_SetLeftGainsTarget(vortex, eq->this130);
vortex_EqHw_SetRightGainsTarget(vortex, &(eq->this130[eq->this10]));
return 0;
}
static int
vortex_Eqlzr_SetAllBands(vortex_t * vortex, u16 gains[], s32 count)
{
eqlzr_t *eq = &(vortex->eq);
int i;
if (((eq->this10) * 2 != count) || (eq->this28 == 0))
return 1;
for (i = 0; i < count; i++) {
eq->this130[i] = gains[i];
}
if (eq->this54)
return 0;
return vortex_Eqlzr_SetAllBandsFromActiveCoeffSet(vortex);
}
static void
vortex_Eqlzr_SetA3dBypassGain(vortex_t * vortex, u32 a, u32 b)
{
eqlzr_t *eq = &(vortex->eq);
u32 eax, ebx;
eq->this58 = a;
eq->this5c = b;
if (eq->this54)
eax = eq->this0e;
else
eax = eq->this0a;
ebx = (eax * eq->this58) >> 0x10;
eax = (eax * eq->this5c) >> 0x10;
vortex_EqHw_SetA3DBypassGain(vortex, ebx, eax);
}
static void vortex_Eqlzr_ProgramA3dBypassGain(vortex_t * vortex)
{
eqlzr_t *eq = &(vortex->eq);
u32 eax, ebx;
if (eq->this54)
eax = eq->this0e;
else
eax = eq->this0a;
ebx = (eax * eq->this58) >> 0x10;
eax = (eax * eq->this5c) >> 0x10;
vortex_EqHw_SetA3DBypassGain(vortex, ebx, eax);
}
static void vortex_Eqlzr_ShutDownA3d(vortex_t * vortex)
{
if (vortex != NULL)
vortex_EqHw_ZeroA3DIO(vortex);
}
static void vortex_Eqlzr_SetBypass(vortex_t * vortex, u32 bp)
{
eqlzr_t *eq = &(vortex->eq);
if ((eq->this28) && (bp == 0)) {
/* EQ enabled */
vortex_Eqlzr_SetAllBandsFromActiveCoeffSet(vortex);
vortex_EqHw_SetBypassGain(vortex, eq->this08, eq->this08);
} else {
/* EQ disabled. */
vortex_EqHw_SetLeftGainsTarget(vortex, eq->this14_array);
vortex_EqHw_SetRightGainsTarget(vortex, eq->this14_array);
vortex_EqHw_SetBypassGain(vortex, eq->this0c, eq->this0c);
}
vortex_Eqlzr_ProgramA3dBypassGain(vortex);
}
static void vortex_Eqlzr_ReadAndSetActiveCoefSet(vortex_t * vortex)
{
eqlzr_t *eq = &(vortex->eq);
/* Set EQ BiQuad filter coeficients */
memcpy(&(eq->coefset), &asEqCoefsNormal, sizeof(auxxEqCoeffSet_t));
/* Set EQ Band gain levels and dump into hardware registers. */
vortex_Eqlzr_SetAllBands(vortex, eq_gains_normal, eq->this10 * 2);
}
static int vortex_Eqlzr_GetAllPeaks(vortex_t * vortex, u16 * peaks, int *count)
{
eqlzr_t *eq = &(vortex->eq);
if (eq->this10 == 0)
return 1;
*count = eq->this10 * 2;
vortex_EqHw_GetTenBandLevels(vortex, peaks);
return 0;
}
#if 0
static auxxEqCoeffSet_t *vortex_Eqlzr_GetActiveCoefSet(vortex_t * vortex)
{
eqlzr_t *eq = &(vortex->eq);
return (&(eq->coefset));
}
#endif
static void vortex_Eqlzr_init(vortex_t * vortex)
{
eqlzr_t *eq = &(vortex->eq);
/* Object constructor */
//eq->this04 = 0;
eq->this08 = 0; /* Bypass gain with EQ in use. */
eq->this0a = 0x5999;
eq->this0c = 0x5999; /* Bypass gain with EQ disabled. */
eq->this0e = 0x5999;
eq->this10 = 0xa; /* 10 eq frequency bands. */
eq->this04.this04 = eq->this10;
eq->this28 = 0x1; /* if 1 => Allow read access to this130 (gains) */
eq->this54 = 0x0; /* if 1 => Dont Allow access to hardware (gains) */
eq->this58 = 0xffff;
eq->this5c = 0xffff;
/* Set gains. */
memset(eq->this14_array, 0, sizeof(eq->this14_array));
/* Actual init. */
vortex_EqHw_ZeroState(vortex);
vortex_EqHw_SetSampleRate(vortex, 0x11);
vortex_Eqlzr_ReadAndSetActiveCoefSet(vortex);
vortex_EqHw_Program10Band(vortex, &(eq->coefset));
vortex_Eqlzr_SetBypass(vortex, eq->this54);
vortex_Eqlzr_SetA3dBypassGain(vortex, 0, 0);
vortex_EqHw_Enable(vortex);
}
static void vortex_Eqlzr_shutdown(vortex_t * vortex)
{
vortex_Eqlzr_ShutDownA3d(vortex);
vortex_EqHw_ProgramPipe(vortex);
vortex_EqHw_Disable(vortex);
}
/* ALSA interface */
/* Control interface */
#define snd_vortex_eqtoggle_info snd_ctl_boolean_mono_info
static int
snd_vortex_eqtoggle_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
vortex_t *vortex = snd_kcontrol_chip(kcontrol);
eqlzr_t *eq = &(vortex->eq);
//int i = kcontrol->private_value;
ucontrol->value.integer.value[0] = eq->this54 ? 0 : 1;
return 0;
}
static int
snd_vortex_eqtoggle_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
vortex_t *vortex = snd_kcontrol_chip(kcontrol);
eqlzr_t *eq = &(vortex->eq);
//int i = kcontrol->private_value;
eq->this54 = ucontrol->value.integer.value[0] ? 0 : 1;
vortex_Eqlzr_SetBypass(vortex, eq->this54);
return 1; /* Allways changes */
}
static struct snd_kcontrol_new vortex_eqtoggle_kcontrol __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "EQ Enable",
.index = 0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = 0,
.info = snd_vortex_eqtoggle_info,
.get = snd_vortex_eqtoggle_get,
.put = snd_vortex_eqtoggle_put
};
static int
snd_vortex_eq_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 = 0x0000;
uinfo->value.integer.max = 0x7fff;
return 0;
}
static int
snd_vortex_eq_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
vortex_t *vortex = snd_kcontrol_chip(kcontrol);
int i = kcontrol->private_value;
u16 gainL = 0, gainR = 0;
vortex_Eqlzr_GetLeftGain(vortex, i, &gainL);
vortex_Eqlzr_GetRightGain(vortex, i, &gainR);
ucontrol->value.integer.value[0] = gainL;
ucontrol->value.integer.value[1] = gainR;
return 0;
}
static int
snd_vortex_eq_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
vortex_t *vortex = snd_kcontrol_chip(kcontrol);
int changed = 0, i = kcontrol->private_value;
u16 gainL = 0, gainR = 0;
vortex_Eqlzr_GetLeftGain(vortex, i, &gainL);
vortex_Eqlzr_GetRightGain(vortex, i, &gainR);
if (gainL != ucontrol->value.integer.value[0]) {
vortex_Eqlzr_SetLeftGain(vortex, i,
ucontrol->value.integer.value[0]);
changed = 1;
}
if (gainR != ucontrol->value.integer.value[1]) {
vortex_Eqlzr_SetRightGain(vortex, i,
ucontrol->value.integer.value[1]);
changed = 1;
}
return changed;
}
static struct snd_kcontrol_new vortex_eq_kcontrol __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = " .",
.index = 0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = 0,
.info = snd_vortex_eq_info,
.get = snd_vortex_eq_get,
.put = snd_vortex_eq_put
};
static int
snd_vortex_peaks_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 20;
uinfo->value.integer.min = 0x0000;
uinfo->value.integer.max = 0x7fff;
return 0;
}
static int
snd_vortex_peaks_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
vortex_t *vortex = snd_kcontrol_chip(kcontrol);
int i, count = 0;
u16 peaks[20];
vortex_Eqlzr_GetAllPeaks(vortex, peaks, &count);
if (count != 20) {
printk(KERN_ERR "vortex: peak count error 20 != %d \n", count);
return -1;
}
for (i = 0; i < 20; i++)
ucontrol->value.integer.value[i] = peaks[i];
return 0;
}
static struct snd_kcontrol_new vortex_levels_kcontrol __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "EQ Peaks",
.access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
.info = snd_vortex_peaks_info,
.get = snd_vortex_peaks_get,
};
/* EQ band gain labels. */
static char *EqBandLabels[10] __devinitdata = {
"EQ0 31Hz\0",
"EQ1 63Hz\0",
"EQ2 125Hz\0",
"EQ3 250Hz\0",
"EQ4 500Hz\0",
"EQ5 1KHz\0",
"EQ6 2KHz\0",
"EQ7 4KHz\0",
"EQ8 8KHz\0",
"EQ9 16KHz\0",
};
/* ALSA driver entry points. Init and exit. */
static int __devinit vortex_eq_init(vortex_t * vortex)
{
struct snd_kcontrol *kcontrol;
int err, i;
vortex_Eqlzr_init(vortex);
if ((kcontrol =
snd_ctl_new1(&vortex_eqtoggle_kcontrol, vortex)) == NULL)
return -ENOMEM;
kcontrol->private_value = 0;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
/* EQ gain controls */
for (i = 0; i < 10; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_eq_kcontrol, vortex)) == NULL)
return -ENOMEM;
snprintf(kcontrol->id.name, sizeof(kcontrol->id.name),
"%s Playback Volume", EqBandLabels[i]);
kcontrol->private_value = i;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
//vortex->eqctrl[i] = kcontrol;
}
/* EQ band levels */
if ((kcontrol = snd_ctl_new1(&vortex_levels_kcontrol, vortex)) == NULL)
return -ENOMEM;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
return 0;
}
static int vortex_eq_free(vortex_t * vortex)
{
/*
//FIXME: segfault because vortex->eqctrl[i] == 4
int i;
for (i=0; i<10; i++) {
if (vortex->eqctrl[i])
snd_ctl_remove(vortex->card, vortex->eqctrl[i]);
}
*/
vortex_Eqlzr_shutdown(vortex);
return 0;
}
/* End */
| gpl-2.0 |
kevinzhang1986/android_kernel_oneplus_msm8994 | arch/x86/mm/dump_pagetables.c | 9181 | 9278 | /*
* Debug helper to dump the current kernel pagetables of the system
* so that we can see what the various memory ranges are set to.
*
* (C) Copyright 2008 Intel Corporation
*
* Author: Arjan van de Ven <arjan@linux.intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*/
#include <linux/debugfs.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <asm/pgtable.h>
/*
* The dumper groups pagetable entries of the same type into one, and for
* that it needs to keep some state when walking, and flush this state
* when a "break" in the continuity is found.
*/
struct pg_state {
int level;
pgprot_t current_prot;
unsigned long start_address;
unsigned long current_address;
const struct addr_marker *marker;
};
struct addr_marker {
unsigned long start_address;
const char *name;
};
/* indices for address_markers; keep sync'd w/ address_markers below */
enum address_markers_idx {
USER_SPACE_NR = 0,
#ifdef CONFIG_X86_64
KERNEL_SPACE_NR,
LOW_KERNEL_NR,
VMALLOC_START_NR,
VMEMMAP_START_NR,
HIGH_KERNEL_NR,
MODULES_VADDR_NR,
MODULES_END_NR,
#else
KERNEL_SPACE_NR,
VMALLOC_START_NR,
VMALLOC_END_NR,
# ifdef CONFIG_HIGHMEM
PKMAP_BASE_NR,
# endif
FIXADDR_START_NR,
#endif
};
/* Address space markers hints */
static struct addr_marker address_markers[] = {
{ 0, "User Space" },
#ifdef CONFIG_X86_64
{ 0x8000000000000000UL, "Kernel Space" },
{ PAGE_OFFSET, "Low Kernel Mapping" },
{ VMALLOC_START, "vmalloc() Area" },
{ VMEMMAP_START, "Vmemmap" },
{ __START_KERNEL_map, "High Kernel Mapping" },
{ MODULES_VADDR, "Modules" },
{ MODULES_END, "End Modules" },
#else
{ PAGE_OFFSET, "Kernel Mapping" },
{ 0/* VMALLOC_START */, "vmalloc() Area" },
{ 0/*VMALLOC_END*/, "vmalloc() End" },
# ifdef CONFIG_HIGHMEM
{ 0/*PKMAP_BASE*/, "Persisent kmap() Area" },
# endif
{ 0/*FIXADDR_START*/, "Fixmap Area" },
#endif
{ -1, NULL } /* End of list */
};
/* Multipliers for offsets within the PTEs */
#define PTE_LEVEL_MULT (PAGE_SIZE)
#define PMD_LEVEL_MULT (PTRS_PER_PTE * PTE_LEVEL_MULT)
#define PUD_LEVEL_MULT (PTRS_PER_PMD * PMD_LEVEL_MULT)
#define PGD_LEVEL_MULT (PTRS_PER_PUD * PUD_LEVEL_MULT)
/*
* Print a readable form of a pgprot_t to the seq_file
*/
static void printk_prot(struct seq_file *m, pgprot_t prot, int level)
{
pgprotval_t pr = pgprot_val(prot);
static const char * const level_name[] =
{ "cr3", "pgd", "pud", "pmd", "pte" };
if (!pgprot_val(prot)) {
/* Not present */
seq_printf(m, " ");
} else {
if (pr & _PAGE_USER)
seq_printf(m, "USR ");
else
seq_printf(m, " ");
if (pr & _PAGE_RW)
seq_printf(m, "RW ");
else
seq_printf(m, "ro ");
if (pr & _PAGE_PWT)
seq_printf(m, "PWT ");
else
seq_printf(m, " ");
if (pr & _PAGE_PCD)
seq_printf(m, "PCD ");
else
seq_printf(m, " ");
/* Bit 9 has a different meaning on level 3 vs 4 */
if (level <= 3) {
if (pr & _PAGE_PSE)
seq_printf(m, "PSE ");
else
seq_printf(m, " ");
} else {
if (pr & _PAGE_PAT)
seq_printf(m, "pat ");
else
seq_printf(m, " ");
}
if (pr & _PAGE_GLOBAL)
seq_printf(m, "GLB ");
else
seq_printf(m, " ");
if (pr & _PAGE_NX)
seq_printf(m, "NX ");
else
seq_printf(m, "x ");
}
seq_printf(m, "%s\n", level_name[level]);
}
/*
* On 64 bits, sign-extend the 48 bit address to 64 bit
*/
static unsigned long normalize_addr(unsigned long u)
{
#ifdef CONFIG_X86_64
return (signed long)(u << 16) >> 16;
#else
return u;
#endif
}
/*
* This function gets called on a break in a continuous series
* of PTE entries; the next one is different so we need to
* print what we collected so far.
*/
static void note_page(struct seq_file *m, struct pg_state *st,
pgprot_t new_prot, int level)
{
pgprotval_t prot, cur;
static const char units[] = "KMGTPE";
/*
* If we have a "break" in the series, we need to flush the state that
* we have now. "break" is either changing perms, levels or
* address space marker.
*/
prot = pgprot_val(new_prot) & PTE_FLAGS_MASK;
cur = pgprot_val(st->current_prot) & PTE_FLAGS_MASK;
if (!st->level) {
/* First entry */
st->current_prot = new_prot;
st->level = level;
st->marker = address_markers;
seq_printf(m, "---[ %s ]---\n", st->marker->name);
} else if (prot != cur || level != st->level ||
st->current_address >= st->marker[1].start_address) {
const char *unit = units;
unsigned long delta;
int width = sizeof(unsigned long) * 2;
/*
* Now print the actual finished series
*/
seq_printf(m, "0x%0*lx-0x%0*lx ",
width, st->start_address,
width, st->current_address);
delta = (st->current_address - st->start_address) >> 10;
while (!(delta & 1023) && unit[1]) {
delta >>= 10;
unit++;
}
seq_printf(m, "%9lu%c ", delta, *unit);
printk_prot(m, st->current_prot, st->level);
/*
* We print markers for special areas of address space,
* such as the start of vmalloc space etc.
* This helps in the interpretation.
*/
if (st->current_address >= st->marker[1].start_address) {
st->marker++;
seq_printf(m, "---[ %s ]---\n", st->marker->name);
}
st->start_address = st->current_address;
st->current_prot = new_prot;
st->level = level;
}
}
static void walk_pte_level(struct seq_file *m, struct pg_state *st, pmd_t addr,
unsigned long P)
{
int i;
pte_t *start;
start = (pte_t *) pmd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PTE; i++) {
pgprot_t prot = pte_pgprot(*start);
st->current_address = normalize_addr(P + i * PTE_LEVEL_MULT);
note_page(m, st, prot, 4);
start++;
}
}
#if PTRS_PER_PMD > 1
static void walk_pmd_level(struct seq_file *m, struct pg_state *st, pud_t addr,
unsigned long P)
{
int i;
pmd_t *start;
start = (pmd_t *) pud_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PMD; i++) {
st->current_address = normalize_addr(P + i * PMD_LEVEL_MULT);
if (!pmd_none(*start)) {
pgprotval_t prot = pmd_val(*start) & PTE_FLAGS_MASK;
if (pmd_large(*start) || !pmd_present(*start))
note_page(m, st, __pgprot(prot), 3);
else
walk_pte_level(m, st, *start,
P + i * PMD_LEVEL_MULT);
} else
note_page(m, st, __pgprot(0), 3);
start++;
}
}
#else
#define walk_pmd_level(m,s,a,p) walk_pte_level(m,s,__pmd(pud_val(a)),p)
#define pud_large(a) pmd_large(__pmd(pud_val(a)))
#define pud_none(a) pmd_none(__pmd(pud_val(a)))
#endif
#if PTRS_PER_PUD > 1
static void walk_pud_level(struct seq_file *m, struct pg_state *st, pgd_t addr,
unsigned long P)
{
int i;
pud_t *start;
start = (pud_t *) pgd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PUD; i++) {
st->current_address = normalize_addr(P + i * PUD_LEVEL_MULT);
if (!pud_none(*start)) {
pgprotval_t prot = pud_val(*start) & PTE_FLAGS_MASK;
if (pud_large(*start) || !pud_present(*start))
note_page(m, st, __pgprot(prot), 2);
else
walk_pmd_level(m, st, *start,
P + i * PUD_LEVEL_MULT);
} else
note_page(m, st, __pgprot(0), 2);
start++;
}
}
#else
#define walk_pud_level(m,s,a,p) walk_pmd_level(m,s,__pud(pgd_val(a)),p)
#define pgd_large(a) pud_large(__pud(pgd_val(a)))
#define pgd_none(a) pud_none(__pud(pgd_val(a)))
#endif
static void walk_pgd_level(struct seq_file *m)
{
#ifdef CONFIG_X86_64
pgd_t *start = (pgd_t *) &init_level4_pgt;
#else
pgd_t *start = swapper_pg_dir;
#endif
int i;
struct pg_state st;
memset(&st, 0, sizeof(st));
for (i = 0; i < PTRS_PER_PGD; i++) {
st.current_address = normalize_addr(i * PGD_LEVEL_MULT);
if (!pgd_none(*start)) {
pgprotval_t prot = pgd_val(*start) & PTE_FLAGS_MASK;
if (pgd_large(*start) || !pgd_present(*start))
note_page(m, &st, __pgprot(prot), 1);
else
walk_pud_level(m, &st, *start,
i * PGD_LEVEL_MULT);
} else
note_page(m, &st, __pgprot(0), 1);
start++;
}
/* Flush out the last page */
st.current_address = normalize_addr(PTRS_PER_PGD*PGD_LEVEL_MULT);
note_page(m, &st, __pgprot(0), 0);
}
static int ptdump_show(struct seq_file *m, void *v)
{
walk_pgd_level(m);
return 0;
}
static int ptdump_open(struct inode *inode, struct file *filp)
{
return single_open(filp, ptdump_show, NULL);
}
static const struct file_operations ptdump_fops = {
.open = ptdump_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int pt_dump_init(void)
{
struct dentry *pe;
#ifdef CONFIG_X86_32
/* Not a compile-time constant on x86-32 */
address_markers[VMALLOC_START_NR].start_address = VMALLOC_START;
address_markers[VMALLOC_END_NR].start_address = VMALLOC_END;
# ifdef CONFIG_HIGHMEM
address_markers[PKMAP_BASE_NR].start_address = PKMAP_BASE;
# endif
address_markers[FIXADDR_START_NR].start_address = FIXADDR_START;
#endif
pe = debugfs_create_file("kernel_page_tables", 0600, NULL, NULL,
&ptdump_fops);
if (!pe)
return -ENOMEM;
return 0;
}
__initcall(pt_dump_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arjan van de Ven <arjan@linux.intel.com>");
MODULE_DESCRIPTION("Kernel debugging helper that dumps pagetables");
| gpl-2.0 |
thesawolf/android_kernel_rockchip_rk3188 | arch/powerpc/platforms/44x/idle.c | 14045 | 1547 | /*
* Copyright 2008 IBM Corp.
*
* Based on arch/powerpc/platforms/pasemi/idle.c:
* Copyright (C) 2006-2007 PA Semi, Inc
*
* Added by: Jerone Young <jyoung5@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/of.h>
#include <linux/kernel.h>
#include <asm/machdep.h>
static int mode_spin;
static void ppc44x_idle(void)
{
unsigned long msr_save;
msr_save = mfmsr();
/* set wait state MSR */
mtmsr(msr_save|MSR_WE|MSR_EE|MSR_CE|MSR_DE);
isync();
/* return to initial state */
mtmsr(msr_save);
isync();
}
int __init ppc44x_idle_init(void)
{
if (!mode_spin) {
/* If we are not setting spin mode
then we set to wait mode */
ppc_md.power_save = &ppc44x_idle;
}
return 0;
}
arch_initcall(ppc44x_idle_init);
static int __init idle_param(char *p)
{
if (!strcmp("spin", p)) {
mode_spin = 1;
ppc_md.power_save = NULL;
}
return 0;
}
early_param("idle", idle_param);
| gpl-2.0 |
aznair/mptcp | drivers/media/dvb-frontends/lgdt3306a.c | 222 | 53245 | /*
* Support for LGDT3306A - 8VSB/QAM-B
*
* Copyright (C) 2013 Fred Richter <frichter@hauppauge.com>
* - driver structure based on lgdt3305.[ch] by Michael Krufky
* - code based on LG3306_V0.35 API by LG Electronics Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <asm/div64.h>
#include <linux/dvb/frontend.h>
#include "dvb_math.h"
#include "lgdt3306a.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "set debug level (info=1, reg=2 (or-able))");
#define DBG_INFO 1
#define DBG_REG 2
#define DBG_DUMP 4 /* FGR - comment out to remove dump code */
#define lg_debug(fmt, arg...) \
printk(KERN_DEBUG pr_fmt(fmt), ## arg)
#define dbg_info(fmt, arg...) \
do { \
if (debug & DBG_INFO) \
lg_debug(fmt, ## arg); \
} while (0)
#define dbg_reg(fmt, arg...) \
do { \
if (debug & DBG_REG) \
lg_debug(fmt, ## arg); \
} while (0)
#define lg_chkerr(ret) \
({ \
int __ret; \
__ret = (ret < 0); \
if (__ret) \
pr_err("error %d on line %d\n", ret, __LINE__); \
__ret; \
})
struct lgdt3306a_state {
struct i2c_adapter *i2c_adap;
const struct lgdt3306a_config *cfg;
struct dvb_frontend frontend;
fe_modulation_t current_modulation;
u32 current_frequency;
u32 snr;
};
/*
* LG3306A Register Usage
* (LG does not really name the registers, so this code does not either)
*
* 0000 -> 00FF Common control and status
* 1000 -> 10FF Synchronizer control and status
* 1F00 -> 1FFF Smart Antenna control and status
* 2100 -> 21FF VSB Equalizer control and status
* 2800 -> 28FF QAM Equalizer control and status
* 3000 -> 30FF FEC control and status
*/
enum lgdt3306a_lock_status {
LG3306_UNLOCK = 0x00,
LG3306_LOCK = 0x01,
LG3306_UNKNOWN_LOCK = 0xff
};
enum lgdt3306a_neverlock_status {
LG3306_NL_INIT = 0x00,
LG3306_NL_PROCESS = 0x01,
LG3306_NL_LOCK = 0x02,
LG3306_NL_FAIL = 0x03,
LG3306_NL_UNKNOWN = 0xff
};
enum lgdt3306a_modulation {
LG3306_VSB = 0x00,
LG3306_QAM64 = 0x01,
LG3306_QAM256 = 0x02,
LG3306_UNKNOWN_MODE = 0xff
};
enum lgdt3306a_lock_check {
LG3306_SYNC_LOCK,
LG3306_FEC_LOCK,
LG3306_TR_LOCK,
LG3306_AGC_LOCK,
};
#ifdef DBG_DUMP
static void lgdt3306a_DumpAllRegs(struct lgdt3306a_state *state);
static void lgdt3306a_DumpRegs(struct lgdt3306a_state *state);
#endif
static int lgdt3306a_write_reg(struct lgdt3306a_state *state, u16 reg, u8 val)
{
int ret;
u8 buf[] = { reg >> 8, reg & 0xff, val };
struct i2c_msg msg = {
.addr = state->cfg->i2c_addr, .flags = 0,
.buf = buf, .len = 3,
};
dbg_reg("reg: 0x%04x, val: 0x%02x\n", reg, val);
ret = i2c_transfer(state->i2c_adap, &msg, 1);
if (ret != 1) {
pr_err("error (addr %02x %02x <- %02x, err = %i)\n",
msg.buf[0], msg.buf[1], msg.buf[2], ret);
if (ret < 0)
return ret;
else
return -EREMOTEIO;
}
return 0;
}
static int lgdt3306a_read_reg(struct lgdt3306a_state *state, u16 reg, u8 *val)
{
int ret;
u8 reg_buf[] = { reg >> 8, reg & 0xff };
struct i2c_msg msg[] = {
{ .addr = state->cfg->i2c_addr,
.flags = 0, .buf = reg_buf, .len = 2 },
{ .addr = state->cfg->i2c_addr,
.flags = I2C_M_RD, .buf = val, .len = 1 },
};
ret = i2c_transfer(state->i2c_adap, msg, 2);
if (ret != 2) {
pr_err("error (addr %02x reg %04x error (ret == %i)\n",
state->cfg->i2c_addr, reg, ret);
if (ret < 0)
return ret;
else
return -EREMOTEIO;
}
dbg_reg("reg: 0x%04x, val: 0x%02x\n", reg, *val);
return 0;
}
#define read_reg(state, reg) \
({ \
u8 __val; \
int ret = lgdt3306a_read_reg(state, reg, &__val); \
if (lg_chkerr(ret)) \
__val = 0; \
__val; \
})
static int lgdt3306a_set_reg_bit(struct lgdt3306a_state *state,
u16 reg, int bit, int onoff)
{
u8 val;
int ret;
dbg_reg("reg: 0x%04x, bit: %d, level: %d\n", reg, bit, onoff);
ret = lgdt3306a_read_reg(state, reg, &val);
if (lg_chkerr(ret))
goto fail;
val &= ~(1 << bit);
val |= (onoff & 1) << bit;
ret = lgdt3306a_write_reg(state, reg, val);
lg_chkerr(ret);
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_soft_reset(struct lgdt3306a_state *state)
{
int ret;
dbg_info("\n");
ret = lgdt3306a_set_reg_bit(state, 0x0000, 7, 0);
if (lg_chkerr(ret))
goto fail;
msleep(20);
ret = lgdt3306a_set_reg_bit(state, 0x0000, 7, 1);
lg_chkerr(ret);
fail:
return ret;
}
static int lgdt3306a_mpeg_mode(struct lgdt3306a_state *state,
enum lgdt3306a_mpeg_mode mode)
{
u8 val;
int ret;
dbg_info("(%d)\n", mode);
/* transport packet format - TPSENB=0x80 */
ret = lgdt3306a_set_reg_bit(state, 0x0071, 7,
mode == LGDT3306A_MPEG_PARALLEL ? 1 : 0);
if (lg_chkerr(ret))
goto fail;
/*
* start of packet signal duration
* TPSSOPBITEN=0x40; 0=byte duration, 1=bit duration
*/
ret = lgdt3306a_set_reg_bit(state, 0x0071, 6, 0);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_read_reg(state, 0x0070, &val);
if (lg_chkerr(ret))
goto fail;
val |= 0x10; /* TPCLKSUPB=0x10 */
if (mode == LGDT3306A_MPEG_PARALLEL)
val &= ~0x10;
ret = lgdt3306a_write_reg(state, 0x0070, val);
lg_chkerr(ret);
fail:
return ret;
}
static int lgdt3306a_mpeg_mode_polarity(struct lgdt3306a_state *state,
enum lgdt3306a_tp_clock_edge edge,
enum lgdt3306a_tp_valid_polarity valid)
{
u8 val;
int ret;
dbg_info("edge=%d, valid=%d\n", edge, valid);
ret = lgdt3306a_read_reg(state, 0x0070, &val);
if (lg_chkerr(ret))
goto fail;
val &= ~0x06; /* TPCLKPOL=0x04, TPVALPOL=0x02 */
if (edge == LGDT3306A_TPCLK_RISING_EDGE)
val |= 0x04;
if (valid == LGDT3306A_TP_VALID_HIGH)
val |= 0x02;
ret = lgdt3306a_write_reg(state, 0x0070, val);
lg_chkerr(ret);
fail:
return ret;
}
static int lgdt3306a_mpeg_tristate(struct lgdt3306a_state *state,
int mode)
{
u8 val;
int ret;
dbg_info("(%d)\n", mode);
if (mode) {
ret = lgdt3306a_read_reg(state, 0x0070, &val);
if (lg_chkerr(ret))
goto fail;
/*
* Tristate bus; TPOUTEN=0x80, TPCLKOUTEN=0x20,
* TPDATAOUTEN=0x08
*/
val &= ~0xa8;
ret = lgdt3306a_write_reg(state, 0x0070, val);
if (lg_chkerr(ret))
goto fail;
/* AGCIFOUTENB=0x40; 1=Disable IFAGC pin */
ret = lgdt3306a_set_reg_bit(state, 0x0003, 6, 1);
if (lg_chkerr(ret))
goto fail;
} else {
/* enable IFAGC pin */
ret = lgdt3306a_set_reg_bit(state, 0x0003, 6, 0);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_read_reg(state, 0x0070, &val);
if (lg_chkerr(ret))
goto fail;
val |= 0xa8; /* enable bus */
ret = lgdt3306a_write_reg(state, 0x0070, val);
if (lg_chkerr(ret))
goto fail;
}
fail:
return ret;
}
static int lgdt3306a_ts_bus_ctrl(struct dvb_frontend *fe, int acquire)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
dbg_info("acquire=%d\n", acquire);
return lgdt3306a_mpeg_tristate(state, acquire ? 0 : 1);
}
static int lgdt3306a_power(struct lgdt3306a_state *state,
int mode)
{
int ret;
dbg_info("(%d)\n", mode);
if (mode == 0) {
/* into reset */
ret = lgdt3306a_set_reg_bit(state, 0x0000, 7, 0);
if (lg_chkerr(ret))
goto fail;
/* power down */
ret = lgdt3306a_set_reg_bit(state, 0x0000, 0, 0);
if (lg_chkerr(ret))
goto fail;
} else {
/* out of reset */
ret = lgdt3306a_set_reg_bit(state, 0x0000, 7, 1);
if (lg_chkerr(ret))
goto fail;
/* power up */
ret = lgdt3306a_set_reg_bit(state, 0x0000, 0, 1);
if (lg_chkerr(ret))
goto fail;
}
#ifdef DBG_DUMP
lgdt3306a_DumpAllRegs(state);
#endif
fail:
return ret;
}
static int lgdt3306a_set_vsb(struct lgdt3306a_state *state)
{
u8 val;
int ret;
dbg_info("\n");
/* 0. Spectrum inversion detection manual; spectrum inverted */
ret = lgdt3306a_read_reg(state, 0x0002, &val);
val &= 0xf7; /* SPECINVAUTO Off */
val |= 0x04; /* SPECINV On */
ret = lgdt3306a_write_reg(state, 0x0002, val);
if (lg_chkerr(ret))
goto fail;
/* 1. Selection of standard mode(0x08=QAM, 0x80=VSB) */
ret = lgdt3306a_write_reg(state, 0x0008, 0x80);
if (lg_chkerr(ret))
goto fail;
/* 2. Bandwidth mode for VSB(6MHz) */
ret = lgdt3306a_read_reg(state, 0x0009, &val);
val &= 0xe3;
val |= 0x0c; /* STDOPDETTMODE[2:0]=3 */
ret = lgdt3306a_write_reg(state, 0x0009, val);
if (lg_chkerr(ret))
goto fail;
/* 3. QAM mode detection mode(None) */
ret = lgdt3306a_read_reg(state, 0x0009, &val);
val &= 0xfc; /* STDOPDETCMODE[1:0]=0 */
ret = lgdt3306a_write_reg(state, 0x0009, val);
if (lg_chkerr(ret))
goto fail;
/* 4. ADC sampling frequency rate(2x sampling) */
ret = lgdt3306a_read_reg(state, 0x000d, &val);
val &= 0xbf; /* SAMPLING4XFEN=0 */
ret = lgdt3306a_write_reg(state, 0x000d, val);
if (lg_chkerr(ret))
goto fail;
#if 0
/* FGR - disable any AICC filtering, testing only */
ret = lgdt3306a_write_reg(state, 0x0024, 0x00);
if (lg_chkerr(ret))
goto fail;
/* AICCFIXFREQ0 NT N-1(Video rejection) */
ret = lgdt3306a_write_reg(state, 0x002e, 0x00);
ret = lgdt3306a_write_reg(state, 0x002f, 0x00);
ret = lgdt3306a_write_reg(state, 0x0030, 0x00);
/* AICCFIXFREQ1 NT N-1(Audio rejection) */
ret = lgdt3306a_write_reg(state, 0x002b, 0x00);
ret = lgdt3306a_write_reg(state, 0x002c, 0x00);
ret = lgdt3306a_write_reg(state, 0x002d, 0x00);
/* AICCFIXFREQ2 NT Co-Channel(Video rejection) */
ret = lgdt3306a_write_reg(state, 0x0028, 0x00);
ret = lgdt3306a_write_reg(state, 0x0029, 0x00);
ret = lgdt3306a_write_reg(state, 0x002a, 0x00);
/* AICCFIXFREQ3 NT Co-Channel(Audio rejection) */
ret = lgdt3306a_write_reg(state, 0x0025, 0x00);
ret = lgdt3306a_write_reg(state, 0x0026, 0x00);
ret = lgdt3306a_write_reg(state, 0x0027, 0x00);
#else
/* FGR - this works well for HVR-1955,1975 */
/* 5. AICCOPMODE NT N-1 Adj. */
ret = lgdt3306a_write_reg(state, 0x0024, 0x5A);
if (lg_chkerr(ret))
goto fail;
/* AICCFIXFREQ0 NT N-1(Video rejection) */
ret = lgdt3306a_write_reg(state, 0x002e, 0x5A);
ret = lgdt3306a_write_reg(state, 0x002f, 0x00);
ret = lgdt3306a_write_reg(state, 0x0030, 0x00);
/* AICCFIXFREQ1 NT N-1(Audio rejection) */
ret = lgdt3306a_write_reg(state, 0x002b, 0x36);
ret = lgdt3306a_write_reg(state, 0x002c, 0x00);
ret = lgdt3306a_write_reg(state, 0x002d, 0x00);
/* AICCFIXFREQ2 NT Co-Channel(Video rejection) */
ret = lgdt3306a_write_reg(state, 0x0028, 0x2A);
ret = lgdt3306a_write_reg(state, 0x0029, 0x00);
ret = lgdt3306a_write_reg(state, 0x002a, 0x00);
/* AICCFIXFREQ3 NT Co-Channel(Audio rejection) */
ret = lgdt3306a_write_reg(state, 0x0025, 0x06);
ret = lgdt3306a_write_reg(state, 0x0026, 0x00);
ret = lgdt3306a_write_reg(state, 0x0027, 0x00);
#endif
ret = lgdt3306a_read_reg(state, 0x001e, &val);
val &= 0x0f;
val |= 0xa0;
ret = lgdt3306a_write_reg(state, 0x001e, val);
ret = lgdt3306a_write_reg(state, 0x0022, 0x08);
ret = lgdt3306a_write_reg(state, 0x0023, 0xFF);
ret = lgdt3306a_read_reg(state, 0x211f, &val);
val &= 0xef;
ret = lgdt3306a_write_reg(state, 0x211f, val);
ret = lgdt3306a_write_reg(state, 0x2173, 0x01);
ret = lgdt3306a_read_reg(state, 0x1061, &val);
val &= 0xf8;
val |= 0x04;
ret = lgdt3306a_write_reg(state, 0x1061, val);
ret = lgdt3306a_read_reg(state, 0x103d, &val);
val &= 0xcf;
ret = lgdt3306a_write_reg(state, 0x103d, val);
ret = lgdt3306a_write_reg(state, 0x2122, 0x40);
ret = lgdt3306a_read_reg(state, 0x2141, &val);
val &= 0x3f;
ret = lgdt3306a_write_reg(state, 0x2141, val);
ret = lgdt3306a_read_reg(state, 0x2135, &val);
val &= 0x0f;
val |= 0x70;
ret = lgdt3306a_write_reg(state, 0x2135, val);
ret = lgdt3306a_read_reg(state, 0x0003, &val);
val &= 0xf7;
ret = lgdt3306a_write_reg(state, 0x0003, val);
ret = lgdt3306a_read_reg(state, 0x001c, &val);
val &= 0x7f;
ret = lgdt3306a_write_reg(state, 0x001c, val);
/* 6. EQ step size */
ret = lgdt3306a_read_reg(state, 0x2179, &val);
val &= 0xf8;
ret = lgdt3306a_write_reg(state, 0x2179, val);
ret = lgdt3306a_read_reg(state, 0x217a, &val);
val &= 0xf8;
ret = lgdt3306a_write_reg(state, 0x217a, val);
/* 7. Reset */
ret = lgdt3306a_soft_reset(state);
if (lg_chkerr(ret))
goto fail;
dbg_info("complete\n");
fail:
return ret;
}
static int lgdt3306a_set_qam(struct lgdt3306a_state *state, int modulation)
{
u8 val;
int ret;
dbg_info("modulation=%d\n", modulation);
/* 1. Selection of standard mode(0x08=QAM, 0x80=VSB) */
ret = lgdt3306a_write_reg(state, 0x0008, 0x08);
if (lg_chkerr(ret))
goto fail;
/* 1a. Spectrum inversion detection to Auto */
ret = lgdt3306a_read_reg(state, 0x0002, &val);
val &= 0xfb; /* SPECINV Off */
val |= 0x08; /* SPECINVAUTO On */
ret = lgdt3306a_write_reg(state, 0x0002, val);
if (lg_chkerr(ret))
goto fail;
/* 2. Bandwidth mode for QAM */
ret = lgdt3306a_read_reg(state, 0x0009, &val);
val &= 0xe3; /* STDOPDETTMODE[2:0]=0 VSB Off */
ret = lgdt3306a_write_reg(state, 0x0009, val);
if (lg_chkerr(ret))
goto fail;
/* 3. : 64QAM/256QAM detection(manual, auto) */
ret = lgdt3306a_read_reg(state, 0x0009, &val);
val &= 0xfc;
val |= 0x02; /* STDOPDETCMODE[1:0]=1=Manual 2=Auto */
ret = lgdt3306a_write_reg(state, 0x0009, val);
if (lg_chkerr(ret))
goto fail;
/* 3a. : 64QAM/256QAM selection for manual */
ret = lgdt3306a_read_reg(state, 0x101a, &val);
val &= 0xf8;
if (modulation == QAM_64)
val |= 0x02; /* QMDQMODE[2:0]=2=QAM64 */
else
val |= 0x04; /* QMDQMODE[2:0]=4=QAM256 */
ret = lgdt3306a_write_reg(state, 0x101a, val);
if (lg_chkerr(ret))
goto fail;
/* 4. ADC sampling frequency rate(4x sampling) */
ret = lgdt3306a_read_reg(state, 0x000d, &val);
val &= 0xbf;
val |= 0x40; /* SAMPLING4XFEN=1 */
ret = lgdt3306a_write_reg(state, 0x000d, val);
if (lg_chkerr(ret))
goto fail;
/* 5. No AICC operation in QAM mode */
ret = lgdt3306a_read_reg(state, 0x0024, &val);
val &= 0x00;
ret = lgdt3306a_write_reg(state, 0x0024, val);
if (lg_chkerr(ret))
goto fail;
/* 6. Reset */
ret = lgdt3306a_soft_reset(state);
if (lg_chkerr(ret))
goto fail;
dbg_info("complete\n");
fail:
return ret;
}
static int lgdt3306a_set_modulation(struct lgdt3306a_state *state,
struct dtv_frontend_properties *p)
{
int ret;
dbg_info("\n");
switch (p->modulation) {
case VSB_8:
ret = lgdt3306a_set_vsb(state);
break;
case QAM_64:
ret = lgdt3306a_set_qam(state, QAM_64);
break;
case QAM_256:
ret = lgdt3306a_set_qam(state, QAM_256);
break;
default:
return -EINVAL;
}
if (lg_chkerr(ret))
goto fail;
state->current_modulation = p->modulation;
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_agc_setup(struct lgdt3306a_state *state,
struct dtv_frontend_properties *p)
{
/* TODO: anything we want to do here??? */
dbg_info("\n");
switch (p->modulation) {
case VSB_8:
break;
case QAM_64:
case QAM_256:
break;
default:
return -EINVAL;
}
return 0;
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_set_inversion(struct lgdt3306a_state *state,
int inversion)
{
int ret;
dbg_info("(%d)\n", inversion);
ret = lgdt3306a_set_reg_bit(state, 0x0002, 2, inversion ? 1 : 0);
return ret;
}
static int lgdt3306a_set_inversion_auto(struct lgdt3306a_state *state,
int enabled)
{
int ret;
dbg_info("(%d)\n", enabled);
/* 0=Manual 1=Auto(QAM only) - SPECINVAUTO=0x04 */
ret = lgdt3306a_set_reg_bit(state, 0x0002, 3, enabled);
return ret;
}
static int lgdt3306a_spectral_inversion(struct lgdt3306a_state *state,
struct dtv_frontend_properties *p,
int inversion)
{
int ret = 0;
dbg_info("(%d)\n", inversion);
#if 0
/*
* FGR - spectral_inversion defaults already set for VSB and QAM;
* can enable later if desired
*/
ret = lgdt3306a_set_inversion(state, inversion);
switch (p->modulation) {
case VSB_8:
/* Manual only for VSB */
ret = lgdt3306a_set_inversion_auto(state, 0);
break;
case QAM_64:
case QAM_256:
/* Auto ok for QAM */
ret = lgdt3306a_set_inversion_auto(state, 1);
break;
default:
ret = -EINVAL;
}
#endif
return ret;
}
static int lgdt3306a_set_if(struct lgdt3306a_state *state,
struct dtv_frontend_properties *p)
{
int ret;
u16 if_freq_khz;
u8 nco1, nco2;
switch (p->modulation) {
case VSB_8:
if_freq_khz = state->cfg->vsb_if_khz;
break;
case QAM_64:
case QAM_256:
if_freq_khz = state->cfg->qam_if_khz;
break;
default:
return -EINVAL;
}
switch (if_freq_khz) {
default:
pr_warn("IF=%d KHz is not supportted, 3250 assumed\n",
if_freq_khz);
/* fallthrough */
case 3250: /* 3.25Mhz */
nco1 = 0x34;
nco2 = 0x00;
break;
case 3500: /* 3.50Mhz */
nco1 = 0x38;
nco2 = 0x00;
break;
case 4000: /* 4.00Mhz */
nco1 = 0x40;
nco2 = 0x00;
break;
case 5000: /* 5.00Mhz */
nco1 = 0x50;
nco2 = 0x00;
break;
case 5380: /* 5.38Mhz */
nco1 = 0x56;
nco2 = 0x14;
break;
}
ret = lgdt3306a_write_reg(state, 0x0010, nco1);
if (ret)
return ret;
ret = lgdt3306a_write_reg(state, 0x0011, nco2);
if (ret)
return ret;
dbg_info("if_freq=%d KHz->[%04x]\n", if_freq_khz, nco1<<8 | nco2);
return 0;
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
if (state->cfg->deny_i2c_rptr) {
dbg_info("deny_i2c_rptr=%d\n", state->cfg->deny_i2c_rptr);
return 0;
}
dbg_info("(%d)\n", enable);
/* NI2CRPTEN=0x80 */
return lgdt3306a_set_reg_bit(state, 0x0002, 7, enable ? 0 : 1);
}
static int lgdt3306a_sleep(struct lgdt3306a_state *state)
{
int ret;
dbg_info("\n");
state->current_frequency = -1; /* force re-tune, when we wake */
ret = lgdt3306a_mpeg_tristate(state, 1); /* disable data bus */
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_power(state, 0); /* power down */
lg_chkerr(ret);
fail:
return 0;
}
static int lgdt3306a_fe_sleep(struct dvb_frontend *fe)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
return lgdt3306a_sleep(state);
}
static int lgdt3306a_init(struct dvb_frontend *fe)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
u8 val;
int ret;
dbg_info("\n");
/* 1. Normal operation mode */
ret = lgdt3306a_set_reg_bit(state, 0x0001, 0, 1); /* SIMFASTENB=0x01 */
if (lg_chkerr(ret))
goto fail;
/* 2. Spectrum inversion auto detection (Not valid for VSB) */
ret = lgdt3306a_set_inversion_auto(state, 0);
if (lg_chkerr(ret))
goto fail;
/* 3. Spectrum inversion(According to the tuner configuration) */
ret = lgdt3306a_set_inversion(state, 1);
if (lg_chkerr(ret))
goto fail;
/* 4. Peak-to-peak voltage of ADC input signal */
/* ADCSEL1V=0x80=1Vpp; 0x00=2Vpp */
ret = lgdt3306a_set_reg_bit(state, 0x0004, 7, 1);
if (lg_chkerr(ret))
goto fail;
/* 5. ADC output data capture clock phase */
/* 0=same phase as ADC clock */
ret = lgdt3306a_set_reg_bit(state, 0x0004, 2, 0);
if (lg_chkerr(ret))
goto fail;
/* 5a. ADC sampling clock source */
/* ADCCLKPLLSEL=0x08; 0=use ext clock, not PLL */
ret = lgdt3306a_set_reg_bit(state, 0x0004, 3, 0);
if (lg_chkerr(ret))
goto fail;
/* 6. Automatic PLL set */
/* PLLSETAUTO=0x40; 0=off */
ret = lgdt3306a_set_reg_bit(state, 0x0005, 6, 0);
if (lg_chkerr(ret))
goto fail;
if (state->cfg->xtalMHz == 24) { /* 24MHz */
/* 7. Frequency for PLL output(0x2564 for 192MHz for 24MHz) */
ret = lgdt3306a_read_reg(state, 0x0005, &val);
if (lg_chkerr(ret))
goto fail;
val &= 0xc0;
val |= 0x25;
ret = lgdt3306a_write_reg(state, 0x0005, val);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_write_reg(state, 0x0006, 0x64);
if (lg_chkerr(ret))
goto fail;
/* 8. ADC sampling frequency(0x180000 for 24MHz sampling) */
ret = lgdt3306a_read_reg(state, 0x000d, &val);
if (lg_chkerr(ret))
goto fail;
val &= 0xc0;
val |= 0x18;
ret = lgdt3306a_write_reg(state, 0x000d, val);
if (lg_chkerr(ret))
goto fail;
} else if (state->cfg->xtalMHz == 25) { /* 25MHz */
/* 7. Frequency for PLL output */
ret = lgdt3306a_read_reg(state, 0x0005, &val);
if (lg_chkerr(ret))
goto fail;
val &= 0xc0;
val |= 0x25;
ret = lgdt3306a_write_reg(state, 0x0005, val);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_write_reg(state, 0x0006, 0x64);
if (lg_chkerr(ret))
goto fail;
/* 8. ADC sampling frequency(0x190000 for 25MHz sampling) */
ret = lgdt3306a_read_reg(state, 0x000d, &val);
if (lg_chkerr(ret))
goto fail;
val &= 0xc0;
val |= 0x19;
ret = lgdt3306a_write_reg(state, 0x000d, val);
if (lg_chkerr(ret))
goto fail;
} else {
pr_err("Bad xtalMHz=%d\n", state->cfg->xtalMHz);
}
#if 0
ret = lgdt3306a_write_reg(state, 0x000e, 0x00);
ret = lgdt3306a_write_reg(state, 0x000f, 0x00);
#endif
/* 9. Center frequency of input signal of ADC */
ret = lgdt3306a_write_reg(state, 0x0010, 0x34); /* 3.25MHz */
ret = lgdt3306a_write_reg(state, 0x0011, 0x00);
/* 10. Fixed gain error value */
ret = lgdt3306a_write_reg(state, 0x0014, 0); /* gain error=0 */
/* 10a. VSB TR BW gear shift initial step */
ret = lgdt3306a_read_reg(state, 0x103c, &val);
val &= 0x0f;
val |= 0x20; /* SAMGSAUTOSTL_V[3:0] = 2 */
ret = lgdt3306a_write_reg(state, 0x103c, val);
/* 10b. Timing offset calibration in low temperature for VSB */
ret = lgdt3306a_read_reg(state, 0x103d, &val);
val &= 0xfc;
val |= 0x03;
ret = lgdt3306a_write_reg(state, 0x103d, val);
/* 10c. Timing offset calibration in low temperature for QAM */
ret = lgdt3306a_read_reg(state, 0x1036, &val);
val &= 0xf0;
val |= 0x0c;
ret = lgdt3306a_write_reg(state, 0x1036, val);
/* 11. Using the imaginary part of CIR in CIR loading */
ret = lgdt3306a_read_reg(state, 0x211f, &val);
val &= 0xef; /* do not use imaginary of CIR */
ret = lgdt3306a_write_reg(state, 0x211f, val);
/* 12. Control of no signal detector function */
ret = lgdt3306a_read_reg(state, 0x2849, &val);
val &= 0xef; /* NOUSENOSIGDET=0, enable no signal detector */
ret = lgdt3306a_write_reg(state, 0x2849, val);
/* FGR - put demod in some known mode */
ret = lgdt3306a_set_vsb(state);
/* 13. TP stream format */
ret = lgdt3306a_mpeg_mode(state, state->cfg->mpeg_mode);
/* 14. disable output buses */
ret = lgdt3306a_mpeg_tristate(state, 1);
/* 15. Sleep (in reset) */
ret = lgdt3306a_sleep(state);
lg_chkerr(ret);
fail:
return ret;
}
static int lgdt3306a_set_parameters(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct lgdt3306a_state *state = fe->demodulator_priv;
int ret;
dbg_info("(%d, %d)\n", p->frequency, p->modulation);
if (state->current_frequency == p->frequency &&
state->current_modulation == p->modulation) {
dbg_info(" (already set, skipping ...)\n");
return 0;
}
state->current_frequency = -1;
state->current_modulation = -1;
ret = lgdt3306a_power(state, 1); /* power up */
if (lg_chkerr(ret))
goto fail;
if (fe->ops.tuner_ops.set_params) {
ret = fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
#if 0
if (lg_chkerr(ret))
goto fail;
state->current_frequency = p->frequency;
#endif
}
ret = lgdt3306a_set_modulation(state, p);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_agc_setup(state, p);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_set_if(state, p);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_spectral_inversion(state, p,
state->cfg->spectral_inversion ? 1 : 0);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_mpeg_mode(state, state->cfg->mpeg_mode);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_mpeg_mode_polarity(state,
state->cfg->tpclk_edge,
state->cfg->tpvalid_polarity);
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_mpeg_tristate(state, 0); /* enable data bus */
if (lg_chkerr(ret))
goto fail;
ret = lgdt3306a_soft_reset(state);
if (lg_chkerr(ret))
goto fail;
#ifdef DBG_DUMP
lgdt3306a_DumpAllRegs(state);
#endif
state->current_frequency = p->frequency;
fail:
return ret;
}
static int lgdt3306a_get_frontend(struct dvb_frontend *fe)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
dbg_info("(%u, %d)\n",
state->current_frequency, state->current_modulation);
p->modulation = state->current_modulation;
p->frequency = state->current_frequency;
return 0;
}
static enum dvbfe_algo lgdt3306a_get_frontend_algo(struct dvb_frontend *fe)
{
#if 1
return DVBFE_ALGO_CUSTOM;
#else
return DVBFE_ALGO_HW;
#endif
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_monitor_vsb(struct lgdt3306a_state *state)
{
u8 val;
int ret;
u8 snrRef, maxPowerMan, nCombDet;
u16 fbDlyCir;
ret = lgdt3306a_read_reg(state, 0x21a1, &val);
if (ret)
return ret;
snrRef = val & 0x3f;
ret = lgdt3306a_read_reg(state, 0x2185, &maxPowerMan);
if (ret)
return ret;
ret = lgdt3306a_read_reg(state, 0x2191, &val);
if (ret)
return ret;
nCombDet = (val & 0x80) >> 7;
ret = lgdt3306a_read_reg(state, 0x2180, &val);
if (ret)
return ret;
fbDlyCir = (val & 0x03) << 8;
ret = lgdt3306a_read_reg(state, 0x2181, &val);
if (ret)
return ret;
fbDlyCir |= val;
dbg_info("snrRef=%d maxPowerMan=0x%x nCombDet=%d fbDlyCir=0x%x\n",
snrRef, maxPowerMan, nCombDet, fbDlyCir);
/* Carrier offset sub loop bandwidth */
ret = lgdt3306a_read_reg(state, 0x1061, &val);
if (ret)
return ret;
val &= 0xf8;
if ((snrRef > 18) && (maxPowerMan > 0x68)
&& (nCombDet == 0x01)
&& ((fbDlyCir == 0x03FF) || (fbDlyCir < 0x6C))) {
/* SNR is over 18dB and no ghosting */
val |= 0x00; /* final bandwidth = 0 */
} else {
val |= 0x04; /* final bandwidth = 4 */
}
ret = lgdt3306a_write_reg(state, 0x1061, val);
if (ret)
return ret;
/* Adjust Notch Filter */
ret = lgdt3306a_read_reg(state, 0x0024, &val);
if (ret)
return ret;
val &= 0x0f;
if (nCombDet == 0) { /* Turn on the Notch Filter */
val |= 0x50;
}
ret = lgdt3306a_write_reg(state, 0x0024, val);
if (ret)
return ret;
/* VSB Timing Recovery output normalization */
ret = lgdt3306a_read_reg(state, 0x103d, &val);
if (ret)
return ret;
val &= 0xcf;
val |= 0x20;
ret = lgdt3306a_write_reg(state, 0x103d, val);
return ret;
}
static enum lgdt3306a_modulation
lgdt3306a_check_oper_mode(struct lgdt3306a_state *state)
{
u8 val = 0;
int ret;
ret = lgdt3306a_read_reg(state, 0x0081, &val);
if (ret)
goto err;
if (val & 0x80) {
dbg_info("VSB\n");
return LG3306_VSB;
}
if (val & 0x08) {
ret = lgdt3306a_read_reg(state, 0x00a6, &val);
if (ret)
goto err;
val = val >> 2;
if (val & 0x01) {
dbg_info("QAM256\n");
return LG3306_QAM256;
}
dbg_info("QAM64\n");
return LG3306_QAM64;
}
err:
pr_warn("UNKNOWN\n");
return LG3306_UNKNOWN_MODE;
}
static enum lgdt3306a_lock_status
lgdt3306a_check_lock_status(struct lgdt3306a_state *state,
enum lgdt3306a_lock_check whatLock)
{
u8 val = 0;
int ret;
enum lgdt3306a_modulation modeOper;
enum lgdt3306a_lock_status lockStatus;
modeOper = LG3306_UNKNOWN_MODE;
switch (whatLock) {
case LG3306_SYNC_LOCK:
{
ret = lgdt3306a_read_reg(state, 0x00a6, &val);
if (ret)
return ret;
if ((val & 0x80) == 0x80)
lockStatus = LG3306_LOCK;
else
lockStatus = LG3306_UNLOCK;
dbg_info("SYNC_LOCK=%x\n", lockStatus);
break;
}
case LG3306_AGC_LOCK:
{
ret = lgdt3306a_read_reg(state, 0x0080, &val);
if (ret)
return ret;
if ((val & 0x40) == 0x40)
lockStatus = LG3306_LOCK;
else
lockStatus = LG3306_UNLOCK;
dbg_info("AGC_LOCK=%x\n", lockStatus);
break;
}
case LG3306_TR_LOCK:
{
modeOper = lgdt3306a_check_oper_mode(state);
if ((modeOper == LG3306_QAM64) || (modeOper == LG3306_QAM256)) {
ret = lgdt3306a_read_reg(state, 0x1094, &val);
if (ret)
return ret;
if ((val & 0x80) == 0x80)
lockStatus = LG3306_LOCK;
else
lockStatus = LG3306_UNLOCK;
} else
lockStatus = LG3306_UNKNOWN_LOCK;
dbg_info("TR_LOCK=%x\n", lockStatus);
break;
}
case LG3306_FEC_LOCK:
{
modeOper = lgdt3306a_check_oper_mode(state);
if ((modeOper == LG3306_QAM64) || (modeOper == LG3306_QAM256)) {
ret = lgdt3306a_read_reg(state, 0x0080, &val);
if (ret)
return ret;
if ((val & 0x10) == 0x10)
lockStatus = LG3306_LOCK;
else
lockStatus = LG3306_UNLOCK;
} else
lockStatus = LG3306_UNKNOWN_LOCK;
dbg_info("FEC_LOCK=%x\n", lockStatus);
break;
}
default:
lockStatus = LG3306_UNKNOWN_LOCK;
pr_warn("UNKNOWN whatLock=%d\n", whatLock);
break;
}
return lockStatus;
}
static enum lgdt3306a_neverlock_status
lgdt3306a_check_neverlock_status(struct lgdt3306a_state *state)
{
u8 val = 0;
int ret;
enum lgdt3306a_neverlock_status lockStatus;
ret = lgdt3306a_read_reg(state, 0x0080, &val);
if (ret)
return ret;
lockStatus = (enum lgdt3306a_neverlock_status)(val & 0x03);
dbg_info("NeverLock=%d", lockStatus);
return lockStatus;
}
static int lgdt3306a_pre_monitoring(struct lgdt3306a_state *state)
{
u8 val = 0;
int ret;
u8 currChDiffACQ, snrRef, mainStrong, aiccrejStatus;
/* Channel variation */
ret = lgdt3306a_read_reg(state, 0x21bc, &currChDiffACQ);
if (ret)
return ret;
/* SNR of Frame sync */
ret = lgdt3306a_read_reg(state, 0x21a1, &val);
if (ret)
return ret;
snrRef = val & 0x3f;
/* Strong Main CIR */
ret = lgdt3306a_read_reg(state, 0x2199, &val);
if (ret)
return ret;
mainStrong = (val & 0x40) >> 6;
ret = lgdt3306a_read_reg(state, 0x0090, &val);
if (ret)
return ret;
aiccrejStatus = (val & 0xf0) >> 4;
dbg_info("snrRef=%d mainStrong=%d aiccrejStatus=%d currChDiffACQ=0x%x\n",
snrRef, mainStrong, aiccrejStatus, currChDiffACQ);
#if 0
/* Dynamic ghost exists */
if ((mainStrong == 0) && (currChDiffACQ > 0x70))
#endif
if (mainStrong == 0) {
ret = lgdt3306a_read_reg(state, 0x2135, &val);
if (ret)
return ret;
val &= 0x0f;
val |= 0xa0;
ret = lgdt3306a_write_reg(state, 0x2135, val);
if (ret)
return ret;
ret = lgdt3306a_read_reg(state, 0x2141, &val);
if (ret)
return ret;
val &= 0x3f;
val |= 0x80;
ret = lgdt3306a_write_reg(state, 0x2141, val);
if (ret)
return ret;
ret = lgdt3306a_write_reg(state, 0x2122, 0x70);
if (ret)
return ret;
} else { /* Weak ghost or static channel */
ret = lgdt3306a_read_reg(state, 0x2135, &val);
if (ret)
return ret;
val &= 0x0f;
val |= 0x70;
ret = lgdt3306a_write_reg(state, 0x2135, val);
if (ret)
return ret;
ret = lgdt3306a_read_reg(state, 0x2141, &val);
if (ret)
return ret;
val &= 0x3f;
val |= 0x40;
ret = lgdt3306a_write_reg(state, 0x2141, val);
if (ret)
return ret;
ret = lgdt3306a_write_reg(state, 0x2122, 0x40);
if (ret)
return ret;
}
return 0;
}
static enum lgdt3306a_lock_status
lgdt3306a_sync_lock_poll(struct lgdt3306a_state *state)
{
enum lgdt3306a_lock_status syncLockStatus = LG3306_UNLOCK;
int i;
for (i = 0; i < 2; i++) {
msleep(30);
syncLockStatus = lgdt3306a_check_lock_status(state,
LG3306_SYNC_LOCK);
if (syncLockStatus == LG3306_LOCK) {
dbg_info("locked(%d)\n", i);
return LG3306_LOCK;
}
}
dbg_info("not locked\n");
return LG3306_UNLOCK;
}
static enum lgdt3306a_lock_status
lgdt3306a_fec_lock_poll(struct lgdt3306a_state *state)
{
enum lgdt3306a_lock_status FECLockStatus = LG3306_UNLOCK;
int i;
for (i = 0; i < 2; i++) {
msleep(30);
FECLockStatus = lgdt3306a_check_lock_status(state,
LG3306_FEC_LOCK);
if (FECLockStatus == LG3306_LOCK) {
dbg_info("locked(%d)\n", i);
return FECLockStatus;
}
}
dbg_info("not locked\n");
return FECLockStatus;
}
static enum lgdt3306a_neverlock_status
lgdt3306a_neverlock_poll(struct lgdt3306a_state *state)
{
enum lgdt3306a_neverlock_status NLLockStatus = LG3306_NL_FAIL;
int i;
for (i = 0; i < 5; i++) {
msleep(30);
NLLockStatus = lgdt3306a_check_neverlock_status(state);
if (NLLockStatus == LG3306_NL_LOCK) {
dbg_info("NL_LOCK(%d)\n", i);
return NLLockStatus;
}
}
dbg_info("NLLockStatus=%d\n", NLLockStatus);
return NLLockStatus;
}
static u8 lgdt3306a_get_packet_error(struct lgdt3306a_state *state)
{
u8 val;
int ret;
ret = lgdt3306a_read_reg(state, 0x00fa, &val);
if (ret)
return ret;
return val;
}
static const u32 valx_x10[] = {
10, 11, 13, 15, 17, 20, 25, 33, 41, 50, 59, 73, 87, 100
};
static const u32 log10x_x1000[] = {
0, 41, 114, 176, 230, 301, 398, 518, 613, 699, 771, 863, 939, 1000
};
static u32 log10_x1000(u32 x)
{
u32 diff_val, step_val, step_log10;
u32 log_val = 0;
u32 i;
if (x <= 0)
return -1000000; /* signal error */
if (x == 10)
return 0; /* log(1)=0 */
if (x < 10) {
while (x < 10) {
x = x * 10;
log_val--;
}
} else { /* x > 10 */
while (x >= 100) {
x = x / 10;
log_val++;
}
}
log_val *= 1000;
if (x == 10) /* was our input an exact multiple of 10 */
return log_val; /* don't need to interpolate */
/* find our place on the log curve */
for (i = 1; i < ARRAY_SIZE(valx_x10); i++) {
if (valx_x10[i] >= x)
break;
}
if (i == ARRAY_SIZE(valx_x10))
return log_val + log10x_x1000[i - 1];
diff_val = x - valx_x10[i-1];
step_val = valx_x10[i] - valx_x10[i - 1];
step_log10 = log10x_x1000[i] - log10x_x1000[i - 1];
/* do a linear interpolation to get in-between values */
return log_val + log10x_x1000[i - 1] +
((diff_val*step_log10) / step_val);
}
static u32 lgdt3306a_calculate_snr_x100(struct lgdt3306a_state *state)
{
u32 mse; /* Mean-Square Error */
u32 pwr; /* Constelation power */
u32 snr_x100;
mse = (read_reg(state, 0x00ec) << 8) |
(read_reg(state, 0x00ed));
pwr = (read_reg(state, 0x00e8) << 8) |
(read_reg(state, 0x00e9));
if (mse == 0) /* no signal */
return 0;
snr_x100 = log10_x1000((pwr * 10000) / mse) - 3000;
dbg_info("mse=%u, pwr=%u, snr_x100=%d\n", mse, pwr, snr_x100);
return snr_x100;
}
static enum lgdt3306a_lock_status
lgdt3306a_vsb_lock_poll(struct lgdt3306a_state *state)
{
int ret;
u8 cnt = 0;
u8 packet_error;
u32 snr;
for (cnt = 0; cnt < 10; cnt++) {
if (lgdt3306a_sync_lock_poll(state) == LG3306_UNLOCK) {
dbg_info("no sync lock!\n");
return LG3306_UNLOCK;
}
msleep(20);
ret = lgdt3306a_pre_monitoring(state);
if (ret)
break;
packet_error = lgdt3306a_get_packet_error(state);
snr = lgdt3306a_calculate_snr_x100(state);
dbg_info("cnt=%d errors=%d snr=%d\n", cnt, packet_error, snr);
if ((snr >= 1500) && (packet_error < 0xff))
return LG3306_LOCK;
}
dbg_info("not locked!\n");
return LG3306_UNLOCK;
}
static enum lgdt3306a_lock_status
lgdt3306a_qam_lock_poll(struct lgdt3306a_state *state)
{
u8 cnt;
u8 packet_error;
u32 snr;
for (cnt = 0; cnt < 10; cnt++) {
if (lgdt3306a_fec_lock_poll(state) == LG3306_UNLOCK) {
dbg_info("no fec lock!\n");
return LG3306_UNLOCK;
}
msleep(20);
packet_error = lgdt3306a_get_packet_error(state);
snr = lgdt3306a_calculate_snr_x100(state);
dbg_info("cnt=%d errors=%d snr=%d\n", cnt, packet_error, snr);
if ((snr >= 1500) && (packet_error < 0xff))
return LG3306_LOCK;
}
dbg_info("not locked!\n");
return LG3306_UNLOCK;
}
static int lgdt3306a_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
u16 strength = 0;
int ret = 0;
if (fe->ops.tuner_ops.get_rf_strength) {
ret = fe->ops.tuner_ops.get_rf_strength(fe, &strength);
if (ret == 0)
dbg_info("strength=%d\n", strength);
else
dbg_info("fe->ops.tuner_ops.get_rf_strength() failed\n");
}
*status = 0;
if (lgdt3306a_neverlock_poll(state) == LG3306_NL_LOCK) {
*status |= FE_HAS_SIGNAL;
*status |= FE_HAS_CARRIER;
switch (state->current_modulation) {
case QAM_256:
case QAM_64:
if (lgdt3306a_qam_lock_poll(state) == LG3306_LOCK) {
*status |= FE_HAS_VITERBI;
*status |= FE_HAS_SYNC;
*status |= FE_HAS_LOCK;
}
break;
case VSB_8:
if (lgdt3306a_vsb_lock_poll(state) == LG3306_LOCK) {
*status |= FE_HAS_VITERBI;
*status |= FE_HAS_SYNC;
*status |= FE_HAS_LOCK;
ret = lgdt3306a_monitor_vsb(state);
}
break;
default:
ret = -EINVAL;
}
}
return ret;
}
static int lgdt3306a_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
state->snr = lgdt3306a_calculate_snr_x100(state);
/* report SNR in dB * 10 */
*snr = state->snr/10;
return 0;
}
static int lgdt3306a_read_signal_strength(struct dvb_frontend *fe,
u16 *strength)
{
/*
* Calculate some sort of "strength" from SNR
*/
struct lgdt3306a_state *state = fe->demodulator_priv;
u16 snr; /* snr_x10 */
int ret;
u32 ref_snr; /* snr*100 */
u32 str;
*strength = 0;
switch (state->current_modulation) {
case VSB_8:
ref_snr = 1600; /* 16dB */
break;
case QAM_64:
ref_snr = 2200; /* 22dB */
break;
case QAM_256:
ref_snr = 2800; /* 28dB */
break;
default:
return -EINVAL;
}
ret = fe->ops.read_snr(fe, &snr);
if (lg_chkerr(ret))
goto fail;
if (state->snr <= (ref_snr - 100))
str = 0;
else if (state->snr <= ref_snr)
str = (0xffff * 65) / 100; /* 65% */
else {
str = state->snr - ref_snr;
str /= 50;
str += 78; /* 78%-100% */
if (str > 100)
str = 100;
str = (0xffff * str) / 100;
}
*strength = (u16)str;
dbg_info("strength=%u\n", *strength);
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
static int lgdt3306a_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
u32 tmp;
*ber = 0;
#if 1
/* FGR - FIXME - I don't know what value is expected by dvb_core
* what is the scale of the value?? */
tmp = read_reg(state, 0x00fc); /* NBERVALUE[24-31] */
tmp = (tmp << 8) | read_reg(state, 0x00fd); /* NBERVALUE[16-23] */
tmp = (tmp << 8) | read_reg(state, 0x00fe); /* NBERVALUE[8-15] */
tmp = (tmp << 8) | read_reg(state, 0x00ff); /* NBERVALUE[0-7] */
*ber = tmp;
dbg_info("ber=%u\n", tmp);
#endif
return 0;
}
static int lgdt3306a_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
*ucblocks = 0;
#if 1
/* FGR - FIXME - I don't know what value is expected by dvb_core
* what happens when value wraps? */
*ucblocks = read_reg(state, 0x00f4); /* TPIFTPERRCNT[0-7] */
dbg_info("ucblocks=%u\n", *ucblocks);
#endif
return 0;
}
static int lgdt3306a_tune(struct dvb_frontend *fe, bool re_tune,
unsigned int mode_flags, unsigned int *delay,
fe_status_t *status)
{
int ret = 0;
struct lgdt3306a_state *state = fe->demodulator_priv;
dbg_info("re_tune=%u\n", re_tune);
if (re_tune) {
state->current_frequency = -1; /* force re-tune */
ret = lgdt3306a_set_parameters(fe);
if (ret != 0)
return ret;
}
*delay = 125;
ret = lgdt3306a_read_status(fe, status);
return ret;
}
static int lgdt3306a_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings
*fe_tune_settings)
{
fe_tune_settings->min_delay_ms = 100;
dbg_info("\n");
return 0;
}
static int lgdt3306a_search(struct dvb_frontend *fe)
{
fe_status_t status = 0;
int i, ret;
/* set frontend */
ret = lgdt3306a_set_parameters(fe);
if (ret)
goto error;
/* wait frontend lock */
for (i = 20; i > 0; i--) {
dbg_info(": loop=%d\n", i);
msleep(50);
ret = lgdt3306a_read_status(fe, &status);
if (ret)
goto error;
if (status & FE_HAS_LOCK)
break;
}
/* check if we have a valid signal */
if (status & FE_HAS_LOCK)
return DVBFE_ALGO_SEARCH_SUCCESS;
else
return DVBFE_ALGO_SEARCH_AGAIN;
error:
dbg_info("failed (%d)\n", ret);
return DVBFE_ALGO_SEARCH_ERROR;
}
static void lgdt3306a_release(struct dvb_frontend *fe)
{
struct lgdt3306a_state *state = fe->demodulator_priv;
dbg_info("\n");
kfree(state);
}
static struct dvb_frontend_ops lgdt3306a_ops;
struct dvb_frontend *lgdt3306a_attach(const struct lgdt3306a_config *config,
struct i2c_adapter *i2c_adap)
{
struct lgdt3306a_state *state = NULL;
int ret;
u8 val;
dbg_info("(%d-%04x)\n",
i2c_adap ? i2c_adapter_id(i2c_adap) : 0,
config ? config->i2c_addr : 0);
state = kzalloc(sizeof(struct lgdt3306a_state), GFP_KERNEL);
if (state == NULL)
goto fail;
state->cfg = config;
state->i2c_adap = i2c_adap;
memcpy(&state->frontend.ops, &lgdt3306a_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
/* verify that we're talking to a lg3306a */
/* FGR - NOTE - there is no obvious ChipId to check; we check
* some "known" bits after reset, but it's still just a guess */
ret = lgdt3306a_read_reg(state, 0x0000, &val);
if (lg_chkerr(ret))
goto fail;
if ((val & 0x74) != 0x74) {
pr_warn("expected 0x74, got 0x%x\n", (val & 0x74));
#if 0
/* FIXME - re-enable when we know this is right */
goto fail;
#endif
}
ret = lgdt3306a_read_reg(state, 0x0001, &val);
if (lg_chkerr(ret))
goto fail;
if ((val & 0xf6) != 0xc6) {
pr_warn("expected 0xc6, got 0x%x\n", (val & 0xf6));
#if 0
/* FIXME - re-enable when we know this is right */
goto fail;
#endif
}
ret = lgdt3306a_read_reg(state, 0x0002, &val);
if (lg_chkerr(ret))
goto fail;
if ((val & 0x73) != 0x03) {
pr_warn("expected 0x03, got 0x%x\n", (val & 0x73));
#if 0
/* FIXME - re-enable when we know this is right */
goto fail;
#endif
}
state->current_frequency = -1;
state->current_modulation = -1;
lgdt3306a_sleep(state);
return &state->frontend;
fail:
pr_warn("unable to detect LGDT3306A hardware\n");
kfree(state);
return NULL;
}
EXPORT_SYMBOL(lgdt3306a_attach);
#ifdef DBG_DUMP
static const short regtab[] = {
0x0000, /* SOFTRSTB 1'b1 1'b1 1'b1 ADCPDB 1'b1 PLLPDB GBBPDB 11111111 */
0x0001, /* 1'b1 1'b1 1'b0 1'b0 AUTORPTRS */
0x0002, /* NI2CRPTEN 1'b0 1'b0 1'b0 SPECINVAUT */
0x0003, /* AGCRFOUT */
0x0004, /* ADCSEL1V ADCCNT ADCCNF ADCCNS ADCCLKPLL */
0x0005, /* PLLINDIVSE */
0x0006, /* PLLCTRL[7:0] 11100001 */
0x0007, /* SYSINITWAITTIME[7:0] (msec) 00001000 */
0x0008, /* STDOPMODE[7:0] 10000000 */
0x0009, /* 1'b0 1'b0 1'b0 STDOPDETTMODE[2:0] STDOPDETCMODE[1:0] 00011110 */
0x000a, /* DAFTEN 1'b1 x x SCSYSLOCK */
0x000b, /* SCSYSLOCKCHKTIME[7:0] (10msec) 01100100 */
0x000d, /* x SAMPLING4 */
0x000e, /* SAMFREQ[15:8] 00000000 */
0x000f, /* SAMFREQ[7:0] 00000000 */
0x0010, /* IFFREQ[15:8] 01100000 */
0x0011, /* IFFREQ[7:0] 00000000 */
0x0012, /* AGCEN AGCREFMO */
0x0013, /* AGCRFFIXB AGCIFFIXB AGCLOCKDETRNGSEL[1:0] 1'b1 1'b0 1'b0 1'b0 11101000 */
0x0014, /* AGCFIXVALUE[7:0] 01111111 */
0x0015, /* AGCREF[15:8] 00001010 */
0x0016, /* AGCREF[7:0] 11100100 */
0x0017, /* AGCDELAY[7:0] 00100000 */
0x0018, /* AGCRFBW[3:0] AGCIFBW[3:0] 10001000 */
0x0019, /* AGCUDOUTMODE[1:0] AGCUDCTRLLEN[1:0] AGCUDCTRL */
0x001c, /* 1'b1 PFEN MFEN AICCVSYNC */
0x001d, /* 1'b0 1'b1 1'b0 1'b1 AICCVSYNC */
0x001e, /* AICCALPHA[3:0] 1'b1 1'b0 1'b1 1'b0 01111010 */
0x001f, /* AICCDETTH[19:16] AICCOFFTH[19:16] 00000000 */
0x0020, /* AICCDETTH[15:8] 01111100 */
0x0021, /* AICCDETTH[7:0] 00000000 */
0x0022, /* AICCOFFTH[15:8] 00000101 */
0x0023, /* AICCOFFTH[7:0] 11100000 */
0x0024, /* AICCOPMODE3[1:0] AICCOPMODE2[1:0] AICCOPMODE1[1:0] AICCOPMODE0[1:0] 00000000 */
0x0025, /* AICCFIXFREQ3[23:16] 00000000 */
0x0026, /* AICCFIXFREQ3[15:8] 00000000 */
0x0027, /* AICCFIXFREQ3[7:0] 00000000 */
0x0028, /* AICCFIXFREQ2[23:16] 00000000 */
0x0029, /* AICCFIXFREQ2[15:8] 00000000 */
0x002a, /* AICCFIXFREQ2[7:0] 00000000 */
0x002b, /* AICCFIXFREQ1[23:16] 00000000 */
0x002c, /* AICCFIXFREQ1[15:8] 00000000 */
0x002d, /* AICCFIXFREQ1[7:0] 00000000 */
0x002e, /* AICCFIXFREQ0[23:16] 00000000 */
0x002f, /* AICCFIXFREQ0[15:8] 00000000 */
0x0030, /* AICCFIXFREQ0[7:0] 00000000 */
0x0031, /* 1'b0 1'b1 1'b0 1'b0 x DAGC1STER */
0x0032, /* DAGC1STEN DAGC1STER */
0x0033, /* DAGC1STREF[15:8] 00001010 */
0x0034, /* DAGC1STREF[7:0] 11100100 */
0x0035, /* DAGC2NDE */
0x0036, /* DAGC2NDREF[15:8] 00001010 */
0x0037, /* DAGC2NDREF[7:0] 10000000 */
0x0038, /* DAGC2NDLOCKDETRNGSEL[1:0] */
0x003d, /* 1'b1 SAMGEARS */
0x0040, /* SAMLFGMA */
0x0041, /* SAMLFBWM */
0x0044, /* 1'b1 CRGEARSHE */
0x0045, /* CRLFGMAN */
0x0046, /* CFLFBWMA */
0x0047, /* CRLFGMAN */
0x0048, /* x x x x CRLFGSTEP_VS[3:0] xxxx1001 */
0x0049, /* CRLFBWMA */
0x004a, /* CRLFBWMA */
0x0050, /* 1'b0 1'b1 1'b1 1'b0 MSECALCDA */
0x0070, /* TPOUTEN TPIFEN TPCLKOUTE */
0x0071, /* TPSENB TPSSOPBITE */
0x0073, /* TP47HINS x x CHBERINT PERMODE[1:0] PERINT[1:0] 1xx11100 */
0x0075, /* x x x x x IQSWAPCTRL[2:0] xxxxx000 */
0x0076, /* NBERCON NBERST NBERPOL NBERWSYN */
0x0077, /* x NBERLOSTTH[2:0] NBERACQTH[3:0] x0000000 */
0x0078, /* NBERPOLY[31:24] 00000000 */
0x0079, /* NBERPOLY[23:16] 00000000 */
0x007a, /* NBERPOLY[15:8] 00000000 */
0x007b, /* NBERPOLY[7:0] 00000000 */
0x007c, /* NBERPED[31:24] 00000000 */
0x007d, /* NBERPED[23:16] 00000000 */
0x007e, /* NBERPED[15:8] 00000000 */
0x007f, /* NBERPED[7:0] 00000000 */
0x0080, /* x AGCLOCK DAGCLOCK SYSLOCK x x NEVERLOCK[1:0] */
0x0085, /* SPECINVST */
0x0088, /* SYSLOCKTIME[15:8] */
0x0089, /* SYSLOCKTIME[7:0] */
0x008c, /* FECLOCKTIME[15:8] */
0x008d, /* FECLOCKTIME[7:0] */
0x008e, /* AGCACCOUT[15:8] */
0x008f, /* AGCACCOUT[7:0] */
0x0090, /* AICCREJSTATUS[3:0] AICCREJBUSY[3:0] */
0x0091, /* AICCVSYNC */
0x009c, /* CARRFREQOFFSET[15:8] */
0x009d, /* CARRFREQOFFSET[7:0] */
0x00a1, /* SAMFREQOFFSET[23:16] */
0x00a2, /* SAMFREQOFFSET[15:8] */
0x00a3, /* SAMFREQOFFSET[7:0] */
0x00a6, /* SYNCLOCK SYNCLOCKH */
#if 0 /* covered elsewhere */
0x00e8, /* CONSTPWR[15:8] */
0x00e9, /* CONSTPWR[7:0] */
0x00ea, /* BMSE[15:8] */
0x00eb, /* BMSE[7:0] */
0x00ec, /* MSE[15:8] */
0x00ed, /* MSE[7:0] */
0x00ee, /* CONSTI[7:0] */
0x00ef, /* CONSTQ[7:0] */
#endif
0x00f4, /* TPIFTPERRCNT[7:0] */
0x00f5, /* TPCORREC */
0x00f6, /* VBBER[15:8] */
0x00f7, /* VBBER[7:0] */
0x00f8, /* VABER[15:8] */
0x00f9, /* VABER[7:0] */
0x00fa, /* TPERRCNT[7:0] */
0x00fb, /* NBERLOCK x x x x x x x */
0x00fc, /* NBERVALUE[31:24] */
0x00fd, /* NBERVALUE[23:16] */
0x00fe, /* NBERVALUE[15:8] */
0x00ff, /* NBERVALUE[7:0] */
0x1000, /* 1'b0 WODAGCOU */
0x1005, /* x x 1'b1 1'b1 x SRD_Q_QM */
0x1009, /* SRDWAITTIME[7:0] (10msec) 00100011 */
0x100a, /* SRDWAITTIME_CQS[7:0] (msec) 01100100 */
0x101a, /* x 1'b1 1'b0 1'b0 x QMDQAMMODE[2:0] x100x010 */
0x1036, /* 1'b0 1'b1 1'b0 1'b0 SAMGSEND_CQS[3:0] 01001110 */
0x103c, /* SAMGSAUTOSTL_V[3:0] SAMGSAUTOEDL_V[3:0] 01000110 */
0x103d, /* 1'b1 1'b1 SAMCNORMBP_V[1:0] 1'b0 1'b0 SAMMODESEL_V[1:0] 11100001 */
0x103f, /* SAMZTEDSE */
0x105d, /* EQSTATUSE */
0x105f, /* x PMAPG2_V[2:0] x DMAPG2_V[2:0] x001x011 */
0x1060, /* 1'b1 EQSTATUSE */
0x1061, /* CRMAPBWSTL_V[3:0] CRMAPBWEDL_V[3:0] 00000100 */
0x1065, /* 1'b0 x CRMODE_V[1:0] 1'b1 x 1'b1 x 0x111x1x */
0x1066, /* 1'b0 1'b0 1'b1 1'b0 1'b1 PNBOOSTSE */
0x1068, /* CREPHNGAIN2_V[3:0] CREPHNPBW_V[3:0] 10010001 */
0x106e, /* x x x x x CREPHNEN_ */
0x106f, /* CREPHNTH_V[7:0] 00010101 */
0x1072, /* CRSWEEPN */
0x1073, /* CRPGAIN_V[3:0] x x 1'b1 1'b1 1001xx11 */
0x1074, /* CRPBW_V[3:0] x x 1'b1 1'b1 0001xx11 */
0x1080, /* DAFTSTATUS[1:0] x x x x x x */
0x1081, /* SRDSTATUS[1:0] x x x x x SRDLOCK */
0x10a9, /* EQSTATUS_CQS[1:0] x x x x x x */
0x10b7, /* EQSTATUS_V[1:0] x x x x x x */
#if 0 /* SMART_ANT */
0x1f00, /* MODEDETE */
0x1f01, /* x x x x x x x SFNRST xxxxxxx0 */
0x1f03, /* NUMOFANT[7:0] 10000000 */
0x1f04, /* x SELMASK[6:0] x0000000 */
0x1f05, /* x SETMASK[6:0] x0000000 */
0x1f06, /* x TXDATA[6:0] x0000000 */
0x1f07, /* x CHNUMBER[6:0] x0000000 */
0x1f09, /* AGCTIME[23:16] 10011000 */
0x1f0a, /* AGCTIME[15:8] 10010110 */
0x1f0b, /* AGCTIME[7:0] 10000000 */
0x1f0c, /* ANTTIME[31:24] 00000000 */
0x1f0d, /* ANTTIME[23:16] 00000011 */
0x1f0e, /* ANTTIME[15:8] 10010000 */
0x1f0f, /* ANTTIME[7:0] 10010000 */
0x1f11, /* SYNCTIME[23:16] 10011000 */
0x1f12, /* SYNCTIME[15:8] 10010110 */
0x1f13, /* SYNCTIME[7:0] 10000000 */
0x1f14, /* SNRTIME[31:24] 00000001 */
0x1f15, /* SNRTIME[23:16] 01111101 */
0x1f16, /* SNRTIME[15:8] 01111000 */
0x1f17, /* SNRTIME[7:0] 01000000 */
0x1f19, /* FECTIME[23:16] 00000000 */
0x1f1a, /* FECTIME[15:8] 01110010 */
0x1f1b, /* FECTIME[7:0] 01110000 */
0x1f1d, /* FECTHD[7:0] 00000011 */
0x1f1f, /* SNRTHD[23:16] 00001000 */
0x1f20, /* SNRTHD[15:8] 01111111 */
0x1f21, /* SNRTHD[7:0] 10000101 */
0x1f80, /* IRQFLG x x SFSDRFLG MODEBFLG SAVEFLG SCANFLG TRACKFLG */
0x1f81, /* x SYNCCON SNRCON FECCON x STDBUSY SYNCRST AGCFZCO */
0x1f82, /* x x x SCANOPCD[4:0] */
0x1f83, /* x x x x MAINOPCD[3:0] */
0x1f84, /* x x RXDATA[13:8] */
0x1f85, /* RXDATA[7:0] */
0x1f86, /* x x SDTDATA[13:8] */
0x1f87, /* SDTDATA[7:0] */
0x1f89, /* ANTSNR[23:16] */
0x1f8a, /* ANTSNR[15:8] */
0x1f8b, /* ANTSNR[7:0] */
0x1f8c, /* x x x x ANTFEC[13:8] */
0x1f8d, /* ANTFEC[7:0] */
0x1f8e, /* MAXCNT[7:0] */
0x1f8f, /* SCANCNT[7:0] */
0x1f91, /* MAXPW[23:16] */
0x1f92, /* MAXPW[15:8] */
0x1f93, /* MAXPW[7:0] */
0x1f95, /* CURPWMSE[23:16] */
0x1f96, /* CURPWMSE[15:8] */
0x1f97, /* CURPWMSE[7:0] */
#endif /* SMART_ANT */
0x211f, /* 1'b1 1'b1 1'b1 CIRQEN x x 1'b0 1'b0 1111xx00 */
0x212a, /* EQAUTOST */
0x2122, /* CHFAST[7:0] 01100000 */
0x212b, /* FFFSTEP_V[3:0] x FBFSTEP_V[2:0] 0001x001 */
0x212c, /* PHDEROTBWSEL[3:0] 1'b1 1'b1 1'b1 1'b0 10001110 */
0x212d, /* 1'b1 1'b1 1'b1 1'b1 x x TPIFLOCKS */
0x2135, /* DYNTRACKFDEQ[3:0] x 1'b0 1'b0 1'b0 1010x000 */
0x2141, /* TRMODE[1:0] 1'b1 1'b1 1'b0 1'b1 1'b1 1'b1 01110111 */
0x2162, /* AICCCTRLE */
0x2173, /* PHNCNFCNT[7:0] 00000100 */
0x2179, /* 1'b0 1'b0 1'b0 1'b1 x BADSINGLEDYNTRACKFBF[2:0] 0001x001 */
0x217a, /* 1'b0 1'b0 1'b0 1'b1 x BADSLOWSINGLEDYNTRACKFBF[2:0] 0001x001 */
0x217e, /* CNFCNTTPIF[7:0] 00001000 */
0x217f, /* TPERRCNTTPIF[7:0] 00000001 */
0x2180, /* x x x x x x FBDLYCIR[9:8] */
0x2181, /* FBDLYCIR[7:0] */
0x2185, /* MAXPWRMAIN[7:0] */
0x2191, /* NCOMBDET x x x x x x x */
0x2199, /* x MAINSTRON */
0x219a, /* FFFEQSTEPOUT_V[3:0] FBFSTEPOUT_V[2:0] */
0x21a1, /* x x SNRREF[5:0] */
0x2845, /* 1'b0 1'b1 x x FFFSTEP_CQS[1:0] FFFCENTERTAP[1:0] 01xx1110 */
0x2846, /* 1'b0 x 1'b0 1'b1 FBFSTEP_CQS[1:0] 1'b1 1'b0 0x011110 */
0x2847, /* ENNOSIGDE */
0x2849, /* 1'b1 1'b1 NOUSENOSI */
0x284a, /* EQINITWAITTIME[7:0] 01100100 */
0x3000, /* 1'b1 1'b1 1'b1 x x x 1'b0 RPTRSTM */
0x3001, /* RPTRSTWAITTIME[7:0] (100msec) 00110010 */
0x3031, /* FRAMELOC */
0x3032, /* 1'b1 1'b0 1'b0 1'b0 x x FRAMELOCKMODE_CQS[1:0] 1000xx11 */
0x30a9, /* VDLOCK_Q FRAMELOCK */
0x30aa, /* MPEGLOCK */
};
#define numDumpRegs (sizeof(regtab)/sizeof(regtab[0]))
static u8 regval1[numDumpRegs] = {0, };
static u8 regval2[numDumpRegs] = {0, };
static void lgdt3306a_DumpAllRegs(struct lgdt3306a_state *state)
{
memset(regval2, 0xff, sizeof(regval2));
lgdt3306a_DumpRegs(state);
}
static void lgdt3306a_DumpRegs(struct lgdt3306a_state *state)
{
int i;
int sav_debug = debug;
if ((debug & DBG_DUMP) == 0)
return;
debug &= ~DBG_REG; /* suppress DBG_REG during reg dump */
lg_debug("\n");
for (i = 0; i < numDumpRegs; i++) {
lgdt3306a_read_reg(state, regtab[i], ®val1[i]);
if (regval1[i] != regval2[i]) {
lg_debug(" %04X = %02X\n", regtab[i], regval1[i]);
regval2[i] = regval1[i];
}
}
debug = sav_debug;
}
#endif /* DBG_DUMP */
static struct dvb_frontend_ops lgdt3306a_ops = {
.delsys = { SYS_ATSC, SYS_DVBC_ANNEX_B },
.info = {
.name = "LG Electronics LGDT3306A VSB/QAM Frontend",
.frequency_min = 54000000,
.frequency_max = 858000000,
.frequency_stepsize = 62500,
.caps = FE_CAN_QAM_64 | FE_CAN_QAM_256 | FE_CAN_8VSB
},
.i2c_gate_ctrl = lgdt3306a_i2c_gate_ctrl,
.init = lgdt3306a_init,
.sleep = lgdt3306a_fe_sleep,
/* if this is set, it overrides the default swzigzag */
.tune = lgdt3306a_tune,
.set_frontend = lgdt3306a_set_parameters,
.get_frontend = lgdt3306a_get_frontend,
.get_frontend_algo = lgdt3306a_get_frontend_algo,
.get_tune_settings = lgdt3306a_get_tune_settings,
.read_status = lgdt3306a_read_status,
.read_ber = lgdt3306a_read_ber,
.read_signal_strength = lgdt3306a_read_signal_strength,
.read_snr = lgdt3306a_read_snr,
.read_ucblocks = lgdt3306a_read_ucblocks,
.release = lgdt3306a_release,
.ts_bus_ctrl = lgdt3306a_ts_bus_ctrl,
.search = lgdt3306a_search,
};
MODULE_DESCRIPTION("LG Electronics LGDT3306A ATSC/QAM-B Demodulator Driver");
MODULE_AUTHOR("Fred Richter <frichter@hauppauge.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.2");
| gpl-2.0 |
CoRfr/linux | drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.c | 478 | 121206 | /**
@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.
@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-1500 | Compiler : GCC |
| Module name : hwdrv_apci1500.c| Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-------------------------------+---------------------------------------+
| Description : Hardware Layer Access For APCI-1500 |
+-----------------------------------------------------------------------+
| UPDATES |
+----------+-----------+------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| | | |
| | | |
| | | |
+----------+-----------+------------------------------------------------+
*/
/********* Definitions for APCI-1500 card *****/
/* Card Specific information */
#define APCI1500_ADDRESS_RANGE 4
/* DIGITAL INPUT-OUTPUT DEFINE */
#define APCI1500_DIGITAL_OP 2
#define APCI1500_DIGITAL_IP 0
#define APCI1500_AND 2
#define APCI1500_OR 4
#define APCI1500_OR_PRIORITY 6
#define APCI1500_CLK_SELECT 0
#define COUNTER1 0
#define COUNTER2 1
#define COUNTER3 2
#define APCI1500_COUNTER 0x20
#define APCI1500_TIMER 0
#define APCI1500_WATCHDOG 0
#define APCI1500_SINGLE 0
#define APCI1500_CONTINUOUS 0x80
#define APCI1500_DISABLE 0
#define APCI1500_ENABLE 1
#define APCI1500_SOFTWARE_TRIGGER 0x4
#define APCI1500_HARDWARE_TRIGGER 0x10
#define APCI1500_SOFTWARE_GATE 0
#define APCI1500_HARDWARE_GATE 0x8
#define START 0
#define STOP 1
#define TRIGGER 2
/*
* Zillog I/O enumeration
*/
enum {
APCI1500_Z8536_PORT_C,
APCI1500_Z8536_PORT_B,
APCI1500_Z8536_PORT_A,
APCI1500_Z8536_CONTROL_REGISTER
};
/*
* Z8536 CIO Internal Address
*/
enum {
APCI1500_RW_MASTER_INTERRUPT_CONTROL,
APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
APCI1500_RW_PORT_A_INTERRUPT_CONTROL,
APCI1500_RW_PORT_B_INTERRUPT_CONTROL,
APCI1500_RW_TIMER_COUNTER_INTERRUPT_VECTOR,
APCI1500_RW_PORT_C_DATA_PCITCH_POLARITY,
APCI1500_RW_PORT_C_DATA_DIRECTION,
APCI1500_RW_PORT_C_SPECIAL_IO_CONTROL,
APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
APCI1500_RW_CPT_TMR1_CMD_STATUS,
APCI1500_RW_CPT_TMR2_CMD_STATUS,
APCI1500_RW_CPT_TMR3_CMD_STATUS,
APCI1500_RW_PORT_A_DATA,
APCI1500_RW_PORT_B_DATA,
APCI1500_RW_PORT_C_DATA,
APCI1500_R_CPT_TMR1_VALUE_HIGH,
APCI1500_R_CPT_TMR1_VALUE_LOW,
APCI1500_R_CPT_TMR2_VALUE_HIGH,
APCI1500_R_CPT_TMR2_VALUE_LOW,
APCI1500_R_CPT_TMR3_VALUE_HIGH,
APCI1500_R_CPT_TMR3_VALUE_LOW,
APCI1500_RW_CPT_TMR1_TIME_CST_HIGH,
APCI1500_RW_CPT_TMR1_TIME_CST_LOW,
APCI1500_RW_CPT_TMR2_TIME_CST_HIGH,
APCI1500_RW_CPT_TMR2_TIME_CST_LOW,
APCI1500_RW_CPT_TMR3_TIME_CST_HIGH,
APCI1500_RW_CPT_TMR3_TIME_CST_LOW,
APCI1500_RW_CPT_TMR1_MODE_SPECIFICATION,
APCI1500_RW_CPT_TMR2_MODE_SPECIFICATION,
APCI1500_RW_CPT_TMR3_MODE_SPECIFICATION,
APCI1500_R_CURRENT_VECTOR,
APCI1500_RW_PORT_A_SPECIFICATION,
APCI1500_RW_PORT_A_HANDSHAKE_SPECIFICATION,
APCI1500_RW_PORT_A_DATA_PCITCH_POLARITY,
APCI1500_RW_PORT_A_DATA_DIRECTION,
APCI1500_RW_PORT_A_SPECIAL_IO_CONTROL,
APCI1500_RW_PORT_A_PATTERN_POLARITY,
APCI1500_RW_PORT_A_PATTERN_TRANSITION,
APCI1500_RW_PORT_A_PATTERN_MASK,
APCI1500_RW_PORT_B_SPECIFICATION,
APCI1500_RW_PORT_B_HANDSHAKE_SPECIFICATION,
APCI1500_RW_PORT_B_DATA_PCITCH_POLARITY,
APCI1500_RW_PORT_B_DATA_DIRECTION,
APCI1500_RW_PORT_B_SPECIAL_IO_CONTROL,
APCI1500_RW_PORT_B_PATTERN_POLARITY,
APCI1500_RW_PORT_B_PATTERN_TRANSITION,
APCI1500_RW_PORT_B_PATTERN_MASK
};
static int i_TimerCounter1Init = 0;
static int i_TimerCounter2Init = 0;
static int i_WatchdogCounter3Init = 0;
static int i_Event1Status = 0, i_Event2Status = 0;
static int i_TimerCounterWatchdogInterrupt = 0;
static int i_Logic = 0, i_CounterLogic = 0;
static int i_InterruptMask = 0;
static int i_InputChannel = 0;
static int i_TimerCounter1Enabled = 0, i_TimerCounter2Enabled = 0,
i_WatchdogCounter3Enabled = 0;
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ConfigDigitalInputEvent |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : An event can be generated for each port. |
| The first event is related to the first 8 channels |
| (port 1) and the second to the following 6 channels |
| (port 2). An interrupt is generated when one or both |
| events have occurred |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| |
| data[0] :Number of the input port on |
| which the event will take place |
| (1 or 2)
| data[1] : The event logic for port 1 has |
| three possibilities |
| :0 APCI1500_AND :This logic |
| links |
| the inputs |
| with an AND |
| logic. |
| 1 APCI1500_OR :This logic |
| links |
| the inputs |
| with a |
| OR logic. |
| 2 APCI1500_OR_PRIORITY |
| :This logic |
| links |
| the inputs |
| with a |
| priority |
| OR logic. |
| Input 1 |
| has the |
| highest |
| priority |
| level and |
| input 8 |
| the smallest|
| For the second port the user has|
| 1 possibility: |
| APCI1500_OR :This logic |
| links |
| the inputs |
| with a |
| polarity |
| OR logic |
| data[2] : These 8-character word for port1|
| and 6-character word for port 2 |
| give the mask of the event. |
| Each place gives the state |
| of the input channels and can |
| have one of these six characters|
| |
| 0 : This input must be on 0 |
| 1 : This input must be on 1 |
| 2 : This input reacts to |
| a falling edge |
| 3 : This input reacts to a |
| rising edge |
| 4 : This input reacts to both edges |
|
| 5 : This input is not |
| used for event |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ConfigDigitalInputEvent(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_PatternPolarity = 0, i_PatternTransition = 0, i_PatternMask = 0;
int i_MaxChannel = 0, i_Count = 0, i_EventMask = 0;
int i_PatternTransitionCount = 0, i_RegValue;
int i;
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Disables the main interrupt on the board */
/**********************************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if (data[0] == 1) {
i_MaxChannel = 8;
} /* if (data[0] == 1) */
else {
if (data[0] == 2) {
i_MaxChannel = 6;
} /* if(data[0]==2) */
else {
printk("\nThe specified port event does not exist\n");
return -EINVAL;
} /* else if(data[0]==2) */
} /* else if (data[0] == 1) */
switch (data[1]) {
case 0:
data[1] = APCI1500_AND;
break;
case 1:
data[1] = APCI1500_OR;
break;
case 2:
data[1] = APCI1500_OR_PRIORITY;
break;
default:
printk("\nThe specified interrupt logic does not exist\n");
return -EINVAL;
} /* switch(data[1]); */
i_Logic = data[1];
for (i_Count = i_MaxChannel, i = 0; i_Count > 0; i_Count--, i++) {
i_EventMask = data[2 + i];
switch (i_EventMask) {
case 0:
i_PatternMask =
i_PatternMask | (1 << (i_MaxChannel - i_Count));
break;
case 1:
i_PatternMask =
i_PatternMask | (1 << (i_MaxChannel - i_Count));
i_PatternPolarity =
i_PatternPolarity | (1 << (i_MaxChannel -
i_Count));
break;
case 2:
i_PatternMask =
i_PatternMask | (1 << (i_MaxChannel - i_Count));
i_PatternTransition =
i_PatternTransition | (1 << (i_MaxChannel -
i_Count));
break;
case 3:
i_PatternMask =
i_PatternMask | (1 << (i_MaxChannel - i_Count));
i_PatternPolarity =
i_PatternPolarity | (1 << (i_MaxChannel -
i_Count));
i_PatternTransition =
i_PatternTransition | (1 << (i_MaxChannel -
i_Count));
break;
case 4:
i_PatternTransition =
i_PatternTransition | (1 << (i_MaxChannel -
i_Count));
break;
case 5:
break;
default:
printk("\nThe option indicated in the event mask does not exist\n");
return -EINVAL;
} /* switch(i_EventMask) */
} /* for (i_Count = i_MaxChannel; i_Count >0;i_Count --) */
if (data[0] == 1) {
/****************************/
/* Test the interrupt logic */
/****************************/
if (data[1] == APCI1500_AND ||
data[1] == APCI1500_OR ||
data[1] == APCI1500_OR_PRIORITY) {
/**************************************/
/* Tests if a transition was declared */
/* for a OR PRIORITY logic */
/**************************************/
if (data[1] == APCI1500_OR_PRIORITY
&& i_PatternTransition != 0) {
/********************************************/
/* Transition error on an OR PRIORITY logic */
/********************************************/
printk("\nTransition error on an OR PRIORITY logic\n");
return -EINVAL;
} /* if (data[1]== APCI1500_OR_PRIORITY && i_PatternTransition != 0) */
/*************************************/
/* Tests if more than one transition */
/* was declared for an AND logic */
/*************************************/
if (data[1] == APCI1500_AND) {
for (i_Count = 0; i_Count < 8; i_Count++) {
i_PatternTransitionCount =
i_PatternTransitionCount +
((i_PatternTransition >>
i_Count) & 0x1);
} /* for (i_Count = 0; i_Count < 8; i_Count++) */
if (i_PatternTransitionCount > 1) {
/****************************************/
/* Transition error on an AND logic */
/****************************************/
printk("\n Transition error on an AND logic\n");
return -EINVAL;
} /* if (i_PatternTransitionCount > 1) */
} /* if (data[1]== APCI1500_AND) */
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port A */
/******************/
outb(0xF0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Selects the polarity register of port 1 */
/**********************************************/
outb(APCI1500_RW_PORT_A_PATTERN_POLARITY,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternPolarity,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*********************************************/
/* Selects the pattern mask register of */
/* port 1 */
/*********************************************/
outb(APCI1500_RW_PORT_A_PATTERN_MASK,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternMask,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************************/
/* Selects the pattern transition register */
/* of port 1 */
/********************************************/
outb(APCI1500_RW_PORT_A_PATTERN_TRANSITION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternTransition,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************************************/
/* Selects the mode specification mask */
/* register of port 1 */
/******************************************/
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************************************/
/* Selects the mode specification mask */
/* register of port 1 */
/******************************************/
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************/
/* Port A new mode */
/**********************/
i_RegValue = (i_RegValue & 0xF9) | data[1] | 0x9;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event1Status = 1;
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port A */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY) */
else {
printk("\nThe choice for interrupt logic does not exist\n");
return -EINVAL;
} /* else }// if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY) */
} /* if (data[0]== 1) */
/************************************/
/* Test if event setting for port 2 */
/************************************/
if (data[0] == 2) {
/************************/
/* Test the event logic */
/************************/
if (data[1] == APCI1500_OR) {
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port B */
/******************/
outb(0x74,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************/
/* Selects the mode specification mask */
/* register of port B */
/****************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************************************/
/* Selects the mode specification mask */
/* register of port B */
/******************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = i_RegValue & 0xF9;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************************/
/* Selects error channels 1 and 2 */
/**********************************/
i_PatternMask = (i_PatternMask | 0xC0);
i_PatternPolarity = (i_PatternPolarity | 0xC0);
i_PatternTransition = (i_PatternTransition | 0xC0);
/**********************************************/
/* Selects the polarity register of port 2 */
/**********************************************/
outb(APCI1500_RW_PORT_B_PATTERN_POLARITY,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternPolarity,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Selects the pattern transition register */
/* of port 2 */
/**********************************************/
outb(APCI1500_RW_PORT_B_PATTERN_TRANSITION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternTransition,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Selects the pattern Mask register */
/* of port 2 */
/**********************************************/
outb(APCI1500_RW_PORT_B_PATTERN_MASK,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_PatternMask,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************************************/
/* Selects the mode specification mask */
/* register of port 2 */
/******************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/******************************************/
/* Selects the mode specification mask */
/* register of port 2 */
/******************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = (i_RegValue & 0xF9) | 4;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event2Status = 1;
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port B */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if (data[1] == APCI1500_OR) */
else {
printk("\nThe choice for interrupt logic does not exist\n");
return -EINVAL;
} /* elseif (data[1] == APCI1500_OR) */
} /* if(data[0]==2) */
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_StartStopInputEvent |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Allows or disallows a port event |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int ui_Channel : Channel number to read |
| unsigned int *data : Data Pointer to read status |
| data[0] :0 Start input event
| 1 Stop input event
| data[1] :No of port (1 or 2)
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_StartStopInputEvent(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_Event1InterruptStatus = 0, i_Event2InterruptStatus =
0, i_RegValue;
switch (data[0]) {
case START:
/*************************/
/* Tests the port number */
/*************************/
if (data[1] == 1 || data[1] == 2) {
/***************************/
/* Test if port 1 selected */
/***************************/
if (data[1] == 1) {
/*****************************/
/* Test if event initialised */
/*****************************/
if (i_Event1Status == 1) {
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port A */
/******************/
outb(0xF0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the command and status register of */
/* port 1 */
/***************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************/
/* Allows the pattern interrupt */
/*************************************/
outb(0xC0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port A */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event1InterruptStatus = 1;
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Authorizes the main interrupt on the board */
/**********************************************/
outb(0xD0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if(i_Event1Status==1) */
else {
printk("\nEvent 1 not initialised\n");
return -EINVAL;
} /* else if(i_Event1Status==1) */
} /* if (data[1]==1) */
if (data[1] == 2) {
if (i_Event2Status == 1) {
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port B */
/******************/
outb(0x74,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the command and status register of */
/* port 2 */
/***************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************/
/* Allows the pattern interrupt */
/*************************************/
outb(0xC0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port B */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Authorizes the main interrupt on the board */
/**********************************************/
outb(0xD0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event2InterruptStatus = 1;
} /* if(i_Event2Status==1) */
else {
printk("\nEvent 2 not initialised\n");
return -EINVAL;
} /* else if(i_Event2Status==1) */
} /* if(data[1]==2) */
} /* if (data[1] == 1 || data[0] == 2) */
else {
printk("\nThe port parameter is in error\n");
return -EINVAL;
} /* else if (data[1] == 1 || data[0] == 2) */
break;
case STOP:
/*************************/
/* Tests the port number */
/*************************/
if (data[1] == 1 || data[1] == 2) {
/***************************/
/* Test if port 1 selected */
/***************************/
if (data[1] == 1) {
/*****************************/
/* Test if event initialised */
/*****************************/
if (i_Event1Status == 1) {
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port A */
/******************/
outb(0xF0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the command and status register of */
/* port 1 */
/***************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************/
/* Inhibits the pattern interrupt */
/*************************************/
outb(0xE0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port A */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event1InterruptStatus = 0;
} /* if(i_Event1Status==1) */
else {
printk("\nEvent 1 not initialised\n");
return -EINVAL;
} /* else if(i_Event1Status==1) */
} /* if (data[1]==1) */
if (data[1] == 2) {
/*****************************/
/* Test if event initialised */
/*****************************/
if (i_Event2Status == 1) {
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************/
/* Disable Port B */
/******************/
outb(0x74,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the command and status register of */
/* port 2 */
/***************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************/
/* Inhibits the pattern interrupt */
/*************************************/
outb(0xE0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************************/
/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
/*****************************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************/
/* Enable Port B */
/*****************/
outb(0xF4,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_Event2InterruptStatus = 0;
} /* if(i_Event2Status==1) */
else {
printk("\nEvent 2 not initialised\n");
return -EINVAL;
} /* else if(i_Event2Status==1) */
} /* if(data[1]==2) */
} /* if (data[1] == 1 || data[1] == 2) */
else {
printk("\nThe port parameter is in error\n");
return -EINVAL;
} /* else if (data[1] == 1 || data[1] == 2) */
break;
default:
printk("\nThe option of START/STOP logic does not exist\n");
return -EINVAL;
} /* switch(data[0]) */
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_Initialisation |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Return the status of the digital input |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int ui_Channel : Channel number to read |
| unsigned int *data : Data Pointer to read status |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_Initialisation(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_DummyRead = 0;
/******************/
/* Software reset */
/******************/
i_DummyRead = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_DummyRead = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(1, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the master configuration control register */
/*****************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0xF4, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the mode specification register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0x10, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data path polarity register of port A */
outb(APCI1500_RW_PORT_A_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* High level of port A means 1 */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port A */
outb(APCI1500_RW_PORT_A_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port A */
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port A */
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of port A: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the handshake specification register of port A */
outb(APCI1500_RW_PORT_A_HANDSHAKE_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes the register */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the mode specification register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0x10, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data path polarity register of port B */
outb(APCI1500_RW_PORT_B_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* A high level of port B means 1 */
outb(0x7F, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port B */
outb(APCI1500_RW_PORT_B_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port B */
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port B */
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of port B: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the handshake specification register of port B */
outb(APCI1500_RW_PORT_B_HANDSHAKE_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes the register */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the data path polarity register of port C */
/*****************************************************/
outb(APCI1500_RW_PORT_C_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* High level of port C means 1 */
outb(0x9, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port C */
outb(APCI1500_RW_PORT_C_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs except channel 1 */
outb(0x0E, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the special IO register of port C */
outb(APCI1500_RW_PORT_C_SPECIAL_IO_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes it */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 1 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of timer 1 */
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of timer 1 */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 2 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of timer 2 */
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates Timer 2 interrupt management: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 3 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of Timer 3 */
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates interrupt management of timer 3: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes all interrupts */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
return insn->n;
}
static int apci1500_di_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
data[1] = inw(devpriv->i_IobaseAddon + APCI1500_DIGITAL_IP);
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ConfigDigitalOutputErrorInterrupt
| (struct comedi_device *dev,struct comedi_subdevice *s struct comedi_insn
| *insn,unsigned int *data) |
| |
+----------------------------------------------------------------------------+
| Task : Configures the digital output memory and the digital
| output error interrupt |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| data[0] :1:Memory on |
| 0:Memory off |
| data[1] :1 Enable the voltage error interrupt
| :0 Disable the voltage error interrupt |
| |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ConfigDigitalOutputErrorInterrupt(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
devpriv->b_OutputMemoryStatus = data[0];
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_WriteDigitalOutput |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Writes port value To the selected port |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int ui_NoOfChannels : No Of Channels To Write |
| unsigned int *data : Data Pointer to read status |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_WriteDigitalOutput(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
static unsigned int ui_Temp = 0;
unsigned int ui_Temp1;
unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec); /* get the channel */
if (!devpriv->b_OutputMemoryStatus) {
ui_Temp = 0;
} /* if(!devpriv->b_OutputMemoryStatus ) */
if (data[3] == 0) {
if (data[1] == 0) {
data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
outw(data[0],
devpriv->i_IobaseAddon + APCI1500_DIGITAL_OP);
} /* if(data[1]==0) */
else {
if (data[1] == 1) {
switch (ui_NoOfChannel) {
case 2:
data[0] =
(data[0] << (2 *
data[2])) | ui_Temp;
break;
case 4:
data[0] =
(data[0] << (4 *
data[2])) | ui_Temp;
break;
case 8:
data[0] =
(data[0] << (8 *
data[2])) | ui_Temp;
break;
case 15:
data[0] = data[0] | ui_Temp;
break;
default:
comedi_error(dev, " chan spec wrong");
return -EINVAL; /* "sorry channel spec wrong " */
} /* switch(ui_NoOfChannels) */
outw(data[0],
devpriv->i_IobaseAddon +
APCI1500_DIGITAL_OP);
} /* if(data[1]==1) */
else {
printk("\nSpecified channel not supported\n");
} /* else if(data[1]==1) */
} /* elseif(data[1]==0) */
} /* if(data[3]==0) */
else {
if (data[3] == 1) {
if (data[1] == 0) {
data[0] = ~data[0] & 0x1;
ui_Temp1 = 1;
ui_Temp1 = ui_Temp1 << ui_NoOfChannel;
ui_Temp = ui_Temp | ui_Temp1;
data[0] =
(data[0] << ui_NoOfChannel) ^
0xffffffff;
data[0] = data[0] & ui_Temp;
outw(data[0],
devpriv->i_IobaseAddon +
APCI1500_DIGITAL_OP);
} /* if(data[1]==0) */
else {
if (data[1] == 1) {
switch (ui_NoOfChannel) {
case 2:
data[0] = ~data[0] & 0x3;
ui_Temp1 = 3;
ui_Temp1 =
ui_Temp1 << 2 * data[2];
ui_Temp = ui_Temp | ui_Temp1;
data[0] =
((data[0] << (2 *
data
[2])) ^
0xffffffff) & ui_Temp;
break;
case 4:
data[0] = ~data[0] & 0xf;
ui_Temp1 = 15;
ui_Temp1 =
ui_Temp1 << 4 * data[2];
ui_Temp = ui_Temp | ui_Temp1;
data[0] =
((data[0] << (4 *
data
[2])) ^
0xffffffff) & ui_Temp;
break;
case 8:
data[0] = ~data[0] & 0xff;
ui_Temp1 = 255;
ui_Temp1 =
ui_Temp1 << 8 * data[2];
ui_Temp = ui_Temp | ui_Temp1;
data[0] =
((data[0] << (8 *
data
[2])) ^
0xffffffff) & ui_Temp;
break;
case 15:
break;
default:
comedi_error(dev,
" chan spec wrong");
return -EINVAL; /* "sorry channel spec wrong " */
} /* switch(ui_NoOfChannels) */
outw(data[0],
devpriv->i_IobaseAddon +
APCI1500_DIGITAL_OP);
} /* if(data[1]==1) */
else {
printk("\nSpecified channel not supported\n");
} /* else if(data[1]==1) */
} /* elseif(data[1]==0) */
} /* if(data[3]==1); */
else {
printk("\nSpecified functionality does not exist\n");
return -EINVAL;
} /* if else data[3]==1) */
} /* if else data[3]==0) */
ui_Temp = data[0];
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ConfigCounterTimerWatchdog(comedi_device
| *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
| |
+----------------------------------------------------------------------------+
| Task : Configures The Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| unsigned int *data : Data Pointer to read status data[0] : 2 APCI1500_1_8_KHZ
| 1 APCI1500_3_6_KHZ |
| 0 APCI1500_115_KHZ
| data[1] : 0 Counter1/Timer1
| 1 Counter2/Timer2
| 2 Counter3/Watchdog
| data[2] : 0 Counter
| 1 Timer/Watchdog
| data[3] : This parameter has |
| two meanings. |
| - If the counter/timer |
| is used as a counter |
| the limit value of |
| the counter is given |
| |
| - If the counter/timer |
| is used as a timer, |
| the divider factor |
| for the output is |
| given.
| data[4] : 0 APCI1500_CONTINUOUS
| 1 APCI1500_SINGLE
| data[5] : 0 Software Trigger
| 1 Hardware Trigger
|
| data[6] :0 Software gate
| 1 Hardware gate
| data[7] :0 Interrupt Disable
| 1 Interrupt Enable
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ConfigCounterTimerWatchdog(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_TimerCounterMode, i_MasterConfiguration;
devpriv->tsk_Current = current;
/* Selection of the input clock */
if (data[0] == 0 || data[0] == 1 || data[0] == 2) {
outw(data[0], devpriv->i_IobaseAddon + APCI1500_CLK_SELECT);
} /* if(data[0]==0||data[0]==1||data[0]==2) */
else {
if (data[0] != 3) {
printk("\nThe option for input clock selection does not exist\n");
return -EINVAL;
} /* if(data[0]!=3) */
} /* elseif(data[0]==0||data[0]==1||data[0]==2) */
/* Select the counter/timer */
switch (data[1]) {
case COUNTER1:
/* selecting counter or timer */
switch (data[2]) {
case 0:
data[2] = APCI1500_COUNTER;
break;
case 1:
data[2] = APCI1500_TIMER;
break;
default:
printk("\nThis choice is not a timer nor a counter\n");
return -EINVAL;
} /* switch(data[2]) */
/* Selecting single or continuous mode */
switch (data[4]) {
case 0:
data[4] = APCI1500_CONTINUOUS;
break;
case 1:
data[4] = APCI1500_SINGLE;
break;
default:
printk("\nThis option for single/continuous mode does not exist\n");
return -EINVAL;
} /* switch(data[4]) */
i_TimerCounterMode = data[2] | data[4] | 7;
/*************************/
/* Test the reload value */
/*************************/
if ((data[3] >= 0) && (data[3] <= 65535)) {
if (data[7] == APCI1500_ENABLE
|| data[7] == APCI1500_DISABLE) {
/************************************************/
/* Selects the mode register of timer/counter 1 */
/************************************************/
outb(APCI1500_RW_CPT_TMR1_MODE_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************/
/* Writes the new mode */
/***********************/
outb(i_TimerCounterMode,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of timer/counter 1 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR1_TIME_CST_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************/
/* Writes the low value */
/*************************/
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of timer/counter 1 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR1_TIME_CST_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**************************/
/* Writes the high value */
/**************************/
data[3] = data[3] >> 8;
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************/
/* Reads the register */
/**********************/
i_MasterConfiguration =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************************************/
/* Enables timer/counter 1 and triggers timer/counter 1 */
/********************************************************/
i_MasterConfiguration =
i_MasterConfiguration | 0x40;
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************/
/* Writes the new configuration */
/********************************/
outb(i_MasterConfiguration,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************/
/* Selects the commands register of */
/* timer/counter 1 */
/****************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************/
/* Disable timer/counter 1 */
/***************************/
outb(0x0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************/
/* Selects the commands register of */
/* timer/counter 1 */
/****************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************/
/* Trigger timer/counter 1 */
/***************************/
outb(0x2,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
else {
printk("\nError in selection of interrupt enable or disable\n");
return -EINVAL;
} /* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
} /* if ((data[3]>= 0) && (data[3] <= 65535)) */
else {
printk("\nError in selection of reload value\n");
return -EINVAL;
} /* else if ((data[3]>= 0) && (data[3] <= 65535)) */
i_TimerCounterWatchdogInterrupt = data[7];
i_TimerCounter1Init = 1;
break;
case COUNTER2: /* selecting counter or timer */
switch (data[2]) {
case 0:
data[2] = APCI1500_COUNTER;
break;
case 1:
data[2] = APCI1500_TIMER;
break;
default:
printk("\nThis choice is not a timer nor a counter\n");
return -EINVAL;
} /* switch(data[2]) */
/* Selecting single or continuous mode */
switch (data[4]) {
case 0:
data[4] = APCI1500_CONTINUOUS;
break;
case 1:
data[4] = APCI1500_SINGLE;
break;
default:
printk("\nThis option for single/continuous mode does not exist\n");
return -EINVAL;
} /* switch(data[4]) */
/* Selecting software or hardware trigger */
switch (data[5]) {
case 0:
data[5] = APCI1500_SOFTWARE_TRIGGER;
break;
case 1:
data[5] = APCI1500_HARDWARE_TRIGGER;
break;
default:
printk("\nThis choice for software or hardware trigger does not exist\n");
return -EINVAL;
} /* switch(data[5]) */
/* Selecting software or hardware gate */
switch (data[6]) {
case 0:
data[6] = APCI1500_SOFTWARE_GATE;
break;
case 1:
data[6] = APCI1500_HARDWARE_GATE;
break;
default:
printk("\nThis choice for software or hardware gate does not exist\n");
return -EINVAL;
} /* switch(data[6]) */
i_TimerCounterMode = data[2] | data[4] | data[5] | data[6] | 7;
/*************************/
/* Test the reload value */
/*************************/
if ((data[3] >= 0) && (data[3] <= 65535)) {
if (data[7] == APCI1500_ENABLE
|| data[7] == APCI1500_DISABLE) {
/************************************************/
/* Selects the mode register of timer/counter 2 */
/************************************************/
outb(APCI1500_RW_CPT_TMR2_MODE_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************/
/* Writes the new mode */
/***********************/
outb(i_TimerCounterMode,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of timer/counter 2 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR2_TIME_CST_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************/
/* Writes the low value */
/*************************/
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of timer/counter 2 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR2_TIME_CST_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**************************/
/* Writes the high value */
/**************************/
data[3] = data[3] >> 8;
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************/
/* Reads the register */
/**********************/
i_MasterConfiguration =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************************************/
/* Enables timer/counter 2 and triggers timer/counter 2 */
/********************************************************/
i_MasterConfiguration =
i_MasterConfiguration | 0x20;
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************/
/* Writes the new configuration */
/********************************/
outb(i_MasterConfiguration,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************/
/* Selects the commands register of */
/* timer/counter 2 */
/****************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************/
/* Disable timer/counter 2 */
/***************************/
outb(0x0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************/
/* Selects the commands register of */
/* timer/counter 2 */
/****************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************/
/* Trigger timer/counter 1 */
/***************************/
outb(0x2,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
else {
printk("\nError in selection of interrupt enable or disable\n");
return -EINVAL;
} /* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
} /* if ((data[3]>= 0) && (data[3] <= 65535)) */
else {
printk("\nError in selection of reload value\n");
return -EINVAL;
} /* else if ((data[3]>= 0) && (data[3] <= 65535)) */
i_TimerCounterWatchdogInterrupt = data[7];
i_TimerCounter2Init = 1;
break;
case COUNTER3: /* selecting counter or watchdog */
switch (data[2]) {
case 0:
data[2] = APCI1500_COUNTER;
break;
case 1:
data[2] = APCI1500_WATCHDOG;
break;
default:
printk("\nThis choice is not a watchdog nor a counter\n");
return -EINVAL;
} /* switch(data[2]) */
/* Selecting single or continuous mode */
switch (data[4]) {
case 0:
data[4] = APCI1500_CONTINUOUS;
break;
case 1:
data[4] = APCI1500_SINGLE;
break;
default:
printk("\nThis option for single/continuous mode does not exist\n");
return -EINVAL;
} /* switch(data[4]) */
/* Selecting software or hardware gate */
switch (data[6]) {
case 0:
data[6] = APCI1500_SOFTWARE_GATE;
break;
case 1:
data[6] = APCI1500_HARDWARE_GATE;
break;
default:
printk("\nThis choice for software or hardware gate does not exist\n");
return -EINVAL;
} /* switch(data[6]) */
/*****************************/
/* Test if used for watchdog */
/*****************************/
if (data[2] == APCI1500_WATCHDOG) {
/*****************************/
/* - Enables the output line */
/* - Enables retrigger */
/* - Pulses output */
/*****************************/
i_TimerCounterMode = data[2] | data[4] | 0x54;
} /* if (data[2] == APCI1500_WATCHDOG) */
else {
i_TimerCounterMode = data[2] | data[4] | data[6] | 7;
} /* elseif (data[2] == APCI1500_WATCHDOG) */
/*************************/
/* Test the reload value */
/*************************/
if ((data[3] >= 0) && (data[3] <= 65535)) {
if (data[7] == APCI1500_ENABLE
|| data[7] == APCI1500_DISABLE) {
/************************************************/
/* Selects the mode register of watchdog/counter 3 */
/************************************************/
outb(APCI1500_RW_CPT_TMR3_MODE_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************/
/* Writes the new mode */
/***********************/
outb(i_TimerCounterMode,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of watchdog/counter 3 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR3_TIME_CST_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************/
/* Writes the low value */
/*************************/
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/****************************************************/
/* Selects the constant register of watchdog/counter 3 */
/****************************************************/
outb(APCI1500_RW_CPT_TMR3_TIME_CST_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**************************/
/* Writes the high value */
/**************************/
data[3] = data[3] >> 8;
outb(data[3],
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/**********************/
/* Reads the register */
/**********************/
i_MasterConfiguration =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************************************/
/* Enables watchdog/counter 3 and triggers watchdog/counter 3 */
/********************************************************/
i_MasterConfiguration =
i_MasterConfiguration | 0x10;
/*********************************************/
/* Selects the master configuration register */
/*********************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************************/
/* Writes the new configuration */
/********************************/
outb(i_MasterConfiguration,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/********************/
/* Test if COUNTER */
/********************/
if (data[2] == APCI1500_COUNTER) {
/*************************************/
/* Selects the command register of */
/* watchdog/counter 3 */
/*************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************************************/
/* Disable the watchdog/counter 3 and starts it */
/*************************************************/
outb(0x0,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************************/
/* Selects the command register of */
/* watchdog/counter 3 */
/*************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/*************************************************/
/* Trigger the watchdog/counter 3 and starts it */
/*************************************************/
outb(0x2,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* elseif(data[2]==APCI1500_COUNTER) */
} /* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
else {
printk("\nError in selection of interrupt enable or disable\n");
return -EINVAL;
} /* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
} /* if ((data[3]>= 0) && (data[3] <= 65535)) */
else {
printk("\nError in selection of reload value\n");
return -EINVAL;
} /* else if ((data[3]>= 0) && (data[3] <= 65535)) */
i_TimerCounterWatchdogInterrupt = data[7];
i_WatchdogCounter3Init = 1;
break;
default:
printk("\nThe specified counter\timer option does not exist\n");
} /* switch(data[1]) */
i_CounterLogic = data[2];
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_StartStopTriggerTimerCounterWatchdog |
| (struct comedi_device *dev,struct comedi_subdevice *s,
| struct comedi_insn *insn,unsigned int *data); |
+----------------------------------------------------------------------------+
| Task : Start / Stop or trigger the timer counter or Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| unsigned int *data : Data Pointer to read status |
| data[0] : 0 Counter1/Timer1
| 1 Counter2/Timer2
| 2 Counter3/Watchdog
| data[1] : 0 start
| 1 stop
| 2 Trigger
| data[2] : 0 Counter
| 1 Timer/Watchdog
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_StartStopTriggerTimerCounterWatchdog(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_CommandAndStatusValue;
switch (data[0]) {
case COUNTER1:
switch (data[1]) {
case START:
if (i_TimerCounter1Init == 1) {
if (i_TimerCounterWatchdogInterrupt == 1) {
i_CommandAndStatusValue = 0xC4; /* Enable the interrupt */
} /* if(i_TimerCounterWatchdogInterrupt==1) */
else {
i_CommandAndStatusValue = 0xE4; /* disable the interrupt */
} /* elseif(i_TimerCounterWatchdogInterrupt==1) */
/**************************/
/* Starts timer/counter 1 */
/**************************/
i_TimerCounter1Enabled = 1;
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter1Init==1) */
else {
printk("\nCounter/Timer1 not configured\n");
return -EINVAL;
}
break;
case STOP:
/**************************/
/* Stop timer/counter 1 */
/**************************/
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(0x00,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_TimerCounter1Enabled = 0;
break;
case TRIGGER:
if (i_TimerCounter1Init == 1) {
if (i_TimerCounter1Enabled == 1) {
/************************/
/* Set Trigger and gate */
/************************/
i_CommandAndStatusValue = 0x6;
} /* if( i_TimerCounter1Enabled==1) */
else {
/***************/
/* Set Trigger */
/***************/
i_CommandAndStatusValue = 0x2;
} /* elseif(i_TimerCounter1Enabled==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter1Init==1) */
else {
printk("\nCounter/Timer1 not configured\n");
return -EINVAL;
}
break;
default:
printk("\nThe specified option for start/stop/trigger does not exist\n");
return -EINVAL;
} /* switch(data[1]) */
break;
case COUNTER2:
switch (data[1]) {
case START:
if (i_TimerCounter2Init == 1) {
if (i_TimerCounterWatchdogInterrupt == 1) {
i_CommandAndStatusValue = 0xC4; /* Enable the interrupt */
} /* if(i_TimerCounterWatchdogInterrupt==1) */
else {
i_CommandAndStatusValue = 0xE4; /* disable the interrupt */
} /* elseif(i_TimerCounterWatchdogInterrupt==1) */
/**************************/
/* Starts timer/counter 2 */
/**************************/
i_TimerCounter2Enabled = 1;
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter2Init==1) */
else {
printk("\nCounter/Timer2 not configured\n");
return -EINVAL;
}
break;
case STOP:
/**************************/
/* Stop timer/counter 2 */
/**************************/
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(0x00,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_TimerCounter2Enabled = 0;
break;
case TRIGGER:
if (i_TimerCounter2Init == 1) {
if (i_TimerCounter2Enabled == 1) {
/************************/
/* Set Trigger and gate */
/************************/
i_CommandAndStatusValue = 0x6;
} /* if( i_TimerCounter2Enabled==1) */
else {
/***************/
/* Set Trigger */
/***************/
i_CommandAndStatusValue = 0x2;
} /* elseif(i_TimerCounter2Enabled==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter2Init==1) */
else {
printk("\nCounter/Timer2 not configured\n");
return -EINVAL;
}
break;
default:
printk("\nThe specified option for start/stop/trigger does not exist\n");
return -EINVAL;
} /* switch(data[1]) */
break;
case COUNTER3:
switch (data[1]) {
case START:
if (i_WatchdogCounter3Init == 1) {
if (i_TimerCounterWatchdogInterrupt == 1) {
i_CommandAndStatusValue = 0xC4; /* Enable the interrupt */
} /* if(i_TimerCounterWatchdogInterrupt==1) */
else {
i_CommandAndStatusValue = 0xE4; /* disable the interrupt */
} /* elseif(i_TimerCounterWatchdogInterrupt==1) */
/**************************/
/* Starts Watchdog/counter 3 */
/**************************/
i_WatchdogCounter3Enabled = 1;
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_WatchdogCounter3init==1) */
else {
printk("\nWatchdog/Counter3 not configured\n");
return -EINVAL;
}
break;
case STOP:
/**************************/
/* Stop Watchdog/counter 3 */
/**************************/
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(0x00,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_WatchdogCounter3Enabled = 0;
break;
case TRIGGER:
switch (data[2]) {
case 0: /* triggering counter 3 */
if (i_WatchdogCounter3Init == 1) {
if (i_WatchdogCounter3Enabled == 1) {
/************************/
/* Set Trigger and gate */
/************************/
i_CommandAndStatusValue = 0x6;
} /* if( i_WatchdogCounter3Enabled==1) */
else {
/***************/
/* Set Trigger */
/***************/
i_CommandAndStatusValue = 0x2;
} /* elseif(i_WatchdogCounter3Enabled==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_WatchdogCounter3Init==1) */
else {
printk("\nCounter3 not configured\n");
return -EINVAL;
}
break;
case 1:
/* triggering Watchdog 3 */
if (i_WatchdogCounter3Init == 1) {
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(0x6,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_WatchdogCounter3Init==1) */
else {
printk("\nWatchdog 3 not configured\n");
return -EINVAL;
}
break;
default:
printk("\nWrong choice of watchdog/counter3\n");
return -EINVAL;
} /* switch(data[2]) */
break;
default:
printk("\nThe specified option for start/stop/trigger does not exist\n");
return -EINVAL;
} /* switch(data[1]) */
break;
default:
printk("\nThe specified choice for counter/watchdog/timer does not exist\n");
return -EINVAL;
} /* switch(data[0]) */
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ReadCounterTimerWatchdog |
| (struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
| unsigned int *data); |
+----------------------------------------------------------------------------+
| Task : Read The Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| unsigned int *data : Data Pointer to read status |
| data[0] : 0 Counter1/Timer1
| 1 Counter2/Timer2
| 2 Counter3/Watchdog
|
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ReadCounterTimerWatchdog(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
int i_CommandAndStatusValue;
switch (data[0]) {
case COUNTER1:
/* Read counter/timer1 */
if (i_TimerCounter1Init == 1) {
if (i_TimerCounter1Enabled == 1) {
/************************/
/* Set RCC and gate */
/************************/
i_CommandAndStatusValue = 0xC;
} /* if( i_TimerCounter1Init==1) */
else {
/***************/
/* Set RCC */
/***************/
i_CommandAndStatusValue = 0x8;
} /* elseif(i_TimerCounter1Init==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************/
/* Selects the counter register (high) */
/***************************************/
outb(APCI1500_R_CPT_TMR1_VALUE_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] = data[0] << 8;
data[0] = data[0] & 0xff00;
outb(APCI1500_R_CPT_TMR1_VALUE_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
data[0] | inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter1Init==1) */
else {
printk("\nTimer/Counter1 not configured\n");
return -EINVAL;
} /* elseif( i_TimerCounter1Init==1) */
break;
case COUNTER2:
/* Read counter/timer2 */
if (i_TimerCounter2Init == 1) {
if (i_TimerCounter2Enabled == 1) {
/************************/
/* Set RCC and gate */
/************************/
i_CommandAndStatusValue = 0xC;
} /* if( i_TimerCounter2Init==1) */
else {
/***************/
/* Set RCC */
/***************/
i_CommandAndStatusValue = 0x8;
} /* elseif(i_TimerCounter2Init==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************/
/* Selects the counter register (high) */
/***************************************/
outb(APCI1500_R_CPT_TMR2_VALUE_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] = data[0] << 8;
data[0] = data[0] & 0xff00;
outb(APCI1500_R_CPT_TMR2_VALUE_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
data[0] | inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_TimerCounter2Init==1) */
else {
printk("\nTimer/Counter2 not configured\n");
return -EINVAL;
} /* elseif( i_TimerCounter2Init==1) */
break;
case COUNTER3:
/* Read counter/watchdog2 */
if (i_WatchdogCounter3Init == 1) {
if (i_WatchdogCounter3Enabled == 1) {
/************************/
/* Set RCC and gate */
/************************/
i_CommandAndStatusValue = 0xC;
} /* if( i_TimerCounter2Init==1) */
else {
/***************/
/* Set RCC */
/***************/
i_CommandAndStatusValue = 0x8;
} /* elseif(i_WatchdogCounter3Init==1) */
/********************************************/
/* Selects the commands and status register */
/********************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
outb(i_CommandAndStatusValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************/
/* Selects the counter register (high) */
/***************************************/
outb(APCI1500_R_CPT_TMR3_VALUE_HIGH,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] = data[0] << 8;
data[0] = data[0] & 0xff00;
outb(APCI1500_R_CPT_TMR3_VALUE_LOW,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
data[0] =
data[0] | inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
} /* if( i_WatchdogCounter3Init==1) */
else {
printk("\nWatchdogCounter3 not configured\n");
return -EINVAL;
} /* elseif( i_WatchdogCounter3Init==1) */
break;
default:
printk("\nThe choice of timer/counter/watchdog does not exist\n");
return -EINVAL;
} /* switch(data[0]) */
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ReadInterruptMask |
| (struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
| unsigned int *data); |
+----------------------------------------------------------------------------+
| Task : Read the interrupt mask |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| unsigned int *data : Data Pointer to read status |
+----------------------------------------------------------------------------+
| Output Parameters : -- data[0]:The interrupt mask value data[1]:Channel no
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ReadInterruptMask(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
data[0] = i_InterruptMask;
data[1] = i_InputChannel;
i_InterruptMask = 0;
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_ConfigureInterrupt |
| (struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
| unsigned int *data); |
+----------------------------------------------------------------------------+
| Task : Configures the interrupt registers |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s, :pointer to subdevice structure
| struct comedi_insn *insn :pointer to insn structure |
| unsigned int *data : Data Pointer |
|
+----------------------------------------------------------------------------+
| Output Parameters : --
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_ConfigureInterrupt(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
unsigned int ui_Status;
int i_RegValue;
int i_Constant;
devpriv->tsk_Current = current;
outl(0x0, devpriv->i_IobaseAmcc + 0x38);
if (data[0] == 1) {
i_Constant = 0xC0;
} /* if(data[0]==1) */
else {
if (data[0] == 0) {
i_Constant = 0x00;
} /* if{data[0]==0) */
else {
printk("\nThe parameter passed to driver is in error for enabling the voltage interrupt\n");
return -EINVAL;
} /* else if(data[0]==0) */
} /* elseif(data[0]==1) */
/*****************************************************/
/* Selects the mode specification register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*********************************************/
/* Writes the new configuration (APCI1500_OR) */
/*********************************************/
i_RegValue = (i_RegValue & 0xF9) | APCI1500_OR;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************/
/* Authorises the interrupt on the board */
/*****************************************/
outb(0xC0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the pattern polarity register of port B */
/***************************************************/
outb(APCI1500_RW_PORT_B_PATTERN_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(i_Constant, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the pattern transition register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_PATTERN_TRANSITION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(i_Constant, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************************/
/* Selects the pattern mask register of port B */
/***********************************************/
outb(APCI1500_RW_PORT_B_PATTERN_MASK,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(i_Constant, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of port A */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of port B */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 1 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 1 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 2 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 2 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 3 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 3 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Authorizes the main interrupt on the board */
/**********************************************/
outb(0xD0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/***************************/
/* Enables the PCI interrupt */
/*****************************/
outl(0x3000, devpriv->i_IobaseAmcc + 0x38);
ui_Status = inl(devpriv->i_IobaseAmcc + 0x10);
ui_Status = inl(devpriv->i_IobaseAmcc + 0x38);
outl(0x23000, devpriv->i_IobaseAmcc + 0x38);
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : static void v_APCI1500_Interrupt |
| (int irq , void *d) |
+----------------------------------------------------------------------------+
| Task : Interrupt handler |
+----------------------------------------------------------------------------+
| Input Parameters : int irq : irq number |
| void *d : void pointer |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static void v_APCI1500_Interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct addi_private *devpriv = dev->private;
unsigned int ui_InterruptStatus = 0;
int i_RegValue = 0;
i_InterruptMask = 0;
/***********************************/
/* Read the board interrupt status */
/***********************************/
ui_InterruptStatus = inl(devpriv->i_IobaseAmcc + 0x38);
/***************************************/
/* Test if board generated a interrupt */
/***************************************/
if ((ui_InterruptStatus & 0x800000) == 0x800000) {
/************************/
/* Disable all Interrupt */
/************************/
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
/* outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER); */
/**********************************************/
/* Disables the main interrupt on the board */
/**********************************************/
/* outb(0x00,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER); */
/*****************************************************/
/* Selects the command and status register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if ((i_RegValue & 0x60) == 0x60) {
/*****************************************************/
/* Selects the command and status register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of port A */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_InterruptMask = i_InterruptMask | 1;
if (i_Logic == APCI1500_OR_PRIORITY) {
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***************************************************/
/* Selects the interrupt vector register of port A */
/***************************************************/
outb(APCI1500_RW_PORT_A_INTERRUPT_CONTROL,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_InputChannel = 1 + (i_RegValue >> 1);
} /* if(i_Logic==APCI1500_OR_PRIORITY) */
else {
i_InputChannel = 0;
} /* elseif(i_Logic==APCI1500_OR_PRIORITY) */
} /* if ((i_RegValue & 0x60) == 0x60) */
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if ((i_RegValue & 0x60) == 0x60) {
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of port B */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
printk("\n\n\n");
/****************/
/* Reads port B */
/****************/
i_RegValue =
inb((unsigned int) devpriv->iobase +
APCI1500_Z8536_PORT_B);
i_RegValue = i_RegValue & 0xC0;
/**************************************/
/* Tests if this is an external error */
/**************************************/
if (i_RegValue) {
/* Disable the interrupt */
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outl(0x0, devpriv->i_IobaseAmcc + 0x38);
if (i_RegValue & 0x80) {
i_InterruptMask =
i_InterruptMask | 0x40;
} /* if (i_RegValue & 0x80) */
if (i_RegValue & 0x40) {
i_InterruptMask =
i_InterruptMask | 0x80;
} /* if (i_RegValue & 0x40) */
} /* if (i_RegValue) */
else {
i_InterruptMask = i_InterruptMask | 2;
} /* if (i_RegValue) */
} /* if ((i_RegValue & 0x60) == 0x60) */
/*****************************************************/
/* Selects the command and status register of timer 1 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if ((i_RegValue & 0x60) == 0x60) {
/*****************************************************/
/* Selects the command and status register of timer 1 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 1 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_InterruptMask = i_InterruptMask | 4;
} /* if ((i_RegValue & 0x60) == 0x60) */
/*****************************************************/
/* Selects the command and status register of timer 2 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if ((i_RegValue & 0x60) == 0x60) {
/*****************************************************/
/* Selects the command and status register of timer 2 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 2 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
i_InterruptMask = i_InterruptMask | 8;
} /* if ((i_RegValue & 0x60) == 0x60) */
/*****************************************************/
/* Selects the command and status register of timer 3 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_RegValue =
inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
if ((i_RegValue & 0x60) == 0x60) {
/*****************************************************/
/* Selects the command and status register of timer 3 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
/***********************************/
/* Deletes the interrupt of timer 3 */
/***********************************/
i_RegValue = (i_RegValue & 0x0F) | 0x20;
outb(i_RegValue,
devpriv->iobase +
APCI1500_Z8536_CONTROL_REGISTER);
if (i_CounterLogic == APCI1500_COUNTER) {
i_InterruptMask = i_InterruptMask | 0x10;
} /* if(i_CounterLogic==APCI1500_COUNTER) */
else {
i_InterruptMask = i_InterruptMask | 0x20;
}
} /* if ((i_RegValue & 0x60) == 0x60) */
send_sig(SIGIO, devpriv->tsk_Current, 0); /* send signal to the sample */
/***********************/
/* Enable all Interrupts */
/***********************/
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/**********************************************/
/* Authorizes the main interrupt on the board */
/**********************************************/
outb(0xD0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
} /* if ((ui_InterruptStatus & 0x800000) == 0x800000) */
else {
printk("\nInterrupt from unknown source\n");
} /* else if ((ui_InterruptStatus & 0x800000) == 0x800000) */
return;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1500_Reset(struct comedi_device *dev) | |
+----------------------------------------------------------------------------+
| Task :resets all the registers |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : |
| |
+----------------------------------------------------------------------------+
*/
static int i_APCI1500_Reset(struct comedi_device *dev)
{
struct addi_private *devpriv = dev->private;
int i_DummyRead = 0;
i_TimerCounter1Init = 0;
i_TimerCounter2Init = 0;
i_WatchdogCounter3Init = 0;
i_Event1Status = 0;
i_Event2Status = 0;
i_TimerCounterWatchdogInterrupt = 0;
i_Logic = 0;
i_CounterLogic = 0;
i_InterruptMask = 0;
i_InputChannel = 0;
i_TimerCounter1Enabled = 0;
i_TimerCounter2Enabled = 0;
i_WatchdogCounter3Enabled = 0;
/******************/
/* Software reset */
/******************/
i_DummyRead = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
i_DummyRead = inb(devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(1, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the master configuration control register */
/*****************************************************/
outb(APCI1500_RW_MASTER_CONFIGURATION_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0xF4, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the mode specification register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0x10, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data path polarity register of port A */
outb(APCI1500_RW_PORT_A_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* High level of port A means 1 */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port A */
outb(APCI1500_RW_PORT_A_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port A */
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port A */
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of port A: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the handshake specification register of port A */
outb(APCI1500_RW_PORT_A_HANDSHAKE_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes the register */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the mode specification register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
outb(0x10, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data path polarity register of port B */
outb(APCI1500_RW_PORT_B_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* A high level of port B means 1 */
outb(0x7F, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port B */
outb(APCI1500_RW_PORT_B_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs */
outb(0xFF, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port B */
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of port B */
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of port B: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the handshake specification register of port B */
outb(APCI1500_RW_PORT_B_HANDSHAKE_SPECIFICATION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes the register */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the data path polarity register of port C */
/*****************************************************/
outb(APCI1500_RW_PORT_C_DATA_PCITCH_POLARITY,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* High level of port C means 1 */
outb(0x9, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the data direction register of port C */
outb(APCI1500_RW_PORT_C_DATA_DIRECTION,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* All bits used as inputs except channel 1 */
outb(0x0E, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the special IO register of port C */
outb(APCI1500_RW_PORT_C_SPECIAL_IO_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes it */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 1 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of timer 1 */
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates the interrupt management of timer 1 */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 2 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of timer 2 */
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates Timer 2 interrupt management: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/******************************************************/
/* Selects the command and status register of timer 3 */
/******************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes IP and IUS */
outb(0x20, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Selects the command and status register of Timer 3 */
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deactivates interrupt management of timer 3: */
outb(0xE0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* Deletes all interrupts */
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/* reset all the digital outputs */
outw(0x0, devpriv->i_IobaseAddon + APCI1500_DIGITAL_OP);
/*******************************/
/* Disable the board interrupt */
/*******************************/
/*************************************************/
/* Selects the master interrupt control register */
/*************************************************/
outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of port A */
/*****************************************************/
outb(APCI1500_RW_PORT_A_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of port B */
/*****************************************************/
outb(APCI1500_RW_PORT_B_COMMAND_AND_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 1 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR1_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 2 */
/*****************************************************/
outb(APCI1500_RW_CPT_TMR2_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/*****************************************************/
/* Selects the command and status register of timer 3*/
/*****************************************************/
outb(APCI1500_RW_CPT_TMR3_CMD_STATUS,
devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
/****************************/
/* Deactivates all interrupts */
/******************************/
outb(0x00, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
return 0;
}
| gpl-2.0 |
sztupy/universal_lagfix_kernel | drivers/infiniband/ulp/ipoib/ipoib_multicast.c | 478 | 25735 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) 2004 Voltaire, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/igmp.h>
#include <linux/inetdevice.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <net/dst.h>
#include "ipoib.h"
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
static int mcast_debug_level;
module_param(mcast_debug_level, int, 0644);
MODULE_PARM_DESC(mcast_debug_level,
"Enable multicast debug tracing if > 0");
#endif
static DEFINE_MUTEX(mcast_mutex);
struct ipoib_mcast_iter {
struct net_device *dev;
union ib_gid mgid;
unsigned long created;
unsigned int queuelen;
unsigned int complete;
unsigned int send_only;
};
static void ipoib_mcast_free(struct ipoib_mcast *mcast)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_neigh *neigh, *tmp;
int tx_dropped = 0;
ipoib_dbg_mcast(netdev_priv(dev), "deleting multicast group %pI6\n",
mcast->mcmember.mgid.raw);
spin_lock_irq(&priv->lock);
list_for_each_entry_safe(neigh, tmp, &mcast->neigh_list, list) {
/*
* It's safe to call ipoib_put_ah() inside priv->lock
* here, because we know that mcast->ah will always
* hold one more reference, so ipoib_put_ah() will
* never do more than decrement the ref count.
*/
if (neigh->ah)
ipoib_put_ah(neigh->ah);
ipoib_neigh_free(dev, neigh);
}
spin_unlock_irq(&priv->lock);
if (mcast->ah)
ipoib_put_ah(mcast->ah);
while (!skb_queue_empty(&mcast->pkt_queue)) {
++tx_dropped;
dev_kfree_skb_any(skb_dequeue(&mcast->pkt_queue));
}
netif_tx_lock_bh(dev);
dev->stats.tx_dropped += tx_dropped;
netif_tx_unlock_bh(dev);
kfree(mcast);
}
static struct ipoib_mcast *ipoib_mcast_alloc(struct net_device *dev,
int can_sleep)
{
struct ipoib_mcast *mcast;
mcast = kzalloc(sizeof *mcast, can_sleep ? GFP_KERNEL : GFP_ATOMIC);
if (!mcast)
return NULL;
mcast->dev = dev;
mcast->created = jiffies;
mcast->backoff = 1;
INIT_LIST_HEAD(&mcast->list);
INIT_LIST_HEAD(&mcast->neigh_list);
skb_queue_head_init(&mcast->pkt_queue);
return mcast;
}
static struct ipoib_mcast *__ipoib_mcast_find(struct net_device *dev, void *mgid)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node *n = priv->multicast_tree.rb_node;
while (n) {
struct ipoib_mcast *mcast;
int ret;
mcast = rb_entry(n, struct ipoib_mcast, rb_node);
ret = memcmp(mgid, mcast->mcmember.mgid.raw,
sizeof (union ib_gid));
if (ret < 0)
n = n->rb_left;
else if (ret > 0)
n = n->rb_right;
else
return mcast;
}
return NULL;
}
static int __ipoib_mcast_add(struct net_device *dev, struct ipoib_mcast *mcast)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node **n = &priv->multicast_tree.rb_node, *pn = NULL;
while (*n) {
struct ipoib_mcast *tmcast;
int ret;
pn = *n;
tmcast = rb_entry(pn, struct ipoib_mcast, rb_node);
ret = memcmp(mcast->mcmember.mgid.raw, tmcast->mcmember.mgid.raw,
sizeof (union ib_gid));
if (ret < 0)
n = &pn->rb_left;
else if (ret > 0)
n = &pn->rb_right;
else
return -EEXIST;
}
rb_link_node(&mcast->rb_node, pn, n);
rb_insert_color(&mcast->rb_node, &priv->multicast_tree);
return 0;
}
static int ipoib_mcast_join_finish(struct ipoib_mcast *mcast,
struct ib_sa_mcmember_rec *mcmember)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_ah *ah;
int ret;
int set_qkey = 0;
mcast->mcmember = *mcmember;
/* Set the cached Q_Key before we attach if it's the broadcast group */
if (!memcmp(mcast->mcmember.mgid.raw, priv->dev->broadcast + 4,
sizeof (union ib_gid))) {
spin_lock_irq(&priv->lock);
if (!priv->broadcast) {
spin_unlock_irq(&priv->lock);
return -EAGAIN;
}
priv->qkey = be32_to_cpu(priv->broadcast->mcmember.qkey);
spin_unlock_irq(&priv->lock);
priv->tx_wr.wr.ud.remote_qkey = priv->qkey;
set_qkey = 1;
}
if (!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
if (test_and_set_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
ipoib_warn(priv, "multicast group %pI6 already attached\n",
mcast->mcmember.mgid.raw);
return 0;
}
ret = ipoib_mcast_attach(dev, be16_to_cpu(mcast->mcmember.mlid),
&mcast->mcmember.mgid, set_qkey);
if (ret < 0) {
ipoib_warn(priv, "couldn't attach QP to multicast group %pI6\n",
mcast->mcmember.mgid.raw);
clear_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags);
return ret;
}
}
{
struct ib_ah_attr av = {
.dlid = be16_to_cpu(mcast->mcmember.mlid),
.port_num = priv->port,
.sl = mcast->mcmember.sl,
.ah_flags = IB_AH_GRH,
.static_rate = mcast->mcmember.rate,
.grh = {
.flow_label = be32_to_cpu(mcast->mcmember.flow_label),
.hop_limit = mcast->mcmember.hop_limit,
.sgid_index = 0,
.traffic_class = mcast->mcmember.traffic_class
}
};
av.grh.dgid = mcast->mcmember.mgid;
ah = ipoib_create_ah(dev, priv->pd, &av);
if (!ah) {
ipoib_warn(priv, "ib_address_create failed\n");
} else {
spin_lock_irq(&priv->lock);
mcast->ah = ah;
spin_unlock_irq(&priv->lock);
ipoib_dbg_mcast(priv, "MGID %pI6 AV %p, LID 0x%04x, SL %d\n",
mcast->mcmember.mgid.raw,
mcast->ah->ah,
be16_to_cpu(mcast->mcmember.mlid),
mcast->mcmember.sl);
}
}
/* actually send any queued packets */
netif_tx_lock_bh(dev);
while (!skb_queue_empty(&mcast->pkt_queue)) {
struct sk_buff *skb = skb_dequeue(&mcast->pkt_queue);
netif_tx_unlock_bh(dev);
skb->dev = dev;
if (!skb_dst(skb) || !skb_dst(skb)->neighbour) {
/* put pseudoheader back on for next time */
skb_push(skb, sizeof (struct ipoib_pseudoheader));
}
if (dev_queue_xmit(skb))
ipoib_warn(priv, "dev_queue_xmit failed to requeue packet\n");
netif_tx_lock_bh(dev);
}
netif_tx_unlock_bh(dev);
return 0;
}
static int
ipoib_mcast_sendonly_join_complete(int status,
struct ib_sa_multicast *multicast)
{
struct ipoib_mcast *mcast = multicast->context;
struct net_device *dev = mcast->dev;
/* We trap for port events ourselves. */
if (status == -ENETRESET)
return 0;
if (!status)
status = ipoib_mcast_join_finish(mcast, &multicast->rec);
if (status) {
if (mcast->logcount++ < 20)
ipoib_dbg_mcast(netdev_priv(dev), "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
/* Flush out any queued packets */
netif_tx_lock_bh(dev);
while (!skb_queue_empty(&mcast->pkt_queue)) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb_dequeue(&mcast->pkt_queue));
}
netif_tx_unlock_bh(dev);
/* Clear the busy flag so we try again */
status = test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY,
&mcast->flags);
}
return status;
}
static int ipoib_mcast_sendonly_join(struct ipoib_mcast *mcast)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ib_sa_mcmember_rec rec = {
#if 0 /* Some SMs don't support send-only yet */
.join_state = 4
#else
.join_state = 1
#endif
};
int ret = 0;
if (!test_bit(IPOIB_FLAG_OPER_UP, &priv->flags)) {
ipoib_dbg_mcast(priv, "device shutting down, no multicast joins\n");
return -ENODEV;
}
if (test_and_set_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags)) {
ipoib_dbg_mcast(priv, "multicast entry busy, skipping\n");
return -EBUSY;
}
rec.mgid = mcast->mcmember.mgid;
rec.port_gid = priv->local_gid;
rec.pkey = cpu_to_be16(priv->pkey);
mcast->mc = ib_sa_join_multicast(&ipoib_sa_client, priv->ca,
priv->port, &rec,
IB_SA_MCMEMBER_REC_MGID |
IB_SA_MCMEMBER_REC_PORT_GID |
IB_SA_MCMEMBER_REC_PKEY |
IB_SA_MCMEMBER_REC_JOIN_STATE,
GFP_ATOMIC,
ipoib_mcast_sendonly_join_complete,
mcast);
if (IS_ERR(mcast->mc)) {
ret = PTR_ERR(mcast->mc);
clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
ipoib_warn(priv, "ib_sa_join_multicast failed (ret = %d)\n",
ret);
} else {
ipoib_dbg_mcast(priv, "no multicast record for %pI6, starting join\n",
mcast->mcmember.mgid.raw);
}
return ret;
}
void ipoib_mcast_carrier_on_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv,
carrier_on_task);
struct ib_port_attr attr;
/*
* Take rtnl_lock to avoid racing with ipoib_stop() and
* turning the carrier back on while a device is being
* removed.
*/
if (ib_query_port(priv->ca, priv->port, &attr) ||
attr.state != IB_PORT_ACTIVE) {
ipoib_dbg(priv, "Keeping carrier off until IB port is active\n");
return;
}
rtnl_lock();
netif_carrier_on(priv->dev);
rtnl_unlock();
}
static int ipoib_mcast_join_complete(int status,
struct ib_sa_multicast *multicast)
{
struct ipoib_mcast *mcast = multicast->context;
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "join completion for %pI6 (status %d)\n",
mcast->mcmember.mgid.raw, status);
/* We trap for port events ourselves. */
if (status == -ENETRESET)
return 0;
if (!status)
status = ipoib_mcast_join_finish(mcast, &multicast->rec);
if (!status) {
mcast->backoff = 1;
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task, 0);
mutex_unlock(&mcast_mutex);
/*
* Defer carrier on work to ipoib_workqueue to avoid a
* deadlock on rtnl_lock here.
*/
if (mcast == priv->broadcast)
queue_work(ipoib_workqueue, &priv->carrier_on_task);
return 0;
}
if (mcast->logcount++ < 20) {
if (status == -ETIMEDOUT || status == -EAGAIN) {
ipoib_dbg_mcast(priv, "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
} else {
ipoib_warn(priv, "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
}
}
mcast->backoff *= 2;
if (mcast->backoff > IPOIB_MAX_BACKOFF_SECONDS)
mcast->backoff = IPOIB_MAX_BACKOFF_SECONDS;
/* Clear the busy flag so we try again */
status = test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
mutex_lock(&mcast_mutex);
spin_lock_irq(&priv->lock);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue, &priv->mcast_task,
mcast->backoff * HZ);
spin_unlock_irq(&priv->lock);
mutex_unlock(&mcast_mutex);
return status;
}
static void ipoib_mcast_join(struct net_device *dev, struct ipoib_mcast *mcast,
int create)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ib_sa_mcmember_rec rec = {
.join_state = 1
};
ib_sa_comp_mask comp_mask;
int ret = 0;
ipoib_dbg_mcast(priv, "joining MGID %pI6\n", mcast->mcmember.mgid.raw);
rec.mgid = mcast->mcmember.mgid;
rec.port_gid = priv->local_gid;
rec.pkey = cpu_to_be16(priv->pkey);
comp_mask =
IB_SA_MCMEMBER_REC_MGID |
IB_SA_MCMEMBER_REC_PORT_GID |
IB_SA_MCMEMBER_REC_PKEY |
IB_SA_MCMEMBER_REC_JOIN_STATE;
if (create) {
comp_mask |=
IB_SA_MCMEMBER_REC_QKEY |
IB_SA_MCMEMBER_REC_MTU_SELECTOR |
IB_SA_MCMEMBER_REC_MTU |
IB_SA_MCMEMBER_REC_TRAFFIC_CLASS |
IB_SA_MCMEMBER_REC_RATE_SELECTOR |
IB_SA_MCMEMBER_REC_RATE |
IB_SA_MCMEMBER_REC_SL |
IB_SA_MCMEMBER_REC_FLOW_LABEL |
IB_SA_MCMEMBER_REC_HOP_LIMIT;
rec.qkey = priv->broadcast->mcmember.qkey;
rec.mtu_selector = IB_SA_EQ;
rec.mtu = priv->broadcast->mcmember.mtu;
rec.traffic_class = priv->broadcast->mcmember.traffic_class;
rec.rate_selector = IB_SA_EQ;
rec.rate = priv->broadcast->mcmember.rate;
rec.sl = priv->broadcast->mcmember.sl;
rec.flow_label = priv->broadcast->mcmember.flow_label;
rec.hop_limit = priv->broadcast->mcmember.hop_limit;
}
set_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
mcast->mc = ib_sa_join_multicast(&ipoib_sa_client, priv->ca, priv->port,
&rec, comp_mask, GFP_KERNEL,
ipoib_mcast_join_complete, mcast);
if (IS_ERR(mcast->mc)) {
clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
ret = PTR_ERR(mcast->mc);
ipoib_warn(priv, "ib_sa_join_multicast failed, status %d\n", ret);
mcast->backoff *= 2;
if (mcast->backoff > IPOIB_MAX_BACKOFF_SECONDS)
mcast->backoff = IPOIB_MAX_BACKOFF_SECONDS;
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task,
mcast->backoff * HZ);
mutex_unlock(&mcast_mutex);
}
}
void ipoib_mcast_join_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv =
container_of(work, struct ipoib_dev_priv, mcast_task.work);
struct net_device *dev = priv->dev;
if (!test_bit(IPOIB_MCAST_RUN, &priv->flags))
return;
if (ib_query_gid(priv->ca, priv->port, 0, &priv->local_gid))
ipoib_warn(priv, "ib_query_gid() failed\n");
else
memcpy(priv->dev->dev_addr + 4, priv->local_gid.raw, sizeof (union ib_gid));
{
struct ib_port_attr attr;
if (!ib_query_port(priv->ca, priv->port, &attr))
priv->local_lid = attr.lid;
else
ipoib_warn(priv, "ib_query_port failed\n");
}
if (!priv->broadcast) {
struct ipoib_mcast *broadcast;
if (!test_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags))
return;
broadcast = ipoib_mcast_alloc(dev, 1);
if (!broadcast) {
ipoib_warn(priv, "failed to allocate broadcast group\n");
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task, HZ);
mutex_unlock(&mcast_mutex);
return;
}
spin_lock_irq(&priv->lock);
memcpy(broadcast->mcmember.mgid.raw, priv->dev->broadcast + 4,
sizeof (union ib_gid));
priv->broadcast = broadcast;
__ipoib_mcast_add(dev, priv->broadcast);
spin_unlock_irq(&priv->lock);
}
if (!test_bit(IPOIB_MCAST_FLAG_ATTACHED, &priv->broadcast->flags)) {
if (!test_bit(IPOIB_MCAST_FLAG_BUSY, &priv->broadcast->flags))
ipoib_mcast_join(dev, priv->broadcast, 0);
return;
}
while (1) {
struct ipoib_mcast *mcast = NULL;
spin_lock_irq(&priv->lock);
list_for_each_entry(mcast, &priv->multicast_list, list) {
if (!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)
&& !test_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags)
&& !test_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
/* Found the next unjoined group */
break;
}
}
spin_unlock_irq(&priv->lock);
if (&mcast->list == &priv->multicast_list) {
/* All done */
break;
}
ipoib_mcast_join(dev, mcast, 1);
return;
}
priv->mcast_mtu = IPOIB_UD_MTU(ib_mtu_enum_to_int(priv->broadcast->mcmember.mtu));
if (!ipoib_cm_admin_enabled(dev)) {
rtnl_lock();
dev_set_mtu(dev, min(priv->mcast_mtu, priv->admin_mtu));
rtnl_unlock();
}
ipoib_dbg_mcast(priv, "successfully joined all multicast groups\n");
clear_bit(IPOIB_MCAST_RUN, &priv->flags);
}
int ipoib_mcast_start_thread(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "starting multicast thread\n");
mutex_lock(&mcast_mutex);
if (!test_and_set_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue, &priv->mcast_task, 0);
mutex_unlock(&mcast_mutex);
return 0;
}
int ipoib_mcast_stop_thread(struct net_device *dev, int flush)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "stopping multicast thread\n");
mutex_lock(&mcast_mutex);
clear_bit(IPOIB_MCAST_RUN, &priv->flags);
cancel_delayed_work(&priv->mcast_task);
mutex_unlock(&mcast_mutex);
if (flush)
flush_workqueue(ipoib_workqueue);
return 0;
}
static int ipoib_mcast_leave(struct net_device *dev, struct ipoib_mcast *mcast)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
int ret = 0;
if (test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags))
ib_sa_free_multicast(mcast->mc);
if (test_and_clear_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
ipoib_dbg_mcast(priv, "leaving MGID %pI6\n",
mcast->mcmember.mgid.raw);
/* Remove ourselves from the multicast group */
ret = ib_detach_mcast(priv->qp, &mcast->mcmember.mgid,
be16_to_cpu(mcast->mcmember.mlid));
if (ret)
ipoib_warn(priv, "ib_detach_mcast failed (result = %d)\n", ret);
}
return 0;
}
void ipoib_mcast_send(struct net_device *dev, void *mgid, struct sk_buff *skb)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_mcast *mcast;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
if (!test_bit(IPOIB_FLAG_OPER_UP, &priv->flags) ||
!priv->broadcast ||
!test_bit(IPOIB_MCAST_FLAG_ATTACHED, &priv->broadcast->flags)) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
goto unlock;
}
mcast = __ipoib_mcast_find(dev, mgid);
if (!mcast) {
/* Let's create a new send only group now */
ipoib_dbg_mcast(priv, "setting up send only multicast group for %pI6\n",
mgid);
mcast = ipoib_mcast_alloc(dev, 0);
if (!mcast) {
ipoib_warn(priv, "unable to allocate memory for "
"multicast structure\n");
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
goto out;
}
set_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags);
memcpy(mcast->mcmember.mgid.raw, mgid, sizeof (union ib_gid));
__ipoib_mcast_add(dev, mcast);
list_add_tail(&mcast->list, &priv->multicast_list);
}
if (!mcast->ah) {
if (skb_queue_len(&mcast->pkt_queue) < IPOIB_MAX_MCAST_QUEUE)
skb_queue_tail(&mcast->pkt_queue, skb);
else {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
if (test_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags))
ipoib_dbg_mcast(priv, "no address vector, "
"but multicast join already started\n");
else if (test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags))
ipoib_mcast_sendonly_join(mcast);
/*
* If lookup completes between here and out:, don't
* want to send packet twice.
*/
mcast = NULL;
}
out:
if (mcast && mcast->ah) {
if (skb_dst(skb) &&
skb_dst(skb)->neighbour &&
!*to_ipoib_neigh(skb_dst(skb)->neighbour)) {
struct ipoib_neigh *neigh = ipoib_neigh_alloc(skb_dst(skb)->neighbour,
skb->dev);
if (neigh) {
kref_get(&mcast->ah->ref);
neigh->ah = mcast->ah;
list_add_tail(&neigh->list, &mcast->neigh_list);
}
}
spin_unlock_irqrestore(&priv->lock, flags);
ipoib_send(dev, skb, mcast->ah, IB_MULTICAST_QPN);
return;
}
unlock:
spin_unlock_irqrestore(&priv->lock, flags);
}
void ipoib_mcast_dev_flush(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
LIST_HEAD(remove_list);
struct ipoib_mcast *mcast, *tmcast;
unsigned long flags;
ipoib_dbg_mcast(priv, "flushing multicast list\n");
spin_lock_irqsave(&priv->lock, flags);
list_for_each_entry_safe(mcast, tmcast, &priv->multicast_list, list) {
list_del(&mcast->list);
rb_erase(&mcast->rb_node, &priv->multicast_tree);
list_add_tail(&mcast->list, &remove_list);
}
if (priv->broadcast) {
rb_erase(&priv->broadcast->rb_node, &priv->multicast_tree);
list_add_tail(&priv->broadcast->list, &remove_list);
priv->broadcast = NULL;
}
spin_unlock_irqrestore(&priv->lock, flags);
list_for_each_entry_safe(mcast, tmcast, &remove_list, list) {
ipoib_mcast_leave(dev, mcast);
ipoib_mcast_free(mcast);
}
}
static int ipoib_mcast_addr_is_valid(const u8 *addr, unsigned int addrlen,
const u8 *broadcast)
{
if (addrlen != INFINIBAND_ALEN)
return 0;
/* reserved QPN, prefix, scope */
if (memcmp(addr, broadcast, 6))
return 0;
/* signature lower, pkey */
if (memcmp(addr + 7, broadcast + 7, 3))
return 0;
return 1;
}
void ipoib_mcast_restart_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv =
container_of(work, struct ipoib_dev_priv, restart_task);
struct net_device *dev = priv->dev;
struct dev_mc_list *mclist;
struct ipoib_mcast *mcast, *tmcast;
LIST_HEAD(remove_list);
unsigned long flags;
struct ib_sa_mcmember_rec rec;
ipoib_dbg_mcast(priv, "restarting multicast task\n");
ipoib_mcast_stop_thread(dev, 0);
local_irq_save(flags);
netif_addr_lock(dev);
spin_lock(&priv->lock);
/*
* Unfortunately, the networking core only gives us a list of all of
* the multicast hardware addresses. We need to figure out which ones
* are new and which ones have been removed
*/
/* Clear out the found flag */
list_for_each_entry(mcast, &priv->multicast_list, list)
clear_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags);
/* Mark all of the entries that are found or don't exist */
for (mclist = dev->mc_list; mclist; mclist = mclist->next) {
union ib_gid mgid;
if (!ipoib_mcast_addr_is_valid(mclist->dmi_addr,
mclist->dmi_addrlen,
dev->broadcast))
continue;
memcpy(mgid.raw, mclist->dmi_addr + 4, sizeof mgid);
mcast = __ipoib_mcast_find(dev, &mgid);
if (!mcast || test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
struct ipoib_mcast *nmcast;
/* ignore group which is directly joined by userspace */
if (test_bit(IPOIB_FLAG_UMCAST, &priv->flags) &&
!ib_sa_get_mcmember_rec(priv->ca, priv->port, &mgid, &rec)) {
ipoib_dbg_mcast(priv, "ignoring multicast entry for mgid %pI6\n",
mgid.raw);
continue;
}
/* Not found or send-only group, let's add a new entry */
ipoib_dbg_mcast(priv, "adding multicast entry for mgid %pI6\n",
mgid.raw);
nmcast = ipoib_mcast_alloc(dev, 0);
if (!nmcast) {
ipoib_warn(priv, "unable to allocate memory for multicast structure\n");
continue;
}
set_bit(IPOIB_MCAST_FLAG_FOUND, &nmcast->flags);
nmcast->mcmember.mgid = mgid;
if (mcast) {
/* Destroy the send only entry */
list_move_tail(&mcast->list, &remove_list);
rb_replace_node(&mcast->rb_node,
&nmcast->rb_node,
&priv->multicast_tree);
} else
__ipoib_mcast_add(dev, nmcast);
list_add_tail(&nmcast->list, &priv->multicast_list);
}
if (mcast)
set_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags);
}
/* Remove all of the entries don't exist anymore */
list_for_each_entry_safe(mcast, tmcast, &priv->multicast_list, list) {
if (!test_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags) &&
!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
ipoib_dbg_mcast(priv, "deleting multicast group %pI6\n",
mcast->mcmember.mgid.raw);
rb_erase(&mcast->rb_node, &priv->multicast_tree);
/* Move to the remove list */
list_move_tail(&mcast->list, &remove_list);
}
}
spin_unlock(&priv->lock);
netif_addr_unlock(dev);
local_irq_restore(flags);
/* We have to cancel outside of the spinlock */
list_for_each_entry_safe(mcast, tmcast, &remove_list, list) {
ipoib_mcast_leave(mcast->dev, mcast);
ipoib_mcast_free(mcast);
}
if (test_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags))
ipoib_mcast_start_thread(dev);
}
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
struct ipoib_mcast_iter *ipoib_mcast_iter_init(struct net_device *dev)
{
struct ipoib_mcast_iter *iter;
iter = kmalloc(sizeof *iter, GFP_KERNEL);
if (!iter)
return NULL;
iter->dev = dev;
memset(iter->mgid.raw, 0, 16);
if (ipoib_mcast_iter_next(iter)) {
kfree(iter);
return NULL;
}
return iter;
}
int ipoib_mcast_iter_next(struct ipoib_mcast_iter *iter)
{
struct ipoib_dev_priv *priv = netdev_priv(iter->dev);
struct rb_node *n;
struct ipoib_mcast *mcast;
int ret = 1;
spin_lock_irq(&priv->lock);
n = rb_first(&priv->multicast_tree);
while (n) {
mcast = rb_entry(n, struct ipoib_mcast, rb_node);
if (memcmp(iter->mgid.raw, mcast->mcmember.mgid.raw,
sizeof (union ib_gid)) < 0) {
iter->mgid = mcast->mcmember.mgid;
iter->created = mcast->created;
iter->queuelen = skb_queue_len(&mcast->pkt_queue);
iter->complete = !!mcast->ah;
iter->send_only = !!(mcast->flags & (1 << IPOIB_MCAST_FLAG_SENDONLY));
ret = 0;
break;
}
n = rb_next(n);
}
spin_unlock_irq(&priv->lock);
return ret;
}
void ipoib_mcast_iter_read(struct ipoib_mcast_iter *iter,
union ib_gid *mgid,
unsigned long *created,
unsigned int *queuelen,
unsigned int *complete,
unsigned int *send_only)
{
*mgid = iter->mgid;
*created = iter->created;
*queuelen = iter->queuelen;
*complete = iter->complete;
*send_only = iter->send_only;
}
#endif /* CONFIG_INFINIBAND_IPOIB_DEBUG */
| gpl-2.0 |
vikrant82/android_kernel_samsung_mondrianwifi | drivers/usb/gadget/inode.c | 1758 | 53084 | /*
* inode.c -- user mode filesystem api for usb gadget controllers
*
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/uts.h>
#include <linux/wait.h>
#include <linux/compiler.h>
#include <asm/uaccess.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/usb/gadgetfs.h>
#include <linux/usb/gadget.h>
/*
* The gadgetfs API maps each endpoint to a file descriptor so that you
* can use standard synchronous read/write calls for I/O. There's some
* O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
* drivers show how this works in practice. You can also use AIO to
* eliminate I/O gaps between requests, to help when streaming data.
*
* Key parts that must be USB-specific are protocols defining how the
* read/write operations relate to the hardware state machines. There
* are two types of files. One type is for the device, implementing ep0.
* The other type is for each IN or OUT endpoint. In both cases, the
* user mode driver must configure the hardware before using it.
*
* - First, dev_config() is called when /dev/gadget/$CHIP is configured
* (by writing configuration and device descriptors). Afterwards it
* may serve as a source of device events, used to handle all control
* requests other than basic enumeration.
*
* - Then, after a SET_CONFIGURATION control request, ep_config() is
* called when each /dev/gadget/ep* file is configured (by writing
* endpoint descriptors). Afterwards these files are used to write()
* IN data or to read() OUT data. To halt the endpoint, a "wrong
* direction" request is issued (like reading an IN endpoint).
*
* Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
* not possible on all hardware. For example, precise fault handling with
* respect to data left in endpoint fifos after aborted operations; or
* selective clearing of endpoint halts, to implement SET_INTERFACE.
*/
#define DRIVER_DESC "USB Gadget filesystem"
#define DRIVER_VERSION "24 Aug 2004"
static const char driver_desc [] = DRIVER_DESC;
static const char shortname [] = "gadgetfs";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
/*----------------------------------------------------------------------*/
#define GADGETFS_MAGIC 0xaee71ee7
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
/* /dev/gadget/$CHIP represents ep0 and the whole device */
enum ep0_state {
/* DISBLED is the initial state.
*/
STATE_DEV_DISABLED = 0,
/* Only one open() of /dev/gadget/$CHIP; only one file tracks
* ep0/device i/o modes and binding to the controller. Driver
* must always write descriptors to initialize the device, then
* the device becomes UNCONNECTED until enumeration.
*/
STATE_DEV_OPENED,
/* From then on, ep0 fd is in either of two basic modes:
* - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
* - SETUP: read/write will transfer control data and succeed;
* or if "wrong direction", performs protocol stall
*/
STATE_DEV_UNCONNECTED,
STATE_DEV_CONNECTED,
STATE_DEV_SETUP,
/* UNBOUND means the driver closed ep0, so the device won't be
* accessible again (DEV_DISABLED) until all fds are closed.
*/
STATE_DEV_UNBOUND,
};
/* enough for the whole queue: most events invalidate others */
#define N_EVENT 5
struct dev_data {
spinlock_t lock;
atomic_t count;
enum ep0_state state; /* P: lock */
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
struct fasync_struct *fasync;
u8 current_config;
/* drivers reading ep0 MUST handle control requests (SETUP)
* reported that way; else the host will time out.
*/
unsigned usermode_setup : 1,
setup_in : 1,
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
setup_abort : 1;
unsigned setup_wLength;
/* the rest is basically write-once */
struct usb_config_descriptor *config, *hs_config;
struct usb_device_descriptor *dev;
struct usb_request *req;
struct usb_gadget *gadget;
struct list_head epfiles;
void *buf;
wait_queue_head_t wait;
struct super_block *sb;
struct dentry *dentry;
/* except this scratch i/o buffer for ep0 */
u8 rbuf [256];
};
static inline void get_dev (struct dev_data *data)
{
atomic_inc (&data->count);
}
static void put_dev (struct dev_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
/* needs no more cleanup */
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
static struct dev_data *dev_new (void)
{
struct dev_data *dev;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return NULL;
dev->state = STATE_DEV_DISABLED;
atomic_set (&dev->count, 1);
spin_lock_init (&dev->lock);
INIT_LIST_HEAD (&dev->epfiles);
init_waitqueue_head (&dev->wait);
return dev;
}
/*----------------------------------------------------------------------*/
/* other /dev/gadget/$ENDPOINT files represent endpoints */
enum ep_state {
STATE_EP_DISABLED = 0,
STATE_EP_READY,
STATE_EP_ENABLED,
STATE_EP_UNBOUND,
};
struct ep_data {
struct mutex lock;
enum ep_state state;
atomic_t count;
struct dev_data *dev;
/* must hold dev->lock before accessing ep or req */
struct usb_ep *ep;
struct usb_request *req;
ssize_t status;
char name [16];
struct usb_endpoint_descriptor desc, hs_desc;
struct list_head epfiles;
wait_queue_head_t wait;
struct dentry *dentry;
struct inode *inode;
};
static inline void get_ep (struct ep_data *data)
{
atomic_inc (&data->count);
}
static void put_ep (struct ep_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
put_dev (data->dev);
/* needs no more cleanup */
BUG_ON (!list_empty (&data->epfiles));
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
/*----------------------------------------------------------------------*/
/* most "how to use the hardware" policy choices are in userspace:
* mapping endpoint roles (which the driver needs) to the capabilities
* which the usb controller has. most of those capabilities are exposed
* implicitly, starting with the driver name and then endpoint names.
*/
static const char *CHIP;
/*----------------------------------------------------------------------*/
/* NOTE: don't use dev_printk calls before binding to the gadget
* at the end of ep0 configuration, or after unbind.
*/
/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
#define xprintk(d,level,fmt,args...) \
printk(level "%s: " fmt , shortname , ## args)
#ifdef DEBUG
#define DBG(dev,fmt,args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE_DEBUG
#define VDEBUG DBG
#else
#define VDEBUG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev,fmt,args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define INFO(dev,fmt,args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*----------------------------------------------------------------------*/
/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
*
* After opening, configure non-control endpoints. Then use normal
* stream read() and write() requests; and maybe ioctl() to get more
* precise FIFO status when recovering from cancellation.
*/
static void epio_complete (struct usb_ep *ep, struct usb_request *req)
{
struct ep_data *epdata = ep->driver_data;
if (!req->context)
return;
if (req->status)
epdata->status = req->status;
else
epdata->status = req->actual;
complete ((struct completion *)req->context);
}
/* tasklock endpoint, returning when it's connected.
* still need dev->lock to use epdata->ep.
*/
static int
get_ready_ep (unsigned f_flags, struct ep_data *epdata)
{
int val;
if (f_flags & O_NONBLOCK) {
if (!mutex_trylock(&epdata->lock))
goto nonblock;
if (epdata->state != STATE_EP_ENABLED) {
mutex_unlock(&epdata->lock);
nonblock:
val = -EAGAIN;
} else
val = 0;
return val;
}
val = mutex_lock_interruptible(&epdata->lock);
if (val < 0)
return val;
switch (epdata->state) {
case STATE_EP_ENABLED:
break;
// case STATE_EP_DISABLED: /* "can't happen" */
// case STATE_EP_READY: /* "can't happen" */
default: /* error! */
pr_debug ("%s: ep %p not available, state %d\n",
shortname, epdata, epdata->state);
// FALLTHROUGH
case STATE_EP_UNBOUND: /* clean disconnect */
val = -ENODEV;
mutex_unlock(&epdata->lock);
}
return val;
}
static ssize_t
ep_io (struct ep_data *epdata, void *buf, unsigned len)
{
DECLARE_COMPLETION_ONSTACK (done);
int value;
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
struct usb_request *req = epdata->req;
req->context = &done;
req->complete = epio_complete;
req->buf = buf;
req->length = len;
value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
} else
value = -ENODEV;
spin_unlock_irq (&epdata->dev->lock);
if (likely (value == 0)) {
value = wait_event_interruptible (done.wait, done.done);
if (value != 0) {
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
DBG (epdata->dev, "%s i/o interrupted\n",
epdata->name);
usb_ep_dequeue (epdata->ep, epdata->req);
spin_unlock_irq (&epdata->dev->lock);
wait_event (done.wait, done.done);
if (epdata->status == -ECONNRESET)
epdata->status = -EINTR;
} else {
spin_unlock_irq (&epdata->dev->lock);
DBG (epdata->dev, "endpoint gone\n");
epdata->status = -ENODEV;
}
}
return epdata->status;
}
return value;
}
/* handle a synchronous OUT bulk/intr/iso transfer */
static ssize_t
ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (usb_endpoint_dir_in(&data->desc)) {
if (usb_endpoint_xfer_isoc(&data->desc)) {
mutex_unlock(&data->lock);
return -EINVAL;
}
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
mutex_unlock(&data->lock);
return -EBADMSG;
}
/* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
value = -ENOMEM;
kbuf = kmalloc (len, GFP_KERNEL);
if (unlikely (!kbuf))
goto free1;
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s read %zu OUT, status %d\n",
data->name, len, (int) value);
if (value >= 0 && copy_to_user (buf, kbuf, value))
value = -EFAULT;
free1:
mutex_unlock(&data->lock);
kfree (kbuf);
return value;
}
/* handle a synchronous IN bulk/intr/iso transfer */
static ssize_t
ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (!usb_endpoint_dir_in(&data->desc)) {
if (usb_endpoint_xfer_isoc(&data->desc)) {
mutex_unlock(&data->lock);
return -EINVAL;
}
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
mutex_unlock(&data->lock);
return -EBADMSG;
}
/* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
value = -ENOMEM;
kbuf = kmalloc (len, GFP_KERNEL);
if (!kbuf)
goto free1;
if (copy_from_user (kbuf, buf, len)) {
value = -EFAULT;
goto free1;
}
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s write %zu IN, status %d\n",
data->name, len, (int) value);
free1:
mutex_unlock(&data->lock);
kfree (kbuf);
return value;
}
static int
ep_release (struct inode *inode, struct file *fd)
{
struct ep_data *data = fd->private_data;
int value;
value = mutex_lock_interruptible(&data->lock);
if (value < 0)
return value;
/* clean up if this can be reopened */
if (data->state != STATE_EP_UNBOUND) {
data->state = STATE_EP_DISABLED;
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
usb_ep_disable(data->ep);
}
mutex_unlock(&data->lock);
put_ep (data);
return 0;
}
static long ep_ioctl(struct file *fd, unsigned code, unsigned long value)
{
struct ep_data *data = fd->private_data;
int status;
if ((status = get_ready_ep (fd->f_flags, data)) < 0)
return status;
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL)) {
switch (code) {
case GADGETFS_FIFO_STATUS:
status = usb_ep_fifo_status (data->ep);
break;
case GADGETFS_FIFO_FLUSH:
usb_ep_fifo_flush (data->ep);
break;
case GADGETFS_CLEAR_HALT:
status = usb_ep_clear_halt (data->ep);
break;
default:
status = -ENOTTY;
}
} else
status = -ENODEV;
spin_unlock_irq (&data->dev->lock);
mutex_unlock(&data->lock);
return status;
}
/*----------------------------------------------------------------------*/
/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
struct kiocb_priv {
struct usb_request *req;
struct ep_data *epdata;
void *buf;
const struct iovec *iv;
unsigned long nr_segs;
unsigned actual;
};
static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
{
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata;
int value;
local_irq_disable();
epdata = priv->epdata;
// spin_lock(&epdata->dev->lock);
kiocbSetCancelled(iocb);
if (likely(epdata && epdata->ep && priv->req))
value = usb_ep_dequeue (epdata->ep, priv->req);
else
value = -EINVAL;
// spin_unlock(&epdata->dev->lock);
local_irq_enable();
aio_put_req(iocb);
return value;
}
static ssize_t ep_aio_read_retry(struct kiocb *iocb)
{
struct kiocb_priv *priv = iocb->private;
ssize_t len, total;
void *to_copy;
int i;
/* we "retry" to get the right mm context for this: */
/* copy stuff into user buffers */
total = priv->actual;
len = 0;
to_copy = priv->buf;
for (i=0; i < priv->nr_segs; i++) {
ssize_t this = min((ssize_t)(priv->iv[i].iov_len), total);
if (copy_to_user(priv->iv[i].iov_base, to_copy, this)) {
if (len == 0)
len = -EFAULT;
break;
}
total -= this;
len += this;
to_copy += this;
if (total == 0)
break;
}
kfree(priv->buf);
kfree(priv);
return len;
}
static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct kiocb *iocb = req->context;
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata = priv->epdata;
/* lock against disconnect (and ideally, cancel) */
spin_lock(&epdata->dev->lock);
priv->req = NULL;
priv->epdata = NULL;
/* if this was a write or a read returning no data then we
* don't need to copy anything to userspace, so we can
* complete the aio request immediately.
*/
if (priv->iv == NULL || unlikely(req->actual == 0)) {
kfree(req->buf);
kfree(priv);
iocb->private = NULL;
/* aio_complete() reports bytes-transferred _and_ faults */
aio_complete(iocb, req->actual ? req->actual : req->status,
req->status);
} else {
/* retry() won't report both; so we hide some faults */
if (unlikely(0 != req->status))
DBG(epdata->dev, "%s fault %d len %d\n",
ep->name, req->status, req->actual);
priv->buf = req->buf;
priv->actual = req->actual;
kick_iocb(iocb);
}
spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
put_ep(epdata);
}
static ssize_t
ep_aio_rwtail(
struct kiocb *iocb,
char *buf,
size_t len,
struct ep_data *epdata,
const struct iovec *iv,
unsigned long nr_segs
)
{
struct kiocb_priv *priv;
struct usb_request *req;
ssize_t value;
priv = kmalloc(sizeof *priv, GFP_KERNEL);
if (!priv) {
value = -ENOMEM;
fail:
kfree(buf);
return value;
}
iocb->private = priv;
priv->iv = iv;
priv->nr_segs = nr_segs;
value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
if (unlikely(value < 0)) {
kfree(priv);
goto fail;
}
iocb->ki_cancel = ep_aio_cancel;
get_ep(epdata);
priv->epdata = epdata;
priv->actual = 0;
/* each kiocb is coupled to one usb_request, but we can't
* allocate or submit those if the host disconnected.
*/
spin_lock_irq(&epdata->dev->lock);
if (likely(epdata->ep)) {
req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
if (likely(req)) {
priv->req = req;
req->buf = buf;
req->length = len;
req->complete = ep_aio_complete;
req->context = iocb;
value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
if (unlikely(0 != value))
usb_ep_free_request(epdata->ep, req);
} else
value = -EAGAIN;
} else
value = -ENODEV;
spin_unlock_irq(&epdata->dev->lock);
mutex_unlock(&epdata->lock);
if (unlikely(value)) {
kfree(priv);
put_ep(epdata);
} else
value = (iv ? -EIOCBRETRY : -EIOCBQUEUED);
return value;
}
static ssize_t
ep_aio_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(usb_endpoint_dir_in(&epdata->desc)))
return -EINVAL;
buf = kmalloc(iocb->ki_left, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
iocb->ki_retry = ep_aio_read_retry;
return ep_aio_rwtail(iocb, buf, iocb->ki_left, epdata, iov, nr_segs);
}
static ssize_t
ep_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
size_t len = 0;
int i = 0;
if (unlikely(!usb_endpoint_dir_in(&epdata->desc)))
return -EINVAL;
buf = kmalloc(iocb->ki_left, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
for (i=0; i < nr_segs; i++) {
if (unlikely(copy_from_user(&buf[len], iov[i].iov_base,
iov[i].iov_len) != 0)) {
kfree(buf);
return -EFAULT;
}
len += iov[i].iov_len;
}
return ep_aio_rwtail(iocb, buf, len, epdata, NULL, 0);
}
/*----------------------------------------------------------------------*/
/* used after endpoint configuration */
static const struct file_operations ep_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep_read,
.write = ep_write,
.unlocked_ioctl = ep_ioctl,
.release = ep_release,
.aio_read = ep_aio_read,
.aio_write = ep_aio_write,
};
/* ENDPOINT INITIALIZATION
*
* fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the endpoint configuration, configuring
* the controller to process bulk, interrupt, or isochronous transfers
* at the right maxpacket size, and so on.
*
* The descriptors are message type 1, identified by a host order u32
* at the beginning of what's written. Descriptor order is: full/low
* speed descriptor, then optional high speed descriptor.
*/
static ssize_t
ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
struct usb_ep *ep;
u32 tag;
int value, length = len;
value = mutex_lock_interruptible(&data->lock);
if (value < 0)
return value;
if (data->state != STATE_EP_READY) {
value = -EL2HLT;
goto fail;
}
value = len;
if (len < USB_DT_ENDPOINT_SIZE + 4)
goto fail0;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4)) {
goto fail1;
}
if (tag != 1) {
DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
goto fail0;
}
buf += 4;
len -= 4;
/* NOTE: audio endpoint extensions not accepted here;
* just don't include the extra bytes.
*/
/* full/low speed descriptor, then high speed */
if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
goto fail0;
if (len != USB_DT_ENDPOINT_SIZE) {
if (len != 2 * USB_DT_ENDPOINT_SIZE)
goto fail0;
if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->hs_desc.bDescriptorType
!= USB_DT_ENDPOINT) {
DBG(data->dev, "config %s, bad hs length or type\n",
data->name);
goto fail0;
}
}
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND) {
value = -ENOENT;
goto gone;
} else if ((ep = data->ep) == NULL) {
value = -ENODEV;
goto gone;
}
switch (data->dev->gadget->speed) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
ep->desc = &data->desc;
value = usb_ep_enable(ep);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
case USB_SPEED_HIGH:
/* fails if caller didn't provide that descriptor... */
ep->desc = &data->hs_desc;
value = usb_ep_enable(ep);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
default:
DBG(data->dev, "unconnected, %s init abandoned\n",
data->name);
value = -EINVAL;
}
if (value == 0) {
fd->f_op = &ep_io_operations;
value = length;
}
gone:
spin_unlock_irq (&data->dev->lock);
if (value < 0) {
fail:
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
mutex_unlock(&data->lock);
return value;
fail0:
value = -EINVAL;
goto fail;
fail1:
value = -EFAULT;
goto fail;
}
static int
ep_open (struct inode *inode, struct file *fd)
{
struct ep_data *data = inode->i_private;
int value = -EBUSY;
if (mutex_lock_interruptible(&data->lock) != 0)
return -EINTR;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND)
value = -ENOENT;
else if (data->state == STATE_EP_DISABLED) {
value = 0;
data->state = STATE_EP_READY;
get_ep (data);
fd->private_data = data;
VDEBUG (data->dev, "%s ready\n", data->name);
} else
DBG (data->dev, "%s state %d\n",
data->name, data->state);
spin_unlock_irq (&data->dev->lock);
mutex_unlock(&data->lock);
return value;
}
/* used before endpoint configuration */
static const struct file_operations ep_config_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = ep_open,
.write = ep_config,
.release = ep_release,
};
/*----------------------------------------------------------------------*/
/* EP0 IMPLEMENTATION can be partly in userspace.
*
* Drivers that use this facility receive various events, including
* control requests the kernel doesn't handle. Drivers that don't
* use this facility may be too simple-minded for real applications.
*/
static inline void ep0_readable (struct dev_data *dev)
{
wake_up (&dev->wait);
kill_fasync (&dev->fasync, SIGIO, POLL_IN);
}
static void clean_req (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
if (req->buf != dev->rbuf) {
kfree(req->buf);
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
}
req->complete = epio_complete;
dev->setup_out_ready = 0;
}
static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
unsigned long flags;
int free = 1;
/* for control OUT, data must still get to userspace */
spin_lock_irqsave(&dev->lock, flags);
if (!dev->setup_in) {
dev->setup_out_error = (req->status != 0);
if (!dev->setup_out_error)
free = 0;
dev->setup_out_ready = 1;
ep0_readable (dev);
}
/* clean up as appropriate */
if (free && req->buf != &dev->rbuf)
clean_req (ep, req);
req->complete = epio_complete;
spin_unlock_irqrestore(&dev->lock, flags);
}
static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
{
struct dev_data *dev = ep->driver_data;
if (dev->setup_out_ready) {
DBG (dev, "ep0 request busy!\n");
return -EBUSY;
}
if (len > sizeof (dev->rbuf))
req->buf = kmalloc(len, GFP_ATOMIC);
if (req->buf == NULL) {
req->buf = dev->rbuf;
return -ENOMEM;
}
req->complete = ep0_complete;
req->length = len;
req->zero = 0;
return 0;
}
static ssize_t
ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval;
enum ep0_state state;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
goto done;
}
/* control DATA stage */
if ((state = dev->state) == STATE_DEV_SETUP) {
if (dev->setup_in) { /* stall IN */
VDEBUG(dev, "ep0in stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_DEV_CONNECTED;
} else if (len == 0) { /* ack SET_CONFIGURATION etc */
struct usb_ep *ep = dev->gadget->ep0;
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0)
retval = usb_ep_queue (ep, req, GFP_ATOMIC);
dev->state = STATE_DEV_CONNECTED;
/* assume that was SET_CONFIGURATION */
if (dev->current_config) {
unsigned power;
if (gadget_is_dualspeed(dev->gadget)
&& (dev->gadget->speed
== USB_SPEED_HIGH))
power = dev->hs_config->bMaxPower;
else
power = dev->config->bMaxPower;
usb_gadget_vbus_draw(dev->gadget, 2 * power);
}
} else { /* collect OUT data */
if ((fd->f_flags & O_NONBLOCK) != 0
&& !dev->setup_out_ready) {
retval = -EAGAIN;
goto done;
}
spin_unlock_irq (&dev->lock);
retval = wait_event_interruptible (dev->wait,
dev->setup_out_ready != 0);
/* FIXME state could change from under us */
spin_lock_irq (&dev->lock);
if (retval)
goto done;
if (dev->state != STATE_DEV_SETUP) {
retval = -ECANCELED;
goto done;
}
dev->state = STATE_DEV_CONNECTED;
if (dev->setup_out_error)
retval = -EIO;
else {
len = min (len, (size_t)dev->req->actual);
// FIXME don't call this with the spinlock held ...
if (copy_to_user (buf, dev->req->buf, len))
retval = -EFAULT;
else
retval = len;
clean_req (dev->gadget->ep0, dev->req);
/* NOTE userspace can't yet choose to stall */
}
}
goto done;
}
/* else normal: return event data */
if (len < sizeof dev->event [0]) {
retval = -EINVAL;
goto done;
}
len -= len % sizeof (struct usb_gadgetfs_event);
dev->usermode_setup = 1;
scan:
/* return queued events right away */
if (dev->ev_next != 0) {
unsigned i, n;
n = len / sizeof (struct usb_gadgetfs_event);
if (dev->ev_next < n)
n = dev->ev_next;
/* ep0 i/o has special semantics during STATE_DEV_SETUP */
for (i = 0; i < n; i++) {
if (dev->event [i].type == GADGETFS_SETUP) {
dev->state = STATE_DEV_SETUP;
n = i + 1;
break;
}
}
spin_unlock_irq (&dev->lock);
len = n * sizeof (struct usb_gadgetfs_event);
if (copy_to_user (buf, &dev->event, len))
retval = -EFAULT;
else
retval = len;
if (len > 0) {
/* NOTE this doesn't guard against broken drivers;
* concurrent ep0 readers may lose events.
*/
spin_lock_irq (&dev->lock);
if (dev->ev_next > n) {
memmove(&dev->event[0], &dev->event[n],
sizeof (struct usb_gadgetfs_event)
* (dev->ev_next - n));
}
dev->ev_next -= n;
spin_unlock_irq (&dev->lock);
}
return retval;
}
if (fd->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto done;
}
switch (state) {
default:
DBG (dev, "fail %s, state %d\n", __func__, state);
retval = -ESRCH;
break;
case STATE_DEV_UNCONNECTED:
case STATE_DEV_CONNECTED:
spin_unlock_irq (&dev->lock);
DBG (dev, "%s wait\n", __func__);
/* wait for events */
retval = wait_event_interruptible (dev->wait,
dev->ev_next != 0);
if (retval < 0)
return retval;
spin_lock_irq (&dev->lock);
goto scan;
}
done:
spin_unlock_irq (&dev->lock);
return retval;
}
static struct usb_gadgetfs_event *
next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
{
struct usb_gadgetfs_event *event;
unsigned i;
switch (type) {
/* these events purge the queue */
case GADGETFS_DISCONNECT:
if (dev->state == STATE_DEV_SETUP)
dev->setup_abort = 1;
// FALL THROUGH
case GADGETFS_CONNECT:
dev->ev_next = 0;
break;
case GADGETFS_SETUP: /* previous request timed out */
case GADGETFS_SUSPEND: /* same effect */
/* these events can't be repeated */
for (i = 0; i != dev->ev_next; i++) {
if (dev->event [i].type != type)
continue;
DBG(dev, "discard old event[%d] %d\n", i, type);
dev->ev_next--;
if (i == dev->ev_next)
break;
/* indices start at zero, for simplicity */
memmove (&dev->event [i], &dev->event [i + 1],
sizeof (struct usb_gadgetfs_event)
* (dev->ev_next - i));
}
break;
default:
BUG ();
}
VDEBUG(dev, "event[%d] = %d\n", dev->ev_next, type);
event = &dev->event [dev->ev_next++];
BUG_ON (dev->ev_next > N_EVENT);
memset (event, 0, sizeof *event);
event->type = type;
return event;
}
static ssize_t
ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval = -ESRCH;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
/* data and/or status stage for control request */
} else if (dev->state == STATE_DEV_SETUP) {
/* IN DATA+STATUS caller makes len <= wLength */
if (dev->setup_in) {
retval = setup_req (dev->gadget->ep0, dev->req, len);
if (retval == 0) {
dev->state = STATE_DEV_CONNECTED;
spin_unlock_irq (&dev->lock);
if (copy_from_user (dev->req->buf, buf, len))
retval = -EFAULT;
else {
if (len < dev->setup_wLength)
dev->req->zero = 1;
retval = usb_ep_queue (
dev->gadget->ep0, dev->req,
GFP_KERNEL);
}
if (retval < 0) {
spin_lock_irq (&dev->lock);
clean_req (dev->gadget->ep0, dev->req);
spin_unlock_irq (&dev->lock);
} else
retval = len;
return retval;
}
/* can stall some OUT transfers */
} else if (dev->setup_can_stall) {
VDEBUG(dev, "ep0out stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_DEV_CONNECTED;
} else {
DBG(dev, "bogus ep0out stall!\n");
}
} else
DBG (dev, "fail %s, state %d\n", __func__, dev->state);
spin_unlock_irq (&dev->lock);
return retval;
}
static int
ep0_fasync (int f, struct file *fd, int on)
{
struct dev_data *dev = fd->private_data;
// caller must F_SETOWN before signal delivery happens
VDEBUG (dev, "%s %s\n", __func__, on ? "on" : "off");
return fasync_helper (f, fd, on, &dev->fasync);
}
static struct usb_gadget_driver gadgetfs_driver;
static int
dev_release (struct inode *inode, struct file *fd)
{
struct dev_data *dev = fd->private_data;
/* closing ep0 === shutdown all */
usb_gadget_unregister_driver (&gadgetfs_driver);
/* at this point "good" hardware has disconnected the
* device from USB; the host won't see it any more.
* alternatively, all host requests will time out.
*/
kfree (dev->buf);
dev->buf = NULL;
put_dev (dev);
/* other endpoints were all decoupled from this device */
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_DISABLED;
spin_unlock_irq(&dev->lock);
return 0;
}
static unsigned int
ep0_poll (struct file *fd, poll_table *wait)
{
struct dev_data *dev = fd->private_data;
int mask = 0;
poll_wait(fd, &dev->wait, wait);
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
mask = POLLHUP;
goto out;
}
if (dev->state == STATE_DEV_SETUP) {
if (dev->setup_in || dev->setup_can_stall)
mask = POLLOUT;
} else {
if (dev->ev_next != 0)
mask = POLLIN;
}
out:
spin_unlock_irq(&dev->lock);
return mask;
}
static long dev_ioctl (struct file *fd, unsigned code, unsigned long value)
{
struct dev_data *dev = fd->private_data;
struct usb_gadget *gadget = dev->gadget;
long ret = -ENOTTY;
if (gadget->ops->ioctl)
ret = gadget->ops->ioctl (gadget, code, value);
return ret;
}
/* used after device configuration */
static const struct file_operations ep0_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep0_read,
.write = ep0_write,
.fasync = ep0_fasync,
.poll = ep0_poll,
.unlocked_ioctl = dev_ioctl,
.release = dev_release,
};
/*----------------------------------------------------------------------*/
/* The in-kernel gadget driver handles most ep0 issues, in particular
* enumerating the single configuration (as provided from user space).
*
* Unrecognized ep0 requests may be handled in user space.
*/
static void make_qualifier (struct dev_data *dev)
{
struct usb_qualifier_descriptor qual;
struct usb_device_descriptor *desc;
qual.bLength = sizeof qual;
qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
qual.bcdUSB = cpu_to_le16 (0x0200);
desc = dev->dev;
qual.bDeviceClass = desc->bDeviceClass;
qual.bDeviceSubClass = desc->bDeviceSubClass;
qual.bDeviceProtocol = desc->bDeviceProtocol;
/* assumes ep0 uses the same value for both speeds ... */
qual.bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
qual.bNumConfigurations = 1;
qual.bRESERVED = 0;
memcpy (dev->rbuf, &qual, sizeof qual);
}
static int
config_buf (struct dev_data *dev, u8 type, unsigned index)
{
int len;
int hs = 0;
/* only one configuration */
if (index > 0)
return -EINVAL;
if (gadget_is_dualspeed(dev->gadget)) {
hs = (dev->gadget->speed == USB_SPEED_HIGH);
if (type == USB_DT_OTHER_SPEED_CONFIG)
hs = !hs;
}
if (hs) {
dev->req->buf = dev->hs_config;
len = le16_to_cpu(dev->hs_config->wTotalLength);
} else {
dev->req->buf = dev->config;
len = le16_to_cpu(dev->config->wTotalLength);
}
((u8 *)dev->req->buf) [1] = type;
return len;
}
static int
gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
{
struct dev_data *dev = get_gadget_data (gadget);
struct usb_request *req = dev->req;
int value = -EOPNOTSUPP;
struct usb_gadgetfs_event *event;
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
spin_lock (&dev->lock);
dev->setup_abort = 0;
if (dev->state == STATE_DEV_UNCONNECTED) {
if (gadget_is_dualspeed(gadget)
&& gadget->speed == USB_SPEED_HIGH
&& dev->hs_config == NULL) {
spin_unlock(&dev->lock);
ERROR (dev, "no high speed config??\n");
return -EINVAL;
}
dev->state = STATE_DEV_CONNECTED;
INFO (dev, "connected\n");
event = next_event (dev, GADGETFS_CONNECT);
event->u.speed = gadget->speed;
ep0_readable (dev);
/* host may have given up waiting for response. we can miss control
* requests handled lower down (device/endpoint status and features);
* then ep0_{read,write} will report the wrong status. controller
* driver will have aborted pending i/o.
*/
} else if (dev->state == STATE_DEV_SETUP)
dev->setup_abort = 1;
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
req->context = NULL;
value = -EOPNOTSUPP;
switch (ctrl->bRequest) {
case USB_REQ_GET_DESCRIPTOR:
if (ctrl->bRequestType != USB_DIR_IN)
goto unrecognized;
switch (w_value >> 8) {
case USB_DT_DEVICE:
value = min (w_length, (u16) sizeof *dev->dev);
dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
req->buf = dev->dev;
break;
case USB_DT_DEVICE_QUALIFIER:
if (!dev->hs_config)
break;
value = min (w_length, (u16)
sizeof (struct usb_qualifier_descriptor));
make_qualifier (dev);
break;
case USB_DT_OTHER_SPEED_CONFIG:
// FALLTHROUGH
case USB_DT_CONFIG:
value = config_buf (dev,
w_value >> 8,
w_value & 0xff);
if (value >= 0)
value = min (w_length, (u16) value);
break;
case USB_DT_STRING:
goto unrecognized;
default: // all others are errors
break;
}
break;
/* currently one config, two speeds */
case USB_REQ_SET_CONFIGURATION:
if (ctrl->bRequestType != 0)
goto unrecognized;
if (0 == (u8) w_value) {
value = 0;
dev->current_config = 0;
usb_gadget_vbus_draw(gadget, 8 /* mA */ );
// user mode expected to disable endpoints
} else {
u8 config, power;
if (gadget_is_dualspeed(gadget)
&& gadget->speed == USB_SPEED_HIGH) {
config = dev->hs_config->bConfigurationValue;
power = dev->hs_config->bMaxPower;
} else {
config = dev->config->bConfigurationValue;
power = dev->config->bMaxPower;
}
if (config == (u8) w_value) {
value = 0;
dev->current_config = config;
usb_gadget_vbus_draw(gadget, 2 * power);
}
}
/* report SET_CONFIGURATION like any other control request,
* except that usermode may not stall this. the next
* request mustn't be allowed start until this finishes:
* endpoints and threads set up, etc.
*
* NOTE: older PXA hardware (before PXA 255: without UDCCFR)
* has bad/racey automagic that prevents synchronizing here.
* even kernel mode drivers often miss them.
*/
if (value == 0) {
INFO (dev, "configuration #%d\n", dev->current_config);
if (dev->usermode_setup) {
dev->setup_can_stall = 0;
goto delegate;
}
}
break;
#ifndef CONFIG_USB_GADGET_PXA25X
/* PXA automagically handles this request too */
case USB_REQ_GET_CONFIGURATION:
if (ctrl->bRequestType != 0x80)
goto unrecognized;
*(u8 *)req->buf = dev->current_config;
value = min (w_length, (u16) 1);
break;
#endif
default:
unrecognized:
VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
dev->usermode_setup ? "delegate" : "fail",
ctrl->bRequestType, ctrl->bRequest,
w_value, le16_to_cpu(ctrl->wIndex), w_length);
/* if there's an ep0 reader, don't stall */
if (dev->usermode_setup) {
dev->setup_can_stall = 1;
delegate:
dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
? 1 : 0;
dev->setup_wLength = w_length;
dev->setup_out_ready = 0;
dev->setup_out_error = 0;
value = 0;
/* read DATA stage for OUT right away */
if (unlikely (!dev->setup_in && w_length)) {
value = setup_req (gadget->ep0, dev->req,
w_length);
if (value < 0)
break;
value = usb_ep_queue (gadget->ep0, dev->req,
GFP_ATOMIC);
if (value < 0) {
clean_req (gadget->ep0, dev->req);
break;
}
/* we can't currently stall these */
dev->setup_can_stall = 0;
}
/* state changes when reader collects event */
event = next_event (dev, GADGETFS_SETUP);
event->u.setup = *ctrl;
ep0_readable (dev);
spin_unlock (&dev->lock);
return 0;
}
}
/* proceed with data transfer and status phases? */
if (value >= 0 && dev->state != STATE_DEV_SETUP) {
req->length = value;
req->zero = value < w_length;
value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
if (value < 0) {
DBG (dev, "ep_queue --> %d\n", value);
req->status = 0;
}
}
/* device stalls when value < 0 */
spin_unlock (&dev->lock);
return value;
}
static void destroy_ep_files (struct dev_data *dev)
{
DBG (dev, "%s %d\n", __func__, dev->state);
/* dev->state must prevent interference */
spin_lock_irq (&dev->lock);
while (!list_empty(&dev->epfiles)) {
struct ep_data *ep;
struct inode *parent;
struct dentry *dentry;
/* break link to FS */
ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
list_del_init (&ep->epfiles);
dentry = ep->dentry;
ep->dentry = NULL;
parent = dentry->d_parent->d_inode;
/* break link to controller */
if (ep->state == STATE_EP_ENABLED)
(void) usb_ep_disable (ep->ep);
ep->state = STATE_EP_UNBOUND;
usb_ep_free_request (ep->ep, ep->req);
ep->ep = NULL;
wake_up (&ep->wait);
put_ep (ep);
spin_unlock_irq (&dev->lock);
/* break link to dcache */
mutex_lock (&parent->i_mutex);
d_delete (dentry);
dput (dentry);
mutex_unlock (&parent->i_mutex);
spin_lock_irq (&dev->lock);
}
spin_unlock_irq (&dev->lock);
}
static struct inode *
gadgetfs_create_file (struct super_block *sb, char const *name,
void *data, const struct file_operations *fops,
struct dentry **dentry_p);
static int activate_ep_files (struct dev_data *dev)
{
struct usb_ep *ep;
struct ep_data *data;
gadget_for_each_ep (ep, dev->gadget) {
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
goto enomem0;
data->state = STATE_EP_DISABLED;
mutex_init(&data->lock);
init_waitqueue_head (&data->wait);
strncpy (data->name, ep->name, sizeof (data->name) - 1);
atomic_set (&data->count, 1);
data->dev = dev;
get_dev (dev);
data->ep = ep;
ep->driver_data = data;
data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
if (!data->req)
goto enomem1;
data->inode = gadgetfs_create_file (dev->sb, data->name,
data, &ep_config_operations,
&data->dentry);
if (!data->inode)
goto enomem2;
list_add_tail (&data->epfiles, &dev->epfiles);
}
return 0;
enomem2:
usb_ep_free_request (ep, data->req);
enomem1:
put_dev (dev);
kfree (data);
enomem0:
DBG (dev, "%s enomem\n", __func__);
destroy_ep_files (dev);
return -ENOMEM;
}
static void
gadgetfs_unbind (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
DBG (dev, "%s\n", __func__);
spin_lock_irq (&dev->lock);
dev->state = STATE_DEV_UNBOUND;
spin_unlock_irq (&dev->lock);
destroy_ep_files (dev);
gadget->ep0->driver_data = NULL;
set_gadget_data (gadget, NULL);
/* we've already been disconnected ... no i/o is active */
if (dev->req)
usb_ep_free_request (gadget->ep0, dev->req);
DBG (dev, "%s done\n", __func__);
put_dev (dev);
}
static struct dev_data *the_device;
static int
gadgetfs_bind (struct usb_gadget *gadget)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
enomem:
gadgetfs_unbind (gadget);
return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
if (dev->state == STATE_DEV_UNCONNECTED)
goto exit;
dev->state = STATE_DEV_UNCONNECTED;
INFO (dev, "disconnected\n");
next_event (dev, GADGETFS_DISCONNECT);
ep0_readable (dev);
exit:
spin_unlock_irqrestore (&dev->lock, flags);
}
static void
gadgetfs_suspend (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
INFO (dev, "suspended from state %d\n", dev->state);
spin_lock (&dev->lock);
switch (dev->state) {
case STATE_DEV_SETUP: // VERY odd... host died??
case STATE_DEV_CONNECTED:
case STATE_DEV_UNCONNECTED:
next_event (dev, GADGETFS_SUSPEND);
ep0_readable (dev);
/* FALLTHROUGH */
default:
break;
}
spin_unlock (&dev->lock);
}
static struct usb_gadget_driver gadgetfs_driver = {
.function = (char *) driver_desc,
.unbind = gadgetfs_unbind,
.setup = gadgetfs_setup,
.disconnect = gadgetfs_disconnect,
.suspend = gadgetfs_suspend,
.driver = {
.name = (char *) shortname,
},
};
/*----------------------------------------------------------------------*/
static void gadgetfs_nop(struct usb_gadget *arg) { }
static int gadgetfs_probe (struct usb_gadget *gadget)
{
CHIP = gadget->name;
return -EISNAM;
}
static struct usb_gadget_driver probe_driver = {
.max_speed = USB_SPEED_HIGH,
.unbind = gadgetfs_nop,
.setup = (void *)gadgetfs_nop,
.disconnect = gadgetfs_nop,
.driver = {
.name = "nop",
},
};
/* DEVICE INITIALIZATION
*
* fd = open ("/dev/gadget/$CHIP", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the device configuration, so the kernel can
* bind to the controller ... guaranteeing it can handle enumeration
* at all necessary speeds. Descriptor order is:
*
* . message tag (u32, host order) ... for now, must be zero; it
* would change to support features like multi-config devices
* . full/low speed config ... all wTotalLength bytes (with interface,
* class, altsetting, endpoint, and other descriptors)
* . high speed config ... all descriptors, for high speed operation;
* this one's optional except for high-speed hardware
* . device descriptor
*
* Endpoints are not yet enabled. Drivers must wait until device
* configuration and interface altsetting changes create
* the need to configure (or unconfigure) them.
*
* After initialization, the device stays active for as long as that
* $CHIP file is open. Events must then be read from that descriptor,
* such as configuration notifications.
*/
static int is_valid_config (struct usb_config_descriptor *config)
{
return config->bDescriptorType == USB_DT_CONFIG
&& config->bLength == USB_DT_CONFIG_SIZE
&& config->bConfigurationValue != 0
&& (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
&& (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
/* FIXME if gadget->is_otg, _must_ include an otg descriptor */
/* FIXME check lengths: walk to end */
}
static ssize_t
dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t value = len, length = len;
unsigned total;
u32 tag;
char *kbuf;
if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
return -EINVAL;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4))
return -EFAULT;
if (tag != 0)
return -EINVAL;
buf += 4;
length -= 4;
kbuf = memdup_user(buf, length);
if (IS_ERR(kbuf))
return PTR_ERR(kbuf);
spin_lock_irq (&dev->lock);
value = -EINVAL;
if (dev->buf)
goto fail;
dev->buf = kbuf;
/* full or low speed config */
dev->config = (void *) kbuf;
total = le16_to_cpu(dev->config->wTotalLength);
if (!is_valid_config (dev->config) || total >= length)
goto fail;
kbuf += total;
length -= total;
/* optional high speed config */
if (kbuf [1] == USB_DT_CONFIG) {
dev->hs_config = (void *) kbuf;
total = le16_to_cpu(dev->hs_config->wTotalLength);
if (!is_valid_config (dev->hs_config) || total >= length)
goto fail;
kbuf += total;
length -= total;
}
/* could support multiple configs, using another encoding! */
/* device descriptor (tweaked for paranoia) */
if (length != USB_DT_DEVICE_SIZE)
goto fail;
dev->dev = (void *)kbuf;
if (dev->dev->bLength != USB_DT_DEVICE_SIZE
|| dev->dev->bDescriptorType != USB_DT_DEVICE
|| dev->dev->bNumConfigurations != 1)
goto fail;
dev->dev->bNumConfigurations = 1;
dev->dev->bcdUSB = cpu_to_le16 (0x0200);
/* triggers gadgetfs_bind(); then we can enumerate. */
spin_unlock_irq (&dev->lock);
if (dev->hs_config)
gadgetfs_driver.max_speed = USB_SPEED_HIGH;
else
gadgetfs_driver.max_speed = USB_SPEED_FULL;
value = usb_gadget_probe_driver(&gadgetfs_driver, gadgetfs_bind);
if (value != 0) {
kfree (dev->buf);
dev->buf = NULL;
} else {
/* at this point "good" hardware has for the first time
* let the USB the host see us. alternatively, if users
* unplug/replug that will clear all the error state.
*
* note: everything running before here was guaranteed
* to choke driver model style diagnostics. from here
* on, they can work ... except in cleanup paths that
* kick in after the ep0 descriptor is closed.
*/
fd->f_op = &ep0_io_operations;
value = len;
}
return value;
fail:
spin_unlock_irq (&dev->lock);
pr_debug ("%s: %s fail %Zd, %p\n", shortname, __func__, value, dev);
kfree (dev->buf);
dev->buf = NULL;
return value;
}
static int
dev_open (struct inode *inode, struct file *fd)
{
struct dev_data *dev = inode->i_private;
int value = -EBUSY;
spin_lock_irq(&dev->lock);
if (dev->state == STATE_DEV_DISABLED) {
dev->ev_next = 0;
dev->state = STATE_DEV_OPENED;
fd->private_data = dev;
get_dev (dev);
value = 0;
}
spin_unlock_irq(&dev->lock);
return value;
}
static const struct file_operations dev_init_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = dev_open,
.write = dev_config,
.fasync = ep0_fasync,
.unlocked_ioctl = dev_ioctl,
.release = dev_release,
};
/*----------------------------------------------------------------------*/
/* FILESYSTEM AND SUPERBLOCK OPERATIONS
*
* Mounting the filesystem creates a controller file, used first for
* device configuration then later for event monitoring.
*/
/* FIXME PAM etc could set this security policy without mount options
* if epfiles inherited ownership and permissons from ep0 ...
*/
static unsigned default_uid;
static unsigned default_gid;
static unsigned default_perm = S_IRUSR | S_IWUSR;
module_param (default_uid, uint, 0644);
module_param (default_gid, uint, 0644);
module_param (default_perm, uint, 0644);
static struct inode *
gadgetfs_make_inode (struct super_block *sb,
void *data, const struct file_operations *fops,
int mode)
{
struct inode *inode = new_inode (sb);
if (inode) {
inode->i_ino = get_next_ino();
inode->i_mode = mode;
inode->i_uid = default_uid;
inode->i_gid = default_gid;
inode->i_atime = inode->i_mtime = inode->i_ctime
= CURRENT_TIME;
inode->i_private = data;
inode->i_fop = fops;
}
return inode;
}
/* creates in fs root directory, so non-renamable and non-linkable.
* so inode and dentry are paired, until device reconfig.
*/
static struct inode *
gadgetfs_create_file (struct super_block *sb, char const *name,
void *data, const struct file_operations *fops,
struct dentry **dentry_p)
{
struct dentry *dentry;
struct inode *inode;
dentry = d_alloc_name(sb->s_root, name);
if (!dentry)
return NULL;
inode = gadgetfs_make_inode (sb, data, fops,
S_IFREG | (default_perm & S_IRWXUGO));
if (!inode) {
dput(dentry);
return NULL;
}
d_add (dentry, inode);
*dentry_p = dentry;
return inode;
}
static const struct super_operations gadget_fs_operations = {
.statfs = simple_statfs,
.drop_inode = generic_delete_inode,
};
static int
gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
{
struct inode *inode;
struct dev_data *dev;
if (the_device)
return -ESRCH;
/* fake probe to determine $CHIP */
(void) usb_gadget_probe_driver(&probe_driver, gadgetfs_probe);
if (!CHIP)
return -ENODEV;
/* superblock */
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
sb->s_magic = GADGETFS_MAGIC;
sb->s_op = &gadget_fs_operations;
sb->s_time_gran = 1;
/* root inode */
inode = gadgetfs_make_inode (sb,
NULL, &simple_dir_operations,
S_IFDIR | S_IRUGO | S_IXUGO);
if (!inode)
goto Enomem;
inode->i_op = &simple_dir_inode_operations;
if (!(sb->s_root = d_make_root (inode)))
goto Enomem;
/* the ep0 file is named after the controller we expect;
* user mode code can use it for sanity checks, like we do.
*/
dev = dev_new ();
if (!dev)
goto Enomem;
dev->sb = sb;
if (!gadgetfs_create_file (sb, CHIP,
dev, &dev_init_operations,
&dev->dentry)) {
put_dev(dev);
goto Enomem;
}
/* other endpoint files are available after hardware setup,
* from binding to a controller.
*/
the_device = dev;
return 0;
Enomem:
return -ENOMEM;
}
/* "mount -t gadgetfs path /dev/gadget" ends up here */
static struct dentry *
gadgetfs_mount (struct file_system_type *t, int flags,
const char *path, void *opts)
{
return mount_single (t, flags, opts, gadgetfs_fill_super);
}
static void
gadgetfs_kill_sb (struct super_block *sb)
{
kill_litter_super (sb);
if (the_device) {
put_dev (the_device);
the_device = NULL;
}
}
/*----------------------------------------------------------------------*/
static struct file_system_type gadgetfs_type = {
.owner = THIS_MODULE,
.name = shortname,
.mount = gadgetfs_mount,
.kill_sb = gadgetfs_kill_sb,
};
/*----------------------------------------------------------------------*/
static int __init init (void)
{
int status;
status = register_filesystem (&gadgetfs_type);
if (status == 0)
pr_info ("%s: %s, version " DRIVER_VERSION "\n",
shortname, driver_desc);
return status;
}
module_init (init);
static void __exit cleanup (void)
{
pr_debug ("unregister %s\n", shortname);
unregister_filesystem (&gadgetfs_type);
}
module_exit (cleanup);
| gpl-2.0 |
wanahmadzainie/linux-mainline | drivers/platform/x86/panasonic-laptop.c | 1758 | 18390 | /*
* Panasonic HotKey and LCD brightness control driver
* (C) 2004 Hiroshi Miura <miura@da-cha.org>
* (C) 2004 NTT DATA Intellilink Co. http://www.intellilink.co.jp/
* (C) YOKOTA Hiroshi <yokota (at) netlab. is. tsukuba. ac. jp>
* (C) 2004 David Bronaugh <dbronaugh>
* (C) 2006-2008 Harald Welte <laforge@gnumonks.org>
*
* derived from toshiba_acpi.c, Copyright (C) 2002-2004 John Belmonte
*
* 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
* publicshed 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
*
*---------------------------------------------------------------------------
*
* ChangeLog:
* Sep.23, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.95 rename driver from drivers/acpi/pcc_acpi.c to
* drivers/misc/panasonic-laptop.c
*
* Jul.04, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.94 replace /proc interface with device attributes
* support {set,get}keycode on th input device
*
* Jun.27, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.92 merge with 2.6.26-rc6 input API changes
* remove broken <= 2.6.15 kernel support
* resolve all compiler warnings
* various coding style fixes (checkpatch.pl)
* add support for backlight api
* major code restructuring
*
* Dac.28, 2007 Harald Welte <laforge@gnumonks.org>
* -v0.91 merge with 2.6.24-rc6 ACPI changes
*
* Nov.04, 2006 Hiroshi Miura <miura@da-cha.org>
* -v0.9 remove warning about section reference.
* remove acpi_os_free
* add /proc/acpi/pcc/brightness interface for HAL access
* merge dbronaugh's enhancement
* Aug.17, 2004 David Bronaugh (dbronaugh)
* - Added screen brightness setting interface
* Thanks to FreeBSD crew (acpi_panasonic.c)
* for the ideas I needed to accomplish it
*
* May.29, 2006 Hiroshi Miura <miura@da-cha.org>
* -v0.8.4 follow to change keyinput structure
* thanks Fabian Yamaguchi <fabs@cs.tu-berlin.de>,
* Jacob Bower <jacob.bower@ic.ac.uk> and
* Hiroshi Yokota for providing solutions.
*
* Oct.02, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.8.2 merge code of YOKOTA Hiroshi
* <yokota@netlab.is.tsukuba.ac.jp>.
* Add sticky key mode interface.
* Refactoring acpi_pcc_generate_keyinput().
*
* Sep.15, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.8 Generate key input event on input subsystem.
* This is based on yet another driver written by
* Ryuta Nakanishi.
*
* Sep.10, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.7 Change proc interface functions using seq_file
* facility as same as other ACPI drivers.
*
* Aug.28, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.6.4 Fix a silly error with status checking
*
* Aug.25, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.6.3 replace read_acpi_int by standard function
* acpi_evaluate_integer
* some clean up and make smart copyright notice.
* fix return value of pcc_acpi_get_key()
* fix checking return value of acpi_bus_register_driver()
*
* Aug.22, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* -v0.6.2 Add check on ACPI data (num_sifr)
* Coding style cleanups, better error messages/handling
* Fixed an off-by-one error in memory allocation
*
* Aug.21, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* -v0.6.1 Fix a silly error with status checking
*
* Aug.20, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* - v0.6 Correct brightness controls to reflect reality
* based on information gleaned by Hiroshi Miura
* and discussions with Hiroshi Miura
*
* Aug.10, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.5 support LCD brightness control
* based on the disclosed information by MEI.
*
* Jul.25, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.4 first post version
* add function to retrive SIFR
*
* Jul.24, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.3 get proper status of hotkey
*
* Jul.22, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.2 add HotKey handler
*
* Jul.17, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.1 start from toshiba_acpi driver written by John Belmonte
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/backlight.h>
#include <linux/ctype.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#ifndef ACPI_HOTKEY_COMPONENT
#define ACPI_HOTKEY_COMPONENT 0x10000000
#endif
#define _COMPONENT ACPI_HOTKEY_COMPONENT
MODULE_AUTHOR("Hiroshi Miura, David Bronaugh and Harald Welte");
MODULE_DESCRIPTION("ACPI HotKey driver for Panasonic Let's Note laptops");
MODULE_LICENSE("GPL");
#define LOGPREFIX "pcc_acpi: "
/* Define ACPI PATHs */
/* Lets note hotkeys */
#define METHOD_HKEY_QUERY "HINF"
#define METHOD_HKEY_SQTY "SQTY"
#define METHOD_HKEY_SINF "SINF"
#define METHOD_HKEY_SSET "SSET"
#define HKEY_NOTIFY 0x80
#define ACPI_PCC_DRIVER_NAME "Panasonic Laptop Support"
#define ACPI_PCC_DEVICE_NAME "Hotkey"
#define ACPI_PCC_CLASS "pcc"
#define ACPI_PCC_INPUT_PHYS "panasonic/hkey0"
/* LCD_TYPEs: 0 = Normal, 1 = Semi-transparent
ENV_STATEs: Normal temp=0x01, High temp=0x81, N/A=0x00
*/
enum SINF_BITS { SINF_NUM_BATTERIES = 0,
SINF_LCD_TYPE,
SINF_AC_MAX_BRIGHT,
SINF_AC_MIN_BRIGHT,
SINF_AC_CUR_BRIGHT,
SINF_DC_MAX_BRIGHT,
SINF_DC_MIN_BRIGHT,
SINF_DC_CUR_BRIGHT,
SINF_MUTE,
SINF_RESERVED,
SINF_ENV_STATE,
SINF_STICKY_KEY = 0x80,
};
/* R1 handles SINF_AC_CUR_BRIGHT as SINF_CUR_BRIGHT, doesn't know AC state */
static int acpi_pcc_hotkey_add(struct acpi_device *device);
static int acpi_pcc_hotkey_remove(struct acpi_device *device);
static void acpi_pcc_hotkey_notify(struct acpi_device *device, u32 event);
static const struct acpi_device_id pcc_device_ids[] = {
{ "MAT0012", 0},
{ "MAT0013", 0},
{ "MAT0018", 0},
{ "MAT0019", 0},
{ "", 0},
};
MODULE_DEVICE_TABLE(acpi, pcc_device_ids);
#ifdef CONFIG_PM_SLEEP
static int acpi_pcc_hotkey_resume(struct device *dev);
#endif
static SIMPLE_DEV_PM_OPS(acpi_pcc_hotkey_pm, NULL, acpi_pcc_hotkey_resume);
static struct acpi_driver acpi_pcc_driver = {
.name = ACPI_PCC_DRIVER_NAME,
.class = ACPI_PCC_CLASS,
.ids = pcc_device_ids,
.ops = {
.add = acpi_pcc_hotkey_add,
.remove = acpi_pcc_hotkey_remove,
.notify = acpi_pcc_hotkey_notify,
},
.drv.pm = &acpi_pcc_hotkey_pm,
};
static const struct key_entry panasonic_keymap[] = {
{ KE_KEY, 0, { KEY_RESERVED } },
{ KE_KEY, 1, { KEY_BRIGHTNESSDOWN } },
{ KE_KEY, 2, { KEY_BRIGHTNESSUP } },
{ KE_KEY, 3, { KEY_DISPLAYTOGGLE } },
{ KE_KEY, 4, { KEY_MUTE } },
{ KE_KEY, 5, { KEY_VOLUMEDOWN } },
{ KE_KEY, 6, { KEY_VOLUMEUP } },
{ KE_KEY, 7, { KEY_SLEEP } },
{ KE_KEY, 8, { KEY_PROG1 } }, /* Change CPU boost */
{ KE_KEY, 9, { KEY_BATTERY } },
{ KE_KEY, 10, { KEY_SUSPEND } },
{ KE_END, 0 }
};
struct pcc_acpi {
acpi_handle handle;
unsigned long num_sifr;
int sticky_mode;
u32 *sinf;
struct acpi_device *device;
struct input_dev *input_dev;
struct backlight_device *backlight;
};
struct pcc_keyinput {
struct acpi_hotkey *hotkey;
};
/* method access functions */
static int acpi_pcc_write_sset(struct pcc_acpi *pcc, int func, int val)
{
union acpi_object in_objs[] = {
{ .integer.type = ACPI_TYPE_INTEGER,
.integer.value = func, },
{ .integer.type = ACPI_TYPE_INTEGER,
.integer.value = val, },
};
struct acpi_object_list params = {
.count = ARRAY_SIZE(in_objs),
.pointer = in_objs,
};
acpi_status status = AE_OK;
status = acpi_evaluate_object(pcc->handle, METHOD_HKEY_SSET,
¶ms, NULL);
return (status == AE_OK) ? 0 : -EIO;
}
static inline int acpi_pcc_get_sqty(struct acpi_device *device)
{
unsigned long long s;
acpi_status status;
status = acpi_evaluate_integer(device->handle, METHOD_HKEY_SQTY,
NULL, &s);
if (ACPI_SUCCESS(status))
return s;
else {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"evaluation error HKEY.SQTY\n"));
return -EINVAL;
}
}
static int acpi_pcc_retrieve_biosdata(struct pcc_acpi *pcc)
{
acpi_status status;
struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
union acpi_object *hkey = NULL;
int i;
status = acpi_evaluate_object(pcc->handle, METHOD_HKEY_SINF, NULL,
&buffer);
if (ACPI_FAILURE(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"evaluation error HKEY.SINF\n"));
return 0;
}
hkey = buffer.pointer;
if (!hkey || (hkey->type != ACPI_TYPE_PACKAGE)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "Invalid HKEY.SINF\n"));
status = AE_ERROR;
goto end;
}
if (pcc->num_sifr < hkey->package.count) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"SQTY reports bad SINF length\n"));
status = AE_ERROR;
goto end;
}
for (i = 0; i < hkey->package.count; i++) {
union acpi_object *element = &(hkey->package.elements[i]);
if (likely(element->type == ACPI_TYPE_INTEGER)) {
pcc->sinf[i] = element->integer.value;
} else
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Invalid HKEY.SINF data\n"));
}
pcc->sinf[hkey->package.count] = -1;
end:
kfree(buffer.pointer);
return status == AE_OK;
}
/* backlight API interface functions */
/* This driver currently treats AC and DC brightness identical,
* since we don't need to invent an interface to the core ACPI
* logic to receive events in case a power supply is plugged in
* or removed */
static int bl_get(struct backlight_device *bd)
{
struct pcc_acpi *pcc = bl_get_data(bd);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return pcc->sinf[SINF_AC_CUR_BRIGHT];
}
static int bl_set_status(struct backlight_device *bd)
{
struct pcc_acpi *pcc = bl_get_data(bd);
int bright = bd->props.brightness;
int rc;
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
if (bright < pcc->sinf[SINF_AC_MIN_BRIGHT])
bright = pcc->sinf[SINF_AC_MIN_BRIGHT];
if (bright < pcc->sinf[SINF_DC_MIN_BRIGHT])
bright = pcc->sinf[SINF_DC_MIN_BRIGHT];
if (bright < pcc->sinf[SINF_AC_MIN_BRIGHT] ||
bright > pcc->sinf[SINF_AC_MAX_BRIGHT])
return -EINVAL;
rc = acpi_pcc_write_sset(pcc, SINF_AC_CUR_BRIGHT, bright);
if (rc < 0)
return rc;
return acpi_pcc_write_sset(pcc, SINF_DC_CUR_BRIGHT, bright);
}
static const struct backlight_ops pcc_backlight_ops = {
.get_brightness = bl_get,
.update_status = bl_set_status,
};
/* sysfs user interface functions */
static ssize_t show_numbatt(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_NUM_BATTERIES]);
}
static ssize_t show_lcdtype(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_LCD_TYPE]);
}
static ssize_t show_mute(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_MUTE]);
}
static ssize_t show_sticky(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_STICKY_KEY]);
}
static ssize_t set_sticky(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
int val;
if (count && sscanf(buf, "%i", &val) == 1 &&
(val == 0 || val == 1)) {
acpi_pcc_write_sset(pcc, SINF_STICKY_KEY, val);
pcc->sticky_mode = val;
}
return count;
}
static DEVICE_ATTR(numbatt, S_IRUGO, show_numbatt, NULL);
static DEVICE_ATTR(lcdtype, S_IRUGO, show_lcdtype, NULL);
static DEVICE_ATTR(mute, S_IRUGO, show_mute, NULL);
static DEVICE_ATTR(sticky_key, S_IRUGO | S_IWUSR, show_sticky, set_sticky);
static struct attribute *pcc_sysfs_entries[] = {
&dev_attr_numbatt.attr,
&dev_attr_lcdtype.attr,
&dev_attr_mute.attr,
&dev_attr_sticky_key.attr,
NULL,
};
static struct attribute_group pcc_attr_group = {
.name = NULL, /* put in device directory */
.attrs = pcc_sysfs_entries,
};
/* hotkey input device driver */
static int sleep_keydown_seen;
static void acpi_pcc_generate_keyinput(struct pcc_acpi *pcc)
{
struct input_dev *hotk_input_dev = pcc->input_dev;
int rc;
unsigned long long result;
rc = acpi_evaluate_integer(pcc->handle, METHOD_HKEY_QUERY,
NULL, &result);
if (!ACPI_SUCCESS(rc)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"error getting hotkey status\n"));
return;
}
/* hack: some firmware sends no key down for sleep / hibernate */
if ((result & 0xf) == 0x7 || (result & 0xf) == 0xa) {
if (result & 0x80)
sleep_keydown_seen = 1;
if (!sleep_keydown_seen)
sparse_keymap_report_event(hotk_input_dev,
result & 0xf, 0x80, false);
}
if (!sparse_keymap_report_event(hotk_input_dev,
result & 0xf, result & 0x80, false))
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unknown hotkey event: %d\n", result));
}
static void acpi_pcc_hotkey_notify(struct acpi_device *device, u32 event)
{
struct pcc_acpi *pcc = acpi_driver_data(device);
switch (event) {
case HKEY_NOTIFY:
acpi_pcc_generate_keyinput(pcc);
break;
default:
/* nothing to do */
break;
}
}
static int acpi_pcc_init_input(struct pcc_acpi *pcc)
{
struct input_dev *input_dev;
int error;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = ACPI_PCC_DRIVER_NAME;
input_dev->phys = ACPI_PCC_INPUT_PHYS;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
error = sparse_keymap_setup(input_dev, panasonic_keymap, NULL);
if (error) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unable to setup input device keymap\n"));
goto err_free_dev;
}
error = input_register_device(input_dev);
if (error) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unable to register input device\n"));
goto err_free_keymap;
}
pcc->input_dev = input_dev;
return 0;
err_free_keymap:
sparse_keymap_free(input_dev);
err_free_dev:
input_free_device(input_dev);
return error;
}
static void acpi_pcc_destroy_input(struct pcc_acpi *pcc)
{
sparse_keymap_free(pcc->input_dev);
input_unregister_device(pcc->input_dev);
/*
* No need to input_free_device() since core input API refcounts
* and free()s the device.
*/
}
/* kernel module interface */
#ifdef CONFIG_PM_SLEEP
static int acpi_pcc_hotkey_resume(struct device *dev)
{
struct pcc_acpi *pcc;
if (!dev)
return -EINVAL;
pcc = acpi_driver_data(to_acpi_device(dev));
if (!pcc)
return -EINVAL;
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "Sticky mode restore: %d\n",
pcc->sticky_mode));
return acpi_pcc_write_sset(pcc, SINF_STICKY_KEY, pcc->sticky_mode);
}
#endif
static int acpi_pcc_hotkey_add(struct acpi_device *device)
{
struct backlight_properties props;
struct pcc_acpi *pcc;
int num_sifr, result;
if (!device)
return -EINVAL;
num_sifr = acpi_pcc_get_sqty(device);
if (num_sifr < 0 || num_sifr > 255) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "num_sifr out of range"));
return -ENODEV;
}
pcc = kzalloc(sizeof(struct pcc_acpi), GFP_KERNEL);
if (!pcc) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Couldn't allocate mem for pcc"));
return -ENOMEM;
}
pcc->sinf = kzalloc(sizeof(u32) * (num_sifr + 1), GFP_KERNEL);
if (!pcc->sinf) {
result = -ENOMEM;
goto out_hotkey;
}
pcc->device = device;
pcc->handle = device->handle;
pcc->num_sifr = num_sifr;
device->driver_data = pcc;
strcpy(acpi_device_name(device), ACPI_PCC_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_PCC_CLASS);
result = acpi_pcc_init_input(pcc);
if (result) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Error installing keyinput handler\n"));
goto out_sinf;
}
if (!acpi_pcc_retrieve_biosdata(pcc)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Couldn't retrieve BIOS data\n"));
result = -EIO;
goto out_input;
}
/* initialize backlight */
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = pcc->sinf[SINF_AC_MAX_BRIGHT];
pcc->backlight = backlight_device_register("panasonic", NULL, pcc,
&pcc_backlight_ops, &props);
if (IS_ERR(pcc->backlight)) {
result = PTR_ERR(pcc->backlight);
goto out_input;
}
/* read the initial brightness setting from the hardware */
pcc->backlight->props.brightness = pcc->sinf[SINF_AC_CUR_BRIGHT];
/* read the initial sticky key mode from the hardware */
pcc->sticky_mode = pcc->sinf[SINF_STICKY_KEY];
/* add sysfs attributes */
result = sysfs_create_group(&device->dev.kobj, &pcc_attr_group);
if (result)
goto out_backlight;
return 0;
out_backlight:
backlight_device_unregister(pcc->backlight);
out_input:
acpi_pcc_destroy_input(pcc);
out_sinf:
kfree(pcc->sinf);
out_hotkey:
kfree(pcc);
return result;
}
static int acpi_pcc_hotkey_remove(struct acpi_device *device)
{
struct pcc_acpi *pcc = acpi_driver_data(device);
if (!device || !pcc)
return -EINVAL;
sysfs_remove_group(&device->dev.kobj, &pcc_attr_group);
backlight_device_unregister(pcc->backlight);
acpi_pcc_destroy_input(pcc);
kfree(pcc->sinf);
kfree(pcc);
return 0;
}
module_acpi_driver(acpi_pcc_driver);
| gpl-2.0 |
SM-G920P/G920PVPU3BOI1 | drivers/gpu/drm/omapdrm/omap_gem_dmabuf.c | 2014 | 6137 | /*
* drivers/gpu/drm/omapdrm/omap_gem_dmabuf.c
*
* Copyright (C) 2011 Texas Instruments
* Author: Rob Clark <rob.clark@linaro.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.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "omap_drv.h"
#include <linux/dma-buf.h>
static struct sg_table *omap_gem_map_dma_buf(
struct dma_buf_attachment *attachment,
enum dma_data_direction dir)
{
struct drm_gem_object *obj = attachment->dmabuf->priv;
struct sg_table *sg;
dma_addr_t paddr;
int ret;
sg = kzalloc(sizeof(*sg), GFP_KERNEL);
if (!sg)
return ERR_PTR(-ENOMEM);
/* camera, etc, need physically contiguous.. but we need a
* better way to know this..
*/
ret = omap_gem_get_paddr(obj, &paddr, true);
if (ret)
goto out;
ret = sg_alloc_table(sg, 1, GFP_KERNEL);
if (ret)
goto out;
sg_init_table(sg->sgl, 1);
sg_dma_len(sg->sgl) = obj->size;
sg_set_page(sg->sgl, pfn_to_page(PFN_DOWN(paddr)), obj->size, 0);
sg_dma_address(sg->sgl) = paddr;
/* this should be after _get_paddr() to ensure we have pages attached */
omap_gem_dma_sync(obj, dir);
return sg;
out:
kfree(sg);
return ERR_PTR(ret);
}
static void omap_gem_unmap_dma_buf(struct dma_buf_attachment *attachment,
struct sg_table *sg, enum dma_data_direction dir)
{
struct drm_gem_object *obj = attachment->dmabuf->priv;
omap_gem_put_paddr(obj);
sg_free_table(sg);
kfree(sg);
}
static void omap_gem_dmabuf_release(struct dma_buf *buffer)
{
struct drm_gem_object *obj = buffer->priv;
/* release reference that was taken when dmabuf was exported
* in omap_gem_prime_set()..
*/
drm_gem_object_unreference_unlocked(obj);
}
static int omap_gem_dmabuf_begin_cpu_access(struct dma_buf *buffer,
size_t start, size_t len, enum dma_data_direction dir)
{
struct drm_gem_object *obj = buffer->priv;
struct page **pages;
if (omap_gem_flags(obj) & OMAP_BO_TILED) {
/* TODO we would need to pin at least part of the buffer to
* get de-tiled view. For now just reject it.
*/
return -ENOMEM;
}
/* make sure we have the pages: */
return omap_gem_get_pages(obj, &pages, true);
}
static void omap_gem_dmabuf_end_cpu_access(struct dma_buf *buffer,
size_t start, size_t len, enum dma_data_direction dir)
{
struct drm_gem_object *obj = buffer->priv;
omap_gem_put_pages(obj);
}
static void *omap_gem_dmabuf_kmap_atomic(struct dma_buf *buffer,
unsigned long page_num)
{
struct drm_gem_object *obj = buffer->priv;
struct page **pages;
omap_gem_get_pages(obj, &pages, false);
omap_gem_cpu_sync(obj, page_num);
return kmap_atomic(pages[page_num]);
}
static void omap_gem_dmabuf_kunmap_atomic(struct dma_buf *buffer,
unsigned long page_num, void *addr)
{
kunmap_atomic(addr);
}
static void *omap_gem_dmabuf_kmap(struct dma_buf *buffer,
unsigned long page_num)
{
struct drm_gem_object *obj = buffer->priv;
struct page **pages;
omap_gem_get_pages(obj, &pages, false);
omap_gem_cpu_sync(obj, page_num);
return kmap(pages[page_num]);
}
static void omap_gem_dmabuf_kunmap(struct dma_buf *buffer,
unsigned long page_num, void *addr)
{
struct drm_gem_object *obj = buffer->priv;
struct page **pages;
omap_gem_get_pages(obj, &pages, false);
kunmap(pages[page_num]);
}
/*
* TODO maybe we can split up drm_gem_mmap to avoid duplicating
* some here.. or at least have a drm_dmabuf_mmap helper.
*/
static int omap_gem_dmabuf_mmap(struct dma_buf *buffer,
struct vm_area_struct *vma)
{
struct drm_gem_object *obj = buffer->priv;
int ret = 0;
if (WARN_ON(!obj->filp))
return -EINVAL;
/* Check for valid size. */
if (omap_gem_mmap_size(obj) < vma->vm_end - vma->vm_start) {
ret = -EINVAL;
goto out_unlock;
}
if (!obj->dev->driver->gem_vm_ops) {
ret = -EINVAL;
goto out_unlock;
}
vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
vma->vm_ops = obj->dev->driver->gem_vm_ops;
vma->vm_private_data = obj;
vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
/* Take a ref for this mapping of the object, so that the fault
* handler can dereference the mmap offset's pointer to the object.
* This reference is cleaned up by the corresponding vm_close
* (which should happen whether the vma was created by this call, or
* by a vm_open due to mremap or partial unmap or whatever).
*/
vma->vm_ops->open(vma);
out_unlock:
return omap_gem_mmap_obj(obj, vma);
}
static struct dma_buf_ops omap_dmabuf_ops = {
.map_dma_buf = omap_gem_map_dma_buf,
.unmap_dma_buf = omap_gem_unmap_dma_buf,
.release = omap_gem_dmabuf_release,
.begin_cpu_access = omap_gem_dmabuf_begin_cpu_access,
.end_cpu_access = omap_gem_dmabuf_end_cpu_access,
.kmap_atomic = omap_gem_dmabuf_kmap_atomic,
.kunmap_atomic = omap_gem_dmabuf_kunmap_atomic,
.kmap = omap_gem_dmabuf_kmap,
.kunmap = omap_gem_dmabuf_kunmap,
.mmap = omap_gem_dmabuf_mmap,
};
struct dma_buf *omap_gem_prime_export(struct drm_device *dev,
struct drm_gem_object *obj, int flags)
{
return dma_buf_export(obj, &omap_dmabuf_ops, obj->size, flags);
}
struct drm_gem_object *omap_gem_prime_import(struct drm_device *dev,
struct dma_buf *buffer)
{
struct drm_gem_object *obj;
/* is this one of own objects? */
if (buffer->ops == &omap_dmabuf_ops) {
obj = buffer->priv;
/* is it from our device? */
if (obj->dev == dev) {
/*
* Importing dmabuf exported from out own gem increases
* refcount on gem itself instead of f_count of dmabuf.
*/
drm_gem_object_reference(obj);
return obj;
}
}
/*
* TODO add support for importing buffers from other devices..
* for now we don't need this but would be nice to add eventually
*/
return ERR_PTR(-EINVAL);
}
| gpl-2.0 |
XxXPachaXxX/kernel_msm_3.0 | drivers/video/mx3fb.c | 2782 | 41871 | /*
* Copyright (C) 2008
* Guennadi Liakhovetski, DENX Software Engineering, <lg@denx.de>
*
* Copyright 2004-2007 Freescale Semiconductor, 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 version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/console.h>
#include <linux/clk.h>
#include <linux/mutex.h>
#include <mach/dma.h>
#include <mach/hardware.h>
#include <mach/ipu.h>
#include <mach/mx3fb.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#define MX3FB_NAME "mx3_sdc_fb"
#define MX3FB_REG_OFFSET 0xB4
/* SDC Registers */
#define SDC_COM_CONF (0xB4 - MX3FB_REG_OFFSET)
#define SDC_GW_CTRL (0xB8 - MX3FB_REG_OFFSET)
#define SDC_FG_POS (0xBC - MX3FB_REG_OFFSET)
#define SDC_BG_POS (0xC0 - MX3FB_REG_OFFSET)
#define SDC_CUR_POS (0xC4 - MX3FB_REG_OFFSET)
#define SDC_PWM_CTRL (0xC8 - MX3FB_REG_OFFSET)
#define SDC_CUR_MAP (0xCC - MX3FB_REG_OFFSET)
#define SDC_HOR_CONF (0xD0 - MX3FB_REG_OFFSET)
#define SDC_VER_CONF (0xD4 - MX3FB_REG_OFFSET)
#define SDC_SHARP_CONF_1 (0xD8 - MX3FB_REG_OFFSET)
#define SDC_SHARP_CONF_2 (0xDC - MX3FB_REG_OFFSET)
/* Register bits */
#define SDC_COM_TFT_COLOR 0x00000001UL
#define SDC_COM_FG_EN 0x00000010UL
#define SDC_COM_GWSEL 0x00000020UL
#define SDC_COM_GLB_A 0x00000040UL
#define SDC_COM_KEY_COLOR_G 0x00000080UL
#define SDC_COM_BG_EN 0x00000200UL
#define SDC_COM_SHARP 0x00001000UL
#define SDC_V_SYNC_WIDTH_L 0x00000001UL
/* Display Interface registers */
#define DI_DISP_IF_CONF (0x0124 - MX3FB_REG_OFFSET)
#define DI_DISP_SIG_POL (0x0128 - MX3FB_REG_OFFSET)
#define DI_SER_DISP1_CONF (0x012C - MX3FB_REG_OFFSET)
#define DI_SER_DISP2_CONF (0x0130 - MX3FB_REG_OFFSET)
#define DI_HSP_CLK_PER (0x0134 - MX3FB_REG_OFFSET)
#define DI_DISP0_TIME_CONF_1 (0x0138 - MX3FB_REG_OFFSET)
#define DI_DISP0_TIME_CONF_2 (0x013C - MX3FB_REG_OFFSET)
#define DI_DISP0_TIME_CONF_3 (0x0140 - MX3FB_REG_OFFSET)
#define DI_DISP1_TIME_CONF_1 (0x0144 - MX3FB_REG_OFFSET)
#define DI_DISP1_TIME_CONF_2 (0x0148 - MX3FB_REG_OFFSET)
#define DI_DISP1_TIME_CONF_3 (0x014C - MX3FB_REG_OFFSET)
#define DI_DISP2_TIME_CONF_1 (0x0150 - MX3FB_REG_OFFSET)
#define DI_DISP2_TIME_CONF_2 (0x0154 - MX3FB_REG_OFFSET)
#define DI_DISP2_TIME_CONF_3 (0x0158 - MX3FB_REG_OFFSET)
#define DI_DISP3_TIME_CONF (0x015C - MX3FB_REG_OFFSET)
#define DI_DISP0_DB0_MAP (0x0160 - MX3FB_REG_OFFSET)
#define DI_DISP0_DB1_MAP (0x0164 - MX3FB_REG_OFFSET)
#define DI_DISP0_DB2_MAP (0x0168 - MX3FB_REG_OFFSET)
#define DI_DISP0_CB0_MAP (0x016C - MX3FB_REG_OFFSET)
#define DI_DISP0_CB1_MAP (0x0170 - MX3FB_REG_OFFSET)
#define DI_DISP0_CB2_MAP (0x0174 - MX3FB_REG_OFFSET)
#define DI_DISP1_DB0_MAP (0x0178 - MX3FB_REG_OFFSET)
#define DI_DISP1_DB1_MAP (0x017C - MX3FB_REG_OFFSET)
#define DI_DISP1_DB2_MAP (0x0180 - MX3FB_REG_OFFSET)
#define DI_DISP1_CB0_MAP (0x0184 - MX3FB_REG_OFFSET)
#define DI_DISP1_CB1_MAP (0x0188 - MX3FB_REG_OFFSET)
#define DI_DISP1_CB2_MAP (0x018C - MX3FB_REG_OFFSET)
#define DI_DISP2_DB0_MAP (0x0190 - MX3FB_REG_OFFSET)
#define DI_DISP2_DB1_MAP (0x0194 - MX3FB_REG_OFFSET)
#define DI_DISP2_DB2_MAP (0x0198 - MX3FB_REG_OFFSET)
#define DI_DISP2_CB0_MAP (0x019C - MX3FB_REG_OFFSET)
#define DI_DISP2_CB1_MAP (0x01A0 - MX3FB_REG_OFFSET)
#define DI_DISP2_CB2_MAP (0x01A4 - MX3FB_REG_OFFSET)
#define DI_DISP3_B0_MAP (0x01A8 - MX3FB_REG_OFFSET)
#define DI_DISP3_B1_MAP (0x01AC - MX3FB_REG_OFFSET)
#define DI_DISP3_B2_MAP (0x01B0 - MX3FB_REG_OFFSET)
#define DI_DISP_ACC_CC (0x01B4 - MX3FB_REG_OFFSET)
#define DI_DISP_LLA_CONF (0x01B8 - MX3FB_REG_OFFSET)
#define DI_DISP_LLA_DATA (0x01BC - MX3FB_REG_OFFSET)
/* DI_DISP_SIG_POL bits */
#define DI_D3_VSYNC_POL_SHIFT 28
#define DI_D3_HSYNC_POL_SHIFT 27
#define DI_D3_DRDY_SHARP_POL_SHIFT 26
#define DI_D3_CLK_POL_SHIFT 25
#define DI_D3_DATA_POL_SHIFT 24
/* DI_DISP_IF_CONF bits */
#define DI_D3_CLK_IDLE_SHIFT 26
#define DI_D3_CLK_SEL_SHIFT 25
#define DI_D3_DATAMSK_SHIFT 24
enum ipu_panel {
IPU_PANEL_SHARP_TFT,
IPU_PANEL_TFT,
};
struct ipu_di_signal_cfg {
unsigned datamask_en:1;
unsigned clksel_en:1;
unsigned clkidle_en:1;
unsigned data_pol:1; /* true = inverted */
unsigned clk_pol:1; /* true = rising edge */
unsigned enable_pol:1;
unsigned Hsync_pol:1; /* true = active high */
unsigned Vsync_pol:1;
};
static const struct fb_videomode mx3fb_modedb[] = {
{
/* 240x320 @ 60 Hz */
.name = "Sharp-QVGA",
.refresh = 60,
.xres = 240,
.yres = 320,
.pixclock = 185925,
.left_margin = 9,
.right_margin = 16,
.upper_margin = 7,
.lower_margin = 9,
.hsync_len = 1,
.vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_SHARP_MODE |
FB_SYNC_CLK_INVERT | FB_SYNC_DATA_INVERT |
FB_SYNC_CLK_IDLE_EN,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
}, {
/* 240x33 @ 60 Hz */
.name = "Sharp-CLI",
.refresh = 60,
.xres = 240,
.yres = 33,
.pixclock = 185925,
.left_margin = 9,
.right_margin = 16,
.upper_margin = 7,
.lower_margin = 9 + 287,
.hsync_len = 1,
.vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_SHARP_MODE |
FB_SYNC_CLK_INVERT | FB_SYNC_DATA_INVERT |
FB_SYNC_CLK_IDLE_EN,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
}, {
/* 640x480 @ 60 Hz */
.name = "NEC-VGA",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 38255,
.left_margin = 144,
.right_margin = 0,
.upper_margin = 34,
.lower_margin = 40,
.hsync_len = 1,
.vsync_len = 1,
.sync = FB_SYNC_VERT_HIGH_ACT | FB_SYNC_OE_ACT_HIGH,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
}, {
/* NTSC TV output */
.name = "TV-NTSC",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 37538,
.left_margin = 38,
.right_margin = 858 - 640 - 38 - 3,
.upper_margin = 36,
.lower_margin = 518 - 480 - 36 - 1,
.hsync_len = 3,
.vsync_len = 1,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
}, {
/* PAL TV output */
.name = "TV-PAL",
.refresh = 50,
.xres = 640,
.yres = 480,
.pixclock = 37538,
.left_margin = 38,
.right_margin = 960 - 640 - 38 - 32,
.upper_margin = 32,
.lower_margin = 555 - 480 - 32 - 3,
.hsync_len = 32,
.vsync_len = 3,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
}, {
/* TV output VGA mode, 640x480 @ 65 Hz */
.name = "TV-VGA",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 40574,
.left_margin = 35,
.right_margin = 45,
.upper_margin = 9,
.lower_margin = 1,
.hsync_len = 46,
.vsync_len = 5,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
},
};
struct mx3fb_data {
struct fb_info *fbi;
int backlight_level;
void __iomem *reg_base;
spinlock_t lock;
struct device *dev;
uint32_t h_start_width;
uint32_t v_start_width;
};
struct dma_chan_request {
struct mx3fb_data *mx3fb;
enum ipu_channel id;
};
/* MX3 specific framebuffer information. */
struct mx3fb_info {
int blank;
enum ipu_channel ipu_ch;
uint32_t cur_ipu_buf;
u32 pseudo_palette[16];
struct completion flip_cmpl;
struct mutex mutex; /* Protects fb-ops */
struct mx3fb_data *mx3fb;
struct idmac_channel *idmac_channel;
struct dma_async_tx_descriptor *txd;
dma_cookie_t cookie;
struct scatterlist sg[2];
u32 sync; /* preserve var->sync flags */
};
static void mx3fb_dma_done(void *);
/* Used fb-mode and bpp. Can be set on kernel command line, therefore file-static. */
static const char *fb_mode;
static unsigned long default_bpp = 16;
static u32 mx3fb_read_reg(struct mx3fb_data *mx3fb, unsigned long reg)
{
return __raw_readl(mx3fb->reg_base + reg);
}
static void mx3fb_write_reg(struct mx3fb_data *mx3fb, u32 value, unsigned long reg)
{
__raw_writel(value, mx3fb->reg_base + reg);
}
static const uint32_t di_mappings[] = {
0x1600AAAA, 0x00E05555, 0x00070000, 3, /* RGB888 */
0x0005000F, 0x000B000F, 0x0011000F, 1, /* RGB666 */
0x0011000F, 0x000B000F, 0x0005000F, 1, /* BGR666 */
0x0004003F, 0x000A000F, 0x000F003F, 1 /* RGB565 */
};
static void sdc_fb_init(struct mx3fb_info *fbi)
{
struct mx3fb_data *mx3fb = fbi->mx3fb;
uint32_t reg;
reg = mx3fb_read_reg(mx3fb, SDC_COM_CONF);
mx3fb_write_reg(mx3fb, reg | SDC_COM_BG_EN, SDC_COM_CONF);
}
/* Returns enabled flag before uninit */
static uint32_t sdc_fb_uninit(struct mx3fb_info *fbi)
{
struct mx3fb_data *mx3fb = fbi->mx3fb;
uint32_t reg;
reg = mx3fb_read_reg(mx3fb, SDC_COM_CONF);
mx3fb_write_reg(mx3fb, reg & ~SDC_COM_BG_EN, SDC_COM_CONF);
return reg & SDC_COM_BG_EN;
}
static void sdc_enable_channel(struct mx3fb_info *mx3_fbi)
{
struct mx3fb_data *mx3fb = mx3_fbi->mx3fb;
struct idmac_channel *ichan = mx3_fbi->idmac_channel;
struct dma_chan *dma_chan = &ichan->dma_chan;
unsigned long flags;
dma_cookie_t cookie;
if (mx3_fbi->txd)
dev_dbg(mx3fb->dev, "mx3fbi %p, desc %p, sg %p\n", mx3_fbi,
to_tx_desc(mx3_fbi->txd), to_tx_desc(mx3_fbi->txd)->sg);
else
dev_dbg(mx3fb->dev, "mx3fbi %p, txd = NULL\n", mx3_fbi);
/* This enables the channel */
if (mx3_fbi->cookie < 0) {
mx3_fbi->txd = dma_chan->device->device_prep_slave_sg(dma_chan,
&mx3_fbi->sg[0], 1, DMA_TO_DEVICE, DMA_PREP_INTERRUPT);
if (!mx3_fbi->txd) {
dev_err(mx3fb->dev, "Cannot allocate descriptor on %d\n",
dma_chan->chan_id);
return;
}
mx3_fbi->txd->callback_param = mx3_fbi->txd;
mx3_fbi->txd->callback = mx3fb_dma_done;
cookie = mx3_fbi->txd->tx_submit(mx3_fbi->txd);
dev_dbg(mx3fb->dev, "%d: Submit %p #%d [%c]\n", __LINE__,
mx3_fbi->txd, cookie, list_empty(&ichan->queue) ? '-' : '+');
} else {
if (!mx3_fbi->txd || !mx3_fbi->txd->tx_submit) {
dev_err(mx3fb->dev, "Cannot enable channel %d\n",
dma_chan->chan_id);
return;
}
/* Just re-activate the same buffer */
dma_async_issue_pending(dma_chan);
cookie = mx3_fbi->cookie;
dev_dbg(mx3fb->dev, "%d: Re-submit %p #%d [%c]\n", __LINE__,
mx3_fbi->txd, cookie, list_empty(&ichan->queue) ? '-' : '+');
}
if (cookie >= 0) {
spin_lock_irqsave(&mx3fb->lock, flags);
sdc_fb_init(mx3_fbi);
mx3_fbi->cookie = cookie;
spin_unlock_irqrestore(&mx3fb->lock, flags);
}
/*
* Attention! Without this msleep the channel keeps generating
* interrupts. Next sdc_set_brightness() is going to be called
* from mx3fb_blank().
*/
msleep(2);
}
static void sdc_disable_channel(struct mx3fb_info *mx3_fbi)
{
struct mx3fb_data *mx3fb = mx3_fbi->mx3fb;
uint32_t enabled;
unsigned long flags;
spin_lock_irqsave(&mx3fb->lock, flags);
enabled = sdc_fb_uninit(mx3_fbi);
spin_unlock_irqrestore(&mx3fb->lock, flags);
mx3_fbi->txd->chan->device->device_control(mx3_fbi->txd->chan,
DMA_TERMINATE_ALL, 0);
mx3_fbi->txd = NULL;
mx3_fbi->cookie = -EINVAL;
}
/**
* sdc_set_window_pos() - set window position of the respective plane.
* @mx3fb: mx3fb context.
* @channel: IPU DMAC channel ID.
* @x_pos: X coordinate relative to the top left corner to place window at.
* @y_pos: Y coordinate relative to the top left corner to place window at.
* @return: 0 on success or negative error code on failure.
*/
static int sdc_set_window_pos(struct mx3fb_data *mx3fb, enum ipu_channel channel,
int16_t x_pos, int16_t y_pos)
{
if (channel != IDMAC_SDC_0)
return -EINVAL;
x_pos += mx3fb->h_start_width;
y_pos += mx3fb->v_start_width;
mx3fb_write_reg(mx3fb, (x_pos << 16) | y_pos, SDC_BG_POS);
return 0;
}
/**
* sdc_init_panel() - initialize a synchronous LCD panel.
* @mx3fb: mx3fb context.
* @panel: panel type.
* @pixel_clk: desired pixel clock frequency in Hz.
* @width: width of panel in pixels.
* @height: height of panel in pixels.
* @pixel_fmt: pixel format of buffer as FOURCC ASCII code.
* @h_start_width: number of pixel clocks between the HSYNC signal pulse
* and the start of valid data.
* @h_sync_width: width of the HSYNC signal in units of pixel clocks.
* @h_end_width: number of pixel clocks between the end of valid data
* and the HSYNC signal for next line.
* @v_start_width: number of lines between the VSYNC signal pulse and the
* start of valid data.
* @v_sync_width: width of the VSYNC signal in units of lines
* @v_end_width: number of lines between the end of valid data and the
* VSYNC signal for next frame.
* @sig: bitfield of signal polarities for LCD interface.
* @return: 0 on success or negative error code on failure.
*/
static int sdc_init_panel(struct mx3fb_data *mx3fb, enum ipu_panel panel,
uint32_t pixel_clk,
uint16_t width, uint16_t height,
enum pixel_fmt pixel_fmt,
uint16_t h_start_width, uint16_t h_sync_width,
uint16_t h_end_width, uint16_t v_start_width,
uint16_t v_sync_width, uint16_t v_end_width,
struct ipu_di_signal_cfg sig)
{
unsigned long lock_flags;
uint32_t reg;
uint32_t old_conf;
uint32_t div;
struct clk *ipu_clk;
dev_dbg(mx3fb->dev, "panel size = %d x %d", width, height);
if (v_sync_width == 0 || h_sync_width == 0)
return -EINVAL;
/* Init panel size and blanking periods */
reg = ((uint32_t) (h_sync_width - 1) << 26) |
((uint32_t) (width + h_start_width + h_end_width - 1) << 16);
mx3fb_write_reg(mx3fb, reg, SDC_HOR_CONF);
#ifdef DEBUG
printk(KERN_CONT " hor_conf %x,", reg);
#endif
reg = ((uint32_t) (v_sync_width - 1) << 26) | SDC_V_SYNC_WIDTH_L |
((uint32_t) (height + v_start_width + v_end_width - 1) << 16);
mx3fb_write_reg(mx3fb, reg, SDC_VER_CONF);
#ifdef DEBUG
printk(KERN_CONT " ver_conf %x\n", reg);
#endif
mx3fb->h_start_width = h_start_width;
mx3fb->v_start_width = v_start_width;
switch (panel) {
case IPU_PANEL_SHARP_TFT:
mx3fb_write_reg(mx3fb, 0x00FD0102L, SDC_SHARP_CONF_1);
mx3fb_write_reg(mx3fb, 0x00F500F4L, SDC_SHARP_CONF_2);
mx3fb_write_reg(mx3fb, SDC_COM_SHARP | SDC_COM_TFT_COLOR, SDC_COM_CONF);
break;
case IPU_PANEL_TFT:
mx3fb_write_reg(mx3fb, SDC_COM_TFT_COLOR, SDC_COM_CONF);
break;
default:
return -EINVAL;
}
/* Init clocking */
/*
* Calculate divider: fractional part is 4 bits so simply multiple by
* 2^4 to get fractional part, as long as we stay under ~250MHz and on
* i.MX31 it (HSP_CLK) is <= 178MHz. Currently 128.267MHz
*/
ipu_clk = clk_get(mx3fb->dev, NULL);
if (!IS_ERR(ipu_clk)) {
div = clk_get_rate(ipu_clk) * 16 / pixel_clk;
clk_put(ipu_clk);
} else {
div = 0;
}
if (div < 0x40) { /* Divider less than 4 */
dev_dbg(mx3fb->dev,
"InitPanel() - Pixel clock divider less than 4\n");
div = 0x40;
}
dev_dbg(mx3fb->dev, "pixel clk = %u, divider %u.%u\n",
pixel_clk, div >> 4, (div & 7) * 125);
spin_lock_irqsave(&mx3fb->lock, lock_flags);
/*
* DISP3_IF_CLK_DOWN_WR is half the divider value and 2 fraction bits
* fewer. Subtract 1 extra from DISP3_IF_CLK_DOWN_WR based on timing
* debug. DISP3_IF_CLK_UP_WR is 0
*/
mx3fb_write_reg(mx3fb, (((div / 8) - 1) << 22) | div, DI_DISP3_TIME_CONF);
/* DI settings */
old_conf = mx3fb_read_reg(mx3fb, DI_DISP_IF_CONF) & 0x78FFFFFF;
old_conf |= sig.datamask_en << DI_D3_DATAMSK_SHIFT |
sig.clksel_en << DI_D3_CLK_SEL_SHIFT |
sig.clkidle_en << DI_D3_CLK_IDLE_SHIFT;
mx3fb_write_reg(mx3fb, old_conf, DI_DISP_IF_CONF);
old_conf = mx3fb_read_reg(mx3fb, DI_DISP_SIG_POL) & 0xE0FFFFFF;
old_conf |= sig.data_pol << DI_D3_DATA_POL_SHIFT |
sig.clk_pol << DI_D3_CLK_POL_SHIFT |
sig.enable_pol << DI_D3_DRDY_SHARP_POL_SHIFT |
sig.Hsync_pol << DI_D3_HSYNC_POL_SHIFT |
sig.Vsync_pol << DI_D3_VSYNC_POL_SHIFT;
mx3fb_write_reg(mx3fb, old_conf, DI_DISP_SIG_POL);
switch (pixel_fmt) {
case IPU_PIX_FMT_RGB24:
mx3fb_write_reg(mx3fb, di_mappings[0], DI_DISP3_B0_MAP);
mx3fb_write_reg(mx3fb, di_mappings[1], DI_DISP3_B1_MAP);
mx3fb_write_reg(mx3fb, di_mappings[2], DI_DISP3_B2_MAP);
mx3fb_write_reg(mx3fb, mx3fb_read_reg(mx3fb, DI_DISP_ACC_CC) |
((di_mappings[3] - 1) << 12), DI_DISP_ACC_CC);
break;
case IPU_PIX_FMT_RGB666:
mx3fb_write_reg(mx3fb, di_mappings[4], DI_DISP3_B0_MAP);
mx3fb_write_reg(mx3fb, di_mappings[5], DI_DISP3_B1_MAP);
mx3fb_write_reg(mx3fb, di_mappings[6], DI_DISP3_B2_MAP);
mx3fb_write_reg(mx3fb, mx3fb_read_reg(mx3fb, DI_DISP_ACC_CC) |
((di_mappings[7] - 1) << 12), DI_DISP_ACC_CC);
break;
case IPU_PIX_FMT_BGR666:
mx3fb_write_reg(mx3fb, di_mappings[8], DI_DISP3_B0_MAP);
mx3fb_write_reg(mx3fb, di_mappings[9], DI_DISP3_B1_MAP);
mx3fb_write_reg(mx3fb, di_mappings[10], DI_DISP3_B2_MAP);
mx3fb_write_reg(mx3fb, mx3fb_read_reg(mx3fb, DI_DISP_ACC_CC) |
((di_mappings[11] - 1) << 12), DI_DISP_ACC_CC);
break;
default:
mx3fb_write_reg(mx3fb, di_mappings[12], DI_DISP3_B0_MAP);
mx3fb_write_reg(mx3fb, di_mappings[13], DI_DISP3_B1_MAP);
mx3fb_write_reg(mx3fb, di_mappings[14], DI_DISP3_B2_MAP);
mx3fb_write_reg(mx3fb, mx3fb_read_reg(mx3fb, DI_DISP_ACC_CC) |
((di_mappings[15] - 1) << 12), DI_DISP_ACC_CC);
break;
}
spin_unlock_irqrestore(&mx3fb->lock, lock_flags);
dev_dbg(mx3fb->dev, "DI_DISP_IF_CONF = 0x%08X\n",
mx3fb_read_reg(mx3fb, DI_DISP_IF_CONF));
dev_dbg(mx3fb->dev, "DI_DISP_SIG_POL = 0x%08X\n",
mx3fb_read_reg(mx3fb, DI_DISP_SIG_POL));
dev_dbg(mx3fb->dev, "DI_DISP3_TIME_CONF = 0x%08X\n",
mx3fb_read_reg(mx3fb, DI_DISP3_TIME_CONF));
return 0;
}
/**
* sdc_set_color_key() - set the transparent color key for SDC graphic plane.
* @mx3fb: mx3fb context.
* @channel: IPU DMAC channel ID.
* @enable: boolean to enable or disable color keyl.
* @color_key: 24-bit RGB color to use as transparent color key.
* @return: 0 on success or negative error code on failure.
*/
static int sdc_set_color_key(struct mx3fb_data *mx3fb, enum ipu_channel channel,
bool enable, uint32_t color_key)
{
uint32_t reg, sdc_conf;
unsigned long lock_flags;
spin_lock_irqsave(&mx3fb->lock, lock_flags);
sdc_conf = mx3fb_read_reg(mx3fb, SDC_COM_CONF);
if (channel == IDMAC_SDC_0)
sdc_conf &= ~SDC_COM_GWSEL;
else
sdc_conf |= SDC_COM_GWSEL;
if (enable) {
reg = mx3fb_read_reg(mx3fb, SDC_GW_CTRL) & 0xFF000000L;
mx3fb_write_reg(mx3fb, reg | (color_key & 0x00FFFFFFL),
SDC_GW_CTRL);
sdc_conf |= SDC_COM_KEY_COLOR_G;
} else {
sdc_conf &= ~SDC_COM_KEY_COLOR_G;
}
mx3fb_write_reg(mx3fb, sdc_conf, SDC_COM_CONF);
spin_unlock_irqrestore(&mx3fb->lock, lock_flags);
return 0;
}
/**
* sdc_set_global_alpha() - set global alpha blending modes.
* @mx3fb: mx3fb context.
* @enable: boolean to enable or disable global alpha blending. If disabled,
* per pixel blending is used.
* @alpha: global alpha value.
* @return: 0 on success or negative error code on failure.
*/
static int sdc_set_global_alpha(struct mx3fb_data *mx3fb, bool enable, uint8_t alpha)
{
uint32_t reg;
unsigned long lock_flags;
spin_lock_irqsave(&mx3fb->lock, lock_flags);
if (enable) {
reg = mx3fb_read_reg(mx3fb, SDC_GW_CTRL) & 0x00FFFFFFL;
mx3fb_write_reg(mx3fb, reg | ((uint32_t) alpha << 24), SDC_GW_CTRL);
reg = mx3fb_read_reg(mx3fb, SDC_COM_CONF);
mx3fb_write_reg(mx3fb, reg | SDC_COM_GLB_A, SDC_COM_CONF);
} else {
reg = mx3fb_read_reg(mx3fb, SDC_COM_CONF);
mx3fb_write_reg(mx3fb, reg & ~SDC_COM_GLB_A, SDC_COM_CONF);
}
spin_unlock_irqrestore(&mx3fb->lock, lock_flags);
return 0;
}
static void sdc_set_brightness(struct mx3fb_data *mx3fb, uint8_t value)
{
dev_dbg(mx3fb->dev, "%s: value = %d\n", __func__, value);
/* This might be board-specific */
mx3fb_write_reg(mx3fb, 0x03000000UL | value << 16, SDC_PWM_CTRL);
return;
}
static uint32_t bpp_to_pixfmt(int bpp)
{
uint32_t pixfmt = 0;
switch (bpp) {
case 24:
pixfmt = IPU_PIX_FMT_BGR24;
break;
case 32:
pixfmt = IPU_PIX_FMT_BGR32;
break;
case 16:
pixfmt = IPU_PIX_FMT_RGB565;
break;
}
return pixfmt;
}
static int mx3fb_blank(int blank, struct fb_info *fbi);
static int mx3fb_map_video_memory(struct fb_info *fbi, unsigned int mem_len,
bool lock);
static int mx3fb_unmap_video_memory(struct fb_info *fbi);
/**
* mx3fb_set_fix() - set fixed framebuffer parameters from variable settings.
* @info: framebuffer information pointer
* @return: 0 on success or negative error code on failure.
*/
static int mx3fb_set_fix(struct fb_info *fbi)
{
struct fb_fix_screeninfo *fix = &fbi->fix;
struct fb_var_screeninfo *var = &fbi->var;
strncpy(fix->id, "DISP3 BG", 8);
fix->line_length = var->xres_virtual * var->bits_per_pixel / 8;
fix->type = FB_TYPE_PACKED_PIXELS;
fix->accel = FB_ACCEL_NONE;
fix->visual = FB_VISUAL_TRUECOLOR;
fix->xpanstep = 1;
fix->ypanstep = 1;
return 0;
}
static void mx3fb_dma_done(void *arg)
{
struct idmac_tx_desc *tx_desc = to_tx_desc(arg);
struct dma_chan *chan = tx_desc->txd.chan;
struct idmac_channel *ichannel = to_idmac_chan(chan);
struct mx3fb_data *mx3fb = ichannel->client;
struct mx3fb_info *mx3_fbi = mx3fb->fbi->par;
dev_dbg(mx3fb->dev, "irq %d callback\n", ichannel->eof_irq);
/* We only need one interrupt, it will be re-enabled as needed */
disable_irq_nosync(ichannel->eof_irq);
complete(&mx3_fbi->flip_cmpl);
}
static int __set_par(struct fb_info *fbi, bool lock)
{
u32 mem_len;
struct ipu_di_signal_cfg sig_cfg;
enum ipu_panel mode = IPU_PANEL_TFT;
struct mx3fb_info *mx3_fbi = fbi->par;
struct mx3fb_data *mx3fb = mx3_fbi->mx3fb;
struct idmac_channel *ichan = mx3_fbi->idmac_channel;
struct idmac_video_param *video = &ichan->params.video;
struct scatterlist *sg = mx3_fbi->sg;
/* Total cleanup */
if (mx3_fbi->txd)
sdc_disable_channel(mx3_fbi);
mx3fb_set_fix(fbi);
mem_len = fbi->var.yres_virtual * fbi->fix.line_length;
if (mem_len > fbi->fix.smem_len) {
if (fbi->fix.smem_start)
mx3fb_unmap_video_memory(fbi);
if (mx3fb_map_video_memory(fbi, mem_len, lock) < 0)
return -ENOMEM;
}
sg_init_table(&sg[0], 1);
sg_init_table(&sg[1], 1);
sg_dma_address(&sg[0]) = fbi->fix.smem_start;
sg_set_page(&sg[0], virt_to_page(fbi->screen_base),
fbi->fix.smem_len,
offset_in_page(fbi->screen_base));
if (mx3_fbi->ipu_ch == IDMAC_SDC_0) {
memset(&sig_cfg, 0, sizeof(sig_cfg));
if (fbi->var.sync & FB_SYNC_HOR_HIGH_ACT)
sig_cfg.Hsync_pol = true;
if (fbi->var.sync & FB_SYNC_VERT_HIGH_ACT)
sig_cfg.Vsync_pol = true;
if (fbi->var.sync & FB_SYNC_CLK_INVERT)
sig_cfg.clk_pol = true;
if (fbi->var.sync & FB_SYNC_DATA_INVERT)
sig_cfg.data_pol = true;
if (fbi->var.sync & FB_SYNC_OE_ACT_HIGH)
sig_cfg.enable_pol = true;
if (fbi->var.sync & FB_SYNC_CLK_IDLE_EN)
sig_cfg.clkidle_en = true;
if (fbi->var.sync & FB_SYNC_CLK_SEL_EN)
sig_cfg.clksel_en = true;
if (fbi->var.sync & FB_SYNC_SHARP_MODE)
mode = IPU_PANEL_SHARP_TFT;
dev_dbg(fbi->device, "pixclock = %ul Hz\n",
(u32) (PICOS2KHZ(fbi->var.pixclock) * 1000UL));
if (sdc_init_panel(mx3fb, mode,
(PICOS2KHZ(fbi->var.pixclock)) * 1000UL,
fbi->var.xres, fbi->var.yres,
(fbi->var.sync & FB_SYNC_SWAP_RGB) ?
IPU_PIX_FMT_BGR666 : IPU_PIX_FMT_RGB666,
fbi->var.left_margin,
fbi->var.hsync_len,
fbi->var.right_margin +
fbi->var.hsync_len,
fbi->var.upper_margin,
fbi->var.vsync_len,
fbi->var.lower_margin +
fbi->var.vsync_len, sig_cfg) != 0) {
dev_err(fbi->device,
"mx3fb: Error initializing panel.\n");
return -EINVAL;
}
}
sdc_set_window_pos(mx3fb, mx3_fbi->ipu_ch, 0, 0);
mx3_fbi->cur_ipu_buf = 0;
video->out_pixel_fmt = bpp_to_pixfmt(fbi->var.bits_per_pixel);
video->out_width = fbi->var.xres;
video->out_height = fbi->var.yres;
video->out_stride = fbi->var.xres_virtual;
if (mx3_fbi->blank == FB_BLANK_UNBLANK)
sdc_enable_channel(mx3_fbi);
return 0;
}
/**
* mx3fb_set_par() - set framebuffer parameters and change the operating mode.
* @fbi: framebuffer information pointer.
* @return: 0 on success or negative error code on failure.
*/
static int mx3fb_set_par(struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
struct mx3fb_data *mx3fb = mx3_fbi->mx3fb;
struct idmac_channel *ichan = mx3_fbi->idmac_channel;
int ret;
dev_dbg(mx3fb->dev, "%s [%c]\n", __func__, list_empty(&ichan->queue) ? '-' : '+');
mutex_lock(&mx3_fbi->mutex);
ret = __set_par(fbi, true);
mutex_unlock(&mx3_fbi->mutex);
return ret;
}
/**
* mx3fb_check_var() - check and adjust framebuffer variable parameters.
* @var: framebuffer variable parameters
* @fbi: framebuffer information pointer
*/
static int mx3fb_check_var(struct fb_var_screeninfo *var, struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
u32 vtotal;
u32 htotal;
dev_dbg(fbi->device, "%s\n", __func__);
if (var->xres_virtual < var->xres)
var->xres_virtual = var->xres;
if (var->yres_virtual < var->yres)
var->yres_virtual = var->yres;
if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) &&
(var->bits_per_pixel != 16))
var->bits_per_pixel = default_bpp;
switch (var->bits_per_pixel) {
case 16:
var->red.length = 5;
var->red.offset = 11;
var->red.msb_right = 0;
var->green.length = 6;
var->green.offset = 5;
var->green.msb_right = 0;
var->blue.length = 5;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.length = 0;
var->transp.offset = 0;
var->transp.msb_right = 0;
break;
case 24:
var->red.length = 8;
var->red.offset = 16;
var->red.msb_right = 0;
var->green.length = 8;
var->green.offset = 8;
var->green.msb_right = 0;
var->blue.length = 8;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.length = 0;
var->transp.offset = 0;
var->transp.msb_right = 0;
break;
case 32:
var->red.length = 8;
var->red.offset = 16;
var->red.msb_right = 0;
var->green.length = 8;
var->green.offset = 8;
var->green.msb_right = 0;
var->blue.length = 8;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.length = 8;
var->transp.offset = 24;
var->transp.msb_right = 0;
break;
}
if (var->pixclock < 1000) {
htotal = var->xres + var->right_margin + var->hsync_len +
var->left_margin;
vtotal = var->yres + var->lower_margin + var->vsync_len +
var->upper_margin;
var->pixclock = (vtotal * htotal * 6UL) / 100UL;
var->pixclock = KHZ2PICOS(var->pixclock);
dev_dbg(fbi->device, "pixclock set for 60Hz refresh = %u ps\n",
var->pixclock);
}
var->height = -1;
var->width = -1;
var->grayscale = 0;
/* Preserve sync flags */
var->sync |= mx3_fbi->sync;
mx3_fbi->sync |= var->sync;
return 0;
}
static u32 chan_to_field(unsigned int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int mx3fb_setcolreg(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
unsigned int trans, struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
u32 val;
int ret = 1;
dev_dbg(fbi->device, "%s, regno = %u\n", __func__, regno);
mutex_lock(&mx3_fbi->mutex);
/*
* If greyscale is true, then we convert the RGB value
* to greyscale no matter what visual we are using.
*/
if (fbi->var.grayscale)
red = green = blue = (19595 * red + 38470 * green +
7471 * blue) >> 16;
switch (fbi->fix.visual) {
case FB_VISUAL_TRUECOLOR:
/*
* 16-bit True Colour. We encode the RGB value
* according to the RGB bitfield information.
*/
if (regno < 16) {
u32 *pal = fbi->pseudo_palette;
val = chan_to_field(red, &fbi->var.red);
val |= chan_to_field(green, &fbi->var.green);
val |= chan_to_field(blue, &fbi->var.blue);
pal[regno] = val;
ret = 0;
}
break;
case FB_VISUAL_STATIC_PSEUDOCOLOR:
case FB_VISUAL_PSEUDOCOLOR:
break;
}
mutex_unlock(&mx3_fbi->mutex);
return ret;
}
static void __blank(int blank, struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
struct mx3fb_data *mx3fb = mx3_fbi->mx3fb;
mx3_fbi->blank = blank;
switch (blank) {
case FB_BLANK_POWERDOWN:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_NORMAL:
sdc_set_brightness(mx3fb, 0);
memset((char *)fbi->screen_base, 0, fbi->fix.smem_len);
/* Give LCD time to update - enough for 50 and 60 Hz */
msleep(25);
sdc_disable_channel(mx3_fbi);
break;
case FB_BLANK_UNBLANK:
sdc_enable_channel(mx3_fbi);
sdc_set_brightness(mx3fb, mx3fb->backlight_level);
break;
}
}
/**
* mx3fb_blank() - blank the display.
*/
static int mx3fb_blank(int blank, struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
dev_dbg(fbi->device, "%s, blank = %d, base %p, len %u\n", __func__,
blank, fbi->screen_base, fbi->fix.smem_len);
if (mx3_fbi->blank == blank)
return 0;
mutex_lock(&mx3_fbi->mutex);
__blank(blank, fbi);
mutex_unlock(&mx3_fbi->mutex);
return 0;
}
/**
* mx3fb_pan_display() - pan or wrap the display
* @var: variable screen buffer information.
* @info: framebuffer information pointer.
*
* We look only at xoffset, yoffset and the FB_VMODE_YWRAP flag
*/
static int mx3fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *fbi)
{
struct mx3fb_info *mx3_fbi = fbi->par;
u32 y_bottom;
unsigned long base;
off_t offset;
dma_cookie_t cookie;
struct scatterlist *sg = mx3_fbi->sg;
struct dma_chan *dma_chan = &mx3_fbi->idmac_channel->dma_chan;
struct dma_async_tx_descriptor *txd;
int ret;
dev_dbg(fbi->device, "%s [%c]\n", __func__,
list_empty(&mx3_fbi->idmac_channel->queue) ? '-' : '+');
if (var->xoffset > 0) {
dev_dbg(fbi->device, "x panning not supported\n");
return -EINVAL;
}
if (fbi->var.xoffset == var->xoffset &&
fbi->var.yoffset == var->yoffset)
return 0; /* No change, do nothing */
y_bottom = var->yoffset;
if (!(var->vmode & FB_VMODE_YWRAP))
y_bottom += var->yres;
if (y_bottom > fbi->var.yres_virtual)
return -EINVAL;
mutex_lock(&mx3_fbi->mutex);
offset = (var->yoffset * var->xres_virtual + var->xoffset) *
(var->bits_per_pixel / 8);
base = fbi->fix.smem_start + offset;
dev_dbg(fbi->device, "Updating SDC BG buf %d address=0x%08lX\n",
mx3_fbi->cur_ipu_buf, base);
/*
* We enable the End of Frame interrupt, which will free a tx-descriptor,
* which we will need for the next device_prep_slave_sg(). The
* IRQ-handler will disable the IRQ again.
*/
init_completion(&mx3_fbi->flip_cmpl);
enable_irq(mx3_fbi->idmac_channel->eof_irq);
ret = wait_for_completion_timeout(&mx3_fbi->flip_cmpl, HZ / 10);
if (ret <= 0) {
mutex_unlock(&mx3_fbi->mutex);
dev_info(fbi->device, "Panning failed due to %s\n", ret < 0 ?
"user interrupt" : "timeout");
disable_irq(mx3_fbi->idmac_channel->eof_irq);
return ret ? : -ETIMEDOUT;
}
mx3_fbi->cur_ipu_buf = !mx3_fbi->cur_ipu_buf;
sg_dma_address(&sg[mx3_fbi->cur_ipu_buf]) = base;
sg_set_page(&sg[mx3_fbi->cur_ipu_buf],
virt_to_page(fbi->screen_base + offset), fbi->fix.smem_len,
offset_in_page(fbi->screen_base + offset));
if (mx3_fbi->txd)
async_tx_ack(mx3_fbi->txd);
txd = dma_chan->device->device_prep_slave_sg(dma_chan, sg +
mx3_fbi->cur_ipu_buf, 1, DMA_TO_DEVICE, DMA_PREP_INTERRUPT);
if (!txd) {
dev_err(fbi->device,
"Error preparing a DMA transaction descriptor.\n");
mutex_unlock(&mx3_fbi->mutex);
return -EIO;
}
txd->callback_param = txd;
txd->callback = mx3fb_dma_done;
/*
* Emulate original mx3fb behaviour: each new call to idmac_tx_submit()
* should switch to another buffer
*/
cookie = txd->tx_submit(txd);
dev_dbg(fbi->device, "%d: Submit %p #%d\n", __LINE__, txd, cookie);
if (cookie < 0) {
dev_err(fbi->device,
"Error updating SDC buf %d to address=0x%08lX\n",
mx3_fbi->cur_ipu_buf, base);
mutex_unlock(&mx3_fbi->mutex);
return -EIO;
}
mx3_fbi->txd = txd;
fbi->var.xoffset = var->xoffset;
fbi->var.yoffset = var->yoffset;
if (var->vmode & FB_VMODE_YWRAP)
fbi->var.vmode |= FB_VMODE_YWRAP;
else
fbi->var.vmode &= ~FB_VMODE_YWRAP;
mutex_unlock(&mx3_fbi->mutex);
dev_dbg(fbi->device, "Update complete\n");
return 0;
}
/*
* This structure contains the pointers to the control functions that are
* invoked by the core framebuffer driver to perform operations like
* blitting, rectangle filling, copy regions and cursor definition.
*/
static struct fb_ops mx3fb_ops = {
.owner = THIS_MODULE,
.fb_set_par = mx3fb_set_par,
.fb_check_var = mx3fb_check_var,
.fb_setcolreg = mx3fb_setcolreg,
.fb_pan_display = mx3fb_pan_display,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_blank = mx3fb_blank,
};
#ifdef CONFIG_PM
/*
* Power management hooks. Note that we won't be called from IRQ context,
* unlike the blank functions above, so we may sleep.
*/
/*
* Suspends the framebuffer and blanks the screen. Power management support
*/
static int mx3fb_suspend(struct platform_device *pdev, pm_message_t state)
{
struct mx3fb_data *mx3fb = platform_get_drvdata(pdev);
struct mx3fb_info *mx3_fbi = mx3fb->fbi->par;
console_lock();
fb_set_suspend(mx3fb->fbi, 1);
console_unlock();
if (mx3_fbi->blank == FB_BLANK_UNBLANK) {
sdc_disable_channel(mx3_fbi);
sdc_set_brightness(mx3fb, 0);
}
return 0;
}
/*
* Resumes the framebuffer and unblanks the screen. Power management support
*/
static int mx3fb_resume(struct platform_device *pdev)
{
struct mx3fb_data *mx3fb = platform_get_drvdata(pdev);
struct mx3fb_info *mx3_fbi = mx3fb->fbi->par;
if (mx3_fbi->blank == FB_BLANK_UNBLANK) {
sdc_enable_channel(mx3_fbi);
sdc_set_brightness(mx3fb, mx3fb->backlight_level);
}
console_lock();
fb_set_suspend(mx3fb->fbi, 0);
console_unlock();
return 0;
}
#else
#define mx3fb_suspend NULL
#define mx3fb_resume NULL
#endif
/*
* Main framebuffer functions
*/
/**
* mx3fb_map_video_memory() - allocates the DRAM memory for the frame buffer.
* @fbi: framebuffer information pointer
* @mem_len: length of mapped memory
* @lock: do not lock during initialisation
* @return: Error code indicating success or failure
*
* This buffer is remapped into a non-cached, non-buffered, memory region to
* allow palette and pixel writes to occur without flushing the cache. Once this
* area is remapped, all virtual memory access to the video memory should occur
* at the new region.
*/
static int mx3fb_map_video_memory(struct fb_info *fbi, unsigned int mem_len,
bool lock)
{
int retval = 0;
dma_addr_t addr;
fbi->screen_base = dma_alloc_writecombine(fbi->device,
mem_len,
&addr, GFP_DMA);
if (!fbi->screen_base) {
dev_err(fbi->device, "Cannot allocate %u bytes framebuffer memory\n",
mem_len);
retval = -EBUSY;
goto err0;
}
if (lock)
mutex_lock(&fbi->mm_lock);
fbi->fix.smem_start = addr;
fbi->fix.smem_len = mem_len;
if (lock)
mutex_unlock(&fbi->mm_lock);
dev_dbg(fbi->device, "allocated fb @ p=0x%08x, v=0x%p, size=%d.\n",
(uint32_t) fbi->fix.smem_start, fbi->screen_base, fbi->fix.smem_len);
fbi->screen_size = fbi->fix.smem_len;
/* Clear the screen */
memset((char *)fbi->screen_base, 0, fbi->fix.smem_len);
return 0;
err0:
fbi->fix.smem_len = 0;
fbi->fix.smem_start = 0;
fbi->screen_base = NULL;
return retval;
}
/**
* mx3fb_unmap_video_memory() - de-allocate frame buffer memory.
* @fbi: framebuffer information pointer
* @return: error code indicating success or failure
*/
static int mx3fb_unmap_video_memory(struct fb_info *fbi)
{
dma_free_writecombine(fbi->device, fbi->fix.smem_len,
fbi->screen_base, fbi->fix.smem_start);
fbi->screen_base = 0;
mutex_lock(&fbi->mm_lock);
fbi->fix.smem_start = 0;
fbi->fix.smem_len = 0;
mutex_unlock(&fbi->mm_lock);
return 0;
}
/**
* mx3fb_init_fbinfo() - initialize framebuffer information object.
* @return: initialized framebuffer structure.
*/
static struct fb_info *mx3fb_init_fbinfo(struct device *dev, struct fb_ops *ops)
{
struct fb_info *fbi;
struct mx3fb_info *mx3fbi;
int ret;
/* Allocate sufficient memory for the fb structure */
fbi = framebuffer_alloc(sizeof(struct mx3fb_info), dev);
if (!fbi)
return NULL;
mx3fbi = fbi->par;
mx3fbi->cookie = -EINVAL;
mx3fbi->cur_ipu_buf = 0;
fbi->var.activate = FB_ACTIVATE_NOW;
fbi->fbops = ops;
fbi->flags = FBINFO_FLAG_DEFAULT;
fbi->pseudo_palette = mx3fbi->pseudo_palette;
mutex_init(&mx3fbi->mutex);
/* Allocate colormap */
ret = fb_alloc_cmap(&fbi->cmap, 16, 0);
if (ret < 0) {
framebuffer_release(fbi);
return NULL;
}
return fbi;
}
static int init_fb_chan(struct mx3fb_data *mx3fb, struct idmac_channel *ichan)
{
struct device *dev = mx3fb->dev;
struct mx3fb_platform_data *mx3fb_pdata = dev->platform_data;
const char *name = mx3fb_pdata->name;
unsigned int irq;
struct fb_info *fbi;
struct mx3fb_info *mx3fbi;
const struct fb_videomode *mode;
int ret, num_modes;
ichan->client = mx3fb;
irq = ichan->eof_irq;
if (ichan->dma_chan.chan_id != IDMAC_SDC_0)
return -EINVAL;
fbi = mx3fb_init_fbinfo(dev, &mx3fb_ops);
if (!fbi)
return -ENOMEM;
if (!fb_mode)
fb_mode = name;
if (!fb_mode) {
ret = -EINVAL;
goto emode;
}
if (mx3fb_pdata->mode && mx3fb_pdata->num_modes) {
mode = mx3fb_pdata->mode;
num_modes = mx3fb_pdata->num_modes;
} else {
mode = mx3fb_modedb;
num_modes = ARRAY_SIZE(mx3fb_modedb);
}
if (!fb_find_mode(&fbi->var, fbi, fb_mode, mode,
num_modes, NULL, default_bpp)) {
ret = -EBUSY;
goto emode;
}
fb_videomode_to_modelist(mode, num_modes, &fbi->modelist);
/* Default Y virtual size is 2x panel size */
fbi->var.yres_virtual = fbi->var.yres * 2;
mx3fb->fbi = fbi;
/* set Display Interface clock period */
mx3fb_write_reg(mx3fb, 0x00100010L, DI_HSP_CLK_PER);
/* Might need to trigger HSP clock change - see 44.3.3.8.5 */
sdc_set_brightness(mx3fb, 255);
sdc_set_global_alpha(mx3fb, true, 0xFF);
sdc_set_color_key(mx3fb, IDMAC_SDC_0, false, 0);
mx3fbi = fbi->par;
mx3fbi->idmac_channel = ichan;
mx3fbi->ipu_ch = ichan->dma_chan.chan_id;
mx3fbi->mx3fb = mx3fb;
mx3fbi->blank = FB_BLANK_NORMAL;
init_completion(&mx3fbi->flip_cmpl);
disable_irq(ichan->eof_irq);
dev_dbg(mx3fb->dev, "disabling irq %d\n", ichan->eof_irq);
ret = __set_par(fbi, false);
if (ret < 0)
goto esetpar;
__blank(FB_BLANK_UNBLANK, fbi);
dev_info(dev, "registered, using mode %s\n", fb_mode);
ret = register_framebuffer(fbi);
if (ret < 0)
goto erfb;
return 0;
erfb:
esetpar:
emode:
fb_dealloc_cmap(&fbi->cmap);
framebuffer_release(fbi);
return ret;
}
static bool chan_filter(struct dma_chan *chan, void *arg)
{
struct dma_chan_request *rq = arg;
struct device *dev;
struct mx3fb_platform_data *mx3fb_pdata;
if (!imx_dma_is_ipu(chan))
return false;
if (!rq)
return false;
dev = rq->mx3fb->dev;
mx3fb_pdata = dev->platform_data;
return rq->id == chan->chan_id &&
mx3fb_pdata->dma_dev == chan->device->dev;
}
static void release_fbi(struct fb_info *fbi)
{
mx3fb_unmap_video_memory(fbi);
fb_dealloc_cmap(&fbi->cmap);
unregister_framebuffer(fbi);
framebuffer_release(fbi);
}
static int mx3fb_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
int ret;
struct resource *sdc_reg;
struct mx3fb_data *mx3fb;
dma_cap_mask_t mask;
struct dma_chan *chan;
struct dma_chan_request rq;
/*
* Display Interface (DI) and Synchronous Display Controller (SDC)
* registers
*/
sdc_reg = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!sdc_reg)
return -EINVAL;
mx3fb = kzalloc(sizeof(*mx3fb), GFP_KERNEL);
if (!mx3fb)
return -ENOMEM;
spin_lock_init(&mx3fb->lock);
mx3fb->reg_base = ioremap(sdc_reg->start, resource_size(sdc_reg));
if (!mx3fb->reg_base) {
ret = -ENOMEM;
goto eremap;
}
pr_debug("Remapped %pR at %p\n", sdc_reg, mx3fb->reg_base);
/* IDMAC interface */
dmaengine_get();
mx3fb->dev = dev;
platform_set_drvdata(pdev, mx3fb);
rq.mx3fb = mx3fb;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
dma_cap_set(DMA_PRIVATE, mask);
rq.id = IDMAC_SDC_0;
chan = dma_request_channel(mask, chan_filter, &rq);
if (!chan) {
ret = -EBUSY;
goto ersdc0;
}
mx3fb->backlight_level = 255;
ret = init_fb_chan(mx3fb, to_idmac_chan(chan));
if (ret < 0)
goto eisdc0;
return 0;
eisdc0:
dma_release_channel(chan);
ersdc0:
dmaengine_put();
iounmap(mx3fb->reg_base);
eremap:
kfree(mx3fb);
dev_err(dev, "mx3fb: failed to register fb\n");
return ret;
}
static int mx3fb_remove(struct platform_device *dev)
{
struct mx3fb_data *mx3fb = platform_get_drvdata(dev);
struct fb_info *fbi = mx3fb->fbi;
struct mx3fb_info *mx3_fbi = fbi->par;
struct dma_chan *chan;
chan = &mx3_fbi->idmac_channel->dma_chan;
release_fbi(fbi);
dma_release_channel(chan);
dmaengine_put();
iounmap(mx3fb->reg_base);
kfree(mx3fb);
return 0;
}
static struct platform_driver mx3fb_driver = {
.driver = {
.name = MX3FB_NAME,
},
.probe = mx3fb_probe,
.remove = mx3fb_remove,
.suspend = mx3fb_suspend,
.resume = mx3fb_resume,
};
/*
* Parse user specified options (`video=mx3fb:')
* example:
* video=mx3fb:bpp=16
*/
static int __init mx3fb_setup(void)
{
#ifndef MODULE
char *opt, *options = NULL;
if (fb_get_options("mx3fb", &options))
return -ENODEV;
if (!options || !*options)
return 0;
while ((opt = strsep(&options, ",")) != NULL) {
if (!*opt)
continue;
if (!strncmp(opt, "bpp=", 4))
default_bpp = simple_strtoul(opt + 4, NULL, 0);
else
fb_mode = opt;
}
#endif
return 0;
}
static int __init mx3fb_init(void)
{
int ret = mx3fb_setup();
if (ret < 0)
return ret;
ret = platform_driver_register(&mx3fb_driver);
return ret;
}
static void __exit mx3fb_exit(void)
{
platform_driver_unregister(&mx3fb_driver);
}
module_init(mx3fb_init);
module_exit(mx3fb_exit);
MODULE_AUTHOR("Freescale Semiconductor, Inc.");
MODULE_DESCRIPTION("MX3 framebuffer driver");
MODULE_ALIAS("platform:" MX3FB_NAME);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
agrabren/android_kernel_htc_shooter | fs/nfsd/nfs4acl.c | 3038 | 22029 | /*
* Common NFSv4 ACL handling code.
*
* Copyright (c) 2002, 2003 The Regents of the University of Michigan.
* All rights reserved.
*
* Marius Aamodt Eriksen <marius@umich.edu>
* Jeff Sedlak <jsedlak@umich.edu>
* J. Bruce Fields <bfields@umich.edu>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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/slab.h>
#include <linux/nfs_fs.h>
#include "acl.h"
/* mode bit translations: */
#define NFS4_READ_MODE (NFS4_ACE_READ_DATA)
#define NFS4_WRITE_MODE (NFS4_ACE_WRITE_DATA | NFS4_ACE_APPEND_DATA)
#define NFS4_EXECUTE_MODE NFS4_ACE_EXECUTE
#define NFS4_ANYONE_MODE (NFS4_ACE_READ_ATTRIBUTES | NFS4_ACE_READ_ACL | NFS4_ACE_SYNCHRONIZE)
#define NFS4_OWNER_MODE (NFS4_ACE_WRITE_ATTRIBUTES | NFS4_ACE_WRITE_ACL)
/* We don't support these bits; insist they be neither allowed nor denied */
#define NFS4_MASK_UNSUPP (NFS4_ACE_DELETE | NFS4_ACE_WRITE_OWNER \
| NFS4_ACE_READ_NAMED_ATTRS | NFS4_ACE_WRITE_NAMED_ATTRS)
/* flags used to simulate posix default ACLs */
#define NFS4_INHERITANCE_FLAGS (NFS4_ACE_FILE_INHERIT_ACE \
| NFS4_ACE_DIRECTORY_INHERIT_ACE)
#define NFS4_SUPPORTED_FLAGS (NFS4_INHERITANCE_FLAGS \
| NFS4_ACE_INHERIT_ONLY_ACE \
| NFS4_ACE_IDENTIFIER_GROUP)
#define MASK_EQUAL(mask1, mask2) \
( ((mask1) & NFS4_ACE_MASK_ALL) == ((mask2) & NFS4_ACE_MASK_ALL) )
static u32
mask_from_posix(unsigned short perm, unsigned int flags)
{
int mask = NFS4_ANYONE_MODE;
if (flags & NFS4_ACL_OWNER)
mask |= NFS4_OWNER_MODE;
if (perm & ACL_READ)
mask |= NFS4_READ_MODE;
if (perm & ACL_WRITE)
mask |= NFS4_WRITE_MODE;
if ((perm & ACL_WRITE) && (flags & NFS4_ACL_DIR))
mask |= NFS4_ACE_DELETE_CHILD;
if (perm & ACL_EXECUTE)
mask |= NFS4_EXECUTE_MODE;
return mask;
}
static u32
deny_mask_from_posix(unsigned short perm, u32 flags)
{
u32 mask = 0;
if (perm & ACL_READ)
mask |= NFS4_READ_MODE;
if (perm & ACL_WRITE)
mask |= NFS4_WRITE_MODE;
if ((perm & ACL_WRITE) && (flags & NFS4_ACL_DIR))
mask |= NFS4_ACE_DELETE_CHILD;
if (perm & ACL_EXECUTE)
mask |= NFS4_EXECUTE_MODE;
return mask;
}
/* XXX: modify functions to return NFS errors; they're only ever
* used by nfs code, after all.... */
/* We only map from NFSv4 to POSIX ACLs when setting ACLs, when we err on the
* side of being more restrictive, so the mode bit mapping below is
* pessimistic. An optimistic version would be needed to handle DENY's,
* but we espect to coalesce all ALLOWs and DENYs before mapping to mode
* bits. */
static void
low_mode_from_nfs4(u32 perm, unsigned short *mode, unsigned int flags)
{
u32 write_mode = NFS4_WRITE_MODE;
if (flags & NFS4_ACL_DIR)
write_mode |= NFS4_ACE_DELETE_CHILD;
*mode = 0;
if ((perm & NFS4_READ_MODE) == NFS4_READ_MODE)
*mode |= ACL_READ;
if ((perm & write_mode) == write_mode)
*mode |= ACL_WRITE;
if ((perm & NFS4_EXECUTE_MODE) == NFS4_EXECUTE_MODE)
*mode |= ACL_EXECUTE;
}
struct ace_container {
struct nfs4_ace *ace;
struct list_head ace_l;
};
static short ace2type(struct nfs4_ace *);
static void _posix_to_nfsv4_one(struct posix_acl *, struct nfs4_acl *,
unsigned int);
struct nfs4_acl *
nfs4_acl_posix_to_nfsv4(struct posix_acl *pacl, struct posix_acl *dpacl,
unsigned int flags)
{
struct nfs4_acl *acl;
int size = 0;
if (pacl) {
if (posix_acl_valid(pacl) < 0)
return ERR_PTR(-EINVAL);
size += 2*pacl->a_count;
}
if (dpacl) {
if (posix_acl_valid(dpacl) < 0)
return ERR_PTR(-EINVAL);
size += 2*dpacl->a_count;
}
/* Allocate for worst case: one (deny, allow) pair each: */
acl = nfs4_acl_new(size);
if (acl == NULL)
return ERR_PTR(-ENOMEM);
if (pacl)
_posix_to_nfsv4_one(pacl, acl, flags & ~NFS4_ACL_TYPE_DEFAULT);
if (dpacl)
_posix_to_nfsv4_one(dpacl, acl, flags | NFS4_ACL_TYPE_DEFAULT);
return acl;
}
struct posix_acl_summary {
unsigned short owner;
unsigned short users;
unsigned short group;
unsigned short groups;
unsigned short other;
unsigned short mask;
};
static void
summarize_posix_acl(struct posix_acl *acl, struct posix_acl_summary *pas)
{
struct posix_acl_entry *pa, *pe;
/*
* Only pas.users and pas.groups need initialization; previous
* posix_acl_valid() calls ensure that the other fields will be
* initialized in the following loop. But, just to placate gcc:
*/
memset(pas, 0, sizeof(*pas));
pas->mask = 07;
pe = acl->a_entries + acl->a_count;
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch (pa->e_tag) {
case ACL_USER_OBJ:
pas->owner = pa->e_perm;
break;
case ACL_GROUP_OBJ:
pas->group = pa->e_perm;
break;
case ACL_USER:
pas->users |= pa->e_perm;
break;
case ACL_GROUP:
pas->groups |= pa->e_perm;
break;
case ACL_OTHER:
pas->other = pa->e_perm;
break;
case ACL_MASK:
pas->mask = pa->e_perm;
break;
}
}
/* We'll only care about effective permissions: */
pas->users &= pas->mask;
pas->group &= pas->mask;
pas->groups &= pas->mask;
}
/* We assume the acl has been verified with posix_acl_valid. */
static void
_posix_to_nfsv4_one(struct posix_acl *pacl, struct nfs4_acl *acl,
unsigned int flags)
{
struct posix_acl_entry *pa, *group_owner_entry;
struct nfs4_ace *ace;
struct posix_acl_summary pas;
unsigned short deny;
int eflag = ((flags & NFS4_ACL_TYPE_DEFAULT) ?
NFS4_INHERITANCE_FLAGS | NFS4_ACE_INHERIT_ONLY_ACE : 0);
BUG_ON(pacl->a_count < 3);
summarize_posix_acl(pacl, &pas);
pa = pacl->a_entries;
ace = acl->aces + acl->naces;
/* We could deny everything not granted by the owner: */
deny = ~pas.owner;
/*
* but it is equivalent (and simpler) to deny only what is not
* granted by later entries:
*/
deny &= pas.users | pas.group | pas.groups | pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_OWNER;
ace++;
acl->naces++;
}
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm, flags | NFS4_ACL_OWNER);
ace->whotype = NFS4_ACL_WHO_OWNER;
ace++;
acl->naces++;
pa++;
while (pa->e_tag == ACL_USER) {
deny = ~(pa->e_perm & pas.mask);
deny &= pas.groups | pas.group | pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who = pa->e_id;
ace++;
acl->naces++;
}
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm & pas.mask,
flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who = pa->e_id;
ace++;
acl->naces++;
pa++;
}
/* In the case of groups, we apply allow ACEs first, then deny ACEs,
* since a user can be in more than one group. */
/* allow ACEs */
group_owner_entry = pa;
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pas.group, flags);
ace->whotype = NFS4_ACL_WHO_GROUP;
ace++;
acl->naces++;
pa++;
while (pa->e_tag == ACL_GROUP) {
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag | NFS4_ACE_IDENTIFIER_GROUP;
ace->access_mask = mask_from_posix(pa->e_perm & pas.mask,
flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who = pa->e_id;
ace++;
acl->naces++;
pa++;
}
/* deny ACEs */
pa = group_owner_entry;
deny = ~pas.group & pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_GROUP;
ace++;
acl->naces++;
}
pa++;
while (pa->e_tag == ACL_GROUP) {
deny = ~(pa->e_perm & pas.mask);
deny &= pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag | NFS4_ACE_IDENTIFIER_GROUP;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who = pa->e_id;
ace++;
acl->naces++;
}
pa++;
}
if (pa->e_tag == ACL_MASK)
pa++;
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm, flags);
ace->whotype = NFS4_ACL_WHO_EVERYONE;
acl->naces++;
}
static void
sort_pacl_range(struct posix_acl *pacl, int start, int end) {
int sorted = 0, i;
struct posix_acl_entry tmp;
/* We just do a bubble sort; easy to do in place, and we're not
* expecting acl's to be long enough to justify anything more. */
while (!sorted) {
sorted = 1;
for (i = start; i < end; i++) {
if (pacl->a_entries[i].e_id
> pacl->a_entries[i+1].e_id) {
sorted = 0;
tmp = pacl->a_entries[i];
pacl->a_entries[i] = pacl->a_entries[i+1];
pacl->a_entries[i+1] = tmp;
}
}
}
}
static void
sort_pacl(struct posix_acl *pacl)
{
/* posix_acl_valid requires that users and groups be in order
* by uid/gid. */
int i, j;
if (pacl->a_count <= 4)
return; /* no users or groups */
i = 1;
while (pacl->a_entries[i].e_tag == ACL_USER)
i++;
sort_pacl_range(pacl, 1, i-1);
BUG_ON(pacl->a_entries[i].e_tag != ACL_GROUP_OBJ);
j = ++i;
while (pacl->a_entries[j].e_tag == ACL_GROUP)
j++;
sort_pacl_range(pacl, i, j-1);
return;
}
/*
* While processing the NFSv4 ACE, this maintains bitmasks representing
* which permission bits have been allowed and which denied to a given
* entity: */
struct posix_ace_state {
u32 allow;
u32 deny;
};
struct posix_user_ace_state {
uid_t uid;
struct posix_ace_state perms;
};
struct posix_ace_state_array {
int n;
struct posix_user_ace_state aces[];
};
/*
* While processing the NFSv4 ACE, this maintains the partial permissions
* calculated so far: */
struct posix_acl_state {
int empty;
struct posix_ace_state owner;
struct posix_ace_state group;
struct posix_ace_state other;
struct posix_ace_state everyone;
struct posix_ace_state mask; /* Deny unused in this case */
struct posix_ace_state_array *users;
struct posix_ace_state_array *groups;
};
static int
init_state(struct posix_acl_state *state, int cnt)
{
int alloc;
memset(state, 0, sizeof(struct posix_acl_state));
state->empty = 1;
/*
* In the worst case, each individual acl could be for a distinct
* named user or group, but we don't no which, so we allocate
* enough space for either:
*/
alloc = sizeof(struct posix_ace_state_array)
+ cnt*sizeof(struct posix_user_ace_state);
state->users = kzalloc(alloc, GFP_KERNEL);
if (!state->users)
return -ENOMEM;
state->groups = kzalloc(alloc, GFP_KERNEL);
if (!state->groups) {
kfree(state->users);
return -ENOMEM;
}
return 0;
}
static void
free_state(struct posix_acl_state *state) {
kfree(state->users);
kfree(state->groups);
}
static inline void add_to_mask(struct posix_acl_state *state, struct posix_ace_state *astate)
{
state->mask.allow |= astate->allow;
}
/*
* Certain bits (SYNCHRONIZE, DELETE, WRITE_OWNER, READ/WRITE_NAMED_ATTRS,
* READ_ATTRIBUTES, READ_ACL) are currently unenforceable and don't translate
* to traditional read/write/execute permissions.
*
* It's problematic to reject acls that use certain mode bits, because it
* places the burden on users to learn the rules about which bits one
* particular server sets, without giving the user a lot of help--we return an
* error that could mean any number of different things. To make matters
* worse, the problematic bits might be introduced by some application that's
* automatically mapping from some other acl model.
*
* So wherever possible we accept anything, possibly erring on the side of
* denying more permissions than necessary.
*
* However we do reject *explicit* DENY's of a few bits representing
* permissions we could never deny:
*/
static inline int check_deny(u32 mask, int isowner)
{
if (mask & (NFS4_ACE_READ_ATTRIBUTES | NFS4_ACE_READ_ACL))
return -EINVAL;
if (!isowner)
return 0;
if (mask & (NFS4_ACE_WRITE_ATTRIBUTES | NFS4_ACE_WRITE_ACL))
return -EINVAL;
return 0;
}
static struct posix_acl *
posix_state_to_acl(struct posix_acl_state *state, unsigned int flags)
{
struct posix_acl_entry *pace;
struct posix_acl *pacl;
int nace;
int i, error = 0;
/*
* ACLs with no ACEs are treated differently in the inheritable
* and effective cases: when there are no inheritable ACEs, we
* set a zero-length default posix acl:
*/
if (state->empty && (flags & NFS4_ACL_TYPE_DEFAULT)) {
pacl = posix_acl_alloc(0, GFP_KERNEL);
return pacl ? pacl : ERR_PTR(-ENOMEM);
}
/*
* When there are no effective ACEs, the following will end
* up setting a 3-element effective posix ACL with all
* permissions zero.
*/
nace = 4 + state->users->n + state->groups->n;
pacl = posix_acl_alloc(nace, GFP_KERNEL);
if (!pacl)
return ERR_PTR(-ENOMEM);
pace = pacl->a_entries;
pace->e_tag = ACL_USER_OBJ;
error = check_deny(state->owner.deny, 1);
if (error)
goto out_err;
low_mode_from_nfs4(state->owner.allow, &pace->e_perm, flags);
pace->e_id = ACL_UNDEFINED_ID;
for (i=0; i < state->users->n; i++) {
pace++;
pace->e_tag = ACL_USER;
error = check_deny(state->users->aces[i].perms.deny, 0);
if (error)
goto out_err;
low_mode_from_nfs4(state->users->aces[i].perms.allow,
&pace->e_perm, flags);
pace->e_id = state->users->aces[i].uid;
add_to_mask(state, &state->users->aces[i].perms);
}
pace++;
pace->e_tag = ACL_GROUP_OBJ;
error = check_deny(state->group.deny, 0);
if (error)
goto out_err;
low_mode_from_nfs4(state->group.allow, &pace->e_perm, flags);
pace->e_id = ACL_UNDEFINED_ID;
add_to_mask(state, &state->group);
for (i=0; i < state->groups->n; i++) {
pace++;
pace->e_tag = ACL_GROUP;
error = check_deny(state->groups->aces[i].perms.deny, 0);
if (error)
goto out_err;
low_mode_from_nfs4(state->groups->aces[i].perms.allow,
&pace->e_perm, flags);
pace->e_id = state->groups->aces[i].uid;
add_to_mask(state, &state->groups->aces[i].perms);
}
pace++;
pace->e_tag = ACL_MASK;
low_mode_from_nfs4(state->mask.allow, &pace->e_perm, flags);
pace->e_id = ACL_UNDEFINED_ID;
pace++;
pace->e_tag = ACL_OTHER;
error = check_deny(state->other.deny, 0);
if (error)
goto out_err;
low_mode_from_nfs4(state->other.allow, &pace->e_perm, flags);
pace->e_id = ACL_UNDEFINED_ID;
return pacl;
out_err:
posix_acl_release(pacl);
return ERR_PTR(error);
}
static inline void allow_bits(struct posix_ace_state *astate, u32 mask)
{
/* Allow all bits in the mask not already denied: */
astate->allow |= mask & ~astate->deny;
}
static inline void deny_bits(struct posix_ace_state *astate, u32 mask)
{
/* Deny all bits in the mask not already allowed: */
astate->deny |= mask & ~astate->allow;
}
static int find_uid(struct posix_acl_state *state, struct posix_ace_state_array *a, uid_t uid)
{
int i;
for (i = 0; i < a->n; i++)
if (a->aces[i].uid == uid)
return i;
/* Not found: */
a->n++;
a->aces[i].uid = uid;
a->aces[i].perms.allow = state->everyone.allow;
a->aces[i].perms.deny = state->everyone.deny;
return i;
}
static void deny_bits_array(struct posix_ace_state_array *a, u32 mask)
{
int i;
for (i=0; i < a->n; i++)
deny_bits(&a->aces[i].perms, mask);
}
static void allow_bits_array(struct posix_ace_state_array *a, u32 mask)
{
int i;
for (i=0; i < a->n; i++)
allow_bits(&a->aces[i].perms, mask);
}
static void process_one_v4_ace(struct posix_acl_state *state,
struct nfs4_ace *ace)
{
u32 mask = ace->access_mask;
int i;
state->empty = 0;
switch (ace2type(ace)) {
case ACL_USER_OBJ:
if (ace->type == NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE) {
allow_bits(&state->owner, mask);
} else {
deny_bits(&state->owner, mask);
}
break;
case ACL_USER:
i = find_uid(state, state->users, ace->who);
if (ace->type == NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE) {
allow_bits(&state->users->aces[i].perms, mask);
} else {
deny_bits(&state->users->aces[i].perms, mask);
mask = state->users->aces[i].perms.deny;
deny_bits(&state->owner, mask);
}
break;
case ACL_GROUP_OBJ:
if (ace->type == NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE) {
allow_bits(&state->group, mask);
} else {
deny_bits(&state->group, mask);
mask = state->group.deny;
deny_bits(&state->owner, mask);
deny_bits(&state->everyone, mask);
deny_bits_array(state->users, mask);
deny_bits_array(state->groups, mask);
}
break;
case ACL_GROUP:
i = find_uid(state, state->groups, ace->who);
if (ace->type == NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE) {
allow_bits(&state->groups->aces[i].perms, mask);
} else {
deny_bits(&state->groups->aces[i].perms, mask);
mask = state->groups->aces[i].perms.deny;
deny_bits(&state->owner, mask);
deny_bits(&state->group, mask);
deny_bits(&state->everyone, mask);
deny_bits_array(state->users, mask);
deny_bits_array(state->groups, mask);
}
break;
case ACL_OTHER:
if (ace->type == NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE) {
allow_bits(&state->owner, mask);
allow_bits(&state->group, mask);
allow_bits(&state->other, mask);
allow_bits(&state->everyone, mask);
allow_bits_array(state->users, mask);
allow_bits_array(state->groups, mask);
} else {
deny_bits(&state->owner, mask);
deny_bits(&state->group, mask);
deny_bits(&state->other, mask);
deny_bits(&state->everyone, mask);
deny_bits_array(state->users, mask);
deny_bits_array(state->groups, mask);
}
}
}
int nfs4_acl_nfsv4_to_posix(struct nfs4_acl *acl, struct posix_acl **pacl,
struct posix_acl **dpacl, unsigned int flags)
{
struct posix_acl_state effective_acl_state, default_acl_state;
struct nfs4_ace *ace;
int ret;
ret = init_state(&effective_acl_state, acl->naces);
if (ret)
return ret;
ret = init_state(&default_acl_state, acl->naces);
if (ret)
goto out_estate;
ret = -EINVAL;
for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) {
if (ace->type != NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE &&
ace->type != NFS4_ACE_ACCESS_DENIED_ACE_TYPE)
goto out_dstate;
if (ace->flag & ~NFS4_SUPPORTED_FLAGS)
goto out_dstate;
if ((ace->flag & NFS4_INHERITANCE_FLAGS) == 0) {
process_one_v4_ace(&effective_acl_state, ace);
continue;
}
if (!(flags & NFS4_ACL_DIR))
goto out_dstate;
/*
* Note that when only one of FILE_INHERIT or DIRECTORY_INHERIT
* is set, we're effectively turning on the other. That's OK,
* according to rfc 3530.
*/
process_one_v4_ace(&default_acl_state, ace);
if (!(ace->flag & NFS4_ACE_INHERIT_ONLY_ACE))
process_one_v4_ace(&effective_acl_state, ace);
}
*pacl = posix_state_to_acl(&effective_acl_state, flags);
if (IS_ERR(*pacl)) {
ret = PTR_ERR(*pacl);
*pacl = NULL;
goto out_dstate;
}
*dpacl = posix_state_to_acl(&default_acl_state,
flags | NFS4_ACL_TYPE_DEFAULT);
if (IS_ERR(*dpacl)) {
ret = PTR_ERR(*dpacl);
*dpacl = NULL;
posix_acl_release(*pacl);
*pacl = NULL;
goto out_dstate;
}
sort_pacl(*pacl);
sort_pacl(*dpacl);
ret = 0;
out_dstate:
free_state(&default_acl_state);
out_estate:
free_state(&effective_acl_state);
return ret;
}
static short
ace2type(struct nfs4_ace *ace)
{
switch (ace->whotype) {
case NFS4_ACL_WHO_NAMED:
return (ace->flag & NFS4_ACE_IDENTIFIER_GROUP ?
ACL_GROUP : ACL_USER);
case NFS4_ACL_WHO_OWNER:
return ACL_USER_OBJ;
case NFS4_ACL_WHO_GROUP:
return ACL_GROUP_OBJ;
case NFS4_ACL_WHO_EVERYONE:
return ACL_OTHER;
}
BUG();
return -1;
}
EXPORT_SYMBOL(nfs4_acl_posix_to_nfsv4);
EXPORT_SYMBOL(nfs4_acl_nfsv4_to_posix);
struct nfs4_acl *
nfs4_acl_new(int n)
{
struct nfs4_acl *acl;
acl = kmalloc(sizeof(*acl) + n*sizeof(struct nfs4_ace), GFP_KERNEL);
if (acl == NULL)
return NULL;
acl->naces = 0;
return acl;
}
static struct {
char *string;
int stringlen;
int type;
} s2t_map[] = {
{
.string = "OWNER@",
.stringlen = sizeof("OWNER@") - 1,
.type = NFS4_ACL_WHO_OWNER,
},
{
.string = "GROUP@",
.stringlen = sizeof("GROUP@") - 1,
.type = NFS4_ACL_WHO_GROUP,
},
{
.string = "EVERYONE@",
.stringlen = sizeof("EVERYONE@") - 1,
.type = NFS4_ACL_WHO_EVERYONE,
},
};
int
nfs4_acl_get_whotype(char *p, u32 len)
{
int i;
for (i = 0; i < ARRAY_SIZE(s2t_map); i++) {
if (s2t_map[i].stringlen == len &&
0 == memcmp(s2t_map[i].string, p, len))
return s2t_map[i].type;
}
return NFS4_ACL_WHO_NAMED;
}
int
nfs4_acl_write_who(int who, char *p)
{
int i;
for (i = 0; i < ARRAY_SIZE(s2t_map); i++) {
if (s2t_map[i].type == who) {
memcpy(p, s2t_map[i].string, s2t_map[i].stringlen);
return s2t_map[i].stringlen;
}
}
BUG();
return -1;
}
EXPORT_SYMBOL(nfs4_acl_new);
EXPORT_SYMBOL(nfs4_acl_get_whotype);
EXPORT_SYMBOL(nfs4_acl_write_who);
| gpl-2.0 |
EPDCenter/android_kernel_archos_97_titan | drivers/net/ehea/ehea_phyp.c | 3294 | 19311 | /*
* linux/drivers/net/ehea/ehea_phyp.c
*
* eHEA ethernet device driver for IBM eServer System p
*
* (C) Copyright IBM Corp. 2006
*
* Authors:
* Christoph Raisch <raisch@de.ibm.com>
* Jan-Bernd Themann <themann@de.ibm.com>
* Thomas Klein <tklein@de.ibm.com>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ehea_phyp.h"
static inline u16 get_order_of_qentries(u16 queue_entries)
{
u8 ld = 1; /* logarithmus dualis */
while (((1U << ld) - 1) < queue_entries)
ld++;
return ld - 1;
}
/* Defines for H_CALL H_ALLOC_RESOURCE */
#define H_ALL_RES_TYPE_QP 1
#define H_ALL_RES_TYPE_CQ 2
#define H_ALL_RES_TYPE_EQ 3
#define H_ALL_RES_TYPE_MR 5
#define H_ALL_RES_TYPE_MW 6
static long ehea_plpar_hcall_norets(unsigned long opcode,
unsigned long arg1,
unsigned long arg2,
unsigned long arg3,
unsigned long arg4,
unsigned long arg5,
unsigned long arg6,
unsigned long arg7)
{
long ret;
int i, sleep_msecs;
for (i = 0; i < 5; i++) {
ret = plpar_hcall_norets(opcode, arg1, arg2, arg3, arg4,
arg5, arg6, arg7);
if (H_IS_LONG_BUSY(ret)) {
sleep_msecs = get_longbusy_msecs(ret);
msleep_interruptible(sleep_msecs);
continue;
}
if (ret < H_SUCCESS)
pr_err("opcode=%lx ret=%lx"
" arg1=%lx arg2=%lx arg3=%lx arg4=%lx"
" arg5=%lx arg6=%lx arg7=%lx\n",
opcode, ret,
arg1, arg2, arg3, arg4, arg5, arg6, arg7);
return ret;
}
return H_BUSY;
}
static long ehea_plpar_hcall9(unsigned long opcode,
unsigned long *outs, /* array of 9 outputs */
unsigned long arg1,
unsigned long arg2,
unsigned long arg3,
unsigned long arg4,
unsigned long arg5,
unsigned long arg6,
unsigned long arg7,
unsigned long arg8,
unsigned long arg9)
{
long ret;
int i, sleep_msecs;
u8 cb_cat;
for (i = 0; i < 5; i++) {
ret = plpar_hcall9(opcode, outs,
arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9);
if (H_IS_LONG_BUSY(ret)) {
sleep_msecs = get_longbusy_msecs(ret);
msleep_interruptible(sleep_msecs);
continue;
}
cb_cat = EHEA_BMASK_GET(H_MEHEAPORT_CAT, arg2);
if ((ret < H_SUCCESS) && !(((ret == H_AUTHORITY)
&& (opcode == H_MODIFY_HEA_PORT))
&& (((cb_cat == H_PORT_CB4) && ((arg3 == H_PORT_CB4_JUMBO)
|| (arg3 == H_PORT_CB4_SPEED))) || ((cb_cat == H_PORT_CB7)
&& (arg3 == H_PORT_CB7_DUCQPN)))))
pr_err("opcode=%lx ret=%lx"
" arg1=%lx arg2=%lx arg3=%lx arg4=%lx"
" arg5=%lx arg6=%lx arg7=%lx arg8=%lx"
" arg9=%lx"
" out1=%lx out2=%lx out3=%lx out4=%lx"
" out5=%lx out6=%lx out7=%lx out8=%lx"
" out9=%lx\n",
opcode, ret,
arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9,
outs[0], outs[1], outs[2], outs[3], outs[4],
outs[5], outs[6], outs[7], outs[8]);
return ret;
}
return H_BUSY;
}
u64 ehea_h_query_ehea_qp(const u64 adapter_handle, const u8 qp_category,
const u64 qp_handle, const u64 sel_mask, void *cb_addr)
{
return ehea_plpar_hcall_norets(H_QUERY_HEA_QP,
adapter_handle, /* R4 */
qp_category, /* R5 */
qp_handle, /* R6 */
sel_mask, /* R7 */
virt_to_abs(cb_addr), /* R8 */
0, 0);
}
/* input param R5 */
#define H_ALL_RES_QP_EQPO EHEA_BMASK_IBM(9, 11)
#define H_ALL_RES_QP_QPP EHEA_BMASK_IBM(12, 12)
#define H_ALL_RES_QP_RQR EHEA_BMASK_IBM(13, 15)
#define H_ALL_RES_QP_EQEG EHEA_BMASK_IBM(16, 16)
#define H_ALL_RES_QP_LL_QP EHEA_BMASK_IBM(17, 17)
#define H_ALL_RES_QP_DMA128 EHEA_BMASK_IBM(19, 19)
#define H_ALL_RES_QP_HSM EHEA_BMASK_IBM(20, 21)
#define H_ALL_RES_QP_SIGT EHEA_BMASK_IBM(22, 23)
#define H_ALL_RES_QP_TENURE EHEA_BMASK_IBM(48, 55)
#define H_ALL_RES_QP_RES_TYP EHEA_BMASK_IBM(56, 63)
/* input param R9 */
#define H_ALL_RES_QP_TOKEN EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_PD EHEA_BMASK_IBM(32, 63)
/* input param R10 */
#define H_ALL_RES_QP_MAX_SWQE EHEA_BMASK_IBM(4, 7)
#define H_ALL_RES_QP_MAX_R1WQE EHEA_BMASK_IBM(12, 15)
#define H_ALL_RES_QP_MAX_R2WQE EHEA_BMASK_IBM(20, 23)
#define H_ALL_RES_QP_MAX_R3WQE EHEA_BMASK_IBM(28, 31)
/* Max Send Scatter Gather Elements */
#define H_ALL_RES_QP_MAX_SSGE EHEA_BMASK_IBM(37, 39)
#define H_ALL_RES_QP_MAX_R1SGE EHEA_BMASK_IBM(45, 47)
/* Max Receive SG Elements RQ1 */
#define H_ALL_RES_QP_MAX_R2SGE EHEA_BMASK_IBM(53, 55)
#define H_ALL_RES_QP_MAX_R3SGE EHEA_BMASK_IBM(61, 63)
/* input param R11 */
#define H_ALL_RES_QP_SWQE_IDL EHEA_BMASK_IBM(0, 7)
/* max swqe immediate data length */
#define H_ALL_RES_QP_PORT_NUM EHEA_BMASK_IBM(48, 63)
/* input param R12 */
#define H_ALL_RES_QP_TH_RQ2 EHEA_BMASK_IBM(0, 15)
/* Threshold RQ2 */
#define H_ALL_RES_QP_TH_RQ3 EHEA_BMASK_IBM(16, 31)
/* Threshold RQ3 */
/* output param R6 */
#define H_ALL_RES_QP_ACT_SWQE EHEA_BMASK_IBM(0, 15)
#define H_ALL_RES_QP_ACT_R1WQE EHEA_BMASK_IBM(16, 31)
#define H_ALL_RES_QP_ACT_R2WQE EHEA_BMASK_IBM(32, 47)
#define H_ALL_RES_QP_ACT_R3WQE EHEA_BMASK_IBM(48, 63)
/* output param, R7 */
#define H_ALL_RES_QP_ACT_SSGE EHEA_BMASK_IBM(0, 7)
#define H_ALL_RES_QP_ACT_R1SGE EHEA_BMASK_IBM(8, 15)
#define H_ALL_RES_QP_ACT_R2SGE EHEA_BMASK_IBM(16, 23)
#define H_ALL_RES_QP_ACT_R3SGE EHEA_BMASK_IBM(24, 31)
#define H_ALL_RES_QP_ACT_SWQE_IDL EHEA_BMASK_IBM(32, 39)
/* output param R8,R9 */
#define H_ALL_RES_QP_SIZE_SQ EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_SIZE_RQ1 EHEA_BMASK_IBM(32, 63)
#define H_ALL_RES_QP_SIZE_RQ2 EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_SIZE_RQ3 EHEA_BMASK_IBM(32, 63)
/* output param R11,R12 */
#define H_ALL_RES_QP_LIOBN_SQ EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_LIOBN_RQ1 EHEA_BMASK_IBM(32, 63)
#define H_ALL_RES_QP_LIOBN_RQ2 EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_LIOBN_RQ3 EHEA_BMASK_IBM(32, 63)
u64 ehea_h_alloc_resource_qp(const u64 adapter_handle,
struct ehea_qp_init_attr *init_attr, const u32 pd,
u64 *qp_handle, struct h_epas *h_epas)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
u64 allocate_controls =
EHEA_BMASK_SET(H_ALL_RES_QP_EQPO, init_attr->low_lat_rq1 ? 1 : 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_QPP, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_RQR, 6) /* rq1 & rq2 & rq3 */
| EHEA_BMASK_SET(H_ALL_RES_QP_EQEG, 0) /* EQE gen. disabled */
| EHEA_BMASK_SET(H_ALL_RES_QP_LL_QP, init_attr->low_lat_rq1)
| EHEA_BMASK_SET(H_ALL_RES_QP_DMA128, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_HSM, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_SIGT, init_attr->signalingtype)
| EHEA_BMASK_SET(H_ALL_RES_QP_RES_TYP, H_ALL_RES_TYPE_QP);
u64 r9_reg = EHEA_BMASK_SET(H_ALL_RES_QP_PD, pd)
| EHEA_BMASK_SET(H_ALL_RES_QP_TOKEN, init_attr->qp_token);
u64 max_r10_reg =
EHEA_BMASK_SET(H_ALL_RES_QP_MAX_SWQE,
get_order_of_qentries(init_attr->max_nr_send_wqes))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R1WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq1))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R2WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq2))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R3WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq3))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_SSGE, init_attr->wqe_size_enc_sq)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R1SGE,
init_attr->wqe_size_enc_rq1)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R2SGE,
init_attr->wqe_size_enc_rq2)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R3SGE,
init_attr->wqe_size_enc_rq3);
u64 r11_in =
EHEA_BMASK_SET(H_ALL_RES_QP_SWQE_IDL, init_attr->swqe_imm_data_len)
| EHEA_BMASK_SET(H_ALL_RES_QP_PORT_NUM, init_attr->port_nr);
u64 threshold =
EHEA_BMASK_SET(H_ALL_RES_QP_TH_RQ2, init_attr->rq2_threshold)
| EHEA_BMASK_SET(H_ALL_RES_QP_TH_RQ3, init_attr->rq3_threshold);
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
allocate_controls, /* R5 */
init_attr->send_cq_handle, /* R6 */
init_attr->recv_cq_handle, /* R7 */
init_attr->aff_eq_handle, /* R8 */
r9_reg, /* R9 */
max_r10_reg, /* R10 */
r11_in, /* R11 */
threshold); /* R12 */
*qp_handle = outs[0];
init_attr->qp_nr = (u32)outs[1];
init_attr->act_nr_send_wqes =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_SWQE, outs[2]);
init_attr->act_nr_rwqes_rq1 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R1WQE, outs[2]);
init_attr->act_nr_rwqes_rq2 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R2WQE, outs[2]);
init_attr->act_nr_rwqes_rq3 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R3WQE, outs[2]);
init_attr->act_wqe_size_enc_sq = init_attr->wqe_size_enc_sq;
init_attr->act_wqe_size_enc_rq1 = init_attr->wqe_size_enc_rq1;
init_attr->act_wqe_size_enc_rq2 = init_attr->wqe_size_enc_rq2;
init_attr->act_wqe_size_enc_rq3 = init_attr->wqe_size_enc_rq3;
init_attr->nr_sq_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_SQ, outs[4]);
init_attr->nr_rq1_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ1, outs[4]);
init_attr->nr_rq2_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ2, outs[5]);
init_attr->nr_rq3_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ3, outs[5]);
init_attr->liobn_sq =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_SQ, outs[7]);
init_attr->liobn_rq1 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ1, outs[7]);
init_attr->liobn_rq2 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ2, outs[8]);
init_attr->liobn_rq3 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ3, outs[8]);
if (!hret)
hcp_epas_ctor(h_epas, outs[6], outs[6]);
return hret;
}
u64 ehea_h_alloc_resource_cq(const u64 adapter_handle,
struct ehea_cq_attr *cq_attr,
u64 *cq_handle, struct h_epas *epas)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
H_ALL_RES_TYPE_CQ, /* R5 */
cq_attr->eq_handle, /* R6 */
cq_attr->cq_token, /* R7 */
cq_attr->max_nr_of_cqes, /* R8 */
0, 0, 0, 0); /* R9-R12 */
*cq_handle = outs[0];
cq_attr->act_nr_of_cqes = outs[3];
cq_attr->nr_pages = outs[4];
if (!hret)
hcp_epas_ctor(epas, outs[5], outs[6]);
return hret;
}
/* Defines for H_CALL H_ALLOC_RESOURCE */
#define H_ALL_RES_TYPE_QP 1
#define H_ALL_RES_TYPE_CQ 2
#define H_ALL_RES_TYPE_EQ 3
#define H_ALL_RES_TYPE_MR 5
#define H_ALL_RES_TYPE_MW 6
/* input param R5 */
#define H_ALL_RES_EQ_NEQ EHEA_BMASK_IBM(0, 0)
#define H_ALL_RES_EQ_NON_NEQ_ISN EHEA_BMASK_IBM(6, 7)
#define H_ALL_RES_EQ_INH_EQE_GEN EHEA_BMASK_IBM(16, 16)
#define H_ALL_RES_EQ_RES_TYPE EHEA_BMASK_IBM(56, 63)
/* input param R6 */
#define H_ALL_RES_EQ_MAX_EQE EHEA_BMASK_IBM(32, 63)
/* output param R6 */
#define H_ALL_RES_EQ_LIOBN EHEA_BMASK_IBM(32, 63)
/* output param R7 */
#define H_ALL_RES_EQ_ACT_EQE EHEA_BMASK_IBM(32, 63)
/* output param R8 */
#define H_ALL_RES_EQ_ACT_PS EHEA_BMASK_IBM(32, 63)
/* output param R9 */
#define H_ALL_RES_EQ_ACT_EQ_IST_C EHEA_BMASK_IBM(30, 31)
#define H_ALL_RES_EQ_ACT_EQ_IST_1 EHEA_BMASK_IBM(40, 63)
/* output param R10 */
#define H_ALL_RES_EQ_ACT_EQ_IST_2 EHEA_BMASK_IBM(40, 63)
/* output param R11 */
#define H_ALL_RES_EQ_ACT_EQ_IST_3 EHEA_BMASK_IBM(40, 63)
/* output param R12 */
#define H_ALL_RES_EQ_ACT_EQ_IST_4 EHEA_BMASK_IBM(40, 63)
u64 ehea_h_alloc_resource_eq(const u64 adapter_handle,
struct ehea_eq_attr *eq_attr, u64 *eq_handle)
{
u64 hret, allocate_controls;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
/* resource type */
allocate_controls =
EHEA_BMASK_SET(H_ALL_RES_EQ_RES_TYPE, H_ALL_RES_TYPE_EQ)
| EHEA_BMASK_SET(H_ALL_RES_EQ_NEQ, eq_attr->type ? 1 : 0)
| EHEA_BMASK_SET(H_ALL_RES_EQ_INH_EQE_GEN, !eq_attr->eqe_gen)
| EHEA_BMASK_SET(H_ALL_RES_EQ_NON_NEQ_ISN, 1);
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
allocate_controls, /* R5 */
eq_attr->max_nr_of_eqes, /* R6 */
0, 0, 0, 0, 0, 0); /* R7-R10 */
*eq_handle = outs[0];
eq_attr->act_nr_of_eqes = outs[3];
eq_attr->nr_pages = outs[4];
eq_attr->ist1 = outs[5];
eq_attr->ist2 = outs[6];
eq_attr->ist3 = outs[7];
eq_attr->ist4 = outs[8];
return hret;
}
u64 ehea_h_modify_ehea_qp(const u64 adapter_handle, const u8 cat,
const u64 qp_handle, const u64 sel_mask,
void *cb_addr, u64 *inv_attr_id, u64 *proc_mask,
u16 *out_swr, u16 *out_rwr)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_MODIFY_HEA_QP,
outs,
adapter_handle, /* R4 */
(u64) cat, /* R5 */
qp_handle, /* R6 */
sel_mask, /* R7 */
virt_to_abs(cb_addr), /* R8 */
0, 0, 0, 0); /* R9-R12 */
*inv_attr_id = outs[0];
*out_swr = outs[3];
*out_rwr = outs[4];
*proc_mask = outs[5];
return hret;
}
u64 ehea_h_register_rpage(const u64 adapter_handle, const u8 pagesize,
const u8 queue_type, const u64 resource_handle,
const u64 log_pageaddr, u64 count)
{
u64 reg_control;
reg_control = EHEA_BMASK_SET(H_REG_RPAGE_PAGE_SIZE, pagesize)
| EHEA_BMASK_SET(H_REG_RPAGE_QT, queue_type);
return ehea_plpar_hcall_norets(H_REGISTER_HEA_RPAGES,
adapter_handle, /* R4 */
reg_control, /* R5 */
resource_handle, /* R6 */
log_pageaddr, /* R7 */
count, /* R8 */
0, 0); /* R9-R10 */
}
u64 ehea_h_register_smr(const u64 adapter_handle, const u64 orig_mr_handle,
const u64 vaddr_in, const u32 access_ctrl, const u32 pd,
struct ehea_mr *mr)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_REGISTER_SMR,
outs,
adapter_handle , /* R4 */
orig_mr_handle, /* R5 */
vaddr_in, /* R6 */
(((u64)access_ctrl) << 32ULL), /* R7 */
pd, /* R8 */
0, 0, 0, 0); /* R9-R12 */
mr->handle = outs[0];
mr->lkey = (u32)outs[2];
return hret;
}
u64 ehea_h_disable_and_get_hea(const u64 adapter_handle, const u64 qp_handle)
{
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
return ehea_plpar_hcall9(H_DISABLE_AND_GET_HEA,
outs,
adapter_handle, /* R4 */
H_DISABLE_GET_EHEA_WQE_P, /* R5 */
qp_handle, /* R6 */
0, 0, 0, 0, 0, 0); /* R7-R12 */
}
u64 ehea_h_free_resource(const u64 adapter_handle, const u64 res_handle,
u64 force_bit)
{
return ehea_plpar_hcall_norets(H_FREE_RESOURCE,
adapter_handle, /* R4 */
res_handle, /* R5 */
force_bit,
0, 0, 0, 0); /* R7-R10 */
}
u64 ehea_h_alloc_resource_mr(const u64 adapter_handle, const u64 vaddr,
const u64 length, const u32 access_ctrl,
const u32 pd, u64 *mr_handle, u32 *lkey)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
5, /* R5 */
vaddr, /* R6 */
length, /* R7 */
(((u64) access_ctrl) << 32ULL), /* R8 */
pd, /* R9 */
0, 0, 0); /* R10-R12 */
*mr_handle = outs[0];
*lkey = (u32)outs[2];
return hret;
}
u64 ehea_h_register_rpage_mr(const u64 adapter_handle, const u64 mr_handle,
const u8 pagesize, const u8 queue_type,
const u64 log_pageaddr, const u64 count)
{
if ((count > 1) && (log_pageaddr & ~PAGE_MASK)) {
pr_err("not on pageboundary\n");
return H_PARAMETER;
}
return ehea_h_register_rpage(adapter_handle, pagesize,
queue_type, mr_handle,
log_pageaddr, count);
}
u64 ehea_h_query_ehea(const u64 adapter_handle, void *cb_addr)
{
u64 hret, cb_logaddr;
cb_logaddr = virt_to_abs(cb_addr);
hret = ehea_plpar_hcall_norets(H_QUERY_HEA,
adapter_handle, /* R4 */
cb_logaddr, /* R5 */
0, 0, 0, 0, 0); /* R6-R10 */
#ifdef DEBUG
ehea_dump(cb_addr, sizeof(struct hcp_query_ehea), "hcp_query_ehea");
#endif
return hret;
}
u64 ehea_h_query_ehea_port(const u64 adapter_handle, const u16 port_num,
const u8 cb_cat, const u64 select_mask,
void *cb_addr)
{
u64 port_info;
u64 cb_logaddr = virt_to_abs(cb_addr);
u64 arr_index = 0;
port_info = EHEA_BMASK_SET(H_MEHEAPORT_CAT, cb_cat)
| EHEA_BMASK_SET(H_MEHEAPORT_PN, port_num);
return ehea_plpar_hcall_norets(H_QUERY_HEA_PORT,
adapter_handle, /* R4 */
port_info, /* R5 */
select_mask, /* R6 */
arr_index, /* R7 */
cb_logaddr, /* R8 */
0, 0); /* R9-R10 */
}
u64 ehea_h_modify_ehea_port(const u64 adapter_handle, const u16 port_num,
const u8 cb_cat, const u64 select_mask,
void *cb_addr)
{
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
u64 port_info;
u64 arr_index = 0;
u64 cb_logaddr = virt_to_abs(cb_addr);
port_info = EHEA_BMASK_SET(H_MEHEAPORT_CAT, cb_cat)
| EHEA_BMASK_SET(H_MEHEAPORT_PN, port_num);
#ifdef DEBUG
ehea_dump(cb_addr, sizeof(struct hcp_ehea_port_cb0), "Before HCALL");
#endif
return ehea_plpar_hcall9(H_MODIFY_HEA_PORT,
outs,
adapter_handle, /* R4 */
port_info, /* R5 */
select_mask, /* R6 */
arr_index, /* R7 */
cb_logaddr, /* R8 */
0, 0, 0, 0); /* R9-R12 */
}
u64 ehea_h_reg_dereg_bcmc(const u64 adapter_handle, const u16 port_num,
const u8 reg_type, const u64 mc_mac_addr,
const u16 vlan_id, const u32 hcall_id)
{
u64 r5_port_num, r6_reg_type, r7_mc_mac_addr, r8_vlan_id;
u64 mac_addr = mc_mac_addr >> 16;
r5_port_num = EHEA_BMASK_SET(H_REGBCMC_PN, port_num);
r6_reg_type = EHEA_BMASK_SET(H_REGBCMC_REGTYPE, reg_type);
r7_mc_mac_addr = EHEA_BMASK_SET(H_REGBCMC_MACADDR, mac_addr);
r8_vlan_id = EHEA_BMASK_SET(H_REGBCMC_VLANID, vlan_id);
return ehea_plpar_hcall_norets(hcall_id,
adapter_handle, /* R4 */
r5_port_num, /* R5 */
r6_reg_type, /* R6 */
r7_mc_mac_addr, /* R7 */
r8_vlan_id, /* R8 */
0, 0); /* R9-R12 */
}
u64 ehea_h_reset_events(const u64 adapter_handle, const u64 neq_handle,
const u64 event_mask)
{
return ehea_plpar_hcall_norets(H_RESET_EVENTS,
adapter_handle, /* R4 */
neq_handle, /* R5 */
event_mask, /* R6 */
0, 0, 0, 0); /* R7-R12 */
}
u64 ehea_h_error_data(const u64 adapter_handle, const u64 ressource_handle,
void *rblock)
{
return ehea_plpar_hcall_norets(H_ERROR_DATA,
adapter_handle, /* R4 */
ressource_handle, /* R5 */
virt_to_abs(rblock), /* R6 */
0, 0, 0, 0); /* R7-R12 */
}
| gpl-2.0 |
OptiPop/kernel_asus_grouper | drivers/input/touchscreen/stmpe-ts.c | 3294 | 9900 | /* STMicroelectronics STMPE811 Touchscreen Driver
*
* (C) 2010 Luotao Fu <l.fu@pengutronix.de>
* 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.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/workqueue.h>
#include <linux/mfd/stmpe.h>
/* Register layouts and functionalities are identical on all stmpexxx variants
* with touchscreen controller
*/
#define STMPE_REG_INT_STA 0x0B
#define STMPE_REG_ADC_CTRL1 0x20
#define STMPE_REG_ADC_CTRL2 0x21
#define STMPE_REG_TSC_CTRL 0x40
#define STMPE_REG_TSC_CFG 0x41
#define STMPE_REG_FIFO_TH 0x4A
#define STMPE_REG_FIFO_STA 0x4B
#define STMPE_REG_FIFO_SIZE 0x4C
#define STMPE_REG_TSC_DATA_XYZ 0x52
#define STMPE_REG_TSC_FRACTION_Z 0x56
#define STMPE_REG_TSC_I_DRIVE 0x58
#define OP_MOD_XYZ 0
#define STMPE_TSC_CTRL_TSC_EN (1<<0)
#define STMPE_FIFO_STA_RESET (1<<0)
#define STMPE_IRQ_TOUCH_DET 0
#define SAMPLE_TIME(x) ((x & 0xf) << 4)
#define MOD_12B(x) ((x & 0x1) << 3)
#define REF_SEL(x) ((x & 0x1) << 1)
#define ADC_FREQ(x) (x & 0x3)
#define AVE_CTRL(x) ((x & 0x3) << 6)
#define DET_DELAY(x) ((x & 0x7) << 3)
#define SETTLING(x) (x & 0x7)
#define FRACTION_Z(x) (x & 0x7)
#define I_DRIVE(x) (x & 0x1)
#define OP_MODE(x) ((x & 0x7) << 1)
#define STMPE_TS_NAME "stmpe-ts"
#define XY_MASK 0xfff
struct stmpe_touch {
struct stmpe *stmpe;
struct input_dev *idev;
struct delayed_work work;
struct device *dev;
u8 sample_time;
u8 mod_12b;
u8 ref_sel;
u8 adc_freq;
u8 ave_ctrl;
u8 touch_det_delay;
u8 settling;
u8 fraction_z;
u8 i_drive;
};
static int __stmpe_reset_fifo(struct stmpe *stmpe)
{
int ret;
ret = stmpe_set_bits(stmpe, STMPE_REG_FIFO_STA,
STMPE_FIFO_STA_RESET, STMPE_FIFO_STA_RESET);
if (ret)
return ret;
return stmpe_set_bits(stmpe, STMPE_REG_FIFO_STA,
STMPE_FIFO_STA_RESET, 0);
}
static void stmpe_work(struct work_struct *work)
{
int int_sta;
u32 timeout = 40;
struct stmpe_touch *ts =
container_of(work, struct stmpe_touch, work.work);
int_sta = stmpe_reg_read(ts->stmpe, STMPE_REG_INT_STA);
/*
* touch_det sometimes get desasserted or just get stuck. This appears
* to be a silicon bug, We still have to clearify this with the
* manufacture. As a workaround We release the key anyway if the
* touch_det keeps coming in after 4ms, while the FIFO contains no value
* during the whole time.
*/
while ((int_sta & (1 << STMPE_IRQ_TOUCH_DET)) && (timeout > 0)) {
timeout--;
int_sta = stmpe_reg_read(ts->stmpe, STMPE_REG_INT_STA);
udelay(100);
}
/* reset the FIFO before we report release event */
__stmpe_reset_fifo(ts->stmpe);
input_report_abs(ts->idev, ABS_PRESSURE, 0);
input_sync(ts->idev);
}
static irqreturn_t stmpe_ts_handler(int irq, void *data)
{
u8 data_set[4];
int x, y, z;
struct stmpe_touch *ts = data;
/*
* Cancel scheduled polling for release if we have new value
* available. Wait if the polling is already running.
*/
cancel_delayed_work_sync(&ts->work);
/*
* The FIFO sometimes just crashes and stops generating interrupts. This
* appears to be a silicon bug. We still have to clearify this with
* the manufacture. As a workaround we disable the TSC while we are
* collecting data and flush the FIFO after reading
*/
stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL,
STMPE_TSC_CTRL_TSC_EN, 0);
stmpe_block_read(ts->stmpe, STMPE_REG_TSC_DATA_XYZ, 4, data_set);
x = (data_set[0] << 4) | (data_set[1] >> 4);
y = ((data_set[1] & 0xf) << 8) | data_set[2];
z = data_set[3];
input_report_abs(ts->idev, ABS_X, x);
input_report_abs(ts->idev, ABS_Y, y);
input_report_abs(ts->idev, ABS_PRESSURE, z);
input_sync(ts->idev);
/* flush the FIFO after we have read out our values. */
__stmpe_reset_fifo(ts->stmpe);
/* reenable the tsc */
stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL,
STMPE_TSC_CTRL_TSC_EN, STMPE_TSC_CTRL_TSC_EN);
/* start polling for touch_det to detect release */
schedule_delayed_work(&ts->work, HZ / 50);
return IRQ_HANDLED;
}
static int __devinit stmpe_init_hw(struct stmpe_touch *ts)
{
int ret;
u8 adc_ctrl1, adc_ctrl1_mask, tsc_cfg, tsc_cfg_mask;
struct stmpe *stmpe = ts->stmpe;
struct device *dev = ts->dev;
ret = stmpe_enable(stmpe, STMPE_BLOCK_TOUCHSCREEN | STMPE_BLOCK_ADC);
if (ret) {
dev_err(dev, "Could not enable clock for ADC and TS\n");
return ret;
}
adc_ctrl1 = SAMPLE_TIME(ts->sample_time) | MOD_12B(ts->mod_12b) |
REF_SEL(ts->ref_sel);
adc_ctrl1_mask = SAMPLE_TIME(0xff) | MOD_12B(0xff) | REF_SEL(0xff);
ret = stmpe_set_bits(stmpe, STMPE_REG_ADC_CTRL1,
adc_ctrl1_mask, adc_ctrl1);
if (ret) {
dev_err(dev, "Could not setup ADC\n");
return ret;
}
ret = stmpe_set_bits(stmpe, STMPE_REG_ADC_CTRL2,
ADC_FREQ(0xff), ADC_FREQ(ts->adc_freq));
if (ret) {
dev_err(dev, "Could not setup ADC\n");
return ret;
}
tsc_cfg = AVE_CTRL(ts->ave_ctrl) | DET_DELAY(ts->touch_det_delay) |
SETTLING(ts->settling);
tsc_cfg_mask = AVE_CTRL(0xff) | DET_DELAY(0xff) | SETTLING(0xff);
ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_CFG, tsc_cfg_mask, tsc_cfg);
if (ret) {
dev_err(dev, "Could not config touch\n");
return ret;
}
ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_FRACTION_Z,
FRACTION_Z(0xff), FRACTION_Z(ts->fraction_z));
if (ret) {
dev_err(dev, "Could not config touch\n");
return ret;
}
ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_I_DRIVE,
I_DRIVE(0xff), I_DRIVE(ts->i_drive));
if (ret) {
dev_err(dev, "Could not config touch\n");
return ret;
}
/* set FIFO to 1 for single point reading */
ret = stmpe_reg_write(stmpe, STMPE_REG_FIFO_TH, 1);
if (ret) {
dev_err(dev, "Could not set FIFO\n");
return ret;
}
ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_CTRL,
OP_MODE(0xff), OP_MODE(OP_MOD_XYZ));
if (ret) {
dev_err(dev, "Could not set mode\n");
return ret;
}
return 0;
}
static int stmpe_ts_open(struct input_dev *dev)
{
struct stmpe_touch *ts = input_get_drvdata(dev);
int ret = 0;
ret = __stmpe_reset_fifo(ts->stmpe);
if (ret)
return ret;
return stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL,
STMPE_TSC_CTRL_TSC_EN, STMPE_TSC_CTRL_TSC_EN);
}
static void stmpe_ts_close(struct input_dev *dev)
{
struct stmpe_touch *ts = input_get_drvdata(dev);
cancel_delayed_work_sync(&ts->work);
stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL,
STMPE_TSC_CTRL_TSC_EN, 0);
}
static int __devinit stmpe_input_probe(struct platform_device *pdev)
{
struct stmpe *stmpe = dev_get_drvdata(pdev->dev.parent);
struct stmpe_platform_data *pdata = stmpe->pdata;
struct stmpe_touch *ts;
struct input_dev *idev;
struct stmpe_ts_platform_data *ts_pdata = NULL;
int ret;
int ts_irq;
ts_irq = platform_get_irq_byname(pdev, "FIFO_TH");
if (ts_irq < 0)
return ts_irq;
ts = kzalloc(sizeof(*ts), GFP_KERNEL);
if (!ts) {
ret = -ENOMEM;
goto err_out;
}
idev = input_allocate_device();
if (!idev) {
ret = -ENOMEM;
goto err_free_ts;
}
platform_set_drvdata(pdev, ts);
ts->stmpe = stmpe;
ts->idev = idev;
ts->dev = &pdev->dev;
if (pdata)
ts_pdata = pdata->ts;
if (ts_pdata) {
ts->sample_time = ts_pdata->sample_time;
ts->mod_12b = ts_pdata->mod_12b;
ts->ref_sel = ts_pdata->ref_sel;
ts->adc_freq = ts_pdata->adc_freq;
ts->ave_ctrl = ts_pdata->ave_ctrl;
ts->touch_det_delay = ts_pdata->touch_det_delay;
ts->settling = ts_pdata->settling;
ts->fraction_z = ts_pdata->fraction_z;
ts->i_drive = ts_pdata->i_drive;
}
INIT_DELAYED_WORK(&ts->work, stmpe_work);
ret = request_threaded_irq(ts_irq, NULL, stmpe_ts_handler,
IRQF_ONESHOT, STMPE_TS_NAME, ts);
if (ret) {
dev_err(&pdev->dev, "Failed to request IRQ %d\n", ts_irq);
goto err_free_input;
}
ret = stmpe_init_hw(ts);
if (ret)
goto err_free_irq;
idev->name = STMPE_TS_NAME;
idev->id.bustype = BUS_I2C;
idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
idev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
idev->open = stmpe_ts_open;
idev->close = stmpe_ts_close;
input_set_drvdata(idev, ts);
input_set_abs_params(idev, ABS_X, 0, XY_MASK, 0, 0);
input_set_abs_params(idev, ABS_Y, 0, XY_MASK, 0, 0);
input_set_abs_params(idev, ABS_PRESSURE, 0x0, 0xff, 0, 0);
ret = input_register_device(idev);
if (ret) {
dev_err(&pdev->dev, "Could not register input device\n");
goto err_free_irq;
}
return ret;
err_free_irq:
free_irq(ts_irq, ts);
err_free_input:
input_free_device(idev);
platform_set_drvdata(pdev, NULL);
err_free_ts:
kfree(ts);
err_out:
return ret;
}
static int __devexit stmpe_ts_remove(struct platform_device *pdev)
{
struct stmpe_touch *ts = platform_get_drvdata(pdev);
unsigned int ts_irq = platform_get_irq_byname(pdev, "FIFO_TH");
stmpe_disable(ts->stmpe, STMPE_BLOCK_TOUCHSCREEN);
free_irq(ts_irq, ts);
platform_set_drvdata(pdev, NULL);
input_unregister_device(ts->idev);
kfree(ts);
return 0;
}
static struct platform_driver stmpe_ts_driver = {
.driver = {
.name = STMPE_TS_NAME,
.owner = THIS_MODULE,
},
.probe = stmpe_input_probe,
.remove = __devexit_p(stmpe_ts_remove),
};
static int __init stmpe_ts_init(void)
{
return platform_driver_register(&stmpe_ts_driver);
}
module_init(stmpe_ts_init);
static void __exit stmpe_ts_exit(void)
{
platform_driver_unregister(&stmpe_ts_driver);
}
module_exit(stmpe_ts_exit);
MODULE_AUTHOR("Luotao Fu <l.fu@pengutronix.de>");
MODULE_DESCRIPTION("STMPEXXX touchscreen driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" STMPE_TS_NAME);
| gpl-2.0 |
madprogrammer/linux-e8-rt | drivers/isdn/mISDN/dsp_audio.c | 4574 | 11056 | /*
* Audio support data for mISDN_dsp.
*
* Copyright 2002/2003 by Andreas Eversberg (jolly@eversberg.eu)
* Rewritten by Peter
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/delay.h>
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include "core.h"
#include "dsp.h"
/* ulaw[unsigned char] -> signed 16-bit */
s32 dsp_audio_ulaw_to_s32[256];
/* alaw[unsigned char] -> signed 16-bit */
s32 dsp_audio_alaw_to_s32[256];
s32 *dsp_audio_law_to_s32;
EXPORT_SYMBOL(dsp_audio_law_to_s32);
/* signed 16-bit -> law */
u8 dsp_audio_s16_to_law[65536];
EXPORT_SYMBOL(dsp_audio_s16_to_law);
/* alaw -> ulaw */
u8 dsp_audio_alaw_to_ulaw[256];
/* ulaw -> alaw */
static u8 dsp_audio_ulaw_to_alaw[256];
u8 dsp_silence;
/*****************************************************
* generate table for conversion of s16 to alaw/ulaw *
*****************************************************/
#define AMI_MASK 0x55
static inline unsigned char linear2alaw(short int linear)
{
int mask;
int seg;
int pcm_val;
static int seg_end[8] = {
0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF
};
pcm_val = linear;
if (pcm_val >= 0) {
/* Sign (7th) bit = 1 */
mask = AMI_MASK | 0x80;
} else {
/* Sign bit = 0 */
mask = AMI_MASK;
pcm_val = -pcm_val;
}
/* Convert the scaled magnitude to segment number. */
for (seg = 0; seg < 8; seg++) {
if (pcm_val <= seg_end[seg])
break;
}
/* Combine the sign, segment, and quantization bits. */
return ((seg << 4) |
((pcm_val >> ((seg) ? (seg + 3) : 4)) & 0x0F)) ^ mask;
}
static inline short int alaw2linear(unsigned char alaw)
{
int i;
int seg;
alaw ^= AMI_MASK;
i = ((alaw & 0x0F) << 4) + 8 /* rounding error */;
seg = (((int) alaw & 0x70) >> 4);
if (seg)
i = (i + 0x100) << (seg - 1);
return (short int) ((alaw & 0x80) ? i : -i);
}
static inline short int ulaw2linear(unsigned char ulaw)
{
short mu, e, f, y;
static short etab[] = {0, 132, 396, 924, 1980, 4092, 8316, 16764};
mu = 255 - ulaw;
e = (mu & 0x70) / 16;
f = mu & 0x0f;
y = f * (1 << (e + 3));
y += etab[e];
if (mu & 0x80)
y = -y;
return y;
}
#define BIAS 0x84 /*!< define the add-in bias for 16 bit samples */
static unsigned char linear2ulaw(short sample)
{
static int exp_lut[256] = {
0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
int sign, exponent, mantissa;
unsigned char ulawbyte;
/* Get the sample into sign-magnitude. */
sign = (sample >> 8) & 0x80; /* set aside the sign */
if (sign != 0)
sample = -sample; /* get magnitude */
/* Convert from 16 bit linear to ulaw. */
sample = sample + BIAS;
exponent = exp_lut[(sample >> 7) & 0xFF];
mantissa = (sample >> (exponent + 3)) & 0x0F;
ulawbyte = ~(sign | (exponent << 4) | mantissa);
return ulawbyte;
}
static int reverse_bits(int i)
{
int z, j;
z = 0;
for (j = 0; j < 8; j++) {
if ((i & (1 << j)) != 0)
z |= 1 << (7 - j);
}
return z;
}
void dsp_audio_generate_law_tables(void)
{
int i;
for (i = 0; i < 256; i++)
dsp_audio_alaw_to_s32[i] = alaw2linear(reverse_bits(i));
for (i = 0; i < 256; i++)
dsp_audio_ulaw_to_s32[i] = ulaw2linear(reverse_bits(i));
for (i = 0; i < 256; i++) {
dsp_audio_alaw_to_ulaw[i] =
linear2ulaw(dsp_audio_alaw_to_s32[i]);
dsp_audio_ulaw_to_alaw[i] =
linear2alaw(dsp_audio_ulaw_to_s32[i]);
}
}
void
dsp_audio_generate_s2law_table(void)
{
int i;
if (dsp_options & DSP_OPT_ULAW) {
/* generating ulaw-table */
for (i = -32768; i < 32768; i++) {
dsp_audio_s16_to_law[i & 0xffff] =
reverse_bits(linear2ulaw(i));
}
} else {
/* generating alaw-table */
for (i = -32768; i < 32768; i++) {
dsp_audio_s16_to_law[i & 0xffff] =
reverse_bits(linear2alaw(i));
}
}
}
/*
* the seven bit sample is the number of every second alaw-sample ordered by
* aplitude. 0x00 is negative, 0x7f is positive amplitude.
*/
u8 dsp_audio_seven2law[128];
u8 dsp_audio_law2seven[256];
/********************************************************************
* generate table for conversion law from/to 7-bit alaw-like sample *
********************************************************************/
void
dsp_audio_generate_seven(void)
{
int i, j, k;
u8 spl;
u8 sorted_alaw[256];
/* generate alaw table, sorted by the linear value */
for (i = 0; i < 256; i++) {
j = 0;
for (k = 0; k < 256; k++) {
if (dsp_audio_alaw_to_s32[k]
< dsp_audio_alaw_to_s32[i])
j++;
}
sorted_alaw[j] = i;
}
/* generate tabels */
for (i = 0; i < 256; i++) {
/* spl is the source: the law-sample (converted to alaw) */
spl = i;
if (dsp_options & DSP_OPT_ULAW)
spl = dsp_audio_ulaw_to_alaw[i];
/* find the 7-bit-sample */
for (j = 0; j < 256; j++) {
if (sorted_alaw[j] == spl)
break;
}
/* write 7-bit audio value */
dsp_audio_law2seven[i] = j >> 1;
}
for (i = 0; i < 128; i++) {
spl = sorted_alaw[i << 1];
if (dsp_options & DSP_OPT_ULAW)
spl = dsp_audio_alaw_to_ulaw[spl];
dsp_audio_seven2law[i] = spl;
}
}
/* mix 2*law -> law */
u8 dsp_audio_mix_law[65536];
/******************************************************
* generate mix table to mix two law samples into one *
******************************************************/
void
dsp_audio_generate_mix_table(void)
{
int i, j;
s32 sample;
i = 0;
while (i < 256) {
j = 0;
while (j < 256) {
sample = dsp_audio_law_to_s32[i];
sample += dsp_audio_law_to_s32[j];
if (sample > 32767)
sample = 32767;
if (sample < -32768)
sample = -32768;
dsp_audio_mix_law[(i<<8)|j] =
dsp_audio_s16_to_law[sample & 0xffff];
j++;
}
i++;
}
}
/*************************************
* generate different volume changes *
*************************************/
static u8 dsp_audio_reduce8[256];
static u8 dsp_audio_reduce7[256];
static u8 dsp_audio_reduce6[256];
static u8 dsp_audio_reduce5[256];
static u8 dsp_audio_reduce4[256];
static u8 dsp_audio_reduce3[256];
static u8 dsp_audio_reduce2[256];
static u8 dsp_audio_reduce1[256];
static u8 dsp_audio_increase1[256];
static u8 dsp_audio_increase2[256];
static u8 dsp_audio_increase3[256];
static u8 dsp_audio_increase4[256];
static u8 dsp_audio_increase5[256];
static u8 dsp_audio_increase6[256];
static u8 dsp_audio_increase7[256];
static u8 dsp_audio_increase8[256];
static u8 *dsp_audio_volume_change[16] = {
dsp_audio_reduce8,
dsp_audio_reduce7,
dsp_audio_reduce6,
dsp_audio_reduce5,
dsp_audio_reduce4,
dsp_audio_reduce3,
dsp_audio_reduce2,
dsp_audio_reduce1,
dsp_audio_increase1,
dsp_audio_increase2,
dsp_audio_increase3,
dsp_audio_increase4,
dsp_audio_increase5,
dsp_audio_increase6,
dsp_audio_increase7,
dsp_audio_increase8,
};
void
dsp_audio_generate_volume_changes(void)
{
register s32 sample;
int i;
int num[] = { 110, 125, 150, 175, 200, 300, 400, 500 };
int denum[] = { 100, 100, 100, 100, 100, 100, 100, 100 };
i = 0;
while (i < 256) {
dsp_audio_reduce8[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[7] / num[7]) & 0xffff];
dsp_audio_reduce7[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[6] / num[6]) & 0xffff];
dsp_audio_reduce6[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[5] / num[5]) & 0xffff];
dsp_audio_reduce5[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[4] / num[4]) & 0xffff];
dsp_audio_reduce4[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[3] / num[3]) & 0xffff];
dsp_audio_reduce3[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[2] / num[2]) & 0xffff];
dsp_audio_reduce2[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[1] / num[1]) & 0xffff];
dsp_audio_reduce1[i] = dsp_audio_s16_to_law[
(dsp_audio_law_to_s32[i] * denum[0] / num[0]) & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[0] / denum[0];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase1[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[1] / denum[1];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase2[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[2] / denum[2];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase3[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[3] / denum[3];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase4[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[4] / denum[4];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase5[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[5] / denum[5];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase6[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[6] / denum[6];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase7[i] = dsp_audio_s16_to_law[sample & 0xffff];
sample = dsp_audio_law_to_s32[i] * num[7] / denum[7];
if (sample < -32768)
sample = -32768;
else if (sample > 32767)
sample = 32767;
dsp_audio_increase8[i] = dsp_audio_s16_to_law[sample & 0xffff];
i++;
}
}
/**************************************
* change the volume of the given skb *
**************************************/
/* this is a helper function for changing volume of skb. the range may be
* -8 to 8, which is a shift to the power of 2. 0 == no volume, 3 == volume*8
*/
void
dsp_change_volume(struct sk_buff *skb, int volume)
{
u8 *volume_change;
int i, ii;
u8 *p;
int shift;
if (volume == 0)
return;
/* get correct conversion table */
if (volume < 0) {
shift = volume + 8;
if (shift < 0)
shift = 0;
} else {
shift = volume + 7;
if (shift > 15)
shift = 15;
}
volume_change = dsp_audio_volume_change[shift];
i = 0;
ii = skb->len;
p = skb->data;
/* change volume */
while (i < ii) {
*p = volume_change[*p];
p++;
i++;
}
}
| gpl-2.0 |
NoelMacwan/android_kernel_sony_u8500 | arch/arm/mach-imx/mach-mx51_3ds.c | 4830 | 4376 | /*
* Copyright 2008-2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2010 Jason Wang <jason77.wang@gmail.com>
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <mach/hardware.h>
#include <mach/common.h>
#include <mach/iomux-mx51.h>
#include <mach/3ds_debugboard.h>
#include "devices-imx51.h"
#define EXPIO_PARENT_INT gpio_to_irq(IMX_GPIO_NR(1, 6))
#define MX51_3DS_ECSPI2_CS (GPIO_PORTC + 28)
static iomux_v3_cfg_t mx51_3ds_pads[] = {
/* UART1 */
MX51_PAD_UART1_RXD__UART1_RXD,
MX51_PAD_UART1_TXD__UART1_TXD,
MX51_PAD_UART1_RTS__UART1_RTS,
MX51_PAD_UART1_CTS__UART1_CTS,
/* UART2 */
MX51_PAD_UART2_RXD__UART2_RXD,
MX51_PAD_UART2_TXD__UART2_TXD,
MX51_PAD_EIM_D25__UART2_CTS,
MX51_PAD_EIM_D26__UART2_RTS,
/* UART3 */
MX51_PAD_UART3_RXD__UART3_RXD,
MX51_PAD_UART3_TXD__UART3_TXD,
MX51_PAD_EIM_D24__UART3_CTS,
MX51_PAD_EIM_D27__UART3_RTS,
/* CPLD PARENT IRQ PIN */
MX51_PAD_GPIO1_6__GPIO1_6,
/* KPP */
MX51_PAD_KEY_ROW0__KEY_ROW0,
MX51_PAD_KEY_ROW1__KEY_ROW1,
MX51_PAD_KEY_ROW2__KEY_ROW2,
MX51_PAD_KEY_ROW3__KEY_ROW3,
MX51_PAD_KEY_COL0__KEY_COL0,
MX51_PAD_KEY_COL1__KEY_COL1,
MX51_PAD_KEY_COL2__KEY_COL2,
MX51_PAD_KEY_COL3__KEY_COL3,
MX51_PAD_KEY_COL4__KEY_COL4,
MX51_PAD_KEY_COL5__KEY_COL5,
/* eCSPI2 */
MX51_PAD_NANDF_RB2__ECSPI2_SCLK,
MX51_PAD_NANDF_RB3__ECSPI2_MISO,
MX51_PAD_NANDF_D15__ECSPI2_MOSI,
MX51_PAD_NANDF_D12__GPIO3_28,
};
/* Serial ports */
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static int mx51_3ds_board_keymap[] = {
KEY(0, 0, KEY_1),
KEY(0, 1, KEY_2),
KEY(0, 2, KEY_3),
KEY(0, 3, KEY_F1),
KEY(0, 4, KEY_UP),
KEY(0, 5, KEY_F2),
KEY(1, 0, KEY_4),
KEY(1, 1, KEY_5),
KEY(1, 2, KEY_6),
KEY(1, 3, KEY_LEFT),
KEY(1, 4, KEY_SELECT),
KEY(1, 5, KEY_RIGHT),
KEY(2, 0, KEY_7),
KEY(2, 1, KEY_8),
KEY(2, 2, KEY_9),
KEY(2, 3, KEY_F3),
KEY(2, 4, KEY_DOWN),
KEY(2, 5, KEY_F4),
KEY(3, 0, KEY_0),
KEY(3, 1, KEY_OK),
KEY(3, 2, KEY_ESC),
KEY(3, 3, KEY_ENTER),
KEY(3, 4, KEY_MENU),
KEY(3, 5, KEY_BACK)
};
static const struct matrix_keymap_data mx51_3ds_map_data __initconst = {
.keymap = mx51_3ds_board_keymap,
.keymap_size = ARRAY_SIZE(mx51_3ds_board_keymap),
};
static int mx51_3ds_spi2_cs[] = {
MXC_SPI_CS(0),
MX51_3DS_ECSPI2_CS,
};
static const struct spi_imx_master mx51_3ds_ecspi2_pdata __initconst = {
.chipselect = mx51_3ds_spi2_cs,
.num_chipselect = ARRAY_SIZE(mx51_3ds_spi2_cs),
};
static struct spi_board_info mx51_3ds_spi_nor_device[] = {
{
.modalias = "m25p80",
.max_speed_hz = 25000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 1,
.chip_select = 1,
.mode = SPI_MODE_0,
.platform_data = NULL,},
};
/*
* Board specific initialization.
*/
static void __init mx51_3ds_init(void)
{
imx51_soc_init();
mxc_iomux_v3_setup_multiple_pads(mx51_3ds_pads,
ARRAY_SIZE(mx51_3ds_pads));
imx51_add_imx_uart(0, &uart_pdata);
imx51_add_imx_uart(1, &uart_pdata);
imx51_add_imx_uart(2, &uart_pdata);
imx51_add_ecspi(1, &mx51_3ds_ecspi2_pdata);
spi_register_board_info(mx51_3ds_spi_nor_device,
ARRAY_SIZE(mx51_3ds_spi_nor_device));
if (mxc_expio_init(MX51_CS5_BASE_ADDR, EXPIO_PARENT_INT))
printk(KERN_WARNING "Init of the debugboard failed, all "
"devices on the board are unusable.\n");
imx51_add_sdhci_esdhc_imx(0, NULL);
imx51_add_imx_keypad(&mx51_3ds_map_data);
imx51_add_imx2_wdt(0, NULL);
}
static void __init mx51_3ds_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 0);
}
static struct sys_timer mx51_3ds_timer = {
.init = mx51_3ds_timer_init,
};
MACHINE_START(MX51_3DS, "Freescale MX51 3-Stack Board")
/* Maintainer: Freescale Semiconductor, Inc. */
.atag_offset = 0x100,
.map_io = mx51_map_io,
.init_early = imx51_init_early,
.init_irq = mx51_init_irq,
.handle_irq = imx51_handle_irq,
.timer = &mx51_3ds_timer,
.init_machine = mx51_3ds_init,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
cnexus/kernel_d2spr_tw_44 | arch/arm/mach-imx/mach-mx51_babbage.c | 4830 | 11120 | /*
* Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2009-2010 Amit Kucheria <amit.kucheria@canonical.com>
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/input.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx51.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "devices-imx51.h"
#include "cpu_op-mx51.h"
#define BABBAGE_USB_HUB_RESET IMX_GPIO_NR(1, 7)
#define BABBAGE_USBH1_STP IMX_GPIO_NR(1, 27)
#define BABBAGE_USB_PHY_RESET IMX_GPIO_NR(2, 5)
#define BABBAGE_FEC_PHY_RESET IMX_GPIO_NR(2, 14)
#define BABBAGE_POWER_KEY IMX_GPIO_NR(2, 21)
#define BABBAGE_ECSPI1_CS0 IMX_GPIO_NR(4, 24)
#define BABBAGE_ECSPI1_CS1 IMX_GPIO_NR(4, 25)
#define BABBAGE_SD2_CD IMX_GPIO_NR(1, 6)
#define BABBAGE_SD2_WP IMX_GPIO_NR(1, 5)
/* USB_CTRL_1 */
#define MX51_USB_CTRL_1_OFFSET 0x10
#define MX51_USB_CTRL_UH1_EXT_CLK_EN (1 << 25)
#define MX51_USB_PLLDIV_12_MHZ 0x00
#define MX51_USB_PLL_DIV_19_2_MHZ 0x01
#define MX51_USB_PLL_DIV_24_MHZ 0x02
static struct gpio_keys_button babbage_buttons[] = {
{
.gpio = BABBAGE_POWER_KEY,
.code = BTN_0,
.desc = "PWR",
.active_low = 1,
.wakeup = 1,
},
};
static const struct gpio_keys_platform_data imx_button_data __initconst = {
.buttons = babbage_buttons,
.nbuttons = ARRAY_SIZE(babbage_buttons),
};
static iomux_v3_cfg_t mx51babbage_pads[] = {
/* UART1 */
MX51_PAD_UART1_RXD__UART1_RXD,
MX51_PAD_UART1_TXD__UART1_TXD,
MX51_PAD_UART1_RTS__UART1_RTS,
MX51_PAD_UART1_CTS__UART1_CTS,
/* UART2 */
MX51_PAD_UART2_RXD__UART2_RXD,
MX51_PAD_UART2_TXD__UART2_TXD,
/* UART3 */
MX51_PAD_EIM_D25__UART3_RXD,
MX51_PAD_EIM_D26__UART3_TXD,
MX51_PAD_EIM_D27__UART3_RTS,
MX51_PAD_EIM_D24__UART3_CTS,
/* I2C1 */
MX51_PAD_EIM_D16__I2C1_SDA,
MX51_PAD_EIM_D19__I2C1_SCL,
/* I2C2 */
MX51_PAD_KEY_COL4__I2C2_SCL,
MX51_PAD_KEY_COL5__I2C2_SDA,
/* HSI2C */
MX51_PAD_I2C1_CLK__I2C1_CLK,
MX51_PAD_I2C1_DAT__I2C1_DAT,
/* USB HOST1 */
MX51_PAD_USBH1_CLK__USBH1_CLK,
MX51_PAD_USBH1_DIR__USBH1_DIR,
MX51_PAD_USBH1_NXT__USBH1_NXT,
MX51_PAD_USBH1_DATA0__USBH1_DATA0,
MX51_PAD_USBH1_DATA1__USBH1_DATA1,
MX51_PAD_USBH1_DATA2__USBH1_DATA2,
MX51_PAD_USBH1_DATA3__USBH1_DATA3,
MX51_PAD_USBH1_DATA4__USBH1_DATA4,
MX51_PAD_USBH1_DATA5__USBH1_DATA5,
MX51_PAD_USBH1_DATA6__USBH1_DATA6,
MX51_PAD_USBH1_DATA7__USBH1_DATA7,
/* USB HUB reset line*/
MX51_PAD_GPIO1_7__GPIO1_7,
/* USB PHY reset line */
MX51_PAD_EIM_D21__GPIO2_5,
/* FEC */
MX51_PAD_EIM_EB2__FEC_MDIO,
MX51_PAD_EIM_EB3__FEC_RDATA1,
MX51_PAD_EIM_CS2__FEC_RDATA2,
MX51_PAD_EIM_CS3__FEC_RDATA3,
MX51_PAD_EIM_CS4__FEC_RX_ER,
MX51_PAD_EIM_CS5__FEC_CRS,
MX51_PAD_NANDF_RB2__FEC_COL,
MX51_PAD_NANDF_RB3__FEC_RX_CLK,
MX51_PAD_NANDF_D9__FEC_RDATA0,
MX51_PAD_NANDF_D8__FEC_TDATA0,
MX51_PAD_NANDF_CS2__FEC_TX_ER,
MX51_PAD_NANDF_CS3__FEC_MDC,
MX51_PAD_NANDF_CS4__FEC_TDATA1,
MX51_PAD_NANDF_CS5__FEC_TDATA2,
MX51_PAD_NANDF_CS6__FEC_TDATA3,
MX51_PAD_NANDF_CS7__FEC_TX_EN,
MX51_PAD_NANDF_RDY_INT__FEC_TX_CLK,
/* FEC PHY reset line */
MX51_PAD_EIM_A20__GPIO2_14,
/* SD 1 */
MX51_PAD_SD1_CMD__SD1_CMD,
MX51_PAD_SD1_CLK__SD1_CLK,
MX51_PAD_SD1_DATA0__SD1_DATA0,
MX51_PAD_SD1_DATA1__SD1_DATA1,
MX51_PAD_SD1_DATA2__SD1_DATA2,
MX51_PAD_SD1_DATA3__SD1_DATA3,
/* CD/WP from controller */
MX51_PAD_GPIO1_0__SD1_CD,
MX51_PAD_GPIO1_1__SD1_WP,
/* SD 2 */
MX51_PAD_SD2_CMD__SD2_CMD,
MX51_PAD_SD2_CLK__SD2_CLK,
MX51_PAD_SD2_DATA0__SD2_DATA0,
MX51_PAD_SD2_DATA1__SD2_DATA1,
MX51_PAD_SD2_DATA2__SD2_DATA2,
MX51_PAD_SD2_DATA3__SD2_DATA3,
/* CD/WP gpio */
MX51_PAD_GPIO1_6__GPIO1_6,
MX51_PAD_GPIO1_5__GPIO1_5,
/* eCSPI1 */
MX51_PAD_CSPI1_MISO__ECSPI1_MISO,
MX51_PAD_CSPI1_MOSI__ECSPI1_MOSI,
MX51_PAD_CSPI1_SCLK__ECSPI1_SCLK,
MX51_PAD_CSPI1_SS0__GPIO4_24,
MX51_PAD_CSPI1_SS1__GPIO4_25,
};
/* Serial ports */
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static const struct imxi2c_platform_data babbage_i2c_data __initconst = {
.bitrate = 100000,
};
static const struct imxi2c_platform_data babbage_hsi2c_data __initconst = {
.bitrate = 400000,
};
static struct gpio mx51_babbage_usbh1_gpios[] = {
{ BABBAGE_USBH1_STP, GPIOF_OUT_INIT_LOW, "usbh1_stp" },
{ BABBAGE_USB_PHY_RESET, GPIOF_OUT_INIT_LOW, "usbh1_phy_reset" },
};
static int gpio_usbh1_active(void)
{
iomux_v3_cfg_t usbh1stp_gpio = MX51_PAD_USBH1_STP__GPIO1_27;
int ret;
/* Set USBH1_STP to GPIO and toggle it */
mxc_iomux_v3_setup_pad(usbh1stp_gpio);
ret = gpio_request_array(mx51_babbage_usbh1_gpios,
ARRAY_SIZE(mx51_babbage_usbh1_gpios));
if (ret) {
pr_debug("failed to get USBH1 pins: %d\n", ret);
return ret;
}
msleep(100);
gpio_set_value(BABBAGE_USBH1_STP, 1);
gpio_set_value(BABBAGE_USB_PHY_RESET, 1);
gpio_free_array(mx51_babbage_usbh1_gpios,
ARRAY_SIZE(mx51_babbage_usbh1_gpios));
return 0;
}
static inline void babbage_usbhub_reset(void)
{
int ret;
/* Reset USB hub */
ret = gpio_request_one(BABBAGE_USB_HUB_RESET,
GPIOF_OUT_INIT_LOW, "GPIO1_7");
if (ret) {
printk(KERN_ERR"failed to get GPIO_USB_HUB_RESET: %d\n", ret);
return;
}
msleep(2);
/* Deassert reset */
gpio_set_value(BABBAGE_USB_HUB_RESET, 1);
}
static inline void babbage_fec_reset(void)
{
int ret;
/* reset FEC PHY */
ret = gpio_request_one(BABBAGE_FEC_PHY_RESET,
GPIOF_OUT_INIT_LOW, "fec-phy-reset");
if (ret) {
printk(KERN_ERR"failed to get GPIO_FEC_PHY_RESET: %d\n", ret);
return;
}
msleep(1);
gpio_set_value(BABBAGE_FEC_PHY_RESET, 1);
}
/* This function is board specific as the bit mask for the plldiv will also
be different for other Freescale SoCs, thus a common bitmask is not
possible and cannot get place in /plat-mxc/ehci.c.*/
static int initialize_otg_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* Set the PHY clock to 19.2MHz */
v = __raw_readl(usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
v &= ~MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK;
v |= MX51_USB_PLL_DIV_19_2_MHZ;
__raw_writel(v, usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(0, MXC_EHCI_INTERNAL_PHY);
}
static int initialize_usbh1_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* The clock for the USBH1 ULPI port will come externally from the PHY. */
v = __raw_readl(usbother_base + MX51_USB_CTRL_1_OFFSET);
__raw_writel(v | MX51_USB_CTRL_UH1_EXT_CLK_EN, usbother_base + MX51_USB_CTRL_1_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(1, MXC_EHCI_POWER_PINS_ENABLED |
MXC_EHCI_ITC_NO_THRESHOLD);
}
static const struct mxc_usbh_platform_data dr_utmi_config __initconst = {
.init = initialize_otg_port,
.portsc = MXC_EHCI_UTMI_16BIT,
};
static const struct fsl_usb2_platform_data usb_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_UTMI_WIDE,
};
static const struct mxc_usbh_platform_data usbh1_config __initconst = {
.init = initialize_usbh1_port,
.portsc = MXC_EHCI_MODE_ULPI,
};
static int otg_mode_host;
static int __init babbage_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", babbage_otg_mode);
static struct spi_board_info mx51_babbage_spi_board_info[] __initdata = {
{
.modalias = "mtd_dataflash",
.max_speed_hz = 25000000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_0,
.platform_data = NULL,
},
};
static int mx51_babbage_spi_cs[] = {
BABBAGE_ECSPI1_CS0,
BABBAGE_ECSPI1_CS1,
};
static const struct spi_imx_master mx51_babbage_spi_pdata __initconst = {
.chipselect = mx51_babbage_spi_cs,
.num_chipselect = ARRAY_SIZE(mx51_babbage_spi_cs),
};
static const struct esdhc_platform_data mx51_babbage_sd1_data __initconst = {
.cd_type = ESDHC_CD_CONTROLLER,
.wp_type = ESDHC_WP_CONTROLLER,
};
static const struct esdhc_platform_data mx51_babbage_sd2_data __initconst = {
.cd_gpio = BABBAGE_SD2_CD,
.wp_gpio = BABBAGE_SD2_WP,
.cd_type = ESDHC_CD_GPIO,
.wp_type = ESDHC_WP_GPIO,
};
void __init imx51_babbage_common_init(void)
{
mxc_iomux_v3_setup_multiple_pads(mx51babbage_pads,
ARRAY_SIZE(mx51babbage_pads));
}
/*
* Board specific initialization.
*/
static void __init mx51_babbage_init(void)
{
iomux_v3_cfg_t usbh1stp = MX51_PAD_USBH1_STP__USBH1_STP;
iomux_v3_cfg_t power_key = NEW_PAD_CTRL(MX51_PAD_EIM_A27__GPIO2_21,
PAD_CTL_SRE_FAST | PAD_CTL_DSE_HIGH);
imx51_soc_init();
#if defined(CONFIG_CPU_FREQ_IMX)
get_cpu_op = mx51_get_cpu_op;
#endif
imx51_babbage_common_init();
imx51_add_imx_uart(0, &uart_pdata);
imx51_add_imx_uart(1, NULL);
imx51_add_imx_uart(2, &uart_pdata);
babbage_fec_reset();
imx51_add_fec(NULL);
/* Set the PAD settings for the pwr key. */
mxc_iomux_v3_setup_pad(power_key);
imx_add_gpio_keys(&imx_button_data);
imx51_add_imx_i2c(0, &babbage_i2c_data);
imx51_add_imx_i2c(1, &babbage_i2c_data);
imx51_add_hsi2c(&babbage_hsi2c_data);
if (otg_mode_host)
imx51_add_mxc_ehci_otg(&dr_utmi_config);
else {
initialize_otg_port(NULL);
imx51_add_fsl_usb2_udc(&usb_pdata);
}
gpio_usbh1_active();
imx51_add_mxc_ehci_hs(1, &usbh1_config);
/* setback USBH1_STP to be function */
mxc_iomux_v3_setup_pad(usbh1stp);
babbage_usbhub_reset();
imx51_add_sdhci_esdhc_imx(0, &mx51_babbage_sd1_data);
imx51_add_sdhci_esdhc_imx(1, &mx51_babbage_sd2_data);
spi_register_board_info(mx51_babbage_spi_board_info,
ARRAY_SIZE(mx51_babbage_spi_board_info));
imx51_add_ecspi(0, &mx51_babbage_spi_pdata);
imx51_add_imx2_wdt(0, NULL);
}
static void __init mx51_babbage_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 0);
}
static struct sys_timer mx51_babbage_timer = {
.init = mx51_babbage_timer_init,
};
MACHINE_START(MX51_BABBAGE, "Freescale MX51 Babbage Board")
/* Maintainer: Amit Kucheria <amit.kucheria@canonical.com> */
.atag_offset = 0x100,
.map_io = mx51_map_io,
.init_early = imx51_init_early,
.init_irq = mx51_init_irq,
.handle_irq = imx51_handle_irq,
.timer = &mx51_babbage_timer,
.init_machine = mx51_babbage_init,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
nks15/nks_kernel_j7xeltektt | sound/last.c | 4830 | 1272 | /*
* Advanced Linux Sound Architecture
* 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 <sound/core.h>
static int __init alsa_sound_last_init(void)
{
int idx, ok = 0;
printk(KERN_INFO "ALSA device list:\n");
for (idx = 0; idx < SNDRV_CARDS; idx++)
if (snd_cards[idx] != NULL) {
printk(KERN_INFO " #%i: %s\n", idx, snd_cards[idx]->longname);
ok++;
}
if (ok == 0)
printk(KERN_INFO " No soundcards found.\n");
return 0;
}
late_initcall_sync(alsa_sound_last_init);
| gpl-2.0 |
pantech-msm8974/android_kernel_pantech_msm8974 | drivers/s390/cio/chsc_sch.c | 5086 | 20406 | /*
* Driver for s390 chsc subchannels
*
* Copyright IBM Corp. 2008, 2011
*
* Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
*
*/
#include <linux/slab.h>
#include <linux/compat.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <linux/kernel_stat.h>
#include <asm/compat.h>
#include <asm/cio.h>
#include <asm/chsc.h>
#include <asm/isc.h>
#include "cio.h"
#include "cio_debug.h"
#include "css.h"
#include "chsc_sch.h"
#include "ioasm.h"
static debug_info_t *chsc_debug_msg_id;
static debug_info_t *chsc_debug_log_id;
#define CHSC_MSG(imp, args...) do { \
debug_sprintf_event(chsc_debug_msg_id, imp , ##args); \
} while (0)
#define CHSC_LOG(imp, txt) do { \
debug_text_event(chsc_debug_log_id, imp , txt); \
} while (0)
static void CHSC_LOG_HEX(int level, void *data, int length)
{
while (length > 0) {
debug_event(chsc_debug_log_id, level, data, length);
length -= chsc_debug_log_id->buf_size;
data += chsc_debug_log_id->buf_size;
}
}
MODULE_AUTHOR("IBM Corporation");
MODULE_DESCRIPTION("driver for s390 chsc subchannels");
MODULE_LICENSE("GPL");
static void chsc_subchannel_irq(struct subchannel *sch)
{
struct chsc_private *private = dev_get_drvdata(&sch->dev);
struct chsc_request *request = private->request;
struct irb *irb = (struct irb *)&S390_lowcore.irb;
CHSC_LOG(4, "irb");
CHSC_LOG_HEX(4, irb, sizeof(*irb));
kstat_cpu(smp_processor_id()).irqs[IOINT_CSC]++;
/* Copy irb to provided request and set done. */
if (!request) {
CHSC_MSG(0, "Interrupt on sch 0.%x.%04x with no request\n",
sch->schid.ssid, sch->schid.sch_no);
return;
}
private->request = NULL;
memcpy(&request->irb, irb, sizeof(*irb));
cio_update_schib(sch);
complete(&request->completion);
put_device(&sch->dev);
}
static int chsc_subchannel_probe(struct subchannel *sch)
{
struct chsc_private *private;
int ret;
CHSC_MSG(6, "Detected chsc subchannel 0.%x.%04x\n",
sch->schid.ssid, sch->schid.sch_no);
sch->isc = CHSC_SCH_ISC;
private = kzalloc(sizeof(*private), GFP_KERNEL);
if (!private)
return -ENOMEM;
dev_set_drvdata(&sch->dev, private);
ret = cio_enable_subchannel(sch, (u32)(unsigned long)sch);
if (ret) {
CHSC_MSG(0, "Failed to enable 0.%x.%04x: %d\n",
sch->schid.ssid, sch->schid.sch_no, ret);
dev_set_drvdata(&sch->dev, NULL);
kfree(private);
} else {
if (dev_get_uevent_suppress(&sch->dev)) {
dev_set_uevent_suppress(&sch->dev, 0);
kobject_uevent(&sch->dev.kobj, KOBJ_ADD);
}
}
return ret;
}
static int chsc_subchannel_remove(struct subchannel *sch)
{
struct chsc_private *private;
cio_disable_subchannel(sch);
private = dev_get_drvdata(&sch->dev);
dev_set_drvdata(&sch->dev, NULL);
if (private->request) {
complete(&private->request->completion);
put_device(&sch->dev);
}
kfree(private);
return 0;
}
static void chsc_subchannel_shutdown(struct subchannel *sch)
{
cio_disable_subchannel(sch);
}
static int chsc_subchannel_prepare(struct subchannel *sch)
{
int cc;
struct schib schib;
/*
* Don't allow suspend while the subchannel is not idle
* since we don't have a way to clear the subchannel and
* cannot disable it with a request running.
*/
cc = stsch_err(sch->schid, &schib);
if (!cc && scsw_stctl(&schib.scsw))
return -EAGAIN;
return 0;
}
static int chsc_subchannel_freeze(struct subchannel *sch)
{
return cio_disable_subchannel(sch);
}
static int chsc_subchannel_restore(struct subchannel *sch)
{
return cio_enable_subchannel(sch, (u32)(unsigned long)sch);
}
static struct css_device_id chsc_subchannel_ids[] = {
{ .match_flags = 0x1, .type =SUBCHANNEL_TYPE_CHSC, },
{ /* end of list */ },
};
MODULE_DEVICE_TABLE(css, chsc_subchannel_ids);
static struct css_driver chsc_subchannel_driver = {
.drv = {
.owner = THIS_MODULE,
.name = "chsc_subchannel",
},
.subchannel_type = chsc_subchannel_ids,
.irq = chsc_subchannel_irq,
.probe = chsc_subchannel_probe,
.remove = chsc_subchannel_remove,
.shutdown = chsc_subchannel_shutdown,
.prepare = chsc_subchannel_prepare,
.freeze = chsc_subchannel_freeze,
.thaw = chsc_subchannel_restore,
.restore = chsc_subchannel_restore,
};
static int __init chsc_init_dbfs(void)
{
chsc_debug_msg_id = debug_register("chsc_msg", 16, 1,
16 * sizeof(long));
if (!chsc_debug_msg_id)
goto out;
debug_register_view(chsc_debug_msg_id, &debug_sprintf_view);
debug_set_level(chsc_debug_msg_id, 2);
chsc_debug_log_id = debug_register("chsc_log", 16, 1, 16);
if (!chsc_debug_log_id)
goto out;
debug_register_view(chsc_debug_log_id, &debug_hex_ascii_view);
debug_set_level(chsc_debug_log_id, 2);
return 0;
out:
if (chsc_debug_msg_id)
debug_unregister(chsc_debug_msg_id);
return -ENOMEM;
}
static void chsc_remove_dbfs(void)
{
debug_unregister(chsc_debug_log_id);
debug_unregister(chsc_debug_msg_id);
}
static int __init chsc_init_sch_driver(void)
{
return css_driver_register(&chsc_subchannel_driver);
}
static void chsc_cleanup_sch_driver(void)
{
css_driver_unregister(&chsc_subchannel_driver);
}
static DEFINE_SPINLOCK(chsc_lock);
static int chsc_subchannel_match_next_free(struct device *dev, void *data)
{
struct subchannel *sch = to_subchannel(dev);
return sch->schib.pmcw.ena && !scsw_fctl(&sch->schib.scsw);
}
static struct subchannel *chsc_get_next_subchannel(struct subchannel *sch)
{
struct device *dev;
dev = driver_find_device(&chsc_subchannel_driver.drv,
sch ? &sch->dev : NULL, NULL,
chsc_subchannel_match_next_free);
return dev ? to_subchannel(dev) : NULL;
}
/**
* chsc_async() - try to start a chsc request asynchronously
* @chsc_area: request to be started
* @request: request structure to associate
*
* Tries to start a chsc request on one of the existing chsc subchannels.
* Returns:
* %0 if the request was performed synchronously
* %-EINPROGRESS if the request was successfully started
* %-EBUSY if all chsc subchannels are busy
* %-ENODEV if no chsc subchannels are available
* Context:
* interrupts disabled, chsc_lock held
*/
static int chsc_async(struct chsc_async_area *chsc_area,
struct chsc_request *request)
{
int cc;
struct chsc_private *private;
struct subchannel *sch = NULL;
int ret = -ENODEV;
char dbf[10];
chsc_area->header.key = PAGE_DEFAULT_KEY >> 4;
while ((sch = chsc_get_next_subchannel(sch))) {
spin_lock(sch->lock);
private = dev_get_drvdata(&sch->dev);
if (private->request) {
spin_unlock(sch->lock);
ret = -EBUSY;
continue;
}
chsc_area->header.sid = sch->schid;
CHSC_LOG(2, "schid");
CHSC_LOG_HEX(2, &sch->schid, sizeof(sch->schid));
cc = chsc(chsc_area);
sprintf(dbf, "cc:%d", cc);
CHSC_LOG(2, dbf);
switch (cc) {
case 0:
ret = 0;
break;
case 1:
sch->schib.scsw.cmd.fctl |= SCSW_FCTL_START_FUNC;
ret = -EINPROGRESS;
private->request = request;
break;
case 2:
ret = -EBUSY;
break;
default:
ret = -ENODEV;
}
spin_unlock(sch->lock);
CHSC_MSG(2, "chsc on 0.%x.%04x returned cc=%d\n",
sch->schid.ssid, sch->schid.sch_no, cc);
if (ret == -EINPROGRESS)
return -EINPROGRESS;
put_device(&sch->dev);
if (ret == 0)
return 0;
}
return ret;
}
static void chsc_log_command(struct chsc_async_area *chsc_area)
{
char dbf[10];
sprintf(dbf, "CHSC:%x", chsc_area->header.code);
CHSC_LOG(0, dbf);
CHSC_LOG_HEX(0, chsc_area, 32);
}
static int chsc_examine_irb(struct chsc_request *request)
{
int backed_up;
if (!(scsw_stctl(&request->irb.scsw) & SCSW_STCTL_STATUS_PEND))
return -EIO;
backed_up = scsw_cstat(&request->irb.scsw) & SCHN_STAT_CHAIN_CHECK;
request->irb.scsw.cmd.cstat &= ~SCHN_STAT_CHAIN_CHECK;
if (scsw_cstat(&request->irb.scsw) == 0)
return 0;
if (!backed_up)
return 0;
if (scsw_cstat(&request->irb.scsw) & SCHN_STAT_PROG_CHECK)
return -EIO;
if (scsw_cstat(&request->irb.scsw) & SCHN_STAT_PROT_CHECK)
return -EPERM;
if (scsw_cstat(&request->irb.scsw) & SCHN_STAT_CHN_DATA_CHK)
return -EAGAIN;
if (scsw_cstat(&request->irb.scsw) & SCHN_STAT_CHN_CTRL_CHK)
return -EAGAIN;
return -EIO;
}
static int chsc_ioctl_start(void __user *user_area)
{
struct chsc_request *request;
struct chsc_async_area *chsc_area;
int ret;
char dbf[10];
if (!css_general_characteristics.dynio)
/* It makes no sense to try. */
return -EOPNOTSUPP;
chsc_area = (void *)get_zeroed_page(GFP_DMA | GFP_KERNEL);
if (!chsc_area)
return -ENOMEM;
request = kzalloc(sizeof(*request), GFP_KERNEL);
if (!request) {
ret = -ENOMEM;
goto out_free;
}
init_completion(&request->completion);
if (copy_from_user(chsc_area, user_area, PAGE_SIZE)) {
ret = -EFAULT;
goto out_free;
}
chsc_log_command(chsc_area);
spin_lock_irq(&chsc_lock);
ret = chsc_async(chsc_area, request);
spin_unlock_irq(&chsc_lock);
if (ret == -EINPROGRESS) {
wait_for_completion(&request->completion);
ret = chsc_examine_irb(request);
}
/* copy area back to user */
if (!ret)
if (copy_to_user(user_area, chsc_area, PAGE_SIZE))
ret = -EFAULT;
out_free:
sprintf(dbf, "ret:%d", ret);
CHSC_LOG(0, dbf);
kfree(request);
free_page((unsigned long)chsc_area);
return ret;
}
static int chsc_ioctl_info_channel_path(void __user *user_cd)
{
struct chsc_chp_cd *cd;
int ret, ccode;
struct {
struct chsc_header request;
u32 : 2;
u32 m : 1;
u32 : 1;
u32 fmt1 : 4;
u32 cssid : 8;
u32 : 8;
u32 first_chpid : 8;
u32 : 24;
u32 last_chpid : 8;
u32 : 32;
struct chsc_header response;
u8 data[PAGE_SIZE - 20];
} __attribute__ ((packed)) *scpcd_area;
scpcd_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!scpcd_area)
return -ENOMEM;
cd = kzalloc(sizeof(*cd), GFP_KERNEL);
if (!cd) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(cd, user_cd, sizeof(*cd))) {
ret = -EFAULT;
goto out_free;
}
scpcd_area->request.length = 0x0010;
scpcd_area->request.code = 0x0028;
scpcd_area->m = cd->m;
scpcd_area->fmt1 = cd->fmt;
scpcd_area->cssid = cd->chpid.cssid;
scpcd_area->first_chpid = cd->chpid.id;
scpcd_area->last_chpid = cd->chpid.id;
ccode = chsc(scpcd_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (scpcd_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "scpcd: response code=%x\n",
scpcd_area->response.code);
goto out_free;
}
memcpy(&cd->cpcb, &scpcd_area->response, scpcd_area->response.length);
if (copy_to_user(user_cd, cd, sizeof(*cd)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(cd);
free_page((unsigned long)scpcd_area);
return ret;
}
static int chsc_ioctl_info_cu(void __user *user_cd)
{
struct chsc_cu_cd *cd;
int ret, ccode;
struct {
struct chsc_header request;
u32 : 2;
u32 m : 1;
u32 : 1;
u32 fmt1 : 4;
u32 cssid : 8;
u32 : 8;
u32 first_cun : 8;
u32 : 24;
u32 last_cun : 8;
u32 : 32;
struct chsc_header response;
u8 data[PAGE_SIZE - 20];
} __attribute__ ((packed)) *scucd_area;
scucd_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!scucd_area)
return -ENOMEM;
cd = kzalloc(sizeof(*cd), GFP_KERNEL);
if (!cd) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(cd, user_cd, sizeof(*cd))) {
ret = -EFAULT;
goto out_free;
}
scucd_area->request.length = 0x0010;
scucd_area->request.code = 0x0028;
scucd_area->m = cd->m;
scucd_area->fmt1 = cd->fmt;
scucd_area->cssid = cd->cssid;
scucd_area->first_cun = cd->cun;
scucd_area->last_cun = cd->cun;
ccode = chsc(scucd_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (scucd_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "scucd: response code=%x\n",
scucd_area->response.code);
goto out_free;
}
memcpy(&cd->cucb, &scucd_area->response, scucd_area->response.length);
if (copy_to_user(user_cd, cd, sizeof(*cd)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(cd);
free_page((unsigned long)scucd_area);
return ret;
}
static int chsc_ioctl_info_sch_cu(void __user *user_cud)
{
struct chsc_sch_cud *cud;
int ret, ccode;
struct {
struct chsc_header request;
u32 : 2;
u32 m : 1;
u32 : 5;
u32 fmt1 : 4;
u32 : 2;
u32 ssid : 2;
u32 first_sch : 16;
u32 : 8;
u32 cssid : 8;
u32 last_sch : 16;
u32 : 32;
struct chsc_header response;
u8 data[PAGE_SIZE - 20];
} __attribute__ ((packed)) *sscud_area;
sscud_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sscud_area)
return -ENOMEM;
cud = kzalloc(sizeof(*cud), GFP_KERNEL);
if (!cud) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(cud, user_cud, sizeof(*cud))) {
ret = -EFAULT;
goto out_free;
}
sscud_area->request.length = 0x0010;
sscud_area->request.code = 0x0006;
sscud_area->m = cud->schid.m;
sscud_area->fmt1 = cud->fmt;
sscud_area->ssid = cud->schid.ssid;
sscud_area->first_sch = cud->schid.sch_no;
sscud_area->cssid = cud->schid.cssid;
sscud_area->last_sch = cud->schid.sch_no;
ccode = chsc(sscud_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (sscud_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "sscud: response code=%x\n",
sscud_area->response.code);
goto out_free;
}
memcpy(&cud->scub, &sscud_area->response, sscud_area->response.length);
if (copy_to_user(user_cud, cud, sizeof(*cud)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(cud);
free_page((unsigned long)sscud_area);
return ret;
}
static int chsc_ioctl_conf_info(void __user *user_ci)
{
struct chsc_conf_info *ci;
int ret, ccode;
struct {
struct chsc_header request;
u32 : 2;
u32 m : 1;
u32 : 1;
u32 fmt1 : 4;
u32 cssid : 8;
u32 : 6;
u32 ssid : 2;
u32 : 8;
u64 : 64;
struct chsc_header response;
u8 data[PAGE_SIZE - 20];
} __attribute__ ((packed)) *sci_area;
sci_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sci_area)
return -ENOMEM;
ci = kzalloc(sizeof(*ci), GFP_KERNEL);
if (!ci) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(ci, user_ci, sizeof(*ci))) {
ret = -EFAULT;
goto out_free;
}
sci_area->request.length = 0x0010;
sci_area->request.code = 0x0012;
sci_area->m = ci->id.m;
sci_area->fmt1 = ci->fmt;
sci_area->cssid = ci->id.cssid;
sci_area->ssid = ci->id.ssid;
ccode = chsc(sci_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (sci_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "sci: response code=%x\n",
sci_area->response.code);
goto out_free;
}
memcpy(&ci->scid, &sci_area->response, sci_area->response.length);
if (copy_to_user(user_ci, ci, sizeof(*ci)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(ci);
free_page((unsigned long)sci_area);
return ret;
}
static int chsc_ioctl_conf_comp_list(void __user *user_ccl)
{
struct chsc_comp_list *ccl;
int ret, ccode;
struct {
struct chsc_header request;
u32 ctype : 8;
u32 : 4;
u32 fmt : 4;
u32 : 16;
u64 : 64;
u32 list_parm[2];
u64 : 64;
struct chsc_header response;
u8 data[PAGE_SIZE - 36];
} __attribute__ ((packed)) *sccl_area;
struct {
u32 m : 1;
u32 : 31;
u32 cssid : 8;
u32 : 16;
u32 chpid : 8;
} __attribute__ ((packed)) *chpid_parm;
struct {
u32 f_cssid : 8;
u32 l_cssid : 8;
u32 : 16;
u32 res;
} __attribute__ ((packed)) *cssids_parm;
sccl_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccl_area)
return -ENOMEM;
ccl = kzalloc(sizeof(*ccl), GFP_KERNEL);
if (!ccl) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(ccl, user_ccl, sizeof(*ccl))) {
ret = -EFAULT;
goto out_free;
}
sccl_area->request.length = 0x0020;
sccl_area->request.code = 0x0030;
sccl_area->fmt = ccl->req.fmt;
sccl_area->ctype = ccl->req.ctype;
switch (sccl_area->ctype) {
case CCL_CU_ON_CHP:
case CCL_IOP_CHP:
chpid_parm = (void *)&sccl_area->list_parm;
chpid_parm->m = ccl->req.chpid.m;
chpid_parm->cssid = ccl->req.chpid.chp.cssid;
chpid_parm->chpid = ccl->req.chpid.chp.id;
break;
case CCL_CSS_IMG:
case CCL_CSS_IMG_CONF_CHAR:
cssids_parm = (void *)&sccl_area->list_parm;
cssids_parm->f_cssid = ccl->req.cssids.f_cssid;
cssids_parm->l_cssid = ccl->req.cssids.l_cssid;
break;
}
ccode = chsc(sccl_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (sccl_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "sccl: response code=%x\n",
sccl_area->response.code);
goto out_free;
}
memcpy(&ccl->sccl, &sccl_area->response, sccl_area->response.length);
if (copy_to_user(user_ccl, ccl, sizeof(*ccl)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(ccl);
free_page((unsigned long)sccl_area);
return ret;
}
static int chsc_ioctl_chpd(void __user *user_chpd)
{
struct chsc_scpd *scpd_area;
struct chsc_cpd_info *chpd;
int ret;
chpd = kzalloc(sizeof(*chpd), GFP_KERNEL);
scpd_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!scpd_area || !chpd) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(chpd, user_chpd, sizeof(*chpd))) {
ret = -EFAULT;
goto out_free;
}
ret = chsc_determine_channel_path_desc(chpd->chpid, chpd->fmt,
chpd->rfmt, chpd->c, chpd->m,
scpd_area);
if (ret)
goto out_free;
memcpy(&chpd->chpdb, &scpd_area->response, scpd_area->response.length);
if (copy_to_user(user_chpd, chpd, sizeof(*chpd)))
ret = -EFAULT;
out_free:
kfree(chpd);
free_page((unsigned long)scpd_area);
return ret;
}
static int chsc_ioctl_dcal(void __user *user_dcal)
{
struct chsc_dcal *dcal;
int ret, ccode;
struct {
struct chsc_header request;
u32 atype : 8;
u32 : 4;
u32 fmt : 4;
u32 : 16;
u32 res0[2];
u32 list_parm[2];
u32 res1[2];
struct chsc_header response;
u8 data[PAGE_SIZE - 36];
} __attribute__ ((packed)) *sdcal_area;
sdcal_area = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sdcal_area)
return -ENOMEM;
dcal = kzalloc(sizeof(*dcal), GFP_KERNEL);
if (!dcal) {
ret = -ENOMEM;
goto out_free;
}
if (copy_from_user(dcal, user_dcal, sizeof(*dcal))) {
ret = -EFAULT;
goto out_free;
}
sdcal_area->request.length = 0x0020;
sdcal_area->request.code = 0x0034;
sdcal_area->atype = dcal->req.atype;
sdcal_area->fmt = dcal->req.fmt;
memcpy(&sdcal_area->list_parm, &dcal->req.list_parm,
sizeof(sdcal_area->list_parm));
ccode = chsc(sdcal_area);
if (ccode != 0) {
ret = -EIO;
goto out_free;
}
if (sdcal_area->response.code != 0x0001) {
ret = -EIO;
CHSC_MSG(0, "sdcal: response code=%x\n",
sdcal_area->response.code);
goto out_free;
}
memcpy(&dcal->sdcal, &sdcal_area->response,
sdcal_area->response.length);
if (copy_to_user(user_dcal, dcal, sizeof(*dcal)))
ret = -EFAULT;
else
ret = 0;
out_free:
kfree(dcal);
free_page((unsigned long)sdcal_area);
return ret;
}
static long chsc_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
void __user *argp;
CHSC_MSG(2, "chsc_ioctl called, cmd=%x\n", cmd);
if (is_compat_task())
argp = compat_ptr(arg);
else
argp = (void __user *)arg;
switch (cmd) {
case CHSC_START:
return chsc_ioctl_start(argp);
case CHSC_INFO_CHANNEL_PATH:
return chsc_ioctl_info_channel_path(argp);
case CHSC_INFO_CU:
return chsc_ioctl_info_cu(argp);
case CHSC_INFO_SCH_CU:
return chsc_ioctl_info_sch_cu(argp);
case CHSC_INFO_CI:
return chsc_ioctl_conf_info(argp);
case CHSC_INFO_CCL:
return chsc_ioctl_conf_comp_list(argp);
case CHSC_INFO_CPD:
return chsc_ioctl_chpd(argp);
case CHSC_INFO_DCAL:
return chsc_ioctl_dcal(argp);
default: /* unknown ioctl number */
return -ENOIOCTLCMD;
}
}
static const struct file_operations chsc_fops = {
.owner = THIS_MODULE,
.open = nonseekable_open,
.unlocked_ioctl = chsc_ioctl,
.compat_ioctl = chsc_ioctl,
.llseek = no_llseek,
};
static struct miscdevice chsc_misc_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "chsc",
.fops = &chsc_fops,
};
static int __init chsc_misc_init(void)
{
return misc_register(&chsc_misc_device);
}
static void chsc_misc_cleanup(void)
{
misc_deregister(&chsc_misc_device);
}
static int __init chsc_sch_init(void)
{
int ret;
ret = chsc_init_dbfs();
if (ret)
return ret;
isc_register(CHSC_SCH_ISC);
ret = chsc_init_sch_driver();
if (ret)
goto out_dbf;
ret = chsc_misc_init();
if (ret)
goto out_driver;
return ret;
out_driver:
chsc_cleanup_sch_driver();
out_dbf:
isc_unregister(CHSC_SCH_ISC);
chsc_remove_dbfs();
return ret;
}
static void __exit chsc_sch_exit(void)
{
chsc_misc_cleanup();
chsc_cleanup_sch_driver();
isc_unregister(CHSC_SCH_ISC);
chsc_remove_dbfs();
}
module_init(chsc_sch_init);
module_exit(chsc_sch_exit);
| gpl-2.0 |
MetSystem/Xiaomi_Kernel_OpenSource | arch/arm/mach-omap2/omap_l3_noc.c | 5086 | 6910 | /*
* OMAP4XXX L3 Interconnect error handling driver
*
* Copyright (C) 2011 Texas Corporation
* Santosh Shilimkar <santosh.shilimkar@ti.com>
* Sricharan <r.sricharan@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include "omap_l3_noc.h"
/*
* Interrupt Handler for L3 error detection.
* 1) Identify the L3 clockdomain partition to which the error belongs to.
* 2) Identify the slave where the error information is logged
* 3) Print the logged information.
* 4) Add dump stack to provide kernel trace.
*
* Two Types of errors :
* 1) Custom errors in L3 :
* Target like DMM/FW/EMIF generates SRESP=ERR error
* 2) Standard L3 error:
* - Unsupported CMD.
* L3 tries to access target while it is idle
* - OCP disconnect.
* - Address hole error:
* If DSS/ISS/FDIF/USBHOSTFS access a target where they
* do not have connectivity, the error is logged in
* their default target which is DMM2.
*
* On High Secure devices, firewall errors are possible and those
* can be trapped as well. But the trapping is implemented as part
* secure software and hence need not be implemented here.
*/
static irqreturn_t l3_interrupt_handler(int irq, void *_l3)
{
struct omap4_l3 *l3 = _l3;
int inttype, i, k;
int err_src = 0;
u32 std_err_main, err_reg, clear, masterid;
void __iomem *base, *l3_targ_base;
char *target_name, *master_name = "UN IDENTIFIED";
/* Get the Type of interrupt */
inttype = irq == l3->app_irq ? L3_APPLICATION_ERROR : L3_DEBUG_ERROR;
for (i = 0; i < L3_MODULES; i++) {
/*
* Read the regerr register of the clock domain
* to determine the source
*/
base = l3->l3_base[i];
err_reg = __raw_readl(base + l3_flagmux[i] +
+ L3_FLAGMUX_REGERR0 + (inttype << 3));
/* Get the corresponding error and analyse */
if (err_reg) {
/* Identify the source from control status register */
err_src = __ffs(err_reg);
/* Read the stderrlog_main_source from clk domain */
l3_targ_base = base + *(l3_targ[i] + err_src);
std_err_main = __raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
masterid = __raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_MSTADDR);
switch (std_err_main & CUSTOM_ERROR) {
case STANDARD_ERROR:
target_name =
l3_targ_inst_name[i][err_src];
WARN(true, "L3 standard error: TARGET:%s at address 0x%x\n",
target_name,
__raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_SLVOFSLSB));
/* clear the std error log*/
clear = std_err_main | CLEAR_STDERR_LOG;
writel(clear, l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
break;
case CUSTOM_ERROR:
target_name =
l3_targ_inst_name[i][err_src];
for (k = 0; k < NUM_OF_L3_MASTERS; k++) {
if (masterid == l3_masters[k].id)
master_name =
l3_masters[k].name;
}
WARN(true, "L3 custom error: MASTER:%s TARGET:%s\n",
master_name, target_name);
/* clear the std error log*/
clear = std_err_main | CLEAR_STDERR_LOG;
writel(clear, l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
break;
default:
/* Nothing to be handled here as of now */
break;
}
/* Error found so break the for loop */
break;
}
}
return IRQ_HANDLED;
}
static int __devinit omap4_l3_probe(struct platform_device *pdev)
{
static struct omap4_l3 *l3;
struct resource *res;
int ret;
l3 = kzalloc(sizeof(*l3), GFP_KERNEL);
if (!l3)
return -ENOMEM;
platform_set_drvdata(pdev, l3);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 0\n");
ret = -ENODEV;
goto err0;
}
l3->l3_base[0] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[0]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err0;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 1\n");
ret = -ENODEV;
goto err1;
}
l3->l3_base[1] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[1]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err1;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 2);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 2\n");
ret = -ENODEV;
goto err2;
}
l3->l3_base[2] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[2]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err2;
}
/*
* Setup interrupt Handlers
*/
l3->debug_irq = platform_get_irq(pdev, 0);
ret = request_irq(l3->debug_irq,
l3_interrupt_handler,
IRQF_DISABLED, "l3-dbg-irq", l3);
if (ret) {
pr_crit("L3: request_irq failed to register for 0x%x\n",
OMAP44XX_IRQ_L3_DBG);
goto err3;
}
l3->app_irq = platform_get_irq(pdev, 1);
ret = request_irq(l3->app_irq,
l3_interrupt_handler,
IRQF_DISABLED, "l3-app-irq", l3);
if (ret) {
pr_crit("L3: request_irq failed to register for 0x%x\n",
OMAP44XX_IRQ_L3_APP);
goto err4;
}
return 0;
err4:
free_irq(l3->debug_irq, l3);
err3:
iounmap(l3->l3_base[2]);
err2:
iounmap(l3->l3_base[1]);
err1:
iounmap(l3->l3_base[0]);
err0:
kfree(l3);
return ret;
}
static int __devexit omap4_l3_remove(struct platform_device *pdev)
{
struct omap4_l3 *l3 = platform_get_drvdata(pdev);
free_irq(l3->app_irq, l3);
free_irq(l3->debug_irq, l3);
iounmap(l3->l3_base[0]);
iounmap(l3->l3_base[1]);
iounmap(l3->l3_base[2]);
kfree(l3);
return 0;
}
#if defined(CONFIG_OF)
static const struct of_device_id l3_noc_match[] = {
{.compatible = "ti,omap4-l3-noc", },
{},
};
MODULE_DEVICE_TABLE(of, l3_noc_match);
#else
#define l3_noc_match NULL
#endif
static struct platform_driver omap4_l3_driver = {
.probe = omap4_l3_probe,
.remove = __devexit_p(omap4_l3_remove),
.driver = {
.name = "omap_l3_noc",
.owner = THIS_MODULE,
.of_match_table = l3_noc_match,
},
};
static int __init omap4_l3_init(void)
{
return platform_driver_register(&omap4_l3_driver);
}
postcore_initcall_sync(omap4_l3_init);
static void __exit omap4_l3_exit(void)
{
platform_driver_unregister(&omap4_l3_driver);
}
module_exit(omap4_l3_exit);
| gpl-2.0 |
EPDCenter/android_kernel_allwinner_a31_unusual | tools/perf/util/dwarf-aux.c | 5598 | 22337 | /*
* dwarf-aux.c : libdw auxiliary interfaces
*
* 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 <stdbool.h>
#include "util.h"
#include "debug.h"
#include "dwarf-aux.h"
/**
* cu_find_realpath - Find the realpath of the target file
* @cu_die: A DIE(dwarf information entry) of CU(compilation Unit)
* @fname: The tail filename of the target file
*
* Find the real(long) path of @fname in @cu_die.
*/
const char *cu_find_realpath(Dwarf_Die *cu_die, const char *fname)
{
Dwarf_Files *files;
size_t nfiles, i;
const char *src = NULL;
int ret;
if (!fname)
return NULL;
ret = dwarf_getsrcfiles(cu_die, &files, &nfiles);
if (ret != 0)
return NULL;
for (i = 0; i < nfiles; i++) {
src = dwarf_filesrc(files, i, NULL, NULL);
if (strtailcmp(src, fname) == 0)
break;
}
if (i == nfiles)
return NULL;
return src;
}
/**
* cu_get_comp_dir - Get the path of compilation directory
* @cu_die: a CU DIE
*
* Get the path of compilation directory of given @cu_die.
* Since this depends on DW_AT_comp_dir, older gcc will not
* embedded it. In that case, this returns NULL.
*/
const char *cu_get_comp_dir(Dwarf_Die *cu_die)
{
Dwarf_Attribute attr;
if (dwarf_attr(cu_die, DW_AT_comp_dir, &attr) == NULL)
return NULL;
return dwarf_formstring(&attr);
}
/**
* cu_find_lineinfo - Get a line number and file name for given address
* @cu_die: a CU DIE
* @addr: An address
* @fname: a pointer which returns the file name string
* @lineno: a pointer which returns the line number
*
* Find a line number and file name for @addr in @cu_die.
*/
int cu_find_lineinfo(Dwarf_Die *cu_die, unsigned long addr,
const char **fname, int *lineno)
{
Dwarf_Line *line;
Dwarf_Addr laddr;
line = dwarf_getsrc_die(cu_die, (Dwarf_Addr)addr);
if (line && dwarf_lineaddr(line, &laddr) == 0 &&
addr == (unsigned long)laddr && dwarf_lineno(line, lineno) == 0) {
*fname = dwarf_linesrc(line, NULL, NULL);
if (!*fname)
/* line number is useless without filename */
*lineno = 0;
}
return *lineno ?: -ENOENT;
}
static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data);
/**
* cu_walk_functions_at - Walk on function DIEs at given address
* @cu_die: A CU DIE
* @addr: An address
* @callback: A callback which called with found DIEs
* @data: A user data
*
* Walk on function DIEs at given @addr in @cu_die. Passed DIEs
* should be subprogram or inlined-subroutines.
*/
int cu_walk_functions_at(Dwarf_Die *cu_die, Dwarf_Addr addr,
int (*callback)(Dwarf_Die *, void *), void *data)
{
Dwarf_Die die_mem;
Dwarf_Die *sc_die;
int ret = -ENOENT;
/* Inlined function could be recursive. Trace it until fail */
for (sc_die = die_find_realfunc(cu_die, addr, &die_mem);
sc_die != NULL;
sc_die = die_find_child(sc_die, __die_find_inline_cb, &addr,
&die_mem)) {
ret = callback(sc_die, data);
if (ret)
break;
}
return ret;
}
/**
* die_compare_name - Compare diename and tname
* @dw_die: a DIE
* @tname: a string of target name
*
* Compare the name of @dw_die and @tname. Return false if @dw_die has no name.
*/
bool die_compare_name(Dwarf_Die *dw_die, const char *tname)
{
const char *name;
name = dwarf_diename(dw_die);
return name ? (strcmp(tname, name) == 0) : false;
}
/**
* die_get_call_lineno - Get callsite line number of inline-function instance
* @in_die: a DIE of an inlined function instance
*
* Get call-site line number of @in_die. This means from where the inline
* function is called.
*/
int die_get_call_lineno(Dwarf_Die *in_die)
{
Dwarf_Attribute attr;
Dwarf_Word ret;
if (!dwarf_attr(in_die, DW_AT_call_line, &attr))
return -ENOENT;
dwarf_formudata(&attr, &ret);
return (int)ret;
}
/**
* die_get_type - Get type DIE
* @vr_die: a DIE of a variable
* @die_mem: where to store a type DIE
*
* Get a DIE of the type of given variable (@vr_die), and store
* it to die_mem. Return NULL if fails to get a type DIE.
*/
Dwarf_Die *die_get_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
Dwarf_Attribute attr;
if (dwarf_attr_integrate(vr_die, DW_AT_type, &attr) &&
dwarf_formref_die(&attr, die_mem))
return die_mem;
else
return NULL;
}
/* Get a type die, but skip qualifiers */
static Dwarf_Die *__die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
int tag;
do {
vr_die = die_get_type(vr_die, die_mem);
if (!vr_die)
break;
tag = dwarf_tag(vr_die);
} while (tag == DW_TAG_const_type ||
tag == DW_TAG_restrict_type ||
tag == DW_TAG_volatile_type ||
tag == DW_TAG_shared_type);
return vr_die;
}
/**
* die_get_real_type - Get a type die, but skip qualifiers and typedef
* @vr_die: a DIE of a variable
* @die_mem: where to store a type DIE
*
* Get a DIE of the type of given variable (@vr_die), and store
* it to die_mem. Return NULL if fails to get a type DIE.
* If the type is qualifiers (e.g. const) or typedef, this skips it
* and tries to find real type (structure or basic types, e.g. int).
*/
Dwarf_Die *die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
do {
vr_die = __die_get_real_type(vr_die, die_mem);
} while (vr_die && dwarf_tag(vr_die) == DW_TAG_typedef);
return vr_die;
}
/* Get attribute and translate it as a udata */
static int die_get_attr_udata(Dwarf_Die *tp_die, unsigned int attr_name,
Dwarf_Word *result)
{
Dwarf_Attribute attr;
if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
dwarf_formudata(&attr, result) != 0)
return -ENOENT;
return 0;
}
/* Get attribute and translate it as a sdata */
static int die_get_attr_sdata(Dwarf_Die *tp_die, unsigned int attr_name,
Dwarf_Sword *result)
{
Dwarf_Attribute attr;
if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
dwarf_formsdata(&attr, result) != 0)
return -ENOENT;
return 0;
}
/**
* die_is_signed_type - Check whether a type DIE is signed or not
* @tp_die: a DIE of a type
*
* Get the encoding of @tp_die and return true if the encoding
* is signed.
*/
bool die_is_signed_type(Dwarf_Die *tp_die)
{
Dwarf_Word ret;
if (die_get_attr_udata(tp_die, DW_AT_encoding, &ret))
return false;
return (ret == DW_ATE_signed_char || ret == DW_ATE_signed ||
ret == DW_ATE_signed_fixed);
}
/**
* die_get_data_member_location - Get the data-member offset
* @mb_die: a DIE of a member of a data structure
* @offs: The offset of the member in the data structure
*
* Get the offset of @mb_die in the data structure including @mb_die, and
* stores result offset to @offs. If any error occurs this returns errno.
*/
int die_get_data_member_location(Dwarf_Die *mb_die, Dwarf_Word *offs)
{
Dwarf_Attribute attr;
Dwarf_Op *expr;
size_t nexpr;
int ret;
if (dwarf_attr(mb_die, DW_AT_data_member_location, &attr) == NULL)
return -ENOENT;
if (dwarf_formudata(&attr, offs) != 0) {
/* DW_AT_data_member_location should be DW_OP_plus_uconst */
ret = dwarf_getlocation(&attr, &expr, &nexpr);
if (ret < 0 || nexpr == 0)
return -ENOENT;
if (expr[0].atom != DW_OP_plus_uconst || nexpr != 1) {
pr_debug("Unable to get offset:Unexpected OP %x (%zd)\n",
expr[0].atom, nexpr);
return -ENOTSUP;
}
*offs = (Dwarf_Word)expr[0].number;
}
return 0;
}
/* Get the call file index number in CU DIE */
static int die_get_call_fileno(Dwarf_Die *in_die)
{
Dwarf_Sword idx;
if (die_get_attr_sdata(in_die, DW_AT_call_file, &idx) == 0)
return (int)idx;
else
return -ENOENT;
}
/* Get the declared file index number in CU DIE */
static int die_get_decl_fileno(Dwarf_Die *pdie)
{
Dwarf_Sword idx;
if (die_get_attr_sdata(pdie, DW_AT_decl_file, &idx) == 0)
return (int)idx;
else
return -ENOENT;
}
/**
* die_get_call_file - Get callsite file name of inlined function instance
* @in_die: a DIE of an inlined function instance
*
* Get call-site file name of @in_die. This means from which file the inline
* function is called.
*/
const char *die_get_call_file(Dwarf_Die *in_die)
{
Dwarf_Die cu_die;
Dwarf_Files *files;
int idx;
idx = die_get_call_fileno(in_die);
if (idx < 0 || !dwarf_diecu(in_die, &cu_die, NULL, NULL) ||
dwarf_getsrcfiles(&cu_die, &files, NULL) != 0)
return NULL;
return dwarf_filesrc(files, idx, NULL, NULL);
}
/**
* die_find_child - Generic DIE search function in DIE tree
* @rt_die: a root DIE
* @callback: a callback function
* @data: a user data passed to the callback function
* @die_mem: a buffer for result DIE
*
* Trace DIE tree from @rt_die and call @callback for each child DIE.
* If @callback returns DIE_FIND_CB_END, this stores the DIE into
* @die_mem and returns it. If @callback returns DIE_FIND_CB_CONTINUE,
* this continues to trace the tree. Optionally, @callback can return
* DIE_FIND_CB_CHILD and DIE_FIND_CB_SIBLING, those means trace only
* the children and trace only the siblings respectively.
* Returns NULL if @callback can't find any appropriate DIE.
*/
Dwarf_Die *die_find_child(Dwarf_Die *rt_die,
int (*callback)(Dwarf_Die *, void *),
void *data, Dwarf_Die *die_mem)
{
Dwarf_Die child_die;
int ret;
ret = dwarf_child(rt_die, die_mem);
if (ret != 0)
return NULL;
do {
ret = callback(die_mem, data);
if (ret == DIE_FIND_CB_END)
return die_mem;
if ((ret & DIE_FIND_CB_CHILD) &&
die_find_child(die_mem, callback, data, &child_die)) {
memcpy(die_mem, &child_die, sizeof(Dwarf_Die));
return die_mem;
}
} while ((ret & DIE_FIND_CB_SIBLING) &&
dwarf_siblingof(die_mem, die_mem) == 0);
return NULL;
}
struct __addr_die_search_param {
Dwarf_Addr addr;
Dwarf_Die *die_mem;
};
/* die_find callback for non-inlined function search */
static int __die_search_func_cb(Dwarf_Die *fn_die, void *data)
{
struct __addr_die_search_param *ad = data;
if (dwarf_tag(fn_die) == DW_TAG_subprogram &&
dwarf_haspc(fn_die, ad->addr)) {
memcpy(ad->die_mem, fn_die, sizeof(Dwarf_Die));
return DWARF_CB_ABORT;
}
return DWARF_CB_OK;
}
/**
* die_find_realfunc - Search a non-inlined function at given address
* @cu_die: a CU DIE which including @addr
* @addr: target address
* @die_mem: a buffer for result DIE
*
* Search a non-inlined function DIE which includes @addr. Stores the
* DIE to @die_mem and returns it if found. Returns NULl if failed.
*/
Dwarf_Die *die_find_realfunc(Dwarf_Die *cu_die, Dwarf_Addr addr,
Dwarf_Die *die_mem)
{
struct __addr_die_search_param ad;
ad.addr = addr;
ad.die_mem = die_mem;
/* dwarf_getscopes can't find subprogram. */
if (!dwarf_getfuncs(cu_die, __die_search_func_cb, &ad, 0))
return NULL;
else
return die_mem;
}
/* die_find callback for inline function search */
static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data)
{
Dwarf_Addr *addr = data;
if (dwarf_tag(die_mem) == DW_TAG_inlined_subroutine &&
dwarf_haspc(die_mem, *addr))
return DIE_FIND_CB_END;
return DIE_FIND_CB_CONTINUE;
}
/**
* die_find_inlinefunc - Search an inlined function at given address
* @cu_die: a CU DIE which including @addr
* @addr: target address
* @die_mem: a buffer for result DIE
*
* Search an inlined function DIE which includes @addr. Stores the
* DIE to @die_mem and returns it if found. Returns NULl if failed.
* If several inlined functions are expanded recursively, this trace
* it and returns deepest one.
*/
Dwarf_Die *die_find_inlinefunc(Dwarf_Die *sp_die, Dwarf_Addr addr,
Dwarf_Die *die_mem)
{
Dwarf_Die tmp_die;
sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr, &tmp_die);
if (!sp_die)
return NULL;
/* Inlined function could be recursive. Trace it until fail */
while (sp_die) {
memcpy(die_mem, sp_die, sizeof(Dwarf_Die));
sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr,
&tmp_die);
}
return die_mem;
}
struct __instance_walk_param {
void *addr;
int (*callback)(Dwarf_Die *, void *);
void *data;
int retval;
};
static int __die_walk_instances_cb(Dwarf_Die *inst, void *data)
{
struct __instance_walk_param *iwp = data;
Dwarf_Attribute attr_mem;
Dwarf_Die origin_mem;
Dwarf_Attribute *attr;
Dwarf_Die *origin;
int tmp;
attr = dwarf_attr(inst, DW_AT_abstract_origin, &attr_mem);
if (attr == NULL)
return DIE_FIND_CB_CONTINUE;
origin = dwarf_formref_die(attr, &origin_mem);
if (origin == NULL || origin->addr != iwp->addr)
return DIE_FIND_CB_CONTINUE;
/* Ignore redundant instances */
if (dwarf_tag(inst) == DW_TAG_inlined_subroutine) {
dwarf_decl_line(origin, &tmp);
if (die_get_call_lineno(inst) == tmp) {
tmp = die_get_decl_fileno(origin);
if (die_get_call_fileno(inst) == tmp)
return DIE_FIND_CB_CONTINUE;
}
}
iwp->retval = iwp->callback(inst, iwp->data);
return (iwp->retval) ? DIE_FIND_CB_END : DIE_FIND_CB_CONTINUE;
}
/**
* die_walk_instances - Walk on instances of given DIE
* @or_die: an abstract original DIE
* @callback: a callback function which is called with instance DIE
* @data: user data
*
* Walk on the instances of give @in_die. @in_die must be an inlined function
* declartion. This returns the return value of @callback if it returns
* non-zero value, or -ENOENT if there is no instance.
*/
int die_walk_instances(Dwarf_Die *or_die, int (*callback)(Dwarf_Die *, void *),
void *data)
{
Dwarf_Die cu_die;
Dwarf_Die die_mem;
struct __instance_walk_param iwp = {
.addr = or_die->addr,
.callback = callback,
.data = data,
.retval = -ENOENT,
};
if (dwarf_diecu(or_die, &cu_die, NULL, NULL) == NULL)
return -ENOENT;
die_find_child(&cu_die, __die_walk_instances_cb, &iwp, &die_mem);
return iwp.retval;
}
/* Line walker internal parameters */
struct __line_walk_param {
bool recursive;
line_walk_callback_t callback;
void *data;
int retval;
};
static int __die_walk_funclines_cb(Dwarf_Die *in_die, void *data)
{
struct __line_walk_param *lw = data;
Dwarf_Addr addr = 0;
const char *fname;
int lineno;
if (dwarf_tag(in_die) == DW_TAG_inlined_subroutine) {
fname = die_get_call_file(in_die);
lineno = die_get_call_lineno(in_die);
if (fname && lineno > 0 && dwarf_entrypc(in_die, &addr) == 0) {
lw->retval = lw->callback(fname, lineno, addr, lw->data);
if (lw->retval != 0)
return DIE_FIND_CB_END;
}
}
if (!lw->recursive)
/* Don't need to search recursively */
return DIE_FIND_CB_SIBLING;
if (addr) {
fname = dwarf_decl_file(in_die);
if (fname && dwarf_decl_line(in_die, &lineno) == 0) {
lw->retval = lw->callback(fname, lineno, addr, lw->data);
if (lw->retval != 0)
return DIE_FIND_CB_END;
}
}
/* Continue to search nested inlined function call-sites */
return DIE_FIND_CB_CONTINUE;
}
/* Walk on lines of blocks included in given DIE */
static int __die_walk_funclines(Dwarf_Die *sp_die, bool recursive,
line_walk_callback_t callback, void *data)
{
struct __line_walk_param lw = {
.recursive = recursive,
.callback = callback,
.data = data,
.retval = 0,
};
Dwarf_Die die_mem;
Dwarf_Addr addr;
const char *fname;
int lineno;
/* Handle function declaration line */
fname = dwarf_decl_file(sp_die);
if (fname && dwarf_decl_line(sp_die, &lineno) == 0 &&
dwarf_entrypc(sp_die, &addr) == 0) {
lw.retval = callback(fname, lineno, addr, data);
if (lw.retval != 0)
goto done;
}
die_find_child(sp_die, __die_walk_funclines_cb, &lw, &die_mem);
done:
return lw.retval;
}
static int __die_walk_culines_cb(Dwarf_Die *sp_die, void *data)
{
struct __line_walk_param *lw = data;
lw->retval = __die_walk_funclines(sp_die, true, lw->callback, lw->data);
if (lw->retval != 0)
return DWARF_CB_ABORT;
return DWARF_CB_OK;
}
/**
* die_walk_lines - Walk on lines inside given DIE
* @rt_die: a root DIE (CU, subprogram or inlined_subroutine)
* @callback: callback routine
* @data: user data
*
* Walk on all lines inside given @rt_die and call @callback on each line.
* If the @rt_die is a function, walk only on the lines inside the function,
* otherwise @rt_die must be a CU DIE.
* Note that this walks not only dwarf line list, but also function entries
* and inline call-site.
*/
int die_walk_lines(Dwarf_Die *rt_die, line_walk_callback_t callback, void *data)
{
Dwarf_Lines *lines;
Dwarf_Line *line;
Dwarf_Addr addr;
const char *fname;
int lineno, ret = 0;
Dwarf_Die die_mem, *cu_die;
size_t nlines, i;
/* Get the CU die */
if (dwarf_tag(rt_die) != DW_TAG_compile_unit)
cu_die = dwarf_diecu(rt_die, &die_mem, NULL, NULL);
else
cu_die = rt_die;
if (!cu_die) {
pr_debug2("Failed to get CU from given DIE.\n");
return -EINVAL;
}
/* Get lines list in the CU */
if (dwarf_getsrclines(cu_die, &lines, &nlines) != 0) {
pr_debug2("Failed to get source lines on this CU.\n");
return -ENOENT;
}
pr_debug2("Get %zd lines from this CU\n", nlines);
/* Walk on the lines on lines list */
for (i = 0; i < nlines; i++) {
line = dwarf_onesrcline(lines, i);
if (line == NULL ||
dwarf_lineno(line, &lineno) != 0 ||
dwarf_lineaddr(line, &addr) != 0) {
pr_debug2("Failed to get line info. "
"Possible error in debuginfo.\n");
continue;
}
/* Filter lines based on address */
if (rt_die != cu_die)
/*
* Address filtering
* The line is included in given function, and
* no inline block includes it.
*/
if (!dwarf_haspc(rt_die, addr) ||
die_find_inlinefunc(rt_die, addr, &die_mem))
continue;
/* Get source line */
fname = dwarf_linesrc(line, NULL, NULL);
ret = callback(fname, lineno, addr, data);
if (ret != 0)
return ret;
}
/*
* Dwarf lines doesn't include function declarations and inlined
* subroutines. We have to check functions list or given function.
*/
if (rt_die != cu_die)
/*
* Don't need walk functions recursively, because nested
* inlined functions don't have lines of the specified DIE.
*/
ret = __die_walk_funclines(rt_die, false, callback, data);
else {
struct __line_walk_param param = {
.callback = callback,
.data = data,
.retval = 0,
};
dwarf_getfuncs(cu_die, __die_walk_culines_cb, ¶m, 0);
ret = param.retval;
}
return ret;
}
struct __find_variable_param {
const char *name;
Dwarf_Addr addr;
};
static int __die_find_variable_cb(Dwarf_Die *die_mem, void *data)
{
struct __find_variable_param *fvp = data;
int tag;
tag = dwarf_tag(die_mem);
if ((tag == DW_TAG_formal_parameter ||
tag == DW_TAG_variable) &&
die_compare_name(die_mem, fvp->name))
return DIE_FIND_CB_END;
if (dwarf_haspc(die_mem, fvp->addr))
return DIE_FIND_CB_CONTINUE;
else
return DIE_FIND_CB_SIBLING;
}
/**
* die_find_variable_at - Find a given name variable at given address
* @sp_die: a function DIE
* @name: variable name
* @addr: address
* @die_mem: a buffer for result DIE
*
* Find a variable DIE called @name at @addr in @sp_die.
*/
Dwarf_Die *die_find_variable_at(Dwarf_Die *sp_die, const char *name,
Dwarf_Addr addr, Dwarf_Die *die_mem)
{
struct __find_variable_param fvp = { .name = name, .addr = addr};
return die_find_child(sp_die, __die_find_variable_cb, (void *)&fvp,
die_mem);
}
static int __die_find_member_cb(Dwarf_Die *die_mem, void *data)
{
const char *name = data;
if ((dwarf_tag(die_mem) == DW_TAG_member) &&
die_compare_name(die_mem, name))
return DIE_FIND_CB_END;
return DIE_FIND_CB_SIBLING;
}
/**
* die_find_member - Find a given name member in a data structure
* @st_die: a data structure type DIE
* @name: member name
* @die_mem: a buffer for result DIE
*
* Find a member DIE called @name in @st_die.
*/
Dwarf_Die *die_find_member(Dwarf_Die *st_die, const char *name,
Dwarf_Die *die_mem)
{
return die_find_child(st_die, __die_find_member_cb, (void *)name,
die_mem);
}
/**
* die_get_typename - Get the name of given variable DIE
* @vr_die: a variable DIE
* @buf: a buffer for result type name
* @len: a max-length of @buf
*
* Get the name of @vr_die and stores it to @buf. Return the actual length
* of type name if succeeded. Return -E2BIG if @len is not enough long, and
* Return -ENOENT if failed to find type name.
* Note that the result will stores typedef name if possible, and stores
* "*(function_type)" if the type is a function pointer.
*/
int die_get_typename(Dwarf_Die *vr_die, char *buf, int len)
{
Dwarf_Die type;
int tag, ret, ret2;
const char *tmp = "";
if (__die_get_real_type(vr_die, &type) == NULL)
return -ENOENT;
tag = dwarf_tag(&type);
if (tag == DW_TAG_array_type || tag == DW_TAG_pointer_type)
tmp = "*";
else if (tag == DW_TAG_subroutine_type) {
/* Function pointer */
ret = snprintf(buf, len, "(function_type)");
return (ret >= len) ? -E2BIG : ret;
} else {
if (!dwarf_diename(&type))
return -ENOENT;
if (tag == DW_TAG_union_type)
tmp = "union ";
else if (tag == DW_TAG_structure_type)
tmp = "struct ";
/* Write a base name */
ret = snprintf(buf, len, "%s%s", tmp, dwarf_diename(&type));
return (ret >= len) ? -E2BIG : ret;
}
ret = die_get_typename(&type, buf, len);
if (ret > 0) {
ret2 = snprintf(buf + ret, len - ret, "%s", tmp);
ret = (ret2 >= len - ret) ? -E2BIG : ret2 + ret;
}
return ret;
}
/**
* die_get_varname - Get the name and type of given variable DIE
* @vr_die: a variable DIE
* @buf: a buffer for type and variable name
* @len: the max-length of @buf
*
* Get the name and type of @vr_die and stores it in @buf as "type\tname".
*/
int die_get_varname(Dwarf_Die *vr_die, char *buf, int len)
{
int ret, ret2;
ret = die_get_typename(vr_die, buf, len);
if (ret < 0) {
pr_debug("Failed to get type, make it unknown.\n");
ret = snprintf(buf, len, "(unknown_type)");
}
if (ret > 0) {
ret2 = snprintf(buf + ret, len - ret, "\t%s",
dwarf_diename(vr_die));
ret = (ret2 >= len - ret) ? -E2BIG : ret2 + ret;
}
return ret;
}
| gpl-2.0 |
Soorma07/linux-davinci | drivers/media/video/gspca/gl860/gl860-mi1320.c | 13022 | 18805 | /* Subdriver for the GL860 chip with the MI1320 sensor
* Author Olivier LORIN from own logs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Sensor : MI1320 */
#include "gl860.h"
static struct validx tbl_common[] = {
{0xba00, 0x00f0}, {0xba00, 0x00f1}, {0xba51, 0x0066}, {0xba02, 0x00f1},
{0xba05, 0x0067}, {0xba05, 0x00f1}, {0xbaa0, 0x0065}, {0xba00, 0x00f1},
{0xffff, 0xffff},
{0xba00, 0x00f0}, {0xba02, 0x00f1}, {0xbafa, 0x0028}, {0xba02, 0x00f1},
{0xba00, 0x00f0}, {0xba01, 0x00f1}, {0xbaf0, 0x0006}, {0xba0e, 0x00f1},
{0xba70, 0x0006}, {0xba0e, 0x00f1},
{0xffff, 0xffff},
{0xba74, 0x0006}, {0xba0e, 0x00f1},
{0xffff, 0xffff},
{0x0061, 0x0000}, {0x0068, 0x000d},
};
static struct validx tbl_init_at_startup[] = {
{0x0000, 0x0000}, {0x0010, 0x0010},
{35, 0xffff},
{0x0008, 0x00c0}, {0x0001, 0x00c1}, {0x0001, 0x00c2}, {0x0020, 0x0006},
{0x006a, 0x000d},
};
static struct validx tbl_sensor_settings_common[] = {
{0x0010, 0x0010}, {0x0003, 0x00c1}, {0x0042, 0x00c2}, {0x0040, 0x0000},
{0x006a, 0x0007}, {0x006a, 0x000d}, {0x0063, 0x0006},
};
static struct validx tbl_sensor_settings_1280[] = {
{0xba00, 0x00f0}, {0xba00, 0x00f1}, {0xba5a, 0x0066}, {0xba02, 0x00f1},
{0xba05, 0x0067}, {0xba05, 0x00f1}, {0xba20, 0x0065}, {0xba00, 0x00f1},
};
static struct validx tbl_sensor_settings_800[] = {
{0xba00, 0x00f0}, {0xba00, 0x00f1}, {0xba5a, 0x0066}, {0xba02, 0x00f1},
{0xba05, 0x0067}, {0xba05, 0x00f1}, {0xba20, 0x0065}, {0xba00, 0x00f1},
};
static struct validx tbl_sensor_settings_640[] = {
{0xba00, 0x00f0}, {0xba00, 0x00f1}, {0xbaa0, 0x0065}, {0xba00, 0x00f1},
{0xba51, 0x0066}, {0xba02, 0x00f1}, {0xba05, 0x0067}, {0xba05, 0x00f1},
{0xba20, 0x0065}, {0xba00, 0x00f1},
};
static struct validx tbl_post_unset_alt[] = {
{0xba00, 0x00f0}, {0xba00, 0x00f1}, {0xbaa0, 0x0065}, {0xba00, 0x00f1},
{0x0061, 0x0000}, {0x0068, 0x000d},
};
static u8 *tbl_1280[] = {
"\x0d\x80\xf1\x08\x03\x04\xf1\x00" "\x04\x05\xf1\x02\x05\x00\xf1\xf1"
"\x06\x00\xf1\x0d\x20\x01\xf1\x00" "\x21\x84\xf1\x00\x0d\x00\xf1\x08"
"\xf0\x00\xf1\x01\x34\x00\xf1\x00" "\x9b\x43\xf1\x00\xa6\x05\xf1\x00"
"\xa9\x04\xf1\x00\xa1\x05\xf1\x00" "\xa4\x04\xf1\x00\xae\x0a\xf1\x08"
,
"\xf0\x00\xf1\x02\x3a\x05\xf1\xf1" "\x3c\x05\xf1\xf1\x59\x01\xf1\x47"
"\x5a\x01\xf1\x88\x5c\x0a\xf1\x06" "\x5d\x0e\xf1\x0a\x64\x5e\xf1\x1c"
"\xd2\x00\xf1\xcf\xcb\x00\xf1\x01"
,
"\xd3\x02\xd4\x28\xd5\x01\xd0\x02" "\xd1\x18\xd2\xc1"
};
static u8 *tbl_800[] = {
"\x0d\x80\xf1\x08\x03\x03\xf1\xc0" "\x04\x05\xf1\x02\x05\x00\xf1\xf1"
"\x06\x00\xf1\x0d\x20\x01\xf1\x00" "\x21\x84\xf1\x00\x0d\x00\xf1\x08"
"\xf0\x00\xf1\x01\x34\x00\xf1\x00" "\x9b\x43\xf1\x00\xa6\x05\xf1\x00"
"\xa9\x03\xf1\xc0\xa1\x03\xf1\x20" "\xa4\x02\xf1\x5a\xae\x0a\xf1\x08"
,
"\xf0\x00\xf1\x02\x3a\x05\xf1\xf1" "\x3c\x05\xf1\xf1\x59\x01\xf1\x47"
"\x5a\x01\xf1\x88\x5c\x0a\xf1\x06" "\x5d\x0e\xf1\x0a\x64\x5e\xf1\x1c"
"\xd2\x00\xf1\xcf\xcb\x00\xf1\x01"
,
"\xd3\x02\xd4\x18\xd5\x21\xd0\x02" "\xd1\x10\xd2\x59"
};
static u8 *tbl_640[] = {
"\x0d\x80\xf1\x08\x03\x04\xf1\x04" "\x04\x05\xf1\x02\x07\x01\xf1\x7c"
"\x08\x00\xf1\x0e\x21\x80\xf1\x00" "\x0d\x00\xf1\x08\xf0\x00\xf1\x01"
"\x34\x10\xf1\x10\x3a\x43\xf1\x00" "\xa6\x05\xf1\x02\xa9\x04\xf1\x04"
"\xa7\x02\xf1\x81\xaa\x01\xf1\xe2" "\xae\x0c\xf1\x09"
,
"\xf0\x00\xf1\x02\x39\x03\xf1\xfc" "\x3b\x04\xf1\x04\x57\x01\xf1\xb6"
"\x58\x02\xf1\x0d\x5c\x1f\xf1\x19" "\x5d\x24\xf1\x1e\x64\x5e\xf1\x1c"
"\xd2\x00\xf1\x00\xcb\x00\xf1\x01"
,
"\xd3\x02\xd4\x10\xd5\x81\xd0\x02" "\xd1\x08\xd2\xe1"
};
static s32 tbl_sat[] = {0x25, 0x1d, 0x15, 0x0d, 0x05, 0x4d, 0x55, 0x5d, 0x2d};
static s32 tbl_bright[] = {0, 8, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70};
static s32 tbl_backlight[] = {0x0e, 0x06, 0x02};
static s32 tbl_cntr1[] = {
0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8, 0xc0, 0xc8, 0xd0, 0xe0, 0xf0};
static s32 tbl_cntr2[] = {
0x70, 0x68, 0x60, 0x58, 0x50, 0x48, 0x40, 0x38, 0x30, 0x20, 0x10};
static u8 dat_wbalNL[] =
"\xf0\x00\xf1\x01\x05\x00\xf1\x06" "\x3b\x04\xf1\x2a\x47\x10\xf1\x10"
"\x9d\x3c\xf1\xae\xaf\x10\xf1\x00" "\xf0\x00\xf1\x02\x2f\x91\xf1\x20"
"\x9c\x91\xf1\x20\x37\x03\xf1\x00" "\x9d\xc5\xf1\x0f\xf0\x00\xf1\x00";
static u8 dat_wbalLL[] =
"\xf0\x00\xf1\x01\x05\x00\xf1\x0c" "\x3b\x04\xf1\x2a\x47\x40\xf1\x40"
"\x9d\x20\xf1\xae\xaf\x10\xf1\x00" "\xf0\x00\xf1\x02\x2f\xd1\xf1\x00"
"\x9c\xd1\xf1\x00\x37\x03\xf1\x00" "\x9d\xc5\xf1\x3f\xf0\x00\xf1\x00";
static u8 dat_wbalBL[] =
"\xf0\x00\xf1\x01\x05\x00\xf1\x06" "\x47\x10\xf1\x30\x9d\x3c\xf1\xae"
"\xaf\x10\xf1\x00\xf0\x00\xf1\x02" "\x2f\x91\xf1\x20\x9c\x91\xf1\x20"
"\x37\x03\xf1\x00\x9d\xc5\xf1\x2f" "\xf0\x00\xf1\x00";
static u8 dat_hvflip1[] = {0xf0, 0x00, 0xf1, 0x00};
static u8 dat_common00[] =
"\x00\x01\x07\x6a\x06\x63\x0d\x6a" "\xc0\x00\x10\x10\xc1\x03\xc2\x42"
"\xd8\x04\x58\x00\x04\x02";
static u8 dat_common01[] =
"\x0d\x00\xf1\x0b\x0d\x00\xf1\x08" "\x35\x00\xf1\x22\x68\x00\xf1\x5d"
"\xf0\x00\xf1\x01\x06\x70\xf1\x0e" "\xf0\x00\xf1\x02\xdd\x18\xf1\xe0";
static u8 dat_common02[] =
"\x05\x01\xf1\x84\x06\x00\xf1\x44" "\x07\x00\xf1\xbe\x08\x00\xf1\x1e"
"\x20\x01\xf1\x03\x21\x84\xf1\x00" "\x22\x0d\xf1\x0f\x24\x80\xf1\x00"
"\x34\x18\xf1\x2d\x35\x00\xf1\x22" "\x43\x83\xf1\x83\x59\x00\xf1\xff";
static u8 dat_common03[] =
"\xf0\x00\xf1\x02\x39\x06\xf1\x8c" "\x3a\x06\xf1\x8c\x3b\x03\xf1\xda"
"\x3c\x05\xf1\x30\x57\x01\xf1\x0c" "\x58\x01\xf1\x42\x59\x01\xf1\x0c"
"\x5a\x01\xf1\x42\x5c\x13\xf1\x0e" "\x5d\x17\xf1\x12\x64\x1e\xf1\x1c";
static u8 dat_common04[] =
"\xf0\x00\xf1\x02\x24\x5f\xf1\x20" "\x28\xea\xf1\x02\x5f\x41\xf1\x43";
static u8 dat_common05[] =
"\x02\x00\xf1\xee\x03\x29\xf1\x1a" "\x04\x02\xf1\xa4\x09\x00\xf1\x68"
"\x0a\x00\xf1\x2a\x0b\x00\xf1\x04" "\x0c\x00\xf1\x93\x0d\x00\xf1\x82"
"\x0e\x00\xf1\x40\x0f\x00\xf1\x5f" "\x10\x00\xf1\x4e\x11\x00\xf1\x5b";
static u8 dat_common06[] =
"\x15\x00\xf1\xc9\x16\x00\xf1\x5e" "\x17\x00\xf1\x9d\x18\x00\xf1\x06"
"\x19\x00\xf1\x89\x1a\x00\xf1\x12" "\x1b\x00\xf1\xa1\x1c\x00\xf1\xe4"
"\x1d\x00\xf1\x7a\x1e\x00\xf1\x64" "\xf6\x00\xf1\x5f";
static u8 dat_common07[] =
"\xf0\x00\xf1\x01\x53\x09\xf1\x03" "\x54\x3d\xf1\x1c\x55\x99\xf1\x72"
"\x56\xc1\xf1\xb1\x57\xd8\xf1\xce" "\x58\xe0\xf1\x00\xdc\x0a\xf1\x03"
"\xdd\x45\xf1\x20\xde\xae\xf1\x82" "\xdf\xdc\xf1\xc9\xe0\xf6\xf1\xea"
"\xe1\xff\xf1\x00";
static u8 dat_common08[] =
"\xf0\x00\xf1\x01\x80\x00\xf1\x06" "\x81\xf6\xf1\x08\x82\xfb\xf1\xf7"
"\x83\x00\xf1\xfe\xb6\x07\xf1\x03" "\xb7\x18\xf1\x0c\x84\xfb\xf1\x06"
"\x85\xfb\xf1\xf9\x86\x00\xf1\xff" "\xb8\x07\xf1\x04\xb9\x16\xf1\x0a";
static u8 dat_common09[] =
"\x87\xfa\xf1\x05\x88\xfc\xf1\xf9" "\x89\x00\xf1\xff\xba\x06\xf1\x03"
"\xbb\x17\xf1\x09\x8a\xe8\xf1\x14" "\x8b\xf7\xf1\xf0\x8c\xfd\xf1\xfa"
"\x8d\x00\xf1\x00\xbc\x05\xf1\x01" "\xbd\x0c\xf1\x08\xbe\x00\xf1\x14";
static u8 dat_common10[] =
"\x8e\xea\xf1\x13\x8f\xf7\xf1\xf2" "\x90\xfd\xf1\xfa\x91\x00\xf1\x00"
"\xbf\x05\xf1\x01\xc0\x0a\xf1\x08" "\xc1\x00\xf1\x0c\x92\xed\xf1\x0f"
"\x93\xf9\xf1\xf4\x94\xfe\xf1\xfb" "\x95\x00\xf1\x00\xc2\x04\xf1\x01"
"\xc3\x0a\xf1\x07\xc4\x00\xf1\x10";
static u8 dat_common11[] =
"\xf0\x00\xf1\x01\x05\x00\xf1\x06" "\x25\x00\xf1\x55\x34\x10\xf1\x10"
"\x35\xf0\xf1\x10\x3a\x02\xf1\x03" "\x3b\x04\xf1\x2a\x9b\x43\xf1\x00"
"\xa4\x03\xf1\xc0\xa7\x02\xf1\x81";
static int mi1320_init_at_startup(struct gspca_dev *gspca_dev);
static int mi1320_configure_alt(struct gspca_dev *gspca_dev);
static int mi1320_init_pre_alt(struct gspca_dev *gspca_dev);
static int mi1320_init_post_alt(struct gspca_dev *gspca_dev);
static void mi1320_post_unset_alt(struct gspca_dev *gspca_dev);
static int mi1320_sensor_settings(struct gspca_dev *gspca_dev);
static int mi1320_camera_settings(struct gspca_dev *gspca_dev);
/*==========================================================================*/
void mi1320_init_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->vcur.backlight = 0;
sd->vcur.brightness = 0;
sd->vcur.sharpness = 6;
sd->vcur.contrast = 10;
sd->vcur.gamma = 20;
sd->vcur.hue = 0;
sd->vcur.saturation = 6;
sd->vcur.whitebal = 0;
sd->vcur.mirror = 0;
sd->vcur.flip = 0;
sd->vcur.AC50Hz = 1;
sd->vmax.backlight = 2;
sd->vmax.brightness = 8;
sd->vmax.sharpness = 7;
sd->vmax.contrast = 0; /* 10 but not working with this driver */
sd->vmax.gamma = 40;
sd->vmax.hue = 5 + 1;
sd->vmax.saturation = 8;
sd->vmax.whitebal = 2;
sd->vmax.mirror = 1;
sd->vmax.flip = 1;
sd->vmax.AC50Hz = 1;
sd->dev_camera_settings = mi1320_camera_settings;
sd->dev_init_at_startup = mi1320_init_at_startup;
sd->dev_configure_alt = mi1320_configure_alt;
sd->dev_init_pre_alt = mi1320_init_pre_alt;
sd->dev_post_unset_alt = mi1320_post_unset_alt;
}
/*==========================================================================*/
static void common(struct gspca_dev *gspca_dev)
{
s32 n; /* reserved for FETCH functions */
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200, 22, dat_common00);
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x0000, 0, NULL);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 32, dat_common01);
n = fetch_validx(gspca_dev, tbl_common, ARRAY_SIZE(tbl_common));
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 48, dat_common02);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 48, dat_common03);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 16, dat_common04);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 48, dat_common05);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 44, dat_common06);
keep_on_fetching_validx(gspca_dev, tbl_common,
ARRAY_SIZE(tbl_common), n);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 52, dat_common07);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 48, dat_common08);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 48, dat_common09);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 56, dat_common10);
keep_on_fetching_validx(gspca_dev, tbl_common,
ARRAY_SIZE(tbl_common), n);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 40, dat_common11);
keep_on_fetching_validx(gspca_dev, tbl_common,
ARRAY_SIZE(tbl_common), n);
}
static int mi1320_init_at_startup(struct gspca_dev *gspca_dev)
{
fetch_validx(gspca_dev, tbl_init_at_startup,
ARRAY_SIZE(tbl_init_at_startup));
common(gspca_dev);
/* ctrl_out(gspca_dev, 0x40, 11, 0x0000, 0x0000, 0, NULL); */
return 0;
}
static int mi1320_init_pre_alt(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->mirrorMask = 0;
sd->vold.backlight = -1;
sd->vold.brightness = -1;
sd->vold.sharpness = -1;
sd->vold.contrast = -1;
sd->vold.saturation = -1;
sd->vold.gamma = -1;
sd->vold.hue = -1;
sd->vold.whitebal = -1;
sd->vold.mirror = -1;
sd->vold.flip = -1;
sd->vold.AC50Hz = -1;
common(gspca_dev);
mi1320_sensor_settings(gspca_dev);
mi1320_init_post_alt(gspca_dev);
return 0;
}
static int mi1320_init_post_alt(struct gspca_dev *gspca_dev)
{
mi1320_camera_settings(gspca_dev);
return 0;
}
static int mi1320_sensor_settings(struct gspca_dev *gspca_dev)
{
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
ctrl_out(gspca_dev, 0x40, 5, 0x0001, 0x0000, 0, NULL);
fetch_validx(gspca_dev, tbl_sensor_settings_common,
ARRAY_SIZE(tbl_sensor_settings_common));
switch (reso) {
case IMAGE_1280:
fetch_validx(gspca_dev, tbl_sensor_settings_1280,
ARRAY_SIZE(tbl_sensor_settings_1280));
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 64, tbl_1280[0]);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 40, tbl_1280[1]);
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200, 12, tbl_1280[2]);
break;
case IMAGE_800:
fetch_validx(gspca_dev, tbl_sensor_settings_800,
ARRAY_SIZE(tbl_sensor_settings_800));
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 64, tbl_800[0]);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 40, tbl_800[1]);
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200, 12, tbl_800[2]);
break;
default:
fetch_validx(gspca_dev, tbl_sensor_settings_640,
ARRAY_SIZE(tbl_sensor_settings_640));
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 60, tbl_640[0]);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 40, tbl_640[1]);
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200, 12, tbl_640[2]);
break;
}
return 0;
}
static int mi1320_configure_alt(struct gspca_dev *gspca_dev)
{
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
switch (reso) {
case IMAGE_640:
gspca_dev->alt = 3 + 1;
break;
case IMAGE_800:
case IMAGE_1280:
gspca_dev->alt = 1 + 1;
break;
}
return 0;
}
static int mi1320_camera_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 backlight = sd->vcur.backlight;
s32 bright = sd->vcur.brightness;
s32 sharp = sd->vcur.sharpness;
s32 cntr = sd->vcur.contrast;
s32 gam = sd->vcur.gamma;
s32 hue = sd->vcur.hue;
s32 sat = sd->vcur.saturation;
s32 wbal = sd->vcur.whitebal;
s32 mirror = (((sd->vcur.mirror > 0) ^ sd->mirrorMask) > 0);
s32 flip = (((sd->vcur.flip > 0) ^ sd->mirrorMask) > 0);
s32 freq = (sd->vcur.AC50Hz > 0);
s32 i;
if (freq != sd->vold.AC50Hz) {
sd->vold.AC50Hz = freq;
freq = 2 * (freq == 0);
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba02, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 , 0x005b, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01 + freq, 0x00f1, 0, NULL);
}
if (wbal != sd->vold.whitebal) {
sd->vold.whitebal = wbal;
if (wbal < 0 || wbal > sd->vmax.whitebal)
wbal = 0;
for (i = 0; i < 2; i++) {
if (wbal == 0) { /* Normal light */
ctrl_out(gspca_dev, 0x40, 1,
0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0003, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0042, 0x00c2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 3,
0xba00, 0x0200, 48, dat_wbalNL);
}
if (wbal == 1) { /* Low light */
ctrl_out(gspca_dev, 0x40, 1,
0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0004, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0043, 0x00c2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 3,
0xba00, 0x0200, 48, dat_wbalLL);
}
if (wbal == 2) { /* Back light */
ctrl_out(gspca_dev, 0x40, 1,
0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0003, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1,
0x0042, 0x00c2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 3,
0xba00, 0x0200, 44, dat_wbalBL);
}
}
}
if (bright != sd->vold.brightness) {
sd->vold.brightness = bright;
if (bright < 0 || bright > sd->vmax.brightness)
bright = 0;
bright = tbl_bright[bright];
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + bright, 0x0034, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + bright, 0x00f1, 0, NULL);
}
if (sat != sd->vold.saturation) {
sd->vold.saturation = sat;
if (sat < 0 || sat > sd->vmax.saturation)
sat = 0;
sat = tbl_sat[sat];
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 , 0x0025, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + sat, 0x00f1, 0, NULL);
}
if (sharp != sd->vold.sharpness) {
sd->vold.sharpness = sharp;
if (sharp < 0 || sharp > sd->vmax.sharpness)
sharp = 0;
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 , 0x0005, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + sharp, 0x00f1, 0, NULL);
}
if (hue != sd->vold.hue) {
/* 0=normal 1=NB 2="sepia" 3=negative 4=other 5=other2 */
if (hue < 0 || hue > sd->vmax.hue)
hue = 0;
if (hue == sd->vmax.hue)
sd->swapRB = 1;
else
sd->swapRB = 0;
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba70, 0x00e2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + hue * (hue < 6), 0x00f1,
0, NULL);
}
if (backlight != sd->vold.backlight) {
sd->vold.backlight = backlight;
if (backlight < 0 || backlight > sd->vmax.backlight)
backlight = 0;
backlight = tbl_backlight[backlight];
for (i = 0; i < 2; i++) {
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba74, 0x0006, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba80 + backlight, 0x00f1,
0, NULL);
}
}
if (hue != sd->vold.hue) {
sd->vold.hue = hue;
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba70, 0x00e2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + hue * (hue < 6), 0x00f1,
0, NULL);
}
if (mirror != sd->vold.mirror || flip != sd->vold.flip) {
u8 dat_hvflip2[4] = {0x20, 0x01, 0xf1, 0x00};
sd->vold.mirror = mirror;
sd->vold.flip = flip;
dat_hvflip2[3] = flip + 2 * mirror;
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 4, dat_hvflip1);
ctrl_out(gspca_dev, 0x40, 3, 0xba00, 0x0200, 4, dat_hvflip2);
}
if (gam != sd->vold.gamma) {
sd->vold.gamma = gam;
if (gam < 0 || gam > sd->vmax.gamma)
gam = 0;
gam = 2 * gam;
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba04 , 0x003b, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba02 + gam, 0x00f1, 0, NULL);
}
if (cntr != sd->vold.contrast) {
sd->vold.contrast = cntr;
if (cntr < 0 || cntr > sd->vmax.contrast)
cntr = 0;
ctrl_out(gspca_dev, 0x40, 1, 0xba00, 0x00f0, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba01, 0x00f1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + tbl_cntr1[cntr], 0x0035,
0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0xba00 + tbl_cntr2[cntr], 0x00f1,
0, NULL);
}
return 0;
}
static void mi1320_post_unset_alt(struct gspca_dev *gspca_dev)
{
ctrl_out(gspca_dev, 0x40, 5, 0x0000, 0x0000, 0, NULL);
fetch_validx(gspca_dev, tbl_post_unset_alt,
ARRAY_SIZE(tbl_post_unset_alt));
}
| gpl-2.0 |
PRJosh/kernel_msm | arch/sparc/mm/extable.c | 13534 | 2252 | /*
* linux/arch/sparc/mm/extable.c
*/
#include <linux/module.h>
#include <asm/uaccess.h>
void sort_extable(struct exception_table_entry *start,
struct exception_table_entry *finish)
{
}
/* Caller knows they are in a range if ret->fixup == 0 */
const struct exception_table_entry *
search_extable(const struct exception_table_entry *start,
const struct exception_table_entry *last,
unsigned long value)
{
const struct exception_table_entry *walk;
/* Single insn entries are encoded as:
* word 1: insn address
* word 2: fixup code address
*
* Range entries are encoded as:
* word 1: first insn address
* word 2: 0
* word 3: last insn address + 4 bytes
* word 4: fixup code address
*
* Deleted entries are encoded as:
* word 1: unused
* word 2: -1
*
* See asm/uaccess.h for more details.
*/
/* 1. Try to find an exact match. */
for (walk = start; walk <= last; walk++) {
if (walk->fixup == 0) {
/* A range entry, skip both parts. */
walk++;
continue;
}
/* A deleted entry; see trim_init_extable */
if (walk->fixup == -1)
continue;
if (walk->insn == value)
return walk;
}
/* 2. Try to find a range match. */
for (walk = start; walk <= (last - 1); walk++) {
if (walk->fixup)
continue;
if (walk[0].insn <= value && walk[1].insn > value)
return walk;
walk++;
}
return NULL;
}
#ifdef CONFIG_MODULES
/* We could memmove them around; easier to mark the trimmed ones. */
void trim_init_extable(struct module *m)
{
unsigned int i;
bool range;
for (i = 0; i < m->num_exentries; i += range ? 2 : 1) {
range = m->extable[i].fixup == 0;
if (within_module_init(m->extable[i].insn, m)) {
m->extable[i].fixup = -1;
if (range)
m->extable[i+1].fixup = -1;
}
if (range)
i++;
}
}
#endif /* CONFIG_MODULES */
/* Special extable search, which handles ranges. Returns fixup */
unsigned long search_extables_range(unsigned long addr, unsigned long *g2)
{
const struct exception_table_entry *entry;
entry = search_exception_tables(addr);
if (!entry)
return 0;
/* Inside range? Fix g2 and return correct fixup */
if (!entry->fixup) {
*g2 = (addr - entry->insn) / 4;
return (entry + 1)->fixup;
}
return entry->fixup;
}
| gpl-2.0 |
rettigs/linux-yocto-3.14 | drivers/s390/net/lcs.c | 479 | 63667 | /*
* Linux for S/390 Lan Channel Station Network Driver
*
* Copyright IBM Corp. 1999, 2009
* Author(s): Original Code written by
* DJ Barrow <djbarrow@de.ibm.com,barrow_dj@yahoo.com>
* Rewritten by
* Frank Pavlic <fpavlic@de.ibm.com> and
* Martin Schwidefsky <schwidefsky@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define KMSG_COMPONENT "lcs"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/fddidevice.h>
#include <linux/inetdevice.h>
#include <linux/in.h>
#include <linux/igmp.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <net/arp.h>
#include <net/ip.h>
#include <asm/debug.h>
#include <asm/idals.h>
#include <asm/timex.h>
#include <linux/device.h>
#include <asm/ccwgroup.h>
#include "lcs.h"
#if !defined(CONFIG_ETHERNET) && !defined(CONFIG_FDDI)
#error Cannot compile lcs.c without some net devices switched on.
#endif
/**
* initialization string for output
*/
static char version[] __initdata = "LCS driver";
/**
* the root device for lcs group devices
*/
static struct device *lcs_root_dev;
/**
* Some prototypes.
*/
static void lcs_tasklet(unsigned long);
static void lcs_start_kernel_thread(struct work_struct *);
static void lcs_get_frames_cb(struct lcs_channel *, struct lcs_buffer *);
#ifdef CONFIG_IP_MULTICAST
static int lcs_send_delipm(struct lcs_card *, struct lcs_ipm_list *);
#endif /* CONFIG_IP_MULTICAST */
static int lcs_recovery(void *ptr);
/**
* Debug Facility Stuff
*/
static char debug_buffer[255];
static debug_info_t *lcs_dbf_setup;
static debug_info_t *lcs_dbf_trace;
/**
* LCS Debug Facility functions
*/
static void
lcs_unregister_debug_facility(void)
{
if (lcs_dbf_setup)
debug_unregister(lcs_dbf_setup);
if (lcs_dbf_trace)
debug_unregister(lcs_dbf_trace);
}
static int
lcs_register_debug_facility(void)
{
lcs_dbf_setup = debug_register("lcs_setup", 2, 1, 8);
lcs_dbf_trace = debug_register("lcs_trace", 4, 1, 8);
if (lcs_dbf_setup == NULL || lcs_dbf_trace == NULL) {
pr_err("Not enough memory for debug facility.\n");
lcs_unregister_debug_facility();
return -ENOMEM;
}
debug_register_view(lcs_dbf_setup, &debug_hex_ascii_view);
debug_set_level(lcs_dbf_setup, 2);
debug_register_view(lcs_dbf_trace, &debug_hex_ascii_view);
debug_set_level(lcs_dbf_trace, 2);
return 0;
}
/**
* Allocate io buffers.
*/
static int
lcs_alloc_channel(struct lcs_channel *channel)
{
int cnt;
LCS_DBF_TEXT(2, setup, "ichalloc");
for (cnt = 0; cnt < LCS_NUM_BUFFS; cnt++) {
/* alloc memory fo iobuffer */
channel->iob[cnt].data =
kzalloc(LCS_IOBUFFERSIZE, GFP_DMA | GFP_KERNEL);
if (channel->iob[cnt].data == NULL)
break;
channel->iob[cnt].state = LCS_BUF_STATE_EMPTY;
}
if (cnt < LCS_NUM_BUFFS) {
/* Not all io buffers could be allocated. */
LCS_DBF_TEXT(2, setup, "echalloc");
while (cnt-- > 0)
kfree(channel->iob[cnt].data);
return -ENOMEM;
}
return 0;
}
/**
* Free io buffers.
*/
static void
lcs_free_channel(struct lcs_channel *channel)
{
int cnt;
LCS_DBF_TEXT(2, setup, "ichfree");
for (cnt = 0; cnt < LCS_NUM_BUFFS; cnt++) {
kfree(channel->iob[cnt].data);
channel->iob[cnt].data = NULL;
}
}
/*
* Cleanup channel.
*/
static void
lcs_cleanup_channel(struct lcs_channel *channel)
{
LCS_DBF_TEXT(3, setup, "cleanch");
/* Kill write channel tasklets. */
tasklet_kill(&channel->irq_tasklet);
/* Free channel buffers. */
lcs_free_channel(channel);
}
/**
* LCS free memory for card and channels.
*/
static void
lcs_free_card(struct lcs_card *card)
{
LCS_DBF_TEXT(2, setup, "remcard");
LCS_DBF_HEX(2, setup, &card, sizeof(void*));
kfree(card);
}
/**
* LCS alloc memory for card and channels
*/
static struct lcs_card *
lcs_alloc_card(void)
{
struct lcs_card *card;
int rc;
LCS_DBF_TEXT(2, setup, "alloclcs");
card = kzalloc(sizeof(struct lcs_card), GFP_KERNEL | GFP_DMA);
if (card == NULL)
return NULL;
card->lan_type = LCS_FRAME_TYPE_AUTO;
card->pkt_seq = 0;
card->lancmd_timeout = LCS_LANCMD_TIMEOUT_DEFAULT;
/* Allocate io buffers for the read channel. */
rc = lcs_alloc_channel(&card->read);
if (rc){
LCS_DBF_TEXT(2, setup, "iccwerr");
lcs_free_card(card);
return NULL;
}
/* Allocate io buffers for the write channel. */
rc = lcs_alloc_channel(&card->write);
if (rc) {
LCS_DBF_TEXT(2, setup, "iccwerr");
lcs_cleanup_channel(&card->read);
lcs_free_card(card);
return NULL;
}
#ifdef CONFIG_IP_MULTICAST
INIT_LIST_HEAD(&card->ipm_list);
#endif
LCS_DBF_HEX(2, setup, &card, sizeof(void*));
return card;
}
/*
* Setup read channel.
*/
static void
lcs_setup_read_ccws(struct lcs_card *card)
{
int cnt;
LCS_DBF_TEXT(2, setup, "ireadccw");
/* Setup read ccws. */
memset(card->read.ccws, 0, sizeof (struct ccw1) * (LCS_NUM_BUFFS + 1));
for (cnt = 0; cnt < LCS_NUM_BUFFS; cnt++) {
card->read.ccws[cnt].cmd_code = LCS_CCW_READ;
card->read.ccws[cnt].count = LCS_IOBUFFERSIZE;
card->read.ccws[cnt].flags =
CCW_FLAG_CC | CCW_FLAG_SLI | CCW_FLAG_PCI;
/*
* Note: we have allocated the buffer with GFP_DMA, so
* we do not need to do set_normalized_cda.
*/
card->read.ccws[cnt].cda =
(__u32) __pa(card->read.iob[cnt].data);
((struct lcs_header *)
card->read.iob[cnt].data)->offset = LCS_ILLEGAL_OFFSET;
card->read.iob[cnt].callback = lcs_get_frames_cb;
card->read.iob[cnt].state = LCS_BUF_STATE_READY;
card->read.iob[cnt].count = LCS_IOBUFFERSIZE;
}
card->read.ccws[0].flags &= ~CCW_FLAG_PCI;
card->read.ccws[LCS_NUM_BUFFS - 1].flags &= ~CCW_FLAG_PCI;
card->read.ccws[LCS_NUM_BUFFS - 1].flags |= CCW_FLAG_SUSPEND;
/* Last ccw is a tic (transfer in channel). */
card->read.ccws[LCS_NUM_BUFFS].cmd_code = LCS_CCW_TRANSFER;
card->read.ccws[LCS_NUM_BUFFS].cda =
(__u32) __pa(card->read.ccws);
/* Setg initial state of the read channel. */
card->read.state = LCS_CH_STATE_INIT;
card->read.io_idx = 0;
card->read.buf_idx = 0;
}
static void
lcs_setup_read(struct lcs_card *card)
{
LCS_DBF_TEXT(3, setup, "initread");
lcs_setup_read_ccws(card);
/* Initialize read channel tasklet. */
card->read.irq_tasklet.data = (unsigned long) &card->read;
card->read.irq_tasklet.func = lcs_tasklet;
/* Initialize waitqueue. */
init_waitqueue_head(&card->read.wait_q);
}
/*
* Setup write channel.
*/
static void
lcs_setup_write_ccws(struct lcs_card *card)
{
int cnt;
LCS_DBF_TEXT(3, setup, "iwritccw");
/* Setup write ccws. */
memset(card->write.ccws, 0, sizeof(struct ccw1) * (LCS_NUM_BUFFS + 1));
for (cnt = 0; cnt < LCS_NUM_BUFFS; cnt++) {
card->write.ccws[cnt].cmd_code = LCS_CCW_WRITE;
card->write.ccws[cnt].count = 0;
card->write.ccws[cnt].flags =
CCW_FLAG_SUSPEND | CCW_FLAG_CC | CCW_FLAG_SLI;
/*
* Note: we have allocated the buffer with GFP_DMA, so
* we do not need to do set_normalized_cda.
*/
card->write.ccws[cnt].cda =
(__u32) __pa(card->write.iob[cnt].data);
}
/* Last ccw is a tic (transfer in channel). */
card->write.ccws[LCS_NUM_BUFFS].cmd_code = LCS_CCW_TRANSFER;
card->write.ccws[LCS_NUM_BUFFS].cda =
(__u32) __pa(card->write.ccws);
/* Set initial state of the write channel. */
card->read.state = LCS_CH_STATE_INIT;
card->write.io_idx = 0;
card->write.buf_idx = 0;
}
static void
lcs_setup_write(struct lcs_card *card)
{
LCS_DBF_TEXT(3, setup, "initwrit");
lcs_setup_write_ccws(card);
/* Initialize write channel tasklet. */
card->write.irq_tasklet.data = (unsigned long) &card->write;
card->write.irq_tasklet.func = lcs_tasklet;
/* Initialize waitqueue. */
init_waitqueue_head(&card->write.wait_q);
}
static void
lcs_set_allowed_threads(struct lcs_card *card, unsigned long threads)
{
unsigned long flags;
spin_lock_irqsave(&card->mask_lock, flags);
card->thread_allowed_mask = threads;
spin_unlock_irqrestore(&card->mask_lock, flags);
wake_up(&card->wait_q);
}
static inline int
lcs_threads_running(struct lcs_card *card, unsigned long threads)
{
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&card->mask_lock, flags);
rc = (card->thread_running_mask & threads);
spin_unlock_irqrestore(&card->mask_lock, flags);
return rc;
}
static int
lcs_wait_for_threads(struct lcs_card *card, unsigned long threads)
{
return wait_event_interruptible(card->wait_q,
lcs_threads_running(card, threads) == 0);
}
static inline int
lcs_set_thread_start_bit(struct lcs_card *card, unsigned long thread)
{
unsigned long flags;
spin_lock_irqsave(&card->mask_lock, flags);
if ( !(card->thread_allowed_mask & thread) ||
(card->thread_start_mask & thread) ) {
spin_unlock_irqrestore(&card->mask_lock, flags);
return -EPERM;
}
card->thread_start_mask |= thread;
spin_unlock_irqrestore(&card->mask_lock, flags);
return 0;
}
static void
lcs_clear_thread_running_bit(struct lcs_card *card, unsigned long thread)
{
unsigned long flags;
spin_lock_irqsave(&card->mask_lock, flags);
card->thread_running_mask &= ~thread;
spin_unlock_irqrestore(&card->mask_lock, flags);
wake_up(&card->wait_q);
}
static inline int
__lcs_do_run_thread(struct lcs_card *card, unsigned long thread)
{
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&card->mask_lock, flags);
if (card->thread_start_mask & thread){
if ((card->thread_allowed_mask & thread) &&
!(card->thread_running_mask & thread)){
rc = 1;
card->thread_start_mask &= ~thread;
card->thread_running_mask |= thread;
} else
rc = -EPERM;
}
spin_unlock_irqrestore(&card->mask_lock, flags);
return rc;
}
static int
lcs_do_run_thread(struct lcs_card *card, unsigned long thread)
{
int rc = 0;
wait_event(card->wait_q,
(rc = __lcs_do_run_thread(card, thread)) >= 0);
return rc;
}
static int
lcs_do_start_thread(struct lcs_card *card, unsigned long thread)
{
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&card->mask_lock, flags);
LCS_DBF_TEXT_(4, trace, " %02x%02x%02x",
(u8) card->thread_start_mask,
(u8) card->thread_allowed_mask,
(u8) card->thread_running_mask);
rc = (card->thread_start_mask & thread);
spin_unlock_irqrestore(&card->mask_lock, flags);
return rc;
}
/**
* Initialize channels,card and state machines.
*/
static void
lcs_setup_card(struct lcs_card *card)
{
LCS_DBF_TEXT(2, setup, "initcard");
LCS_DBF_HEX(2, setup, &card, sizeof(void*));
lcs_setup_read(card);
lcs_setup_write(card);
/* Set cards initial state. */
card->state = DEV_STATE_DOWN;
card->tx_buffer = NULL;
card->tx_emitted = 0;
init_waitqueue_head(&card->wait_q);
spin_lock_init(&card->lock);
spin_lock_init(&card->ipm_lock);
spin_lock_init(&card->mask_lock);
#ifdef CONFIG_IP_MULTICAST
INIT_LIST_HEAD(&card->ipm_list);
#endif
INIT_LIST_HEAD(&card->lancmd_waiters);
}
static inline void
lcs_clear_multicast_list(struct lcs_card *card)
{
#ifdef CONFIG_IP_MULTICAST
struct lcs_ipm_list *ipm;
unsigned long flags;
/* Free multicast list. */
LCS_DBF_TEXT(3, setup, "clmclist");
spin_lock_irqsave(&card->ipm_lock, flags);
while (!list_empty(&card->ipm_list)){
ipm = list_entry(card->ipm_list.next,
struct lcs_ipm_list, list);
list_del(&ipm->list);
if (ipm->ipm_state != LCS_IPM_STATE_SET_REQUIRED){
spin_unlock_irqrestore(&card->ipm_lock, flags);
lcs_send_delipm(card, ipm);
spin_lock_irqsave(&card->ipm_lock, flags);
}
kfree(ipm);
}
spin_unlock_irqrestore(&card->ipm_lock, flags);
#endif
}
/**
* Cleanup channels,card and state machines.
*/
static void
lcs_cleanup_card(struct lcs_card *card)
{
LCS_DBF_TEXT(3, setup, "cleancrd");
LCS_DBF_HEX(2,setup,&card,sizeof(void*));
if (card->dev != NULL)
free_netdev(card->dev);
/* Cleanup channels. */
lcs_cleanup_channel(&card->write);
lcs_cleanup_channel(&card->read);
}
/**
* Start channel.
*/
static int
lcs_start_channel(struct lcs_channel *channel)
{
unsigned long flags;
int rc;
LCS_DBF_TEXT_(4, trace,"ssch%s", dev_name(&channel->ccwdev->dev));
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
rc = ccw_device_start(channel->ccwdev,
channel->ccws + channel->io_idx, 0, 0,
DOIO_DENY_PREFETCH | DOIO_ALLOW_SUSPEND);
if (rc == 0)
channel->state = LCS_CH_STATE_RUNNING;
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
if (rc) {
LCS_DBF_TEXT_(4,trace,"essh%s",
dev_name(&channel->ccwdev->dev));
dev_err(&channel->ccwdev->dev,
"Starting an LCS device resulted in an error,"
" rc=%d!\n", rc);
}
return rc;
}
static int
lcs_clear_channel(struct lcs_channel *channel)
{
unsigned long flags;
int rc;
LCS_DBF_TEXT(4,trace,"clearch");
LCS_DBF_TEXT_(4, trace, "%s", dev_name(&channel->ccwdev->dev));
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
rc = ccw_device_clear(channel->ccwdev, (addr_t) channel);
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
if (rc) {
LCS_DBF_TEXT_(4, trace, "ecsc%s",
dev_name(&channel->ccwdev->dev));
return rc;
}
wait_event(channel->wait_q, (channel->state == LCS_CH_STATE_CLEARED));
channel->state = LCS_CH_STATE_STOPPED;
return rc;
}
/**
* Stop channel.
*/
static int
lcs_stop_channel(struct lcs_channel *channel)
{
unsigned long flags;
int rc;
if (channel->state == LCS_CH_STATE_STOPPED)
return 0;
LCS_DBF_TEXT(4,trace,"haltsch");
LCS_DBF_TEXT_(4, trace, "%s", dev_name(&channel->ccwdev->dev));
channel->state = LCS_CH_STATE_INIT;
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
rc = ccw_device_halt(channel->ccwdev, (addr_t) channel);
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
if (rc) {
LCS_DBF_TEXT_(4, trace, "ehsc%s",
dev_name(&channel->ccwdev->dev));
return rc;
}
/* Asynchronous halt initialted. Wait for its completion. */
wait_event(channel->wait_q, (channel->state == LCS_CH_STATE_HALTED));
lcs_clear_channel(channel);
return 0;
}
/**
* start read and write channel
*/
static int
lcs_start_channels(struct lcs_card *card)
{
int rc;
LCS_DBF_TEXT(2, trace, "chstart");
/* start read channel */
rc = lcs_start_channel(&card->read);
if (rc)
return rc;
/* start write channel */
rc = lcs_start_channel(&card->write);
if (rc)
lcs_stop_channel(&card->read);
return rc;
}
/**
* stop read and write channel
*/
static int
lcs_stop_channels(struct lcs_card *card)
{
LCS_DBF_TEXT(2, trace, "chhalt");
lcs_stop_channel(&card->read);
lcs_stop_channel(&card->write);
return 0;
}
/**
* Get empty buffer.
*/
static struct lcs_buffer *
__lcs_get_buffer(struct lcs_channel *channel)
{
int index;
LCS_DBF_TEXT(5, trace, "_getbuff");
index = channel->io_idx;
do {
if (channel->iob[index].state == LCS_BUF_STATE_EMPTY) {
channel->iob[index].state = LCS_BUF_STATE_LOCKED;
return channel->iob + index;
}
index = (index + 1) & (LCS_NUM_BUFFS - 1);
} while (index != channel->io_idx);
return NULL;
}
static struct lcs_buffer *
lcs_get_buffer(struct lcs_channel *channel)
{
struct lcs_buffer *buffer;
unsigned long flags;
LCS_DBF_TEXT(5, trace, "getbuff");
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
buffer = __lcs_get_buffer(channel);
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
return buffer;
}
/**
* Resume channel program if the channel is suspended.
*/
static int
__lcs_resume_channel(struct lcs_channel *channel)
{
int rc;
if (channel->state != LCS_CH_STATE_SUSPENDED)
return 0;
if (channel->ccws[channel->io_idx].flags & CCW_FLAG_SUSPEND)
return 0;
LCS_DBF_TEXT_(5, trace, "rsch%s", dev_name(&channel->ccwdev->dev));
rc = ccw_device_resume(channel->ccwdev);
if (rc) {
LCS_DBF_TEXT_(4, trace, "ersc%s",
dev_name(&channel->ccwdev->dev));
dev_err(&channel->ccwdev->dev,
"Sending data from the LCS device to the LAN failed"
" with rc=%d\n",rc);
} else
channel->state = LCS_CH_STATE_RUNNING;
return rc;
}
/**
* Make a buffer ready for processing.
*/
static inline void
__lcs_ready_buffer_bits(struct lcs_channel *channel, int index)
{
int prev, next;
LCS_DBF_TEXT(5, trace, "rdybits");
prev = (index - 1) & (LCS_NUM_BUFFS - 1);
next = (index + 1) & (LCS_NUM_BUFFS - 1);
/* Check if we may clear the suspend bit of this buffer. */
if (channel->ccws[next].flags & CCW_FLAG_SUSPEND) {
/* Check if we have to set the PCI bit. */
if (!(channel->ccws[prev].flags & CCW_FLAG_SUSPEND))
/* Suspend bit of the previous buffer is not set. */
channel->ccws[index].flags |= CCW_FLAG_PCI;
/* Suspend bit of the next buffer is set. */
channel->ccws[index].flags &= ~CCW_FLAG_SUSPEND;
}
}
static int
lcs_ready_buffer(struct lcs_channel *channel, struct lcs_buffer *buffer)
{
unsigned long flags;
int index, rc;
LCS_DBF_TEXT(5, trace, "rdybuff");
BUG_ON(buffer->state != LCS_BUF_STATE_LOCKED &&
buffer->state != LCS_BUF_STATE_PROCESSED);
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
buffer->state = LCS_BUF_STATE_READY;
index = buffer - channel->iob;
/* Set length. */
channel->ccws[index].count = buffer->count;
/* Check relevant PCI/suspend bits. */
__lcs_ready_buffer_bits(channel, index);
rc = __lcs_resume_channel(channel);
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
return rc;
}
/**
* Mark the buffer as processed. Take care of the suspend bit
* of the previous buffer. This function is called from
* interrupt context, so the lock must not be taken.
*/
static int
__lcs_processed_buffer(struct lcs_channel *channel, struct lcs_buffer *buffer)
{
int index, prev, next;
LCS_DBF_TEXT(5, trace, "prcsbuff");
BUG_ON(buffer->state != LCS_BUF_STATE_READY);
buffer->state = LCS_BUF_STATE_PROCESSED;
index = buffer - channel->iob;
prev = (index - 1) & (LCS_NUM_BUFFS - 1);
next = (index + 1) & (LCS_NUM_BUFFS - 1);
/* Set the suspend bit and clear the PCI bit of this buffer. */
channel->ccws[index].flags |= CCW_FLAG_SUSPEND;
channel->ccws[index].flags &= ~CCW_FLAG_PCI;
/* Check the suspend bit of the previous buffer. */
if (channel->iob[prev].state == LCS_BUF_STATE_READY) {
/*
* Previous buffer is in state ready. It might have
* happened in lcs_ready_buffer that the suspend bit
* has not been cleared to avoid an endless loop.
* Do it now.
*/
__lcs_ready_buffer_bits(channel, prev);
}
/* Clear PCI bit of next buffer. */
channel->ccws[next].flags &= ~CCW_FLAG_PCI;
return __lcs_resume_channel(channel);
}
/**
* Put a processed buffer back to state empty.
*/
static void
lcs_release_buffer(struct lcs_channel *channel, struct lcs_buffer *buffer)
{
unsigned long flags;
LCS_DBF_TEXT(5, trace, "relbuff");
BUG_ON(buffer->state != LCS_BUF_STATE_LOCKED &&
buffer->state != LCS_BUF_STATE_PROCESSED);
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
buffer->state = LCS_BUF_STATE_EMPTY;
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
}
/**
* Get buffer for a lan command.
*/
static struct lcs_buffer *
lcs_get_lancmd(struct lcs_card *card, int count)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(4, trace, "getlncmd");
/* Get buffer and wait if none is available. */
wait_event(card->write.wait_q,
((buffer = lcs_get_buffer(&card->write)) != NULL));
count += sizeof(struct lcs_header);
*(__u16 *)(buffer->data + count) = 0;
buffer->count = count + sizeof(__u16);
buffer->callback = lcs_release_buffer;
cmd = (struct lcs_cmd *) buffer->data;
cmd->offset = count;
cmd->type = LCS_FRAME_TYPE_CONTROL;
cmd->slot = 0;
return buffer;
}
static void
lcs_get_reply(struct lcs_reply *reply)
{
WARN_ON(atomic_read(&reply->refcnt) <= 0);
atomic_inc(&reply->refcnt);
}
static void
lcs_put_reply(struct lcs_reply *reply)
{
WARN_ON(atomic_read(&reply->refcnt) <= 0);
if (atomic_dec_and_test(&reply->refcnt)) {
kfree(reply);
}
}
static struct lcs_reply *
lcs_alloc_reply(struct lcs_cmd *cmd)
{
struct lcs_reply *reply;
LCS_DBF_TEXT(4, trace, "getreply");
reply = kzalloc(sizeof(struct lcs_reply), GFP_ATOMIC);
if (!reply)
return NULL;
atomic_set(&reply->refcnt,1);
reply->sequence_no = cmd->sequence_no;
reply->received = 0;
reply->rc = 0;
init_waitqueue_head(&reply->wait_q);
return reply;
}
/**
* Notifier function for lancmd replies. Called from read irq.
*/
static void
lcs_notify_lancmd_waiters(struct lcs_card *card, struct lcs_cmd *cmd)
{
struct list_head *l, *n;
struct lcs_reply *reply;
LCS_DBF_TEXT(4, trace, "notiwait");
spin_lock(&card->lock);
list_for_each_safe(l, n, &card->lancmd_waiters) {
reply = list_entry(l, struct lcs_reply, list);
if (reply->sequence_no == cmd->sequence_no) {
lcs_get_reply(reply);
list_del_init(&reply->list);
if (reply->callback != NULL)
reply->callback(card, cmd);
reply->received = 1;
reply->rc = cmd->return_code;
wake_up(&reply->wait_q);
lcs_put_reply(reply);
break;
}
}
spin_unlock(&card->lock);
}
/**
* Emit buffer of a lan command.
*/
static void
lcs_lancmd_timeout(unsigned long data)
{
struct lcs_reply *reply, *list_reply, *r;
unsigned long flags;
LCS_DBF_TEXT(4, trace, "timeout");
reply = (struct lcs_reply *) data;
spin_lock_irqsave(&reply->card->lock, flags);
list_for_each_entry_safe(list_reply, r,
&reply->card->lancmd_waiters,list) {
if (reply == list_reply) {
lcs_get_reply(reply);
list_del_init(&reply->list);
spin_unlock_irqrestore(&reply->card->lock, flags);
reply->received = 1;
reply->rc = -ETIME;
wake_up(&reply->wait_q);
lcs_put_reply(reply);
return;
}
}
spin_unlock_irqrestore(&reply->card->lock, flags);
}
static int
lcs_send_lancmd(struct lcs_card *card, struct lcs_buffer *buffer,
void (*reply_callback)(struct lcs_card *, struct lcs_cmd *))
{
struct lcs_reply *reply;
struct lcs_cmd *cmd;
struct timer_list timer;
unsigned long flags;
int rc;
LCS_DBF_TEXT(4, trace, "sendcmd");
cmd = (struct lcs_cmd *) buffer->data;
cmd->return_code = 0;
cmd->sequence_no = card->sequence_no++;
reply = lcs_alloc_reply(cmd);
if (!reply)
return -ENOMEM;
reply->callback = reply_callback;
reply->card = card;
spin_lock_irqsave(&card->lock, flags);
list_add_tail(&reply->list, &card->lancmd_waiters);
spin_unlock_irqrestore(&card->lock, flags);
buffer->callback = lcs_release_buffer;
rc = lcs_ready_buffer(&card->write, buffer);
if (rc)
return rc;
init_timer_on_stack(&timer);
timer.function = lcs_lancmd_timeout;
timer.data = (unsigned long) reply;
timer.expires = jiffies + HZ*card->lancmd_timeout;
add_timer(&timer);
wait_event(reply->wait_q, reply->received);
del_timer_sync(&timer);
LCS_DBF_TEXT_(4, trace, "rc:%d",reply->rc);
rc = reply->rc;
lcs_put_reply(reply);
return rc ? -EIO : 0;
}
/**
* LCS startup command
*/
static int
lcs_send_startup(struct lcs_card *card, __u8 initiator)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "startup");
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_STARTUP;
cmd->initiator = initiator;
cmd->cmd.lcs_startup.buff_size = LCS_IOBUFFERSIZE;
return lcs_send_lancmd(card, buffer, NULL);
}
/**
* LCS shutdown command
*/
static int
lcs_send_shutdown(struct lcs_card *card)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "shutdown");
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_SHUTDOWN;
cmd->initiator = LCS_INITIATOR_TCPIP;
return lcs_send_lancmd(card, buffer, NULL);
}
/**
* LCS lanstat command
*/
static void
__lcs_lanstat_cb(struct lcs_card *card, struct lcs_cmd *cmd)
{
LCS_DBF_TEXT(2, trace, "statcb");
memcpy(card->mac, cmd->cmd.lcs_lanstat_cmd.mac_addr, LCS_MAC_LENGTH);
}
static int
lcs_send_lanstat(struct lcs_card *card)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2,trace, "cmdstat");
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
/* Setup lanstat command. */
cmd->cmd_code = LCS_CMD_LANSTAT;
cmd->initiator = LCS_INITIATOR_TCPIP;
cmd->cmd.lcs_std_cmd.lan_type = card->lan_type;
cmd->cmd.lcs_std_cmd.portno = card->portno;
return lcs_send_lancmd(card, buffer, __lcs_lanstat_cb);
}
/**
* send stoplan command
*/
static int
lcs_send_stoplan(struct lcs_card *card, __u8 initiator)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "cmdstpln");
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_STOPLAN;
cmd->initiator = initiator;
cmd->cmd.lcs_std_cmd.lan_type = card->lan_type;
cmd->cmd.lcs_std_cmd.portno = card->portno;
return lcs_send_lancmd(card, buffer, NULL);
}
/**
* send startlan command
*/
static void
__lcs_send_startlan_cb(struct lcs_card *card, struct lcs_cmd *cmd)
{
LCS_DBF_TEXT(2, trace, "srtlancb");
card->lan_type = cmd->cmd.lcs_std_cmd.lan_type;
card->portno = cmd->cmd.lcs_std_cmd.portno;
}
static int
lcs_send_startlan(struct lcs_card *card, __u8 initiator)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "cmdstaln");
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_STARTLAN;
cmd->initiator = initiator;
cmd->cmd.lcs_std_cmd.lan_type = card->lan_type;
cmd->cmd.lcs_std_cmd.portno = card->portno;
return lcs_send_lancmd(card, buffer, __lcs_send_startlan_cb);
}
#ifdef CONFIG_IP_MULTICAST
/**
* send setipm command (Multicast)
*/
static int
lcs_send_setipm(struct lcs_card *card,struct lcs_ipm_list *ipm_list)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "cmdsetim");
buffer = lcs_get_lancmd(card, LCS_MULTICAST_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_SETIPM;
cmd->initiator = LCS_INITIATOR_TCPIP;
cmd->cmd.lcs_qipassist.lan_type = card->lan_type;
cmd->cmd.lcs_qipassist.portno = card->portno;
cmd->cmd.lcs_qipassist.version = 4;
cmd->cmd.lcs_qipassist.num_ip_pairs = 1;
memcpy(cmd->cmd.lcs_qipassist.lcs_ipass_ctlmsg.ip_mac_pair,
&ipm_list->ipm, sizeof (struct lcs_ip_mac_pair));
LCS_DBF_TEXT_(2, trace, "%x",ipm_list->ipm.ip_addr);
return lcs_send_lancmd(card, buffer, NULL);
}
/**
* send delipm command (Multicast)
*/
static int
lcs_send_delipm(struct lcs_card *card,struct lcs_ipm_list *ipm_list)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
LCS_DBF_TEXT(2, trace, "cmddelim");
buffer = lcs_get_lancmd(card, LCS_MULTICAST_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_DELIPM;
cmd->initiator = LCS_INITIATOR_TCPIP;
cmd->cmd.lcs_qipassist.lan_type = card->lan_type;
cmd->cmd.lcs_qipassist.portno = card->portno;
cmd->cmd.lcs_qipassist.version = 4;
cmd->cmd.lcs_qipassist.num_ip_pairs = 1;
memcpy(cmd->cmd.lcs_qipassist.lcs_ipass_ctlmsg.ip_mac_pair,
&ipm_list->ipm, sizeof (struct lcs_ip_mac_pair));
LCS_DBF_TEXT_(2, trace, "%x",ipm_list->ipm.ip_addr);
return lcs_send_lancmd(card, buffer, NULL);
}
/**
* check if multicast is supported by LCS
*/
static void
__lcs_check_multicast_cb(struct lcs_card *card, struct lcs_cmd *cmd)
{
LCS_DBF_TEXT(2, trace, "chkmccb");
card->ip_assists_supported =
cmd->cmd.lcs_qipassist.ip_assists_supported;
card->ip_assists_enabled =
cmd->cmd.lcs_qipassist.ip_assists_enabled;
}
static int
lcs_check_multicast_support(struct lcs_card *card)
{
struct lcs_buffer *buffer;
struct lcs_cmd *cmd;
int rc;
LCS_DBF_TEXT(2, trace, "cmdqipa");
/* Send query ipassist. */
buffer = lcs_get_lancmd(card, LCS_STD_CMD_SIZE);
cmd = (struct lcs_cmd *) buffer->data;
cmd->cmd_code = LCS_CMD_QIPASSIST;
cmd->initiator = LCS_INITIATOR_TCPIP;
cmd->cmd.lcs_qipassist.lan_type = card->lan_type;
cmd->cmd.lcs_qipassist.portno = card->portno;
cmd->cmd.lcs_qipassist.version = 4;
cmd->cmd.lcs_qipassist.num_ip_pairs = 1;
rc = lcs_send_lancmd(card, buffer, __lcs_check_multicast_cb);
if (rc != 0) {
pr_err("Query IPAssist failed. Assuming unsupported!\n");
return -EOPNOTSUPP;
}
if (card->ip_assists_supported & LCS_IPASS_MULTICAST_SUPPORT)
return 0;
return -EOPNOTSUPP;
}
/**
* set or del multicast address on LCS card
*/
static void
lcs_fix_multicast_list(struct lcs_card *card)
{
struct list_head failed_list;
struct lcs_ipm_list *ipm, *tmp;
unsigned long flags;
int rc;
LCS_DBF_TEXT(4,trace, "fixipm");
INIT_LIST_HEAD(&failed_list);
spin_lock_irqsave(&card->ipm_lock, flags);
list_modified:
list_for_each_entry_safe(ipm, tmp, &card->ipm_list, list){
switch (ipm->ipm_state) {
case LCS_IPM_STATE_SET_REQUIRED:
/* del from ipm_list so no one else can tamper with
* this entry */
list_del_init(&ipm->list);
spin_unlock_irqrestore(&card->ipm_lock, flags);
rc = lcs_send_setipm(card, ipm);
spin_lock_irqsave(&card->ipm_lock, flags);
if (rc) {
pr_info("Adding multicast address failed."
" Table possibly full!\n");
/* store ipm in failed list -> will be added
* to ipm_list again, so a retry will be done
* during the next call of this function */
list_add_tail(&ipm->list, &failed_list);
} else {
ipm->ipm_state = LCS_IPM_STATE_ON_CARD;
/* re-insert into ipm_list */
list_add_tail(&ipm->list, &card->ipm_list);
}
goto list_modified;
case LCS_IPM_STATE_DEL_REQUIRED:
list_del(&ipm->list);
spin_unlock_irqrestore(&card->ipm_lock, flags);
lcs_send_delipm(card, ipm);
spin_lock_irqsave(&card->ipm_lock, flags);
kfree(ipm);
goto list_modified;
case LCS_IPM_STATE_ON_CARD:
break;
}
}
/* re-insert all entries from the failed_list into ipm_list */
list_for_each_entry_safe(ipm, tmp, &failed_list, list)
list_move_tail(&ipm->list, &card->ipm_list);
spin_unlock_irqrestore(&card->ipm_lock, flags);
}
/**
* get mac address for the relevant Multicast address
*/
static void
lcs_get_mac_for_ipm(__be32 ipm, char *mac, struct net_device *dev)
{
LCS_DBF_TEXT(4,trace, "getmac");
ip_eth_mc_map(ipm, mac);
}
/**
* function called by net device to handle multicast address relevant things
*/
static inline void
lcs_remove_mc_addresses(struct lcs_card *card, struct in_device *in4_dev)
{
struct ip_mc_list *im4;
struct list_head *l;
struct lcs_ipm_list *ipm;
unsigned long flags;
char buf[MAX_ADDR_LEN];
LCS_DBF_TEXT(4, trace, "remmclst");
spin_lock_irqsave(&card->ipm_lock, flags);
list_for_each(l, &card->ipm_list) {
ipm = list_entry(l, struct lcs_ipm_list, list);
for (im4 = rcu_dereference(in4_dev->mc_list);
im4 != NULL; im4 = rcu_dereference(im4->next_rcu)) {
lcs_get_mac_for_ipm(im4->multiaddr, buf, card->dev);
if ( (ipm->ipm.ip_addr == im4->multiaddr) &&
(memcmp(buf, &ipm->ipm.mac_addr,
LCS_MAC_LENGTH) == 0) )
break;
}
if (im4 == NULL)
ipm->ipm_state = LCS_IPM_STATE_DEL_REQUIRED;
}
spin_unlock_irqrestore(&card->ipm_lock, flags);
}
static inline struct lcs_ipm_list *
lcs_check_addr_entry(struct lcs_card *card, struct ip_mc_list *im4, char *buf)
{
struct lcs_ipm_list *tmp, *ipm = NULL;
struct list_head *l;
unsigned long flags;
LCS_DBF_TEXT(4, trace, "chkmcent");
spin_lock_irqsave(&card->ipm_lock, flags);
list_for_each(l, &card->ipm_list) {
tmp = list_entry(l, struct lcs_ipm_list, list);
if ( (tmp->ipm.ip_addr == im4->multiaddr) &&
(memcmp(buf, &tmp->ipm.mac_addr,
LCS_MAC_LENGTH) == 0) ) {
ipm = tmp;
break;
}
}
spin_unlock_irqrestore(&card->ipm_lock, flags);
return ipm;
}
static inline void
lcs_set_mc_addresses(struct lcs_card *card, struct in_device *in4_dev)
{
struct ip_mc_list *im4;
struct lcs_ipm_list *ipm;
char buf[MAX_ADDR_LEN];
unsigned long flags;
LCS_DBF_TEXT(4, trace, "setmclst");
for (im4 = rcu_dereference(in4_dev->mc_list); im4 != NULL;
im4 = rcu_dereference(im4->next_rcu)) {
lcs_get_mac_for_ipm(im4->multiaddr, buf, card->dev);
ipm = lcs_check_addr_entry(card, im4, buf);
if (ipm != NULL)
continue; /* Address already in list. */
ipm = kzalloc(sizeof(struct lcs_ipm_list), GFP_ATOMIC);
if (ipm == NULL) {
pr_info("Not enough memory to add"
" new multicast entry!\n");
break;
}
memcpy(&ipm->ipm.mac_addr, buf, LCS_MAC_LENGTH);
ipm->ipm.ip_addr = im4->multiaddr;
ipm->ipm_state = LCS_IPM_STATE_SET_REQUIRED;
spin_lock_irqsave(&card->ipm_lock, flags);
LCS_DBF_HEX(2,trace,&ipm->ipm.ip_addr,4);
list_add(&ipm->list, &card->ipm_list);
spin_unlock_irqrestore(&card->ipm_lock, flags);
}
}
static int
lcs_register_mc_addresses(void *data)
{
struct lcs_card *card;
struct in_device *in4_dev;
card = (struct lcs_card *) data;
if (!lcs_do_run_thread(card, LCS_SET_MC_THREAD))
return 0;
LCS_DBF_TEXT(4, trace, "regmulti");
in4_dev = in_dev_get(card->dev);
if (in4_dev == NULL)
goto out;
rcu_read_lock();
lcs_remove_mc_addresses(card,in4_dev);
lcs_set_mc_addresses(card, in4_dev);
rcu_read_unlock();
in_dev_put(in4_dev);
netif_carrier_off(card->dev);
netif_tx_disable(card->dev);
wait_event(card->write.wait_q,
(card->write.state != LCS_CH_STATE_RUNNING));
lcs_fix_multicast_list(card);
if (card->state == DEV_STATE_UP) {
netif_carrier_on(card->dev);
netif_wake_queue(card->dev);
}
out:
lcs_clear_thread_running_bit(card, LCS_SET_MC_THREAD);
return 0;
}
#endif /* CONFIG_IP_MULTICAST */
/**
* function called by net device to
* handle multicast address relevant things
*/
static void
lcs_set_multicast_list(struct net_device *dev)
{
#ifdef CONFIG_IP_MULTICAST
struct lcs_card *card;
LCS_DBF_TEXT(4, trace, "setmulti");
card = (struct lcs_card *) dev->ml_priv;
if (!lcs_set_thread_start_bit(card, LCS_SET_MC_THREAD))
schedule_work(&card->kernel_thread_starter);
#endif /* CONFIG_IP_MULTICAST */
}
static long
lcs_check_irb_error(struct ccw_device *cdev, struct irb *irb)
{
if (!IS_ERR(irb))
return 0;
switch (PTR_ERR(irb)) {
case -EIO:
dev_warn(&cdev->dev,
"An I/O-error occurred on the LCS device\n");
LCS_DBF_TEXT(2, trace, "ckirberr");
LCS_DBF_TEXT_(2, trace, " rc%d", -EIO);
break;
case -ETIMEDOUT:
dev_warn(&cdev->dev,
"A command timed out on the LCS device\n");
LCS_DBF_TEXT(2, trace, "ckirberr");
LCS_DBF_TEXT_(2, trace, " rc%d", -ETIMEDOUT);
break;
default:
dev_warn(&cdev->dev,
"An error occurred on the LCS device, rc=%ld\n",
PTR_ERR(irb));
LCS_DBF_TEXT(2, trace, "ckirberr");
LCS_DBF_TEXT(2, trace, " rc???");
}
return PTR_ERR(irb);
}
static int
lcs_get_problem(struct ccw_device *cdev, struct irb *irb)
{
int dstat, cstat;
char *sense;
sense = (char *) irb->ecw;
cstat = irb->scsw.cmd.cstat;
dstat = irb->scsw.cmd.dstat;
if (cstat & (SCHN_STAT_CHN_CTRL_CHK | SCHN_STAT_INTF_CTRL_CHK |
SCHN_STAT_CHN_DATA_CHK | SCHN_STAT_CHAIN_CHECK |
SCHN_STAT_PROT_CHECK | SCHN_STAT_PROG_CHECK)) {
LCS_DBF_TEXT(2, trace, "CGENCHK");
return 1;
}
if (dstat & DEV_STAT_UNIT_CHECK) {
if (sense[LCS_SENSE_BYTE_1] &
LCS_SENSE_RESETTING_EVENT) {
LCS_DBF_TEXT(2, trace, "REVIND");
return 1;
}
if (sense[LCS_SENSE_BYTE_0] &
LCS_SENSE_CMD_REJECT) {
LCS_DBF_TEXT(2, trace, "CMDREJ");
return 0;
}
if ((!sense[LCS_SENSE_BYTE_0]) &&
(!sense[LCS_SENSE_BYTE_1]) &&
(!sense[LCS_SENSE_BYTE_2]) &&
(!sense[LCS_SENSE_BYTE_3])) {
LCS_DBF_TEXT(2, trace, "ZEROSEN");
return 0;
}
LCS_DBF_TEXT(2, trace, "DGENCHK");
return 1;
}
return 0;
}
static void
lcs_schedule_recovery(struct lcs_card *card)
{
LCS_DBF_TEXT(2, trace, "startrec");
if (!lcs_set_thread_start_bit(card, LCS_RECOVERY_THREAD))
schedule_work(&card->kernel_thread_starter);
}
/**
* IRQ Handler for LCS channels
*/
static void
lcs_irq(struct ccw_device *cdev, unsigned long intparm, struct irb *irb)
{
struct lcs_card *card;
struct lcs_channel *channel;
int rc, index;
int cstat, dstat;
if (lcs_check_irb_error(cdev, irb))
return;
card = CARD_FROM_DEV(cdev);
if (card->read.ccwdev == cdev)
channel = &card->read;
else
channel = &card->write;
cstat = irb->scsw.cmd.cstat;
dstat = irb->scsw.cmd.dstat;
LCS_DBF_TEXT_(5, trace, "Rint%s", dev_name(&cdev->dev));
LCS_DBF_TEXT_(5, trace, "%4x%4x", irb->scsw.cmd.cstat,
irb->scsw.cmd.dstat);
LCS_DBF_TEXT_(5, trace, "%4x%4x", irb->scsw.cmd.fctl,
irb->scsw.cmd.actl);
/* Check for channel and device errors presented */
rc = lcs_get_problem(cdev, irb);
if (rc || (dstat & DEV_STAT_UNIT_EXCEP)) {
dev_warn(&cdev->dev,
"The LCS device stopped because of an error,"
" dstat=0x%X, cstat=0x%X \n",
dstat, cstat);
if (rc) {
channel->state = LCS_CH_STATE_ERROR;
}
}
if (channel->state == LCS_CH_STATE_ERROR) {
lcs_schedule_recovery(card);
wake_up(&card->wait_q);
return;
}
/* How far in the ccw chain have we processed? */
if ((channel->state != LCS_CH_STATE_INIT) &&
(irb->scsw.cmd.fctl & SCSW_FCTL_START_FUNC) &&
(irb->scsw.cmd.cpa != 0)) {
index = (struct ccw1 *) __va((addr_t) irb->scsw.cmd.cpa)
- channel->ccws;
if ((irb->scsw.cmd.actl & SCSW_ACTL_SUSPENDED) ||
(irb->scsw.cmd.cstat & SCHN_STAT_PCI))
/* Bloody io subsystem tells us lies about cpa... */
index = (index - 1) & (LCS_NUM_BUFFS - 1);
while (channel->io_idx != index) {
__lcs_processed_buffer(channel,
channel->iob + channel->io_idx);
channel->io_idx =
(channel->io_idx + 1) & (LCS_NUM_BUFFS - 1);
}
}
if ((irb->scsw.cmd.dstat & DEV_STAT_DEV_END) ||
(irb->scsw.cmd.dstat & DEV_STAT_CHN_END) ||
(irb->scsw.cmd.dstat & DEV_STAT_UNIT_CHECK))
/* Mark channel as stopped. */
channel->state = LCS_CH_STATE_STOPPED;
else if (irb->scsw.cmd.actl & SCSW_ACTL_SUSPENDED)
/* CCW execution stopped on a suspend bit. */
channel->state = LCS_CH_STATE_SUSPENDED;
if (irb->scsw.cmd.fctl & SCSW_FCTL_HALT_FUNC) {
if (irb->scsw.cmd.cc != 0) {
ccw_device_halt(channel->ccwdev, (addr_t) channel);
return;
}
/* The channel has been stopped by halt_IO. */
channel->state = LCS_CH_STATE_HALTED;
}
if (irb->scsw.cmd.fctl & SCSW_FCTL_CLEAR_FUNC)
channel->state = LCS_CH_STATE_CLEARED;
/* Do the rest in the tasklet. */
tasklet_schedule(&channel->irq_tasklet);
}
/**
* Tasklet for IRQ handler
*/
static void
lcs_tasklet(unsigned long data)
{
unsigned long flags;
struct lcs_channel *channel;
struct lcs_buffer *iob;
int buf_idx;
channel = (struct lcs_channel *) data;
LCS_DBF_TEXT_(5, trace, "tlet%s", dev_name(&channel->ccwdev->dev));
/* Check for processed buffers. */
iob = channel->iob;
buf_idx = channel->buf_idx;
while (iob[buf_idx].state == LCS_BUF_STATE_PROCESSED) {
/* Do the callback thing. */
if (iob[buf_idx].callback != NULL)
iob[buf_idx].callback(channel, iob + buf_idx);
buf_idx = (buf_idx + 1) & (LCS_NUM_BUFFS - 1);
}
channel->buf_idx = buf_idx;
if (channel->state == LCS_CH_STATE_STOPPED)
lcs_start_channel(channel);
spin_lock_irqsave(get_ccwdev_lock(channel->ccwdev), flags);
if (channel->state == LCS_CH_STATE_SUSPENDED &&
channel->iob[channel->io_idx].state == LCS_BUF_STATE_READY)
__lcs_resume_channel(channel);
spin_unlock_irqrestore(get_ccwdev_lock(channel->ccwdev), flags);
/* Something happened on the channel. Wake up waiters. */
wake_up(&channel->wait_q);
}
/**
* Finish current tx buffer and make it ready for transmit.
*/
static void
__lcs_emit_txbuffer(struct lcs_card *card)
{
LCS_DBF_TEXT(5, trace, "emittx");
*(__u16 *)(card->tx_buffer->data + card->tx_buffer->count) = 0;
card->tx_buffer->count += 2;
lcs_ready_buffer(&card->write, card->tx_buffer);
card->tx_buffer = NULL;
card->tx_emitted++;
}
/**
* Callback for finished tx buffers.
*/
static void
lcs_txbuffer_cb(struct lcs_channel *channel, struct lcs_buffer *buffer)
{
struct lcs_card *card;
LCS_DBF_TEXT(5, trace, "txbuffcb");
/* Put buffer back to pool. */
lcs_release_buffer(channel, buffer);
card = container_of(channel, struct lcs_card, write);
if (netif_queue_stopped(card->dev) && netif_carrier_ok(card->dev))
netif_wake_queue(card->dev);
spin_lock(&card->lock);
card->tx_emitted--;
if (card->tx_emitted <= 0 && card->tx_buffer != NULL)
/*
* Last running tx buffer has finished. Submit partially
* filled current buffer.
*/
__lcs_emit_txbuffer(card);
spin_unlock(&card->lock);
}
/**
* Packet transmit function called by network stack
*/
static int
__lcs_start_xmit(struct lcs_card *card, struct sk_buff *skb,
struct net_device *dev)
{
struct lcs_header *header;
int rc = NETDEV_TX_OK;
LCS_DBF_TEXT(5, trace, "hardxmit");
if (skb == NULL) {
card->stats.tx_dropped++;
card->stats.tx_errors++;
return NETDEV_TX_OK;
}
if (card->state != DEV_STATE_UP) {
dev_kfree_skb(skb);
card->stats.tx_dropped++;
card->stats.tx_errors++;
card->stats.tx_carrier_errors++;
return NETDEV_TX_OK;
}
if (skb->protocol == htons(ETH_P_IPV6)) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
netif_stop_queue(card->dev);
spin_lock(&card->lock);
if (card->tx_buffer != NULL &&
card->tx_buffer->count + sizeof(struct lcs_header) +
skb->len + sizeof(u16) > LCS_IOBUFFERSIZE)
/* skb too big for current tx buffer. */
__lcs_emit_txbuffer(card);
if (card->tx_buffer == NULL) {
/* Get new tx buffer */
card->tx_buffer = lcs_get_buffer(&card->write);
if (card->tx_buffer == NULL) {
card->stats.tx_dropped++;
rc = NETDEV_TX_BUSY;
goto out;
}
card->tx_buffer->callback = lcs_txbuffer_cb;
card->tx_buffer->count = 0;
}
header = (struct lcs_header *)
(card->tx_buffer->data + card->tx_buffer->count);
card->tx_buffer->count += skb->len + sizeof(struct lcs_header);
header->offset = card->tx_buffer->count;
header->type = card->lan_type;
header->slot = card->portno;
skb_copy_from_linear_data(skb, header + 1, skb->len);
spin_unlock(&card->lock);
card->stats.tx_bytes += skb->len;
card->stats.tx_packets++;
dev_kfree_skb(skb);
netif_wake_queue(card->dev);
spin_lock(&card->lock);
if (card->tx_emitted <= 0 && card->tx_buffer != NULL)
/* If this is the first tx buffer emit it immediately. */
__lcs_emit_txbuffer(card);
out:
spin_unlock(&card->lock);
return rc;
}
static int
lcs_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct lcs_card *card;
int rc;
LCS_DBF_TEXT(5, trace, "pktxmit");
card = (struct lcs_card *) dev->ml_priv;
rc = __lcs_start_xmit(card, skb, dev);
return rc;
}
/**
* send startlan and lanstat command to make LCS device ready
*/
static int
lcs_startlan_auto(struct lcs_card *card)
{
int rc;
LCS_DBF_TEXT(2, trace, "strtauto");
#ifdef CONFIG_ETHERNET
card->lan_type = LCS_FRAME_TYPE_ENET;
rc = lcs_send_startlan(card, LCS_INITIATOR_TCPIP);
if (rc == 0)
return 0;
#endif
#ifdef CONFIG_FDDI
card->lan_type = LCS_FRAME_TYPE_FDDI;
rc = lcs_send_startlan(card, LCS_INITIATOR_TCPIP);
if (rc == 0)
return 0;
#endif
return -EIO;
}
static int
lcs_startlan(struct lcs_card *card)
{
int rc, i;
LCS_DBF_TEXT(2, trace, "startlan");
rc = 0;
if (card->portno != LCS_INVALID_PORT_NO) {
if (card->lan_type == LCS_FRAME_TYPE_AUTO)
rc = lcs_startlan_auto(card);
else
rc = lcs_send_startlan(card, LCS_INITIATOR_TCPIP);
} else {
for (i = 0; i <= 16; i++) {
card->portno = i;
if (card->lan_type != LCS_FRAME_TYPE_AUTO)
rc = lcs_send_startlan(card,
LCS_INITIATOR_TCPIP);
else
/* autodetecting lan type */
rc = lcs_startlan_auto(card);
if (rc == 0)
break;
}
}
if (rc == 0)
return lcs_send_lanstat(card);
return rc;
}
/**
* LCS detect function
* setup channels and make them I/O ready
*/
static int
lcs_detect(struct lcs_card *card)
{
int rc = 0;
LCS_DBF_TEXT(2, setup, "lcsdetct");
/* start/reset card */
if (card->dev)
netif_stop_queue(card->dev);
rc = lcs_stop_channels(card);
if (rc == 0) {
rc = lcs_start_channels(card);
if (rc == 0) {
rc = lcs_send_startup(card, LCS_INITIATOR_TCPIP);
if (rc == 0)
rc = lcs_startlan(card);
}
}
if (rc == 0) {
card->state = DEV_STATE_UP;
} else {
card->state = DEV_STATE_DOWN;
card->write.state = LCS_CH_STATE_INIT;
card->read.state = LCS_CH_STATE_INIT;
}
return rc;
}
/**
* LCS Stop card
*/
static int
lcs_stopcard(struct lcs_card *card)
{
int rc;
LCS_DBF_TEXT(3, setup, "stopcard");
if (card->read.state != LCS_CH_STATE_STOPPED &&
card->write.state != LCS_CH_STATE_STOPPED &&
card->read.state != LCS_CH_STATE_ERROR &&
card->write.state != LCS_CH_STATE_ERROR &&
card->state == DEV_STATE_UP) {
lcs_clear_multicast_list(card);
rc = lcs_send_stoplan(card,LCS_INITIATOR_TCPIP);
rc = lcs_send_shutdown(card);
}
rc = lcs_stop_channels(card);
card->state = DEV_STATE_DOWN;
return rc;
}
/**
* Kernel Thread helper functions for LGW initiated commands
*/
static void
lcs_start_kernel_thread(struct work_struct *work)
{
struct lcs_card *card = container_of(work, struct lcs_card, kernel_thread_starter);
LCS_DBF_TEXT(5, trace, "krnthrd");
if (lcs_do_start_thread(card, LCS_RECOVERY_THREAD))
kthread_run(lcs_recovery, card, "lcs_recover");
#ifdef CONFIG_IP_MULTICAST
if (lcs_do_start_thread(card, LCS_SET_MC_THREAD))
kthread_run(lcs_register_mc_addresses, card, "regipm");
#endif
}
/**
* Process control frames.
*/
static void
lcs_get_control(struct lcs_card *card, struct lcs_cmd *cmd)
{
LCS_DBF_TEXT(5, trace, "getctrl");
if (cmd->initiator == LCS_INITIATOR_LGW) {
switch(cmd->cmd_code) {
case LCS_CMD_STARTUP:
case LCS_CMD_STARTLAN:
lcs_schedule_recovery(card);
break;
case LCS_CMD_STOPLAN:
pr_warning("Stoplan for %s initiated by LGW.\n",
card->dev->name);
if (card->dev)
netif_carrier_off(card->dev);
break;
default:
LCS_DBF_TEXT(5, trace, "noLGWcmd");
break;
}
} else
lcs_notify_lancmd_waiters(card, cmd);
}
/**
* Unpack network packet.
*/
static void
lcs_get_skb(struct lcs_card *card, char *skb_data, unsigned int skb_len)
{
struct sk_buff *skb;
LCS_DBF_TEXT(5, trace, "getskb");
if (card->dev == NULL ||
card->state != DEV_STATE_UP)
/* The card isn't up. Ignore the packet. */
return;
skb = dev_alloc_skb(skb_len);
if (skb == NULL) {
dev_err(&card->dev->dev,
" Allocating a socket buffer to interface %s failed\n",
card->dev->name);
card->stats.rx_dropped++;
return;
}
memcpy(skb_put(skb, skb_len), skb_data, skb_len);
skb->protocol = card->lan_type_trans(skb, card->dev);
card->stats.rx_bytes += skb_len;
card->stats.rx_packets++;
if (skb->protocol == htons(ETH_P_802_2))
*((__u32 *)skb->cb) = ++card->pkt_seq;
netif_rx(skb);
}
/**
* LCS main routine to get packets and lancmd replies from the buffers
*/
static void
lcs_get_frames_cb(struct lcs_channel *channel, struct lcs_buffer *buffer)
{
struct lcs_card *card;
struct lcs_header *lcs_hdr;
__u16 offset;
LCS_DBF_TEXT(5, trace, "lcsgtpkt");
lcs_hdr = (struct lcs_header *) buffer->data;
if (lcs_hdr->offset == LCS_ILLEGAL_OFFSET) {
LCS_DBF_TEXT(4, trace, "-eiogpkt");
return;
}
card = container_of(channel, struct lcs_card, read);
offset = 0;
while (lcs_hdr->offset != 0) {
if (lcs_hdr->offset <= 0 ||
lcs_hdr->offset > LCS_IOBUFFERSIZE ||
lcs_hdr->offset < offset) {
/* Offset invalid. */
card->stats.rx_length_errors++;
card->stats.rx_errors++;
return;
}
/* What kind of frame is it? */
if (lcs_hdr->type == LCS_FRAME_TYPE_CONTROL)
/* Control frame. */
lcs_get_control(card, (struct lcs_cmd *) lcs_hdr);
else if (lcs_hdr->type == LCS_FRAME_TYPE_ENET ||
lcs_hdr->type == LCS_FRAME_TYPE_TR ||
lcs_hdr->type == LCS_FRAME_TYPE_FDDI)
/* Normal network packet. */
lcs_get_skb(card, (char *)(lcs_hdr + 1),
lcs_hdr->offset - offset -
sizeof(struct lcs_header));
else
/* Unknown frame type. */
; // FIXME: error message ?
/* Proceed to next frame. */
offset = lcs_hdr->offset;
lcs_hdr->offset = LCS_ILLEGAL_OFFSET;
lcs_hdr = (struct lcs_header *) (buffer->data + offset);
}
/* The buffer is now empty. Make it ready again. */
lcs_ready_buffer(&card->read, buffer);
}
/**
* get network statistics for ifconfig and other user programs
*/
static struct net_device_stats *
lcs_getstats(struct net_device *dev)
{
struct lcs_card *card;
LCS_DBF_TEXT(4, trace, "netstats");
card = (struct lcs_card *) dev->ml_priv;
return &card->stats;
}
/**
* stop lcs device
* This function will be called by user doing ifconfig xxx down
*/
static int
lcs_stop_device(struct net_device *dev)
{
struct lcs_card *card;
int rc;
LCS_DBF_TEXT(2, trace, "stopdev");
card = (struct lcs_card *) dev->ml_priv;
netif_carrier_off(dev);
netif_tx_disable(dev);
dev->flags &= ~IFF_UP;
wait_event(card->write.wait_q,
(card->write.state != LCS_CH_STATE_RUNNING));
rc = lcs_stopcard(card);
if (rc)
dev_err(&card->dev->dev,
" Shutting down the LCS device failed\n ");
return rc;
}
/**
* start lcs device and make it runnable
* This function will be called by user doing ifconfig xxx up
*/
static int
lcs_open_device(struct net_device *dev)
{
struct lcs_card *card;
int rc;
LCS_DBF_TEXT(2, trace, "opendev");
card = (struct lcs_card *) dev->ml_priv;
/* initialize statistics */
rc = lcs_detect(card);
if (rc) {
pr_err("Error in opening device!\n");
} else {
dev->flags |= IFF_UP;
netif_carrier_on(dev);
netif_wake_queue(dev);
card->state = DEV_STATE_UP;
}
return rc;
}
/**
* show function for portno called by cat or similar things
*/
static ssize_t
lcs_portno_show (struct device *dev, struct device_attribute *attr, char *buf)
{
struct lcs_card *card;
card = dev_get_drvdata(dev);
if (!card)
return 0;
return sprintf(buf, "%d\n", card->portno);
}
/**
* store the value which is piped to file portno
*/
static ssize_t
lcs_portno_store (struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct lcs_card *card;
int value;
card = dev_get_drvdata(dev);
if (!card)
return 0;
sscanf(buf, "%u", &value);
/* TODO: sanity checks */
card->portno = value;
return count;
}
static DEVICE_ATTR(portno, 0644, lcs_portno_show, lcs_portno_store);
static const char *lcs_type[] = {
"not a channel",
"2216 parallel",
"2216 channel",
"OSA LCS card",
"unknown channel type",
"unsupported channel type",
};
static ssize_t
lcs_type_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct ccwgroup_device *cgdev;
cgdev = to_ccwgroupdev(dev);
if (!cgdev)
return -ENODEV;
return sprintf(buf, "%s\n", lcs_type[cgdev->cdev[0]->id.driver_info]);
}
static DEVICE_ATTR(type, 0444, lcs_type_show, NULL);
static ssize_t
lcs_timeout_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct lcs_card *card;
card = dev_get_drvdata(dev);
return card ? sprintf(buf, "%u\n", card->lancmd_timeout) : 0;
}
static ssize_t
lcs_timeout_store (struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct lcs_card *card;
int value;
card = dev_get_drvdata(dev);
if (!card)
return 0;
sscanf(buf, "%u", &value);
/* TODO: sanity checks */
card->lancmd_timeout = value;
return count;
}
static DEVICE_ATTR(lancmd_timeout, 0644, lcs_timeout_show, lcs_timeout_store);
static ssize_t
lcs_dev_recover_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct lcs_card *card = dev_get_drvdata(dev);
char *tmp;
int i;
if (!card)
return -EINVAL;
if (card->state != DEV_STATE_UP)
return -EPERM;
i = simple_strtoul(buf, &tmp, 16);
if (i == 1)
lcs_schedule_recovery(card);
return count;
}
static DEVICE_ATTR(recover, 0200, NULL, lcs_dev_recover_store);
static struct attribute * lcs_attrs[] = {
&dev_attr_portno.attr,
&dev_attr_type.attr,
&dev_attr_lancmd_timeout.attr,
&dev_attr_recover.attr,
NULL,
};
static struct attribute_group lcs_attr_group = {
.attrs = lcs_attrs,
};
static const struct attribute_group *lcs_attr_groups[] = {
&lcs_attr_group,
NULL,
};
static const struct device_type lcs_devtype = {
.name = "lcs",
.groups = lcs_attr_groups,
};
/**
* lcs_probe_device is called on establishing a new ccwgroup_device.
*/
static int
lcs_probe_device(struct ccwgroup_device *ccwgdev)
{
struct lcs_card *card;
if (!get_device(&ccwgdev->dev))
return -ENODEV;
LCS_DBF_TEXT(2, setup, "add_dev");
card = lcs_alloc_card();
if (!card) {
LCS_DBF_TEXT_(2, setup, " rc%d", -ENOMEM);
put_device(&ccwgdev->dev);
return -ENOMEM;
}
dev_set_drvdata(&ccwgdev->dev, card);
ccwgdev->cdev[0]->handler = lcs_irq;
ccwgdev->cdev[1]->handler = lcs_irq;
card->gdev = ccwgdev;
INIT_WORK(&card->kernel_thread_starter, lcs_start_kernel_thread);
card->thread_start_mask = 0;
card->thread_allowed_mask = 0;
card->thread_running_mask = 0;
ccwgdev->dev.type = &lcs_devtype;
return 0;
}
static int
lcs_register_netdev(struct ccwgroup_device *ccwgdev)
{
struct lcs_card *card;
LCS_DBF_TEXT(2, setup, "regnetdv");
card = dev_get_drvdata(&ccwgdev->dev);
if (card->dev->reg_state != NETREG_UNINITIALIZED)
return 0;
SET_NETDEV_DEV(card->dev, &ccwgdev->dev);
return register_netdev(card->dev);
}
/**
* lcs_new_device will be called by setting the group device online.
*/
static const struct net_device_ops lcs_netdev_ops = {
.ndo_open = lcs_open_device,
.ndo_stop = lcs_stop_device,
.ndo_get_stats = lcs_getstats,
.ndo_start_xmit = lcs_start_xmit,
};
static const struct net_device_ops lcs_mc_netdev_ops = {
.ndo_open = lcs_open_device,
.ndo_stop = lcs_stop_device,
.ndo_get_stats = lcs_getstats,
.ndo_start_xmit = lcs_start_xmit,
.ndo_set_rx_mode = lcs_set_multicast_list,
};
static int
lcs_new_device(struct ccwgroup_device *ccwgdev)
{
struct lcs_card *card;
struct net_device *dev=NULL;
enum lcs_dev_states recover_state;
int rc;
card = dev_get_drvdata(&ccwgdev->dev);
if (!card)
return -ENODEV;
LCS_DBF_TEXT(2, setup, "newdev");
LCS_DBF_HEX(3, setup, &card, sizeof(void*));
card->read.ccwdev = ccwgdev->cdev[0];
card->write.ccwdev = ccwgdev->cdev[1];
recover_state = card->state;
rc = ccw_device_set_online(card->read.ccwdev);
if (rc)
goto out_err;
rc = ccw_device_set_online(card->write.ccwdev);
if (rc)
goto out_werr;
LCS_DBF_TEXT(3, setup, "lcsnewdv");
lcs_setup_card(card);
rc = lcs_detect(card);
if (rc) {
LCS_DBF_TEXT(2, setup, "dtctfail");
dev_err(&card->dev->dev,
"Detecting a network adapter for LCS devices"
" failed with rc=%d (0x%x)\n", rc, rc);
lcs_stopcard(card);
goto out;
}
if (card->dev) {
LCS_DBF_TEXT(2, setup, "samedev");
LCS_DBF_HEX(3, setup, &card, sizeof(void*));
goto netdev_out;
}
switch (card->lan_type) {
#ifdef CONFIG_ETHERNET
case LCS_FRAME_TYPE_ENET:
card->lan_type_trans = eth_type_trans;
dev = alloc_etherdev(0);
break;
#endif
#ifdef CONFIG_FDDI
case LCS_FRAME_TYPE_FDDI:
card->lan_type_trans = fddi_type_trans;
dev = alloc_fddidev(0);
break;
#endif
default:
LCS_DBF_TEXT(3, setup, "errinit");
pr_err(" Initialization failed\n");
goto out;
}
if (!dev)
goto out;
card->dev = dev;
card->dev->ml_priv = card;
card->dev->netdev_ops = &lcs_netdev_ops;
memcpy(card->dev->dev_addr, card->mac, LCS_MAC_LENGTH);
#ifdef CONFIG_IP_MULTICAST
if (!lcs_check_multicast_support(card))
card->dev->netdev_ops = &lcs_mc_netdev_ops;
#endif
netdev_out:
lcs_set_allowed_threads(card,0xffffffff);
if (recover_state == DEV_STATE_RECOVER) {
lcs_set_multicast_list(card->dev);
card->dev->flags |= IFF_UP;
netif_carrier_on(card->dev);
netif_wake_queue(card->dev);
card->state = DEV_STATE_UP;
} else {
lcs_stopcard(card);
}
if (lcs_register_netdev(ccwgdev) != 0)
goto out;
/* Print out supported assists: IPv6 */
pr_info("LCS device %s %s IPv6 support\n", card->dev->name,
(card->ip_assists_supported & LCS_IPASS_IPV6_SUPPORT) ?
"with" : "without");
/* Print out supported assist: Multicast */
pr_info("LCS device %s %s Multicast support\n", card->dev->name,
(card->ip_assists_supported & LCS_IPASS_MULTICAST_SUPPORT) ?
"with" : "without");
return 0;
out:
ccw_device_set_offline(card->write.ccwdev);
out_werr:
ccw_device_set_offline(card->read.ccwdev);
out_err:
return -ENODEV;
}
/**
* lcs_shutdown_device, called when setting the group device offline.
*/
static int
__lcs_shutdown_device(struct ccwgroup_device *ccwgdev, int recovery_mode)
{
struct lcs_card *card;
enum lcs_dev_states recover_state;
int ret = 0, ret2 = 0, ret3 = 0;
LCS_DBF_TEXT(3, setup, "shtdndev");
card = dev_get_drvdata(&ccwgdev->dev);
if (!card)
return -ENODEV;
if (recovery_mode == 0) {
lcs_set_allowed_threads(card, 0);
if (lcs_wait_for_threads(card, LCS_SET_MC_THREAD))
return -ERESTARTSYS;
}
LCS_DBF_HEX(3, setup, &card, sizeof(void*));
recover_state = card->state;
ret = lcs_stop_device(card->dev);
ret2 = ccw_device_set_offline(card->read.ccwdev);
ret3 = ccw_device_set_offline(card->write.ccwdev);
if (!ret)
ret = (ret2) ? ret2 : ret3;
if (ret)
LCS_DBF_TEXT_(3, setup, "1err:%d", ret);
if (recover_state == DEV_STATE_UP) {
card->state = DEV_STATE_RECOVER;
}
return 0;
}
static int
lcs_shutdown_device(struct ccwgroup_device *ccwgdev)
{
return __lcs_shutdown_device(ccwgdev, 0);
}
/**
* drive lcs recovery after startup and startlan initiated by Lan Gateway
*/
static int
lcs_recovery(void *ptr)
{
struct lcs_card *card;
struct ccwgroup_device *gdev;
int rc;
card = (struct lcs_card *) ptr;
LCS_DBF_TEXT(4, trace, "recover1");
if (!lcs_do_run_thread(card, LCS_RECOVERY_THREAD))
return 0;
LCS_DBF_TEXT(4, trace, "recover2");
gdev = card->gdev;
dev_warn(&gdev->dev,
"A recovery process has been started for the LCS device\n");
rc = __lcs_shutdown_device(gdev, 1);
rc = lcs_new_device(gdev);
if (!rc)
pr_info("Device %s successfully recovered!\n",
card->dev->name);
else
pr_info("Device %s could not be recovered!\n",
card->dev->name);
lcs_clear_thread_running_bit(card, LCS_RECOVERY_THREAD);
return 0;
}
/**
* lcs_remove_device, free buffers and card
*/
static void
lcs_remove_device(struct ccwgroup_device *ccwgdev)
{
struct lcs_card *card;
card = dev_get_drvdata(&ccwgdev->dev);
if (!card)
return;
LCS_DBF_TEXT(3, setup, "remdev");
LCS_DBF_HEX(3, setup, &card, sizeof(void*));
if (ccwgdev->state == CCWGROUP_ONLINE) {
lcs_shutdown_device(ccwgdev);
}
if (card->dev)
unregister_netdev(card->dev);
lcs_cleanup_card(card);
lcs_free_card(card);
dev_set_drvdata(&ccwgdev->dev, NULL);
put_device(&ccwgdev->dev);
}
static int lcs_pm_suspend(struct lcs_card *card)
{
if (card->dev)
netif_device_detach(card->dev);
lcs_set_allowed_threads(card, 0);
lcs_wait_for_threads(card, 0xffffffff);
if (card->state != DEV_STATE_DOWN)
__lcs_shutdown_device(card->gdev, 1);
return 0;
}
static int lcs_pm_resume(struct lcs_card *card)
{
int rc = 0;
if (card->state == DEV_STATE_RECOVER)
rc = lcs_new_device(card->gdev);
if (card->dev)
netif_device_attach(card->dev);
if (rc) {
dev_warn(&card->gdev->dev, "The lcs device driver "
"failed to recover the device\n");
}
return rc;
}
static int lcs_prepare(struct ccwgroup_device *gdev)
{
return 0;
}
static void lcs_complete(struct ccwgroup_device *gdev)
{
return;
}
static int lcs_freeze(struct ccwgroup_device *gdev)
{
struct lcs_card *card = dev_get_drvdata(&gdev->dev);
return lcs_pm_suspend(card);
}
static int lcs_thaw(struct ccwgroup_device *gdev)
{
struct lcs_card *card = dev_get_drvdata(&gdev->dev);
return lcs_pm_resume(card);
}
static int lcs_restore(struct ccwgroup_device *gdev)
{
struct lcs_card *card = dev_get_drvdata(&gdev->dev);
return lcs_pm_resume(card);
}
static struct ccw_device_id lcs_ids[] = {
{CCW_DEVICE(0x3088, 0x08), .driver_info = lcs_channel_type_parallel},
{CCW_DEVICE(0x3088, 0x1f), .driver_info = lcs_channel_type_2216},
{CCW_DEVICE(0x3088, 0x60), .driver_info = lcs_channel_type_osa2},
{},
};
MODULE_DEVICE_TABLE(ccw, lcs_ids);
static struct ccw_driver lcs_ccw_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "lcs",
},
.ids = lcs_ids,
.probe = ccwgroup_probe_ccwdev,
.remove = ccwgroup_remove_ccwdev,
.int_class = IRQIO_LCS,
};
/**
* LCS ccwgroup driver registration
*/
static struct ccwgroup_driver lcs_group_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "lcs",
},
.setup = lcs_probe_device,
.remove = lcs_remove_device,
.set_online = lcs_new_device,
.set_offline = lcs_shutdown_device,
.prepare = lcs_prepare,
.complete = lcs_complete,
.freeze = lcs_freeze,
.thaw = lcs_thaw,
.restore = lcs_restore,
};
static ssize_t lcs_driver_group_store(struct device_driver *ddrv,
const char *buf, size_t count)
{
int err;
err = ccwgroup_create_dev(lcs_root_dev, &lcs_group_driver, 2, buf);
return err ? err : count;
}
static DRIVER_ATTR(group, 0200, NULL, lcs_driver_group_store);
static struct attribute *lcs_drv_attrs[] = {
&driver_attr_group.attr,
NULL,
};
static struct attribute_group lcs_drv_attr_group = {
.attrs = lcs_drv_attrs,
};
static const struct attribute_group *lcs_drv_attr_groups[] = {
&lcs_drv_attr_group,
NULL,
};
/**
* LCS Module/Kernel initialization function
*/
static int
__init lcs_init_module(void)
{
int rc;
pr_info("Loading %s\n", version);
rc = lcs_register_debug_facility();
LCS_DBF_TEXT(0, setup, "lcsinit");
if (rc)
goto out_err;
lcs_root_dev = root_device_register("lcs");
rc = PTR_RET(lcs_root_dev);
if (rc)
goto register_err;
rc = ccw_driver_register(&lcs_ccw_driver);
if (rc)
goto ccw_err;
lcs_group_driver.driver.groups = lcs_drv_attr_groups;
rc = ccwgroup_driver_register(&lcs_group_driver);
if (rc)
goto ccwgroup_err;
return 0;
ccwgroup_err:
ccw_driver_unregister(&lcs_ccw_driver);
ccw_err:
root_device_unregister(lcs_root_dev);
register_err:
lcs_unregister_debug_facility();
out_err:
pr_err("Initializing the lcs device driver failed\n");
return rc;
}
/**
* LCS module cleanup function
*/
static void
__exit lcs_cleanup_module(void)
{
pr_info("Terminating lcs module.\n");
LCS_DBF_TEXT(0, trace, "cleanup");
ccwgroup_driver_unregister(&lcs_group_driver);
ccw_driver_unregister(&lcs_ccw_driver);
root_device_unregister(lcs_root_dev);
lcs_unregister_debug_facility();
}
module_init(lcs_init_module);
module_exit(lcs_cleanup_module);
MODULE_AUTHOR("Frank Pavlic <fpavlic@de.ibm.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
neomanu/NeoKernel-MT6589-A116 | net/x25/af_x25.c | 735 | 41426 | /*
* X.25 Packet Layer release 002
*
* This is ALPHA test software. This code may break your machine,
* randomly fail to work with new releases, misbehave and/or generally
* screw up. It might even work.
*
* This code REQUIRES 2.1.15 or higher
*
* This module:
* This module 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.
*
* History
* X.25 001 Jonathan Naylor Started coding.
* X.25 002 Jonathan Naylor Centralised disconnect handling.
* New timer architecture.
* 2000-03-11 Henner Eisen MSG_EOR handling more POSIX compliant.
* 2000-03-22 Daniela Squassoni Allowed disabling/enabling of
* facilities negotiation and increased
* the throughput upper limit.
* 2000-08-27 Arnaldo C. Melo s/suser/capable/ + micro cleanups
* 2000-09-04 Henner Eisen Set sock->state in x25_accept().
* Fixed x25_output() related skb leakage.
* 2000-10-02 Henner Eisen Made x25_kick() single threaded per socket.
* 2000-10-27 Henner Eisen MSG_DONTWAIT for fragment allocation.
* 2000-11-14 Henner Eisen Closing datalink from NETDEV_GOING_DOWN
* 2002-10-06 Arnaldo C. Melo Get rid of cli/sti, move proc stuff to
* x25_proc.c, using seq_file
* 2005-04-02 Shaun Pereira Selective sub address matching
* with call user data
* 2005-04-15 Shaun Pereira Fast select with no restriction on
* response
*/
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/termios.h> /* For TIOCINQ/OUTQ */
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/ctype.h>
#include <net/x25.h>
#include <net/compat.h>
int sysctl_x25_restart_request_timeout = X25_DEFAULT_T20;
int sysctl_x25_call_request_timeout = X25_DEFAULT_T21;
int sysctl_x25_reset_request_timeout = X25_DEFAULT_T22;
int sysctl_x25_clear_request_timeout = X25_DEFAULT_T23;
int sysctl_x25_ack_holdback_timeout = X25_DEFAULT_T2;
int sysctl_x25_forward = 0;
HLIST_HEAD(x25_list);
DEFINE_RWLOCK(x25_list_lock);
static const struct proto_ops x25_proto_ops;
static struct x25_address null_x25_address = {" "};
#ifdef CONFIG_COMPAT
struct compat_x25_subscrip_struct {
char device[200-sizeof(compat_ulong_t)];
compat_ulong_t global_facil_mask;
compat_uint_t extended;
};
#endif
int x25_parse_address_block(struct sk_buff *skb,
struct x25_address *called_addr,
struct x25_address *calling_addr)
{
unsigned char len;
int needed;
int rc;
if (!pskb_may_pull(skb, 1)) {
/* packet has no address block */
rc = 0;
goto empty;
}
len = *skb->data;
needed = 1 + (len >> 4) + (len & 0x0f);
if (!pskb_may_pull(skb, needed)) {
/* packet is too short to hold the addresses it claims
to hold */
rc = -1;
goto empty;
}
return x25_addr_ntoa(skb->data, called_addr, calling_addr);
empty:
*called_addr->x25_addr = 0;
*calling_addr->x25_addr = 0;
return rc;
}
int x25_addr_ntoa(unsigned char *p, struct x25_address *called_addr,
struct x25_address *calling_addr)
{
unsigned int called_len, calling_len;
char *called, *calling;
unsigned int i;
called_len = (*p >> 0) & 0x0F;
calling_len = (*p >> 4) & 0x0F;
called = called_addr->x25_addr;
calling = calling_addr->x25_addr;
p++;
for (i = 0; i < (called_len + calling_len); i++) {
if (i < called_len) {
if (i % 2 != 0) {
*called++ = ((*p >> 0) & 0x0F) + '0';
p++;
} else {
*called++ = ((*p >> 4) & 0x0F) + '0';
}
} else {
if (i % 2 != 0) {
*calling++ = ((*p >> 0) & 0x0F) + '0';
p++;
} else {
*calling++ = ((*p >> 4) & 0x0F) + '0';
}
}
}
*called = *calling = '\0';
return 1 + (called_len + calling_len + 1) / 2;
}
int x25_addr_aton(unsigned char *p, struct x25_address *called_addr,
struct x25_address *calling_addr)
{
unsigned int called_len, calling_len;
char *called, *calling;
int i;
called = called_addr->x25_addr;
calling = calling_addr->x25_addr;
called_len = strlen(called);
calling_len = strlen(calling);
*p++ = (calling_len << 4) | (called_len << 0);
for (i = 0; i < (called_len + calling_len); i++) {
if (i < called_len) {
if (i % 2 != 0) {
*p |= (*called++ - '0') << 0;
p++;
} else {
*p = 0x00;
*p |= (*called++ - '0') << 4;
}
} else {
if (i % 2 != 0) {
*p |= (*calling++ - '0') << 0;
p++;
} else {
*p = 0x00;
*p |= (*calling++ - '0') << 4;
}
}
}
return 1 + (called_len + calling_len + 1) / 2;
}
/*
* Socket removal during an interrupt is now safe.
*/
static void x25_remove_socket(struct sock *sk)
{
write_lock_bh(&x25_list_lock);
sk_del_node_init(sk);
write_unlock_bh(&x25_list_lock);
}
/*
* Kill all bound sockets on a dropped device.
*/
static void x25_kill_by_device(struct net_device *dev)
{
struct sock *s;
struct hlist_node *node;
write_lock_bh(&x25_list_lock);
sk_for_each(s, node, &x25_list)
if (x25_sk(s)->neighbour && x25_sk(s)->neighbour->dev == dev)
x25_disconnect(s, ENETUNREACH, 0, 0);
write_unlock_bh(&x25_list_lock);
}
/*
* Handle device status changes.
*/
static int x25_device_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = ptr;
struct x25_neigh *nb;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (dev->type == ARPHRD_X25
#if IS_ENABLED(CONFIG_LLC)
|| dev->type == ARPHRD_ETHER
#endif
) {
switch (event) {
case NETDEV_UP:
x25_link_device_up(dev);
break;
case NETDEV_GOING_DOWN:
nb = x25_get_neigh(dev);
if (nb) {
x25_terminate_link(nb);
x25_neigh_put(nb);
}
break;
case NETDEV_DOWN:
x25_kill_by_device(dev);
x25_route_device_down(dev);
x25_link_device_down(dev);
break;
}
}
return NOTIFY_DONE;
}
/*
* Add a socket to the bound sockets list.
*/
static void x25_insert_socket(struct sock *sk)
{
write_lock_bh(&x25_list_lock);
sk_add_node(sk, &x25_list);
write_unlock_bh(&x25_list_lock);
}
/*
* Find a socket that wants to accept the Call Request we just
* received. Check the full list for an address/cud match.
* If no cuds match return the next_best thing, an address match.
* Note: if a listening socket has cud set it must only get calls
* with matching cud.
*/
static struct sock *x25_find_listener(struct x25_address *addr,
struct sk_buff *skb)
{
struct sock *s;
struct sock *next_best;
struct hlist_node *node;
read_lock_bh(&x25_list_lock);
next_best = NULL;
sk_for_each(s, node, &x25_list)
if ((!strcmp(addr->x25_addr,
x25_sk(s)->source_addr.x25_addr) ||
!strcmp(addr->x25_addr,
null_x25_address.x25_addr)) &&
s->sk_state == TCP_LISTEN) {
/*
* Found a listening socket, now check the incoming
* call user data vs this sockets call user data
*/
if (x25_sk(s)->cudmatchlength > 0 &&
skb->len >= x25_sk(s)->cudmatchlength) {
if((memcmp(x25_sk(s)->calluserdata.cuddata,
skb->data,
x25_sk(s)->cudmatchlength)) == 0) {
sock_hold(s);
goto found;
}
} else
next_best = s;
}
if (next_best) {
s = next_best;
sock_hold(s);
goto found;
}
s = NULL;
found:
read_unlock_bh(&x25_list_lock);
return s;
}
/*
* Find a connected X.25 socket given my LCI and neighbour.
*/
static struct sock *__x25_find_socket(unsigned int lci, struct x25_neigh *nb)
{
struct sock *s;
struct hlist_node *node;
sk_for_each(s, node, &x25_list)
if (x25_sk(s)->lci == lci && x25_sk(s)->neighbour == nb) {
sock_hold(s);
goto found;
}
s = NULL;
found:
return s;
}
struct sock *x25_find_socket(unsigned int lci, struct x25_neigh *nb)
{
struct sock *s;
read_lock_bh(&x25_list_lock);
s = __x25_find_socket(lci, nb);
read_unlock_bh(&x25_list_lock);
return s;
}
/*
* Find a unique LCI for a given device.
*/
static unsigned int x25_new_lci(struct x25_neigh *nb)
{
unsigned int lci = 1;
struct sock *sk;
read_lock_bh(&x25_list_lock);
while ((sk = __x25_find_socket(lci, nb)) != NULL) {
sock_put(sk);
if (++lci == 4096) {
lci = 0;
break;
}
}
read_unlock_bh(&x25_list_lock);
return lci;
}
/*
* Deferred destroy.
*/
static void __x25_destroy_socket(struct sock *);
/*
* handler for deferred kills.
*/
static void x25_destroy_timer(unsigned long data)
{
x25_destroy_socket_from_timer((struct sock *)data);
}
/*
* This is called from user mode and the timers. Thus it protects itself
* against interrupt users but doesn't worry about being called during
* work. Once it is removed from the queue no interrupt or bottom half
* will touch it and we are (fairly 8-) ) safe.
* Not static as it's used by the timer
*/
static void __x25_destroy_socket(struct sock *sk)
{
struct sk_buff *skb;
x25_stop_heartbeat(sk);
x25_stop_timer(sk);
x25_remove_socket(sk);
x25_clear_queues(sk); /* Flush the queues */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (skb->sk != sk) { /* A pending connection */
/*
* Queue the unaccepted socket for death
*/
skb->sk->sk_state = TCP_LISTEN;
sock_set_flag(skb->sk, SOCK_DEAD);
x25_start_heartbeat(skb->sk);
x25_sk(skb->sk)->state = X25_STATE_0;
}
kfree_skb(skb);
}
if (sk_has_allocations(sk)) {
/* Defer: outstanding buffers */
sk->sk_timer.expires = jiffies + 10 * HZ;
sk->sk_timer.function = x25_destroy_timer;
sk->sk_timer.data = (unsigned long)sk;
add_timer(&sk->sk_timer);
} else {
/* drop last reference so sock_put will free */
__sock_put(sk);
}
}
void x25_destroy_socket_from_timer(struct sock *sk)
{
sock_hold(sk);
bh_lock_sock(sk);
__x25_destroy_socket(sk);
bh_unlock_sock(sk);
sock_put(sk);
}
/*
* Handling for system calls applied via the various interfaces to a
* X.25 socket object.
*/
static int x25_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
int opt;
struct sock *sk = sock->sk;
int rc = -ENOPROTOOPT;
if (level != SOL_X25 || optname != X25_QBITINCL)
goto out;
rc = -EINVAL;
if (optlen < sizeof(int))
goto out;
rc = -EFAULT;
if (get_user(opt, (int __user *)optval))
goto out;
if (opt)
set_bit(X25_Q_BIT_FLAG, &x25_sk(sk)->flags);
else
clear_bit(X25_Q_BIT_FLAG, &x25_sk(sk)->flags);
rc = 0;
out:
return rc;
}
static int x25_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
int val, len, rc = -ENOPROTOOPT;
if (level != SOL_X25 || optname != X25_QBITINCL)
goto out;
rc = -EFAULT;
if (get_user(len, optlen))
goto out;
len = min_t(unsigned int, len, sizeof(int));
rc = -EINVAL;
if (len < 0)
goto out;
rc = -EFAULT;
if (put_user(len, optlen))
goto out;
val = test_bit(X25_Q_BIT_FLAG, &x25_sk(sk)->flags);
rc = copy_to_user(optval, &val, len) ? -EFAULT : 0;
out:
return rc;
}
static int x25_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int rc = -EOPNOTSUPP;
lock_sock(sk);
if (sk->sk_state != TCP_LISTEN) {
memset(&x25_sk(sk)->dest_addr, 0, X25_ADDR_LEN);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
rc = 0;
}
release_sock(sk);
return rc;
}
static struct proto x25_proto = {
.name = "X25",
.owner = THIS_MODULE,
.obj_size = sizeof(struct x25_sock),
};
static struct sock *x25_alloc_socket(struct net *net)
{
struct x25_sock *x25;
struct sock *sk = sk_alloc(net, AF_X25, GFP_ATOMIC, &x25_proto);
if (!sk)
goto out;
sock_init_data(NULL, sk);
x25 = x25_sk(sk);
skb_queue_head_init(&x25->ack_queue);
skb_queue_head_init(&x25->fragment_queue);
skb_queue_head_init(&x25->interrupt_in_queue);
skb_queue_head_init(&x25->interrupt_out_queue);
out:
return sk;
}
static int x25_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct x25_sock *x25;
int rc = -EAFNOSUPPORT;
if (!net_eq(net, &init_net))
goto out;
rc = -ESOCKTNOSUPPORT;
if (sock->type != SOCK_SEQPACKET)
goto out;
rc = -EINVAL;
if (protocol)
goto out;
rc = -ENOBUFS;
if ((sk = x25_alloc_socket(net)) == NULL)
goto out;
x25 = x25_sk(sk);
sock_init_data(sock, sk);
x25_init_timers(sk);
sock->ops = &x25_proto_ops;
sk->sk_protocol = protocol;
sk->sk_backlog_rcv = x25_backlog_rcv;
x25->t21 = sysctl_x25_call_request_timeout;
x25->t22 = sysctl_x25_reset_request_timeout;
x25->t23 = sysctl_x25_clear_request_timeout;
x25->t2 = sysctl_x25_ack_holdback_timeout;
x25->state = X25_STATE_0;
x25->cudmatchlength = 0;
set_bit(X25_ACCPT_APPRV_FLAG, &x25->flags); /* normally no cud */
/* on call accept */
x25->facilities.winsize_in = X25_DEFAULT_WINDOW_SIZE;
x25->facilities.winsize_out = X25_DEFAULT_WINDOW_SIZE;
x25->facilities.pacsize_in = X25_DEFAULT_PACKET_SIZE;
x25->facilities.pacsize_out = X25_DEFAULT_PACKET_SIZE;
x25->facilities.throughput = 0; /* by default don't negotiate
throughput */
x25->facilities.reverse = X25_DEFAULT_REVERSE;
x25->dte_facilities.calling_len = 0;
x25->dte_facilities.called_len = 0;
memset(x25->dte_facilities.called_ae, '\0',
sizeof(x25->dte_facilities.called_ae));
memset(x25->dte_facilities.calling_ae, '\0',
sizeof(x25->dte_facilities.calling_ae));
rc = 0;
out:
return rc;
}
static struct sock *x25_make_new(struct sock *osk)
{
struct sock *sk = NULL;
struct x25_sock *x25, *ox25;
if (osk->sk_type != SOCK_SEQPACKET)
goto out;
if ((sk = x25_alloc_socket(sock_net(osk))) == NULL)
goto out;
x25 = x25_sk(sk);
sk->sk_type = osk->sk_type;
sk->sk_priority = osk->sk_priority;
sk->sk_protocol = osk->sk_protocol;
sk->sk_rcvbuf = osk->sk_rcvbuf;
sk->sk_sndbuf = osk->sk_sndbuf;
sk->sk_state = TCP_ESTABLISHED;
sk->sk_backlog_rcv = osk->sk_backlog_rcv;
sock_copy_flags(sk, osk);
ox25 = x25_sk(osk);
x25->t21 = ox25->t21;
x25->t22 = ox25->t22;
x25->t23 = ox25->t23;
x25->t2 = ox25->t2;
x25->flags = ox25->flags;
x25->facilities = ox25->facilities;
x25->dte_facilities = ox25->dte_facilities;
x25->cudmatchlength = ox25->cudmatchlength;
clear_bit(X25_INTERRUPT_FLAG, &x25->flags);
x25_init_timers(sk);
out:
return sk;
}
static int x25_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct x25_sock *x25;
if (!sk)
return 0;
x25 = x25_sk(sk);
sock_hold(sk);
lock_sock(sk);
switch (x25->state) {
case X25_STATE_0:
case X25_STATE_2:
x25_disconnect(sk, 0, 0, 0);
__x25_destroy_socket(sk);
goto out;
case X25_STATE_1:
case X25_STATE_3:
case X25_STATE_4:
x25_clear_queues(sk);
x25_write_internal(sk, X25_CLEAR_REQUEST);
x25_start_t23timer(sk);
x25->state = X25_STATE_2;
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
sock_set_flag(sk, SOCK_DESTROY);
break;
}
sock_orphan(sk);
out:
release_sock(sk);
sock_put(sk);
return 0;
}
static int x25_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_x25 *addr = (struct sockaddr_x25 *)uaddr;
int len, i, rc = 0;
if (!sock_flag(sk, SOCK_ZAPPED) ||
addr_len != sizeof(struct sockaddr_x25) ||
addr->sx25_family != AF_X25) {
rc = -EINVAL;
goto out;
}
len = strlen(addr->sx25_addr.x25_addr);
for (i = 0; i < len; i++) {
if (!isdigit(addr->sx25_addr.x25_addr[i])) {
rc = -EINVAL;
goto out;
}
}
lock_sock(sk);
x25_sk(sk)->source_addr = addr->sx25_addr;
x25_insert_socket(sk);
sock_reset_flag(sk, SOCK_ZAPPED);
release_sock(sk);
SOCK_DEBUG(sk, "x25_bind: socket is bound\n");
out:
return rc;
}
static int x25_wait_for_connection_establishment(struct sock *sk)
{
DECLARE_WAITQUEUE(wait, current);
int rc;
add_wait_queue_exclusive(sk_sleep(sk), &wait);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = sock_error(sk);
if (rc) {
sk->sk_socket->state = SS_UNCONNECTED;
break;
}
rc = 0;
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
schedule();
lock_sock(sk);
} else
break;
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return rc;
}
static int x25_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *addr = (struct sockaddr_x25 *)uaddr;
struct x25_route *rt;
int rc = 0;
lock_sock(sk);
if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
sock->state = SS_CONNECTED;
goto out; /* Connect completed during a ERESTARTSYS event */
}
rc = -ECONNREFUSED;
if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) {
sock->state = SS_UNCONNECTED;
goto out;
}
rc = -EISCONN; /* No reconnect on a seqpacket socket */
if (sk->sk_state == TCP_ESTABLISHED)
goto out;
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
rc = -EINVAL;
if (addr_len != sizeof(struct sockaddr_x25) ||
addr->sx25_family != AF_X25)
goto out;
rc = -ENETUNREACH;
rt = x25_get_route(&addr->sx25_addr);
if (!rt)
goto out;
x25->neighbour = x25_get_neigh(rt->dev);
if (!x25->neighbour)
goto out_put_route;
x25_limit_facilities(&x25->facilities, x25->neighbour);
x25->lci = x25_new_lci(x25->neighbour);
if (!x25->lci)
goto out_put_neigh;
rc = -EINVAL;
if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */
goto out_put_neigh;
if (!strcmp(x25->source_addr.x25_addr, null_x25_address.x25_addr))
memset(&x25->source_addr, '\0', X25_ADDR_LEN);
x25->dest_addr = addr->sx25_addr;
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
x25->state = X25_STATE_1;
x25_write_internal(sk, X25_CALL_REQUEST);
x25_start_heartbeat(sk);
x25_start_t21timer(sk);
/* Now the loop */
rc = -EINPROGRESS;
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK))
goto out_put_neigh;
rc = x25_wait_for_connection_establishment(sk);
if (rc)
goto out_put_neigh;
sock->state = SS_CONNECTED;
rc = 0;
out_put_neigh:
if (rc)
x25_neigh_put(x25->neighbour);
out_put_route:
x25_route_put(rt);
out:
release_sock(sk);
return rc;
}
static int x25_wait_for_data(struct sock *sk, long timeout)
{
DECLARE_WAITQUEUE(wait, current);
int rc = 0;
add_wait_queue_exclusive(sk_sleep(sk), &wait);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = -EAGAIN;
if (!timeout)
break;
rc = 0;
if (skb_queue_empty(&sk->sk_receive_queue)) {
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
} else
break;
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return rc;
}
static int x25_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct sock *newsk;
struct sk_buff *skb;
int rc = -EINVAL;
if (!sk)
goto out;
rc = -EOPNOTSUPP;
if (sk->sk_type != SOCK_SEQPACKET)
goto out;
lock_sock(sk);
rc = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out2;
rc = x25_wait_for_data(sk, sk->sk_rcvtimeo);
if (rc)
goto out2;
skb = skb_dequeue(&sk->sk_receive_queue);
rc = -EINVAL;
if (!skb->sk)
goto out2;
newsk = skb->sk;
sock_graft(newsk, newsock);
/* Now attach up the new socket */
skb->sk = NULL;
kfree_skb(skb);
sk->sk_ack_backlog--;
newsock->state = SS_CONNECTED;
rc = 0;
out2:
release_sock(sk);
out:
return rc;
}
static int x25_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)uaddr;
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
int rc = 0;
if (peer) {
if (sk->sk_state != TCP_ESTABLISHED) {
rc = -ENOTCONN;
goto out;
}
sx25->sx25_addr = x25->dest_addr;
} else
sx25->sx25_addr = x25->source_addr;
sx25->sx25_family = AF_X25;
*uaddr_len = sizeof(*sx25);
out:
return rc;
}
int x25_rx_call_request(struct sk_buff *skb, struct x25_neigh *nb,
unsigned int lci)
{
struct sock *sk;
struct sock *make;
struct x25_sock *makex25;
struct x25_address source_addr, dest_addr;
struct x25_facilities facilities;
struct x25_dte_facilities dte_facilities;
int len, addr_len, rc;
/*
* Remove the LCI and frame type.
*/
skb_pull(skb, X25_STD_MIN_LEN);
/*
* Extract the X.25 addresses and convert them to ASCII strings,
* and remove them.
*
* Address block is mandatory in call request packets
*/
addr_len = x25_parse_address_block(skb, &source_addr, &dest_addr);
if (addr_len <= 0)
goto out_clear_request;
skb_pull(skb, addr_len);
/*
* Get the length of the facilities, skip past them for the moment
* get the call user data because this is needed to determine
* the correct listener
*
* Facilities length is mandatory in call request packets
*/
if (!pskb_may_pull(skb, 1))
goto out_clear_request;
len = skb->data[0] + 1;
if (!pskb_may_pull(skb, len))
goto out_clear_request;
skb_pull(skb,len);
/*
* Ensure that the amount of call user data is valid.
*/
if (skb->len > X25_MAX_CUD_LEN)
goto out_clear_request;
/*
* Get all the call user data so it can be used in
* x25_find_listener and skb_copy_from_linear_data up ahead.
*/
if (!pskb_may_pull(skb, skb->len))
goto out_clear_request;
/*
* Find a listener for the particular address/cud pair.
*/
sk = x25_find_listener(&source_addr,skb);
skb_push(skb,len);
if (sk != NULL && sk_acceptq_is_full(sk)) {
goto out_sock_put;
}
/*
* We dont have any listeners for this incoming call.
* Try forwarding it.
*/
if (sk == NULL) {
skb_push(skb, addr_len + X25_STD_MIN_LEN);
if (sysctl_x25_forward &&
x25_forward_call(&dest_addr, nb, skb, lci) > 0)
{
/* Call was forwarded, dont process it any more */
kfree_skb(skb);
rc = 1;
goto out;
} else {
/* No listeners, can't forward, clear the call */
goto out_clear_request;
}
}
/*
* Try to reach a compromise on the requested facilities.
*/
len = x25_negotiate_facilities(skb, sk, &facilities, &dte_facilities);
if (len == -1)
goto out_sock_put;
/*
* current neighbour/link might impose additional limits
* on certain facilties
*/
x25_limit_facilities(&facilities, nb);
/*
* Try to create a new socket.
*/
make = x25_make_new(sk);
if (!make)
goto out_sock_put;
/*
* Remove the facilities
*/
skb_pull(skb, len);
skb->sk = make;
make->sk_state = TCP_ESTABLISHED;
makex25 = x25_sk(make);
makex25->lci = lci;
makex25->dest_addr = dest_addr;
makex25->source_addr = source_addr;
makex25->neighbour = nb;
makex25->facilities = facilities;
makex25->dte_facilities= dte_facilities;
makex25->vc_facil_mask = x25_sk(sk)->vc_facil_mask;
/* ensure no reverse facil on accept */
makex25->vc_facil_mask &= ~X25_MASK_REVERSE;
/* ensure no calling address extension on accept */
makex25->vc_facil_mask &= ~X25_MASK_CALLING_AE;
makex25->cudmatchlength = x25_sk(sk)->cudmatchlength;
/* Normally all calls are accepted immediately */
if (test_bit(X25_ACCPT_APPRV_FLAG, &makex25->flags)) {
x25_write_internal(make, X25_CALL_ACCEPTED);
makex25->state = X25_STATE_3;
}
/*
* Incoming Call User Data.
*/
skb_copy_from_linear_data(skb, makex25->calluserdata.cuddata, skb->len);
makex25->calluserdata.cudlength = skb->len;
sk->sk_ack_backlog++;
x25_insert_socket(make);
skb_queue_head(&sk->sk_receive_queue, skb);
x25_start_heartbeat(make);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, skb->len);
rc = 1;
sock_put(sk);
out:
return rc;
out_sock_put:
sock_put(sk);
out_clear_request:
rc = 0;
x25_transmit_clear_request(nb, lci, 0x01);
goto out;
}
static int x25_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *usx25 = (struct sockaddr_x25 *)msg->msg_name;
struct sockaddr_x25 sx25;
struct sk_buff *skb;
unsigned char *asmptr;
int noblock = msg->msg_flags & MSG_DONTWAIT;
size_t size;
int qbit = 0, rc = -EINVAL;
lock_sock(sk);
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_OOB|MSG_EOR|MSG_CMSG_COMPAT))
goto out;
/* we currently don't support segmented records at the user interface */
if (!(msg->msg_flags & (MSG_EOR|MSG_OOB)))
goto out;
rc = -EADDRNOTAVAIL;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
rc = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
goto out;
}
rc = -ENETUNREACH;
if (!x25->neighbour)
goto out;
if (usx25) {
rc = -EINVAL;
if (msg->msg_namelen < sizeof(sx25))
goto out;
memcpy(&sx25, usx25, sizeof(sx25));
rc = -EISCONN;
if (strcmp(x25->dest_addr.x25_addr, sx25.sx25_addr.x25_addr))
goto out;
rc = -EINVAL;
if (sx25.sx25_family != AF_X25)
goto out;
} else {
/*
* FIXME 1003.1g - if the socket is like this because
* it has become closed (not started closed) we ought
* to SIGPIPE, EPIPE;
*/
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
sx25.sx25_family = AF_X25;
sx25.sx25_addr = x25->dest_addr;
}
/* Sanity check the packet size */
if (len > 65535) {
rc = -EMSGSIZE;
goto out;
}
SOCK_DEBUG(sk, "x25_sendmsg: sendto: Addresses built.\n");
/* Build a packet */
SOCK_DEBUG(sk, "x25_sendmsg: sendto: building packet.\n");
if ((msg->msg_flags & MSG_OOB) && len > 32)
len = 32;
size = len + X25_MAX_L2_LEN + X25_EXT_MIN_LEN;
release_sock(sk);
skb = sock_alloc_send_skb(sk, size, noblock, &rc);
lock_sock(sk);
if (!skb)
goto out;
X25_SKB_CB(skb)->flags = msg->msg_flags;
skb_reserve(skb, X25_MAX_L2_LEN + X25_EXT_MIN_LEN);
/*
* Put the data on the end
*/
SOCK_DEBUG(sk, "x25_sendmsg: Copying user data\n");
skb_reset_transport_header(skb);
skb_put(skb, len);
rc = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (rc)
goto out_kfree_skb;
/*
* If the Q BIT Include socket option is in force, the first
* byte of the user data is the logical value of the Q Bit.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
if (!pskb_may_pull(skb, 1))
goto out_kfree_skb;
qbit = skb->data[0];
skb_pull(skb, 1);
}
/*
* Push down the X.25 header
*/
SOCK_DEBUG(sk, "x25_sendmsg: Building X.25 Header.\n");
if (msg->msg_flags & MSG_OOB) {
if (x25->neighbour->extended) {
asmptr = skb_push(skb, X25_STD_MIN_LEN);
*asmptr++ = ((x25->lci >> 8) & 0x0F) | X25_GFI_EXTSEQ;
*asmptr++ = (x25->lci >> 0) & 0xFF;
*asmptr++ = X25_INTERRUPT;
} else {
asmptr = skb_push(skb, X25_STD_MIN_LEN);
*asmptr++ = ((x25->lci >> 8) & 0x0F) | X25_GFI_STDSEQ;
*asmptr++ = (x25->lci >> 0) & 0xFF;
*asmptr++ = X25_INTERRUPT;
}
} else {
if (x25->neighbour->extended) {
/* Build an Extended X.25 header */
asmptr = skb_push(skb, X25_EXT_MIN_LEN);
*asmptr++ = ((x25->lci >> 8) & 0x0F) | X25_GFI_EXTSEQ;
*asmptr++ = (x25->lci >> 0) & 0xFF;
*asmptr++ = X25_DATA;
*asmptr++ = X25_DATA;
} else {
/* Build an Standard X.25 header */
asmptr = skb_push(skb, X25_STD_MIN_LEN);
*asmptr++ = ((x25->lci >> 8) & 0x0F) | X25_GFI_STDSEQ;
*asmptr++ = (x25->lci >> 0) & 0xFF;
*asmptr++ = X25_DATA;
}
if (qbit)
skb->data[0] |= X25_Q_BIT;
}
SOCK_DEBUG(sk, "x25_sendmsg: Built header.\n");
SOCK_DEBUG(sk, "x25_sendmsg: Transmitting buffer\n");
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out_kfree_skb;
if (msg->msg_flags & MSG_OOB)
skb_queue_tail(&x25->interrupt_out_queue, skb);
else {
rc = x25_output(sk, skb);
len = rc;
if (rc < 0)
kfree_skb(skb);
else if (test_bit(X25_Q_BIT_FLAG, &x25->flags))
len++;
}
x25_kick(sk);
rc = len;
out:
release_sock(sk);
return rc;
out_kfree_skb:
kfree_skb(skb);
goto out;
}
static int x25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name;
size_t copied;
int qbit, header_len;
struct sk_buff *skb;
unsigned char *asmptr;
int rc = -ENOTCONN;
lock_sock(sk);
if (x25->neighbour == NULL)
goto out;
header_len = x25->neighbour->extended ?
X25_EXT_MIN_LEN : X25_STD_MIN_LEN;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if (flags & MSG_OOB) {
rc = -EINVAL;
if (sock_flag(sk, SOCK_URGINLINE) ||
!skb_peek(&x25->interrupt_in_queue))
goto out;
skb = skb_dequeue(&x25->interrupt_in_queue);
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
goto out_free_dgram;
skb_pull(skb, X25_STD_MIN_LEN);
/*
* No Q bit information on Interrupt data.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = 0x00;
}
msg->msg_flags |= MSG_OOB;
} else {
/* Now we can treat all alike */
release_sock(sk);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
lock_sock(sk);
if (!skb)
goto out;
if (!pskb_may_pull(skb, header_len))
goto out_free_dgram;
qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT;
skb_pull(skb, header_len);
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
/* Currently, each datagram always contains a complete record */
msg->msg_flags |= MSG_EOR;
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (rc)
goto out_free_dgram;
if (sx25) {
sx25->sx25_family = AF_X25;
sx25->sx25_addr = x25->dest_addr;
msg->msg_namelen = sizeof(*sx25);
}
x25_check_rbuf(sk);
rc = copied;
out_free_dgram:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
static int x25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
void __user *argp = (void __user *)arg;
int rc;
switch (cmd) {
case TIOCOUTQ: {
int amount;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
rc = put_user(amount, (unsigned int __user *)argp);
break;
}
case TIOCINQ: {
struct sk_buff *skb;
int amount = 0;
/*
* These two are safe on a single CPU system as
* only user tasks fiddle here
*/
lock_sock(sk);
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
release_sock(sk);
rc = put_user(amount, (unsigned int __user *)argp);
break;
}
case SIOCGSTAMP:
rc = -EINVAL;
if (sk)
rc = sock_get_timestamp(sk,
(struct timeval __user *)argp);
break;
case SIOCGSTAMPNS:
rc = -EINVAL;
if (sk)
rc = sock_get_timestampns(sk,
(struct timespec __user *)argp);
break;
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
rc = -EINVAL;
break;
case SIOCADDRT:
case SIOCDELRT:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = x25_route_ioctl(cmd, argp);
break;
case SIOCX25GSUBSCRIP:
rc = x25_subscr_ioctl(cmd, argp);
break;
case SIOCX25SSUBSCRIP:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = x25_subscr_ioctl(cmd, argp);
break;
case SIOCX25GFACILITIES: {
lock_sock(sk);
rc = copy_to_user(argp, &x25->facilities,
sizeof(x25->facilities))
? -EFAULT : 0;
release_sock(sk);
break;
}
case SIOCX25SFACILITIES: {
struct x25_facilities facilities;
rc = -EFAULT;
if (copy_from_user(&facilities, argp, sizeof(facilities)))
break;
rc = -EINVAL;
lock_sock(sk);
if (sk->sk_state != TCP_LISTEN &&
sk->sk_state != TCP_CLOSE)
goto out_fac_release;
if (facilities.pacsize_in < X25_PS16 ||
facilities.pacsize_in > X25_PS4096)
goto out_fac_release;
if (facilities.pacsize_out < X25_PS16 ||
facilities.pacsize_out > X25_PS4096)
goto out_fac_release;
if (facilities.winsize_in < 1 ||
facilities.winsize_in > 127)
goto out_fac_release;
if (facilities.throughput) {
int out = facilities.throughput & 0xf0;
int in = facilities.throughput & 0x0f;
if (!out)
facilities.throughput |=
X25_DEFAULT_THROUGHPUT << 4;
else if (out < 0x30 || out > 0xD0)
goto out_fac_release;
if (!in)
facilities.throughput |=
X25_DEFAULT_THROUGHPUT;
else if (in < 0x03 || in > 0x0D)
goto out_fac_release;
}
if (facilities.reverse &&
(facilities.reverse & 0x81) != 0x81)
goto out_fac_release;
x25->facilities = facilities;
rc = 0;
out_fac_release:
release_sock(sk);
break;
}
case SIOCX25GDTEFACILITIES: {
lock_sock(sk);
rc = copy_to_user(argp, &x25->dte_facilities,
sizeof(x25->dte_facilities));
release_sock(sk);
if (rc)
rc = -EFAULT;
break;
}
case SIOCX25SDTEFACILITIES: {
struct x25_dte_facilities dtefacs;
rc = -EFAULT;
if (copy_from_user(&dtefacs, argp, sizeof(dtefacs)))
break;
rc = -EINVAL;
lock_sock(sk);
if (sk->sk_state != TCP_LISTEN &&
sk->sk_state != TCP_CLOSE)
goto out_dtefac_release;
if (dtefacs.calling_len > X25_MAX_AE_LEN)
goto out_dtefac_release;
if (dtefacs.calling_ae == NULL)
goto out_dtefac_release;
if (dtefacs.called_len > X25_MAX_AE_LEN)
goto out_dtefac_release;
if (dtefacs.called_ae == NULL)
goto out_dtefac_release;
x25->dte_facilities = dtefacs;
rc = 0;
out_dtefac_release:
release_sock(sk);
break;
}
case SIOCX25GCALLUSERDATA: {
lock_sock(sk);
rc = copy_to_user(argp, &x25->calluserdata,
sizeof(x25->calluserdata))
? -EFAULT : 0;
release_sock(sk);
break;
}
case SIOCX25SCALLUSERDATA: {
struct x25_calluserdata calluserdata;
rc = -EFAULT;
if (copy_from_user(&calluserdata, argp, sizeof(calluserdata)))
break;
rc = -EINVAL;
if (calluserdata.cudlength > X25_MAX_CUD_LEN)
break;
lock_sock(sk);
x25->calluserdata = calluserdata;
release_sock(sk);
rc = 0;
break;
}
case SIOCX25GCAUSEDIAG: {
lock_sock(sk);
rc = copy_to_user(argp, &x25->causediag, sizeof(x25->causediag))
? -EFAULT : 0;
release_sock(sk);
break;
}
case SIOCX25SCAUSEDIAG: {
struct x25_causediag causediag;
rc = -EFAULT;
if (copy_from_user(&causediag, argp, sizeof(causediag)))
break;
lock_sock(sk);
x25->causediag = causediag;
release_sock(sk);
rc = 0;
break;
}
case SIOCX25SCUDMATCHLEN: {
struct x25_subaddr sub_addr;
rc = -EINVAL;
lock_sock(sk);
if(sk->sk_state != TCP_CLOSE)
goto out_cud_release;
rc = -EFAULT;
if (copy_from_user(&sub_addr, argp,
sizeof(sub_addr)))
goto out_cud_release;
rc = -EINVAL;
if (sub_addr.cudmatchlength > X25_MAX_CUD_LEN)
goto out_cud_release;
x25->cudmatchlength = sub_addr.cudmatchlength;
rc = 0;
out_cud_release:
release_sock(sk);
break;
}
case SIOCX25CALLACCPTAPPRV: {
rc = -EINVAL;
lock_sock(sk);
if (sk->sk_state == TCP_CLOSE) {
clear_bit(X25_ACCPT_APPRV_FLAG, &x25->flags);
rc = 0;
}
release_sock(sk);
break;
}
case SIOCX25SENDCALLACCPT: {
rc = -EINVAL;
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED)
goto out_sendcallaccpt_release;
/* must call accptapprv above */
if (test_bit(X25_ACCPT_APPRV_FLAG, &x25->flags))
goto out_sendcallaccpt_release;
x25_write_internal(sk, X25_CALL_ACCEPTED);
x25->state = X25_STATE_3;
rc = 0;
out_sendcallaccpt_release:
release_sock(sk);
break;
}
default:
rc = -ENOIOCTLCMD;
break;
}
return rc;
}
static const struct net_proto_family x25_family_ops = {
.family = AF_X25,
.create = x25_create,
.owner = THIS_MODULE,
};
#ifdef CONFIG_COMPAT
static int compat_x25_subscr_ioctl(unsigned int cmd,
struct compat_x25_subscrip_struct __user *x25_subscr32)
{
struct compat_x25_subscrip_struct x25_subscr;
struct x25_neigh *nb;
struct net_device *dev;
int rc = -EINVAL;
rc = -EFAULT;
if (copy_from_user(&x25_subscr, x25_subscr32, sizeof(*x25_subscr32)))
goto out;
rc = -EINVAL;
dev = x25_dev_get(x25_subscr.device);
if (dev == NULL)
goto out;
nb = x25_get_neigh(dev);
if (nb == NULL)
goto out_dev_put;
dev_put(dev);
if (cmd == SIOCX25GSUBSCRIP) {
read_lock_bh(&x25_neigh_list_lock);
x25_subscr.extended = nb->extended;
x25_subscr.global_facil_mask = nb->global_facil_mask;
read_unlock_bh(&x25_neigh_list_lock);
rc = copy_to_user(x25_subscr32, &x25_subscr,
sizeof(*x25_subscr32)) ? -EFAULT : 0;
} else {
rc = -EINVAL;
if (x25_subscr.extended == 0 || x25_subscr.extended == 1) {
rc = 0;
write_lock_bh(&x25_neigh_list_lock);
nb->extended = x25_subscr.extended;
nb->global_facil_mask = x25_subscr.global_facil_mask;
write_unlock_bh(&x25_neigh_list_lock);
}
}
x25_neigh_put(nb);
out:
return rc;
out_dev_put:
dev_put(dev);
goto out;
}
static int compat_x25_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
void __user *argp = compat_ptr(arg);
struct sock *sk = sock->sk;
int rc = -ENOIOCTLCMD;
switch(cmd) {
case TIOCOUTQ:
case TIOCINQ:
rc = x25_ioctl(sock, cmd, (unsigned long)argp);
break;
case SIOCGSTAMP:
rc = -EINVAL;
if (sk)
rc = compat_sock_get_timestamp(sk,
(struct timeval __user*)argp);
break;
case SIOCGSTAMPNS:
rc = -EINVAL;
if (sk)
rc = compat_sock_get_timestampns(sk,
(struct timespec __user*)argp);
break;
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
rc = -EINVAL;
break;
case SIOCADDRT:
case SIOCDELRT:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = x25_route_ioctl(cmd, argp);
break;
case SIOCX25GSUBSCRIP:
rc = compat_x25_subscr_ioctl(cmd, argp);
break;
case SIOCX25SSUBSCRIP:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = compat_x25_subscr_ioctl(cmd, argp);
break;
case SIOCX25GFACILITIES:
case SIOCX25SFACILITIES:
case SIOCX25GDTEFACILITIES:
case SIOCX25SDTEFACILITIES:
case SIOCX25GCALLUSERDATA:
case SIOCX25SCALLUSERDATA:
case SIOCX25GCAUSEDIAG:
case SIOCX25SCAUSEDIAG:
case SIOCX25SCUDMATCHLEN:
case SIOCX25CALLACCPTAPPRV:
case SIOCX25SENDCALLACCPT:
rc = x25_ioctl(sock, cmd, (unsigned long)argp);
break;
default:
rc = -ENOIOCTLCMD;
break;
}
return rc;
}
#endif
static const struct proto_ops x25_proto_ops = {
.family = AF_X25,
.owner = THIS_MODULE,
.release = x25_release,
.bind = x25_bind,
.connect = x25_connect,
.socketpair = sock_no_socketpair,
.accept = x25_accept,
.getname = x25_getname,
.poll = datagram_poll,
.ioctl = x25_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = compat_x25_ioctl,
#endif
.listen = x25_listen,
.shutdown = sock_no_shutdown,
.setsockopt = x25_setsockopt,
.getsockopt = x25_getsockopt,
.sendmsg = x25_sendmsg,
.recvmsg = x25_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct packet_type x25_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_X25),
.func = x25_lapb_receive_frame,
};
static struct notifier_block x25_dev_notifier = {
.notifier_call = x25_device_event,
};
void x25_kill_by_neigh(struct x25_neigh *nb)
{
struct sock *s;
struct hlist_node *node;
write_lock_bh(&x25_list_lock);
sk_for_each(s, node, &x25_list)
if (x25_sk(s)->neighbour == nb)
x25_disconnect(s, ENETUNREACH, 0, 0);
write_unlock_bh(&x25_list_lock);
/* Remove any related forwards */
x25_clear_forward_by_dev(nb->dev);
}
static int __init x25_init(void)
{
int rc = proto_register(&x25_proto, 0);
if (rc != 0)
goto out;
rc = sock_register(&x25_family_ops);
if (rc != 0)
goto out_proto;
dev_add_pack(&x25_packet_type);
rc = register_netdevice_notifier(&x25_dev_notifier);
if (rc != 0)
goto out_sock;
printk(KERN_INFO "X.25 for Linux Version 0.2\n");
x25_register_sysctl();
rc = x25_proc_init();
if (rc != 0)
goto out_dev;
out:
return rc;
out_dev:
unregister_netdevice_notifier(&x25_dev_notifier);
out_sock:
sock_unregister(AF_X25);
out_proto:
proto_unregister(&x25_proto);
goto out;
}
module_init(x25_init);
static void __exit x25_exit(void)
{
x25_proc_exit();
x25_link_free();
x25_route_free();
x25_unregister_sysctl();
unregister_netdevice_notifier(&x25_dev_notifier);
dev_remove_pack(&x25_packet_type);
sock_unregister(AF_X25);
proto_unregister(&x25_proto);
}
module_exit(x25_exit);
MODULE_AUTHOR("Jonathan Naylor <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The X.25 Packet Layer network layer protocol");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_X25);
| gpl-2.0 |
XCage15/linux | sound/core/pcm_memory.c | 1247 | 13836 | /*
* Digital Audio (PCM) abstract layer
* 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/io.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
#include <linux/vmalloc.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/info.h>
#include <sound/initval.h>
static int preallocate_dma = 1;
module_param(preallocate_dma, int, 0444);
MODULE_PARM_DESC(preallocate_dma, "Preallocate DMA memory when the PCM devices are initialized.");
static int maximum_substreams = 4;
module_param(maximum_substreams, int, 0444);
MODULE_PARM_DESC(maximum_substreams, "Maximum substreams with preallocated DMA memory.");
static const size_t snd_minimum_buffer = 16384;
/*
* try to allocate as the large pages as possible.
* stores the resultant memory size in *res_size.
*
* the minimum size is snd_minimum_buffer. it should be power of 2.
*/
static int preallocate_pcm_pages(struct snd_pcm_substream *substream, size_t size)
{
struct snd_dma_buffer *dmab = &substream->dma_buffer;
size_t orig_size = size;
int err;
do {
if ((err = snd_dma_alloc_pages(dmab->dev.type, dmab->dev.dev,
size, dmab)) < 0) {
if (err != -ENOMEM)
return err; /* fatal error */
} else
return 0;
size >>= 1;
} while (size >= snd_minimum_buffer);
dmab->bytes = 0; /* tell error */
pr_warn("ALSA pcmC%dD%d%c,%d:%s: cannot preallocate for size %zu\n",
substream->pcm->card->number, substream->pcm->device,
substream->stream ? 'c' : 'p', substream->number,
substream->pcm->name, orig_size);
return 0;
}
/*
* release the preallocated buffer if not yet done.
*/
static void snd_pcm_lib_preallocate_dma_free(struct snd_pcm_substream *substream)
{
if (substream->dma_buffer.area == NULL)
return;
snd_dma_free_pages(&substream->dma_buffer);
substream->dma_buffer.area = NULL;
}
/**
* snd_pcm_lib_preallocate_free - release the preallocated buffer of the specified substream.
* @substream: the pcm substream instance
*
* Releases the pre-allocated buffer of the given substream.
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_preallocate_free(struct snd_pcm_substream *substream)
{
snd_pcm_lib_preallocate_dma_free(substream);
#ifdef CONFIG_SND_VERBOSE_PROCFS
snd_info_free_entry(substream->proc_prealloc_max_entry);
substream->proc_prealloc_max_entry = NULL;
snd_info_free_entry(substream->proc_prealloc_entry);
substream->proc_prealloc_entry = NULL;
#endif
return 0;
}
/**
* snd_pcm_lib_preallocate_free_for_all - release all pre-allocated buffers on the pcm
* @pcm: the pcm instance
*
* Releases all the pre-allocated buffers on the given pcm.
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_preallocate_free_for_all(struct snd_pcm *pcm)
{
struct snd_pcm_substream *substream;
int stream;
for (stream = 0; stream < 2; stream++)
for (substream = pcm->streams[stream].substream; substream; substream = substream->next)
snd_pcm_lib_preallocate_free(substream);
return 0;
}
EXPORT_SYMBOL(snd_pcm_lib_preallocate_free_for_all);
#ifdef CONFIG_SND_VERBOSE_PROCFS
/*
* read callback for prealloc proc file
*
* prints the current allocated size in kB.
*/
static void snd_pcm_lib_preallocate_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
snd_iprintf(buffer, "%lu\n", (unsigned long) substream->dma_buffer.bytes / 1024);
}
/*
* read callback for prealloc_max proc file
*
* prints the maximum allowed size in kB.
*/
static void snd_pcm_lib_preallocate_max_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
snd_iprintf(buffer, "%lu\n", (unsigned long) substream->dma_max / 1024);
}
/*
* write callback for prealloc proc file
*
* accepts the preallocation size in kB.
*/
static void snd_pcm_lib_preallocate_proc_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
char line[64], str[64];
size_t size;
struct snd_dma_buffer new_dmab;
if (substream->runtime) {
buffer->error = -EBUSY;
return;
}
if (!snd_info_get_line(buffer, line, sizeof(line))) {
snd_info_get_str(str, line, sizeof(str));
size = simple_strtoul(str, NULL, 10) * 1024;
if ((size != 0 && size < 8192) || size > substream->dma_max) {
buffer->error = -EINVAL;
return;
}
if (substream->dma_buffer.bytes == size)
return;
memset(&new_dmab, 0, sizeof(new_dmab));
new_dmab.dev = substream->dma_buffer.dev;
if (size > 0) {
if (snd_dma_alloc_pages(substream->dma_buffer.dev.type,
substream->dma_buffer.dev.dev,
size, &new_dmab) < 0) {
buffer->error = -ENOMEM;
return;
}
substream->buffer_bytes_max = size;
} else {
substream->buffer_bytes_max = UINT_MAX;
}
if (substream->dma_buffer.area)
snd_dma_free_pages(&substream->dma_buffer);
substream->dma_buffer = new_dmab;
} else {
buffer->error = -EINVAL;
}
}
static inline void preallocate_info_init(struct snd_pcm_substream *substream)
{
struct snd_info_entry *entry;
if ((entry = snd_info_create_card_entry(substream->pcm->card, "prealloc", substream->proc_root)) != NULL) {
entry->c.text.read = snd_pcm_lib_preallocate_proc_read;
entry->c.text.write = snd_pcm_lib_preallocate_proc_write;
entry->mode |= S_IWUSR;
entry->private_data = substream;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_prealloc_entry = entry;
if ((entry = snd_info_create_card_entry(substream->pcm->card, "prealloc_max", substream->proc_root)) != NULL) {
entry->c.text.read = snd_pcm_lib_preallocate_max_proc_read;
entry->private_data = substream;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_prealloc_max_entry = entry;
}
#else /* !CONFIG_SND_VERBOSE_PROCFS */
#define preallocate_info_init(s)
#endif /* CONFIG_SND_VERBOSE_PROCFS */
/*
* pre-allocate the buffer and create a proc file for the substream
*/
static int snd_pcm_lib_preallocate_pages1(struct snd_pcm_substream *substream,
size_t size, size_t max)
{
if (size > 0 && preallocate_dma && substream->number < maximum_substreams)
preallocate_pcm_pages(substream, size);
if (substream->dma_buffer.bytes > 0)
substream->buffer_bytes_max = substream->dma_buffer.bytes;
substream->dma_max = max;
preallocate_info_init(substream);
return 0;
}
/**
* snd_pcm_lib_preallocate_pages - pre-allocation for the given DMA type
* @substream: the pcm substream instance
* @type: DMA type (SNDRV_DMA_TYPE_*)
* @data: DMA type dependent data
* @size: the requested pre-allocation size in bytes
* @max: the max. allowed pre-allocation size
*
* Do pre-allocation for the given DMA buffer type.
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_preallocate_pages(struct snd_pcm_substream *substream,
int type, struct device *data,
size_t size, size_t max)
{
substream->dma_buffer.dev.type = type;
substream->dma_buffer.dev.dev = data;
return snd_pcm_lib_preallocate_pages1(substream, size, max);
}
EXPORT_SYMBOL(snd_pcm_lib_preallocate_pages);
/**
* snd_pcm_lib_preallocate_pages_for_all - pre-allocation for continuous memory type (all substreams)
* @pcm: the pcm instance
* @type: DMA type (SNDRV_DMA_TYPE_*)
* @data: DMA type dependent data
* @size: the requested pre-allocation size in bytes
* @max: the max. allowed pre-allocation size
*
* Do pre-allocation to all substreams of the given pcm for the
* specified DMA type.
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_preallocate_pages_for_all(struct snd_pcm *pcm,
int type, void *data,
size_t size, size_t max)
{
struct snd_pcm_substream *substream;
int stream, err;
for (stream = 0; stream < 2; stream++)
for (substream = pcm->streams[stream].substream; substream; substream = substream->next)
if ((err = snd_pcm_lib_preallocate_pages(substream, type, data, size, max)) < 0)
return err;
return 0;
}
EXPORT_SYMBOL(snd_pcm_lib_preallocate_pages_for_all);
#ifdef CONFIG_SND_DMA_SGBUF
/**
* snd_pcm_sgbuf_ops_page - get the page struct at the given offset
* @substream: the pcm substream instance
* @offset: the buffer offset
*
* Used as the page callback of PCM ops.
*
* Return: The page struct at the given buffer offset. %NULL on failure.
*/
struct page *snd_pcm_sgbuf_ops_page(struct snd_pcm_substream *substream, unsigned long offset)
{
struct snd_sg_buf *sgbuf = snd_pcm_substream_sgbuf(substream);
unsigned int idx = offset >> PAGE_SHIFT;
if (idx >= (unsigned int)sgbuf->pages)
return NULL;
return sgbuf->page_table[idx];
}
EXPORT_SYMBOL(snd_pcm_sgbuf_ops_page);
#endif /* CONFIG_SND_DMA_SGBUF */
/**
* snd_pcm_lib_malloc_pages - allocate the DMA buffer
* @substream: the substream to allocate the DMA buffer to
* @size: the requested buffer size in bytes
*
* Allocates the DMA buffer on the BUS type given earlier to
* snd_pcm_lib_preallocate_xxx_pages().
*
* Return: 1 if the buffer is changed, 0 if not changed, or a negative
* code on failure.
*/
int snd_pcm_lib_malloc_pages(struct snd_pcm_substream *substream, size_t size)
{
struct snd_pcm_runtime *runtime;
struct snd_dma_buffer *dmab = NULL;
if (PCM_RUNTIME_CHECK(substream))
return -EINVAL;
if (snd_BUG_ON(substream->dma_buffer.dev.type ==
SNDRV_DMA_TYPE_UNKNOWN))
return -EINVAL;
runtime = substream->runtime;
if (runtime->dma_buffer_p) {
/* perphaps, we might free the large DMA memory region
to save some space here, but the actual solution
costs us less time */
if (runtime->dma_buffer_p->bytes >= size) {
runtime->dma_bytes = size;
return 0; /* ok, do not change */
}
snd_pcm_lib_free_pages(substream);
}
if (substream->dma_buffer.area != NULL &&
substream->dma_buffer.bytes >= size) {
dmab = &substream->dma_buffer; /* use the pre-allocated buffer */
} else {
dmab = kzalloc(sizeof(*dmab), GFP_KERNEL);
if (! dmab)
return -ENOMEM;
dmab->dev = substream->dma_buffer.dev;
if (snd_dma_alloc_pages(substream->dma_buffer.dev.type,
substream->dma_buffer.dev.dev,
size, dmab) < 0) {
kfree(dmab);
return -ENOMEM;
}
}
snd_pcm_set_runtime_buffer(substream, dmab);
runtime->dma_bytes = size;
return 1; /* area was changed */
}
EXPORT_SYMBOL(snd_pcm_lib_malloc_pages);
/**
* snd_pcm_lib_free_pages - release the allocated DMA buffer.
* @substream: the substream to release the DMA buffer
*
* Releases the DMA buffer allocated via snd_pcm_lib_malloc_pages().
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_free_pages(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
if (PCM_RUNTIME_CHECK(substream))
return -EINVAL;
runtime = substream->runtime;
if (runtime->dma_area == NULL)
return 0;
if (runtime->dma_buffer_p != &substream->dma_buffer) {
/* it's a newly allocated buffer. release it now. */
snd_dma_free_pages(runtime->dma_buffer_p);
kfree(runtime->dma_buffer_p);
}
snd_pcm_set_runtime_buffer(substream, NULL);
return 0;
}
EXPORT_SYMBOL(snd_pcm_lib_free_pages);
int _snd_pcm_lib_alloc_vmalloc_buffer(struct snd_pcm_substream *substream,
size_t size, gfp_t gfp_flags)
{
struct snd_pcm_runtime *runtime;
if (PCM_RUNTIME_CHECK(substream))
return -EINVAL;
runtime = substream->runtime;
if (runtime->dma_area) {
if (runtime->dma_bytes >= size)
return 0; /* already large enough */
vfree(runtime->dma_area);
}
runtime->dma_area = __vmalloc(size, gfp_flags, PAGE_KERNEL);
if (!runtime->dma_area)
return -ENOMEM;
runtime->dma_bytes = size;
return 1;
}
EXPORT_SYMBOL(_snd_pcm_lib_alloc_vmalloc_buffer);
/**
* snd_pcm_lib_free_vmalloc_buffer - free vmalloc buffer
* @substream: the substream with a buffer allocated by
* snd_pcm_lib_alloc_vmalloc_buffer()
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_pcm_lib_free_vmalloc_buffer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
if (PCM_RUNTIME_CHECK(substream))
return -EINVAL;
runtime = substream->runtime;
vfree(runtime->dma_area);
runtime->dma_area = NULL;
return 0;
}
EXPORT_SYMBOL(snd_pcm_lib_free_vmalloc_buffer);
/**
* snd_pcm_lib_get_vmalloc_page - map vmalloc buffer offset to page struct
* @substream: the substream with a buffer allocated by
* snd_pcm_lib_alloc_vmalloc_buffer()
* @offset: offset in the buffer
*
* This function is to be used as the page callback in the PCM ops.
*
* Return: The page struct, or %NULL on failure.
*/
struct page *snd_pcm_lib_get_vmalloc_page(struct snd_pcm_substream *substream,
unsigned long offset)
{
return vmalloc_to_page(substream->runtime->dma_area + offset);
}
EXPORT_SYMBOL(snd_pcm_lib_get_vmalloc_page);
| gpl-2.0 |
coolstreamtech/cst-public-linux-kernel | arch/x86/kernel/doublefault_32.c | 2015 | 1702 | #include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/init_task.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/desc.h>
#define DOUBLEFAULT_STACKSIZE (1024)
static unsigned long doublefault_stack[DOUBLEFAULT_STACKSIZE];
#define STACK_START (unsigned long)(doublefault_stack+DOUBLEFAULT_STACKSIZE)
#define ptr_ok(x) ((x) > PAGE_OFFSET && (x) < PAGE_OFFSET + MAXMEM)
static void doublefault_fn(void)
{
struct desc_ptr gdt_desc = {0, 0};
unsigned long gdt, tss;
native_store_gdt(&gdt_desc);
gdt = gdt_desc.address;
printk(KERN_EMERG "PANIC: double fault, gdt at %08lx [%d bytes]\n", gdt, gdt_desc.size);
if (ptr_ok(gdt)) {
gdt += GDT_ENTRY_TSS << 3;
tss = get_desc_base((struct desc_struct *)gdt);
printk(KERN_EMERG "double fault, tss at %08lx\n", tss);
if (ptr_ok(tss)) {
struct x86_hw_tss *t = (struct x86_hw_tss *)tss;
printk(KERN_EMERG "eip = %08lx, esp = %08lx\n",
t->ip, t->sp);
printk(KERN_EMERG "eax = %08lx, ebx = %08lx, ecx = %08lx, edx = %08lx\n",
t->ax, t->bx, t->cx, t->dx);
printk(KERN_EMERG "esi = %08lx, edi = %08lx\n",
t->si, t->di);
}
}
for (;;)
cpu_relax();
}
struct tss_struct doublefault_tss __cacheline_aligned = {
.x86_tss = {
.sp0 = STACK_START,
.ss0 = __KERNEL_DS,
.ldt = 0,
.io_bitmap_base = INVALID_IO_BITMAP_OFFSET,
.ip = (unsigned long) doublefault_fn,
/* 0x2 bit is always set */
.flags = X86_EFLAGS_SF | 0x2,
.sp = STACK_START,
.es = __USER_DS,
.cs = __KERNEL_CS,
.ss = __KERNEL_DS,
.ds = __USER_DS,
.fs = __KERNEL_PERCPU,
.__cr3 = __pa_nodebug(swapper_pg_dir),
}
};
| gpl-2.0 |
cristianhristea/linux_kernel | arch/alpha/kernel/alpha_ksyms.c | 2271 | 2554 | /*
* linux/arch/alpha/kernel/alpha_ksyms.c
*
* Export the alpha-specific functions that are needed for loadable
* modules.
*/
#include <linux/module.h>
#include <asm/console.h>
#include <asm/uaccess.h>
#include <asm/checksum.h>
#include <asm/fpu.h>
#include <asm/machvec.h>
#include <linux/syscalls.h>
/* these are C runtime functions with special calling conventions: */
extern void __divl (void);
extern void __reml (void);
extern void __divq (void);
extern void __remq (void);
extern void __divlu (void);
extern void __remlu (void);
extern void __divqu (void);
extern void __remqu (void);
EXPORT_SYMBOL(alpha_mv);
EXPORT_SYMBOL(callback_getenv);
EXPORT_SYMBOL(callback_setenv);
EXPORT_SYMBOL(callback_save_env);
/* platform dependent support */
EXPORT_SYMBOL(strcat);
EXPORT_SYMBOL(strcpy);
EXPORT_SYMBOL(strlen);
EXPORT_SYMBOL(strncpy);
EXPORT_SYMBOL(strncat);
EXPORT_SYMBOL(strchr);
EXPORT_SYMBOL(strrchr);
EXPORT_SYMBOL(memmove);
EXPORT_SYMBOL(__memcpy);
EXPORT_SYMBOL(__memset);
EXPORT_SYMBOL(__memsetw);
EXPORT_SYMBOL(__constant_c_memset);
EXPORT_SYMBOL(copy_page);
EXPORT_SYMBOL(clear_page);
EXPORT_SYMBOL(alpha_read_fp_reg);
EXPORT_SYMBOL(alpha_read_fp_reg_s);
EXPORT_SYMBOL(alpha_write_fp_reg);
EXPORT_SYMBOL(alpha_write_fp_reg_s);
/* Networking helper routines. */
EXPORT_SYMBOL(csum_tcpudp_magic);
EXPORT_SYMBOL(ip_compute_csum);
EXPORT_SYMBOL(ip_fast_csum);
EXPORT_SYMBOL(csum_partial_copy_nocheck);
EXPORT_SYMBOL(csum_partial_copy_from_user);
EXPORT_SYMBOL(csum_ipv6_magic);
#ifdef CONFIG_MATHEMU_MODULE
extern long (*alpha_fp_emul_imprecise)(struct pt_regs *, unsigned long);
extern long (*alpha_fp_emul) (unsigned long pc);
EXPORT_SYMBOL(alpha_fp_emul_imprecise);
EXPORT_SYMBOL(alpha_fp_emul);
#endif
/*
* The following are specially called from the uaccess assembly stubs.
*/
EXPORT_SYMBOL(__copy_user);
EXPORT_SYMBOL(__do_clear_user);
/*
* SMP-specific symbols.
*/
#ifdef CONFIG_SMP
EXPORT_SYMBOL(_atomic_dec_and_lock);
#endif /* CONFIG_SMP */
/*
* The following are special because they're not called
* explicitly (the C compiler or assembler generates them in
* response to division operations). Fortunately, their
* interface isn't gonna change any time soon now, so it's OK
* to leave it out of version control.
*/
# undef memcpy
# undef memset
EXPORT_SYMBOL(__divl);
EXPORT_SYMBOL(__divlu);
EXPORT_SYMBOL(__divq);
EXPORT_SYMBOL(__divqu);
EXPORT_SYMBOL(__reml);
EXPORT_SYMBOL(__remlu);
EXPORT_SYMBOL(__remq);
EXPORT_SYMBOL(__remqu);
EXPORT_SYMBOL(memcpy);
EXPORT_SYMBOL(memset);
EXPORT_SYMBOL(memchr);
| gpl-2.0 |
jyizheng/net-next-nuse-old | arch/sh/kernel/io_trapped.c | 2527 | 6552 | /*
* Trapped io support
*
* Copyright (C) 2008 Magnus Damm
*
* Intercept io operations by trapping.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/bitops.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/init.h>
#include <asm/mmu_context.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/io_trapped.h>
#define TRAPPED_PAGES_MAX 16
#ifdef CONFIG_HAS_IOPORT_MAP
LIST_HEAD(trapped_io);
EXPORT_SYMBOL_GPL(trapped_io);
#endif
#ifdef CONFIG_HAS_IOMEM
LIST_HEAD(trapped_mem);
EXPORT_SYMBOL_GPL(trapped_mem);
#endif
static DEFINE_SPINLOCK(trapped_lock);
static int trapped_io_disable __read_mostly;
static int __init trapped_io_setup(char *__unused)
{
trapped_io_disable = 1;
return 1;
}
__setup("noiotrap", trapped_io_setup);
int register_trapped_io(struct trapped_io *tiop)
{
struct resource *res;
unsigned long len = 0, flags = 0;
struct page *pages[TRAPPED_PAGES_MAX];
int k, n;
if (unlikely(trapped_io_disable))
return 0;
/* structure must be page aligned */
if ((unsigned long)tiop & (PAGE_SIZE - 1))
goto bad;
for (k = 0; k < tiop->num_resources; k++) {
res = tiop->resource + k;
len += roundup(resource_size(res), PAGE_SIZE);
flags |= res->flags;
}
/* support IORESOURCE_IO _or_ MEM, not both */
if (hweight_long(flags) != 1)
goto bad;
n = len >> PAGE_SHIFT;
if (n >= TRAPPED_PAGES_MAX)
goto bad;
for (k = 0; k < n; k++)
pages[k] = virt_to_page(tiop);
tiop->virt_base = vmap(pages, n, VM_MAP, PAGE_NONE);
if (!tiop->virt_base)
goto bad;
len = 0;
for (k = 0; k < tiop->num_resources; k++) {
res = tiop->resource + k;
pr_info("trapped io 0x%08lx overrides %s 0x%08lx\n",
(unsigned long)(tiop->virt_base + len),
res->flags & IORESOURCE_IO ? "io" : "mmio",
(unsigned long)res->start);
len += roundup(resource_size(res), PAGE_SIZE);
}
tiop->magic = IO_TRAPPED_MAGIC;
INIT_LIST_HEAD(&tiop->list);
spin_lock_irq(&trapped_lock);
#ifdef CONFIG_HAS_IOPORT_MAP
if (flags & IORESOURCE_IO)
list_add(&tiop->list, &trapped_io);
#endif
#ifdef CONFIG_HAS_IOMEM
if (flags & IORESOURCE_MEM)
list_add(&tiop->list, &trapped_mem);
#endif
spin_unlock_irq(&trapped_lock);
return 0;
bad:
pr_warning("unable to install trapped io filter\n");
return -1;
}
EXPORT_SYMBOL_GPL(register_trapped_io);
void __iomem *match_trapped_io_handler(struct list_head *list,
unsigned long offset,
unsigned long size)
{
unsigned long voffs;
struct trapped_io *tiop;
struct resource *res;
int k, len;
unsigned long flags;
spin_lock_irqsave(&trapped_lock, flags);
list_for_each_entry(tiop, list, list) {
voffs = 0;
for (k = 0; k < tiop->num_resources; k++) {
res = tiop->resource + k;
if (res->start == offset) {
spin_unlock_irqrestore(&trapped_lock, flags);
return tiop->virt_base + voffs;
}
len = resource_size(res);
voffs += roundup(len, PAGE_SIZE);
}
}
spin_unlock_irqrestore(&trapped_lock, flags);
return NULL;
}
EXPORT_SYMBOL_GPL(match_trapped_io_handler);
static struct trapped_io *lookup_tiop(unsigned long address)
{
pgd_t *pgd_k;
pud_t *pud_k;
pmd_t *pmd_k;
pte_t *pte_k;
pte_t entry;
pgd_k = swapper_pg_dir + pgd_index(address);
if (!pgd_present(*pgd_k))
return NULL;
pud_k = pud_offset(pgd_k, address);
if (!pud_present(*pud_k))
return NULL;
pmd_k = pmd_offset(pud_k, address);
if (!pmd_present(*pmd_k))
return NULL;
pte_k = pte_offset_kernel(pmd_k, address);
entry = *pte_k;
return pfn_to_kaddr(pte_pfn(entry));
}
static unsigned long lookup_address(struct trapped_io *tiop,
unsigned long address)
{
struct resource *res;
unsigned long vaddr = (unsigned long)tiop->virt_base;
unsigned long len;
int k;
for (k = 0; k < tiop->num_resources; k++) {
res = tiop->resource + k;
len = roundup(resource_size(res), PAGE_SIZE);
if (address < (vaddr + len))
return res->start + (address - vaddr);
vaddr += len;
}
return 0;
}
static unsigned long long copy_word(unsigned long src_addr, int src_len,
unsigned long dst_addr, int dst_len)
{
unsigned long long tmp = 0;
switch (src_len) {
case 1:
tmp = __raw_readb(src_addr);
break;
case 2:
tmp = __raw_readw(src_addr);
break;
case 4:
tmp = __raw_readl(src_addr);
break;
case 8:
tmp = __raw_readq(src_addr);
break;
}
switch (dst_len) {
case 1:
__raw_writeb(tmp, dst_addr);
break;
case 2:
__raw_writew(tmp, dst_addr);
break;
case 4:
__raw_writel(tmp, dst_addr);
break;
case 8:
__raw_writeq(tmp, dst_addr);
break;
}
return tmp;
}
static unsigned long from_device(void *dst, const void *src, unsigned long cnt)
{
struct trapped_io *tiop;
unsigned long src_addr = (unsigned long)src;
unsigned long long tmp;
pr_debug("trapped io read 0x%08lx (%ld)\n", src_addr, cnt);
tiop = lookup_tiop(src_addr);
WARN_ON(!tiop || (tiop->magic != IO_TRAPPED_MAGIC));
src_addr = lookup_address(tiop, src_addr);
if (!src_addr)
return cnt;
tmp = copy_word(src_addr,
max_t(unsigned long, cnt,
(tiop->minimum_bus_width / 8)),
(unsigned long)dst, cnt);
pr_debug("trapped io read 0x%08lx -> 0x%08llx\n", src_addr, tmp);
return 0;
}
static unsigned long to_device(void *dst, const void *src, unsigned long cnt)
{
struct trapped_io *tiop;
unsigned long dst_addr = (unsigned long)dst;
unsigned long long tmp;
pr_debug("trapped io write 0x%08lx (%ld)\n", dst_addr, cnt);
tiop = lookup_tiop(dst_addr);
WARN_ON(!tiop || (tiop->magic != IO_TRAPPED_MAGIC));
dst_addr = lookup_address(tiop, dst_addr);
if (!dst_addr)
return cnt;
tmp = copy_word((unsigned long)src, cnt,
dst_addr, max_t(unsigned long, cnt,
(tiop->minimum_bus_width / 8)));
pr_debug("trapped io write 0x%08lx -> 0x%08llx\n", dst_addr, tmp);
return 0;
}
static struct mem_access trapped_io_access = {
from_device,
to_device,
};
int handle_trapped_io(struct pt_regs *regs, unsigned long address)
{
mm_segment_t oldfs;
insn_size_t instruction;
int tmp;
if (trapped_io_disable)
return 0;
if (!lookup_tiop(address))
return 0;
WARN_ON(user_mode(regs));
oldfs = get_fs();
set_fs(KERNEL_DS);
if (copy_from_user(&instruction, (void *)(regs->pc),
sizeof(instruction))) {
set_fs(oldfs);
return 0;
}
tmp = handle_unaligned_access(instruction, regs,
&trapped_io_access, 1, address);
set_fs(oldfs);
return tmp == 0;
}
| gpl-2.0 |
ea4862/boeffla41_e210k | drivers/video/via/via-core.c | 2783 | 20902 | /*
* Copyright 1998-2009 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2008 S3 Graphics, Inc. All Rights Reserved.
* Copyright 2009 Jonathan Corbet <corbet@lwn.net>
*/
/*
* Core code for the Via multifunction framebuffer device.
*/
#include <linux/via-core.h>
#include <linux/via_i2c.h>
#include <linux/via-gpio.h>
#include "global.h"
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/list.h>
#include <linux/pm.h>
#include <asm/olpc.h>
/*
* The default port config.
*/
static struct via_port_cfg adap_configs[] = {
[VIA_PORT_26] = { VIA_PORT_I2C, VIA_MODE_I2C, VIASR, 0x26 },
[VIA_PORT_31] = { VIA_PORT_I2C, VIA_MODE_I2C, VIASR, 0x31 },
[VIA_PORT_25] = { VIA_PORT_GPIO, VIA_MODE_GPIO, VIASR, 0x25 },
[VIA_PORT_2C] = { VIA_PORT_GPIO, VIA_MODE_I2C, VIASR, 0x2c },
[VIA_PORT_3D] = { VIA_PORT_GPIO, VIA_MODE_GPIO, VIASR, 0x3d },
{ 0, 0, 0, 0 }
};
/*
* The OLPC XO-1.5 puts the camera power and reset lines onto
* GPIO 2C.
*/
static const struct via_port_cfg olpc_adap_configs[] = {
[VIA_PORT_26] = { VIA_PORT_I2C, VIA_MODE_I2C, VIASR, 0x26 },
[VIA_PORT_31] = { VIA_PORT_I2C, VIA_MODE_I2C, VIASR, 0x31 },
[VIA_PORT_25] = { VIA_PORT_GPIO, VIA_MODE_GPIO, VIASR, 0x25 },
[VIA_PORT_2C] = { VIA_PORT_GPIO, VIA_MODE_GPIO, VIASR, 0x2c },
[VIA_PORT_3D] = { VIA_PORT_GPIO, VIA_MODE_GPIO, VIASR, 0x3d },
{ 0, 0, 0, 0 }
};
/*
* We currently only support one viafb device (will there ever be
* more than one?), so just declare it globally here.
*/
static struct viafb_dev global_dev;
/*
* Basic register access; spinlock required.
*/
static inline void viafb_mmio_write(int reg, u32 v)
{
iowrite32(v, global_dev.engine_mmio + reg);
}
static inline int viafb_mmio_read(int reg)
{
return ioread32(global_dev.engine_mmio + reg);
}
/* ---------------------------------------------------------------------- */
/*
* Interrupt management. We have a single IRQ line for a lot of
* different functions, so we need to share it. The design here
* is that we don't want to reimplement the shared IRQ code here;
* we also want to avoid having contention for a single handler thread.
* So each subdev driver which needs interrupts just requests
* them directly from the kernel. We just have what's needed for
* overall access to the interrupt control register.
*/
/*
* Which interrupts are enabled now?
*/
static u32 viafb_enabled_ints;
static void __devinit viafb_int_init(void)
{
viafb_enabled_ints = 0;
viafb_mmio_write(VDE_INTERRUPT, 0);
}
/*
* Allow subdevs to ask for specific interrupts to be enabled. These
* functions must be called with reg_lock held
*/
void viafb_irq_enable(u32 mask)
{
viafb_enabled_ints |= mask;
viafb_mmio_write(VDE_INTERRUPT, viafb_enabled_ints | VDE_I_ENABLE);
}
EXPORT_SYMBOL_GPL(viafb_irq_enable);
void viafb_irq_disable(u32 mask)
{
viafb_enabled_ints &= ~mask;
if (viafb_enabled_ints == 0)
viafb_mmio_write(VDE_INTERRUPT, 0); /* Disable entirely */
else
viafb_mmio_write(VDE_INTERRUPT,
viafb_enabled_ints | VDE_I_ENABLE);
}
EXPORT_SYMBOL_GPL(viafb_irq_disable);
/* ---------------------------------------------------------------------- */
/*
* Currently, the camera driver is the only user of the DMA code, so we
* only compile it in if the camera driver is being built. Chances are,
* most viafb systems will not need to have this extra code for a while.
* As soon as another user comes long, the ifdef can be removed.
*/
#if defined(CONFIG_VIDEO_VIA_CAMERA) || defined(CONFIG_VIDEO_VIA_CAMERA_MODULE)
/*
* Access to the DMA engine. This currently provides what the camera
* driver needs (i.e. outgoing only) but is easily expandable if need
* be.
*/
/*
* There are four DMA channels in the vx855. For now, we only
* use one of them, though. Most of the time, the DMA channel
* will be idle, so we keep the IRQ handler unregistered except
* when some subsystem has indicated an interest.
*/
static int viafb_dma_users;
static DECLARE_COMPLETION(viafb_dma_completion);
/*
* This mutex protects viafb_dma_users and our global interrupt
* registration state; it also serializes access to the DMA
* engine.
*/
static DEFINE_MUTEX(viafb_dma_lock);
/*
* The VX855 DMA descriptor (used for s/g transfers) looks
* like this.
*/
struct viafb_vx855_dma_descr {
u32 addr_low; /* Low part of phys addr */
u32 addr_high; /* High 12 bits of addr */
u32 fb_offset; /* Offset into FB memory */
u32 seg_size; /* Size, 16-byte units */
u32 tile_mode; /* "tile mode" setting */
u32 next_desc_low; /* Next descriptor addr */
u32 next_desc_high;
u32 pad; /* Fill out to 64 bytes */
};
/*
* Flags added to the "next descriptor low" pointers
*/
#define VIAFB_DMA_MAGIC 0x01 /* ??? Just has to be there */
#define VIAFB_DMA_FINAL_SEGMENT 0x02 /* Final segment */
/*
* The completion IRQ handler.
*/
static irqreturn_t viafb_dma_irq(int irq, void *data)
{
int csr;
irqreturn_t ret = IRQ_NONE;
spin_lock(&global_dev.reg_lock);
csr = viafb_mmio_read(VDMA_CSR0);
if (csr & VDMA_C_DONE) {
viafb_mmio_write(VDMA_CSR0, VDMA_C_DONE);
complete(&viafb_dma_completion);
ret = IRQ_HANDLED;
}
spin_unlock(&global_dev.reg_lock);
return ret;
}
/*
* Indicate a need for DMA functionality.
*/
int viafb_request_dma(void)
{
int ret = 0;
/*
* Only VX855 is supported currently.
*/
if (global_dev.chip_type != UNICHROME_VX855)
return -ENODEV;
/*
* Note the new user and set up our interrupt handler
* if need be.
*/
mutex_lock(&viafb_dma_lock);
viafb_dma_users++;
if (viafb_dma_users == 1) {
ret = request_irq(global_dev.pdev->irq, viafb_dma_irq,
IRQF_SHARED, "via-dma", &viafb_dma_users);
if (ret)
viafb_dma_users--;
else
viafb_irq_enable(VDE_I_DMA0TDEN);
}
mutex_unlock(&viafb_dma_lock);
return ret;
}
EXPORT_SYMBOL_GPL(viafb_request_dma);
void viafb_release_dma(void)
{
mutex_lock(&viafb_dma_lock);
viafb_dma_users--;
if (viafb_dma_users == 0) {
viafb_irq_disable(VDE_I_DMA0TDEN);
free_irq(global_dev.pdev->irq, &viafb_dma_users);
}
mutex_unlock(&viafb_dma_lock);
}
EXPORT_SYMBOL_GPL(viafb_release_dma);
#if 0
/*
* Copy a single buffer from FB memory, synchronously. This code works
* but is not currently used.
*/
void viafb_dma_copy_out(unsigned int offset, dma_addr_t paddr, int len)
{
unsigned long flags;
int csr;
mutex_lock(&viafb_dma_lock);
init_completion(&viafb_dma_completion);
/*
* Program the controller.
*/
spin_lock_irqsave(&global_dev.reg_lock, flags);
viafb_mmio_write(VDMA_CSR0, VDMA_C_ENABLE|VDMA_C_DONE);
/* Enable ints; must happen after CSR0 write! */
viafb_mmio_write(VDMA_MR0, VDMA_MR_TDIE);
viafb_mmio_write(VDMA_MARL0, (int) (paddr & 0xfffffff0));
viafb_mmio_write(VDMA_MARH0, (int) ((paddr >> 28) & 0xfff));
/* Data sheet suggests DAR0 should be <<4, but it lies */
viafb_mmio_write(VDMA_DAR0, offset);
viafb_mmio_write(VDMA_DQWCR0, len >> 4);
viafb_mmio_write(VDMA_TMR0, 0);
viafb_mmio_write(VDMA_DPRL0, 0);
viafb_mmio_write(VDMA_DPRH0, 0);
viafb_mmio_write(VDMA_PMR0, 0);
csr = viafb_mmio_read(VDMA_CSR0);
viafb_mmio_write(VDMA_CSR0, VDMA_C_ENABLE|VDMA_C_START);
spin_unlock_irqrestore(&global_dev.reg_lock, flags);
/*
* Now we just wait until the interrupt handler says
* we're done.
*/
wait_for_completion_interruptible(&viafb_dma_completion);
viafb_mmio_write(VDMA_MR0, 0); /* Reset int enable */
mutex_unlock(&viafb_dma_lock);
}
EXPORT_SYMBOL_GPL(viafb_dma_copy_out);
#endif
/*
* Do a scatter/gather DMA copy from FB memory. You must have done
* a successful call to viafb_request_dma() first.
*/
int viafb_dma_copy_out_sg(unsigned int offset, struct scatterlist *sg, int nsg)
{
struct viafb_vx855_dma_descr *descr;
void *descrpages;
dma_addr_t descr_handle;
unsigned long flags;
int i;
struct scatterlist *sgentry;
dma_addr_t nextdesc;
/*
* Get a place to put the descriptors.
*/
descrpages = dma_alloc_coherent(&global_dev.pdev->dev,
nsg*sizeof(struct viafb_vx855_dma_descr),
&descr_handle, GFP_KERNEL);
if (descrpages == NULL) {
dev_err(&global_dev.pdev->dev, "Unable to get descr page.\n");
return -ENOMEM;
}
mutex_lock(&viafb_dma_lock);
/*
* Fill them in.
*/
descr = descrpages;
nextdesc = descr_handle + sizeof(struct viafb_vx855_dma_descr);
for_each_sg(sg, sgentry, nsg, i) {
dma_addr_t paddr = sg_dma_address(sgentry);
descr->addr_low = paddr & 0xfffffff0;
descr->addr_high = ((u64) paddr >> 32) & 0x0fff;
descr->fb_offset = offset;
descr->seg_size = sg_dma_len(sgentry) >> 4;
descr->tile_mode = 0;
descr->next_desc_low = (nextdesc&0xfffffff0) | VIAFB_DMA_MAGIC;
descr->next_desc_high = ((u64) nextdesc >> 32) & 0x0fff;
descr->pad = 0xffffffff; /* VIA driver does this */
offset += sg_dma_len(sgentry);
nextdesc += sizeof(struct viafb_vx855_dma_descr);
descr++;
}
descr[-1].next_desc_low = VIAFB_DMA_FINAL_SEGMENT|VIAFB_DMA_MAGIC;
/*
* Program the engine.
*/
spin_lock_irqsave(&global_dev.reg_lock, flags);
init_completion(&viafb_dma_completion);
viafb_mmio_write(VDMA_DQWCR0, 0);
viafb_mmio_write(VDMA_CSR0, VDMA_C_ENABLE|VDMA_C_DONE);
viafb_mmio_write(VDMA_MR0, VDMA_MR_TDIE | VDMA_MR_CHAIN);
viafb_mmio_write(VDMA_DPRL0, descr_handle | VIAFB_DMA_MAGIC);
viafb_mmio_write(VDMA_DPRH0,
(((u64)descr_handle >> 32) & 0x0fff) | 0xf0000);
(void) viafb_mmio_read(VDMA_CSR0);
viafb_mmio_write(VDMA_CSR0, VDMA_C_ENABLE|VDMA_C_START);
spin_unlock_irqrestore(&global_dev.reg_lock, flags);
/*
* Now we just wait until the interrupt handler says
* we're done. Except that, actually, we need to wait a little
* longer: the interrupts seem to jump the gun a little and we
* get corrupted frames sometimes.
*/
wait_for_completion_timeout(&viafb_dma_completion, 1);
msleep(1);
if ((viafb_mmio_read(VDMA_CSR0)&VDMA_C_DONE) == 0)
printk(KERN_ERR "VIA DMA timeout!\n");
/*
* Clean up and we're done.
*/
viafb_mmio_write(VDMA_CSR0, VDMA_C_DONE);
viafb_mmio_write(VDMA_MR0, 0); /* Reset int enable */
mutex_unlock(&viafb_dma_lock);
dma_free_coherent(&global_dev.pdev->dev,
nsg*sizeof(struct viafb_vx855_dma_descr), descrpages,
descr_handle);
return 0;
}
EXPORT_SYMBOL_GPL(viafb_dma_copy_out_sg);
#endif /* CONFIG_VIDEO_VIA_CAMERA */
/* ---------------------------------------------------------------------- */
/*
* Figure out how big our framebuffer memory is. Kind of ugly,
* but evidently we can't trust the information found in the
* fbdev configuration area.
*/
static u16 via_function3[] = {
CLE266_FUNCTION3, KM400_FUNCTION3, CN400_FUNCTION3, CN700_FUNCTION3,
CX700_FUNCTION3, KM800_FUNCTION3, KM890_FUNCTION3, P4M890_FUNCTION3,
P4M900_FUNCTION3, VX800_FUNCTION3, VX855_FUNCTION3, VX900_FUNCTION3,
};
/* Get the BIOS-configured framebuffer size from PCI configuration space
* of function 3 in the respective chipset */
static int viafb_get_fb_size_from_pci(int chip_type)
{
int i;
u8 offset = 0;
u32 FBSize;
u32 VideoMemSize;
/* search for the "FUNCTION3" device in this chipset */
for (i = 0; i < ARRAY_SIZE(via_function3); i++) {
struct pci_dev *pdev;
pdev = pci_get_device(PCI_VENDOR_ID_VIA, via_function3[i],
NULL);
if (!pdev)
continue;
DEBUG_MSG(KERN_INFO "Device ID = %x\n", pdev->device);
switch (pdev->device) {
case CLE266_FUNCTION3:
case KM400_FUNCTION3:
offset = 0xE0;
break;
case CN400_FUNCTION3:
case CN700_FUNCTION3:
case CX700_FUNCTION3:
case KM800_FUNCTION3:
case KM890_FUNCTION3:
case P4M890_FUNCTION3:
case P4M900_FUNCTION3:
case VX800_FUNCTION3:
case VX855_FUNCTION3:
case VX900_FUNCTION3:
/*case CN750_FUNCTION3: */
offset = 0xA0;
break;
}
if (!offset)
break;
pci_read_config_dword(pdev, offset, &FBSize);
pci_dev_put(pdev);
}
if (!offset) {
printk(KERN_ERR "cannot determine framebuffer size\n");
return -EIO;
}
FBSize = FBSize & 0x00007000;
DEBUG_MSG(KERN_INFO "FB Size = %x\n", FBSize);
if (chip_type < UNICHROME_CX700) {
switch (FBSize) {
case 0x00004000:
VideoMemSize = (16 << 20); /*16M */
break;
case 0x00005000:
VideoMemSize = (32 << 20); /*32M */
break;
case 0x00006000:
VideoMemSize = (64 << 20); /*64M */
break;
default:
VideoMemSize = (32 << 20); /*32M */
break;
}
} else {
switch (FBSize) {
case 0x00001000:
VideoMemSize = (8 << 20); /*8M */
break;
case 0x00002000:
VideoMemSize = (16 << 20); /*16M */
break;
case 0x00003000:
VideoMemSize = (32 << 20); /*32M */
break;
case 0x00004000:
VideoMemSize = (64 << 20); /*64M */
break;
case 0x00005000:
VideoMemSize = (128 << 20); /*128M */
break;
case 0x00006000:
VideoMemSize = (256 << 20); /*256M */
break;
case 0x00007000: /* Only on VX855/875 */
VideoMemSize = (512 << 20); /*512M */
break;
default:
VideoMemSize = (32 << 20); /*32M */
break;
}
}
return VideoMemSize;
}
/*
* Figure out and map our MMIO regions.
*/
static int __devinit via_pci_setup_mmio(struct viafb_dev *vdev)
{
int ret;
/*
* Hook up to the device registers. Note that we soldier
* on if it fails; the framebuffer can operate (without
* acceleration) without this region.
*/
vdev->engine_start = pci_resource_start(vdev->pdev, 1);
vdev->engine_len = pci_resource_len(vdev->pdev, 1);
vdev->engine_mmio = ioremap_nocache(vdev->engine_start,
vdev->engine_len);
if (vdev->engine_mmio == NULL)
dev_err(&vdev->pdev->dev,
"Unable to map engine MMIO; operation will be "
"slow and crippled.\n");
/*
* Map in framebuffer memory. For now, failure here is
* fatal. Unfortunately, in the absence of significant
* vmalloc space, failure here is also entirely plausible.
* Eventually we want to move away from mapping this
* entire region.
*/
if (vdev->chip_type == UNICHROME_VX900)
vdev->fbmem_start = pci_resource_start(vdev->pdev, 2);
else
vdev->fbmem_start = pci_resource_start(vdev->pdev, 0);
ret = vdev->fbmem_len = viafb_get_fb_size_from_pci(vdev->chip_type);
if (ret < 0)
goto out_unmap;
/* try to map less memory on failure, 8 MB should be still enough */
for (; vdev->fbmem_len >= 8 << 20; vdev->fbmem_len /= 2) {
vdev->fbmem = ioremap_wc(vdev->fbmem_start, vdev->fbmem_len);
if (vdev->fbmem)
break;
}
if (vdev->fbmem == NULL) {
ret = -ENOMEM;
goto out_unmap;
}
return 0;
out_unmap:
iounmap(vdev->engine_mmio);
return ret;
}
static void via_pci_teardown_mmio(struct viafb_dev *vdev)
{
iounmap(vdev->fbmem);
iounmap(vdev->engine_mmio);
}
/*
* Create our subsidiary devices.
*/
static struct viafb_subdev_info {
char *name;
struct platform_device *platdev;
} viafb_subdevs[] = {
{
.name = "viafb-gpio",
},
{
.name = "viafb-i2c",
},
#if defined(CONFIG_VIDEO_VIA_CAMERA) || defined(CONFIG_VIDEO_VIA_CAMERA_MODULE)
{
.name = "viafb-camera",
},
#endif
};
#define N_SUBDEVS ARRAY_SIZE(viafb_subdevs)
static int __devinit via_create_subdev(struct viafb_dev *vdev,
struct viafb_subdev_info *info)
{
int ret;
info->platdev = platform_device_alloc(info->name, -1);
if (!info->platdev) {
dev_err(&vdev->pdev->dev, "Unable to allocate pdev %s\n",
info->name);
return -ENOMEM;
}
info->platdev->dev.parent = &vdev->pdev->dev;
info->platdev->dev.platform_data = vdev;
ret = platform_device_add(info->platdev);
if (ret) {
dev_err(&vdev->pdev->dev, "Unable to add pdev %s\n",
info->name);
platform_device_put(info->platdev);
info->platdev = NULL;
}
return ret;
}
static int __devinit via_setup_subdevs(struct viafb_dev *vdev)
{
int i;
/*
* Ignore return values. Even if some of the devices
* fail to be created, we'll still be able to use some
* of the rest.
*/
for (i = 0; i < N_SUBDEVS; i++)
via_create_subdev(vdev, viafb_subdevs + i);
return 0;
}
static void via_teardown_subdevs(void)
{
int i;
for (i = 0; i < N_SUBDEVS; i++)
if (viafb_subdevs[i].platdev) {
viafb_subdevs[i].platdev->dev.platform_data = NULL;
platform_device_unregister(viafb_subdevs[i].platdev);
}
}
/*
* Power management functions
*/
#ifdef CONFIG_PM
static LIST_HEAD(viafb_pm_hooks);
static DEFINE_MUTEX(viafb_pm_hooks_lock);
void viafb_pm_register(struct viafb_pm_hooks *hooks)
{
INIT_LIST_HEAD(&hooks->list);
mutex_lock(&viafb_pm_hooks_lock);
list_add_tail(&hooks->list, &viafb_pm_hooks);
mutex_unlock(&viafb_pm_hooks_lock);
}
EXPORT_SYMBOL_GPL(viafb_pm_register);
void viafb_pm_unregister(struct viafb_pm_hooks *hooks)
{
mutex_lock(&viafb_pm_hooks_lock);
list_del(&hooks->list);
mutex_unlock(&viafb_pm_hooks_lock);
}
EXPORT_SYMBOL_GPL(viafb_pm_unregister);
static int via_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct viafb_pm_hooks *hooks;
if (state.event != PM_EVENT_SUSPEND)
return 0;
/*
* "I've occasionally hit a few drivers that caused suspend
* failures, and each and every time it was a driver bug, and
* the right thing to do was to just ignore the error and suspend
* anyway - returning an error code and trying to undo the suspend
* is not what anybody ever really wants, even if our model
*_allows_ for it."
* -- Linus Torvalds, Dec. 7, 2009
*/
mutex_lock(&viafb_pm_hooks_lock);
list_for_each_entry_reverse(hooks, &viafb_pm_hooks, list)
hooks->suspend(hooks->private);
mutex_unlock(&viafb_pm_hooks_lock);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int via_resume(struct pci_dev *pdev)
{
struct viafb_pm_hooks *hooks;
/* Get the bus side powered up */
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
if (pci_enable_device(pdev))
return 0;
pci_set_master(pdev);
/* Now bring back any subdevs */
mutex_lock(&viafb_pm_hooks_lock);
list_for_each_entry(hooks, &viafb_pm_hooks, list)
hooks->resume(hooks->private);
mutex_unlock(&viafb_pm_hooks_lock);
return 0;
}
#endif /* CONFIG_PM */
static int __devinit via_pci_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int ret;
ret = pci_enable_device(pdev);
if (ret)
return ret;
/*
* Global device initialization.
*/
memset(&global_dev, 0, sizeof(global_dev));
global_dev.pdev = pdev;
global_dev.chip_type = ent->driver_data;
global_dev.port_cfg = adap_configs;
if (machine_is_olpc())
global_dev.port_cfg = olpc_adap_configs;
spin_lock_init(&global_dev.reg_lock);
ret = via_pci_setup_mmio(&global_dev);
if (ret)
goto out_disable;
/*
* Set up interrupts and create our subdevices. Continue even if
* some things fail.
*/
viafb_int_init();
via_setup_subdevs(&global_dev);
/*
* Set up the framebuffer device
*/
ret = via_fb_pci_probe(&global_dev);
if (ret)
goto out_subdevs;
return 0;
out_subdevs:
via_teardown_subdevs();
via_pci_teardown_mmio(&global_dev);
out_disable:
pci_disable_device(pdev);
return ret;
}
static void __devexit via_pci_remove(struct pci_dev *pdev)
{
via_teardown_subdevs();
via_fb_pci_remove(pdev);
via_pci_teardown_mmio(&global_dev);
pci_disable_device(pdev);
}
static struct pci_device_id via_pci_table[] __devinitdata = {
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_CLE266_DID),
.driver_data = UNICHROME_CLE266 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_K400_DID),
.driver_data = UNICHROME_K400 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_K800_DID),
.driver_data = UNICHROME_K800 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_PM800_DID),
.driver_data = UNICHROME_PM800 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_CN700_DID),
.driver_data = UNICHROME_CN700 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_CX700_DID),
.driver_data = UNICHROME_CX700 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_CN750_DID),
.driver_data = UNICHROME_CN750 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_K8M890_DID),
.driver_data = UNICHROME_K8M890 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_P4M890_DID),
.driver_data = UNICHROME_P4M890 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_P4M900_DID),
.driver_data = UNICHROME_P4M900 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_VX800_DID),
.driver_data = UNICHROME_VX800 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_VX855_DID),
.driver_data = UNICHROME_VX855 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, UNICHROME_VX900_DID),
.driver_data = UNICHROME_VX900 },
{ }
};
MODULE_DEVICE_TABLE(pci, via_pci_table);
static struct pci_driver via_driver = {
.name = "viafb",
.id_table = via_pci_table,
.probe = via_pci_probe,
.remove = __devexit_p(via_pci_remove),
#ifdef CONFIG_PM
.suspend = via_suspend,
.resume = via_resume,
#endif
};
static int __init via_core_init(void)
{
int ret;
ret = viafb_init();
if (ret)
return ret;
viafb_i2c_init();
viafb_gpio_init();
return pci_register_driver(&via_driver);
}
static void __exit via_core_exit(void)
{
pci_unregister_driver(&via_driver);
viafb_gpio_exit();
viafb_i2c_exit();
viafb_exit();
}
module_init(via_core_init);
module_exit(via_core_exit);
| gpl-2.0 |
linuxmake/kernel_softwinner_fiber | drivers/net/arcnet/com20020_cs.c | 3039 | 8135 | /*
* Linux ARCnet driver - COM20020 PCMCIA support
*
* Written 1994-1999 by Avery Pennarun,
* based on an ISA version by David Woodhouse.
* Derived from ibmtr_cs.c by Steve Kipisz (pcmcia-cs 3.1.4)
* which was derived from pcnet_cs.c by David Hinds.
* Some additional portions derived from skeleton.c by Donald Becker.
*
* Special thanks to Contemporary Controls, Inc. (www.ccontrols.com)
* for sponsoring the further development of this driver.
*
* **********************
*
* The original copyright of skeleton.c was as follows:
*
* skeleton.c Written 1993 by Donald Becker.
* Copyright 1993 United States Government as represented by the
* Director, National Security Agency. This software may only be used
* and distributed according to the terms of the GNU General Public License as
* modified by SRC, incorporated herein by reference.
*
* **********************
* Changes:
* Arnaldo Carvalho de Melo <acme@conectiva.com.br> - 08/08/2000
* - reorganize kmallocs in com20020_attach, checking all for failure
* and releasing the previous allocations if one fails
* **********************
*
* For more details, see drivers/net/arcnet.c
*
* **********************
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/arcdevice.h>
#include <linux/com20020.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
#include <asm/io.h>
#include <asm/system.h>
#define VERSION "arcnet: COM20020 PCMCIA support loaded.\n"
static void regdump(struct net_device *dev)
{
#ifdef DEBUG
int ioaddr = dev->base_addr;
int count;
netdev_dbg(dev, "register dump:\n");
for (count = ioaddr; count < ioaddr + 16; count++)
{
if (!(count % 16))
pr_cont("%04X:", count);
pr_cont(" %02X", inb(count));
}
pr_cont("\n");
netdev_dbg(dev, "buffer0 dump:\n");
/* set up the address register */
count = 0;
outb((count >> 8) | RDDATAflag | AUTOINCflag, _ADDR_HI);
outb(count & 0xff, _ADDR_LO);
for (count = 0; count < 256+32; count++)
{
if (!(count % 16))
pr_cont("%04X:", count);
/* copy the data */
pr_cont(" %02X", inb(_MEMDATA));
}
pr_cont("\n");
#endif
}
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
static int node;
static int timeout = 3;
static int backplane;
static int clockp;
static int clockm;
module_param(node, int, 0);
module_param(timeout, int, 0);
module_param(backplane, int, 0);
module_param(clockp, int, 0);
module_param(clockm, int, 0);
MODULE_LICENSE("GPL");
/*====================================================================*/
static int com20020_config(struct pcmcia_device *link);
static void com20020_release(struct pcmcia_device *link);
static void com20020_detach(struct pcmcia_device *p_dev);
/*====================================================================*/
typedef struct com20020_dev_t {
struct net_device *dev;
} com20020_dev_t;
static int com20020_probe(struct pcmcia_device *p_dev)
{
com20020_dev_t *info;
struct net_device *dev;
struct arcnet_local *lp;
dev_dbg(&p_dev->dev, "com20020_attach()\n");
/* Create new network device */
info = kzalloc(sizeof(struct com20020_dev_t), GFP_KERNEL);
if (!info)
goto fail_alloc_info;
dev = alloc_arcdev("");
if (!dev)
goto fail_alloc_dev;
lp = netdev_priv(dev);
lp->timeout = timeout;
lp->backplane = backplane;
lp->clockp = clockp;
lp->clockm = clockm & 3;
lp->hw.owner = THIS_MODULE;
/* fill in our module parameters as defaults */
dev->dev_addr[0] = node;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
p_dev->resource[0]->end = 16;
p_dev->config_flags |= CONF_ENABLE_IRQ;
info->dev = dev;
p_dev->priv = info;
return com20020_config(p_dev);
fail_alloc_dev:
kfree(info);
fail_alloc_info:
return -ENOMEM;
} /* com20020_attach */
static void com20020_detach(struct pcmcia_device *link)
{
struct com20020_dev_t *info = link->priv;
struct net_device *dev = info->dev;
dev_dbg(&link->dev, "detach...\n");
dev_dbg(&link->dev, "com20020_detach\n");
dev_dbg(&link->dev, "unregister...\n");
unregister_netdev(dev);
/*
* this is necessary because we register our IRQ separately
* from card services.
*/
if (dev->irq)
free_irq(dev->irq, dev);
com20020_release(link);
/* Unlink device structure, free bits */
dev_dbg(&link->dev, "unlinking...\n");
if (link->priv)
{
dev = info->dev;
if (dev)
{
dev_dbg(&link->dev, "kfree...\n");
free_netdev(dev);
}
dev_dbg(&link->dev, "kfree2...\n");
kfree(info);
}
} /* com20020_detach */
static int com20020_config(struct pcmcia_device *link)
{
struct arcnet_local *lp;
com20020_dev_t *info;
struct net_device *dev;
int i, ret;
int ioaddr;
info = link->priv;
dev = info->dev;
dev_dbg(&link->dev, "config...\n");
dev_dbg(&link->dev, "com20020_config\n");
dev_dbg(&link->dev, "baseport1 is %Xh\n",
(unsigned int) link->resource[0]->start);
i = -ENODEV;
link->io_lines = 16;
if (!link->resource[0]->start)
{
for (ioaddr = 0x100; ioaddr < 0x400; ioaddr += 0x10)
{
link->resource[0]->start = ioaddr;
i = pcmcia_request_io(link);
if (i == 0)
break;
}
}
else
i = pcmcia_request_io(link);
if (i != 0)
{
dev_dbg(&link->dev, "requestIO failed totally!\n");
goto failed;
}
ioaddr = dev->base_addr = link->resource[0]->start;
dev_dbg(&link->dev, "got ioaddr %Xh\n", ioaddr);
dev_dbg(&link->dev, "request IRQ %d\n",
link->irq);
if (!link->irq)
{
dev_dbg(&link->dev, "requestIRQ failed totally!\n");
goto failed;
}
dev->irq = link->irq;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
if (com20020_check(dev))
{
regdump(dev);
goto failed;
}
lp = netdev_priv(dev);
lp->card_name = "PCMCIA COM20020";
lp->card_flags = ARC_CAN_10MBIT; /* pretend all of them can 10Mbit */
SET_NETDEV_DEV(dev, &link->dev);
i = com20020_found(dev, 0); /* calls register_netdev */
if (i != 0) {
dev_notice(&link->dev,
"com20020_found() failed\n");
goto failed;
}
netdev_dbg(dev, "port %#3lx, irq %d\n",
dev->base_addr, dev->irq);
return 0;
failed:
dev_dbg(&link->dev, "com20020_config failed...\n");
com20020_release(link);
return -ENODEV;
} /* com20020_config */
static void com20020_release(struct pcmcia_device *link)
{
dev_dbg(&link->dev, "com20020_release\n");
pcmcia_disable_device(link);
}
static int com20020_suspend(struct pcmcia_device *link)
{
com20020_dev_t *info = link->priv;
struct net_device *dev = info->dev;
if (link->open)
netif_device_detach(dev);
return 0;
}
static int com20020_resume(struct pcmcia_device *link)
{
com20020_dev_t *info = link->priv;
struct net_device *dev = info->dev;
if (link->open) {
int ioaddr = dev->base_addr;
struct arcnet_local *lp = netdev_priv(dev);
ARCRESET;
}
return 0;
}
static const struct pcmcia_device_id com20020_ids[] = {
PCMCIA_DEVICE_PROD_ID12("Contemporary Control Systems, Inc.",
"PCM20 Arcnet Adapter", 0x59991666, 0x95dfffaf),
PCMCIA_DEVICE_PROD_ID12("SoHard AG",
"SH ARC PCMCIA", 0xf8991729, 0x69dff0c7),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, com20020_ids);
static struct pcmcia_driver com20020_cs_driver = {
.owner = THIS_MODULE,
.name = "com20020_cs",
.probe = com20020_probe,
.remove = com20020_detach,
.id_table = com20020_ids,
.suspend = com20020_suspend,
.resume = com20020_resume,
};
static int __init init_com20020_cs(void)
{
return pcmcia_register_driver(&com20020_cs_driver);
}
static void __exit exit_com20020_cs(void)
{
pcmcia_unregister_driver(&com20020_cs_driver);
}
module_init(init_com20020_cs);
module_exit(exit_com20020_cs);
| gpl-2.0 |
ciwrl/android_kernel_huawei_msm8939 | drivers/atm/zatm.c | 3295 | 44309 | /* drivers/atm/zatm.c - ZeitNet ZN122x device driver */
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/errno.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/sonet.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/uio.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/atm_zatm.h>
#include <linux/capability.h>
#include <linux/bitops.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/string.h>
#include <asm/io.h>
#include <linux/atomic.h>
#include <asm/uaccess.h>
#include "uPD98401.h"
#include "uPD98402.h"
#include "zeprom.h"
#include "zatm.h"
/*
* TODO:
*
* Minor features
* - support 64 kB SDUs (will have to use multibuffer batches then :-( )
* - proper use of CDV, credit = max(1,CDVT*PCR)
* - AAL0
* - better receive timestamps
* - OAM
*/
#define ZATM_COPPER 1
#if 0
#define DPRINTK(format,args...) printk(KERN_DEBUG format,##args)
#else
#define DPRINTK(format,args...)
#endif
#ifndef CONFIG_ATM_ZATM_DEBUG
#define NULLCHECK(x)
#define EVENT(s,a,b)
static void event_dump(void)
{
}
#else
/*
* NULL pointer checking
*/
#define NULLCHECK(x) \
if ((unsigned long) (x) < 0x30) printk(KERN_CRIT #x "==0x%x\n", (int) (x))
/*
* Very extensive activity logging. Greatly improves bug detection speed but
* costs a few Mbps if enabled.
*/
#define EV 64
static const char *ev[EV];
static unsigned long ev_a[EV],ev_b[EV];
static int ec = 0;
static void EVENT(const char *s,unsigned long a,unsigned long b)
{
ev[ec] = s;
ev_a[ec] = a;
ev_b[ec] = b;
ec = (ec+1) % EV;
}
static void event_dump(void)
{
int n,i;
printk(KERN_NOTICE "----- event dump follows -----\n");
for (n = 0; n < EV; n++) {
i = (ec+n) % EV;
printk(KERN_NOTICE);
printk(ev[i] ? ev[i] : "(null)",ev_a[i],ev_b[i]);
}
printk(KERN_NOTICE "----- event dump ends here -----\n");
}
#endif /* CONFIG_ATM_ZATM_DEBUG */
#define RING_BUSY 1 /* indication from do_tx that PDU has to be
backlogged */
static struct atm_dev *zatm_boards = NULL;
static unsigned long dummy[2] = {0,0};
#define zin_n(r) inl(zatm_dev->base+r*4)
#define zin(r) inl(zatm_dev->base+uPD98401_##r*4)
#define zout(v,r) outl(v,zatm_dev->base+uPD98401_##r*4)
#define zwait while (zin(CMR) & uPD98401_BUSY)
/* RX0, RX1, TX0, TX1 */
static const int mbx_entries[NR_MBX] = { 1024,1024,1024,1024 };
static const int mbx_esize[NR_MBX] = { 16,16,4,4 }; /* entry size in bytes */
#define MBX_SIZE(i) (mbx_entries[i]*mbx_esize[i])
/*-------------------------------- utilities --------------------------------*/
static void zpokel(struct zatm_dev *zatm_dev,u32 value,u32 addr)
{
zwait;
zout(value,CER);
zout(uPD98401_IND_ACC | uPD98401_IA_BALL |
(uPD98401_IA_TGT_CM << uPD98401_IA_TGT_SHIFT) | addr,CMR);
}
static u32 zpeekl(struct zatm_dev *zatm_dev,u32 addr)
{
zwait;
zout(uPD98401_IND_ACC | uPD98401_IA_BALL | uPD98401_IA_RW |
(uPD98401_IA_TGT_CM << uPD98401_IA_TGT_SHIFT) | addr,CMR);
zwait;
return zin(CER);
}
/*------------------------------- free lists --------------------------------*/
/*
* Free buffer head structure:
* [0] pointer to buffer (for SAR)
* [1] buffer descr link pointer (for SAR)
* [2] back pointer to skb (for poll_rx)
* [3] data
* ...
*/
struct rx_buffer_head {
u32 buffer; /* pointer to buffer (for SAR) */
u32 link; /* buffer descriptor link pointer (for SAR) */
struct sk_buff *skb; /* back pointer to skb (for poll_rx) */
};
static void refill_pool(struct atm_dev *dev,int pool)
{
struct zatm_dev *zatm_dev;
struct sk_buff *skb;
struct rx_buffer_head *first;
unsigned long flags;
int align,offset,free,count,size;
EVENT("refill_pool\n",0,0);
zatm_dev = ZATM_DEV(dev);
size = (64 << (pool <= ZATM_AAL5_POOL_BASE ? 0 :
pool-ZATM_AAL5_POOL_BASE))+sizeof(struct rx_buffer_head);
if (size < PAGE_SIZE) {
align = 32; /* for 32 byte alignment */
offset = sizeof(struct rx_buffer_head);
}
else {
align = 4096;
offset = zatm_dev->pool_info[pool].offset+
sizeof(struct rx_buffer_head);
}
size += align;
spin_lock_irqsave(&zatm_dev->lock, flags);
free = zpeekl(zatm_dev,zatm_dev->pool_base+2*pool) &
uPD98401_RXFP_REMAIN;
spin_unlock_irqrestore(&zatm_dev->lock, flags);
if (free >= zatm_dev->pool_info[pool].low_water) return;
EVENT("starting ... POOL: 0x%x, 0x%x\n",
zpeekl(zatm_dev,zatm_dev->pool_base+2*pool),
zpeekl(zatm_dev,zatm_dev->pool_base+2*pool+1));
EVENT("dummy: 0x%08lx, 0x%08lx\n",dummy[0],dummy[1]);
count = 0;
first = NULL;
while (free < zatm_dev->pool_info[pool].high_water) {
struct rx_buffer_head *head;
skb = alloc_skb(size,GFP_ATOMIC);
if (!skb) {
printk(KERN_WARNING DEV_LABEL "(Itf %d): got no new "
"skb (%d) with %d free\n",dev->number,size,free);
break;
}
skb_reserve(skb,(unsigned char *) ((((unsigned long) skb->data+
align+offset-1) & ~(unsigned long) (align-1))-offset)-
skb->data);
head = (struct rx_buffer_head *) skb->data;
skb_reserve(skb,sizeof(struct rx_buffer_head));
if (!first) first = head;
count++;
head->buffer = virt_to_bus(skb->data);
head->link = 0;
head->skb = skb;
EVENT("enq skb 0x%08lx/0x%08lx\n",(unsigned long) skb,
(unsigned long) head);
spin_lock_irqsave(&zatm_dev->lock, flags);
if (zatm_dev->last_free[pool])
((struct rx_buffer_head *) (zatm_dev->last_free[pool]->
data))[-1].link = virt_to_bus(head);
zatm_dev->last_free[pool] = skb;
skb_queue_tail(&zatm_dev->pool[pool],skb);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
free++;
}
if (first) {
spin_lock_irqsave(&zatm_dev->lock, flags);
zwait;
zout(virt_to_bus(first),CER);
zout(uPD98401_ADD_BAT | (pool << uPD98401_POOL_SHIFT) | count,
CMR);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
EVENT ("POOL: 0x%x, 0x%x\n",
zpeekl(zatm_dev,zatm_dev->pool_base+2*pool),
zpeekl(zatm_dev,zatm_dev->pool_base+2*pool+1));
EVENT("dummy: 0x%08lx, 0x%08lx\n",dummy[0],dummy[1]);
}
}
static void drain_free(struct atm_dev *dev,int pool)
{
skb_queue_purge(&ZATM_DEV(dev)->pool[pool]);
}
static int pool_index(int max_pdu)
{
int i;
if (max_pdu % ATM_CELL_PAYLOAD)
printk(KERN_ERR DEV_LABEL ": driver error in pool_index: "
"max_pdu is %d\n",max_pdu);
if (max_pdu > 65536) return -1;
for (i = 0; (64 << i) < max_pdu; i++);
return i+ZATM_AAL5_POOL_BASE;
}
/* use_pool isn't reentrant */
static void use_pool(struct atm_dev *dev,int pool)
{
struct zatm_dev *zatm_dev;
unsigned long flags;
int size;
zatm_dev = ZATM_DEV(dev);
if (!(zatm_dev->pool_info[pool].ref_count++)) {
skb_queue_head_init(&zatm_dev->pool[pool]);
size = pool-ZATM_AAL5_POOL_BASE;
if (size < 0) size = 0; /* 64B... */
else if (size > 10) size = 10; /* ... 64kB */
spin_lock_irqsave(&zatm_dev->lock, flags);
zpokel(zatm_dev,((zatm_dev->pool_info[pool].low_water/4) <<
uPD98401_RXFP_ALERT_SHIFT) |
(1 << uPD98401_RXFP_BTSZ_SHIFT) |
(size << uPD98401_RXFP_BFSZ_SHIFT),
zatm_dev->pool_base+pool*2);
zpokel(zatm_dev,(unsigned long) dummy,zatm_dev->pool_base+
pool*2+1);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
zatm_dev->last_free[pool] = NULL;
refill_pool(dev,pool);
}
DPRINTK("pool %d: %d\n",pool,zatm_dev->pool_info[pool].ref_count);
}
static void unuse_pool(struct atm_dev *dev,int pool)
{
if (!(--ZATM_DEV(dev)->pool_info[pool].ref_count))
drain_free(dev,pool);
}
/*----------------------------------- RX ------------------------------------*/
#if 0
static void exception(struct atm_vcc *vcc)
{
static int count = 0;
struct zatm_dev *zatm_dev = ZATM_DEV(vcc->dev);
struct zatm_vcc *zatm_vcc = ZATM_VCC(vcc);
unsigned long *qrp;
int i;
if (count++ > 2) return;
for (i = 0; i < 8; i++)
printk("TX%d: 0x%08lx\n",i,
zpeekl(zatm_dev,zatm_vcc->tx_chan*VC_SIZE/4+i));
for (i = 0; i < 5; i++)
printk("SH%d: 0x%08lx\n",i,
zpeekl(zatm_dev,uPD98401_IM(zatm_vcc->shaper)+16*i));
qrp = (unsigned long *) zpeekl(zatm_dev,zatm_vcc->tx_chan*VC_SIZE/4+
uPD98401_TXVC_QRP);
printk("qrp=0x%08lx\n",(unsigned long) qrp);
for (i = 0; i < 4; i++) printk("QRP[%d]: 0x%08lx",i,qrp[i]);
}
#endif
static const char *err_txt[] = {
"No error",
"RX buf underflow",
"RX FIFO overrun",
"Maximum len violation",
"CRC error",
"User abort",
"Length violation",
"T1 error",
"Deactivated",
"???",
"???",
"???",
"???",
"???",
"???",
"???"
};
static void poll_rx(struct atm_dev *dev,int mbx)
{
struct zatm_dev *zatm_dev;
unsigned long pos;
u32 x;
int error;
EVENT("poll_rx\n",0,0);
zatm_dev = ZATM_DEV(dev);
pos = (zatm_dev->mbx_start[mbx] & ~0xffffUL) | zin(MTA(mbx));
while (x = zin(MWA(mbx)), (pos & 0xffff) != x) {
u32 *here;
struct sk_buff *skb;
struct atm_vcc *vcc;
int cells,size,chan;
EVENT("MBX: host 0x%lx, nic 0x%x\n",pos,x);
here = (u32 *) pos;
if (((pos += 16) & 0xffff) == zatm_dev->mbx_end[mbx])
pos = zatm_dev->mbx_start[mbx];
cells = here[0] & uPD98401_AAL5_SIZE;
#if 0
printk("RX IND: 0x%x, 0x%x, 0x%x, 0x%x\n",here[0],here[1],here[2],here[3]);
{
unsigned long *x;
printk("POOL: 0x%08x, 0x%08x\n",zpeekl(zatm_dev,
zatm_dev->pool_base),
zpeekl(zatm_dev,zatm_dev->pool_base+1));
x = (unsigned long *) here[2];
printk("[0..3] = 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx\n",
x[0],x[1],x[2],x[3]);
}
#endif
error = 0;
if (here[3] & uPD98401_AAL5_ERR) {
error = (here[3] & uPD98401_AAL5_ES) >>
uPD98401_AAL5_ES_SHIFT;
if (error == uPD98401_AAL5_ES_DEACT ||
error == uPD98401_AAL5_ES_FREE) continue;
}
EVENT("error code 0x%x/0x%x\n",(here[3] & uPD98401_AAL5_ES) >>
uPD98401_AAL5_ES_SHIFT,error);
skb = ((struct rx_buffer_head *) bus_to_virt(here[2]))->skb;
__net_timestamp(skb);
#if 0
printk("[-3..0] 0x%08lx 0x%08lx 0x%08lx 0x%08lx\n",((unsigned *) skb->data)[-3],
((unsigned *) skb->data)[-2],((unsigned *) skb->data)[-1],
((unsigned *) skb->data)[0]);
#endif
EVENT("skb 0x%lx, here 0x%lx\n",(unsigned long) skb,
(unsigned long) here);
#if 0
printk("dummy: 0x%08lx, 0x%08lx\n",dummy[0],dummy[1]);
#endif
size = error ? 0 : ntohs(((__be16 *) skb->data)[cells*
ATM_CELL_PAYLOAD/sizeof(u16)-3]);
EVENT("got skb 0x%lx, size %d\n",(unsigned long) skb,size);
chan = (here[3] & uPD98401_AAL5_CHAN) >>
uPD98401_AAL5_CHAN_SHIFT;
if (chan < zatm_dev->chans && zatm_dev->rx_map[chan]) {
int pos;
vcc = zatm_dev->rx_map[chan];
pos = ZATM_VCC(vcc)->pool;
if (skb == zatm_dev->last_free[pos])
zatm_dev->last_free[pos] = NULL;
skb_unlink(skb, zatm_dev->pool + pos);
}
else {
printk(KERN_ERR DEV_LABEL "(itf %d): RX indication "
"for non-existing channel\n",dev->number);
size = 0;
vcc = NULL;
event_dump();
}
if (error) {
static unsigned long silence = 0;
static int last_error = 0;
if (error != last_error ||
time_after(jiffies, silence) || silence == 0){
printk(KERN_WARNING DEV_LABEL "(itf %d): "
"chan %d error %s\n",dev->number,chan,
err_txt[error]);
last_error = error;
silence = (jiffies+2*HZ)|1;
}
size = 0;
}
if (size && (size > cells*ATM_CELL_PAYLOAD-ATM_AAL5_TRAILER ||
size <= (cells-1)*ATM_CELL_PAYLOAD-ATM_AAL5_TRAILER)) {
printk(KERN_ERR DEV_LABEL "(itf %d): size %d with %d "
"cells\n",dev->number,size,cells);
size = 0;
event_dump();
}
if (size > ATM_MAX_AAL5_PDU) {
printk(KERN_ERR DEV_LABEL "(itf %d): size too big "
"(%d)\n",dev->number,size);
size = 0;
event_dump();
}
if (!size) {
dev_kfree_skb_irq(skb);
if (vcc) atomic_inc(&vcc->stats->rx_err);
continue;
}
if (!atm_charge(vcc,skb->truesize)) {
dev_kfree_skb_irq(skb);
continue;
}
skb->len = size;
ATM_SKB(skb)->vcc = vcc;
vcc->push(vcc,skb);
atomic_inc(&vcc->stats->rx);
}
zout(pos & 0xffff,MTA(mbx));
#if 0 /* probably a stupid idea */
refill_pool(dev,zatm_vcc->pool);
/* maybe this saves us a few interrupts */
#endif
}
static int open_rx_first(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
unsigned short chan;
int cells;
DPRINTK("open_rx_first (0x%x)\n",inb_p(0xc053));
zatm_dev = ZATM_DEV(vcc->dev);
zatm_vcc = ZATM_VCC(vcc);
zatm_vcc->rx_chan = 0;
if (vcc->qos.rxtp.traffic_class == ATM_NONE) return 0;
if (vcc->qos.aal == ATM_AAL5) {
if (vcc->qos.rxtp.max_sdu > 65464)
vcc->qos.rxtp.max_sdu = 65464;
/* fix this - we may want to receive 64kB SDUs
later */
cells = DIV_ROUND_UP(vcc->qos.rxtp.max_sdu + ATM_AAL5_TRAILER,
ATM_CELL_PAYLOAD);
zatm_vcc->pool = pool_index(cells*ATM_CELL_PAYLOAD);
}
else {
cells = 1;
zatm_vcc->pool = ZATM_AAL0_POOL;
}
if (zatm_vcc->pool < 0) return -EMSGSIZE;
spin_lock_irqsave(&zatm_dev->lock, flags);
zwait;
zout(uPD98401_OPEN_CHAN,CMR);
zwait;
DPRINTK("0x%x 0x%x\n",zin(CMR),zin(CER));
chan = (zin(CMR) & uPD98401_CHAN_ADDR) >> uPD98401_CHAN_ADDR_SHIFT;
spin_unlock_irqrestore(&zatm_dev->lock, flags);
DPRINTK("chan is %d\n",chan);
if (!chan) return -EAGAIN;
use_pool(vcc->dev,zatm_vcc->pool);
DPRINTK("pool %d\n",zatm_vcc->pool);
/* set up VC descriptor */
spin_lock_irqsave(&zatm_dev->lock, flags);
zpokel(zatm_dev,zatm_vcc->pool << uPD98401_RXVC_POOL_SHIFT,
chan*VC_SIZE/4);
zpokel(zatm_dev,uPD98401_RXVC_OD | (vcc->qos.aal == ATM_AAL5 ?
uPD98401_RXVC_AR : 0) | cells,chan*VC_SIZE/4+1);
zpokel(zatm_dev,0,chan*VC_SIZE/4+2);
zatm_vcc->rx_chan = chan;
zatm_dev->rx_map[chan] = vcc;
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return 0;
}
static int open_rx_second(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
int pos,shift;
DPRINTK("open_rx_second (0x%x)\n",inb_p(0xc053));
zatm_dev = ZATM_DEV(vcc->dev);
zatm_vcc = ZATM_VCC(vcc);
if (!zatm_vcc->rx_chan) return 0;
spin_lock_irqsave(&zatm_dev->lock, flags);
/* should also handle VPI @@@ */
pos = vcc->vci >> 1;
shift = (1-(vcc->vci & 1)) << 4;
zpokel(zatm_dev,(zpeekl(zatm_dev,pos) & ~(0xffff << shift)) |
((zatm_vcc->rx_chan | uPD98401_RXLT_ENBL) << shift),pos);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return 0;
}
static void close_rx(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
int pos,shift;
zatm_vcc = ZATM_VCC(vcc);
zatm_dev = ZATM_DEV(vcc->dev);
if (!zatm_vcc->rx_chan) return;
DPRINTK("close_rx\n");
/* disable receiver */
if (vcc->vpi != ATM_VPI_UNSPEC && vcc->vci != ATM_VCI_UNSPEC) {
spin_lock_irqsave(&zatm_dev->lock, flags);
pos = vcc->vci >> 1;
shift = (1-(vcc->vci & 1)) << 4;
zpokel(zatm_dev,zpeekl(zatm_dev,pos) & ~(0xffff << shift),pos);
zwait;
zout(uPD98401_NOP,CMR);
zwait;
zout(uPD98401_NOP,CMR);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
}
spin_lock_irqsave(&zatm_dev->lock, flags);
zwait;
zout(uPD98401_DEACT_CHAN | uPD98401_CHAN_RT | (zatm_vcc->rx_chan <<
uPD98401_CHAN_ADDR_SHIFT),CMR);
zwait;
udelay(10); /* why oh why ... ? */
zout(uPD98401_CLOSE_CHAN | uPD98401_CHAN_RT | (zatm_vcc->rx_chan <<
uPD98401_CHAN_ADDR_SHIFT),CMR);
zwait;
if (!(zin(CMR) & uPD98401_CHAN_ADDR))
printk(KERN_CRIT DEV_LABEL "(itf %d): can't close RX channel "
"%d\n",vcc->dev->number,zatm_vcc->rx_chan);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
zatm_dev->rx_map[zatm_vcc->rx_chan] = NULL;
zatm_vcc->rx_chan = 0;
unuse_pool(vcc->dev,zatm_vcc->pool);
}
static int start_rx(struct atm_dev *dev)
{
struct zatm_dev *zatm_dev;
int size,i;
DPRINTK("start_rx\n");
zatm_dev = ZATM_DEV(dev);
size = sizeof(struct atm_vcc *)*zatm_dev->chans;
zatm_dev->rx_map = kzalloc(size,GFP_KERNEL);
if (!zatm_dev->rx_map) return -ENOMEM;
/* set VPI/VCI split (use all VCIs and give what's left to VPIs) */
zpokel(zatm_dev,(1 << dev->ci_range.vci_bits)-1,uPD98401_VRR);
/* prepare free buffer pools */
for (i = 0; i <= ZATM_LAST_POOL; i++) {
zatm_dev->pool_info[i].ref_count = 0;
zatm_dev->pool_info[i].rqa_count = 0;
zatm_dev->pool_info[i].rqu_count = 0;
zatm_dev->pool_info[i].low_water = LOW_MARK;
zatm_dev->pool_info[i].high_water = HIGH_MARK;
zatm_dev->pool_info[i].offset = 0;
zatm_dev->pool_info[i].next_off = 0;
zatm_dev->pool_info[i].next_cnt = 0;
zatm_dev->pool_info[i].next_thres = OFF_CNG_THRES;
}
return 0;
}
/*----------------------------------- TX ------------------------------------*/
static int do_tx(struct sk_buff *skb)
{
struct atm_vcc *vcc;
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
u32 *dsc;
unsigned long flags;
EVENT("do_tx\n",0,0);
DPRINTK("sending skb %p\n",skb);
vcc = ATM_SKB(skb)->vcc;
zatm_dev = ZATM_DEV(vcc->dev);
zatm_vcc = ZATM_VCC(vcc);
EVENT("iovcnt=%d\n",skb_shinfo(skb)->nr_frags,0);
spin_lock_irqsave(&zatm_dev->lock, flags);
if (!skb_shinfo(skb)->nr_frags) {
if (zatm_vcc->txing == RING_ENTRIES-1) {
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return RING_BUSY;
}
zatm_vcc->txing++;
dsc = zatm_vcc->ring+zatm_vcc->ring_curr;
zatm_vcc->ring_curr = (zatm_vcc->ring_curr+RING_WORDS) &
(RING_ENTRIES*RING_WORDS-1);
dsc[1] = 0;
dsc[2] = skb->len;
dsc[3] = virt_to_bus(skb->data);
mb();
dsc[0] = uPD98401_TXPD_V | uPD98401_TXPD_DP | uPD98401_TXPD_SM
| (vcc->qos.aal == ATM_AAL5 ? uPD98401_TXPD_AAL5 : 0 |
(ATM_SKB(skb)->atm_options & ATM_ATMOPT_CLP ?
uPD98401_CLPM_1 : uPD98401_CLPM_0));
EVENT("dsc (0x%lx)\n",(unsigned long) dsc,0);
}
else {
printk("NONONONOO!!!!\n");
dsc = NULL;
#if 0
u32 *put;
int i;
dsc = kmalloc(uPD98401_TXPD_SIZE * 2 +
uPD98401_TXBD_SIZE * ATM_SKB(skb)->iovcnt, GFP_ATOMIC);
if (!dsc) {
if (vcc->pop)
vcc->pop(vcc, skb);
else
dev_kfree_skb_irq(skb);
return -EAGAIN;
}
/* @@@ should check alignment */
put = dsc+8;
dsc[0] = uPD98401_TXPD_V | uPD98401_TXPD_DP |
(vcc->aal == ATM_AAL5 ? uPD98401_TXPD_AAL5 : 0 |
(ATM_SKB(skb)->atm_options & ATM_ATMOPT_CLP ?
uPD98401_CLPM_1 : uPD98401_CLPM_0));
dsc[1] = 0;
dsc[2] = ATM_SKB(skb)->iovcnt * uPD98401_TXBD_SIZE;
dsc[3] = virt_to_bus(put);
for (i = 0; i < ATM_SKB(skb)->iovcnt; i++) {
*put++ = ((struct iovec *) skb->data)[i].iov_len;
*put++ = virt_to_bus(((struct iovec *)
skb->data)[i].iov_base);
}
put[-2] |= uPD98401_TXBD_LAST;
#endif
}
ZATM_PRV_DSC(skb) = dsc;
skb_queue_tail(&zatm_vcc->tx_queue,skb);
DPRINTK("QRP=0x%08lx\n",zpeekl(zatm_dev,zatm_vcc->tx_chan*VC_SIZE/4+
uPD98401_TXVC_QRP));
zwait;
zout(uPD98401_TX_READY | (zatm_vcc->tx_chan <<
uPD98401_CHAN_ADDR_SHIFT),CMR);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
EVENT("done\n",0,0);
return 0;
}
static inline void dequeue_tx(struct atm_vcc *vcc)
{
struct zatm_vcc *zatm_vcc;
struct sk_buff *skb;
EVENT("dequeue_tx\n",0,0);
zatm_vcc = ZATM_VCC(vcc);
skb = skb_dequeue(&zatm_vcc->tx_queue);
if (!skb) {
printk(KERN_CRIT DEV_LABEL "(itf %d): dequeue_tx but not "
"txing\n",vcc->dev->number);
return;
}
#if 0 /* @@@ would fail on CLP */
if (*ZATM_PRV_DSC(skb) != (uPD98401_TXPD_V | uPD98401_TXPD_DP |
uPD98401_TXPD_SM | uPD98401_TXPD_AAL5)) printk("@#*$!!!! (%08x)\n",
*ZATM_PRV_DSC(skb));
#endif
*ZATM_PRV_DSC(skb) = 0; /* mark as invalid */
zatm_vcc->txing--;
if (vcc->pop) vcc->pop(vcc,skb);
else dev_kfree_skb_irq(skb);
while ((skb = skb_dequeue(&zatm_vcc->backlog)))
if (do_tx(skb) == RING_BUSY) {
skb_queue_head(&zatm_vcc->backlog,skb);
break;
}
atomic_inc(&vcc->stats->tx);
wake_up(&zatm_vcc->tx_wait);
}
static void poll_tx(struct atm_dev *dev,int mbx)
{
struct zatm_dev *zatm_dev;
unsigned long pos;
u32 x;
EVENT("poll_tx\n",0,0);
zatm_dev = ZATM_DEV(dev);
pos = (zatm_dev->mbx_start[mbx] & ~0xffffUL) | zin(MTA(mbx));
while (x = zin(MWA(mbx)), (pos & 0xffff) != x) {
int chan;
#if 1
u32 data,*addr;
EVENT("MBX: host 0x%lx, nic 0x%x\n",pos,x);
addr = (u32 *) pos;
data = *addr;
chan = (data & uPD98401_TXI_CONN) >> uPD98401_TXI_CONN_SHIFT;
EVENT("addr = 0x%lx, data = 0x%08x,",(unsigned long) addr,
data);
EVENT("chan = %d\n",chan,0);
#else
NO !
chan = (zatm_dev->mbx_start[mbx][pos >> 2] & uPD98401_TXI_CONN)
>> uPD98401_TXI_CONN_SHIFT;
#endif
if (chan < zatm_dev->chans && zatm_dev->tx_map[chan])
dequeue_tx(zatm_dev->tx_map[chan]);
else {
printk(KERN_CRIT DEV_LABEL "(itf %d): TX indication "
"for non-existing channel %d\n",dev->number,chan);
event_dump();
}
if (((pos += 4) & 0xffff) == zatm_dev->mbx_end[mbx])
pos = zatm_dev->mbx_start[mbx];
}
zout(pos & 0xffff,MTA(mbx));
}
/*
* BUG BUG BUG: Doesn't handle "new-style" rate specification yet.
*/
static int alloc_shaper(struct atm_dev *dev,int *pcr,int min,int max,int ubr)
{
struct zatm_dev *zatm_dev;
unsigned long flags;
unsigned long i,m,c;
int shaper;
DPRINTK("alloc_shaper (min = %d, max = %d)\n",min,max);
zatm_dev = ZATM_DEV(dev);
if (!zatm_dev->free_shapers) return -EAGAIN;
for (shaper = 0; !((zatm_dev->free_shapers >> shaper) & 1); shaper++);
zatm_dev->free_shapers &= ~1 << shaper;
if (ubr) {
c = 5;
i = m = 1;
zatm_dev->ubr_ref_cnt++;
zatm_dev->ubr = shaper;
*pcr = 0;
}
else {
if (min) {
if (min <= 255) {
i = min;
m = ATM_OC3_PCR;
}
else {
i = 255;
m = ATM_OC3_PCR*255/min;
}
}
else {
if (max > zatm_dev->tx_bw) max = zatm_dev->tx_bw;
if (max <= 255) {
i = max;
m = ATM_OC3_PCR;
}
else {
i = 255;
m = DIV_ROUND_UP(ATM_OC3_PCR*255, max);
}
}
if (i > m) {
printk(KERN_CRIT DEV_LABEL "shaper algorithm botched "
"[%d,%d] -> i=%ld,m=%ld\n",min,max,i,m);
m = i;
}
*pcr = i*ATM_OC3_PCR/m;
c = 20; /* @@@ should use max_cdv ! */
if ((min && *pcr < min) || (max && *pcr > max)) return -EINVAL;
if (zatm_dev->tx_bw < *pcr) return -EAGAIN;
zatm_dev->tx_bw -= *pcr;
}
spin_lock_irqsave(&zatm_dev->lock, flags);
DPRINTK("i = %d, m = %d, PCR = %d\n",i,m,*pcr);
zpokel(zatm_dev,(i << uPD98401_IM_I_SHIFT) | m,uPD98401_IM(shaper));
zpokel(zatm_dev,c << uPD98401_PC_C_SHIFT,uPD98401_PC(shaper));
zpokel(zatm_dev,0,uPD98401_X(shaper));
zpokel(zatm_dev,0,uPD98401_Y(shaper));
zpokel(zatm_dev,uPD98401_PS_E,uPD98401_PS(shaper));
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return shaper;
}
static void dealloc_shaper(struct atm_dev *dev,int shaper)
{
struct zatm_dev *zatm_dev;
unsigned long flags;
zatm_dev = ZATM_DEV(dev);
if (shaper == zatm_dev->ubr) {
if (--zatm_dev->ubr_ref_cnt) return;
zatm_dev->ubr = -1;
}
spin_lock_irqsave(&zatm_dev->lock, flags);
zpokel(zatm_dev,zpeekl(zatm_dev,uPD98401_PS(shaper)) & ~uPD98401_PS_E,
uPD98401_PS(shaper));
spin_unlock_irqrestore(&zatm_dev->lock, flags);
zatm_dev->free_shapers |= 1 << shaper;
}
static void close_tx(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
int chan;
zatm_vcc = ZATM_VCC(vcc);
zatm_dev = ZATM_DEV(vcc->dev);
chan = zatm_vcc->tx_chan;
if (!chan) return;
DPRINTK("close_tx\n");
if (skb_peek(&zatm_vcc->backlog)) {
printk("waiting for backlog to drain ...\n");
event_dump();
wait_event(zatm_vcc->tx_wait, !skb_peek(&zatm_vcc->backlog));
}
if (skb_peek(&zatm_vcc->tx_queue)) {
printk("waiting for TX queue to drain ...\n");
event_dump();
wait_event(zatm_vcc->tx_wait, !skb_peek(&zatm_vcc->tx_queue));
}
spin_lock_irqsave(&zatm_dev->lock, flags);
#if 0
zwait;
zout(uPD98401_DEACT_CHAN | (chan << uPD98401_CHAN_ADDR_SHIFT),CMR);
#endif
zwait;
zout(uPD98401_CLOSE_CHAN | (chan << uPD98401_CHAN_ADDR_SHIFT),CMR);
zwait;
if (!(zin(CMR) & uPD98401_CHAN_ADDR))
printk(KERN_CRIT DEV_LABEL "(itf %d): can't close TX channel "
"%d\n",vcc->dev->number,chan);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
zatm_vcc->tx_chan = 0;
zatm_dev->tx_map[chan] = NULL;
if (zatm_vcc->shaper != zatm_dev->ubr) {
zatm_dev->tx_bw += vcc->qos.txtp.min_pcr;
dealloc_shaper(vcc->dev,zatm_vcc->shaper);
}
kfree(zatm_vcc->ring);
}
static int open_tx_first(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
u32 *loop;
unsigned short chan;
int unlimited;
DPRINTK("open_tx_first\n");
zatm_dev = ZATM_DEV(vcc->dev);
zatm_vcc = ZATM_VCC(vcc);
zatm_vcc->tx_chan = 0;
if (vcc->qos.txtp.traffic_class == ATM_NONE) return 0;
spin_lock_irqsave(&zatm_dev->lock, flags);
zwait;
zout(uPD98401_OPEN_CHAN,CMR);
zwait;
DPRINTK("0x%x 0x%x\n",zin(CMR),zin(CER));
chan = (zin(CMR) & uPD98401_CHAN_ADDR) >> uPD98401_CHAN_ADDR_SHIFT;
spin_unlock_irqrestore(&zatm_dev->lock, flags);
DPRINTK("chan is %d\n",chan);
if (!chan) return -EAGAIN;
unlimited = vcc->qos.txtp.traffic_class == ATM_UBR &&
(!vcc->qos.txtp.max_pcr || vcc->qos.txtp.max_pcr == ATM_MAX_PCR ||
vcc->qos.txtp.max_pcr >= ATM_OC3_PCR);
if (unlimited && zatm_dev->ubr != -1) zatm_vcc->shaper = zatm_dev->ubr;
else {
int uninitialized_var(pcr);
if (unlimited) vcc->qos.txtp.max_sdu = ATM_MAX_AAL5_PDU;
if ((zatm_vcc->shaper = alloc_shaper(vcc->dev,&pcr,
vcc->qos.txtp.min_pcr,vcc->qos.txtp.max_pcr,unlimited))
< 0) {
close_tx(vcc);
return zatm_vcc->shaper;
}
if (pcr > ATM_OC3_PCR) pcr = ATM_OC3_PCR;
vcc->qos.txtp.min_pcr = vcc->qos.txtp.max_pcr = pcr;
}
zatm_vcc->tx_chan = chan;
skb_queue_head_init(&zatm_vcc->tx_queue);
init_waitqueue_head(&zatm_vcc->tx_wait);
/* initialize ring */
zatm_vcc->ring = kzalloc(RING_SIZE,GFP_KERNEL);
if (!zatm_vcc->ring) return -ENOMEM;
loop = zatm_vcc->ring+RING_ENTRIES*RING_WORDS;
loop[0] = uPD98401_TXPD_V;
loop[1] = loop[2] = 0;
loop[3] = virt_to_bus(zatm_vcc->ring);
zatm_vcc->ring_curr = 0;
zatm_vcc->txing = 0;
skb_queue_head_init(&zatm_vcc->backlog);
zpokel(zatm_dev,virt_to_bus(zatm_vcc->ring),
chan*VC_SIZE/4+uPD98401_TXVC_QRP);
return 0;
}
static int open_tx_second(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
unsigned long flags;
DPRINTK("open_tx_second\n");
zatm_dev = ZATM_DEV(vcc->dev);
zatm_vcc = ZATM_VCC(vcc);
if (!zatm_vcc->tx_chan) return 0;
/* set up VC descriptor */
spin_lock_irqsave(&zatm_dev->lock, flags);
zpokel(zatm_dev,0,zatm_vcc->tx_chan*VC_SIZE/4);
zpokel(zatm_dev,uPD98401_TXVC_L | (zatm_vcc->shaper <<
uPD98401_TXVC_SHP_SHIFT) | (vcc->vpi << uPD98401_TXVC_VPI_SHIFT) |
vcc->vci,zatm_vcc->tx_chan*VC_SIZE/4+1);
zpokel(zatm_dev,0,zatm_vcc->tx_chan*VC_SIZE/4+2);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
zatm_dev->tx_map[zatm_vcc->tx_chan] = vcc;
return 0;
}
static int start_tx(struct atm_dev *dev)
{
struct zatm_dev *zatm_dev;
int i;
DPRINTK("start_tx\n");
zatm_dev = ZATM_DEV(dev);
zatm_dev->tx_map = kmalloc(sizeof(struct atm_vcc *)*
zatm_dev->chans,GFP_KERNEL);
if (!zatm_dev->tx_map) return -ENOMEM;
zatm_dev->tx_bw = ATM_OC3_PCR;
zatm_dev->free_shapers = (1 << NR_SHAPERS)-1;
zatm_dev->ubr = -1;
zatm_dev->ubr_ref_cnt = 0;
/* initialize shapers */
for (i = 0; i < NR_SHAPERS; i++) zpokel(zatm_dev,0,uPD98401_PS(i));
return 0;
}
/*------------------------------- interrupts --------------------------------*/
static irqreturn_t zatm_int(int irq,void *dev_id)
{
struct atm_dev *dev;
struct zatm_dev *zatm_dev;
u32 reason;
int handled = 0;
dev = dev_id;
zatm_dev = ZATM_DEV(dev);
while ((reason = zin(GSR))) {
handled = 1;
EVENT("reason 0x%x\n",reason,0);
if (reason & uPD98401_INT_PI) {
EVENT("PHY int\n",0,0);
dev->phy->interrupt(dev);
}
if (reason & uPD98401_INT_RQA) {
unsigned long pools;
int i;
pools = zin(RQA);
EVENT("RQA (0x%08x)\n",pools,0);
for (i = 0; pools; i++) {
if (pools & 1) {
refill_pool(dev,i);
zatm_dev->pool_info[i].rqa_count++;
}
pools >>= 1;
}
}
if (reason & uPD98401_INT_RQU) {
unsigned long pools;
int i;
pools = zin(RQU);
printk(KERN_WARNING DEV_LABEL "(itf %d): RQU 0x%08lx\n",
dev->number,pools);
event_dump();
for (i = 0; pools; i++) {
if (pools & 1) {
refill_pool(dev,i);
zatm_dev->pool_info[i].rqu_count++;
}
pools >>= 1;
}
}
/* don't handle RD */
if (reason & uPD98401_INT_SPE)
printk(KERN_ALERT DEV_LABEL "(itf %d): system parity "
"error at 0x%08x\n",dev->number,zin(ADDR));
if (reason & uPD98401_INT_CPE)
printk(KERN_ALERT DEV_LABEL "(itf %d): control memory "
"parity error at 0x%08x\n",dev->number,zin(ADDR));
if (reason & uPD98401_INT_SBE) {
printk(KERN_ALERT DEV_LABEL "(itf %d): system bus "
"error at 0x%08x\n",dev->number,zin(ADDR));
event_dump();
}
/* don't handle IND */
if (reason & uPD98401_INT_MF) {
printk(KERN_CRIT DEV_LABEL "(itf %d): mailbox full "
"(0x%x)\n",dev->number,(reason & uPD98401_INT_MF)
>> uPD98401_INT_MF_SHIFT);
event_dump();
/* @@@ should try to recover */
}
if (reason & uPD98401_INT_MM) {
if (reason & 1) poll_rx(dev,0);
if (reason & 2) poll_rx(dev,1);
if (reason & 4) poll_tx(dev,2);
if (reason & 8) poll_tx(dev,3);
}
/* @@@ handle RCRn */
}
return IRQ_RETVAL(handled);
}
/*----------------------------- (E)EPROM access -----------------------------*/
static void eprom_set(struct zatm_dev *zatm_dev, unsigned long value,
unsigned short cmd)
{
int error;
if ((error = pci_write_config_dword(zatm_dev->pci_dev,cmd,value)))
printk(KERN_ERR DEV_LABEL ": PCI write failed (0x%02x)\n",
error);
}
static unsigned long eprom_get(struct zatm_dev *zatm_dev, unsigned short cmd)
{
unsigned int value;
int error;
if ((error = pci_read_config_dword(zatm_dev->pci_dev,cmd,&value)))
printk(KERN_ERR DEV_LABEL ": PCI read failed (0x%02x)\n",
error);
return value;
}
static void eprom_put_bits(struct zatm_dev *zatm_dev, unsigned long data,
int bits, unsigned short cmd)
{
unsigned long value;
int i;
for (i = bits-1; i >= 0; i--) {
value = ZEPROM_CS | (((data >> i) & 1) ? ZEPROM_DI : 0);
eprom_set(zatm_dev,value,cmd);
eprom_set(zatm_dev,value | ZEPROM_SK,cmd);
eprom_set(zatm_dev,value,cmd);
}
}
static void eprom_get_byte(struct zatm_dev *zatm_dev, unsigned char *byte,
unsigned short cmd)
{
int i;
*byte = 0;
for (i = 8; i; i--) {
eprom_set(zatm_dev,ZEPROM_CS,cmd);
eprom_set(zatm_dev,ZEPROM_CS | ZEPROM_SK,cmd);
*byte <<= 1;
if (eprom_get(zatm_dev,cmd) & ZEPROM_DO) *byte |= 1;
eprom_set(zatm_dev,ZEPROM_CS,cmd);
}
}
static unsigned char eprom_try_esi(struct atm_dev *dev, unsigned short cmd,
int offset, int swap)
{
unsigned char buf[ZEPROM_SIZE];
struct zatm_dev *zatm_dev;
int i;
zatm_dev = ZATM_DEV(dev);
for (i = 0; i < ZEPROM_SIZE; i += 2) {
eprom_set(zatm_dev,ZEPROM_CS,cmd); /* select EPROM */
eprom_put_bits(zatm_dev,ZEPROM_CMD_READ,ZEPROM_CMD_LEN,cmd);
eprom_put_bits(zatm_dev,i >> 1,ZEPROM_ADDR_LEN,cmd);
eprom_get_byte(zatm_dev,buf+i+swap,cmd);
eprom_get_byte(zatm_dev,buf+i+1-swap,cmd);
eprom_set(zatm_dev,0,cmd); /* deselect EPROM */
}
memcpy(dev->esi,buf+offset,ESI_LEN);
return memcmp(dev->esi,"\0\0\0\0\0",ESI_LEN); /* assumes ESI_LEN == 6 */
}
static void eprom_get_esi(struct atm_dev *dev)
{
if (eprom_try_esi(dev,ZEPROM_V1_REG,ZEPROM_V1_ESI_OFF,1)) return;
(void) eprom_try_esi(dev,ZEPROM_V2_REG,ZEPROM_V2_ESI_OFF,0);
}
/*--------------------------------- entries ---------------------------------*/
static int zatm_init(struct atm_dev *dev)
{
struct zatm_dev *zatm_dev;
struct pci_dev *pci_dev;
unsigned short command;
int error,i,last;
unsigned long t0,t1,t2;
DPRINTK(">zatm_init\n");
zatm_dev = ZATM_DEV(dev);
spin_lock_init(&zatm_dev->lock);
pci_dev = zatm_dev->pci_dev;
zatm_dev->base = pci_resource_start(pci_dev, 0);
zatm_dev->irq = pci_dev->irq;
if ((error = pci_read_config_word(pci_dev,PCI_COMMAND,&command))) {
printk(KERN_ERR DEV_LABEL "(itf %d): init error 0x%02x\n",
dev->number,error);
return -EINVAL;
}
if ((error = pci_write_config_word(pci_dev,PCI_COMMAND,
command | PCI_COMMAND_IO | PCI_COMMAND_MASTER))) {
printk(KERN_ERR DEV_LABEL "(itf %d): can't enable IO (0x%02x)"
"\n",dev->number,error);
return -EIO;
}
eprom_get_esi(dev);
printk(KERN_NOTICE DEV_LABEL "(itf %d): rev.%d,base=0x%x,irq=%d,",
dev->number,pci_dev->revision,zatm_dev->base,zatm_dev->irq);
/* reset uPD98401 */
zout(0,SWR);
while (!(zin(GSR) & uPD98401_INT_IND));
zout(uPD98401_GMR_ONE /*uPD98401_BURST4*/,GMR);
last = MAX_CRAM_SIZE;
for (i = last-RAM_INCREMENT; i >= 0; i -= RAM_INCREMENT) {
zpokel(zatm_dev,0x55555555,i);
if (zpeekl(zatm_dev,i) != 0x55555555) last = i;
else {
zpokel(zatm_dev,0xAAAAAAAA,i);
if (zpeekl(zatm_dev,i) != 0xAAAAAAAA) last = i;
else zpokel(zatm_dev,i,i);
}
}
for (i = 0; i < last; i += RAM_INCREMENT)
if (zpeekl(zatm_dev,i) != i) break;
zatm_dev->mem = i << 2;
while (i) zpokel(zatm_dev,0,--i);
/* reset again to rebuild memory pointers */
zout(0,SWR);
while (!(zin(GSR) & uPD98401_INT_IND));
zout(uPD98401_GMR_ONE | uPD98401_BURST8 | uPD98401_BURST4 |
uPD98401_BURST2 | uPD98401_GMR_PM | uPD98401_GMR_DR,GMR);
/* TODO: should shrink allocation now */
printk("mem=%dkB,%s (",zatm_dev->mem >> 10,zatm_dev->copper ? "UTP" :
"MMF");
for (i = 0; i < ESI_LEN; i++)
printk("%02X%s",dev->esi[i],i == ESI_LEN-1 ? ")\n" : "-");
do {
unsigned long flags;
spin_lock_irqsave(&zatm_dev->lock, flags);
t0 = zpeekl(zatm_dev,uPD98401_TSR);
udelay(10);
t1 = zpeekl(zatm_dev,uPD98401_TSR);
udelay(1010);
t2 = zpeekl(zatm_dev,uPD98401_TSR);
spin_unlock_irqrestore(&zatm_dev->lock, flags);
}
while (t0 > t1 || t1 > t2); /* loop if wrapping ... */
zatm_dev->khz = t2-2*t1+t0;
printk(KERN_NOTICE DEV_LABEL "(itf %d): uPD98401 %d.%d at %d.%03d "
"MHz\n",dev->number,
(zin(VER) & uPD98401_MAJOR) >> uPD98401_MAJOR_SHIFT,
zin(VER) & uPD98401_MINOR,zatm_dev->khz/1000,zatm_dev->khz % 1000);
return uPD98402_init(dev);
}
static int zatm_start(struct atm_dev *dev)
{
struct zatm_dev *zatm_dev = ZATM_DEV(dev);
struct pci_dev *pdev = zatm_dev->pci_dev;
unsigned long curr;
int pools,vccs,rx;
int error, i, ld;
DPRINTK("zatm_start\n");
zatm_dev->rx_map = zatm_dev->tx_map = NULL;
for (i = 0; i < NR_MBX; i++)
zatm_dev->mbx_start[i] = 0;
error = request_irq(zatm_dev->irq, zatm_int, IRQF_SHARED, DEV_LABEL, dev);
if (error < 0) {
printk(KERN_ERR DEV_LABEL "(itf %d): IRQ%d is already in use\n",
dev->number,zatm_dev->irq);
goto done;
}
/* define memory regions */
pools = NR_POOLS;
if (NR_SHAPERS*SHAPER_SIZE > pools*POOL_SIZE)
pools = NR_SHAPERS*SHAPER_SIZE/POOL_SIZE;
vccs = (zatm_dev->mem-NR_SHAPERS*SHAPER_SIZE-pools*POOL_SIZE)/
(2*VC_SIZE+RX_SIZE);
ld = -1;
for (rx = 1; rx < vccs; rx <<= 1) ld++;
dev->ci_range.vpi_bits = 0; /* @@@ no VPI for now */
dev->ci_range.vci_bits = ld;
dev->link_rate = ATM_OC3_PCR;
zatm_dev->chans = vccs; /* ??? */
curr = rx*RX_SIZE/4;
DPRINTK("RX pool 0x%08lx\n",curr);
zpokel(zatm_dev,curr,uPD98401_PMA); /* receive pool */
zatm_dev->pool_base = curr;
curr += pools*POOL_SIZE/4;
DPRINTK("Shapers 0x%08lx\n",curr);
zpokel(zatm_dev,curr,uPD98401_SMA); /* shapers */
curr += NR_SHAPERS*SHAPER_SIZE/4;
DPRINTK("Free 0x%08lx\n",curr);
zpokel(zatm_dev,curr,uPD98401_TOS); /* free pool */
printk(KERN_INFO DEV_LABEL "(itf %d): %d shapers, %d pools, %d RX, "
"%ld VCs\n",dev->number,NR_SHAPERS,pools,rx,
(zatm_dev->mem-curr*4)/VC_SIZE);
/* create mailboxes */
for (i = 0; i < NR_MBX; i++) {
void *mbx;
dma_addr_t mbx_dma;
if (!mbx_entries[i])
continue;
mbx = pci_alloc_consistent(pdev, 2*MBX_SIZE(i), &mbx_dma);
if (!mbx) {
error = -ENOMEM;
goto out;
}
/*
* Alignment provided by pci_alloc_consistent() isn't enough
* for this device.
*/
if (((unsigned long)mbx ^ mbx_dma) & 0xffff) {
printk(KERN_ERR DEV_LABEL "(itf %d): system "
"bus incompatible with driver\n", dev->number);
pci_free_consistent(pdev, 2*MBX_SIZE(i), mbx, mbx_dma);
error = -ENODEV;
goto out;
}
DPRINTK("mbx@0x%08lx-0x%08lx\n", mbx, mbx + MBX_SIZE(i));
zatm_dev->mbx_start[i] = (unsigned long)mbx;
zatm_dev->mbx_dma[i] = mbx_dma;
zatm_dev->mbx_end[i] = (zatm_dev->mbx_start[i] + MBX_SIZE(i)) &
0xffff;
zout(mbx_dma >> 16, MSH(i));
zout(mbx_dma, MSL(i));
zout(zatm_dev->mbx_end[i], MBA(i));
zout((unsigned long)mbx & 0xffff, MTA(i));
zout((unsigned long)mbx & 0xffff, MWA(i));
}
error = start_tx(dev);
if (error)
goto out;
error = start_rx(dev);
if (error)
goto out_tx;
error = dev->phy->start(dev);
if (error)
goto out_rx;
zout(0xffffffff,IMR); /* enable interrupts */
/* enable TX & RX */
zout(zin(GMR) | uPD98401_GMR_SE | uPD98401_GMR_RE,GMR);
done:
return error;
out_rx:
kfree(zatm_dev->rx_map);
out_tx:
kfree(zatm_dev->tx_map);
out:
while (i-- > 0) {
pci_free_consistent(pdev, 2*MBX_SIZE(i),
(void *)zatm_dev->mbx_start[i],
zatm_dev->mbx_dma[i]);
}
free_irq(zatm_dev->irq, dev);
goto done;
}
static void zatm_close(struct atm_vcc *vcc)
{
DPRINTK(">zatm_close\n");
if (!ZATM_VCC(vcc)) return;
clear_bit(ATM_VF_READY,&vcc->flags);
close_rx(vcc);
EVENT("close_tx\n",0,0);
close_tx(vcc);
DPRINTK("zatm_close: done waiting\n");
/* deallocate memory */
kfree(ZATM_VCC(vcc));
vcc->dev_data = NULL;
clear_bit(ATM_VF_ADDR,&vcc->flags);
}
static int zatm_open(struct atm_vcc *vcc)
{
struct zatm_dev *zatm_dev;
struct zatm_vcc *zatm_vcc;
short vpi = vcc->vpi;
int vci = vcc->vci;
int error;
DPRINTK(">zatm_open\n");
zatm_dev = ZATM_DEV(vcc->dev);
if (!test_bit(ATM_VF_PARTIAL,&vcc->flags))
vcc->dev_data = NULL;
if (vci != ATM_VPI_UNSPEC && vpi != ATM_VCI_UNSPEC)
set_bit(ATM_VF_ADDR,&vcc->flags);
if (vcc->qos.aal != ATM_AAL5) return -EINVAL; /* @@@ AAL0 */
DPRINTK(DEV_LABEL "(itf %d): open %d.%d\n",vcc->dev->number,vcc->vpi,
vcc->vci);
if (!test_bit(ATM_VF_PARTIAL,&vcc->flags)) {
zatm_vcc = kmalloc(sizeof(struct zatm_vcc),GFP_KERNEL);
if (!zatm_vcc) {
clear_bit(ATM_VF_ADDR,&vcc->flags);
return -ENOMEM;
}
vcc->dev_data = zatm_vcc;
ZATM_VCC(vcc)->tx_chan = 0; /* for zatm_close after open_rx */
if ((error = open_rx_first(vcc))) {
zatm_close(vcc);
return error;
}
if ((error = open_tx_first(vcc))) {
zatm_close(vcc);
return error;
}
}
if (vci == ATM_VPI_UNSPEC || vpi == ATM_VCI_UNSPEC) return 0;
if ((error = open_rx_second(vcc))) {
zatm_close(vcc);
return error;
}
if ((error = open_tx_second(vcc))) {
zatm_close(vcc);
return error;
}
set_bit(ATM_VF_READY,&vcc->flags);
return 0;
}
static int zatm_change_qos(struct atm_vcc *vcc,struct atm_qos *qos,int flags)
{
printk("Not yet implemented\n");
return -ENOSYS;
/* @@@ */
}
static int zatm_ioctl(struct atm_dev *dev,unsigned int cmd,void __user *arg)
{
struct zatm_dev *zatm_dev;
unsigned long flags;
zatm_dev = ZATM_DEV(dev);
switch (cmd) {
case ZATM_GETPOOLZ:
if (!capable(CAP_NET_ADMIN)) return -EPERM;
/* fall through */
case ZATM_GETPOOL:
{
struct zatm_pool_info info;
int pool;
if (get_user(pool,
&((struct zatm_pool_req __user *) arg)->pool_num))
return -EFAULT;
if (pool < 0 || pool > ZATM_LAST_POOL)
return -EINVAL;
spin_lock_irqsave(&zatm_dev->lock, flags);
info = zatm_dev->pool_info[pool];
if (cmd == ZATM_GETPOOLZ) {
zatm_dev->pool_info[pool].rqa_count = 0;
zatm_dev->pool_info[pool].rqu_count = 0;
}
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return copy_to_user(
&((struct zatm_pool_req __user *) arg)->info,
&info,sizeof(info)) ? -EFAULT : 0;
}
case ZATM_SETPOOL:
{
struct zatm_pool_info info;
int pool;
if (!capable(CAP_NET_ADMIN)) return -EPERM;
if (get_user(pool,
&((struct zatm_pool_req __user *) arg)->pool_num))
return -EFAULT;
if (pool < 0 || pool > ZATM_LAST_POOL)
return -EINVAL;
if (copy_from_user(&info,
&((struct zatm_pool_req __user *) arg)->info,
sizeof(info))) return -EFAULT;
if (!info.low_water)
info.low_water = zatm_dev->
pool_info[pool].low_water;
if (!info.high_water)
info.high_water = zatm_dev->
pool_info[pool].high_water;
if (!info.next_thres)
info.next_thres = zatm_dev->
pool_info[pool].next_thres;
if (info.low_water >= info.high_water ||
info.low_water < 0)
return -EINVAL;
spin_lock_irqsave(&zatm_dev->lock, flags);
zatm_dev->pool_info[pool].low_water =
info.low_water;
zatm_dev->pool_info[pool].high_water =
info.high_water;
zatm_dev->pool_info[pool].next_thres =
info.next_thres;
spin_unlock_irqrestore(&zatm_dev->lock, flags);
return 0;
}
default:
if (!dev->phy->ioctl) return -ENOIOCTLCMD;
return dev->phy->ioctl(dev,cmd,arg);
}
}
static int zatm_getsockopt(struct atm_vcc *vcc,int level,int optname,
void __user *optval,int optlen)
{
return -EINVAL;
}
static int zatm_setsockopt(struct atm_vcc *vcc,int level,int optname,
void __user *optval,unsigned int optlen)
{
return -EINVAL;
}
static int zatm_send(struct atm_vcc *vcc,struct sk_buff *skb)
{
int error;
EVENT(">zatm_send 0x%lx\n",(unsigned long) skb,0);
if (!ZATM_VCC(vcc)->tx_chan || !test_bit(ATM_VF_READY,&vcc->flags)) {
if (vcc->pop) vcc->pop(vcc,skb);
else dev_kfree_skb(skb);
return -EINVAL;
}
if (!skb) {
printk(KERN_CRIT "!skb in zatm_send ?\n");
if (vcc->pop) vcc->pop(vcc,skb);
return -EINVAL;
}
ATM_SKB(skb)->vcc = vcc;
error = do_tx(skb);
if (error != RING_BUSY) return error;
skb_queue_tail(&ZATM_VCC(vcc)->backlog,skb);
return 0;
}
static void zatm_phy_put(struct atm_dev *dev,unsigned char value,
unsigned long addr)
{
struct zatm_dev *zatm_dev;
zatm_dev = ZATM_DEV(dev);
zwait;
zout(value,CER);
zout(uPD98401_IND_ACC | uPD98401_IA_B0 |
(uPD98401_IA_TGT_PHY << uPD98401_IA_TGT_SHIFT) | addr,CMR);
}
static unsigned char zatm_phy_get(struct atm_dev *dev,unsigned long addr)
{
struct zatm_dev *zatm_dev;
zatm_dev = ZATM_DEV(dev);
zwait;
zout(uPD98401_IND_ACC | uPD98401_IA_B0 | uPD98401_IA_RW |
(uPD98401_IA_TGT_PHY << uPD98401_IA_TGT_SHIFT) | addr,CMR);
zwait;
return zin(CER) & 0xff;
}
static const struct atmdev_ops ops = {
.open = zatm_open,
.close = zatm_close,
.ioctl = zatm_ioctl,
.getsockopt = zatm_getsockopt,
.setsockopt = zatm_setsockopt,
.send = zatm_send,
.phy_put = zatm_phy_put,
.phy_get = zatm_phy_get,
.change_qos = zatm_change_qos,
};
static int zatm_init_one(struct pci_dev *pci_dev,
const struct pci_device_id *ent)
{
struct atm_dev *dev;
struct zatm_dev *zatm_dev;
int ret = -ENOMEM;
zatm_dev = kmalloc(sizeof(*zatm_dev), GFP_KERNEL);
if (!zatm_dev) {
printk(KERN_EMERG "%s: memory shortage\n", DEV_LABEL);
goto out;
}
dev = atm_dev_register(DEV_LABEL, &pci_dev->dev, &ops, -1, NULL);
if (!dev)
goto out_free;
ret = pci_enable_device(pci_dev);
if (ret < 0)
goto out_deregister;
ret = pci_request_regions(pci_dev, DEV_LABEL);
if (ret < 0)
goto out_disable;
zatm_dev->pci_dev = pci_dev;
dev->dev_data = zatm_dev;
zatm_dev->copper = (int)ent->driver_data;
if ((ret = zatm_init(dev)) || (ret = zatm_start(dev)))
goto out_release;
pci_set_drvdata(pci_dev, dev);
zatm_dev->more = zatm_boards;
zatm_boards = dev;
ret = 0;
out:
return ret;
out_release:
pci_release_regions(pci_dev);
out_disable:
pci_disable_device(pci_dev);
out_deregister:
atm_dev_deregister(dev);
out_free:
kfree(zatm_dev);
goto out;
}
MODULE_LICENSE("GPL");
static struct pci_device_id zatm_pci_tbl[] = {
{ PCI_VDEVICE(ZEITNET, PCI_DEVICE_ID_ZEITNET_1221), ZATM_COPPER },
{ PCI_VDEVICE(ZEITNET, PCI_DEVICE_ID_ZEITNET_1225), 0 },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, zatm_pci_tbl);
static struct pci_driver zatm_driver = {
.name = DEV_LABEL,
.id_table = zatm_pci_tbl,
.probe = zatm_init_one,
};
static int __init zatm_init_module(void)
{
return pci_register_driver(&zatm_driver);
}
module_init(zatm_init_module);
/* module_exit not defined so not unloadable */
| gpl-2.0 |
KangBangKreations/KangBangKing | arch/x86/power/hibernate_32.c | 3551 | 4047 | /*
* Hibernation support specific for i386 - temporary page tables
*
* Distribute under GPLv2
*
* Copyright (c) 2006 Rafael J. Wysocki <rjw@sisk.pl>
*/
#include <linux/gfp.h>
#include <linux/suspend.h>
#include <linux/bootmem.h>
#include <asm/system.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/mmzone.h>
/* Defined in hibernate_asm_32.S */
extern int restore_image(void);
/* References to section boundaries */
extern const void __nosave_begin, __nosave_end;
/* Pointer to the temporary resume page tables */
pgd_t *resume_pg_dir;
/* The following three functions are based on the analogous code in
* arch/x86/mm/init_32.c
*/
/*
* Create a middle page table on a resume-safe page and put a pointer to it in
* the given global directory entry. This only returns the gd entry
* in non-PAE compilation mode, since the middle layer is folded.
*/
static pmd_t *resume_one_md_table_init(pgd_t *pgd)
{
pud_t *pud;
pmd_t *pmd_table;
#ifdef CONFIG_X86_PAE
pmd_table = (pmd_t *)get_safe_page(GFP_ATOMIC);
if (!pmd_table)
return NULL;
set_pgd(pgd, __pgd(__pa(pmd_table) | _PAGE_PRESENT));
pud = pud_offset(pgd, 0);
BUG_ON(pmd_table != pmd_offset(pud, 0));
#else
pud = pud_offset(pgd, 0);
pmd_table = pmd_offset(pud, 0);
#endif
return pmd_table;
}
/*
* Create a page table on a resume-safe page and place a pointer to it in
* a middle page directory entry.
*/
static pte_t *resume_one_page_table_init(pmd_t *pmd)
{
if (pmd_none(*pmd)) {
pte_t *page_table = (pte_t *)get_safe_page(GFP_ATOMIC);
if (!page_table)
return NULL;
set_pmd(pmd, __pmd(__pa(page_table) | _PAGE_TABLE));
BUG_ON(page_table != pte_offset_kernel(pmd, 0));
return page_table;
}
return pte_offset_kernel(pmd, 0);
}
/*
* This maps the physical memory to kernel virtual address space, a total
* of max_low_pfn pages, by creating page tables starting from address
* PAGE_OFFSET. The page tables are allocated out of resume-safe pages.
*/
static int resume_physical_mapping_init(pgd_t *pgd_base)
{
unsigned long pfn;
pgd_t *pgd;
pmd_t *pmd;
pte_t *pte;
int pgd_idx, pmd_idx;
pgd_idx = pgd_index(PAGE_OFFSET);
pgd = pgd_base + pgd_idx;
pfn = 0;
for (; pgd_idx < PTRS_PER_PGD; pgd++, pgd_idx++) {
pmd = resume_one_md_table_init(pgd);
if (!pmd)
return -ENOMEM;
if (pfn >= max_low_pfn)
continue;
for (pmd_idx = 0; pmd_idx < PTRS_PER_PMD; pmd++, pmd_idx++) {
if (pfn >= max_low_pfn)
break;
/* Map with big pages if possible, otherwise create
* normal page tables.
* NOTE: We can mark everything as executable here
*/
if (cpu_has_pse) {
set_pmd(pmd, pfn_pmd(pfn, PAGE_KERNEL_LARGE_EXEC));
pfn += PTRS_PER_PTE;
} else {
pte_t *max_pte;
pte = resume_one_page_table_init(pmd);
if (!pte)
return -ENOMEM;
max_pte = pte + PTRS_PER_PTE;
for (; pte < max_pte; pte++, pfn++) {
if (pfn >= max_low_pfn)
break;
set_pte(pte, pfn_pte(pfn, PAGE_KERNEL_EXEC));
}
}
}
}
resume_map_numa_kva(pgd_base);
return 0;
}
static inline void resume_init_first_level_page_table(pgd_t *pg_dir)
{
#ifdef CONFIG_X86_PAE
int i;
/* Init entries of the first-level page table to the zero page */
for (i = 0; i < PTRS_PER_PGD; i++)
set_pgd(pg_dir + i,
__pgd(__pa(empty_zero_page) | _PAGE_PRESENT));
#endif
}
int swsusp_arch_resume(void)
{
int error;
resume_pg_dir = (pgd_t *)get_safe_page(GFP_ATOMIC);
if (!resume_pg_dir)
return -ENOMEM;
resume_init_first_level_page_table(resume_pg_dir);
error = resume_physical_mapping_init(resume_pg_dir);
if (error)
return error;
/* We have got enough memory and from now on we cannot recover */
restore_image();
return 0;
}
/*
* pfn_is_nosave - check if given pfn is in the 'nosave' section
*/
int pfn_is_nosave(unsigned long pfn)
{
unsigned long nosave_begin_pfn = __pa_symbol(&__nosave_begin) >> PAGE_SHIFT;
unsigned long nosave_end_pfn = PAGE_ALIGN(__pa_symbol(&__nosave_end)) >> PAGE_SHIFT;
return (pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
}
| gpl-2.0 |
holyangel/M8-GPE_L | arch/arm/mach-omap2/board-3630sdp.c | 4831 | 5346 | /*
* Copyright (C) 2009 Texas Instruments Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <linux/mtd/nand.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include "common.h"
#include <plat/board.h>
#include <plat/gpmc-smc91x.h>
#include <plat/usb.h>
#include <mach/board-zoom.h>
#include "board-flash.h"
#include "mux.h"
#include "sdram-hynix-h8mbx00u0mer-0em.h"
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
static struct omap_smc91x_platform_data board_smc91x_data = {
.cs = 3,
.flags = GPMC_MUX_ADD_DATA | IORESOURCE_IRQ_LOWLEVEL,
};
static void __init board_smc91x_init(void)
{
board_smc91x_data.gpio_irq = 158;
gpmc_smc91x_init(&board_smc91x_data);
}
#else
static inline void board_smc91x_init(void)
{
}
#endif /* defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE) */
static void enable_board_wakeup_source(void)
{
/* T2 interrupt line (keypad) */
omap_mux_init_signal("sys_nirq",
OMAP_WAKEUP_EN | OMAP_PIN_INPUT_PULLUP);
}
static const struct usbhs_omap_board_data usbhs_bdata __initconst = {
.port_mode[0] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[1] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED,
.phy_reset = true,
.reset_gpio_port[0] = 126,
.reset_gpio_port[1] = 61,
.reset_gpio_port[2] = -EINVAL
};
static struct omap_board_config_kernel sdp_config[] __initdata = {
};
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#endif
/*
* SDP3630 CS organization
* See also the Switch S8 settings in the comments.
*/
static char chip_sel_sdp[][GPMC_CS_NUM] = {
{PDC_NOR, PDC_NAND, PDC_ONENAND, DBG_MPDB, 0, 0, 0, 0}, /* S8:1111 */
{PDC_ONENAND, PDC_NAND, PDC_NOR, DBG_MPDB, 0, 0, 0, 0}, /* S8:1110 */
{PDC_NAND, PDC_ONENAND, PDC_NOR, DBG_MPDB, 0, 0, 0, 0}, /* S8:1101 */
};
static struct mtd_partition sdp_nor_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
{
.name = "Bootloader-NOR",
.offset = 0,
.size = SZ_256K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
{
.name = "Params-NOR",
.offset = MTDPART_OFS_APPEND,
.size = SZ_256K,
.mask_flags = 0,
},
/* kernel */
{
.name = "Kernel-NOR",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0
},
/* file system */
{
.name = "Filesystem-NOR",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0
}
};
static struct mtd_partition sdp_onenand_partitions[] = {
{
.name = "X-Loader-OneNAND",
.offset = 0,
.size = 4 * (64 * 2048),
.mask_flags = MTD_WRITEABLE /* force read-only */
},
{
.name = "U-Boot-OneNAND",
.offset = MTDPART_OFS_APPEND,
.size = 2 * (64 * 2048),
.mask_flags = MTD_WRITEABLE /* force read-only */
},
{
.name = "U-Boot Environment-OneNAND",
.offset = MTDPART_OFS_APPEND,
.size = 1 * (64 * 2048),
},
{
.name = "Kernel-OneNAND",
.offset = MTDPART_OFS_APPEND,
.size = 16 * (64 * 2048),
},
{
.name = "File System-OneNAND",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct mtd_partition sdp_nand_partitions[] = {
/* All the partition sizes are listed in terms of NAND block size */
{
.name = "X-Loader-NAND",
.offset = 0,
.size = 4 * (64 * 2048),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
{
.name = "U-Boot-NAND",
.offset = MTDPART_OFS_APPEND, /* Offset = 0x80000 */
.size = 10 * (64 * 2048),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
{
.name = "Boot Env-NAND",
.offset = MTDPART_OFS_APPEND, /* Offset = 0x1c0000 */
.size = 6 * (64 * 2048),
},
{
.name = "Kernel-NAND",
.offset = MTDPART_OFS_APPEND, /* Offset = 0x280000 */
.size = 40 * (64 * 2048),
},
{
.name = "File System - NAND",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND, /* Offset = 0x780000 */
},
};
static struct flash_partitions sdp_flash_partitions[] = {
{
.parts = sdp_nor_partitions,
.nr_parts = ARRAY_SIZE(sdp_nor_partitions),
},
{
.parts = sdp_onenand_partitions,
.nr_parts = ARRAY_SIZE(sdp_onenand_partitions),
},
{
.parts = sdp_nand_partitions,
.nr_parts = ARRAY_SIZE(sdp_nand_partitions),
},
};
static void __init omap_sdp_init(void)
{
omap3_mux_init(board_mux, OMAP_PACKAGE_CBP);
omap_board_config = sdp_config;
omap_board_config_size = ARRAY_SIZE(sdp_config);
zoom_peripherals_init();
omap_sdrc_init(h8mbx00u0mer0em_sdrc_params,
h8mbx00u0mer0em_sdrc_params);
zoom_display_init();
board_smc91x_init();
board_flash_init(sdp_flash_partitions, chip_sel_sdp, NAND_BUSWIDTH_16);
enable_board_wakeup_source();
usbhs_init(&usbhs_bdata);
}
MACHINE_START(OMAP_3630SDP, "OMAP 3630SDP board")
.atag_offset = 0x100,
.reserve = omap_reserve,
.map_io = omap3_map_io,
.init_early = omap3630_init_early,
.init_irq = omap3_init_irq,
.handle_irq = omap3_intc_handle_irq,
.init_machine = omap_sdp_init,
.timer = &omap3_timer,
.restart = omap_prcm_restart,
MACHINE_END
| gpl-2.0 |
mdeejay/android_kernel_mako | drivers/net/ethernet/dlink/de600.c | 5087 | 13275 | static const char version[] = "de600.c: $Revision: 1.41-2.5 $, Bjorn Ekwall (bj0rn@blox.se)\n";
/*
* de600.c
*
* Linux driver for the D-Link DE-600 Ethernet pocket adapter.
*
* Portions (C) Copyright 1993, 1994 by Bjorn Ekwall
* The Author may be reached as bj0rn@blox.se
*
* Based on adapter information gathered from DE600.ASM by D-Link Inc.,
* as included on disk C in the v.2.11 of PC/TCP from FTP Software.
* For DE600.asm:
* Portions (C) Copyright 1990 D-Link, Inc.
* Copyright, 1988-1992, Russell Nelson, Crynwr Software
*
* Adapted to the sample network driver core for linux,
* written by: Donald Becker <becker@super.org>
* (Now at <becker@scyld.com>)
*
**************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************/
/* Add more time here if your adapter won't work OK: */
#define DE600_SLOW_DOWN udelay(delay_time)
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/string.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include "de600.h"
static bool check_lost = true;
module_param(check_lost, bool, 0);
MODULE_PARM_DESC(check_lost, "If set then check for unplugged de600");
static unsigned int delay_time = 10;
module_param(delay_time, int, 0);
MODULE_PARM_DESC(delay_time, "DE-600 deley on I/O in microseconds");
/*
* D-Link driver variables:
*/
static volatile int rx_page;
#define TX_PAGES 2
static volatile int tx_fifo[TX_PAGES];
static volatile int tx_fifo_in;
static volatile int tx_fifo_out;
static volatile int free_tx_pages = TX_PAGES;
static int was_down;
static DEFINE_SPINLOCK(de600_lock);
static inline u8 de600_read_status(struct net_device *dev)
{
u8 status;
outb_p(STATUS, DATA_PORT);
status = inb(STATUS_PORT);
outb_p(NULL_COMMAND | HI_NIBBLE, DATA_PORT);
return status;
}
static inline u8 de600_read_byte(unsigned char type, struct net_device *dev)
{
/* dev used by macros */
u8 lo;
outb_p((type), DATA_PORT);
lo = ((unsigned char)inb(STATUS_PORT)) >> 4;
outb_p((type) | HI_NIBBLE, DATA_PORT);
return ((unsigned char)inb(STATUS_PORT) & (unsigned char)0xf0) | lo;
}
/*
* Open/initialize the board. This is called (in the current kernel)
* after booting when 'ifconfig <dev->name> $IP_ADDR' is run (in rc.inet1).
*
* This routine should set everything up anew at each open, even
* registers that "should" only need to be set once at boot, so that
* there is a non-reboot way to recover if something goes wrong.
*/
static int de600_open(struct net_device *dev)
{
unsigned long flags;
int ret = request_irq(DE600_IRQ, de600_interrupt, 0, dev->name, dev);
if (ret) {
printk(KERN_ERR "%s: unable to get IRQ %d\n", dev->name, DE600_IRQ);
return ret;
}
spin_lock_irqsave(&de600_lock, flags);
ret = adapter_init(dev);
spin_unlock_irqrestore(&de600_lock, flags);
return ret;
}
/*
* The inverse routine to de600_open().
*/
static int de600_close(struct net_device *dev)
{
select_nic();
rx_page = 0;
de600_put_command(RESET);
de600_put_command(STOP_RESET);
de600_put_command(0);
select_prn();
free_irq(DE600_IRQ, dev);
return 0;
}
static inline void trigger_interrupt(struct net_device *dev)
{
de600_put_command(FLIP_IRQ);
select_prn();
DE600_SLOW_DOWN;
select_nic();
de600_put_command(0);
}
/*
* Copy a buffer to the adapter transmit page memory.
* Start sending.
*/
static int de600_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
unsigned long flags;
int transmit_from;
int len;
int tickssofar;
u8 *buffer = skb->data;
int i;
if (free_tx_pages <= 0) { /* Do timeouts, to avoid hangs. */
tickssofar = jiffies - dev_trans_start(dev);
if (tickssofar < HZ/20)
return NETDEV_TX_BUSY;
/* else */
printk(KERN_WARNING "%s: transmit timed out (%d), %s?\n", dev->name, tickssofar, "network cable problem");
/* Restart the adapter. */
spin_lock_irqsave(&de600_lock, flags);
if (adapter_init(dev)) {
spin_unlock_irqrestore(&de600_lock, flags);
return NETDEV_TX_BUSY;
}
spin_unlock_irqrestore(&de600_lock, flags);
}
/* Start real output */
pr_debug("de600_start_xmit:len=%d, page %d/%d\n", skb->len, tx_fifo_in, free_tx_pages);
if ((len = skb->len) < RUNT)
len = RUNT;
spin_lock_irqsave(&de600_lock, flags);
select_nic();
tx_fifo[tx_fifo_in] = transmit_from = tx_page_adr(tx_fifo_in) - len;
tx_fifo_in = (tx_fifo_in + 1) % TX_PAGES; /* Next free tx page */
if(check_lost)
{
/* This costs about 40 instructions per packet... */
de600_setup_address(NODE_ADDRESS, RW_ADDR);
de600_read_byte(READ_DATA, dev);
if (was_down || (de600_read_byte(READ_DATA, dev) != 0xde)) {
if (adapter_init(dev)) {
spin_unlock_irqrestore(&de600_lock, flags);
return NETDEV_TX_BUSY;
}
}
}
de600_setup_address(transmit_from, RW_ADDR);
for (i = 0; i < skb->len ; ++i, ++buffer)
de600_put_byte(*buffer);
for (; i < len; ++i)
de600_put_byte(0);
if (free_tx_pages-- == TX_PAGES) { /* No transmission going on */
dev->trans_start = jiffies;
netif_start_queue(dev); /* allow more packets into adapter */
/* Send page and generate a faked interrupt */
de600_setup_address(transmit_from, TX_ADDR);
de600_put_command(TX_ENABLE);
}
else {
if (free_tx_pages)
netif_start_queue(dev);
else
netif_stop_queue(dev);
select_prn();
}
spin_unlock_irqrestore(&de600_lock, flags);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/*
* The typical workload of the driver:
* Handle the network interface interrupts.
*/
static irqreturn_t de600_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
u8 irq_status;
int retrig = 0;
int boguscount = 0;
spin_lock(&de600_lock);
select_nic();
irq_status = de600_read_status(dev);
do {
pr_debug("de600_interrupt (%02X)\n", irq_status);
if (irq_status & RX_GOOD)
de600_rx_intr(dev);
else if (!(irq_status & RX_BUSY))
de600_put_command(RX_ENABLE);
/* Any transmission in progress? */
if (free_tx_pages < TX_PAGES)
retrig = de600_tx_intr(dev, irq_status);
else
retrig = 0;
irq_status = de600_read_status(dev);
} while ( (irq_status & RX_GOOD) || ((++boguscount < 100) && retrig) );
/*
* Yeah, it _looks_ like busy waiting, smells like busy waiting
* and I know it's not PC, but please, it will only occur once
* in a while and then only for a loop or so (< 1ms for sure!)
*/
/* Enable adapter interrupts */
select_prn();
if (retrig)
trigger_interrupt(dev);
spin_unlock(&de600_lock);
return IRQ_HANDLED;
}
static int de600_tx_intr(struct net_device *dev, int irq_status)
{
/*
* Returns 1 if tx still not done
*/
/* Check if current transmission is done yet */
if (irq_status & TX_BUSY)
return 1; /* tx not done, try again */
/* else */
/* If last transmission OK then bump fifo index */
if (!(irq_status & TX_FAILED16)) {
tx_fifo_out = (tx_fifo_out + 1) % TX_PAGES;
++free_tx_pages;
dev->stats.tx_packets++;
netif_wake_queue(dev);
}
/* More to send, or resend last packet? */
if ((free_tx_pages < TX_PAGES) || (irq_status & TX_FAILED16)) {
dev->trans_start = jiffies;
de600_setup_address(tx_fifo[tx_fifo_out], TX_ADDR);
de600_put_command(TX_ENABLE);
return 1;
}
/* else */
return 0;
}
/*
* We have a good packet, get it out of the adapter.
*/
static void de600_rx_intr(struct net_device *dev)
{
struct sk_buff *skb;
int i;
int read_from;
int size;
unsigned char *buffer;
/* Get size of received packet */
size = de600_read_byte(RX_LEN, dev); /* low byte */
size += (de600_read_byte(RX_LEN, dev) << 8); /* high byte */
size -= 4; /* Ignore trailing 4 CRC-bytes */
/* Tell adapter where to store next incoming packet, enable receiver */
read_from = rx_page_adr();
next_rx_page();
de600_put_command(RX_ENABLE);
if ((size < 32) || (size > 1535)) {
printk(KERN_WARNING "%s: Bogus packet size %d.\n", dev->name, size);
if (size > 10000)
adapter_init(dev);
return;
}
skb = netdev_alloc_skb(dev, size + 2);
if (skb == NULL) {
printk("%s: Couldn't allocate a sk_buff of size %d.\n", dev->name, size);
return;
}
/* else */
skb_reserve(skb,2); /* Align */
/* 'skb->data' points to the start of sk_buff data area. */
buffer = skb_put(skb,size);
/* copy the packet into the buffer */
de600_setup_address(read_from, RW_ADDR);
for (i = size; i > 0; --i, ++buffer)
*buffer = de600_read_byte(READ_DATA, dev);
skb->protocol=eth_type_trans(skb,dev);
netif_rx(skb);
/* update stats */
dev->stats.rx_packets++; /* count all receives */
dev->stats.rx_bytes += size; /* count all received bytes */
/*
* If any worth-while packets have been received, netif_rx()
* will work on them when we get to the tasklets.
*/
}
static const struct net_device_ops de600_netdev_ops = {
.ndo_open = de600_open,
.ndo_stop = de600_close,
.ndo_start_xmit = de600_start_xmit,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static struct net_device * __init de600_probe(void)
{
int i;
struct net_device *dev;
int err;
dev = alloc_etherdev(0);
if (!dev)
return ERR_PTR(-ENOMEM);
if (!request_region(DE600_IO, 3, "de600")) {
printk(KERN_WARNING "DE600: port 0x%x busy\n", DE600_IO);
err = -EBUSY;
goto out;
}
printk(KERN_INFO "%s: D-Link DE-600 pocket adapter", dev->name);
/* Alpha testers must have the version number to report bugs. */
pr_debug("%s", version);
/* probe for adapter */
err = -ENODEV;
rx_page = 0;
select_nic();
(void)de600_read_status(dev);
de600_put_command(RESET);
de600_put_command(STOP_RESET);
if (de600_read_status(dev) & 0xf0) {
printk(": not at I/O %#3x.\n", DATA_PORT);
goto out1;
}
/*
* Maybe we found one,
* have to check if it is a D-Link DE-600 adapter...
*/
/* Get the adapter ethernet address from the ROM */
de600_setup_address(NODE_ADDRESS, RW_ADDR);
for (i = 0; i < ETH_ALEN; i++) {
dev->dev_addr[i] = de600_read_byte(READ_DATA, dev);
dev->broadcast[i] = 0xff;
}
/* Check magic code */
if ((dev->dev_addr[1] == 0xde) && (dev->dev_addr[2] == 0x15)) {
/* OK, install real address */
dev->dev_addr[0] = 0x00;
dev->dev_addr[1] = 0x80;
dev->dev_addr[2] = 0xc8;
dev->dev_addr[3] &= 0x0f;
dev->dev_addr[3] |= 0x70;
} else {
printk(" not identified in the printer port\n");
goto out1;
}
printk(", Ethernet Address: %pM\n", dev->dev_addr);
dev->netdev_ops = &de600_netdev_ops;
dev->flags&=~IFF_MULTICAST;
select_prn();
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
release_region(DE600_IO, 3);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static int adapter_init(struct net_device *dev)
{
int i;
select_nic();
rx_page = 0; /* used by RESET */
de600_put_command(RESET);
de600_put_command(STOP_RESET);
/* Check if it is still there... */
/* Get the some bytes of the adapter ethernet address from the ROM */
de600_setup_address(NODE_ADDRESS, RW_ADDR);
de600_read_byte(READ_DATA, dev);
if ((de600_read_byte(READ_DATA, dev) != 0xde) ||
(de600_read_byte(READ_DATA, dev) != 0x15)) {
/* was: if (de600_read_status(dev) & 0xf0) { */
printk("Something has happened to the DE-600! Please check it and do a new ifconfig!\n");
/* Goodbye, cruel world... */
dev->flags &= ~IFF_UP;
de600_close(dev);
was_down = 1;
netif_stop_queue(dev); /* Transmit busy... */
return 1; /* failed */
}
if (was_down) {
printk(KERN_INFO "%s: Thanks, I feel much better now!\n", dev->name);
was_down = 0;
}
tx_fifo_in = 0;
tx_fifo_out = 0;
free_tx_pages = TX_PAGES;
/* set the ether address. */
de600_setup_address(NODE_ADDRESS, RW_ADDR);
for (i = 0; i < ETH_ALEN; i++)
de600_put_byte(dev->dev_addr[i]);
/* where to start saving incoming packets */
rx_page = RX_BP | RX_BASE_PAGE;
de600_setup_address(MEM_4K, RW_ADDR);
/* Enable receiver */
de600_put_command(RX_ENABLE);
select_prn();
netif_start_queue(dev);
return 0; /* OK */
}
static struct net_device *de600_dev;
static int __init de600_init(void)
{
de600_dev = de600_probe();
if (IS_ERR(de600_dev))
return PTR_ERR(de600_dev);
return 0;
}
static void __exit de600_exit(void)
{
unregister_netdev(de600_dev);
release_region(DE600_IO, 3);
free_netdev(de600_dev);
}
module_init(de600_init);
module_exit(de600_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
varunchitre15/thunderzap_canvas2_jb | crypto/algif_skcipher.c | 6367 | 13524 | /*
* algif_skcipher: User-space interface for skcipher algorithms
*
* This file provides the user-space API for symmetric key ciphers.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/scatterwalk.h>
#include <crypto/skcipher.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct skcipher_sg_list {
struct list_head list;
int cur;
struct scatterlist sg[0];
};
struct skcipher_ctx {
struct list_head tsgl;
struct af_alg_sgl rsgl;
void *iv;
struct af_alg_completion completion;
unsigned used;
unsigned int len;
bool more;
bool merge;
bool enc;
struct ablkcipher_request req;
};
#define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \
sizeof(struct scatterlist) - 1)
static inline int skcipher_sndbuf(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
ctx->used, 0);
}
static inline bool skcipher_writable(struct sock *sk)
{
return PAGE_SIZE <= skcipher_sndbuf(sk);
}
static int skcipher_alloc_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg = NULL;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
if (!list_empty(&ctx->tsgl))
sg = sgl->sg;
if (!sg || sgl->cur >= MAX_SGL_ENTS) {
sgl = sock_kmalloc(sk, sizeof(*sgl) +
sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1),
GFP_KERNEL);
if (!sgl)
return -ENOMEM;
sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
sgl->cur = 0;
if (sg)
scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
list_add_tail(&sgl->list, &ctx->tsgl);
}
return 0;
}
static void skcipher_pull_sgl(struct sock *sk, int used)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
int i;
while (!list_empty(&ctx->tsgl)) {
sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list,
list);
sg = sgl->sg;
for (i = 0; i < sgl->cur; i++) {
int plen = min_t(int, used, sg[i].length);
if (!sg_page(sg + i))
continue;
sg[i].length -= plen;
sg[i].offset += plen;
used -= plen;
ctx->used -= plen;
if (sg[i].length)
return;
put_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
}
list_del(&sgl->list);
sock_kfree_s(sk, sgl,
sizeof(*sgl) + sizeof(sgl->sg[0]) *
(MAX_SGL_ENTS + 1));
}
if (!ctx->used)
ctx->merge = 0;
}
static void skcipher_free_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
skcipher_pull_sgl(sk, ctx->used);
}
static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags)
{
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT)
return -EAGAIN;
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void skcipher_wmem_wakeup(struct sock *sk)
{
struct socket_wq *wq;
if (!skcipher_writable(sk))
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static int skcipher_wait_for_data(struct sock *sk, unsigned flags)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT) {
return -EAGAIN;
}
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, ctx->used)) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
return err;
}
static void skcipher_data_wakeup(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct socket_wq *wq;
if (!ctx->used)
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
rcu_read_unlock();
}
static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t size)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
unsigned ivsize = crypto_ablkcipher_ivsize(tfm);
struct skcipher_sg_list *sgl;
struct af_alg_control con = {};
long copied = 0;
bool enc = 0;
int err;
int i;
if (msg->msg_controllen) {
err = af_alg_cmsg_send(msg, &con);
if (err)
return err;
switch (con.op) {
case ALG_OP_ENCRYPT:
enc = 1;
break;
case ALG_OP_DECRYPT:
enc = 0;
break;
default:
return -EINVAL;
}
if (con.iv && con.iv->ivlen != ivsize)
return -EINVAL;
}
err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!ctx->used) {
ctx->enc = enc;
if (con.iv)
memcpy(ctx->iv, con.iv->iv, ivsize);
}
while (size) {
struct scatterlist *sg;
unsigned long len = size;
int plen;
if (ctx->merge) {
sgl = list_entry(ctx->tsgl.prev,
struct skcipher_sg_list, list);
sg = sgl->sg + sgl->cur - 1;
len = min_t(unsigned long, len,
PAGE_SIZE - sg->offset - sg->length);
err = memcpy_fromiovec(page_address(sg_page(sg)) +
sg->offset + sg->length,
msg->msg_iov, len);
if (err)
goto unlock;
sg->length += len;
ctx->merge = (sg->offset + sg->length) &
(PAGE_SIZE - 1);
ctx->used += len;
copied += len;
size -= len;
continue;
}
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, msg->msg_flags);
if (err)
goto unlock;
}
len = min_t(unsigned long, len, skcipher_sndbuf(sk));
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
sg = sgl->sg;
do {
i = sgl->cur;
plen = min_t(int, len, PAGE_SIZE);
sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
err = -ENOMEM;
if (!sg_page(sg + i))
goto unlock;
err = memcpy_fromiovec(page_address(sg_page(sg + i)),
msg->msg_iov, plen);
if (err) {
__free_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
goto unlock;
}
sg[i].length = plen;
len -= plen;
ctx->used += plen;
copied += plen;
size -= plen;
sgl->cur++;
} while (len && sgl->cur < MAX_SGL_ENTS);
ctx->merge = plen & (PAGE_SIZE - 1);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static ssize_t skcipher_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
int err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!size)
goto done;
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, flags);
if (err)
goto unlock;
}
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
ctx->merge = 0;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
get_page(page);
sg_set_page(sgl->sg + sgl->cur, page, size, offset);
sgl->cur++;
ctx->used += size;
done:
ctx->more = flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return err ?: size;
}
static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static unsigned int skcipher_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
if (ctx->used)
mask |= POLLIN | POLLRDNORM;
if (skcipher_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static struct proto_ops algif_skcipher_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.accept = sock_no_accept,
.setsockopt = sock_no_setsockopt,
.release = af_alg_release,
.sendmsg = skcipher_sendmsg,
.sendpage = skcipher_sendpage,
.recvmsg = skcipher_recvmsg,
.poll = skcipher_poll,
};
static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ablkcipher(name, type, mask);
}
static void skcipher_release(void *private)
{
crypto_free_ablkcipher(private);
}
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ablkcipher_setkey(private, key, keylen);
}
static void skcipher_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
skcipher_free_sgl(sk);
sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ablkcipher_request_set_tfm(&ctx->req, private);
ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_skcipher = {
.bind = skcipher_bind,
.release = skcipher_release,
.setkey = skcipher_setkey,
.accept = skcipher_accept_parent,
.ops = &algif_skcipher_ops,
.name = "skcipher",
.owner = THIS_MODULE
};
static int __init algif_skcipher_init(void)
{
return af_alg_register_type(&algif_type_skcipher);
}
static void __exit algif_skcipher_exit(void)
{
int err = af_alg_unregister_type(&algif_type_skcipher);
BUG_ON(err);
}
module_init(algif_skcipher_init);
module_exit(algif_skcipher_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
silver-alx/ac100_kernel | fs/hfs/btree.c | 480 | 8712 | /*
* linux/fs/hfs/btree.c
*
* Copyright (C) 2001
* Brad Boyer (flar@allandria.com)
* (C) 2003 Ardis Technologies <roman@ardistech.com>
*
* Handle opening/closing btree
*/
#include <linux/pagemap.h>
#include <linux/log2.h>
#include "btree.h"
/* Get a reference to a B*Tree and do some initial checks */
struct hfs_btree *hfs_btree_open(struct super_block *sb, u32 id, btree_keycmp keycmp)
{
struct hfs_btree *tree;
struct hfs_btree_header_rec *head;
struct address_space *mapping;
struct page *page;
unsigned int size;
tree = kzalloc(sizeof(*tree), GFP_KERNEL);
if (!tree)
return NULL;
init_MUTEX(&tree->tree_lock);
spin_lock_init(&tree->hash_lock);
/* Set the correct compare function */
tree->sb = sb;
tree->cnid = id;
tree->keycmp = keycmp;
tree->inode = iget_locked(sb, id);
if (!tree->inode)
goto free_tree;
BUG_ON(!(tree->inode->i_state & I_NEW));
{
struct hfs_mdb *mdb = HFS_SB(sb)->mdb;
HFS_I(tree->inode)->flags = 0;
mutex_init(&HFS_I(tree->inode)->extents_lock);
switch (id) {
case HFS_EXT_CNID:
hfs_inode_read_fork(tree->inode, mdb->drXTExtRec, mdb->drXTFlSize,
mdb->drXTFlSize, be32_to_cpu(mdb->drXTClpSiz));
tree->inode->i_mapping->a_ops = &hfs_btree_aops;
break;
case HFS_CAT_CNID:
hfs_inode_read_fork(tree->inode, mdb->drCTExtRec, mdb->drCTFlSize,
mdb->drCTFlSize, be32_to_cpu(mdb->drCTClpSiz));
tree->inode->i_mapping->a_ops = &hfs_btree_aops;
break;
default:
BUG();
}
}
unlock_new_inode(tree->inode);
if (!HFS_I(tree->inode)->first_blocks) {
printk(KERN_ERR "hfs: invalid btree extent records (0 size).\n");
goto free_inode;
}
mapping = tree->inode->i_mapping;
page = read_mapping_page(mapping, 0, NULL);
if (IS_ERR(page))
goto free_inode;
/* Load the header */
head = (struct hfs_btree_header_rec *)(kmap(page) + sizeof(struct hfs_bnode_desc));
tree->root = be32_to_cpu(head->root);
tree->leaf_count = be32_to_cpu(head->leaf_count);
tree->leaf_head = be32_to_cpu(head->leaf_head);
tree->leaf_tail = be32_to_cpu(head->leaf_tail);
tree->node_count = be32_to_cpu(head->node_count);
tree->free_nodes = be32_to_cpu(head->free_nodes);
tree->attributes = be32_to_cpu(head->attributes);
tree->node_size = be16_to_cpu(head->node_size);
tree->max_key_len = be16_to_cpu(head->max_key_len);
tree->depth = be16_to_cpu(head->depth);
size = tree->node_size;
if (!is_power_of_2(size))
goto fail_page;
if (!tree->node_count)
goto fail_page;
switch (id) {
case HFS_EXT_CNID:
if (tree->max_key_len != HFS_MAX_EXT_KEYLEN) {
printk(KERN_ERR "hfs: invalid extent max_key_len %d\n",
tree->max_key_len);
goto fail_page;
}
break;
case HFS_CAT_CNID:
if (tree->max_key_len != HFS_MAX_CAT_KEYLEN) {
printk(KERN_ERR "hfs: invalid catalog max_key_len %d\n",
tree->max_key_len);
goto fail_page;
}
break;
default:
BUG();
}
tree->node_size_shift = ffs(size) - 1;
tree->pages_per_bnode = (tree->node_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
kunmap(page);
page_cache_release(page);
return tree;
fail_page:
page_cache_release(page);
free_inode:
tree->inode->i_mapping->a_ops = &hfs_aops;
iput(tree->inode);
free_tree:
kfree(tree);
return NULL;
}
/* Release resources used by a btree */
void hfs_btree_close(struct hfs_btree *tree)
{
struct hfs_bnode *node;
int i;
if (!tree)
return;
for (i = 0; i < NODE_HASH_SIZE; i++) {
while ((node = tree->node_hash[i])) {
tree->node_hash[i] = node->next_hash;
if (atomic_read(&node->refcnt))
printk(KERN_ERR "hfs: node %d:%d still has %d user(s)!\n",
node->tree->cnid, node->this, atomic_read(&node->refcnt));
hfs_bnode_free(node);
tree->node_hash_cnt--;
}
}
iput(tree->inode);
kfree(tree);
}
void hfs_btree_write(struct hfs_btree *tree)
{
struct hfs_btree_header_rec *head;
struct hfs_bnode *node;
struct page *page;
node = hfs_bnode_find(tree, 0);
if (IS_ERR(node))
/* panic? */
return;
/* Load the header */
page = node->page[0];
head = (struct hfs_btree_header_rec *)(kmap(page) + sizeof(struct hfs_bnode_desc));
head->root = cpu_to_be32(tree->root);
head->leaf_count = cpu_to_be32(tree->leaf_count);
head->leaf_head = cpu_to_be32(tree->leaf_head);
head->leaf_tail = cpu_to_be32(tree->leaf_tail);
head->node_count = cpu_to_be32(tree->node_count);
head->free_nodes = cpu_to_be32(tree->free_nodes);
head->attributes = cpu_to_be32(tree->attributes);
head->depth = cpu_to_be16(tree->depth);
kunmap(page);
set_page_dirty(page);
hfs_bnode_put(node);
}
static struct hfs_bnode *hfs_bmap_new_bmap(struct hfs_bnode *prev, u32 idx)
{
struct hfs_btree *tree = prev->tree;
struct hfs_bnode *node;
struct hfs_bnode_desc desc;
__be32 cnid;
node = hfs_bnode_create(tree, idx);
if (IS_ERR(node))
return node;
if (!tree->free_nodes)
panic("FIXME!!!");
tree->free_nodes--;
prev->next = idx;
cnid = cpu_to_be32(idx);
hfs_bnode_write(prev, &cnid, offsetof(struct hfs_bnode_desc, next), 4);
node->type = HFS_NODE_MAP;
node->num_recs = 1;
hfs_bnode_clear(node, 0, tree->node_size);
desc.next = 0;
desc.prev = 0;
desc.type = HFS_NODE_MAP;
desc.height = 0;
desc.num_recs = cpu_to_be16(1);
desc.reserved = 0;
hfs_bnode_write(node, &desc, 0, sizeof(desc));
hfs_bnode_write_u16(node, 14, 0x8000);
hfs_bnode_write_u16(node, tree->node_size - 2, 14);
hfs_bnode_write_u16(node, tree->node_size - 4, tree->node_size - 6);
return node;
}
struct hfs_bnode *hfs_bmap_alloc(struct hfs_btree *tree)
{
struct hfs_bnode *node, *next_node;
struct page **pagep;
u32 nidx, idx;
unsigned off;
u16 off16;
u16 len;
u8 *data, byte, m;
int i;
while (!tree->free_nodes) {
struct inode *inode = tree->inode;
u32 count;
int res;
res = hfs_extend_file(inode);
if (res)
return ERR_PTR(res);
HFS_I(inode)->phys_size = inode->i_size =
(loff_t)HFS_I(inode)->alloc_blocks *
HFS_SB(tree->sb)->alloc_blksz;
HFS_I(inode)->fs_blocks = inode->i_size >>
tree->sb->s_blocksize_bits;
inode_set_bytes(inode, inode->i_size);
count = inode->i_size >> tree->node_size_shift;
tree->free_nodes = count - tree->node_count;
tree->node_count = count;
}
nidx = 0;
node = hfs_bnode_find(tree, nidx);
if (IS_ERR(node))
return node;
len = hfs_brec_lenoff(node, 2, &off16);
off = off16;
off += node->page_offset;
pagep = node->page + (off >> PAGE_CACHE_SHIFT);
data = kmap(*pagep);
off &= ~PAGE_CACHE_MASK;
idx = 0;
for (;;) {
while (len) {
byte = data[off];
if (byte != 0xff) {
for (m = 0x80, i = 0; i < 8; m >>= 1, i++) {
if (!(byte & m)) {
idx += i;
data[off] |= m;
set_page_dirty(*pagep);
kunmap(*pagep);
tree->free_nodes--;
mark_inode_dirty(tree->inode);
hfs_bnode_put(node);
return hfs_bnode_create(tree, idx);
}
}
}
if (++off >= PAGE_CACHE_SIZE) {
kunmap(*pagep);
data = kmap(*++pagep);
off = 0;
}
idx += 8;
len--;
}
kunmap(*pagep);
nidx = node->next;
if (!nidx) {
printk(KERN_DEBUG "hfs: create new bmap node...\n");
next_node = hfs_bmap_new_bmap(node, idx);
} else
next_node = hfs_bnode_find(tree, nidx);
hfs_bnode_put(node);
if (IS_ERR(next_node))
return next_node;
node = next_node;
len = hfs_brec_lenoff(node, 0, &off16);
off = off16;
off += node->page_offset;
pagep = node->page + (off >> PAGE_CACHE_SHIFT);
data = kmap(*pagep);
off &= ~PAGE_CACHE_MASK;
}
}
void hfs_bmap_free(struct hfs_bnode *node)
{
struct hfs_btree *tree;
struct page *page;
u16 off, len;
u32 nidx;
u8 *data, byte, m;
dprint(DBG_BNODE_MOD, "btree_free_node: %u\n", node->this);
tree = node->tree;
nidx = node->this;
node = hfs_bnode_find(tree, 0);
if (IS_ERR(node))
return;
len = hfs_brec_lenoff(node, 2, &off);
while (nidx >= len * 8) {
u32 i;
nidx -= len * 8;
i = node->next;
hfs_bnode_put(node);
if (!i) {
/* panic */;
printk(KERN_CRIT "hfs: unable to free bnode %u. bmap not found!\n", node->this);
return;
}
node = hfs_bnode_find(tree, i);
if (IS_ERR(node))
return;
if (node->type != HFS_NODE_MAP) {
/* panic */;
printk(KERN_CRIT "hfs: invalid bmap found! (%u,%d)\n", node->this, node->type);
hfs_bnode_put(node);
return;
}
len = hfs_brec_lenoff(node, 0, &off);
}
off += node->page_offset + nidx / 8;
page = node->page[off >> PAGE_CACHE_SHIFT];
data = kmap(page);
off &= ~PAGE_CACHE_MASK;
m = 1 << (~nidx & 7);
byte = data[off];
if (!(byte & m)) {
printk(KERN_CRIT "hfs: trying to free free bnode %u(%d)\n", node->this, node->type);
kunmap(page);
hfs_bnode_put(node);
return;
}
data[off] = byte & ~m;
set_page_dirty(page);
kunmap(page);
hfs_bnode_put(node);
tree->free_nodes++;
mark_inode_dirty(tree->inode);
}
| gpl-2.0 |
tgnice/kvm | sound/isa/wavefront/wavefront.c | 480 | 19037 | /*
* ALSA card-level driver for Turtle Beach Wavefront cards
* (Maui,Tropez,Tropez+)
*
* Copyright (c) 1997-1999 by Paul Barton-Davis <pbd@op.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/init.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/pnp.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/opl3.h>
#include <sound/wss.h>
#include <sound/snd_wavefront.h>
MODULE_AUTHOR("Paul Barton-Davis <pbd@op.net>");
MODULE_DESCRIPTION("Turtle Beach Wavefront");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Turtle Beach,Maui/Tropez/Tropez+}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
#ifdef CONFIG_PNP
static bool isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long cs4232_pcm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int cs4232_pcm_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,11,12,15 */
static long cs4232_mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int cs4232_mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 9,11,12,15 */
static long ics2115_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int ics2115_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 2,9,11,12,15 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
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 */
static bool use_cs4232_midi[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for WaveFront soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for WaveFront soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable WaveFront soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "ISA PnP detection for WaveFront soundcards.");
#endif
module_param_array(cs4232_pcm_port, long, NULL, 0444);
MODULE_PARM_DESC(cs4232_pcm_port, "Port # for CS4232 PCM interface.");
module_param_array(cs4232_pcm_irq, int, NULL, 0444);
MODULE_PARM_DESC(cs4232_pcm_irq, "IRQ # for CS4232 PCM interface.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA1 # for CS4232 PCM interface.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA2 # for CS4232 PCM interface.");
module_param_array(cs4232_mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(cs4232_mpu_port, "port # for CS4232 MPU-401 interface.");
module_param_array(cs4232_mpu_irq, int, NULL, 0444);
MODULE_PARM_DESC(cs4232_mpu_irq, "IRQ # for CS4232 MPU-401 interface.");
module_param_array(ics2115_irq, int, NULL, 0444);
MODULE_PARM_DESC(ics2115_irq, "IRQ # for ICS2115.");
module_param_array(ics2115_port, long, NULL, 0444);
MODULE_PARM_DESC(ics2115_port, "Port # for ICS2115.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port #.");
module_param_array(use_cs4232_midi, bool, NULL, 0444);
MODULE_PARM_DESC(use_cs4232_midi, "Use CS4232 MPU-401 interface (inaccessibly located inside your computer)");
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
static struct pnp_card_device_id snd_wavefront_pnpids[] = {
/* Tropez */
{ .id = "CSC7532", .devs = { { "CSC0000" }, { "CSC0010" }, { "PnPb006" }, { "CSC0004" } } },
/* Tropez+ */
{ .id = "CSC7632", .devs = { { "CSC0000" }, { "CSC0010" }, { "PnPb006" }, { "CSC0004" } } },
{ .id = "" }
};
MODULE_DEVICE_TABLE(pnp_card, snd_wavefront_pnpids);
static int
snd_wavefront_pnp (int dev, snd_wavefront_card_t *acard, struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
/* Check for each logical device. */
/* CS4232 chip (aka "windows sound system") is logical device 0 */
acard->wss = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->wss == NULL)
return -EBUSY;
/* there is a game port at logical device 1, but we ignore it completely */
/* the control interface is logical device 2, but we ignore it
completely. in fact, nobody even seems to know what it
does.
*/
/* Only configure the CS4232 MIDI interface if its been
specifically requested. It is logical device 3.
*/
if (use_cs4232_midi[dev]) {
acard->mpu = pnp_request_card_device(card, id->devs[2].id, NULL);
if (acard->mpu == NULL)
return -EBUSY;
}
/* The ICS2115 synth is logical device 4 */
acard->synth = pnp_request_card_device(card, id->devs[3].id, NULL);
if (acard->synth == NULL)
return -EBUSY;
/* PCM/FM initialization */
pdev = acard->wss;
/* An interesting note from the Tropez+ FAQ:
Q. [Ports] Why is the base address of the WSS I/O ports off by 4?
A. WSS I/O requires a block of 8 I/O addresses ("ports"). Of these, the first
4 are used to identify and configure the board. With the advent of PnP,
these first 4 addresses have become obsolete, and software applications
only use the last 4 addresses to control the codec chip. Therefore, the
base address setting "skips past" the 4 unused addresses.
*/
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR "PnP WSS pnp configure failure\n");
return err;
}
cs4232_pcm_port[dev] = pnp_port_start(pdev, 0);
fm_port[dev] = pnp_port_start(pdev, 1);
dma1[dev] = pnp_dma(pdev, 0);
dma2[dev] = pnp_dma(pdev, 1);
cs4232_pcm_irq[dev] = pnp_irq(pdev, 0);
/* Synth initialization */
pdev = acard->synth;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR "PnP ICS2115 pnp configure failure\n");
return err;
}
ics2115_port[dev] = pnp_port_start(pdev, 0);
ics2115_irq[dev] = pnp_irq(pdev, 0);
/* CS4232 MPU initialization. Configure this only if
explicitly requested, since its physically inaccessible and
consumes another IRQ.
*/
if (use_cs4232_midi[dev]) {
pdev = acard->mpu;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR "PnP MPU401 pnp configure failure\n");
cs4232_mpu_port[dev] = SNDRV_AUTO_PORT;
} else {
cs4232_mpu_port[dev] = pnp_port_start(pdev, 0);
cs4232_mpu_irq[dev] = pnp_irq(pdev, 0);
}
snd_printk (KERN_INFO "CS4232 MPU: port=0x%lx, irq=%i\n",
cs4232_mpu_port[dev],
cs4232_mpu_irq[dev]);
}
snd_printdd ("CS4232: pcm port=0x%lx, fm port=0x%lx, dma1=%i, dma2=%i, irq=%i\nICS2115: port=0x%lx, irq=%i\n",
cs4232_pcm_port[dev],
fm_port[dev],
dma1[dev],
dma2[dev],
cs4232_pcm_irq[dev],
ics2115_port[dev],
ics2115_irq[dev]);
return 0;
}
#endif /* CONFIG_PNP */
static irqreturn_t snd_wavefront_ics2115_interrupt(int irq, void *dev_id)
{
snd_wavefront_card_t *acard;
acard = (snd_wavefront_card_t *) dev_id;
if (acard == NULL)
return IRQ_NONE;
if (acard->wavefront.interrupts_are_midi) {
snd_wavefront_midi_interrupt (acard);
} else {
snd_wavefront_internal_interrupt (acard);
}
return IRQ_HANDLED;
}
static struct snd_hwdep *snd_wavefront_new_synth(struct snd_card *card,
int hw_dev,
snd_wavefront_card_t *acard)
{
struct snd_hwdep *wavefront_synth;
if (snd_wavefront_detect (acard) < 0) {
return NULL;
}
if (snd_wavefront_start (&acard->wavefront) < 0) {
return NULL;
}
if (snd_hwdep_new(card, "WaveFront", hw_dev, &wavefront_synth) < 0)
return NULL;
strcpy (wavefront_synth->name,
"WaveFront (ICS2115) wavetable synthesizer");
wavefront_synth->ops.open = snd_wavefront_synth_open;
wavefront_synth->ops.release = snd_wavefront_synth_release;
wavefront_synth->ops.ioctl = snd_wavefront_synth_ioctl;
return wavefront_synth;
}
static struct snd_hwdep *snd_wavefront_new_fx(struct snd_card *card,
int hw_dev,
snd_wavefront_card_t *acard,
unsigned long port)
{
struct snd_hwdep *fx_processor;
if (snd_wavefront_fx_start (&acard->wavefront)) {
snd_printk (KERN_ERR "cannot initialize YSS225 FX processor");
return NULL;
}
if (snd_hwdep_new (card, "YSS225", hw_dev, &fx_processor) < 0)
return NULL;
sprintf (fx_processor->name, "YSS225 FX Processor at 0x%lx", port);
fx_processor->ops.open = snd_wavefront_fx_open;
fx_processor->ops.release = snd_wavefront_fx_release;
fx_processor->ops.ioctl = snd_wavefront_fx_ioctl;
return fx_processor;
}
static snd_wavefront_mpu_id internal_id = internal_mpu;
static snd_wavefront_mpu_id external_id = external_mpu;
static struct snd_rawmidi *snd_wavefront_new_midi(struct snd_card *card,
int midi_dev,
snd_wavefront_card_t *acard,
unsigned long port,
snd_wavefront_mpu_id mpu)
{
struct snd_rawmidi *rmidi;
static int first = 1;
if (first) {
first = 0;
acard->wavefront.midi.base = port;
if (snd_wavefront_midi_start (acard)) {
snd_printk (KERN_ERR "cannot initialize MIDI interface\n");
return NULL;
}
}
if (snd_rawmidi_new (card, "WaveFront MIDI", midi_dev, 1, 1, &rmidi) < 0)
return NULL;
if (mpu == internal_mpu) {
strcpy(rmidi->name, "WaveFront MIDI (Internal)");
rmidi->private_data = &internal_id;
} else {
strcpy(rmidi->name, "WaveFront MIDI (External)");
rmidi->private_data = &external_id;
}
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_wavefront_midi_output);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_wavefront_midi_input);
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT |
SNDRV_RAWMIDI_INFO_INPUT |
SNDRV_RAWMIDI_INFO_DUPLEX;
return rmidi;
}
static void
snd_wavefront_free(struct snd_card *card)
{
snd_wavefront_card_t *acard = (snd_wavefront_card_t *)card->private_data;
if (acard) {
release_and_free_resource(acard->wavefront.res_base);
if (acard->wavefront.irq > 0)
free_irq(acard->wavefront.irq, (void *)acard);
}
}
static int snd_wavefront_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
snd_wavefront_card_t *acard;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(snd_wavefront_card_t), &card);
if (err < 0)
return err;
acard = card->private_data;
acard->wavefront.irq = -1;
spin_lock_init(&acard->wavefront.irq_lock);
init_waitqueue_head(&acard->wavefront.interrupt_sleeper);
spin_lock_init(&acard->wavefront.midi.open);
spin_lock_init(&acard->wavefront.midi.virtual);
acard->wavefront.card = card;
card->private_free = snd_wavefront_free;
*cardp = card;
return 0;
}
static int
snd_wavefront_probe (struct snd_card *card, int dev)
{
snd_wavefront_card_t *acard = card->private_data;
struct snd_wss *chip;
struct snd_hwdep *wavefront_synth;
struct snd_rawmidi *ics2115_internal_rmidi = NULL;
struct snd_rawmidi *ics2115_external_rmidi = NULL;
struct snd_hwdep *fx_processor;
int hw_dev = 0, midi_dev = 0, err;
/* --------- PCM --------------- */
err = snd_wss_create(card, cs4232_pcm_port[dev], -1,
cs4232_pcm_irq[dev], dma1[dev], dma2[dev],
WSS_HW_DETECT, 0, &chip);
if (err < 0) {
snd_printk(KERN_ERR "can't allocate WSS device\n");
return err;
}
err = snd_wss_pcm(chip, 0, NULL);
if (err < 0)
return err;
err = snd_wss_timer(chip, 0, NULL);
if (err < 0)
return err;
/* ---------- OPL3 synth --------- */
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
struct snd_opl3 *opl3;
err = snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2,
OPL3_HW_OPL3_CS, 0, &opl3);
if (err < 0) {
snd_printk (KERN_ERR "can't allocate or detect OPL3 synth\n");
return err;
}
err = snd_opl3_hwdep_new(opl3, hw_dev, 1, NULL);
if (err < 0)
return err;
hw_dev++;
}
/* ------- ICS2115 Wavetable synth ------- */
acard->wavefront.res_base = request_region(ics2115_port[dev], 16,
"ICS2115");
if (acard->wavefront.res_base == NULL) {
snd_printk(KERN_ERR "unable to grab ICS2115 i/o region 0x%lx-0x%lx\n",
ics2115_port[dev], ics2115_port[dev] + 16 - 1);
return -EBUSY;
}
if (request_irq(ics2115_irq[dev], snd_wavefront_ics2115_interrupt,
0, "ICS2115", acard)) {
snd_printk(KERN_ERR "unable to use ICS2115 IRQ %d\n", ics2115_irq[dev]);
return -EBUSY;
}
acard->wavefront.irq = ics2115_irq[dev];
acard->wavefront.base = ics2115_port[dev];
wavefront_synth = snd_wavefront_new_synth(card, hw_dev, acard);
if (wavefront_synth == NULL) {
snd_printk (KERN_ERR "can't create WaveFront synth device\n");
return -ENOMEM;
}
strcpy (wavefront_synth->name, "ICS2115 Wavetable MIDI Synthesizer");
wavefront_synth->iface = SNDRV_HWDEP_IFACE_ICS2115;
hw_dev++;
/* --------- Mixer ------------ */
err = snd_wss_mixer(chip);
if (err < 0) {
snd_printk (KERN_ERR "can't allocate mixer device\n");
return err;
}
/* -------- CS4232 MPU-401 interface -------- */
if (cs4232_mpu_port[dev] > 0 && cs4232_mpu_port[dev] != SNDRV_AUTO_PORT) {
err = snd_mpu401_uart_new(card, midi_dev, MPU401_HW_CS4232,
cs4232_mpu_port[dev], 0,
cs4232_mpu_irq[dev], NULL);
if (err < 0) {
snd_printk (KERN_ERR "can't allocate CS4232 MPU-401 device\n");
return err;
}
midi_dev++;
}
/* ------ ICS2115 internal MIDI ------------ */
if (ics2115_port[dev] > 0 && ics2115_port[dev] != SNDRV_AUTO_PORT) {
ics2115_internal_rmidi =
snd_wavefront_new_midi (card,
midi_dev,
acard,
ics2115_port[dev],
internal_mpu);
if (ics2115_internal_rmidi == NULL) {
snd_printk (KERN_ERR "can't setup ICS2115 internal MIDI device\n");
return -ENOMEM;
}
midi_dev++;
}
/* ------ ICS2115 external MIDI ------------ */
if (ics2115_port[dev] > 0 && ics2115_port[dev] != SNDRV_AUTO_PORT) {
ics2115_external_rmidi =
snd_wavefront_new_midi (card,
midi_dev,
acard,
ics2115_port[dev],
external_mpu);
if (ics2115_external_rmidi == NULL) {
snd_printk (KERN_ERR "can't setup ICS2115 external MIDI device\n");
return -ENOMEM;
}
midi_dev++;
}
/* FX processor for Tropez+ */
if (acard->wavefront.has_fx) {
fx_processor = snd_wavefront_new_fx (card,
hw_dev,
acard,
ics2115_port[dev]);
if (fx_processor == NULL) {
snd_printk (KERN_ERR "can't setup FX device\n");
return -ENOMEM;
}
hw_dev++;
strcpy(card->driver, "Tropez+");
strcpy(card->shortname, "Turtle Beach Tropez+");
} else {
/* Need a way to distinguish between Maui and Tropez */
strcpy(card->driver, "WaveFront");
strcpy(card->shortname, "Turtle Beach WaveFront");
}
/* ----- Register the card --------- */
/* Not safe to include "Turtle Beach" in longname, due to
length restrictions
*/
sprintf(card->longname, "%s PCM 0x%lx irq %d dma %d",
card->driver,
chip->port,
cs4232_pcm_irq[dev],
dma1[dev]);
if (dma2[dev] >= 0 && dma2[dev] < 8)
sprintf(card->longname + strlen(card->longname), "&%d", dma2[dev]);
if (cs4232_mpu_port[dev] > 0 && cs4232_mpu_port[dev] != SNDRV_AUTO_PORT) {
sprintf (card->longname + strlen (card->longname),
" MPU-401 0x%lx irq %d",
cs4232_mpu_port[dev],
cs4232_mpu_irq[dev]);
}
sprintf (card->longname + strlen (card->longname),
" SYNTH 0x%lx irq %d",
ics2115_port[dev],
ics2115_irq[dev]);
return snd_card_register(card);
}
static int snd_wavefront_isa_match(struct device *pdev,
unsigned int dev)
{
if (!enable[dev])
return 0;
#ifdef CONFIG_PNP
if (isapnp[dev])
return 0;
#endif
if (cs4232_pcm_port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR "specify CS4232 port\n");
return 0;
}
if (ics2115_port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR "specify ICS2115 port\n");
return 0;
}
return 1;
}
static int snd_wavefront_isa_probe(struct device *pdev,
unsigned int dev)
{
struct snd_card *card;
int err;
err = snd_wavefront_card_new(dev, &card);
if (err < 0)
return err;
snd_card_set_dev(card, pdev);
if ((err = snd_wavefront_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(pdev, card);
return 0;
}
static int snd_wavefront_isa_remove(struct device *devptr,
unsigned int dev)
{
snd_card_free(dev_get_drvdata(devptr));
return 0;
}
#define DEV_NAME "wavefront"
static struct isa_driver snd_wavefront_driver = {
.match = snd_wavefront_isa_match,
.probe = snd_wavefront_isa_probe,
.remove = snd_wavefront_isa_remove,
/* FIXME: suspend, resume */
.driver = {
.name = DEV_NAME
},
};
#ifdef CONFIG_PNP
static int snd_wavefront_pnp_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_wavefront_card_new(dev, &card);
if (res < 0)
return res;
if (snd_wavefront_pnp (dev, card->private_data, pcard, pid) < 0) {
if (cs4232_pcm_port[dev] == SNDRV_AUTO_PORT) {
snd_printk (KERN_ERR "isapnp detection failed\n");
snd_card_free (card);
return -ENODEV;
}
}
snd_card_set_dev(card, &pcard->card->dev);
if ((res = snd_wavefront_probe(card, dev)) < 0)
return res;
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
static void snd_wavefront_pnp_remove(struct pnp_card_link *pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
static struct pnp_card_driver wavefront_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = "wavefront",
.id_table = snd_wavefront_pnpids,
.probe = snd_wavefront_pnp_detect,
.remove = snd_wavefront_pnp_remove,
/* FIXME: suspend,resume */
};
#endif /* CONFIG_PNP */
static int __init alsa_card_wavefront_init(void)
{
int err;
err = isa_register_driver(&snd_wavefront_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_card_driver(&wavefront_pnpc_driver);
if (!err)
pnp_registered = 1;
if (isa_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_wavefront_exit(void)
{
#ifdef CONFIG_PNP
if (pnp_registered)
pnp_unregister_card_driver(&wavefront_pnpc_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_wavefront_driver);
}
module_init(alsa_card_wavefront_init)
module_exit(alsa_card_wavefront_exit)
| gpl-2.0 |
trickyMan/linux-socfpga | arch/arm64/net/bpf_jit_comp.c | 480 | 19373 | /*
* BPF JIT compiler for ARM64
*
* Copyright (C) 2014 Zi Shen Lim <zlim.lnx@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define pr_fmt(fmt) "bpf_jit: " fmt
#include <linux/filter.h>
#include <linux/printk.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/cacheflush.h>
#include <asm/debug-monitors.h>
#include "bpf_jit.h"
int bpf_jit_enable __read_mostly;
#define TMP_REG_1 (MAX_BPF_REG + 0)
#define TMP_REG_2 (MAX_BPF_REG + 1)
/* Map BPF registers to A64 registers */
static const int bpf2a64[] = {
/* return value from in-kernel function, and exit value from eBPF */
[BPF_REG_0] = A64_R(7),
/* arguments from eBPF program to in-kernel function */
[BPF_REG_1] = A64_R(0),
[BPF_REG_2] = A64_R(1),
[BPF_REG_3] = A64_R(2),
[BPF_REG_4] = A64_R(3),
[BPF_REG_5] = A64_R(4),
/* callee saved registers that in-kernel function will preserve */
[BPF_REG_6] = A64_R(19),
[BPF_REG_7] = A64_R(20),
[BPF_REG_8] = A64_R(21),
[BPF_REG_9] = A64_R(22),
/* read-only frame pointer to access stack */
[BPF_REG_FP] = A64_FP,
/* temporary register for internal BPF JIT */
[TMP_REG_1] = A64_R(23),
[TMP_REG_2] = A64_R(24),
};
struct jit_ctx {
const struct bpf_prog *prog;
int idx;
int tmp_used;
int epilogue_offset;
int *offset;
u32 *image;
};
static inline void emit(const u32 insn, struct jit_ctx *ctx)
{
if (ctx->image != NULL)
ctx->image[ctx->idx] = cpu_to_le32(insn);
ctx->idx++;
}
static inline void emit_a64_mov_i64(const int reg, const u64 val,
struct jit_ctx *ctx)
{
u64 tmp = val;
int shift = 0;
emit(A64_MOVZ(1, reg, tmp & 0xffff, shift), ctx);
tmp >>= 16;
shift += 16;
while (tmp) {
if (tmp & 0xffff)
emit(A64_MOVK(1, reg, tmp & 0xffff, shift), ctx);
tmp >>= 16;
shift += 16;
}
}
static inline void emit_a64_mov_i(const int is64, const int reg,
const s32 val, struct jit_ctx *ctx)
{
u16 hi = val >> 16;
u16 lo = val & 0xffff;
if (hi & 0x8000) {
if (hi == 0xffff) {
emit(A64_MOVN(is64, reg, (u16)~lo, 0), ctx);
} else {
emit(A64_MOVN(is64, reg, (u16)~hi, 16), ctx);
emit(A64_MOVK(is64, reg, lo, 0), ctx);
}
} else {
emit(A64_MOVZ(is64, reg, lo, 0), ctx);
if (hi)
emit(A64_MOVK(is64, reg, hi, 16), ctx);
}
}
static inline int bpf2a64_offset(int bpf_to, int bpf_from,
const struct jit_ctx *ctx)
{
int to = ctx->offset[bpf_to];
/* -1 to account for the Branch instruction */
int from = ctx->offset[bpf_from] - 1;
return to - from;
}
static void jit_fill_hole(void *area, unsigned int size)
{
u32 *ptr;
/* We are guaranteed to have aligned memory. */
for (ptr = area; size >= sizeof(u32); size -= sizeof(u32))
*ptr++ = cpu_to_le32(AARCH64_BREAK_FAULT);
}
static inline int epilogue_offset(const struct jit_ctx *ctx)
{
int to = ctx->epilogue_offset;
int from = ctx->idx;
return to - from;
}
/* Stack must be multiples of 16B */
#define STACK_ALIGN(sz) (((sz) + 15) & ~15)
static void build_prologue(struct jit_ctx *ctx)
{
const u8 r6 = bpf2a64[BPF_REG_6];
const u8 r7 = bpf2a64[BPF_REG_7];
const u8 r8 = bpf2a64[BPF_REG_8];
const u8 r9 = bpf2a64[BPF_REG_9];
const u8 fp = bpf2a64[BPF_REG_FP];
const u8 ra = bpf2a64[BPF_REG_A];
const u8 rx = bpf2a64[BPF_REG_X];
const u8 tmp1 = bpf2a64[TMP_REG_1];
const u8 tmp2 = bpf2a64[TMP_REG_2];
int stack_size = MAX_BPF_STACK;
stack_size += 4; /* extra for skb_copy_bits buffer */
stack_size = STACK_ALIGN(stack_size);
/* Save callee-saved register */
emit(A64_PUSH(r6, r7, A64_SP), ctx);
emit(A64_PUSH(r8, r9, A64_SP), ctx);
if (ctx->tmp_used)
emit(A64_PUSH(tmp1, tmp2, A64_SP), ctx);
/* Set up BPF stack */
emit(A64_SUB_I(1, A64_SP, A64_SP, stack_size), ctx);
/* Set up frame pointer */
emit(A64_MOV(1, fp, A64_SP), ctx);
/* Clear registers A and X */
emit_a64_mov_i64(ra, 0, ctx);
emit_a64_mov_i64(rx, 0, ctx);
}
static void build_epilogue(struct jit_ctx *ctx)
{
const u8 r0 = bpf2a64[BPF_REG_0];
const u8 r6 = bpf2a64[BPF_REG_6];
const u8 r7 = bpf2a64[BPF_REG_7];
const u8 r8 = bpf2a64[BPF_REG_8];
const u8 r9 = bpf2a64[BPF_REG_9];
const u8 fp = bpf2a64[BPF_REG_FP];
const u8 tmp1 = bpf2a64[TMP_REG_1];
const u8 tmp2 = bpf2a64[TMP_REG_2];
int stack_size = MAX_BPF_STACK;
stack_size += 4; /* extra for skb_copy_bits buffer */
stack_size = STACK_ALIGN(stack_size);
/* We're done with BPF stack */
emit(A64_ADD_I(1, A64_SP, A64_SP, stack_size), ctx);
/* Restore callee-saved register */
if (ctx->tmp_used)
emit(A64_POP(tmp1, tmp2, A64_SP), ctx);
emit(A64_POP(r8, r9, A64_SP), ctx);
emit(A64_POP(r6, r7, A64_SP), ctx);
/* Restore frame pointer */
emit(A64_MOV(1, fp, A64_SP), ctx);
/* Set return value */
emit(A64_MOV(1, A64_R(0), r0), ctx);
emit(A64_RET(A64_LR), ctx);
}
/* JITs an eBPF instruction.
* Returns:
* 0 - successfully JITed an 8-byte eBPF instruction.
* >0 - successfully JITed a 16-byte eBPF instruction.
* <0 - failed to JIT.
*/
static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx)
{
const u8 code = insn->code;
const u8 dst = bpf2a64[insn->dst_reg];
const u8 src = bpf2a64[insn->src_reg];
const u8 tmp = bpf2a64[TMP_REG_1];
const u8 tmp2 = bpf2a64[TMP_REG_2];
const s16 off = insn->off;
const s32 imm = insn->imm;
const int i = insn - ctx->prog->insnsi;
const bool is64 = BPF_CLASS(code) == BPF_ALU64;
u8 jmp_cond;
s32 jmp_offset;
switch (code) {
/* dst = src */
case BPF_ALU | BPF_MOV | BPF_X:
case BPF_ALU64 | BPF_MOV | BPF_X:
emit(A64_MOV(is64, dst, src), ctx);
break;
/* dst = dst OP src */
case BPF_ALU | BPF_ADD | BPF_X:
case BPF_ALU64 | BPF_ADD | BPF_X:
emit(A64_ADD(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_SUB | BPF_X:
case BPF_ALU64 | BPF_SUB | BPF_X:
emit(A64_SUB(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_AND | BPF_X:
case BPF_ALU64 | BPF_AND | BPF_X:
emit(A64_AND(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_OR | BPF_X:
case BPF_ALU64 | BPF_OR | BPF_X:
emit(A64_ORR(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_XOR | BPF_X:
case BPF_ALU64 | BPF_XOR | BPF_X:
emit(A64_EOR(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_MUL | BPF_X:
case BPF_ALU64 | BPF_MUL | BPF_X:
emit(A64_MUL(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_DIV | BPF_X:
case BPF_ALU64 | BPF_DIV | BPF_X:
emit(A64_UDIV(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_MOD | BPF_X:
case BPF_ALU64 | BPF_MOD | BPF_X:
ctx->tmp_used = 1;
emit(A64_UDIV(is64, tmp, dst, src), ctx);
emit(A64_MUL(is64, tmp, tmp, src), ctx);
emit(A64_SUB(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_LSH | BPF_X:
case BPF_ALU64 | BPF_LSH | BPF_X:
emit(A64_LSLV(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_RSH | BPF_X:
case BPF_ALU64 | BPF_RSH | BPF_X:
emit(A64_LSRV(is64, dst, dst, src), ctx);
break;
case BPF_ALU | BPF_ARSH | BPF_X:
case BPF_ALU64 | BPF_ARSH | BPF_X:
emit(A64_ASRV(is64, dst, dst, src), ctx);
break;
/* dst = -dst */
case BPF_ALU | BPF_NEG:
case BPF_ALU64 | BPF_NEG:
emit(A64_NEG(is64, dst, dst), ctx);
break;
/* dst = BSWAP##imm(dst) */
case BPF_ALU | BPF_END | BPF_FROM_LE:
case BPF_ALU | BPF_END | BPF_FROM_BE:
#ifdef CONFIG_CPU_BIG_ENDIAN
if (BPF_SRC(code) == BPF_FROM_BE)
goto emit_bswap_uxt;
#else /* !CONFIG_CPU_BIG_ENDIAN */
if (BPF_SRC(code) == BPF_FROM_LE)
goto emit_bswap_uxt;
#endif
switch (imm) {
case 16:
emit(A64_REV16(is64, dst, dst), ctx);
/* zero-extend 16 bits into 64 bits */
emit(A64_UXTH(is64, dst, dst), ctx);
break;
case 32:
emit(A64_REV32(is64, dst, dst), ctx);
/* upper 32 bits already cleared */
break;
case 64:
emit(A64_REV64(dst, dst), ctx);
break;
}
break;
emit_bswap_uxt:
switch (imm) {
case 16:
/* zero-extend 16 bits into 64 bits */
emit(A64_UXTH(is64, dst, dst), ctx);
break;
case 32:
/* zero-extend 32 bits into 64 bits */
emit(A64_UXTW(is64, dst, dst), ctx);
break;
case 64:
/* nop */
break;
}
break;
/* dst = imm */
case BPF_ALU | BPF_MOV | BPF_K:
case BPF_ALU64 | BPF_MOV | BPF_K:
emit_a64_mov_i(is64, dst, imm, ctx);
break;
/* dst = dst OP imm */
case BPF_ALU | BPF_ADD | BPF_K:
case BPF_ALU64 | BPF_ADD | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_ADD(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_SUB | BPF_K:
case BPF_ALU64 | BPF_SUB | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_SUB(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_AND | BPF_K:
case BPF_ALU64 | BPF_AND | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_AND(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_OR | BPF_K:
case BPF_ALU64 | BPF_OR | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_ORR(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_XOR | BPF_K:
case BPF_ALU64 | BPF_XOR | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_EOR(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_MUL | BPF_K:
case BPF_ALU64 | BPF_MUL | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_MUL(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_DIV | BPF_K:
case BPF_ALU64 | BPF_DIV | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp, imm, ctx);
emit(A64_UDIV(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_MOD | BPF_K:
case BPF_ALU64 | BPF_MOD | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(is64, tmp2, imm, ctx);
emit(A64_UDIV(is64, tmp, dst, tmp2), ctx);
emit(A64_MUL(is64, tmp, tmp, tmp2), ctx);
emit(A64_SUB(is64, dst, dst, tmp), ctx);
break;
case BPF_ALU | BPF_LSH | BPF_K:
case BPF_ALU64 | BPF_LSH | BPF_K:
emit(A64_LSL(is64, dst, dst, imm), ctx);
break;
case BPF_ALU | BPF_RSH | BPF_K:
case BPF_ALU64 | BPF_RSH | BPF_K:
emit(A64_LSR(is64, dst, dst, imm), ctx);
break;
case BPF_ALU | BPF_ARSH | BPF_K:
case BPF_ALU64 | BPF_ARSH | BPF_K:
emit(A64_ASR(is64, dst, dst, imm), ctx);
break;
#define check_imm(bits, imm) do { \
if ((((imm) > 0) && ((imm) >> (bits))) || \
(((imm) < 0) && (~(imm) >> (bits)))) { \
pr_info("[%2d] imm=%d(0x%x) out of range\n", \
i, imm, imm); \
return -EINVAL; \
} \
} while (0)
#define check_imm19(imm) check_imm(19, imm)
#define check_imm26(imm) check_imm(26, imm)
/* JUMP off */
case BPF_JMP | BPF_JA:
jmp_offset = bpf2a64_offset(i + off, i, ctx);
check_imm26(jmp_offset);
emit(A64_B(jmp_offset), ctx);
break;
/* IF (dst COND src) JUMP off */
case BPF_JMP | BPF_JEQ | BPF_X:
case BPF_JMP | BPF_JGT | BPF_X:
case BPF_JMP | BPF_JGE | BPF_X:
case BPF_JMP | BPF_JNE | BPF_X:
case BPF_JMP | BPF_JSGT | BPF_X:
case BPF_JMP | BPF_JSGE | BPF_X:
emit(A64_CMP(1, dst, src), ctx);
emit_cond_jmp:
jmp_offset = bpf2a64_offset(i + off, i, ctx);
check_imm19(jmp_offset);
switch (BPF_OP(code)) {
case BPF_JEQ:
jmp_cond = A64_COND_EQ;
break;
case BPF_JGT:
jmp_cond = A64_COND_HI;
break;
case BPF_JGE:
jmp_cond = A64_COND_CS;
break;
case BPF_JNE:
jmp_cond = A64_COND_NE;
break;
case BPF_JSGT:
jmp_cond = A64_COND_GT;
break;
case BPF_JSGE:
jmp_cond = A64_COND_GE;
break;
default:
return -EFAULT;
}
emit(A64_B_(jmp_cond, jmp_offset), ctx);
break;
case BPF_JMP | BPF_JSET | BPF_X:
emit(A64_TST(1, dst, src), ctx);
goto emit_cond_jmp;
/* IF (dst COND imm) JUMP off */
case BPF_JMP | BPF_JEQ | BPF_K:
case BPF_JMP | BPF_JGT | BPF_K:
case BPF_JMP | BPF_JGE | BPF_K:
case BPF_JMP | BPF_JNE | BPF_K:
case BPF_JMP | BPF_JSGT | BPF_K:
case BPF_JMP | BPF_JSGE | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(1, tmp, imm, ctx);
emit(A64_CMP(1, dst, tmp), ctx);
goto emit_cond_jmp;
case BPF_JMP | BPF_JSET | BPF_K:
ctx->tmp_used = 1;
emit_a64_mov_i(1, tmp, imm, ctx);
emit(A64_TST(1, dst, tmp), ctx);
goto emit_cond_jmp;
/* function call */
case BPF_JMP | BPF_CALL:
{
const u8 r0 = bpf2a64[BPF_REG_0];
const u64 func = (u64)__bpf_call_base + imm;
ctx->tmp_used = 1;
emit_a64_mov_i64(tmp, func, ctx);
emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
emit(A64_MOV(1, A64_FP, A64_SP), ctx);
emit(A64_BLR(tmp), ctx);
emit(A64_MOV(1, r0, A64_R(0)), ctx);
emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
break;
}
/* function return */
case BPF_JMP | BPF_EXIT:
/* Optimization: when last instruction is EXIT,
simply fallthrough to epilogue. */
if (i == ctx->prog->len - 1)
break;
jmp_offset = epilogue_offset(ctx);
check_imm26(jmp_offset);
emit(A64_B(jmp_offset), ctx);
break;
/* dst = imm64 */
case BPF_LD | BPF_IMM | BPF_DW:
{
const struct bpf_insn insn1 = insn[1];
u64 imm64;
if (insn1.code != 0 || insn1.src_reg != 0 ||
insn1.dst_reg != 0 || insn1.off != 0) {
/* Note: verifier in BPF core must catch invalid
* instructions.
*/
pr_err_once("Invalid BPF_LD_IMM64 instruction\n");
return -EINVAL;
}
imm64 = (u64)insn1.imm << 32 | (u32)imm;
emit_a64_mov_i64(dst, imm64, ctx);
return 1;
}
/* LDX: dst = *(size *)(src + off) */
case BPF_LDX | BPF_MEM | BPF_W:
case BPF_LDX | BPF_MEM | BPF_H:
case BPF_LDX | BPF_MEM | BPF_B:
case BPF_LDX | BPF_MEM | BPF_DW:
ctx->tmp_used = 1;
emit_a64_mov_i(1, tmp, off, ctx);
switch (BPF_SIZE(code)) {
case BPF_W:
emit(A64_LDR32(dst, src, tmp), ctx);
break;
case BPF_H:
emit(A64_LDRH(dst, src, tmp), ctx);
break;
case BPF_B:
emit(A64_LDRB(dst, src, tmp), ctx);
break;
case BPF_DW:
emit(A64_LDR64(dst, src, tmp), ctx);
break;
}
break;
/* ST: *(size *)(dst + off) = imm */
case BPF_ST | BPF_MEM | BPF_W:
case BPF_ST | BPF_MEM | BPF_H:
case BPF_ST | BPF_MEM | BPF_B:
case BPF_ST | BPF_MEM | BPF_DW:
goto notyet;
/* STX: *(size *)(dst + off) = src */
case BPF_STX | BPF_MEM | BPF_W:
case BPF_STX | BPF_MEM | BPF_H:
case BPF_STX | BPF_MEM | BPF_B:
case BPF_STX | BPF_MEM | BPF_DW:
ctx->tmp_used = 1;
emit_a64_mov_i(1, tmp, off, ctx);
switch (BPF_SIZE(code)) {
case BPF_W:
emit(A64_STR32(src, dst, tmp), ctx);
break;
case BPF_H:
emit(A64_STRH(src, dst, tmp), ctx);
break;
case BPF_B:
emit(A64_STRB(src, dst, tmp), ctx);
break;
case BPF_DW:
emit(A64_STR64(src, dst, tmp), ctx);
break;
}
break;
/* STX XADD: lock *(u32 *)(dst + off) += src */
case BPF_STX | BPF_XADD | BPF_W:
/* STX XADD: lock *(u64 *)(dst + off) += src */
case BPF_STX | BPF_XADD | BPF_DW:
goto notyet;
/* R0 = ntohx(*(size *)(((struct sk_buff *)R6)->data + imm)) */
case BPF_LD | BPF_ABS | BPF_W:
case BPF_LD | BPF_ABS | BPF_H:
case BPF_LD | BPF_ABS | BPF_B:
/* R0 = ntohx(*(size *)(((struct sk_buff *)R6)->data + src + imm)) */
case BPF_LD | BPF_IND | BPF_W:
case BPF_LD | BPF_IND | BPF_H:
case BPF_LD | BPF_IND | BPF_B:
{
const u8 r0 = bpf2a64[BPF_REG_0]; /* r0 = return value */
const u8 r6 = bpf2a64[BPF_REG_6]; /* r6 = pointer to sk_buff */
const u8 fp = bpf2a64[BPF_REG_FP];
const u8 r1 = bpf2a64[BPF_REG_1]; /* r1: struct sk_buff *skb */
const u8 r2 = bpf2a64[BPF_REG_2]; /* r2: int k */
const u8 r3 = bpf2a64[BPF_REG_3]; /* r3: unsigned int size */
const u8 r4 = bpf2a64[BPF_REG_4]; /* r4: void *buffer */
const u8 r5 = bpf2a64[BPF_REG_5]; /* r5: void *(*func)(...) */
int size;
emit(A64_MOV(1, r1, r6), ctx);
emit_a64_mov_i(0, r2, imm, ctx);
if (BPF_MODE(code) == BPF_IND)
emit(A64_ADD(0, r2, r2, src), ctx);
switch (BPF_SIZE(code)) {
case BPF_W:
size = 4;
break;
case BPF_H:
size = 2;
break;
case BPF_B:
size = 1;
break;
default:
return -EINVAL;
}
emit_a64_mov_i64(r3, size, ctx);
emit(A64_ADD_I(1, r4, fp, MAX_BPF_STACK), ctx);
emit_a64_mov_i64(r5, (unsigned long)bpf_load_pointer, ctx);
emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
emit(A64_MOV(1, A64_FP, A64_SP), ctx);
emit(A64_BLR(r5), ctx);
emit(A64_MOV(1, r0, A64_R(0)), ctx);
emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
jmp_offset = epilogue_offset(ctx);
check_imm19(jmp_offset);
emit(A64_CBZ(1, r0, jmp_offset), ctx);
emit(A64_MOV(1, r5, r0), ctx);
switch (BPF_SIZE(code)) {
case BPF_W:
emit(A64_LDR32(r0, r5, A64_ZR), ctx);
#ifndef CONFIG_CPU_BIG_ENDIAN
emit(A64_REV32(0, r0, r0), ctx);
#endif
break;
case BPF_H:
emit(A64_LDRH(r0, r5, A64_ZR), ctx);
#ifndef CONFIG_CPU_BIG_ENDIAN
emit(A64_REV16(0, r0, r0), ctx);
#endif
break;
case BPF_B:
emit(A64_LDRB(r0, r5, A64_ZR), ctx);
break;
}
break;
}
notyet:
pr_info_once("*** NOT YET: opcode %02x ***\n", code);
return -EFAULT;
default:
pr_err_once("unknown opcode %02x\n", code);
return -EINVAL;
}
return 0;
}
static int build_body(struct jit_ctx *ctx)
{
const struct bpf_prog *prog = ctx->prog;
int i;
for (i = 0; i < prog->len; i++) {
const struct bpf_insn *insn = &prog->insnsi[i];
int ret;
ret = build_insn(insn, ctx);
if (ctx->image == NULL)
ctx->offset[i] = ctx->idx;
if (ret > 0) {
i++;
continue;
}
if (ret)
return ret;
}
return 0;
}
static inline void bpf_flush_icache(void *start, void *end)
{
flush_icache_range((unsigned long)start, (unsigned long)end);
}
void bpf_jit_compile(struct bpf_prog *prog)
{
/* Nothing to do here. We support Internal BPF. */
}
void bpf_int_jit_compile(struct bpf_prog *prog)
{
struct bpf_binary_header *header;
struct jit_ctx ctx;
int image_size;
u8 *image_ptr;
if (!bpf_jit_enable)
return;
if (!prog || !prog->len)
return;
memset(&ctx, 0, sizeof(ctx));
ctx.prog = prog;
ctx.offset = kcalloc(prog->len, sizeof(int), GFP_KERNEL);
if (ctx.offset == NULL)
return;
/* 1. Initial fake pass to compute ctx->idx. */
/* Fake pass to fill in ctx->offset and ctx->tmp_used. */
if (build_body(&ctx))
goto out;
build_prologue(&ctx);
ctx.epilogue_offset = ctx.idx;
build_epilogue(&ctx);
/* Now we know the actual image size. */
image_size = sizeof(u32) * ctx.idx;
header = bpf_jit_binary_alloc(image_size, &image_ptr,
sizeof(u32), jit_fill_hole);
if (header == NULL)
goto out;
/* 2. Now, the actual pass. */
ctx.image = (u32 *)image_ptr;
ctx.idx = 0;
build_prologue(&ctx);
if (build_body(&ctx)) {
bpf_jit_binary_free(header);
goto out;
}
build_epilogue(&ctx);
/* And we're done. */
if (bpf_jit_enable > 1)
bpf_jit_dump(prog->len, image_size, 2, ctx.image);
bpf_flush_icache(ctx.image, ctx.image + ctx.idx);
set_memory_ro((unsigned long)header, header->pages);
prog->bpf_func = (void *)ctx.image;
prog->jited = true;
out:
kfree(ctx.offset);
}
void bpf_jit_free(struct bpf_prog *prog)
{
unsigned long addr = (unsigned long)prog->bpf_func & PAGE_MASK;
struct bpf_binary_header *header = (void *)addr;
if (!prog->jited)
goto free_filter;
set_memory_rw(addr, header->pages);
bpf_jit_binary_free(header);
free_filter:
bpf_prog_unlock_free(prog);
}
| gpl-2.0 |
Haxynox/kernel_samsung_n7100 | drivers/misc/mpu3050/accel/bma150.c | 736 | 3885 | /*
$License:
Copyright (C) 2010 InvenSense Corporation, All Rights Reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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/>.
$
*/
/**
* @defgroup ACCELDL (Motion Library - Accelerometer Driver Layer)
* @brief Provides the interface to setup and handle an accelerometers
* connected to the secondary I2C interface of the gyroscope.
*
* @{
* @file bma150.c
* @brief Accelerometer setup and handling methods.
*/
/* ------------------ */
/* - Include Files. - */
/* ------------------ */
#ifdef __KERNEL__
#include <linux/module.h>
#endif
#include "mpu.h"
#include "mlos.h"
#include "mlsl.h"
/* --------------------- */
/* - Variables. - */
/* --------------------- */
/*********************************************
Accelerometer Initialization Functions
**********************************************/
static int bma150_suspend(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
int result;
result =
MLSLSerialWriteSingle(mlsl_handle, pdata->address, 0x0a, 0x01);
MLOSSleep(3); /* 3 ms powerup time maximum */
ERROR_CHECK(result);
return result;
}
/* full scale setting - register and mask */
#define ACCEL_BOSCH_CTRL_REG (0x14)
#define ACCEL_BOSCH_CTRL_MASK (0x18)
static int bma150_resume(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
int result;
unsigned char reg = 0;
/* Soft reset */
result =
MLSLSerialWriteSingle(mlsl_handle, pdata->address, 0x0a, 0x02);
ERROR_CHECK(result);
MLOSSleep(3);
result =
MLSLSerialRead(mlsl_handle, pdata->address, 0x14, 1, ®);
ERROR_CHECK(result);
/* Bandwidth */
reg &= 0xc0;
reg |= 3; /* 3=190 Hz */
/* Full Scale */
reg &= ~ACCEL_BOSCH_CTRL_MASK;
if (slave->range.mantissa == 4)
reg |= 0x08;
else if (slave->range.mantissa == 8)
reg |= 0x10;
else {
slave->range.mantissa = 2;
reg |= 0x00;
}
slave->range.fraction = 0;
result =
MLSLSerialWriteSingle(mlsl_handle, pdata->address, 0x14, reg);
ERROR_CHECK(result);
return result;
}
static int bma150_read(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata,
unsigned char *data)
{
int result;
result = MLSLSerialRead(mlsl_handle, pdata->address,
slave->reg, slave->len, data);
return result;
}
static struct ext_slave_descr bma150_descr = {
/*.init = */ NULL,
/*.exit = */ NULL,
/*.suspend = */ bma150_suspend,
/*.resume = */ bma150_resume,
/*.read = */ bma150_read,
/*.config = */ NULL,
/*.get_config = */ NULL,
/*.name = */ "bma150",
/*.type = */ EXT_SLAVE_TYPE_ACCELEROMETER,
/*.id = */ ACCEL_ID_BMA150,
/*.reg = */ 0x02,
/*.len = */ 6,
/*.endian = */ EXT_SLAVE_LITTLE_ENDIAN,
/*.range = */ {2, 0},
};
struct ext_slave_descr *bma150_get_slave_descr(void)
{
return &bma150_descr;
}
EXPORT_SYMBOL(bma150_get_slave_descr);
#ifdef __KERNEL__
MODULE_AUTHOR("Invensense");
MODULE_DESCRIPTION("User space IRQ handler for MPU3xxx devices");
MODULE_LICENSE("GPL");
MODULE_ALIAS("bma");
#endif
/**
* @}
*/
| gpl-2.0 |
LegacyHuawei/android_kernel_huawei_msm7x30 | drivers/thermal/thermal_sys.c | 1248 | 38909 | /*
* thermal.c - Generic Thermal Management Sysfs support.
*
* Copyright (C) 2008 Intel Corp
* Copyright (C) 2008 Zhang Rui <rui.zhang@intel.com>
* Copyright (C) 2008 Sujith Thomas <sujith.thomas@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/kdev_t.h>
#include <linux/idr.h>
#include <linux/thermal.h>
#include <linux/spinlock.h>
#include <linux/reboot.h>
#include <net/netlink.h>
#include <net/genetlink.h>
MODULE_AUTHOR("Zhang Rui");
MODULE_DESCRIPTION("Generic thermal management sysfs support");
MODULE_LICENSE("GPL");
struct thermal_cooling_device_instance {
int id;
char name[THERMAL_NAME_LENGTH];
struct thermal_zone_device *tz;
struct thermal_cooling_device *cdev;
int trip;
char attr_name[THERMAL_NAME_LENGTH];
struct device_attribute attr;
struct list_head node;
};
static DEFINE_IDR(thermal_tz_idr);
static DEFINE_IDR(thermal_cdev_idr);
static DEFINE_MUTEX(thermal_idr_lock);
static LIST_HEAD(thermal_tz_list);
static LIST_HEAD(thermal_cdev_list);
static DEFINE_MUTEX(thermal_list_lock);
static int get_idr(struct idr *idr, struct mutex *lock, int *id)
{
int err;
again:
if (unlikely(idr_pre_get(idr, GFP_KERNEL) == 0))
return -ENOMEM;
if (lock)
mutex_lock(lock);
err = idr_get_new(idr, NULL, id);
if (lock)
mutex_unlock(lock);
if (unlikely(err == -EAGAIN))
goto again;
else if (unlikely(err))
return err;
*id = *id & MAX_ID_MASK;
return 0;
}
static void release_idr(struct idr *idr, struct mutex *lock, int id)
{
if (lock)
mutex_lock(lock);
idr_remove(idr, id);
if (lock)
mutex_unlock(lock);
}
/* sys I/F for thermal zone */
#define to_thermal_zone(_dev) \
container_of(_dev, struct thermal_zone_device, device)
static ssize_t
type_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
return sprintf(buf, "%s\n", tz->type);
}
static ssize_t
temp_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
long temperature;
int ret;
if (!tz->ops->get_temp)
return -EPERM;
ret = tz->ops->get_temp(tz, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static ssize_t
mode_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
enum thermal_device_mode mode;
int result;
if (!tz->ops->get_mode)
return -EPERM;
result = tz->ops->get_mode(tz, &mode);
if (result)
return result;
return sprintf(buf, "%s\n", mode == THERMAL_DEVICE_ENABLED ? "enabled"
: "disabled");
}
static ssize_t
mode_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int result;
if (!tz->ops->set_mode)
return -EPERM;
if (!strncmp(buf, "enabled", sizeof("enabled") - 1))
result = tz->ops->set_mode(tz, THERMAL_DEVICE_ENABLED);
else if (!strncmp(buf, "disabled", sizeof("disabled") - 1))
result = tz->ops->set_mode(tz, THERMAL_DEVICE_DISABLED);
else
result = -EINVAL;
if (result)
return result;
return count;
}
static ssize_t
trip_point_type_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
enum thermal_trip_type type;
int trip, result;
if (!tz->ops->get_trip_type)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_type", &trip))
return -EINVAL;
result = tz->ops->get_trip_type(tz, trip, &type);
if (result)
return result;
switch (type) {
case THERMAL_TRIP_CRITICAL:
return sprintf(buf, "critical\n");
case THERMAL_TRIP_HOT:
return sprintf(buf, "hot\n");
case THERMAL_TRIP_CONFIGURABLE_HI:
return sprintf(buf, "configurable_hi\n");
case THERMAL_TRIP_CONFIGURABLE_LOW:
return sprintf(buf, "configurable_low\n");
case THERMAL_TRIP_CRITICAL_LOW:
return sprintf(buf, "critical_low\n");
case THERMAL_TRIP_PASSIVE:
return sprintf(buf, "passive\n");
case THERMAL_TRIP_ACTIVE:
return sprintf(buf, "active\n");
default:
return sprintf(buf, "unknown\n");
}
}
static ssize_t
trip_point_type_activate(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, result;
if (!tz->ops->activate_trip_type)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_type", &trip))
return -EINVAL;
if (!strncmp(buf, "enabled", sizeof("enabled")))
result = tz->ops->activate_trip_type(tz, trip,
THERMAL_TRIP_ACTIVATION_ENABLED);
else if (!strncmp(buf, "disabled", sizeof("disabled")))
result = tz->ops->activate_trip_type(tz, trip,
THERMAL_TRIP_ACTIVATION_DISABLED);
else
result = -EINVAL;
if (result)
return result;
return count;
}
static ssize_t
trip_point_temp_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
long temperature;
if (!tz->ops->get_trip_temp)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_temp", &trip))
return -EINVAL;
ret = tz->ops->get_trip_temp(tz, trip, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static ssize_t
trip_point_temp_set(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
long temperature;
if (!tz->ops->set_trip_temp)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_temp", &trip))
return -EINVAL;
if (!sscanf(buf, "%ld", &temperature))
return -EINVAL;
ret = tz->ops->set_trip_temp(tz, trip, temperature);
if (ret)
return ret;
return count;
}
static ssize_t
passive_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
struct thermal_cooling_device *cdev = NULL;
int state;
if (!sscanf(buf, "%d\n", &state))
return -EINVAL;
/* sanity check: values below 1000 millicelcius don't make sense
* and can cause the system to go into a thermal heart attack
*/
if (state && state < 1000)
return -EINVAL;
if (state && !tz->forced_passive) {
mutex_lock(&thermal_list_lock);
list_for_each_entry(cdev, &thermal_cdev_list, node) {
if (!strncmp("Processor", cdev->type,
sizeof("Processor")))
thermal_zone_bind_cooling_device(tz,
THERMAL_TRIPS_NONE,
cdev);
}
mutex_unlock(&thermal_list_lock);
if (!tz->passive_delay)
tz->passive_delay = 1000;
} else if (!state && tz->forced_passive) {
mutex_lock(&thermal_list_lock);
list_for_each_entry(cdev, &thermal_cdev_list, node) {
if (!strncmp("Processor", cdev->type,
sizeof("Processor")))
thermal_zone_unbind_cooling_device(tz,
THERMAL_TRIPS_NONE,
cdev);
}
mutex_unlock(&thermal_list_lock);
tz->passive_delay = 0;
}
tz->tc1 = 1;
tz->tc2 = 1;
tz->forced_passive = state;
thermal_zone_device_update(tz);
return count;
}
static ssize_t
passive_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
return sprintf(buf, "%d\n", tz->forced_passive);
}
static DEVICE_ATTR(type, 0444, type_show, NULL);
static DEVICE_ATTR(temp, 0444, temp_show, NULL);
static DEVICE_ATTR(mode, 0644, mode_show, mode_store);
static DEVICE_ATTR(passive, S_IRUGO | S_IWUSR, passive_show, passive_store);
static struct device_attribute trip_point_attrs[] = {
__ATTR(trip_point_0_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_0_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_1_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_1_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_2_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_2_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_3_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_3_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_4_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_4_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_5_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_5_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_6_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_6_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_7_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_7_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_8_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_8_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_9_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_9_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_10_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_10_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
__ATTR(trip_point_11_type, 0644, trip_point_type_show,
trip_point_type_activate),
__ATTR(trip_point_11_temp, 0644, trip_point_temp_show,
trip_point_temp_set),
};
/* sys I/F for cooling device */
#define to_cooling_device(_dev) \
container_of(_dev, struct thermal_cooling_device, device)
static ssize_t
thermal_cooling_device_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
return sprintf(buf, "%s\n", cdev->type);
}
static ssize_t
thermal_cooling_device_max_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int ret;
ret = cdev->ops->get_max_state(cdev, &state);
if (ret)
return ret;
return sprintf(buf, "%ld\n", state);
}
static ssize_t
thermal_cooling_device_cur_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int ret;
ret = cdev->ops->get_cur_state(cdev, &state);
if (ret)
return ret;
return sprintf(buf, "%ld\n", state);
}
static ssize_t
thermal_cooling_device_cur_state_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int result;
if (!sscanf(buf, "%ld\n", &state))
return -EINVAL;
if ((long)state < 0)
return -EINVAL;
result = cdev->ops->set_cur_state(cdev, state);
if (result)
return result;
return count;
}
static struct device_attribute dev_attr_cdev_type =
__ATTR(type, 0444, thermal_cooling_device_type_show, NULL);
static DEVICE_ATTR(max_state, 0444,
thermal_cooling_device_max_state_show, NULL);
static DEVICE_ATTR(cur_state, 0644,
thermal_cooling_device_cur_state_show,
thermal_cooling_device_cur_state_store);
static ssize_t
thermal_cooling_device_trip_point_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device_instance *instance;
instance =
container_of(attr, struct thermal_cooling_device_instance, attr);
if (instance->trip == THERMAL_TRIPS_NONE)
return sprintf(buf, "-1\n");
else
return sprintf(buf, "%d\n", instance->trip);
}
/* Device management */
#if defined(CONFIG_THERMAL_HWMON)
/* hwmon sys I/F */
#include <linux/hwmon.h>
/* thermal zone devices with the same type share one hwmon device */
struct thermal_hwmon_device {
char type[THERMAL_NAME_LENGTH];
struct device *device;
int count;
struct list_head tz_list;
struct list_head node;
};
struct thermal_hwmon_attr {
struct device_attribute attr;
char name[16];
};
/* one temperature input for each thermal zone */
struct thermal_hwmon_temp {
struct list_head hwmon_node;
struct thermal_zone_device *tz;
struct thermal_hwmon_attr temp_input; /* hwmon sys attr */
struct thermal_hwmon_attr temp_crit; /* hwmon sys attr */
};
static LIST_HEAD(thermal_hwmon_list);
static ssize_t
name_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_hwmon_device *hwmon = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", hwmon->type);
}
static DEVICE_ATTR(name, 0444, name_show, NULL);
static ssize_t
temp_input_show(struct device *dev, struct device_attribute *attr, char *buf)
{
long temperature;
int ret;
struct thermal_hwmon_attr *hwmon_attr
= container_of(attr, struct thermal_hwmon_attr, attr);
struct thermal_hwmon_temp *temp
= container_of(hwmon_attr, struct thermal_hwmon_temp,
temp_input);
struct thermal_zone_device *tz = temp->tz;
ret = tz->ops->get_temp(tz, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static ssize_t
temp_crit_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_hwmon_attr *hwmon_attr
= container_of(attr, struct thermal_hwmon_attr, attr);
struct thermal_hwmon_temp *temp
= container_of(hwmon_attr, struct thermal_hwmon_temp,
temp_crit);
struct thermal_zone_device *tz = temp->tz;
long temperature;
int ret;
ret = tz->ops->get_trip_temp(tz, 0, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static struct thermal_hwmon_device *
thermal_hwmon_lookup_by_type(const struct thermal_zone_device *tz)
{
struct thermal_hwmon_device *hwmon;
mutex_lock(&thermal_list_lock);
list_for_each_entry(hwmon, &thermal_hwmon_list, node)
if (!strcmp(hwmon->type, tz->type)) {
mutex_unlock(&thermal_list_lock);
return hwmon;
}
mutex_unlock(&thermal_list_lock);
return NULL;
}
/* Find the temperature input matching a given thermal zone */
static struct thermal_hwmon_temp *
thermal_hwmon_lookup_temp(const struct thermal_hwmon_device *hwmon,
const struct thermal_zone_device *tz)
{
struct thermal_hwmon_temp *temp;
mutex_lock(&thermal_list_lock);
list_for_each_entry(temp, &hwmon->tz_list, hwmon_node)
if (temp->tz == tz) {
mutex_unlock(&thermal_list_lock);
return temp;
}
mutex_unlock(&thermal_list_lock);
return NULL;
}
static int
thermal_add_hwmon_sysfs(struct thermal_zone_device *tz)
{
struct thermal_hwmon_device *hwmon;
struct thermal_hwmon_temp *temp;
int new_hwmon_device = 1;
int result;
hwmon = thermal_hwmon_lookup_by_type(tz);
if (hwmon) {
new_hwmon_device = 0;
goto register_sys_interface;
}
hwmon = kzalloc(sizeof(struct thermal_hwmon_device), GFP_KERNEL);
if (!hwmon)
return -ENOMEM;
INIT_LIST_HEAD(&hwmon->tz_list);
strlcpy(hwmon->type, tz->type, THERMAL_NAME_LENGTH);
hwmon->device = hwmon_device_register(NULL);
if (IS_ERR(hwmon->device)) {
result = PTR_ERR(hwmon->device);
goto free_mem;
}
dev_set_drvdata(hwmon->device, hwmon);
result = device_create_file(hwmon->device, &dev_attr_name);
if (result)
goto free_mem;
register_sys_interface:
temp = kzalloc(sizeof(struct thermal_hwmon_temp), GFP_KERNEL);
if (!temp) {
result = -ENOMEM;
goto unregister_name;
}
temp->tz = tz;
hwmon->count++;
snprintf(temp->temp_input.name, THERMAL_NAME_LENGTH,
"temp%d_input", hwmon->count);
temp->temp_input.attr.attr.name = temp->temp_input.name;
temp->temp_input.attr.attr.mode = 0444;
temp->temp_input.attr.show = temp_input_show;
sysfs_attr_init(&temp->temp_input.attr.attr);
result = device_create_file(hwmon->device, &temp->temp_input.attr);
if (result)
goto free_temp_mem;
if (tz->ops->get_crit_temp) {
unsigned long temperature;
if (!tz->ops->get_crit_temp(tz, &temperature)) {
snprintf(temp->temp_crit.name, THERMAL_NAME_LENGTH,
"temp%d_crit", hwmon->count);
temp->temp_crit.attr.attr.name = temp->temp_crit.name;
temp->temp_crit.attr.attr.mode = 0444;
temp->temp_crit.attr.show = temp_crit_show;
sysfs_attr_init(&temp->temp_crit.attr.attr);
result = device_create_file(hwmon->device,
&temp->temp_crit.attr);
if (result)
goto unregister_input;
}
}
mutex_lock(&thermal_list_lock);
if (new_hwmon_device)
list_add_tail(&hwmon->node, &thermal_hwmon_list);
list_add_tail(&temp->hwmon_node, &hwmon->tz_list);
mutex_unlock(&thermal_list_lock);
return 0;
unregister_input:
device_remove_file(hwmon->device, &temp->temp_input.attr);
free_temp_mem:
kfree(temp);
unregister_name:
if (new_hwmon_device) {
device_remove_file(hwmon->device, &dev_attr_name);
hwmon_device_unregister(hwmon->device);
}
free_mem:
if (new_hwmon_device)
kfree(hwmon);
return result;
}
static void
thermal_remove_hwmon_sysfs(struct thermal_zone_device *tz)
{
struct thermal_hwmon_device *hwmon;
struct thermal_hwmon_temp *temp;
hwmon = thermal_hwmon_lookup_by_type(tz);
if (unlikely(!hwmon)) {
/* Should never happen... */
dev_dbg(&tz->device, "hwmon device lookup failed!\n");
return;
}
temp = thermal_hwmon_lookup_temp(hwmon, tz);
if (unlikely(!temp)) {
/* Should never happen... */
dev_dbg(&tz->device, "temperature input lookup failed!\n");
return;
}
device_remove_file(hwmon->device, &temp->temp_input.attr);
if (tz->ops->get_crit_temp)
device_remove_file(hwmon->device, &temp->temp_crit.attr);
mutex_lock(&thermal_list_lock);
list_del(&temp->hwmon_node);
kfree(temp);
if (!list_empty(&hwmon->tz_list)) {
mutex_unlock(&thermal_list_lock);
return;
}
list_del(&hwmon->node);
mutex_unlock(&thermal_list_lock);
device_remove_file(hwmon->device, &dev_attr_name);
hwmon_device_unregister(hwmon->device);
kfree(hwmon);
}
#else
static int
thermal_add_hwmon_sysfs(struct thermal_zone_device *tz)
{
return 0;
}
static void
thermal_remove_hwmon_sysfs(struct thermal_zone_device *tz)
{
}
#endif
static void thermal_zone_device_set_polling(struct thermal_zone_device *tz,
int delay)
{
cancel_delayed_work(&(tz->poll_queue));
if (!delay)
return;
if (delay > 1000)
queue_delayed_work(system_freezable_wq, &(tz->poll_queue),
round_jiffies(msecs_to_jiffies(delay)));
else
queue_delayed_work(system_freezable_wq, &(tz->poll_queue),
msecs_to_jiffies(delay));
}
static void thermal_zone_device_passive(struct thermal_zone_device *tz,
int temp, int trip_temp, int trip)
{
int trend = 0;
struct thermal_cooling_device_instance *instance;
struct thermal_cooling_device *cdev;
long state, max_state;
/*
* Above Trip?
* -----------
* Calculate the thermal trend (using the passive cooling equation)
* and modify the performance limit for all passive cooling devices
* accordingly. Note that we assume symmetry.
*/
if (temp >= trip_temp) {
tz->passive = true;
trend = (tz->tc1 * (temp - tz->last_temperature)) +
(tz->tc2 * (temp - trip_temp));
/* Heating up? */
if (trend > 0) {
list_for_each_entry(instance, &tz->cooling_devices,
node) {
if (instance->trip != trip)
continue;
cdev = instance->cdev;
cdev->ops->get_cur_state(cdev, &state);
cdev->ops->get_max_state(cdev, &max_state);
if (state++ < max_state)
cdev->ops->set_cur_state(cdev, state);
}
} else if (trend < 0) { /* Cooling off? */
list_for_each_entry(instance, &tz->cooling_devices,
node) {
if (instance->trip != trip)
continue;
cdev = instance->cdev;
cdev->ops->get_cur_state(cdev, &state);
cdev->ops->get_max_state(cdev, &max_state);
if (state > 0)
cdev->ops->set_cur_state(cdev, --state);
}
}
return;
}
/*
* Below Trip?
* -----------
* Implement passive cooling hysteresis to slowly increase performance
* and avoid thrashing around the passive trip point. Note that we
* assume symmetry.
*/
list_for_each_entry(instance, &tz->cooling_devices, node) {
if (instance->trip != trip)
continue;
cdev = instance->cdev;
cdev->ops->get_cur_state(cdev, &state);
cdev->ops->get_max_state(cdev, &max_state);
if (state > 0)
cdev->ops->set_cur_state(cdev, --state);
if (state == 0)
tz->passive = false;
}
}
static void thermal_zone_device_check(struct work_struct *work)
{
struct thermal_zone_device *tz = container_of(work, struct
thermal_zone_device,
poll_queue.work);
thermal_zone_device_update(tz);
}
/**
* thermal_zone_bind_cooling_device - bind a cooling device to a thermal zone
* @tz: thermal zone device
* @trip: indicates which trip point the cooling devices is
* associated with in this thermal zone.
* @cdev: thermal cooling device
*
* This function is usually called in the thermal zone device .bind callback.
*/
int thermal_zone_bind_cooling_device(struct thermal_zone_device *tz,
int trip,
struct thermal_cooling_device *cdev)
{
struct thermal_cooling_device_instance *dev;
struct thermal_cooling_device_instance *pos;
struct thermal_zone_device *pos1;
struct thermal_cooling_device *pos2;
int result;
if (trip >= tz->trips || (trip < 0 && trip != THERMAL_TRIPS_NONE))
return -EINVAL;
list_for_each_entry(pos1, &thermal_tz_list, node) {
if (pos1 == tz)
break;
}
list_for_each_entry(pos2, &thermal_cdev_list, node) {
if (pos2 == cdev)
break;
}
if (tz != pos1 || cdev != pos2)
return -EINVAL;
dev =
kzalloc(sizeof(struct thermal_cooling_device_instance), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->tz = tz;
dev->cdev = cdev;
dev->trip = trip;
result = get_idr(&tz->idr, &tz->lock, &dev->id);
if (result)
goto free_mem;
sprintf(dev->name, "cdev%d", dev->id);
result =
sysfs_create_link(&tz->device.kobj, &cdev->device.kobj, dev->name);
if (result)
goto release_idr;
sprintf(dev->attr_name, "cdev%d_trip_point", dev->id);
sysfs_attr_init(&dev->attr.attr);
dev->attr.attr.name = dev->attr_name;
dev->attr.attr.mode = 0444;
dev->attr.show = thermal_cooling_device_trip_point_show;
result = device_create_file(&tz->device, &dev->attr);
if (result)
goto remove_symbol_link;
mutex_lock(&tz->lock);
list_for_each_entry(pos, &tz->cooling_devices, node)
if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
result = -EEXIST;
break;
}
if (!result)
list_add_tail(&dev->node, &tz->cooling_devices);
mutex_unlock(&tz->lock);
if (!result)
return 0;
device_remove_file(&tz->device, &dev->attr);
remove_symbol_link:
sysfs_remove_link(&tz->device.kobj, dev->name);
release_idr:
release_idr(&tz->idr, &tz->lock, dev->id);
free_mem:
kfree(dev);
return result;
}
EXPORT_SYMBOL(thermal_zone_bind_cooling_device);
/**
* thermal_zone_unbind_cooling_device - unbind a cooling device from a thermal zone
* @tz: thermal zone device
* @trip: indicates which trip point the cooling devices is
* associated with in this thermal zone.
* @cdev: thermal cooling device
*
* This function is usually called in the thermal zone device .unbind callback.
*/
int thermal_zone_unbind_cooling_device(struct thermal_zone_device *tz,
int trip,
struct thermal_cooling_device *cdev)
{
struct thermal_cooling_device_instance *pos, *next;
mutex_lock(&tz->lock);
list_for_each_entry_safe(pos, next, &tz->cooling_devices, node) {
if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
list_del(&pos->node);
mutex_unlock(&tz->lock);
goto unbind;
}
}
mutex_unlock(&tz->lock);
return -ENODEV;
unbind:
device_remove_file(&tz->device, &pos->attr);
sysfs_remove_link(&tz->device.kobj, pos->name);
release_idr(&tz->idr, &tz->lock, pos->id);
kfree(pos);
return 0;
}
EXPORT_SYMBOL(thermal_zone_unbind_cooling_device);
static void thermal_release(struct device *dev)
{
struct thermal_zone_device *tz;
struct thermal_cooling_device *cdev;
if (!strncmp(dev_name(dev), "thermal_zone",
sizeof("thermal_zone") - 1)) {
tz = to_thermal_zone(dev);
kfree(tz);
} else {
cdev = to_cooling_device(dev);
kfree(cdev);
}
}
static struct class thermal_class = {
.name = "thermal",
.dev_release = thermal_release,
};
/**
* thermal_cooling_device_register - register a new thermal cooling device
* @type: the thermal cooling device type.
* @devdata: device private data.
* @ops: standard thermal cooling devices callbacks.
*/
struct thermal_cooling_device *
thermal_cooling_device_register(char *type, void *devdata,
const struct thermal_cooling_device_ops *ops)
{
struct thermal_cooling_device *cdev;
struct thermal_zone_device *pos;
int result;
if (strlen(type) >= THERMAL_NAME_LENGTH)
return ERR_PTR(-EINVAL);
if (!ops || !ops->get_max_state || !ops->get_cur_state ||
!ops->set_cur_state)
return ERR_PTR(-EINVAL);
cdev = kzalloc(sizeof(struct thermal_cooling_device), GFP_KERNEL);
if (!cdev)
return ERR_PTR(-ENOMEM);
result = get_idr(&thermal_cdev_idr, &thermal_idr_lock, &cdev->id);
if (result) {
kfree(cdev);
return ERR_PTR(result);
}
strcpy(cdev->type, type);
cdev->ops = ops;
cdev->device.class = &thermal_class;
cdev->devdata = devdata;
dev_set_name(&cdev->device, "cooling_device%d", cdev->id);
result = device_register(&cdev->device);
if (result) {
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
kfree(cdev);
return ERR_PTR(result);
}
/* sys I/F */
if (type) {
result = device_create_file(&cdev->device, &dev_attr_cdev_type);
if (result)
goto unregister;
}
result = device_create_file(&cdev->device, &dev_attr_max_state);
if (result)
goto unregister;
result = device_create_file(&cdev->device, &dev_attr_cur_state);
if (result)
goto unregister;
mutex_lock(&thermal_list_lock);
list_add(&cdev->node, &thermal_cdev_list);
list_for_each_entry(pos, &thermal_tz_list, node) {
if (!pos->ops->bind)
continue;
result = pos->ops->bind(pos, cdev);
if (result)
break;
}
mutex_unlock(&thermal_list_lock);
if (!result)
return cdev;
unregister:
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
device_unregister(&cdev->device);
return ERR_PTR(result);
}
EXPORT_SYMBOL(thermal_cooling_device_register);
/**
* thermal_cooling_device_unregister - removes the registered thermal cooling device
* @cdev: the thermal cooling device to remove.
*
* thermal_cooling_device_unregister() must be called when the device is no
* longer needed.
*/
void thermal_cooling_device_unregister(struct
thermal_cooling_device
*cdev)
{
struct thermal_zone_device *tz;
struct thermal_cooling_device *pos = NULL;
if (!cdev)
return;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_cdev_list, node)
if (pos == cdev)
break;
if (pos != cdev) {
/* thermal cooling device not found */
mutex_unlock(&thermal_list_lock);
return;
}
list_del(&cdev->node);
list_for_each_entry(tz, &thermal_tz_list, node) {
if (!tz->ops->unbind)
continue;
tz->ops->unbind(tz, cdev);
}
mutex_unlock(&thermal_list_lock);
if (cdev->type[0])
device_remove_file(&cdev->device, &dev_attr_cdev_type);
device_remove_file(&cdev->device, &dev_attr_max_state);
device_remove_file(&cdev->device, &dev_attr_cur_state);
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
device_unregister(&cdev->device);
return;
}
EXPORT_SYMBOL(thermal_cooling_device_unregister);
/**
* thermal_zone_device_update - force an update of a thermal zone's state
* @ttz: the thermal zone to update
*/
void thermal_zone_device_update(struct thermal_zone_device *tz)
{
int count, ret = 0;
long temp, trip_temp;
enum thermal_trip_type trip_type;
struct thermal_cooling_device_instance *instance;
struct thermal_cooling_device *cdev;
mutex_lock(&tz->lock);
if (tz->ops->get_temp(tz, &temp)) {
/* get_temp failed - retry it later */
pr_warn("failed to read out thermal zone %d\n", tz->id);
goto leave;
}
for (count = 0; count < tz->trips; count++) {
tz->ops->get_trip_type(tz, count, &trip_type);
tz->ops->get_trip_temp(tz, count, &trip_temp);
switch (trip_type) {
case THERMAL_TRIP_CRITICAL:
if (temp >= trip_temp) {
if (tz->ops->notify)
ret = tz->ops->notify(tz, count,
trip_type);
if (!ret) {
pr_emerg("Critical temperature reached (%ld C), shutting down\n",
temp/1000);
orderly_poweroff(true);
}
}
break;
case THERMAL_TRIP_HOT:
if (temp >= trip_temp)
if (tz->ops->notify)
tz->ops->notify(tz, count, trip_type);
break;
case THERMAL_TRIP_CONFIGURABLE_HI:
if (temp >= trip_temp)
if (tz->ops->notify)
tz->ops->notify(tz, count, trip_type);
break;
case THERMAL_TRIP_CONFIGURABLE_LOW:
if (temp <= trip_temp)
if (tz->ops->notify)
tz->ops->notify(tz, count, trip_type);
break;
case THERMAL_TRIP_CRITICAL_LOW:
if (temp <= trip_temp) {
if (tz->ops->notify)
ret = tz->ops->notify(tz, count,
trip_type);
if (!ret) {
printk(KERN_EMERG
"Critical temperature reached (%ld C), \
shutting down.\n", temp/1000);
orderly_poweroff(true);
}
}
break;
case THERMAL_TRIP_ACTIVE:
list_for_each_entry(instance, &tz->cooling_devices,
node) {
if (instance->trip != count)
continue;
cdev = instance->cdev;
if (temp >= trip_temp)
cdev->ops->set_cur_state(cdev, 1);
else
cdev->ops->set_cur_state(cdev, 0);
}
break;
case THERMAL_TRIP_PASSIVE:
if (temp >= trip_temp || tz->passive)
thermal_zone_device_passive(tz, temp,
trip_temp, count);
break;
}
}
if (tz->forced_passive)
thermal_zone_device_passive(tz, temp, tz->forced_passive,
THERMAL_TRIPS_NONE);
tz->last_temperature = temp;
leave:
if (tz->passive)
thermal_zone_device_set_polling(tz, tz->passive_delay);
else if (tz->polling_delay)
thermal_zone_device_set_polling(tz, tz->polling_delay);
else
thermal_zone_device_set_polling(tz, 0);
mutex_unlock(&tz->lock);
}
EXPORT_SYMBOL(thermal_zone_device_update);
/**
* thermal_zone_device_register - register a new thermal zone device
* @type: the thermal zone device type
* @trips: the number of trip points the thermal zone support
* @devdata: private device data
* @ops: standard thermal zone device callbacks
* @tc1: thermal coefficient 1 for passive calculations
* @tc2: thermal coefficient 2 for passive calculations
* @passive_delay: number of milliseconds to wait between polls when
* performing passive cooling
* @polling_delay: number of milliseconds to wait between polls when checking
* whether trip points have been crossed (0 for interrupt
* driven systems)
*
* thermal_zone_device_unregister() must be called when the device is no
* longer needed. The passive cooling formula uses tc1 and tc2 as described in
* section 11.1.5.1 of the ACPI specification 3.0.
*/
struct thermal_zone_device *thermal_zone_device_register(char *type,
int trips, void *devdata,
const struct thermal_zone_device_ops *ops,
int tc1, int tc2, int passive_delay, int polling_delay)
{
struct thermal_zone_device *tz;
struct thermal_cooling_device *pos;
enum thermal_trip_type trip_type;
int result;
int count;
int passive = 0;
if (strlen(type) >= THERMAL_NAME_LENGTH)
return ERR_PTR(-EINVAL);
if (trips > THERMAL_MAX_TRIPS || trips < 0)
return ERR_PTR(-EINVAL);
if (!ops || !ops->get_temp)
return ERR_PTR(-EINVAL);
tz = kzalloc(sizeof(struct thermal_zone_device), GFP_KERNEL);
if (!tz)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&tz->cooling_devices);
idr_init(&tz->idr);
mutex_init(&tz->lock);
result = get_idr(&thermal_tz_idr, &thermal_idr_lock, &tz->id);
if (result) {
kfree(tz);
return ERR_PTR(result);
}
strcpy(tz->type, type);
tz->ops = ops;
tz->device.class = &thermal_class;
tz->devdata = devdata;
tz->trips = trips;
tz->tc1 = tc1;
tz->tc2 = tc2;
tz->passive_delay = passive_delay;
tz->polling_delay = polling_delay;
dev_set_name(&tz->device, "thermal_zone%d", tz->id);
result = device_register(&tz->device);
if (result) {
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
kfree(tz);
return ERR_PTR(result);
}
/* sys I/F */
if (type) {
result = device_create_file(&tz->device, &dev_attr_type);
if (result)
goto unregister;
}
result = device_create_file(&tz->device, &dev_attr_temp);
if (result)
goto unregister;
if (ops->get_mode) {
result = device_create_file(&tz->device, &dev_attr_mode);
if (result)
goto unregister;
}
for (count = 0; count < trips; count++) {
result = device_create_file(&tz->device,
&trip_point_attrs[count * 2]);
if (result)
break;
result = device_create_file(&tz->device,
&trip_point_attrs[count * 2 + 1]);
if (result)
goto unregister;
tz->ops->get_trip_type(tz, count, &trip_type);
if (trip_type == THERMAL_TRIP_PASSIVE)
passive = 1;
}
if (!passive)
result = device_create_file(&tz->device,
&dev_attr_passive);
if (result)
goto unregister;
result = thermal_add_hwmon_sysfs(tz);
if (result)
goto unregister;
mutex_lock(&thermal_list_lock);
list_add_tail(&tz->node, &thermal_tz_list);
if (ops->bind)
list_for_each_entry(pos, &thermal_cdev_list, node) {
result = ops->bind(tz, pos);
if (result)
break;
}
mutex_unlock(&thermal_list_lock);
INIT_DELAYED_WORK(&(tz->poll_queue), thermal_zone_device_check);
thermal_zone_device_update(tz);
if (!result)
return tz;
unregister:
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
device_unregister(&tz->device);
return ERR_PTR(result);
}
EXPORT_SYMBOL(thermal_zone_device_register);
/**
* thermal_device_unregister - removes the registered thermal zone device
* @tz: the thermal zone device to remove
*/
void thermal_zone_device_unregister(struct thermal_zone_device *tz)
{
struct thermal_cooling_device *cdev;
struct thermal_zone_device *pos = NULL;
int count;
if (!tz)
return;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node)
if (pos == tz)
break;
if (pos != tz) {
/* thermal zone device not found */
mutex_unlock(&thermal_list_lock);
return;
}
list_del(&tz->node);
if (tz->ops->unbind)
list_for_each_entry(cdev, &thermal_cdev_list, node)
tz->ops->unbind(tz, cdev);
mutex_unlock(&thermal_list_lock);
thermal_zone_device_set_polling(tz, 0);
if (tz->type[0])
device_remove_file(&tz->device, &dev_attr_type);
device_remove_file(&tz->device, &dev_attr_temp);
if (tz->ops->get_mode)
device_remove_file(&tz->device, &dev_attr_mode);
for (count = 0; count < tz->trips; count++) {
device_remove_file(&tz->device,
&trip_point_attrs[count * 2]);
device_remove_file(&tz->device,
&trip_point_attrs[count * 2 + 1]);
}
thermal_remove_hwmon_sysfs(tz);
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
idr_destroy(&tz->idr);
mutex_destroy(&tz->lock);
device_unregister(&tz->device);
return;
}
EXPORT_SYMBOL(thermal_zone_device_unregister);
#ifdef CONFIG_NET
static struct genl_family thermal_event_genl_family = {
.id = GENL_ID_GENERATE,
.name = THERMAL_GENL_FAMILY_NAME,
.version = THERMAL_GENL_VERSION,
.maxattr = THERMAL_GENL_ATTR_MAX,
};
static struct genl_multicast_group thermal_event_mcgrp = {
.name = THERMAL_GENL_MCAST_GROUP_NAME,
};
int thermal_generate_netlink_event(u32 orig, enum events event)
{
struct sk_buff *skb;
struct nlattr *attr;
struct thermal_genl_event *thermal_event;
void *msg_header;
int size;
int result;
static unsigned int thermal_event_seqnum;
/* allocate memory */
size = nla_total_size(sizeof(struct thermal_genl_event)) +
nla_total_size(0);
skb = genlmsg_new(size, GFP_ATOMIC);
if (!skb)
return -ENOMEM;
/* add the genetlink message header */
msg_header = genlmsg_put(skb, 0, thermal_event_seqnum++,
&thermal_event_genl_family, 0,
THERMAL_GENL_CMD_EVENT);
if (!msg_header) {
nlmsg_free(skb);
return -ENOMEM;
}
/* fill the data */
attr = nla_reserve(skb, THERMAL_GENL_ATTR_EVENT,
sizeof(struct thermal_genl_event));
if (!attr) {
nlmsg_free(skb);
return -EINVAL;
}
thermal_event = nla_data(attr);
if (!thermal_event) {
nlmsg_free(skb);
return -EINVAL;
}
memset(thermal_event, 0, sizeof(struct thermal_genl_event));
thermal_event->orig = orig;
thermal_event->event = event;
/* send multicast genetlink message */
result = genlmsg_end(skb, msg_header);
if (result < 0) {
nlmsg_free(skb);
return result;
}
result = genlmsg_multicast(skb, 0, thermal_event_mcgrp.id, GFP_ATOMIC);
if (result)
pr_info("failed to send netlink event:%d\n", result);
return result;
}
EXPORT_SYMBOL(thermal_generate_netlink_event);
static int genetlink_init(void)
{
int result;
result = genl_register_family(&thermal_event_genl_family);
if (result)
return result;
result = genl_register_mc_group(&thermal_event_genl_family,
&thermal_event_mcgrp);
if (result)
genl_unregister_family(&thermal_event_genl_family);
return result;
}
static void genetlink_exit(void)
{
genl_unregister_family(&thermal_event_genl_family);
}
#else /* !CONFIG_NET */
static inline int genetlink_init(void) { return 0; }
static inline void genetlink_exit(void) {}
#endif /* !CONFIG_NET */
static int __init thermal_init(void)
{
int result = 0;
result = class_register(&thermal_class);
if (result) {
idr_destroy(&thermal_tz_idr);
idr_destroy(&thermal_cdev_idr);
mutex_destroy(&thermal_idr_lock);
mutex_destroy(&thermal_list_lock);
}
result = genetlink_init();
return result;
}
static void __exit thermal_exit(void)
{
class_unregister(&thermal_class);
idr_destroy(&thermal_tz_idr);
idr_destroy(&thermal_cdev_idr);
mutex_destroy(&thermal_idr_lock);
mutex_destroy(&thermal_list_lock);
genetlink_exit();
}
fs_initcall(thermal_init);
module_exit(thermal_exit);
| gpl-2.0 |
networkosnet/linux | sound/isa/sb/sb16_main.c | 1248 | 27152 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Routines for control of 16-bit SoundBlaster cards and clones
* Note: This is very ugly hardware which uses one 8-bit DMA channel and
* second 16-bit DMA channel. Unfortunately 8-bit DMA channel can't
* transfer 16-bit samples and 16-bit DMA channels can't transfer
* 8-bit samples. This make full duplex more complicated than
* can be... People, don't buy these soundcards for full 16-bit
* duplex!!!
* Note: 16-bit wide is assigned to first direction which made request.
* With full duplex - playback is preferred with abstract layer.
*
* Note: Some chip revisions have hardware bug. Changing capture
* channel from full-duplex 8bit DMA to 16bit DMA will block
* 16bit DMA transfers from DSP chip (capture) until 8bit transfer
* to DSP chip (playback) starts. This bug can be avoided with
* "16bit DMA Allocation" setting set to Playback or Capture.
*
*
* 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/io.h>
#include <asm/dma.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/sb.h>
#include <sound/sb16_csp.h>
#include <sound/mpu401.h>
#include <sound/control.h>
#include <sound/info.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Routines for control of 16-bit SoundBlaster cards and clones");
MODULE_LICENSE("GPL");
#ifdef CONFIG_SND_SB16_CSP
static void snd_sb16_csp_playback_prepare(struct snd_sb *chip, struct snd_pcm_runtime *runtime)
{
if (chip->hardware == SB_HW_16CSP) {
struct snd_sb_csp *csp = chip->csp;
if (csp->running & SNDRV_SB_CSP_ST_LOADED) {
/* manually loaded codec */
if ((csp->mode & SNDRV_SB_CSP_MODE_DSP_WRITE) &&
((1U << runtime->format) == csp->acc_format)) {
/* Supported runtime PCM format for playback */
if (csp->ops.csp_use(csp) == 0) {
/* If CSP was successfully acquired */
goto __start_CSP;
}
} else if ((csp->mode & SNDRV_SB_CSP_MODE_QSOUND) && (csp->q_enabled)) {
/* QSound decoder is loaded and enabled */
if ((1 << runtime->format) & (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8 |
SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE)) {
/* Only for simple PCM formats */
if (csp->ops.csp_use(csp) == 0) {
/* If CSP was successfully acquired */
goto __start_CSP;
}
}
}
} else if (csp->ops.csp_use(csp) == 0) {
/* Acquire CSP and try to autoload hardware codec */
if (csp->ops.csp_autoload(csp, runtime->format, SNDRV_SB_CSP_MODE_DSP_WRITE)) {
/* Unsupported format, release CSP */
csp->ops.csp_unuse(csp);
} else {
__start_CSP:
/* Try to start CSP */
if (csp->ops.csp_start(csp, (chip->mode & SB_MODE_PLAYBACK_16) ?
SNDRV_SB_CSP_SAMPLE_16BIT : SNDRV_SB_CSP_SAMPLE_8BIT,
(runtime->channels > 1) ?
SNDRV_SB_CSP_STEREO : SNDRV_SB_CSP_MONO)) {
/* Failed, release CSP */
csp->ops.csp_unuse(csp);
} else {
/* Success, CSP acquired and running */
chip->open = SNDRV_SB_CSP_MODE_DSP_WRITE;
}
}
}
}
}
static void snd_sb16_csp_capture_prepare(struct snd_sb *chip, struct snd_pcm_runtime *runtime)
{
if (chip->hardware == SB_HW_16CSP) {
struct snd_sb_csp *csp = chip->csp;
if (csp->running & SNDRV_SB_CSP_ST_LOADED) {
/* manually loaded codec */
if ((csp->mode & SNDRV_SB_CSP_MODE_DSP_READ) &&
((1U << runtime->format) == csp->acc_format)) {
/* Supported runtime PCM format for capture */
if (csp->ops.csp_use(csp) == 0) {
/* If CSP was successfully acquired */
goto __start_CSP;
}
}
} else if (csp->ops.csp_use(csp) == 0) {
/* Acquire CSP and try to autoload hardware codec */
if (csp->ops.csp_autoload(csp, runtime->format, SNDRV_SB_CSP_MODE_DSP_READ)) {
/* Unsupported format, release CSP */
csp->ops.csp_unuse(csp);
} else {
__start_CSP:
/* Try to start CSP */
if (csp->ops.csp_start(csp, (chip->mode & SB_MODE_CAPTURE_16) ?
SNDRV_SB_CSP_SAMPLE_16BIT : SNDRV_SB_CSP_SAMPLE_8BIT,
(runtime->channels > 1) ?
SNDRV_SB_CSP_STEREO : SNDRV_SB_CSP_MONO)) {
/* Failed, release CSP */
csp->ops.csp_unuse(csp);
} else {
/* Success, CSP acquired and running */
chip->open = SNDRV_SB_CSP_MODE_DSP_READ;
}
}
}
}
}
static void snd_sb16_csp_update(struct snd_sb *chip)
{
if (chip->hardware == SB_HW_16CSP) {
struct snd_sb_csp *csp = chip->csp;
if (csp->qpos_changed) {
spin_lock(&chip->reg_lock);
csp->ops.csp_qsound_transfer (csp);
spin_unlock(&chip->reg_lock);
}
}
}
static void snd_sb16_csp_playback_open(struct snd_sb *chip, struct snd_pcm_runtime *runtime)
{
/* CSP decoders (QSound excluded) support only 16bit transfers */
if (chip->hardware == SB_HW_16CSP) {
struct snd_sb_csp *csp = chip->csp;
if (csp->running & SNDRV_SB_CSP_ST_LOADED) {
/* manually loaded codec */
if (csp->mode & SNDRV_SB_CSP_MODE_DSP_WRITE) {
runtime->hw.formats |= csp->acc_format;
}
} else {
/* autoloaded codecs */
runtime->hw.formats |= SNDRV_PCM_FMTBIT_MU_LAW | SNDRV_PCM_FMTBIT_A_LAW |
SNDRV_PCM_FMTBIT_IMA_ADPCM;
}
}
}
static void snd_sb16_csp_playback_close(struct snd_sb *chip)
{
if ((chip->hardware == SB_HW_16CSP) && (chip->open == SNDRV_SB_CSP_MODE_DSP_WRITE)) {
struct snd_sb_csp *csp = chip->csp;
if (csp->ops.csp_stop(csp) == 0) {
csp->ops.csp_unuse(csp);
chip->open = 0;
}
}
}
static void snd_sb16_csp_capture_open(struct snd_sb *chip, struct snd_pcm_runtime *runtime)
{
/* CSP coders support only 16bit transfers */
if (chip->hardware == SB_HW_16CSP) {
struct snd_sb_csp *csp = chip->csp;
if (csp->running & SNDRV_SB_CSP_ST_LOADED) {
/* manually loaded codec */
if (csp->mode & SNDRV_SB_CSP_MODE_DSP_READ) {
runtime->hw.formats |= csp->acc_format;
}
} else {
/* autoloaded codecs */
runtime->hw.formats |= SNDRV_PCM_FMTBIT_MU_LAW | SNDRV_PCM_FMTBIT_A_LAW |
SNDRV_PCM_FMTBIT_IMA_ADPCM;
}
}
}
static void snd_sb16_csp_capture_close(struct snd_sb *chip)
{
if ((chip->hardware == SB_HW_16CSP) && (chip->open == SNDRV_SB_CSP_MODE_DSP_READ)) {
struct snd_sb_csp *csp = chip->csp;
if (csp->ops.csp_stop(csp) == 0) {
csp->ops.csp_unuse(csp);
chip->open = 0;
}
}
}
#else
#define snd_sb16_csp_playback_prepare(chip, runtime) /*nop*/
#define snd_sb16_csp_capture_prepare(chip, runtime) /*nop*/
#define snd_sb16_csp_update(chip) /*nop*/
#define snd_sb16_csp_playback_open(chip, runtime) /*nop*/
#define snd_sb16_csp_playback_close(chip) /*nop*/
#define snd_sb16_csp_capture_open(chip, runtime) /*nop*/
#define snd_sb16_csp_capture_close(chip) /*nop*/
#endif
static void snd_sb16_setup_rate(struct snd_sb *chip,
unsigned short rate,
int channel)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->mode & (channel == SNDRV_PCM_STREAM_PLAYBACK ? SB_MODE_PLAYBACK_16 : SB_MODE_CAPTURE_16))
snd_sb_ack_16bit(chip);
else
snd_sb_ack_8bit(chip);
if (!(chip->mode & SB_RATE_LOCK)) {
chip->locked_rate = rate;
snd_sbdsp_command(chip, SB_DSP_SAMPLE_RATE_IN);
snd_sbdsp_command(chip, rate >> 8);
snd_sbdsp_command(chip, rate & 0xff);
snd_sbdsp_command(chip, SB_DSP_SAMPLE_RATE_OUT);
snd_sbdsp_command(chip, rate >> 8);
snd_sbdsp_command(chip, rate & 0xff);
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static int snd_sb16_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_sb16_hw_free(struct snd_pcm_substream *substream)
{
snd_pcm_lib_free_pages(substream);
return 0;
}
static int snd_sb16_playback_prepare(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned char format;
unsigned int size, count, dma;
snd_sb16_csp_playback_prepare(chip, runtime);
if (snd_pcm_format_unsigned(runtime->format) > 0) {
format = runtime->channels > 1 ? SB_DSP4_MODE_UNS_STEREO : SB_DSP4_MODE_UNS_MONO;
} else {
format = runtime->channels > 1 ? SB_DSP4_MODE_SIGN_STEREO : SB_DSP4_MODE_SIGN_MONO;
}
snd_sb16_setup_rate(chip, runtime->rate, SNDRV_PCM_STREAM_PLAYBACK);
size = chip->p_dma_size = snd_pcm_lib_buffer_bytes(substream);
dma = (chip->mode & SB_MODE_PLAYBACK_8) ? chip->dma8 : chip->dma16;
snd_dma_program(dma, runtime->dma_addr, size, DMA_MODE_WRITE | DMA_AUTOINIT);
count = snd_pcm_lib_period_bytes(substream);
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->mode & SB_MODE_PLAYBACK_16) {
count >>= 1;
count--;
snd_sbdsp_command(chip, SB_DSP4_OUT16_AI);
snd_sbdsp_command(chip, format);
snd_sbdsp_command(chip, count & 0xff);
snd_sbdsp_command(chip, count >> 8);
snd_sbdsp_command(chip, SB_DSP_DMA16_OFF);
} else {
count--;
snd_sbdsp_command(chip, SB_DSP4_OUT8_AI);
snd_sbdsp_command(chip, format);
snd_sbdsp_command(chip, count & 0xff);
snd_sbdsp_command(chip, count >> 8);
snd_sbdsp_command(chip, SB_DSP_DMA8_OFF);
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_sb16_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_sb *chip = snd_pcm_substream_chip(substream);
int result = 0;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
chip->mode |= SB_RATE_LOCK_PLAYBACK;
snd_sbdsp_command(chip, chip->mode & SB_MODE_PLAYBACK_16 ? SB_DSP_DMA16_ON : SB_DSP_DMA8_ON);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
snd_sbdsp_command(chip, chip->mode & SB_MODE_PLAYBACK_16 ? SB_DSP_DMA16_OFF : SB_DSP_DMA8_OFF);
/* next two lines are needed for some types of DSP4 (SB AWE 32 - 4.13) */
if (chip->mode & SB_RATE_LOCK_CAPTURE)
snd_sbdsp_command(chip, chip->mode & SB_MODE_CAPTURE_16 ? SB_DSP_DMA16_ON : SB_DSP_DMA8_ON);
chip->mode &= ~SB_RATE_LOCK_PLAYBACK;
break;
default:
result = -EINVAL;
}
spin_unlock(&chip->reg_lock);
return result;
}
static int snd_sb16_capture_prepare(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned char format;
unsigned int size, count, dma;
snd_sb16_csp_capture_prepare(chip, runtime);
if (snd_pcm_format_unsigned(runtime->format) > 0) {
format = runtime->channels > 1 ? SB_DSP4_MODE_UNS_STEREO : SB_DSP4_MODE_UNS_MONO;
} else {
format = runtime->channels > 1 ? SB_DSP4_MODE_SIGN_STEREO : SB_DSP4_MODE_SIGN_MONO;
}
snd_sb16_setup_rate(chip, runtime->rate, SNDRV_PCM_STREAM_CAPTURE);
size = chip->c_dma_size = snd_pcm_lib_buffer_bytes(substream);
dma = (chip->mode & SB_MODE_CAPTURE_8) ? chip->dma8 : chip->dma16;
snd_dma_program(dma, runtime->dma_addr, size, DMA_MODE_READ | DMA_AUTOINIT);
count = snd_pcm_lib_period_bytes(substream);
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->mode & SB_MODE_CAPTURE_16) {
count >>= 1;
count--;
snd_sbdsp_command(chip, SB_DSP4_IN16_AI);
snd_sbdsp_command(chip, format);
snd_sbdsp_command(chip, count & 0xff);
snd_sbdsp_command(chip, count >> 8);
snd_sbdsp_command(chip, SB_DSP_DMA16_OFF);
} else {
count--;
snd_sbdsp_command(chip, SB_DSP4_IN8_AI);
snd_sbdsp_command(chip, format);
snd_sbdsp_command(chip, count & 0xff);
snd_sbdsp_command(chip, count >> 8);
snd_sbdsp_command(chip, SB_DSP_DMA8_OFF);
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_sb16_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_sb *chip = snd_pcm_substream_chip(substream);
int result = 0;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
chip->mode |= SB_RATE_LOCK_CAPTURE;
snd_sbdsp_command(chip, chip->mode & SB_MODE_CAPTURE_16 ? SB_DSP_DMA16_ON : SB_DSP_DMA8_ON);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
snd_sbdsp_command(chip, chip->mode & SB_MODE_CAPTURE_16 ? SB_DSP_DMA16_OFF : SB_DSP_DMA8_OFF);
/* next two lines are needed for some types of DSP4 (SB AWE 32 - 4.13) */
if (chip->mode & SB_RATE_LOCK_PLAYBACK)
snd_sbdsp_command(chip, chip->mode & SB_MODE_PLAYBACK_16 ? SB_DSP_DMA16_ON : SB_DSP_DMA8_ON);
chip->mode &= ~SB_RATE_LOCK_CAPTURE;
break;
default:
result = -EINVAL;
}
spin_unlock(&chip->reg_lock);
return result;
}
irqreturn_t snd_sb16dsp_interrupt(int irq, void *dev_id)
{
struct snd_sb *chip = dev_id;
unsigned char status;
int ok;
spin_lock(&chip->mixer_lock);
status = snd_sbmixer_read(chip, SB_DSP4_IRQSTATUS);
spin_unlock(&chip->mixer_lock);
if ((status & SB_IRQTYPE_MPUIN) && chip->rmidi_callback)
chip->rmidi_callback(irq, chip->rmidi->private_data);
if (status & SB_IRQTYPE_8BIT) {
ok = 0;
if (chip->mode & SB_MODE_PLAYBACK_8) {
snd_pcm_period_elapsed(chip->playback_substream);
snd_sb16_csp_update(chip);
ok++;
}
if (chip->mode & SB_MODE_CAPTURE_8) {
snd_pcm_period_elapsed(chip->capture_substream);
ok++;
}
spin_lock(&chip->reg_lock);
if (!ok)
snd_sbdsp_command(chip, SB_DSP_DMA8_OFF);
snd_sb_ack_8bit(chip);
spin_unlock(&chip->reg_lock);
}
if (status & SB_IRQTYPE_16BIT) {
ok = 0;
if (chip->mode & SB_MODE_PLAYBACK_16) {
snd_pcm_period_elapsed(chip->playback_substream);
snd_sb16_csp_update(chip);
ok++;
}
if (chip->mode & SB_MODE_CAPTURE_16) {
snd_pcm_period_elapsed(chip->capture_substream);
ok++;
}
spin_lock(&chip->reg_lock);
if (!ok)
snd_sbdsp_command(chip, SB_DSP_DMA16_OFF);
snd_sb_ack_16bit(chip);
spin_unlock(&chip->reg_lock);
}
return IRQ_HANDLED;
}
/*
*/
static snd_pcm_uframes_t snd_sb16_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_sb *chip = snd_pcm_substream_chip(substream);
unsigned int dma;
size_t ptr;
dma = (chip->mode & SB_MODE_PLAYBACK_8) ? chip->dma8 : chip->dma16;
ptr = snd_dma_pointer(dma, chip->p_dma_size);
return bytes_to_frames(substream->runtime, ptr);
}
static snd_pcm_uframes_t snd_sb16_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_sb *chip = snd_pcm_substream_chip(substream);
unsigned int dma;
size_t ptr;
dma = (chip->mode & SB_MODE_CAPTURE_8) ? chip->dma8 : chip->dma16;
ptr = snd_dma_pointer(dma, chip->c_dma_size);
return bytes_to_frames(substream->runtime, ptr);
}
/*
*/
static struct snd_pcm_hardware snd_sb16_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = 0,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_44100,
.rate_min = 4000,
.rate_max = 44100,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_sb16_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = 0,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_44100,
.rate_min = 4000,
.rate_max = 44100,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
/*
* open/close
*/
static int snd_sb16_playback_open(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
spin_lock_irqsave(&chip->open_lock, flags);
if (chip->mode & SB_MODE_PLAYBACK) {
spin_unlock_irqrestore(&chip->open_lock, flags);
return -EAGAIN;
}
runtime->hw = snd_sb16_playback;
/* skip if 16 bit DMA was reserved for capture */
if (chip->force_mode16 & SB_MODE_CAPTURE_16)
goto __skip_16bit;
if (chip->dma16 >= 0 && !(chip->mode & SB_MODE_CAPTURE_16)) {
chip->mode |= SB_MODE_PLAYBACK_16;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE;
/* Vibra16X hack */
if (chip->dma16 <= 3) {
runtime->hw.buffer_bytes_max =
runtime->hw.period_bytes_max = 64 * 1024;
} else {
snd_sb16_csp_playback_open(chip, runtime);
}
goto __open_ok;
}
__skip_16bit:
if (chip->dma8 >= 0 && !(chip->mode & SB_MODE_CAPTURE_8)) {
chip->mode |= SB_MODE_PLAYBACK_8;
/* DSP v 4.xx can transfer 16bit data through 8bit DMA channel, SBHWPG 2-7 */
if (chip->dma16 < 0) {
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE;
chip->mode |= SB_MODE_PLAYBACK_16;
} else {
runtime->hw.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8;
}
runtime->hw.buffer_bytes_max =
runtime->hw.period_bytes_max = 64 * 1024;
goto __open_ok;
}
spin_unlock_irqrestore(&chip->open_lock, flags);
return -EAGAIN;
__open_ok:
if (chip->hardware == SB_HW_ALS100)
runtime->hw.rate_max = 48000;
if (chip->hardware == SB_HW_CS5530) {
runtime->hw.buffer_bytes_max = 32 * 1024;
runtime->hw.periods_min = 2;
runtime->hw.rate_min = 44100;
}
if (chip->mode & SB_RATE_LOCK)
runtime->hw.rate_min = runtime->hw.rate_max = chip->locked_rate;
chip->playback_substream = substream;
spin_unlock_irqrestore(&chip->open_lock, flags);
return 0;
}
static int snd_sb16_playback_close(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
snd_sb16_csp_playback_close(chip);
spin_lock_irqsave(&chip->open_lock, flags);
chip->playback_substream = NULL;
chip->mode &= ~SB_MODE_PLAYBACK;
spin_unlock_irqrestore(&chip->open_lock, flags);
return 0;
}
static int snd_sb16_capture_open(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
spin_lock_irqsave(&chip->open_lock, flags);
if (chip->mode & SB_MODE_CAPTURE) {
spin_unlock_irqrestore(&chip->open_lock, flags);
return -EAGAIN;
}
runtime->hw = snd_sb16_capture;
/* skip if 16 bit DMA was reserved for playback */
if (chip->force_mode16 & SB_MODE_PLAYBACK_16)
goto __skip_16bit;
if (chip->dma16 >= 0 && !(chip->mode & SB_MODE_PLAYBACK_16)) {
chip->mode |= SB_MODE_CAPTURE_16;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE;
/* Vibra16X hack */
if (chip->dma16 <= 3) {
runtime->hw.buffer_bytes_max =
runtime->hw.period_bytes_max = 64 * 1024;
} else {
snd_sb16_csp_capture_open(chip, runtime);
}
goto __open_ok;
}
__skip_16bit:
if (chip->dma8 >= 0 && !(chip->mode & SB_MODE_PLAYBACK_8)) {
chip->mode |= SB_MODE_CAPTURE_8;
/* DSP v 4.xx can transfer 16bit data through 8bit DMA channel, SBHWPG 2-7 */
if (chip->dma16 < 0) {
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE;
chip->mode |= SB_MODE_CAPTURE_16;
} else {
runtime->hw.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8;
}
runtime->hw.buffer_bytes_max =
runtime->hw.period_bytes_max = 64 * 1024;
goto __open_ok;
}
spin_unlock_irqrestore(&chip->open_lock, flags);
return -EAGAIN;
__open_ok:
if (chip->hardware == SB_HW_ALS100)
runtime->hw.rate_max = 48000;
if (chip->hardware == SB_HW_CS5530) {
runtime->hw.buffer_bytes_max = 32 * 1024;
runtime->hw.periods_min = 2;
runtime->hw.rate_min = 44100;
}
if (chip->mode & SB_RATE_LOCK)
runtime->hw.rate_min = runtime->hw.rate_max = chip->locked_rate;
chip->capture_substream = substream;
spin_unlock_irqrestore(&chip->open_lock, flags);
return 0;
}
static int snd_sb16_capture_close(struct snd_pcm_substream *substream)
{
unsigned long flags;
struct snd_sb *chip = snd_pcm_substream_chip(substream);
snd_sb16_csp_capture_close(chip);
spin_lock_irqsave(&chip->open_lock, flags);
chip->capture_substream = NULL;
chip->mode &= ~SB_MODE_CAPTURE;
spin_unlock_irqrestore(&chip->open_lock, flags);
return 0;
}
/*
* DMA control interface
*/
static int snd_sb16_set_dma_mode(struct snd_sb *chip, int what)
{
if (chip->dma8 < 0 || chip->dma16 < 0) {
if (snd_BUG_ON(what))
return -EINVAL;
return 0;
}
if (what == 0) {
chip->force_mode16 = 0;
} else if (what == 1) {
chip->force_mode16 = SB_MODE_PLAYBACK_16;
} else if (what == 2) {
chip->force_mode16 = SB_MODE_CAPTURE_16;
} else {
return -EINVAL;
}
return 0;
}
static int snd_sb16_get_dma_mode(struct snd_sb *chip)
{
if (chip->dma8 < 0 || chip->dma16 < 0)
return 0;
switch (chip->force_mode16) {
case SB_MODE_PLAYBACK_16:
return 1;
case SB_MODE_CAPTURE_16:
return 2;
default:
return 0;
}
}
static int snd_sb16_dma_control_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static const char * const texts[3] = {
"Auto", "Playback", "Capture"
};
return snd_ctl_enum_info(uinfo, 1, 3, texts);
}
static int snd_sb16_dma_control_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_sb *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
ucontrol->value.enumerated.item[0] = snd_sb16_get_dma_mode(chip);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_sb16_dma_control_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_sb *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
unsigned char nval, oval;
int change;
if ((nval = ucontrol->value.enumerated.item[0]) > 2)
return -EINVAL;
spin_lock_irqsave(&chip->reg_lock, flags);
oval = snd_sb16_get_dma_mode(chip);
change = nval != oval;
snd_sb16_set_dma_mode(chip, nval);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return change;
}
static struct snd_kcontrol_new snd_sb16_dma_control = {
.iface = SNDRV_CTL_ELEM_IFACE_CARD,
.name = "16-bit DMA Allocation",
.info = snd_sb16_dma_control_info,
.get = snd_sb16_dma_control_get,
.put = snd_sb16_dma_control_put
};
/*
* Initialization part
*/
int snd_sb16dsp_configure(struct snd_sb * chip)
{
unsigned long flags;
unsigned char irqreg = 0, dmareg = 0, mpureg;
unsigned char realirq, realdma, realmpureg;
/* note: mpu register should be present only on SB16 Vibra soundcards */
// printk(KERN_DEBUG "codec->irq=%i, codec->dma8=%i, codec->dma16=%i\n", chip->irq, chip->dma8, chip->dma16);
spin_lock_irqsave(&chip->mixer_lock, flags);
mpureg = snd_sbmixer_read(chip, SB_DSP4_MPUSETUP) & ~0x06;
spin_unlock_irqrestore(&chip->mixer_lock, flags);
switch (chip->irq) {
case 2:
case 9:
irqreg |= SB_IRQSETUP_IRQ9;
break;
case 5:
irqreg |= SB_IRQSETUP_IRQ5;
break;
case 7:
irqreg |= SB_IRQSETUP_IRQ7;
break;
case 10:
irqreg |= SB_IRQSETUP_IRQ10;
break;
default:
return -EINVAL;
}
if (chip->dma8 >= 0) {
switch (chip->dma8) {
case 0:
dmareg |= SB_DMASETUP_DMA0;
break;
case 1:
dmareg |= SB_DMASETUP_DMA1;
break;
case 3:
dmareg |= SB_DMASETUP_DMA3;
break;
default:
return -EINVAL;
}
}
if (chip->dma16 >= 0 && chip->dma16 != chip->dma8) {
switch (chip->dma16) {
case 5:
dmareg |= SB_DMASETUP_DMA5;
break;
case 6:
dmareg |= SB_DMASETUP_DMA6;
break;
case 7:
dmareg |= SB_DMASETUP_DMA7;
break;
default:
return -EINVAL;
}
}
switch (chip->mpu_port) {
case 0x300:
mpureg |= 0x04;
break;
case 0x330:
mpureg |= 0x00;
break;
default:
mpureg |= 0x02; /* disable MPU */
}
spin_lock_irqsave(&chip->mixer_lock, flags);
snd_sbmixer_write(chip, SB_DSP4_IRQSETUP, irqreg);
realirq = snd_sbmixer_read(chip, SB_DSP4_IRQSETUP);
snd_sbmixer_write(chip, SB_DSP4_DMASETUP, dmareg);
realdma = snd_sbmixer_read(chip, SB_DSP4_DMASETUP);
snd_sbmixer_write(chip, SB_DSP4_MPUSETUP, mpureg);
realmpureg = snd_sbmixer_read(chip, SB_DSP4_MPUSETUP);
spin_unlock_irqrestore(&chip->mixer_lock, flags);
if ((~realirq) & irqreg || (~realdma) & dmareg) {
snd_printk(KERN_ERR "SB16 [0x%lx]: unable to set DMA & IRQ (PnP device?)\n", chip->port);
snd_printk(KERN_ERR "SB16 [0x%lx]: wanted: irqreg=0x%x, dmareg=0x%x, mpureg = 0x%x\n", chip->port, realirq, realdma, realmpureg);
snd_printk(KERN_ERR "SB16 [0x%lx]: got: irqreg=0x%x, dmareg=0x%x, mpureg = 0x%x\n", chip->port, irqreg, dmareg, mpureg);
return -ENODEV;
}
return 0;
}
static struct snd_pcm_ops snd_sb16_playback_ops = {
.open = snd_sb16_playback_open,
.close = snd_sb16_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_sb16_hw_params,
.hw_free = snd_sb16_hw_free,
.prepare = snd_sb16_playback_prepare,
.trigger = snd_sb16_playback_trigger,
.pointer = snd_sb16_playback_pointer,
};
static struct snd_pcm_ops snd_sb16_capture_ops = {
.open = snd_sb16_capture_open,
.close = snd_sb16_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_sb16_hw_params,
.hw_free = snd_sb16_hw_free,
.prepare = snd_sb16_capture_prepare,
.trigger = snd_sb16_capture_trigger,
.pointer = snd_sb16_capture_pointer,
};
int snd_sb16dsp_pcm(struct snd_sb *chip, int device)
{
struct snd_card *card = chip->card;
struct snd_pcm *pcm;
int err;
if ((err = snd_pcm_new(card, "SB16 DSP", device, 1, 1, &pcm)) < 0)
return err;
sprintf(pcm->name, "DSP v%i.%i", chip->version >> 8, chip->version & 0xff);
pcm->info_flags = SNDRV_PCM_INFO_JOINT_DUPLEX;
pcm->private_data = chip;
chip->pcm = pcm;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_sb16_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_sb16_capture_ops);
if (chip->dma16 >= 0 && chip->dma8 != chip->dma16)
snd_ctl_add(card, snd_ctl_new1(&snd_sb16_dma_control, chip));
else
pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_isa_data(),
64*1024, 128*1024);
return 0;
}
const struct snd_pcm_ops *snd_sb16dsp_get_pcm_ops(int direction)
{
return direction == SNDRV_PCM_STREAM_PLAYBACK ?
&snd_sb16_playback_ops : &snd_sb16_capture_ops;
}
EXPORT_SYMBOL(snd_sb16dsp_pcm);
EXPORT_SYMBOL(snd_sb16dsp_get_pcm_ops);
EXPORT_SYMBOL(snd_sb16dsp_configure);
EXPORT_SYMBOL(snd_sb16dsp_interrupt);
/*
* INIT part
*/
static int __init alsa_sb16_init(void)
{
return 0;
}
static void __exit alsa_sb16_exit(void)
{
}
module_init(alsa_sb16_init)
module_exit(alsa_sb16_exit)
| gpl-2.0 |
PyYoshi/b2g_kernel_sharp_is01 | arch/mips/pci/pci-rc32434.c | 1504 | 7505 | /*
* BRIEF MODULE DESCRIPTION
* PCI initialization for IDT EB434 board
*
* Copyright 2004 IDT Inc. (rischelp@idt.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/mach-rc32434/rc32434.h>
#include <asm/mach-rc32434/pci.h>
#define PCI_ACCESS_READ 0
#define PCI_ACCESS_WRITE 1
/* define an unsigned array for the PCI registers */
static unsigned int korina_cnfg_regs[25] = {
KORINA_CNFG1, KORINA_CNFG2, KORINA_CNFG3, KORINA_CNFG4,
KORINA_CNFG5, KORINA_CNFG6, KORINA_CNFG7, KORINA_CNFG8,
KORINA_CNFG9, KORINA_CNFG10, KORINA_CNFG11, KORINA_CNFG12,
KORINA_CNFG13, KORINA_CNFG14, KORINA_CNFG15, KORINA_CNFG16,
KORINA_CNFG17, KORINA_CNFG18, KORINA_CNFG19, KORINA_CNFG20,
KORINA_CNFG21, KORINA_CNFG22, KORINA_CNFG23, KORINA_CNFG24
};
static struct resource rc32434_res_pci_mem1;
static struct resource rc32434_res_pci_mem2;
static struct resource rc32434_res_pci_mem1 = {
.name = "PCI MEM1",
.start = 0x50000000,
.end = 0x5FFFFFFF,
.flags = IORESOURCE_MEM,
.parent = &rc32434_res_pci_mem1,
.sibling = NULL,
.child = &rc32434_res_pci_mem2
};
static struct resource rc32434_res_pci_mem2 = {
.name = "PCI Mem2",
.start = 0x60000000,
.end = 0x6FFFFFFF,
.flags = IORESOURCE_MEM,
.parent = &rc32434_res_pci_mem1,
.sibling = NULL,
.child = NULL
};
static struct resource rc32434_res_pci_io1 = {
.name = "PCI I/O1",
.start = 0x18800000,
.end = 0x188FFFFF,
.flags = IORESOURCE_IO,
};
extern struct pci_ops rc32434_pci_ops;
#define PCI_MEM1_START PCI_ADDR_START
#define PCI_MEM1_END (PCI_ADDR_START + CPUTOPCI_MEM_WIN - 1)
#define PCI_MEM2_START (PCI_ADDR_START + CPUTOPCI_MEM_WIN)
#define PCI_MEM2_END (PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) - 1)
#define PCI_IO1_START (PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN))
#define PCI_IO1_END \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + CPUTOPCI_IO_WIN - 1)
#define PCI_IO2_START \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + CPUTOPCI_IO_WIN)
#define PCI_IO2_END \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + (2 * CPUTOPCI_IO_WIN) - 1)
struct pci_controller rc32434_controller2;
struct pci_controller rc32434_controller = {
.pci_ops = &rc32434_pci_ops,
.mem_resource = &rc32434_res_pci_mem1,
.io_resource = &rc32434_res_pci_io1,
.mem_offset = 0,
.io_offset = 0,
};
#ifdef __MIPSEB__
#define PCI_ENDIAN_FLAG PCILBAC_sb_m
#else
#define PCI_ENDIAN_FLAG 0
#endif
static int __init rc32434_pcibridge_init(void)
{
unsigned int pcicvalue, pcicdata = 0;
unsigned int dummyread, pcicntlval;
int loopCount;
unsigned int pci_config_addr;
pcicvalue = rc32434_pci->pcic;
pcicvalue = (pcicvalue >> PCIM_SHFT) & PCIM_BIT_LEN;
if (!((pcicvalue == PCIM_H_EA) ||
(pcicvalue == PCIM_H_IA_FIX) ||
(pcicvalue == PCIM_H_IA_RR))) {
pr_err(KERN_ERR "PCI init error!!!\n");
/* Not in Host Mode, return ERROR */
return -1;
}
/* Enables the Idle Grant mode, Arbiter Parking */
pcicdata |= (PCI_CTL_IGM | PCI_CTL_EAP | PCI_CTL_EN);
rc32434_pci->pcic = pcicdata; /* Enable the PCI bus Interface */
/* Zero out the PCI status & PCI Status Mask */
for (;;) {
pcicdata = rc32434_pci->pcis;
if (!(pcicdata & PCI_STAT_RIP))
break;
}
rc32434_pci->pcis = 0;
rc32434_pci->pcism = 0xFFFFFFFF;
/* Zero out the PCI decoupled registers */
rc32434_pci->pcidac = 0; /*
* disable PCI decoupled accesses at
* initialization
*/
rc32434_pci->pcidas = 0; /* clear the status */
rc32434_pci->pcidasm = 0x0000007F; /* Mask all the interrupts */
/* Mask PCI Messaging Interrupts */
rc32434_pci_msg->pciiic = 0;
rc32434_pci_msg->pciiim = 0xFFFFFFFF;
rc32434_pci_msg->pciioic = 0;
rc32434_pci_msg->pciioim = 0;
/* Setup PCILB0 as Memory Window */
rc32434_pci->pcilba[0].address = (unsigned int) (PCI_ADDR_START);
/* setup the PCI map address as same as the local address */
rc32434_pci->pcilba[0].mapping = (unsigned int) (PCI_ADDR_START);
/* Setup PCILBA1 as MEM */
rc32434_pci->pcilba[0].control =
(((SIZE_256MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[0].control; /* flush the CPU write Buffers */
rc32434_pci->pcilba[1].address = 0x60000000;
rc32434_pci->pcilba[1].mapping = 0x60000000;
/* setup PCILBA2 as IO Window */
rc32434_pci->pcilba[1].control =
(((SIZE_256MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[1].control; /* flush the CPU write Buffers */
rc32434_pci->pcilba[2].address = 0x18C00000;
rc32434_pci->pcilba[2].mapping = 0x18FFFFFF;
/* setup PCILBA2 as IO Window */
rc32434_pci->pcilba[2].control =
(((SIZE_4MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[2].control; /* flush the CPU write Buffers */
/* Setup PCILBA3 as IO Window */
rc32434_pci->pcilba[3].address = 0x18800000;
rc32434_pci->pcilba[3].mapping = 0x18800000;
rc32434_pci->pcilba[3].control =
((((SIZE_1MB & 0x1ff) << PCI_LBAC_SIZE_BIT) | PCI_LBAC_MSI) |
PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[3].control; /* flush the CPU write Buffers */
pci_config_addr = (unsigned int) (0x80000004);
for (loopCount = 0; loopCount < 24; loopCount++) {
rc32434_pci->pcicfga = pci_config_addr;
dummyread = rc32434_pci->pcicfga;
rc32434_pci->pcicfgd = korina_cnfg_regs[loopCount];
dummyread = rc32434_pci->pcicfgd;
pci_config_addr += 4;
}
rc32434_pci->pcitc =
(unsigned int) ((PCITC_RTIMER_VAL & 0xff) << PCI_TC_RTIMER_BIT) |
((PCITC_DTIMER_VAL & 0xff) << PCI_TC_DTIMER_BIT);
pcicntlval = rc32434_pci->pcic;
pcicntlval &= ~PCI_CTL_TNR;
rc32434_pci->pcic = pcicntlval;
pcicntlval = rc32434_pci->pcic;
return 0;
}
static int __init rc32434_pci_init(void)
{
void __iomem *io_map_base;
pr_info("PCI: Initializing PCI\n");
ioport_resource.start = rc32434_res_pci_io1.start;
ioport_resource.end = rc32434_res_pci_io1.end;
rc32434_pcibridge_init();
io_map_base = ioremap(rc32434_res_pci_io1.start,
rc32434_res_pci_io1.end - rc32434_res_pci_io1.start + 1);
if (!io_map_base)
return -ENOMEM;
rc32434_controller.io_map_base =
(unsigned long)io_map_base - rc32434_res_pci_io1.start;
register_pci_controller(&rc32434_controller);
rc32434_sync();
return 0;
}
arch_initcall(rc32434_pci_init);
| gpl-2.0 |
manfromnn/msm8909_tp-link_c5l_kernel | arch/arm/mach-imx/mach-cpuimx51sd.c | 2272 | 10075 | /*
*
* Copyright (C) 2010 Eric Bénard <eric@eukrea.com>
*
* based on board-mx51_babbage.c which is
* Copyright 2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2009-2010 Amit Kucheria <amit.kucheria@canonical.com>
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/i2c/tsc2007.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/i2c-gpio.h>
#include <linux/spi/spi.h>
#include <linux/can/platform/mcp251x.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "common.h"
#include "devices-imx51.h"
#include "eukrea-baseboards.h"
#include "hardware.h"
#include "iomux-mx51.h"
#define USBH1_RST IMX_GPIO_NR(2, 28)
#define ETH_RST IMX_GPIO_NR(2, 31)
#define TSC2007_IRQGPIO_REV2 IMX_GPIO_NR(3, 12)
#define TSC2007_IRQGPIO_REV3 IMX_GPIO_NR(4, 0)
#define CAN_IRQGPIO IMX_GPIO_NR(1, 1)
#define CAN_RST IMX_GPIO_NR(4, 15)
#define CAN_NCS IMX_GPIO_NR(4, 24)
#define CAN_RXOBF_REV2 IMX_GPIO_NR(1, 4)
#define CAN_RXOBF_REV3 IMX_GPIO_NR(3, 12)
#define CAN_RX1BF IMX_GPIO_NR(1, 6)
#define CAN_TXORTS IMX_GPIO_NR(1, 7)
#define CAN_TX1RTS IMX_GPIO_NR(1, 8)
#define CAN_TX2RTS IMX_GPIO_NR(1, 9)
#define I2C_SCL IMX_GPIO_NR(4, 16)
#define I2C_SDA IMX_GPIO_NR(4, 17)
/* USB_CTRL_1 */
#define MX51_USB_CTRL_1_OFFSET 0x10
#define MX51_USB_CTRL_UH1_EXT_CLK_EN (1 << 25)
#define MX51_USB_PLLDIV_12_MHZ 0x00
#define MX51_USB_PLL_DIV_19_2_MHZ 0x01
#define MX51_USB_PLL_DIV_24_MHZ 0x02
static iomux_v3_cfg_t eukrea_cpuimx51sd_pads[] = {
/* UART1 */
MX51_PAD_UART1_RXD__UART1_RXD,
MX51_PAD_UART1_TXD__UART1_TXD,
MX51_PAD_UART1_RTS__UART1_RTS,
MX51_PAD_UART1_CTS__UART1_CTS,
/* USB HOST1 */
MX51_PAD_USBH1_CLK__USBH1_CLK,
MX51_PAD_USBH1_DIR__USBH1_DIR,
MX51_PAD_USBH1_NXT__USBH1_NXT,
MX51_PAD_USBH1_DATA0__USBH1_DATA0,
MX51_PAD_USBH1_DATA1__USBH1_DATA1,
MX51_PAD_USBH1_DATA2__USBH1_DATA2,
MX51_PAD_USBH1_DATA3__USBH1_DATA3,
MX51_PAD_USBH1_DATA4__USBH1_DATA4,
MX51_PAD_USBH1_DATA5__USBH1_DATA5,
MX51_PAD_USBH1_DATA6__USBH1_DATA6,
MX51_PAD_USBH1_DATA7__USBH1_DATA7,
MX51_PAD_USBH1_STP__USBH1_STP,
MX51_PAD_EIM_CS3__GPIO2_28, /* PHY nRESET */
/* FEC */
MX51_PAD_EIM_DTACK__GPIO2_31, /* PHY nRESET */
/* HSI2C */
MX51_PAD_I2C1_CLK__GPIO4_16,
MX51_PAD_I2C1_DAT__GPIO4_17,
/* I2C1 */
MX51_PAD_SD2_CMD__I2C1_SCL,
MX51_PAD_SD2_CLK__I2C1_SDA,
/* CAN */
MX51_PAD_CSPI1_MOSI__ECSPI1_MOSI,
MX51_PAD_CSPI1_MISO__ECSPI1_MISO,
MX51_PAD_CSPI1_SCLK__ECSPI1_SCLK,
MX51_PAD_CSPI1_SS0__GPIO4_24, /* nCS */
MX51_PAD_CSI2_PIXCLK__GPIO4_15, /* nReset */
MX51_PAD_GPIO1_1__GPIO1_1, /* IRQ */
MX51_PAD_GPIO1_4__GPIO1_4, /* Control signals */
MX51_PAD_GPIO1_6__GPIO1_6,
MX51_PAD_GPIO1_7__GPIO1_7,
MX51_PAD_GPIO1_8__GPIO1_8,
MX51_PAD_GPIO1_9__GPIO1_9,
/* Touchscreen */
/* IRQ */
NEW_PAD_CTRL(MX51_PAD_GPIO_NAND__GPIO_NAND, PAD_CTL_PUS_22K_UP |
PAD_CTL_PKE | PAD_CTL_SRE_FAST |
PAD_CTL_DSE_HIGH | PAD_CTL_PUE | PAD_CTL_HYS),
NEW_PAD_CTRL(MX51_PAD_NANDF_D8__GPIO4_0, PAD_CTL_PUS_22K_UP |
PAD_CTL_PKE | PAD_CTL_SRE_FAST |
PAD_CTL_DSE_HIGH | PAD_CTL_PUE | PAD_CTL_HYS),
};
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static int tsc2007_get_pendown_state(void)
{
if (mx51_revision() < IMX_CHIP_REVISION_3_0)
return !gpio_get_value(TSC2007_IRQGPIO_REV2);
else
return !gpio_get_value(TSC2007_IRQGPIO_REV3);
}
static struct tsc2007_platform_data tsc2007_info = {
.model = 2007,
.x_plate_ohms = 180,
.get_pendown_state = tsc2007_get_pendown_state,
};
static struct i2c_board_info eukrea_cpuimx51sd_i2c_devices[] = {
{
I2C_BOARD_INFO("pcf8563", 0x51),
}, {
I2C_BOARD_INFO("tsc2007", 0x49),
.platform_data = &tsc2007_info,
},
};
static const struct mxc_nand_platform_data
eukrea_cpuimx51sd_nand_board_info __initconst = {
.width = 1,
.hw_ecc = 1,
.flash_bbt = 1,
};
/* This function is board specific as the bit mask for the plldiv will also
be different for other Freescale SoCs, thus a common bitmask is not
possible and cannot get place in /plat-mxc/ehci.c.*/
static int initialize_otg_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* Set the PHY clock to 19.2MHz */
v = __raw_readl(usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
v &= ~MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK;
v |= MX51_USB_PLL_DIV_19_2_MHZ;
__raw_writel(v, usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(0, MXC_EHCI_INTERNAL_PHY);
}
static int initialize_usbh1_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* The clock for the USBH1 ULPI port will come from the PHY. */
v = __raw_readl(usbother_base + MX51_USB_CTRL_1_OFFSET);
__raw_writel(v | MX51_USB_CTRL_UH1_EXT_CLK_EN,
usbother_base + MX51_USB_CTRL_1_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(1, MXC_EHCI_POWER_PINS_ENABLED |
MXC_EHCI_ITC_NO_THRESHOLD);
}
static const struct mxc_usbh_platform_data dr_utmi_config __initconst = {
.init = initialize_otg_port,
.portsc = MXC_EHCI_UTMI_16BIT,
};
static const struct fsl_usb2_platform_data usb_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_UTMI_WIDE,
};
static const struct mxc_usbh_platform_data usbh1_config __initconst = {
.init = initialize_usbh1_port,
.portsc = MXC_EHCI_MODE_ULPI,
};
static bool otg_mode_host __initdata;
static int __init eukrea_cpuimx51sd_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = true;
else if (!strcmp(options, "device"))
otg_mode_host = false;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 1;
}
__setup("otg_mode=", eukrea_cpuimx51sd_otg_mode);
static struct i2c_gpio_platform_data pdata = {
.sda_pin = I2C_SDA,
.sda_is_open_drain = 0,
.scl_pin = I2C_SCL,
.scl_is_open_drain = 0,
.udelay = 2,
};
static struct platform_device hsi2c_gpio_device = {
.name = "i2c-gpio",
.id = 0,
.dev.platform_data = &pdata,
};
static struct mcp251x_platform_data mcp251x_info = {
.oscillator_frequency = 24E6,
};
static struct spi_board_info cpuimx51sd_spi_device[] = {
{
.modalias = "mcp2515",
.max_speed_hz = 10000000,
.bus_num = 0,
.mode = SPI_MODE_0,
.chip_select = 0,
.platform_data = &mcp251x_info,
/* irq number is run-time assigned */
},
};
static int cpuimx51sd_spi1_cs[] = {
CAN_NCS,
};
static const struct spi_imx_master cpuimx51sd_ecspi1_pdata __initconst = {
.chipselect = cpuimx51sd_spi1_cs,
.num_chipselect = ARRAY_SIZE(cpuimx51sd_spi1_cs),
};
static struct platform_device *rev2_platform_devices[] __initdata = {
&hsi2c_gpio_device,
};
static const struct imxi2c_platform_data cpuimx51sd_i2c_data __initconst = {
.bitrate = 100000,
};
static void __init eukrea_cpuimx51sd_init(void)
{
imx51_soc_init();
mxc_iomux_v3_setup_multiple_pads(eukrea_cpuimx51sd_pads,
ARRAY_SIZE(eukrea_cpuimx51sd_pads));
imx51_add_imx_uart(0, &uart_pdata);
imx51_add_mxc_nand(&eukrea_cpuimx51sd_nand_board_info);
imx51_add_imx2_wdt(0);
gpio_request(ETH_RST, "eth_rst");
gpio_set_value(ETH_RST, 1);
imx51_add_fec(NULL);
gpio_request(CAN_IRQGPIO, "can_irq");
gpio_direction_input(CAN_IRQGPIO);
gpio_free(CAN_IRQGPIO);
gpio_request(CAN_NCS, "can_ncs");
gpio_direction_output(CAN_NCS, 1);
gpio_free(CAN_NCS);
gpio_request(CAN_RST, "can_rst");
gpio_direction_output(CAN_RST, 0);
msleep(20);
gpio_set_value(CAN_RST, 1);
imx51_add_ecspi(0, &cpuimx51sd_ecspi1_pdata);
cpuimx51sd_spi_device[0].irq = gpio_to_irq(CAN_IRQGPIO);
spi_register_board_info(cpuimx51sd_spi_device,
ARRAY_SIZE(cpuimx51sd_spi_device));
if (mx51_revision() < IMX_CHIP_REVISION_3_0) {
eukrea_cpuimx51sd_i2c_devices[1].irq =
gpio_to_irq(TSC2007_IRQGPIO_REV2),
platform_add_devices(rev2_platform_devices,
ARRAY_SIZE(rev2_platform_devices));
gpio_request(TSC2007_IRQGPIO_REV2, "tsc2007_irq");
gpio_direction_input(TSC2007_IRQGPIO_REV2);
gpio_free(TSC2007_IRQGPIO_REV2);
} else {
eukrea_cpuimx51sd_i2c_devices[1].irq =
gpio_to_irq(TSC2007_IRQGPIO_REV3),
imx51_add_imx_i2c(0, &cpuimx51sd_i2c_data);
gpio_request(TSC2007_IRQGPIO_REV3, "tsc2007_irq");
gpio_direction_input(TSC2007_IRQGPIO_REV3);
gpio_free(TSC2007_IRQGPIO_REV3);
}
i2c_register_board_info(0, eukrea_cpuimx51sd_i2c_devices,
ARRAY_SIZE(eukrea_cpuimx51sd_i2c_devices));
if (otg_mode_host)
imx51_add_mxc_ehci_otg(&dr_utmi_config);
else {
initialize_otg_port(NULL);
imx51_add_fsl_usb2_udc(&usb_pdata);
}
gpio_request(USBH1_RST, "usb_rst");
gpio_direction_output(USBH1_RST, 0);
msleep(20);
gpio_set_value(USBH1_RST, 1);
imx51_add_mxc_ehci_hs(1, &usbh1_config);
#ifdef CONFIG_MACH_EUKREA_MBIMXSD51_BASEBOARD
eukrea_mbimxsd51_baseboard_init();
#endif
}
static void __init eukrea_cpuimx51sd_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 0);
}
MACHINE_START(EUKREA_CPUIMX51SD, "Eukrea CPUIMX51SD")
/* Maintainer: Eric Bénard <eric@eukrea.com> */
.atag_offset = 0x100,
.map_io = mx51_map_io,
.init_early = imx51_init_early,
.init_irq = mx51_init_irq,
.handle_irq = imx51_handle_irq,
.init_time = eukrea_cpuimx51sd_timer_init,
.init_machine = eukrea_cpuimx51sd_init,
.init_late = imx51_init_late,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
varunchitre15/thunderzap_sprout | drivers/isdn/mISDN/dsp_core.c | 2272 | 33946 | /*
* Author Andreas Eversberg (jolly@eversberg.eu)
* Based on source code structure by
* Karsten Keil (keil@isdn4linux.de)
*
* This file is (c) under GNU PUBLIC LICENSE
* For changes and modifications please read
* ../../../Documentation/isdn/mISDN.cert
*
* Thanks to Karsten Keil (great drivers)
* Cologne Chip (great chips)
*
* This module does:
* Real-time tone generation
* DTMF detection
* Real-time cross-connection and conferrence
* Compensate jitter due to system load and hardware fault.
* All features are done in kernel space and will be realized
* using hardware, if available and supported by chip set.
* Blowfish encryption/decryption
*/
/* STRUCTURE:
*
* The dsp module provides layer 2 for b-channels (64kbit). It provides
* transparent audio forwarding with special digital signal processing:
*
* - (1) generation of tones
* - (2) detection of dtmf tones
* - (3) crossconnecting and conferences (clocking)
* - (4) echo generation for delay test
* - (5) volume control
* - (6) disable receive data
* - (7) pipeline
* - (8) encryption/decryption
*
* Look:
* TX RX
* ------upper layer------
* | ^
* | |(6)
* v |
* +-----+-------------+-----+
* |(3)(4) |
* | CMX |
* | |
* | +-------------+
* | | ^
* | | |
* |+---------+| +----+----+
* ||(1) || |(2) |
* || || | |
* || Tones || | DTMF |
* || || | |
* || || | |
* |+----+----+| +----+----+
* +-----+-----+ ^
* | |
* v |
* +----+----+ +----+----+
* |(5) | |(5) |
* | | | |
* |TX Volume| |RX Volume|
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* +----+-------------+----+
* |(7) |
* | |
* | Pipeline Processing |
* | |
* | |
* +----+-------------+----+
* | ^
* | |
* v |
* +----+----+ +----+----+
* |(8) | |(8) |
* | | | |
* | Encrypt | | Decrypt |
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* ------card layer------
* TX RX
*
* Above you can see the logical data flow. If software is used to do the
* process, it is actually the real data flow. If hardware is used, data
* may not flow, but hardware commands to the card, to provide the data flow
* as shown.
*
* NOTE: The channel must be activated in order to make dsp work, even if
* no data flow to the upper layer is intended. Activation can be done
* after and before controlling the setting using PH_CONTROL requests.
*
* DTMF: Will be detected by hardware if possible. It is done before CMX
* processing.
*
* Tones: Will be generated via software if endless looped audio fifos are
* not supported by hardware. Tones will override all data from CMX.
* It is not required to join a conference to use tones at any time.
*
* CMX: Is transparent when not used. When it is used, it will do
* crossconnections and conferences via software if not possible through
* hardware. If hardware capability is available, hardware is used.
*
* Echo: Is generated by CMX and is used to check performance of hard and
* software CMX.
*
* The CMX has special functions for conferences with one, two and more
* members. It will allow different types of data flow. Receive and transmit
* data to/form upper layer may be swithed on/off individually without losing
* features of CMX, Tones and DTMF.
*
* Echo Cancellation: Sometimes we like to cancel echo from the interface.
* Note that a VoIP call may not have echo caused by the IP phone. The echo
* is generated by the telephone line connected to it. Because the delay
* is high, it becomes an echo. RESULT: Echo Cachelation is required if
* both echo AND delay is applied to an interface.
* Remember that software CMX always generates a more or less delay.
*
* If all used features can be realized in hardware, and if transmit and/or
* receive data ist disabled, the card may not send/receive any data at all.
* Not receiving is useful if only announcements are played. Not sending is
* useful if an answering machine records audio. Not sending and receiving is
* useful during most states of the call. If supported by hardware, tones
* will be played without cpu load. Small PBXs and NT-Mode applications will
* not need expensive hardware when processing calls.
*
*
* LOCKING:
*
* When data is received from upper or lower layer (card), the complete dsp
* module is locked by a global lock. This lock MUST lock irq, because it
* must lock timer events by DSP poll timer.
* When data is ready to be transmitted down, the data is queued and sent
* outside lock and timer event.
* PH_CONTROL must not change any settings, join or split conference members
* during process of data.
*
* HDLC:
*
* It works quite the same as transparent, except that HDLC data is forwarded
* to all other conference members if no hardware bridging is possible.
* Send data will be writte to sendq. Sendq will be sent if confirm is received.
* Conference cannot join, if one member is not hdlc.
*
*/
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include "core.h"
#include "dsp.h"
static const char *mISDN_dsp_revision = "2.0";
static int debug;
static int options;
static int poll;
static int dtmfthreshold = 100;
MODULE_AUTHOR("Andreas Eversberg");
module_param(debug, uint, S_IRUGO | S_IWUSR);
module_param(options, uint, S_IRUGO | S_IWUSR);
module_param(poll, uint, S_IRUGO | S_IWUSR);
module_param(dtmfthreshold, uint, S_IRUGO | S_IWUSR);
MODULE_LICENSE("GPL");
/*int spinnest = 0;*/
spinlock_t dsp_lock; /* global dsp lock */
struct list_head dsp_ilist;
struct list_head conf_ilist;
int dsp_debug;
int dsp_options;
int dsp_poll, dsp_tics;
/* check if rx may be turned off or must be turned on */
static void
dsp_rx_off_member(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
int rx_off = 1;
memset(&cq, 0, sizeof(cq));
if (!dsp->features_rx_off)
return;
/* not disabled */
if (!dsp->rx_disabled)
rx_off = 0;
/* software dtmf */
else if (dsp->dtmf.software)
rx_off = 0;
/* echo in software */
else if (dsp->echo.software)
rx_off = 0;
/* bridge in software */
else if (dsp->conf && dsp->conf->software)
rx_off = 0;
/* data is not required by user space and not required
* for echo dtmf detection, soft-echo, soft-bridging */
if (rx_off == dsp->rx_is_off)
return;
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no rx_off\n",
__func__);
return;
}
cq.op = MISDN_CTRL_RX_OFF;
cq.p1 = rx_off;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
return;
}
dsp->rx_is_off = rx_off;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set rx_off = %d\n",
__func__, dsp->name, rx_off);
}
static void
dsp_rx_off(struct dsp *dsp)
{
struct dsp_conf_member *member;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
/* no conf */
if (!dsp->conf) {
dsp_rx_off_member(dsp);
return;
}
/* check all members in conf */
list_for_each_entry(member, &dsp->conf->mlist, list) {
dsp_rx_off_member(member->dsp);
}
}
/* enable "fill empty" feature */
static void
dsp_fill_empty(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
memset(&cq, 0, sizeof(cq));
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no fill_empty\n",
__func__);
return;
}
cq.op = MISDN_CTRL_FILL_EMPTY;
cq.p1 = 1;
cq.p2 = dsp_silence;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set fill_empty = 1\n",
__func__, dsp->name);
}
static int
dsp_control_req(struct dsp *dsp, struct mISDNhead *hh, struct sk_buff *skb)
{
struct sk_buff *nskb;
int ret = 0;
int cont;
u8 *data;
int len;
if (skb->len < sizeof(int))
printk(KERN_ERR "%s: PH_CONTROL message too short\n", __func__);
cont = *((int *)skb->data);
len = skb->len - sizeof(int);
data = skb->data + sizeof(int);
switch (cont) {
case DTMF_TONE_START: /* turn on DTMF */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: start dtmf\n", __func__);
if (len == sizeof(int)) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_NOTICE "changing DTMF Threshold "
"to %d\n", *((int *)data));
dsp->dtmf.treshold = (*(int *)data) * 10000;
}
dsp->dtmf.enable = 1;
/* init goertzel */
dsp_dtmf_goertzel_init(dsp);
/* check dtmf hardware */
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DTMF_TONE_STOP: /* turn off DTMF */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: stop dtmf\n", __func__);
dsp->dtmf.enable = 0;
dsp->dtmf.hardware = 0;
dsp->dtmf.software = 0;
break;
case DSP_CONF_JOIN: /* join / update conference */
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (*((u32 *)data) == 0)
goto conf_split;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: join conference %d\n",
__func__, *((u32 *)data));
ret = dsp_cmx_conf(dsp, *((u32 *)data));
/* dsp_cmx_hardware will also be called here */
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_CONF_SPLIT: /* remove from conference */
conf_split:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: release conference\n", __func__);
ret = dsp_cmx_conf(dsp, 0);
/* dsp_cmx_hardware will also be called here */
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
dsp_rx_off(dsp);
break;
case DSP_TONE_PATT_ON: /* play tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone 0x%x on\n",
__func__, *((int *)skb->data));
ret = dsp_tone(dsp, *((int *)data));
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
if (!dsp->tone.tone)
goto tone_off;
break;
case DSP_TONE_PATT_OFF: /* stop tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone off\n", __func__);
dsp_tone(dsp, 0);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
/* reset tx buffers (user space data) */
tone_off:
dsp->rx_W = 0;
dsp->rx_R = 0;
break;
case DSP_VOL_CHANGE_TX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->tx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_VOL_CHANGE_RX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->rx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change rx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_ECHO_ON: /* enable echo */
dsp->echo.software = 1; /* soft echo */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_ECHO_OFF: /* disable echo */
dsp->echo.software = 0;
dsp->echo.hardware = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_RECEIVE_ON: /* enable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable receive to user "
"space\n", __func__);
dsp->rx_disabled = 0;
dsp_rx_off(dsp);
break;
case DSP_RECEIVE_OFF: /* disable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable receive to "
"user space\n", __func__);
dsp->rx_disabled = 1;
dsp_rx_off(dsp);
break;
case DSP_MIX_ON: /* enable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 1;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_MIX_OFF: /* disable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_ON: /* enable txdata */
dsp->tx_data = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_OFF: /* disable txdata */
dsp->tx_data = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_DELAY: /* use delay algorithm instead of dynamic
jitter algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = (*((int *)data)) << 3;
/* milliseconds to samples */
if (dsp->cmx_delay >= (CMX_BUFF_HALF >> 1))
/* clip to half of maximum usable buffer
(half of half buffer) */
dsp->cmx_delay = (CMX_BUFF_HALF >> 1) - 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use delay algorithm to "
"compensate jitter (%d samples)\n",
__func__, dsp->cmx_delay);
break;
case DSP_JITTER: /* use dynamic jitter algorithm instead of
delay algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use jitter algorithm to "
"compensate jitter\n", __func__);
break;
case DSP_TX_DEJITTER: /* use dynamic jitter algorithm for tx-buffer */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use dejitter on TX "
"buffer\n", __func__);
break;
case DSP_TX_DEJ_OFF: /* use tx-buffer without dejittering*/
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use TX buffer without "
"dejittering\n", __func__);
break;
case DSP_PIPELINE_CFG:
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len > 0 && ((char *)data)[len - 1]) {
printk(KERN_DEBUG "%s: pipeline config string "
"is not NULL terminated!\n", __func__);
ret = -EINVAL;
} else {
dsp->pipeline.inuse = 1;
dsp_cmx_hardware(dsp->conf, dsp);
ret = dsp_pipeline_build(&dsp->pipeline,
len > 0 ? data : NULL);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_ENABLE_KEY: /* turn blowfish on */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < 4 || len > 56) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish on (key "
"not shown)\n", __func__);
ret = dsp_bf_init(dsp, (u8 *)data, len);
/* set new cont */
if (!ret)
cont = DSP_BF_ACCEPT;
else
cont = DSP_BF_REJECT;
/* send indication if it worked to set it */
nskb = _alloc_mISDN_skb(PH_CONTROL_IND, MISDN_ID_ANY,
sizeof(int), &cont, GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_DISABLE: /* turn blowfish off */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish off\n", __func__);
dsp_bf_cleanup(dsp);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl req %x unhandled\n",
__func__, cont);
ret = -EINVAL;
}
return ret;
}
static void
get_features(struct mISDNchannel *ch)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDN_ctrl_req cq;
if (!ch->peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no features\n",
__func__);
return;
}
memset(&cq, 0, sizeof(cq));
cq.op = MISDN_CTRL_GETOP;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq) < 0) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (cq.op & MISDN_CTRL_RX_OFF)
dsp->features_rx_off = 1;
if (cq.op & MISDN_CTRL_FILL_EMPTY)
dsp->features_fill_empty = 1;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
if ((cq.op & MISDN_CTRL_HW_FEATURES_OP)) {
cq.op = MISDN_CTRL_HW_FEATURES;
*((u_long *)&cq.p1) = (u_long)&dsp->features;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
}
} else
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: features not supported for %s\n",
__func__, dsp->name);
}
static int
dsp_function(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDNhead *hh;
int ret = 0;
u8 *digits = NULL;
u_long flags;
hh = mISDN_HEAD_P(skb);
switch (hh->prim) {
/* FROM DOWN */
case (PH_DATA_CNF):
dsp->data_pending = 0;
/* trigger next hdlc frame, if any */
if (dsp->hdlc) {
spin_lock_irqsave(&dsp_lock, flags);
if (dsp->b_active)
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_DATA_IND):
case (DL_DATA_IND):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->rx_is_off) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: rx-data during rx_off"
" for %s\n",
__func__, dsp->name);
}
if (dsp->hdlc) {
/* hdlc */
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_hdlc(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
}
spin_lock_irqsave(&dsp_lock, flags);
/* decrypt if enabled */
if (dsp->bf_enable)
dsp_bf_decrypt(dsp, skb->data, skb->len);
/* pipeline */
if (dsp->pipeline.inuse)
dsp_pipeline_process_rx(&dsp->pipeline, skb->data,
skb->len, hh->id);
/* change volume if requested */
if (dsp->rx_volume)
dsp_change_volume(skb, dsp->rx_volume);
/* check if dtmf soft decoding is turned on */
if (dsp->dtmf.software) {
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, (dsp_options & DSP_OPT_ULAW) ? 1 : 0);
}
/* we need to process receive data if software */
if (dsp->conf && dsp->conf->software) {
/* process data from card at cmx */
dsp_cmx_receive(dsp, skb);
}
spin_unlock_irqrestore(&dsp_lock, flags);
/* send dtmf result, if any */
if (digits) {
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
}
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_CONTROL_IND):
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: PH_CONTROL INDICATION "
"received: %x (len %d) %s\n", __func__,
hh->id, skb->len, dsp->name);
switch (hh->id) {
case (DTMF_HFC_COEF): /* getting coefficients */
if (!dsp->dtmf.hardware) {
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: ignoring DTMF "
"coefficients from HFC\n",
__func__);
break;
}
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, 2);
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
break;
case (HFC_VOL_CHANGE_TX): /* change volume */
if (skb->len != sizeof(int)) {
ret = -EINVAL;
break;
}
spin_lock_irqsave(&dsp_lock, flags);
dsp->tx_volume = *((int *)skb->data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx volume to "
"%d\n", __func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl ind %x unhandled "
"%s\n", __func__, hh->id, dsp->name);
ret = -EINVAL;
}
break;
case (PH_ACTIVATE_IND):
case (PH_ACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now active %s\n",
__func__, dsp->name);
/* bchannel now active */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 1;
dsp->data_pending = 0;
dsp->rx_init = 1;
/* rx_W and rx_R will be adjusted on first frame */
dsp->rx_W = 0;
dsp->rx_R = 0;
memset(dsp->rx_buff, 0, sizeof(dsp->rx_buff));
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: done with activation, sending "
"confirm to user space. %s\n", __func__,
dsp->name);
/* send activation to upper layer */
hh->prim = DL_ESTABLISH_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_DEACTIVATE_IND):
case (PH_DEACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now inactive %s\n",
__func__, dsp->name);
/* bchannel now inactive */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
dsp->data_pending = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = DL_RELEASE_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
/* FROM UP */
case (DL_DATA_REQ):
case (PH_DATA_REQ):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->hdlc) {
/* hdlc */
if (!dsp->b_active) {
ret = -EIO;
break;
}
hh->prim = PH_DATA_REQ;
spin_lock_irqsave(&dsp_lock, flags);
skb_queue_tail(&dsp->sendq, skb);
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
/* send data to tx-buffer (if no tone is played) */
if (!dsp->tone.tone) {
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_transmit(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_CONTROL_REQ):
spin_lock_irqsave(&dsp_lock, flags);
ret = dsp_control_req(dsp, hh, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
case (DL_ESTABLISH_REQ):
case (PH_ACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: activating b_channel %s\n",
__func__, dsp->name);
if (dsp->dtmf.hardware || dsp->dtmf.software)
dsp_dtmf_goertzel_init(dsp);
get_features(ch);
/* enable fill_empty feature */
if (dsp->features_fill_empty)
dsp_fill_empty(dsp);
/* send ph_activate */
hh->prim = PH_ACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
case (DL_RELEASE_REQ):
case (PH_DEACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: releasing b_channel %s\n",
__func__, dsp->name);
spin_lock_irqsave(&dsp_lock, flags);
dsp->tone.tone = 0;
dsp->tone.hardware = 0;
dsp->tone.software = 0;
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
if (dsp->conf)
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be
called here */
skb_queue_purge(&dsp->sendq);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = PH_DEACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: msg %x unhandled %s\n",
__func__, hh->prim, dsp->name);
ret = -EINVAL;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static int
dsp_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
u_long flags;
int err = 0;
if (debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s:(%x)\n", __func__, cmd);
switch (cmd) {
case OPEN_CHANNEL:
break;
case CLOSE_CHANNEL:
if (dsp->ch.peer)
dsp->ch.peer->ctrl(dsp->ch.peer, CLOSE_CHANNEL, NULL);
/* wait until workqueue has finished,
* must lock here, or we may hit send-process currently
* queueing. */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
spin_unlock_irqrestore(&dsp_lock, flags);
/* MUST not be locked, because it waits until queue is done. */
cancel_work_sync(&dsp->workq);
spin_lock_irqsave(&dsp_lock, flags);
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
skb_queue_purge(&dsp->sendq);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: releasing member %s\n",
__func__, dsp->name);
dsp->b_active = 0;
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be called
here */
dsp_pipeline_destroy(&dsp->pipeline);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: remove & destroy object %s\n",
__func__, dsp->name);
list_del(&dsp->list);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: dsp instance released\n",
__func__);
vfree(dsp);
module_put(THIS_MODULE);
break;
}
return err;
}
static void
dsp_send_bh(struct work_struct *work)
{
struct dsp *dsp = container_of(work, struct dsp, workq);
struct sk_buff *skb;
struct mISDNhead *hh;
if (dsp->hdlc && dsp->data_pending)
return; /* wait until data has been acknowledged */
/* send queued data */
while ((skb = skb_dequeue(&dsp->sendq))) {
/* in locked date, we must have still data in queue */
if (dsp->data_pending) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: fifo full %s, this is "
"no bug!\n", __func__, dsp->name);
/* flush transparent data, if not acked */
dev_kfree_skb(skb);
continue;
}
hh = mISDN_HEAD_P(skb);
if (hh->prim == DL_DATA_REQ) {
/* send packet up */
if (dsp->up) {
if (dsp->up->send(dsp->up, skb))
dev_kfree_skb(skb);
} else
dev_kfree_skb(skb);
} else {
/* send packet down */
if (dsp->ch.peer) {
dsp->data_pending = 1;
if (dsp->ch.recv(dsp->ch.peer, skb)) {
dev_kfree_skb(skb);
dsp->data_pending = 0;
}
} else
dev_kfree_skb(skb);
}
}
}
static int
dspcreate(struct channel_req *crq)
{
struct dsp *ndsp;
u_long flags;
if (crq->protocol != ISDN_P_B_L2DSP
&& crq->protocol != ISDN_P_B_L2DSPHDLC)
return -EPROTONOSUPPORT;
ndsp = vzalloc(sizeof(struct dsp));
if (!ndsp) {
printk(KERN_ERR "%s: vmalloc struct dsp failed\n", __func__);
return -ENOMEM;
}
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: creating new dsp instance\n", __func__);
/* default enabled */
INIT_WORK(&ndsp->workq, (void *)dsp_send_bh);
skb_queue_head_init(&ndsp->sendq);
ndsp->ch.send = dsp_function;
ndsp->ch.ctrl = dsp_ctrl;
ndsp->up = crq->ch;
crq->ch = &ndsp->ch;
if (crq->protocol == ISDN_P_B_L2DSP) {
crq->protocol = ISDN_P_B_RAW;
ndsp->hdlc = 0;
} else {
crq->protocol = ISDN_P_B_HDLC;
ndsp->hdlc = 1;
}
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s:cannot get module\n",
__func__);
sprintf(ndsp->name, "DSP_C%x(0x%p)",
ndsp->up->st->dev->id + 1, ndsp);
/* set frame size to start */
ndsp->features.hfc_id = -1; /* current PCM id */
ndsp->features.pcm_id = -1; /* current PCM id */
ndsp->pcm_slot_rx = -1; /* current CPM slot */
ndsp->pcm_slot_tx = -1;
ndsp->pcm_bank_rx = -1;
ndsp->pcm_bank_tx = -1;
ndsp->hfc_conf = -1; /* current conference number */
/* set tone timer */
ndsp->tone.tl.function = (void *)dsp_tone_timeout;
ndsp->tone.tl.data = (long) ndsp;
init_timer(&ndsp->tone.tl);
if (dtmfthreshold < 20 || dtmfthreshold > 500)
dtmfthreshold = 200;
ndsp->dtmf.treshold = dtmfthreshold * 10000;
/* init pipeline append to list */
spin_lock_irqsave(&dsp_lock, flags);
dsp_pipeline_init(&ndsp->pipeline);
list_add_tail(&ndsp->list, &dsp_ilist);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
static struct Bprotocol DSP = {
.Bprotocols = (1 << (ISDN_P_B_L2DSP & ISDN_P_B_MASK))
| (1 << (ISDN_P_B_L2DSPHDLC & ISDN_P_B_MASK)),
.name = "dsp",
.create = dspcreate
};
static int __init dsp_init(void)
{
int err;
int tics;
printk(KERN_INFO "DSP module %s\n", mISDN_dsp_revision);
dsp_options = options;
dsp_debug = debug;
/* set packet size */
dsp_poll = poll;
if (dsp_poll) {
if (dsp_poll > MAX_POLL) {
printk(KERN_ERR "%s: Wrong poll value (%d), use %d "
"maximum.\n", __func__, poll, MAX_POLL);
err = -EINVAL;
return err;
}
if (dsp_poll < 8) {
printk(KERN_ERR "%s: Wrong poll value (%d), use 8 "
"minimum.\n", __func__, dsp_poll);
err = -EINVAL;
return err;
}
dsp_tics = poll * HZ / 8000;
if (dsp_tics * 8000 != poll * HZ) {
printk(KERN_INFO "mISDN_dsp: Cannot clock every %d "
"samples (0,125 ms). It is not a multiple of "
"%d HZ.\n", poll, HZ);
err = -EINVAL;
return err;
}
} else {
poll = 8;
while (poll <= MAX_POLL) {
tics = (poll * HZ) / 8000;
if (tics * 8000 == poll * HZ) {
dsp_tics = tics;
dsp_poll = poll;
if (poll >= 64)
break;
}
poll++;
}
}
if (dsp_poll == 0) {
printk(KERN_INFO "mISDN_dsp: There is no multiple of kernel "
"clock that equals exactly the duration of 8-256 "
"samples. (Choose kernel clock speed like 100, 250, "
"300, 1000)\n");
err = -EINVAL;
return err;
}
printk(KERN_INFO "mISDN_dsp: DSP clocks every %d samples. This equals "
"%d jiffies.\n", dsp_poll, dsp_tics);
spin_lock_init(&dsp_lock);
INIT_LIST_HEAD(&dsp_ilist);
INIT_LIST_HEAD(&conf_ilist);
/* init conversion tables */
dsp_audio_generate_law_tables();
dsp_silence = (dsp_options & DSP_OPT_ULAW) ? 0xff : 0x2a;
dsp_audio_law_to_s32 = (dsp_options & DSP_OPT_ULAW) ?
dsp_audio_ulaw_to_s32 : dsp_audio_alaw_to_s32;
dsp_audio_generate_s2law_table();
dsp_audio_generate_seven();
dsp_audio_generate_mix_table();
if (dsp_options & DSP_OPT_ULAW)
dsp_audio_generate_ulaw_samples();
dsp_audio_generate_volume_changes();
err = dsp_pipeline_module_init();
if (err) {
printk(KERN_ERR "mISDN_dsp: Can't initialize pipeline, "
"error(%d)\n", err);
return err;
}
err = mISDN_register_Bprotocol(&DSP);
if (err) {
printk(KERN_ERR "Can't register %s error(%d)\n", DSP.name, err);
return err;
}
/* set sample timer */
dsp_spl_tl.function = (void *)dsp_cmx_send;
dsp_spl_tl.data = 0;
init_timer(&dsp_spl_tl);
dsp_spl_tl.expires = jiffies + dsp_tics;
dsp_spl_jiffies = dsp_spl_tl.expires;
add_timer(&dsp_spl_tl);
return 0;
}
static void __exit dsp_cleanup(void)
{
mISDN_unregister_Bprotocol(&DSP);
del_timer_sync(&dsp_spl_tl);
if (!list_empty(&dsp_ilist)) {
printk(KERN_ERR "mISDN_dsp: Audio DSP object inst list not "
"empty.\n");
}
if (!list_empty(&conf_ilist)) {
printk(KERN_ERR "mISDN_dsp: Conference list not empty. Not "
"all memory freed.\n");
}
dsp_pipeline_module_exit();
}
module_init(dsp_init);
module_exit(dsp_cleanup);
| gpl-2.0 |
Krabappel2548/kernel_msm8x60 | drivers/pci/pci-label.c | 2528 | 8427 | /*
* Purpose: Export the firmware instance and label associated with
* a pci device to sysfs
* Copyright (C) 2010 Dell Inc.
* by Narendra K <Narendra_K@dell.com>,
* Jordan Hargrave <Jordan_Hargrave@dell.com>
*
* PCI Firmware Specification Revision 3.1 section 4.6.7 (DSM for Naming a
* PCI or PCI Express Device Under Operating Systems) defines an instance
* number and string name. This code retrieves them and exports them to sysfs.
* If the system firmware does not provide the ACPI _DSM (Device Specific
* Method), then the SMBIOS type 41 instance number and string is exported to
* sysfs.
*
* SMBIOS defines type 41 for onboard pci devices. This code retrieves
* the instance number and string from the type 41 record and exports
* it to sysfs.
*
* Please see http://linux.dell.com/wiki/index.php/Oss/libnetdevname for more
* information.
*/
#include <linux/dmi.h>
#include <linux/sysfs.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/nls.h>
#include <linux/acpi.h>
#include <linux/pci-acpi.h>
#include <acpi/acpi_bus.h>
#include "pci.h"
#define DEVICE_LABEL_DSM 0x07
#ifndef CONFIG_DMI
static inline int
pci_create_smbiosname_file(struct pci_dev *pdev)
{
return -1;
}
static inline void
pci_remove_smbiosname_file(struct pci_dev *pdev)
{
}
#else
enum smbios_attr_enum {
SMBIOS_ATTR_NONE = 0,
SMBIOS_ATTR_LABEL_SHOW,
SMBIOS_ATTR_INSTANCE_SHOW,
};
static mode_t
find_smbios_instance_string(struct pci_dev *pdev, char *buf,
enum smbios_attr_enum attribute)
{
const struct dmi_device *dmi;
struct dmi_dev_onboard *donboard;
int bus;
int devfn;
bus = pdev->bus->number;
devfn = pdev->devfn;
dmi = NULL;
while ((dmi = dmi_find_device(DMI_DEV_TYPE_DEV_ONBOARD,
NULL, dmi)) != NULL) {
donboard = dmi->device_data;
if (donboard && donboard->bus == bus &&
donboard->devfn == devfn) {
if (buf) {
if (attribute == SMBIOS_ATTR_INSTANCE_SHOW)
return scnprintf(buf, PAGE_SIZE,
"%d\n",
donboard->instance);
else if (attribute == SMBIOS_ATTR_LABEL_SHOW)
return scnprintf(buf, PAGE_SIZE,
"%s\n",
dmi->name);
}
return strlen(dmi->name);
}
}
return 0;
}
static mode_t
smbios_instance_string_exist(struct kobject *kobj, struct attribute *attr,
int n)
{
struct device *dev;
struct pci_dev *pdev;
dev = container_of(kobj, struct device, kobj);
pdev = to_pci_dev(dev);
return find_smbios_instance_string(pdev, NULL, SMBIOS_ATTR_NONE) ?
S_IRUGO : 0;
}
static ssize_t
smbioslabel_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct pci_dev *pdev;
pdev = to_pci_dev(dev);
return find_smbios_instance_string(pdev, buf,
SMBIOS_ATTR_LABEL_SHOW);
}
static ssize_t
smbiosinstance_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pci_dev *pdev;
pdev = to_pci_dev(dev);
return find_smbios_instance_string(pdev, buf,
SMBIOS_ATTR_INSTANCE_SHOW);
}
static struct device_attribute smbios_attr_label = {
.attr = {.name = "label", .mode = 0444},
.show = smbioslabel_show,
};
static struct device_attribute smbios_attr_instance = {
.attr = {.name = "index", .mode = 0444},
.show = smbiosinstance_show,
};
static struct attribute *smbios_attributes[] = {
&smbios_attr_label.attr,
&smbios_attr_instance.attr,
NULL,
};
static struct attribute_group smbios_attr_group = {
.attrs = smbios_attributes,
.is_visible = smbios_instance_string_exist,
};
static int
pci_create_smbiosname_file(struct pci_dev *pdev)
{
return sysfs_create_group(&pdev->dev.kobj, &smbios_attr_group);
}
static void
pci_remove_smbiosname_file(struct pci_dev *pdev)
{
sysfs_remove_group(&pdev->dev.kobj, &smbios_attr_group);
}
#endif
#ifndef CONFIG_ACPI
static inline int
pci_create_acpi_index_label_files(struct pci_dev *pdev)
{
return -1;
}
static inline int
pci_remove_acpi_index_label_files(struct pci_dev *pdev)
{
return -1;
}
static inline bool
device_has_dsm(struct device *dev)
{
return false;
}
#else
static const char device_label_dsm_uuid[] = {
0xD0, 0x37, 0xC9, 0xE5, 0x53, 0x35, 0x7A, 0x4D,
0x91, 0x17, 0xEA, 0x4D, 0x19, 0xC3, 0x43, 0x4D
};
enum acpi_attr_enum {
ACPI_ATTR_NONE = 0,
ACPI_ATTR_LABEL_SHOW,
ACPI_ATTR_INDEX_SHOW,
};
static void dsm_label_utf16s_to_utf8s(union acpi_object *obj, char *buf)
{
int len;
len = utf16s_to_utf8s((const wchar_t *)obj->
package.elements[1].string.pointer,
obj->package.elements[1].string.length,
UTF16_LITTLE_ENDIAN,
buf, PAGE_SIZE);
buf[len] = '\n';
}
static int
dsm_get_label(acpi_handle handle, int func,
struct acpi_buffer *output,
char *buf, enum acpi_attr_enum attribute)
{
struct acpi_object_list input;
union acpi_object params[4];
union acpi_object *obj;
int len = 0;
int err;
input.count = 4;
input.pointer = params;
params[0].type = ACPI_TYPE_BUFFER;
params[0].buffer.length = sizeof(device_label_dsm_uuid);
params[0].buffer.pointer = (char *)device_label_dsm_uuid;
params[1].type = ACPI_TYPE_INTEGER;
params[1].integer.value = 0x02;
params[2].type = ACPI_TYPE_INTEGER;
params[2].integer.value = func;
params[3].type = ACPI_TYPE_PACKAGE;
params[3].package.count = 0;
params[3].package.elements = NULL;
err = acpi_evaluate_object(handle, "_DSM", &input, output);
if (err)
return -1;
obj = (union acpi_object *)output->pointer;
switch (obj->type) {
case ACPI_TYPE_PACKAGE:
if (obj->package.count != 2)
break;
len = obj->package.elements[0].integer.value;
if (buf) {
if (attribute == ACPI_ATTR_INDEX_SHOW)
scnprintf(buf, PAGE_SIZE, "%llu\n",
obj->package.elements[0].integer.value);
else if (attribute == ACPI_ATTR_LABEL_SHOW)
dsm_label_utf16s_to_utf8s(obj, buf);
kfree(output->pointer);
return strlen(buf);
}
kfree(output->pointer);
return len;
break;
default:
kfree(output->pointer);
}
return -1;
}
static bool
device_has_dsm(struct device *dev)
{
acpi_handle handle;
struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle)
return FALSE;
if (dsm_get_label(handle, DEVICE_LABEL_DSM, &output, NULL,
ACPI_ATTR_NONE) > 0)
return TRUE;
return FALSE;
}
static mode_t
acpi_index_string_exist(struct kobject *kobj, struct attribute *attr, int n)
{
struct device *dev;
dev = container_of(kobj, struct device, kobj);
if (device_has_dsm(dev))
return S_IRUGO;
return 0;
}
static ssize_t
acpilabel_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
acpi_handle handle;
int length;
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle)
return -1;
length = dsm_get_label(handle, DEVICE_LABEL_DSM,
&output, buf, ACPI_ATTR_LABEL_SHOW);
if (length < 1)
return -1;
return length;
}
static ssize_t
acpiindex_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
acpi_handle handle;
int length;
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle)
return -1;
length = dsm_get_label(handle, DEVICE_LABEL_DSM,
&output, buf, ACPI_ATTR_INDEX_SHOW);
if (length < 0)
return -1;
return length;
}
static struct device_attribute acpi_attr_label = {
.attr = {.name = "label", .mode = 0444},
.show = acpilabel_show,
};
static struct device_attribute acpi_attr_index = {
.attr = {.name = "acpi_index", .mode = 0444},
.show = acpiindex_show,
};
static struct attribute *acpi_attributes[] = {
&acpi_attr_label.attr,
&acpi_attr_index.attr,
NULL,
};
static struct attribute_group acpi_attr_group = {
.attrs = acpi_attributes,
.is_visible = acpi_index_string_exist,
};
static int
pci_create_acpi_index_label_files(struct pci_dev *pdev)
{
return sysfs_create_group(&pdev->dev.kobj, &acpi_attr_group);
}
static int
pci_remove_acpi_index_label_files(struct pci_dev *pdev)
{
sysfs_remove_group(&pdev->dev.kobj, &acpi_attr_group);
return 0;
}
#endif
void pci_create_firmware_label_files(struct pci_dev *pdev)
{
if (device_has_dsm(&pdev->dev))
pci_create_acpi_index_label_files(pdev);
else
pci_create_smbiosname_file(pdev);
}
void pci_remove_firmware_label_files(struct pci_dev *pdev)
{
if (device_has_dsm(&pdev->dev))
pci_remove_acpi_index_label_files(pdev);
else
pci_remove_smbiosname_file(pdev);
}
| gpl-2.0 |
jamison904/d2tmo_kernel | drivers/mtd/nand/plat_nand.c | 2784 | 4540 | /*
* Generic NAND driver
*
* Author: Vitaly Wool <vitalywool@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
struct plat_nand_data {
struct nand_chip chip;
struct mtd_info mtd;
void __iomem *io_base;
int nr_parts;
struct mtd_partition *parts;
};
/*
* Probe for the NAND device.
*/
static int __devinit plat_nand_probe(struct platform_device *pdev)
{
struct platform_nand_data *pdata = pdev->dev.platform_data;
struct plat_nand_data *data;
struct resource *res;
int err = 0;
if (pdata->chip.nr_chips < 1) {
dev_err(&pdev->dev, "invalid number of chips specified\n");
return -EINVAL;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
/* Allocate memory for the device structure (and zero it) */
data = kzalloc(sizeof(struct plat_nand_data), GFP_KERNEL);
if (!data) {
dev_err(&pdev->dev, "failed to allocate device structure.\n");
return -ENOMEM;
}
if (!request_mem_region(res->start, resource_size(res),
dev_name(&pdev->dev))) {
dev_err(&pdev->dev, "request_mem_region failed\n");
err = -EBUSY;
goto out_free;
}
data->io_base = ioremap(res->start, resource_size(res));
if (data->io_base == NULL) {
dev_err(&pdev->dev, "ioremap failed\n");
err = -EIO;
goto out_release_io;
}
data->chip.priv = &data;
data->mtd.priv = &data->chip;
data->mtd.owner = THIS_MODULE;
data->mtd.name = dev_name(&pdev->dev);
data->chip.IO_ADDR_R = data->io_base;
data->chip.IO_ADDR_W = data->io_base;
data->chip.cmd_ctrl = pdata->ctrl.cmd_ctrl;
data->chip.dev_ready = pdata->ctrl.dev_ready;
data->chip.select_chip = pdata->ctrl.select_chip;
data->chip.write_buf = pdata->ctrl.write_buf;
data->chip.read_buf = pdata->ctrl.read_buf;
data->chip.chip_delay = pdata->chip.chip_delay;
data->chip.options |= pdata->chip.options;
data->chip.ecc.hwctl = pdata->ctrl.hwcontrol;
data->chip.ecc.layout = pdata->chip.ecclayout;
data->chip.ecc.mode = NAND_ECC_SOFT;
platform_set_drvdata(pdev, data);
/* Handle any platform specific setup */
if (pdata->ctrl.probe) {
err = pdata->ctrl.probe(pdev);
if (err)
goto out;
}
/* Scan to find existence of the device */
if (nand_scan(&data->mtd, pdata->chip.nr_chips)) {
err = -ENXIO;
goto out;
}
if (pdata->chip.part_probe_types) {
err = parse_mtd_partitions(&data->mtd,
pdata->chip.part_probe_types,
&data->parts, 0);
if (err > 0) {
mtd_device_register(&data->mtd, data->parts, err);
return 0;
}
}
if (pdata->chip.set_parts)
pdata->chip.set_parts(data->mtd.size, &pdata->chip);
if (pdata->chip.partitions) {
data->parts = pdata->chip.partitions;
err = mtd_device_register(&data->mtd, data->parts,
pdata->chip.nr_partitions);
} else
err = mtd_device_register(&data->mtd, NULL, 0);
if (!err)
return err;
nand_release(&data->mtd);
out:
if (pdata->ctrl.remove)
pdata->ctrl.remove(pdev);
platform_set_drvdata(pdev, NULL);
iounmap(data->io_base);
out_release_io:
release_mem_region(res->start, resource_size(res));
out_free:
kfree(data);
return err;
}
/*
* Remove a NAND device.
*/
static int __devexit plat_nand_remove(struct platform_device *pdev)
{
struct plat_nand_data *data = platform_get_drvdata(pdev);
struct platform_nand_data *pdata = pdev->dev.platform_data;
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
nand_release(&data->mtd);
if (data->parts && data->parts != pdata->chip.partitions)
kfree(data->parts);
if (pdata->ctrl.remove)
pdata->ctrl.remove(pdev);
iounmap(data->io_base);
release_mem_region(res->start, resource_size(res));
kfree(data);
return 0;
}
static struct platform_driver plat_nand_driver = {
.probe = plat_nand_probe,
.remove = __devexit_p(plat_nand_remove),
.driver = {
.name = "gen_nand",
.owner = THIS_MODULE,
},
};
static int __init plat_nand_init(void)
{
return platform_driver_register(&plat_nand_driver);
}
static void __exit plat_nand_exit(void)
{
platform_driver_unregister(&plat_nand_driver);
}
module_init(plat_nand_init);
module_exit(plat_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Vitaly Wool");
MODULE_DESCRIPTION("Simple generic NAND driver");
MODULE_ALIAS("platform:gen_nand");
| gpl-2.0 |
voodik/android_kernel_hardkernel_odroidu | drivers/mtd/devices/mtd_dataflash.c | 2784 | 25632 | /*
* Atmel AT45xxx DataFlash MTD driver for lightweight SPI framework
*
* Largely derived from at91_dataflash.c:
* Copyright (C) 2003-2005 SAN People (Pty) Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/math64.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
/*
* DataFlash is a kind of SPI flash. Most AT45 chips have two buffers in
* each chip, which may be used for double buffered I/O; but this driver
* doesn't (yet) use these for any kind of i/o overlap or prefetching.
*
* Sometimes DataFlash is packaged in MMC-format cards, although the
* MMC stack can't (yet?) distinguish between MMC and DataFlash
* protocols during enumeration.
*/
/* reads can bypass the buffers */
#define OP_READ_CONTINUOUS 0xE8
#define OP_READ_PAGE 0xD2
/* group B requests can run even while status reports "busy" */
#define OP_READ_STATUS 0xD7 /* group B */
/* move data between host and buffer */
#define OP_READ_BUFFER1 0xD4 /* group B */
#define OP_READ_BUFFER2 0xD6 /* group B */
#define OP_WRITE_BUFFER1 0x84 /* group B */
#define OP_WRITE_BUFFER2 0x87 /* group B */
/* erasing flash */
#define OP_ERASE_PAGE 0x81
#define OP_ERASE_BLOCK 0x50
/* move data between buffer and flash */
#define OP_TRANSFER_BUF1 0x53
#define OP_TRANSFER_BUF2 0x55
#define OP_MREAD_BUFFER1 0xD4
#define OP_MREAD_BUFFER2 0xD6
#define OP_MWERASE_BUFFER1 0x83
#define OP_MWERASE_BUFFER2 0x86
#define OP_MWRITE_BUFFER1 0x88 /* sector must be pre-erased */
#define OP_MWRITE_BUFFER2 0x89 /* sector must be pre-erased */
/* write to buffer, then write-erase to flash */
#define OP_PROGRAM_VIA_BUF1 0x82
#define OP_PROGRAM_VIA_BUF2 0x85
/* compare buffer to flash */
#define OP_COMPARE_BUF1 0x60
#define OP_COMPARE_BUF2 0x61
/* read flash to buffer, then write-erase to flash */
#define OP_REWRITE_VIA_BUF1 0x58
#define OP_REWRITE_VIA_BUF2 0x59
/* newer chips report JEDEC manufacturer and device IDs; chip
* serial number and OTP bits; and per-sector writeprotect.
*/
#define OP_READ_ID 0x9F
#define OP_READ_SECURITY 0x77
#define OP_WRITE_SECURITY_REVC 0x9A
#define OP_WRITE_SECURITY 0x9B /* revision D */
struct dataflash {
uint8_t command[4];
char name[24];
unsigned partitioned:1;
unsigned short page_offset; /* offset in flash address */
unsigned int page_size; /* of bytes per page */
struct mutex lock;
struct spi_device *spi;
struct mtd_info mtd;
};
/* ......................................................................... */
/*
* Return the status of the DataFlash device.
*/
static inline int dataflash_status(struct spi_device *spi)
{
/* NOTE: at45db321c over 25 MHz wants to write
* a dummy byte after the opcode...
*/
return spi_w8r8(spi, OP_READ_STATUS);
}
/*
* Poll the DataFlash device until it is READY.
* This usually takes 5-20 msec or so; more for sector erase.
*/
static int dataflash_waitready(struct spi_device *spi)
{
int status;
for (;;) {
status = dataflash_status(spi);
if (status < 0) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: status %d?\n",
dev_name(&spi->dev), status);
status = 0;
}
if (status & (1 << 7)) /* RDY/nBSY */
return status;
msleep(3);
}
}
/* ......................................................................... */
/*
* Erase pages of flash.
*/
static int dataflash_erase(struct mtd_info *mtd, struct erase_info *instr)
{
struct dataflash *priv = mtd->priv;
struct spi_device *spi = priv->spi;
struct spi_transfer x = { .tx_dma = 0, };
struct spi_message msg;
unsigned blocksize = priv->page_size << 3;
uint8_t *command;
uint32_t rem;
DEBUG(MTD_DEBUG_LEVEL2, "%s: erase addr=0x%llx len 0x%llx\n",
dev_name(&spi->dev), (long long)instr->addr,
(long long)instr->len);
/* Sanity checks */
if (instr->addr + instr->len > mtd->size)
return -EINVAL;
div_u64_rem(instr->len, priv->page_size, &rem);
if (rem)
return -EINVAL;
div_u64_rem(instr->addr, priv->page_size, &rem);
if (rem)
return -EINVAL;
spi_message_init(&msg);
x.tx_buf = command = priv->command;
x.len = 4;
spi_message_add_tail(&x, &msg);
mutex_lock(&priv->lock);
while (instr->len > 0) {
unsigned int pageaddr;
int status;
int do_block;
/* Calculate flash page address; use block erase (for speed) if
* we're at a block boundary and need to erase the whole block.
*/
pageaddr = div_u64(instr->addr, priv->page_size);
do_block = (pageaddr & 0x7) == 0 && instr->len >= blocksize;
pageaddr = pageaddr << priv->page_offset;
command[0] = do_block ? OP_ERASE_BLOCK : OP_ERASE_PAGE;
command[1] = (uint8_t)(pageaddr >> 16);
command[2] = (uint8_t)(pageaddr >> 8);
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "ERASE %s: (%x) %x %x %x [%i]\n",
do_block ? "block" : "page",
command[0], command[1], command[2], command[3],
pageaddr);
status = spi_sync(spi, &msg);
(void) dataflash_waitready(spi);
if (status < 0) {
printk(KERN_ERR "%s: erase %x, err %d\n",
dev_name(&spi->dev), pageaddr, status);
/* REVISIT: can retry instr->retries times; or
* giveup and instr->fail_addr = instr->addr;
*/
continue;
}
if (do_block) {
instr->addr += blocksize;
instr->len -= blocksize;
} else {
instr->addr += priv->page_size;
instr->len -= priv->page_size;
}
}
mutex_unlock(&priv->lock);
/* Inform MTD subsystem that erase is complete */
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return 0;
}
/*
* Read from the DataFlash device.
* from : Start offset in flash device
* len : Amount to read
* retlen : About of data actually read
* buf : Buffer containing the data
*/
static int dataflash_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
struct spi_transfer x[2] = { { .tx_dma = 0, }, };
struct spi_message msg;
unsigned int addr;
uint8_t *command;
int status;
DEBUG(MTD_DEBUG_LEVEL2, "%s: read 0x%x..0x%x\n",
dev_name(&priv->spi->dev), (unsigned)from, (unsigned)(from + len));
*retlen = 0;
/* Sanity checks */
if (!len)
return 0;
if (from + len > mtd->size)
return -EINVAL;
/* Calculate flash page/byte address */
addr = (((unsigned)from / priv->page_size) << priv->page_offset)
+ ((unsigned)from % priv->page_size);
command = priv->command;
DEBUG(MTD_DEBUG_LEVEL3, "READ: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
spi_message_init(&msg);
x[0].tx_buf = command;
x[0].len = 8;
spi_message_add_tail(&x[0], &msg);
x[1].rx_buf = buf;
x[1].len = len;
spi_message_add_tail(&x[1], &msg);
mutex_lock(&priv->lock);
/* Continuous read, max clock = f(car) which may be less than
* the peak rate available. Some chips support commands with
* fewer "don't care" bytes. Both buffers stay unchanged.
*/
command[0] = OP_READ_CONTINUOUS;
command[1] = (uint8_t)(addr >> 16);
command[2] = (uint8_t)(addr >> 8);
command[3] = (uint8_t)(addr >> 0);
/* plus 4 "don't care" bytes */
status = spi_sync(priv->spi, &msg);
mutex_unlock(&priv->lock);
if (status >= 0) {
*retlen = msg.actual_length - 8;
status = 0;
} else
DEBUG(MTD_DEBUG_LEVEL1, "%s: read %x..%x --> %d\n",
dev_name(&priv->spi->dev),
(unsigned)from, (unsigned)(from + len),
status);
return status;
}
/*
* Write to the DataFlash device.
* to : Start offset in flash device
* len : Amount to write
* retlen : Amount of data actually written
* buf : Buffer containing the data
*/
static int dataflash_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t * retlen, const u_char * buf)
{
struct dataflash *priv = mtd->priv;
struct spi_device *spi = priv->spi;
struct spi_transfer x[2] = { { .tx_dma = 0, }, };
struct spi_message msg;
unsigned int pageaddr, addr, offset, writelen;
size_t remaining = len;
u_char *writebuf = (u_char *) buf;
int status = -EINVAL;
uint8_t *command;
DEBUG(MTD_DEBUG_LEVEL2, "%s: write 0x%x..0x%x\n",
dev_name(&spi->dev), (unsigned)to, (unsigned)(to + len));
*retlen = 0;
/* Sanity checks */
if (!len)
return 0;
if ((to + len) > mtd->size)
return -EINVAL;
spi_message_init(&msg);
x[0].tx_buf = command = priv->command;
x[0].len = 4;
spi_message_add_tail(&x[0], &msg);
pageaddr = ((unsigned)to / priv->page_size);
offset = ((unsigned)to % priv->page_size);
if (offset + len > priv->page_size)
writelen = priv->page_size - offset;
else
writelen = len;
mutex_lock(&priv->lock);
while (remaining > 0) {
DEBUG(MTD_DEBUG_LEVEL3, "write @ %i:%i len=%i\n",
pageaddr, offset, writelen);
/* REVISIT:
* (a) each page in a sector must be rewritten at least
* once every 10K sibling erase/program operations.
* (b) for pages that are already erased, we could
* use WRITE+MWRITE not PROGRAM for ~30% speedup.
* (c) WRITE to buffer could be done while waiting for
* a previous MWRITE/MWERASE to complete ...
* (d) error handling here seems to be mostly missing.
*
* Two persistent bits per page, plus a per-sector counter,
* could support (a) and (b) ... we might consider using
* the second half of sector zero, which is just one block,
* to track that state. (On AT91, that sector should also
* support boot-from-DataFlash.)
*/
addr = pageaddr << priv->page_offset;
/* (1) Maybe transfer partial page to Buffer1 */
if (writelen != priv->page_size) {
command[0] = OP_TRANSFER_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "TRANSFER: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
status = spi_sync(spi, &msg);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: xfer %u -> %d \n",
dev_name(&spi->dev), addr, status);
(void) dataflash_waitready(priv->spi);
}
/* (2) Program full page via Buffer1 */
addr += offset;
command[0] = OP_PROGRAM_VIA_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = (addr & 0x000000FF);
DEBUG(MTD_DEBUG_LEVEL3, "PROGRAM: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
x[1].tx_buf = writebuf;
x[1].len = writelen;
spi_message_add_tail(x + 1, &msg);
status = spi_sync(spi, &msg);
spi_transfer_del(x + 1);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: pgm %u/%u -> %d \n",
dev_name(&spi->dev), addr, writelen, status);
(void) dataflash_waitready(priv->spi);
#ifdef CONFIG_MTD_DATAFLASH_WRITE_VERIFY
/* (3) Compare to Buffer1 */
addr = pageaddr << priv->page_offset;
command[0] = OP_COMPARE_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "COMPARE: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
status = spi_sync(spi, &msg);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: compare %u -> %d \n",
dev_name(&spi->dev), addr, status);
status = dataflash_waitready(priv->spi);
/* Check result of the compare operation */
if (status & (1 << 6)) {
printk(KERN_ERR "%s: compare page %u, err %d\n",
dev_name(&spi->dev), pageaddr, status);
remaining = 0;
status = -EIO;
break;
} else
status = 0;
#endif /* CONFIG_MTD_DATAFLASH_WRITE_VERIFY */
remaining = remaining - writelen;
pageaddr++;
offset = 0;
writebuf += writelen;
*retlen += writelen;
if (remaining > priv->page_size)
writelen = priv->page_size;
else
writelen = remaining;
}
mutex_unlock(&priv->lock);
return status;
}
/* ......................................................................... */
#ifdef CONFIG_MTD_DATAFLASH_OTP
static int dataflash_get_otp_info(struct mtd_info *mtd,
struct otp_info *info, size_t len)
{
/* Report both blocks as identical: bytes 0..64, locked.
* Unless the user block changed from all-ones, we can't
* tell whether it's still writable; so we assume it isn't.
*/
info->start = 0;
info->length = 64;
info->locked = 1;
return sizeof(*info);
}
static ssize_t otp_read(struct spi_device *spi, unsigned base,
uint8_t *buf, loff_t off, size_t len)
{
struct spi_message m;
size_t l;
uint8_t *scratch;
struct spi_transfer t;
int status;
if (off > 64)
return -EINVAL;
if ((off + len) > 64)
len = 64 - off;
if (len == 0)
return len;
spi_message_init(&m);
l = 4 + base + off + len;
scratch = kzalloc(l, GFP_KERNEL);
if (!scratch)
return -ENOMEM;
/* OUT: OP_READ_SECURITY, 3 don't-care bytes, zeroes
* IN: ignore 4 bytes, data bytes 0..N (max 127)
*/
scratch[0] = OP_READ_SECURITY;
memset(&t, 0, sizeof t);
t.tx_buf = scratch;
t.rx_buf = scratch;
t.len = l;
spi_message_add_tail(&t, &m);
dataflash_waitready(spi);
status = spi_sync(spi, &m);
if (status >= 0) {
memcpy(buf, scratch + 4 + base + off, len);
status = len;
}
kfree(scratch);
return status;
}
static int dataflash_read_fact_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
int status;
/* 64 bytes, from 0..63 ... start at 64 on-chip */
mutex_lock(&priv->lock);
status = otp_read(priv->spi, 64, buf, from, len);
mutex_unlock(&priv->lock);
if (status < 0)
return status;
*retlen = status;
return 0;
}
static int dataflash_read_user_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
int status;
/* 64 bytes, from 0..63 ... start at 0 on-chip */
mutex_lock(&priv->lock);
status = otp_read(priv->spi, 0, buf, from, len);
mutex_unlock(&priv->lock);
if (status < 0)
return status;
*retlen = status;
return 0;
}
static int dataflash_write_user_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct spi_message m;
const size_t l = 4 + 64;
uint8_t *scratch;
struct spi_transfer t;
struct dataflash *priv = mtd->priv;
int status;
if (len > 64)
return -EINVAL;
/* Strictly speaking, we *could* truncate the write ... but
* let's not do that for the only write that's ever possible.
*/
if ((from + len) > 64)
return -EINVAL;
/* OUT: OP_WRITE_SECURITY, 3 zeroes, 64 data-or-zero bytes
* IN: ignore all
*/
scratch = kzalloc(l, GFP_KERNEL);
if (!scratch)
return -ENOMEM;
scratch[0] = OP_WRITE_SECURITY;
memcpy(scratch + 4 + from, buf, len);
spi_message_init(&m);
memset(&t, 0, sizeof t);
t.tx_buf = scratch;
t.len = l;
spi_message_add_tail(&t, &m);
/* Write the OTP bits, if they've not yet been written.
* This modifies SRAM buffer1.
*/
mutex_lock(&priv->lock);
dataflash_waitready(priv->spi);
status = spi_sync(priv->spi, &m);
mutex_unlock(&priv->lock);
kfree(scratch);
if (status >= 0) {
status = 0;
*retlen = len;
}
return status;
}
static char *otp_setup(struct mtd_info *device, char revision)
{
device->get_fact_prot_info = dataflash_get_otp_info;
device->read_fact_prot_reg = dataflash_read_fact_otp;
device->get_user_prot_info = dataflash_get_otp_info;
device->read_user_prot_reg = dataflash_read_user_otp;
/* rev c parts (at45db321c and at45db1281 only!) use a
* different write procedure; not (yet?) implemented.
*/
if (revision > 'c')
device->write_user_prot_reg = dataflash_write_user_otp;
return ", OTP";
}
#else
static char *otp_setup(struct mtd_info *device, char revision)
{
return " (OTP)";
}
#endif
/* ......................................................................... */
/*
* Register DataFlash device with MTD subsystem.
*/
static int __devinit
add_dataflash_otp(struct spi_device *spi, char *name,
int nr_pages, int pagesize, int pageoffset, char revision)
{
struct dataflash *priv;
struct mtd_info *device;
struct flash_platform_data *pdata = spi->dev.platform_data;
char *otp_tag = "";
int err = 0;
struct mtd_partition *parts;
int nr_parts = 0;
priv = kzalloc(sizeof *priv, GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_init(&priv->lock);
priv->spi = spi;
priv->page_size = pagesize;
priv->page_offset = pageoffset;
/* name must be usable with cmdlinepart */
sprintf(priv->name, "spi%d.%d-%s",
spi->master->bus_num, spi->chip_select,
name);
device = &priv->mtd;
device->name = (pdata && pdata->name) ? pdata->name : priv->name;
device->size = nr_pages * pagesize;
device->erasesize = pagesize;
device->writesize = pagesize;
device->owner = THIS_MODULE;
device->type = MTD_DATAFLASH;
device->flags = MTD_WRITEABLE;
device->erase = dataflash_erase;
device->read = dataflash_read;
device->write = dataflash_write;
device->priv = priv;
device->dev.parent = &spi->dev;
if (revision >= 'c')
otp_tag = otp_setup(device, revision);
dev_info(&spi->dev, "%s (%lld KBytes) pagesize %d bytes%s\n",
name, (long long)((device->size + 1023) >> 10),
pagesize, otp_tag);
dev_set_drvdata(&spi->dev, priv);
if (mtd_has_cmdlinepart()) {
static const char *part_probes[] = { "cmdlinepart", NULL, };
nr_parts = parse_mtd_partitions(device, part_probes, &parts,
0);
}
if (nr_parts <= 0 && pdata && pdata->parts) {
parts = pdata->parts;
nr_parts = pdata->nr_parts;
}
if (nr_parts > 0) {
priv->partitioned = 1;
err = mtd_device_register(device, parts, nr_parts);
goto out;
}
if (mtd_device_register(device, NULL, 0) == 1)
err = -ENODEV;
out:
if (!err)
return 0;
dev_set_drvdata(&spi->dev, NULL);
kfree(priv);
return err;
}
static inline int __devinit
add_dataflash(struct spi_device *spi, char *name,
int nr_pages, int pagesize, int pageoffset)
{
return add_dataflash_otp(spi, name, nr_pages, pagesize,
pageoffset, 0);
}
struct flash_info {
char *name;
/* JEDEC id has a high byte of zero plus three data bytes:
* the manufacturer id, then a two byte device id.
*/
uint32_t jedec_id;
/* The size listed here is what works with OP_ERASE_PAGE. */
unsigned nr_pages;
uint16_t pagesize;
uint16_t pageoffset;
uint16_t flags;
#define SUP_POW2PS 0x0002 /* supports 2^N byte pages */
#define IS_POW2PS 0x0001 /* uses 2^N byte pages */
};
static struct flash_info __devinitdata dataflash_data [] = {
/*
* NOTE: chips with SUP_POW2PS (rev D and up) need two entries,
* one with IS_POW2PS and the other without. The entry with the
* non-2^N byte page size can't name exact chip revisions without
* losing backwards compatibility for cmdlinepart.
*
* These newer chips also support 128-byte security registers (with
* 64 bytes one-time-programmable) and software write-protection.
*/
{ "AT45DB011B", 0x1f2200, 512, 264, 9, SUP_POW2PS},
{ "at45db011d", 0x1f2200, 512, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB021B", 0x1f2300, 1024, 264, 9, SUP_POW2PS},
{ "at45db021d", 0x1f2300, 1024, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB041x", 0x1f2400, 2048, 264, 9, SUP_POW2PS},
{ "at45db041d", 0x1f2400, 2048, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB081B", 0x1f2500, 4096, 264, 9, SUP_POW2PS},
{ "at45db081d", 0x1f2500, 4096, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB161x", 0x1f2600, 4096, 528, 10, SUP_POW2PS},
{ "at45db161d", 0x1f2600, 4096, 512, 9, SUP_POW2PS | IS_POW2PS},
{ "AT45DB321x", 0x1f2700, 8192, 528, 10, 0}, /* rev C */
{ "AT45DB321x", 0x1f2701, 8192, 528, 10, SUP_POW2PS},
{ "at45db321d", 0x1f2701, 8192, 512, 9, SUP_POW2PS | IS_POW2PS},
{ "AT45DB642x", 0x1f2800, 8192, 1056, 11, SUP_POW2PS},
{ "at45db642d", 0x1f2800, 8192, 1024, 10, SUP_POW2PS | IS_POW2PS},
};
static struct flash_info *__devinit jedec_probe(struct spi_device *spi)
{
int tmp;
uint8_t code = OP_READ_ID;
uint8_t id[3];
uint32_t jedec;
struct flash_info *info;
int status;
/* JEDEC also defines an optional "extended device information"
* string for after vendor-specific data, after the three bytes
* we use here. Supporting some chips might require using it.
*
* If the vendor ID isn't Atmel's (0x1f), assume this call failed.
* That's not an error; only rev C and newer chips handle it, and
* only Atmel sells these chips.
*/
tmp = spi_write_then_read(spi, &code, 1, id, 3);
if (tmp < 0) {
DEBUG(MTD_DEBUG_LEVEL0, "%s: error %d reading JEDEC ID\n",
dev_name(&spi->dev), tmp);
return ERR_PTR(tmp);
}
if (id[0] != 0x1f)
return NULL;
jedec = id[0];
jedec = jedec << 8;
jedec |= id[1];
jedec = jedec << 8;
jedec |= id[2];
for (tmp = 0, info = dataflash_data;
tmp < ARRAY_SIZE(dataflash_data);
tmp++, info++) {
if (info->jedec_id == jedec) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: OTP, sector protect%s\n",
dev_name(&spi->dev),
(info->flags & SUP_POW2PS)
? ", binary pagesize" : ""
);
if (info->flags & SUP_POW2PS) {
status = dataflash_status(spi);
if (status < 0) {
DEBUG(MTD_DEBUG_LEVEL1,
"%s: status error %d\n",
dev_name(&spi->dev), status);
return ERR_PTR(status);
}
if (status & 0x1) {
if (info->flags & IS_POW2PS)
return info;
} else {
if (!(info->flags & IS_POW2PS))
return info;
}
} else
return info;
}
}
/*
* Treat other chips as errors ... we won't know the right page
* size (it might be binary) even when we can tell which density
* class is involved (legacy chip id scheme).
*/
dev_warn(&spi->dev, "JEDEC id %06x not handled\n", jedec);
return ERR_PTR(-ENODEV);
}
/*
* Detect and initialize DataFlash device, using JEDEC IDs on newer chips
* or else the ID code embedded in the status bits:
*
* Device Density ID code #Pages PageSize Offset
* AT45DB011B 1Mbit (128K) xx0011xx (0x0c) 512 264 9
* AT45DB021B 2Mbit (256K) xx0101xx (0x14) 1024 264 9
* AT45DB041B 4Mbit (512K) xx0111xx (0x1c) 2048 264 9
* AT45DB081B 8Mbit (1M) xx1001xx (0x24) 4096 264 9
* AT45DB0161B 16Mbit (2M) xx1011xx (0x2c) 4096 528 10
* AT45DB0321B 32Mbit (4M) xx1101xx (0x34) 8192 528 10
* AT45DB0642 64Mbit (8M) xx111xxx (0x3c) 8192 1056 11
* AT45DB1282 128Mbit (16M) xx0100xx (0x10) 16384 1056 11
*/
static int __devinit dataflash_probe(struct spi_device *spi)
{
int status;
struct flash_info *info;
/*
* Try to detect dataflash by JEDEC ID.
* If it succeeds we know we have either a C or D part.
* D will support power of 2 pagesize option.
* Both support the security register, though with different
* write procedures.
*/
info = jedec_probe(spi);
if (IS_ERR(info))
return PTR_ERR(info);
if (info != NULL)
return add_dataflash_otp(spi, info->name, info->nr_pages,
info->pagesize, info->pageoffset,
(info->flags & SUP_POW2PS) ? 'd' : 'c');
/*
* Older chips support only legacy commands, identifing
* capacity using bits in the status byte.
*/
status = dataflash_status(spi);
if (status <= 0 || status == 0xff) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: status error %d\n",
dev_name(&spi->dev), status);
if (status == 0 || status == 0xff)
status = -ENODEV;
return status;
}
/* if there's a device there, assume it's dataflash.
* board setup should have set spi->max_speed_max to
* match f(car) for continuous reads, mode 0 or 3.
*/
switch (status & 0x3c) {
case 0x0c: /* 0 0 1 1 x x */
status = add_dataflash(spi, "AT45DB011B", 512, 264, 9);
break;
case 0x14: /* 0 1 0 1 x x */
status = add_dataflash(spi, "AT45DB021B", 1024, 264, 9);
break;
case 0x1c: /* 0 1 1 1 x x */
status = add_dataflash(spi, "AT45DB041x", 2048, 264, 9);
break;
case 0x24: /* 1 0 0 1 x x */
status = add_dataflash(spi, "AT45DB081B", 4096, 264, 9);
break;
case 0x2c: /* 1 0 1 1 x x */
status = add_dataflash(spi, "AT45DB161x", 4096, 528, 10);
break;
case 0x34: /* 1 1 0 1 x x */
status = add_dataflash(spi, "AT45DB321x", 8192, 528, 10);
break;
case 0x38: /* 1 1 1 x x x */
case 0x3c:
status = add_dataflash(spi, "AT45DB642x", 8192, 1056, 11);
break;
/* obsolete AT45DB1282 not (yet?) supported */
default:
DEBUG(MTD_DEBUG_LEVEL1, "%s: unsupported device (%x)\n",
dev_name(&spi->dev), status & 0x3c);
status = -ENODEV;
}
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: add_dataflash --> %d\n",
dev_name(&spi->dev), status);
return status;
}
static int __devexit dataflash_remove(struct spi_device *spi)
{
struct dataflash *flash = dev_get_drvdata(&spi->dev);
int status;
DEBUG(MTD_DEBUG_LEVEL1, "%s: remove\n", dev_name(&spi->dev));
status = mtd_device_unregister(&flash->mtd);
if (status == 0) {
dev_set_drvdata(&spi->dev, NULL);
kfree(flash);
}
return status;
}
static struct spi_driver dataflash_driver = {
.driver = {
.name = "mtd_dataflash",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = dataflash_probe,
.remove = __devexit_p(dataflash_remove),
/* FIXME: investigate suspend and resume... */
};
static int __init dataflash_init(void)
{
return spi_register_driver(&dataflash_driver);
}
module_init(dataflash_init);
static void __exit dataflash_exit(void)
{
spi_unregister_driver(&dataflash_driver);
}
module_exit(dataflash_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Andrew Victor, David Brownell");
MODULE_DESCRIPTION("MTD DataFlash driver");
MODULE_ALIAS("spi:mtd_dataflash");
| gpl-2.0 |
MROM/android_kernel_bn_encore | drivers/pps/clients/pps_parport.c | 3040 | 6427 | /*
* pps_parport.c -- kernel parallel port PPS client
*
*
* Copyright (C) 2009 Alexander Gordeev <lasaine@lvk.cs.msu.su>
*
* 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.
*/
/*
* TODO:
* implement echo over SEL pin
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/irqnr.h>
#include <linux/time.h>
#include <linux/parport.h>
#include <linux/pps_kernel.h>
#define DRVDESC "parallel port PPS client"
/* module parameters */
#define CLEAR_WAIT_MAX 100
#define CLEAR_WAIT_MAX_ERRORS 5
static unsigned int clear_wait = 100;
MODULE_PARM_DESC(clear_wait,
"Maximum number of port reads when polling for signal clear,"
" zero turns clear edge capture off entirely");
module_param(clear_wait, uint, 0);
/* internal per port structure */
struct pps_client_pp {
struct pardevice *pardev; /* parport device */
struct pps_device *pps; /* PPS device */
unsigned int cw; /* port clear timeout */
unsigned int cw_err; /* number of timeouts */
};
static inline int signal_is_set(struct parport *port)
{
return (port->ops->read_status(port) & PARPORT_STATUS_ACK) != 0;
}
/* parport interrupt handler */
static void parport_irq(void *handle)
{
struct pps_event_time ts_assert, ts_clear;
struct pps_client_pp *dev = handle;
struct parport *port = dev->pardev->port;
unsigned int i;
unsigned long flags;
/* first of all we get the time stamp... */
pps_get_ts(&ts_assert);
if (dev->cw == 0)
/* clear edge capture disabled */
goto out_assert;
/* try capture the clear edge */
/* We have to disable interrupts here. The idea is to prevent
* other interrupts on the same processor to introduce random
* lags while polling the port. Reading from IO port is known
* to take approximately 1us while other interrupt handlers can
* take much more potentially.
*
* Interrupts won't be disabled for a long time because the
* number of polls is limited by clear_wait parameter which is
* kept rather low. So it should never be an issue.
*/
local_irq_save(flags);
/* check the signal (no signal means the pulse is lost this time) */
if (!signal_is_set(port)) {
local_irq_restore(flags);
dev_err(dev->pps->dev, "lost the signal\n");
goto out_assert;
}
/* poll the port until the signal is unset */
for (i = dev->cw; i; i--)
if (!signal_is_set(port)) {
pps_get_ts(&ts_clear);
local_irq_restore(flags);
dev->cw_err = 0;
goto out_both;
}
local_irq_restore(flags);
/* timeout */
dev->cw_err++;
if (dev->cw_err >= CLEAR_WAIT_MAX_ERRORS) {
dev_err(dev->pps->dev, "disabled clear edge capture after %d"
" timeouts\n", dev->cw_err);
dev->cw = 0;
dev->cw_err = 0;
}
out_assert:
/* fire assert event */
pps_event(dev->pps, &ts_assert,
PPS_CAPTUREASSERT, NULL);
return;
out_both:
/* fire assert event */
pps_event(dev->pps, &ts_assert,
PPS_CAPTUREASSERT, NULL);
/* fire clear event */
pps_event(dev->pps, &ts_clear,
PPS_CAPTURECLEAR, NULL);
return;
}
/* the PPS echo function */
static void pps_echo(struct pps_device *pps, int event, void *data)
{
dev_info(pps->dev, "echo %s %s\n",
event & PPS_CAPTUREASSERT ? "assert" : "",
event & PPS_CAPTURECLEAR ? "clear" : "");
}
static void parport_attach(struct parport *port)
{
struct pps_client_pp *device;
struct pps_source_info info = {
.name = KBUILD_MODNAME,
.path = "",
.mode = PPS_CAPTUREBOTH | \
PPS_OFFSETASSERT | PPS_OFFSETCLEAR | \
PPS_ECHOASSERT | PPS_ECHOCLEAR | \
PPS_CANWAIT | PPS_TSFMT_TSPEC,
.echo = pps_echo,
.owner = THIS_MODULE,
.dev = NULL
};
device = kzalloc(sizeof(struct pps_client_pp), GFP_KERNEL);
if (!device) {
pr_err("memory allocation failed, not attaching\n");
return;
}
device->pardev = parport_register_device(port, KBUILD_MODNAME,
NULL, NULL, parport_irq, PARPORT_FLAG_EXCL, device);
if (!device->pardev) {
pr_err("couldn't register with %s\n", port->name);
goto err_free;
}
if (parport_claim_or_block(device->pardev) < 0) {
pr_err("couldn't claim %s\n", port->name);
goto err_unregister_dev;
}
device->pps = pps_register_source(&info,
PPS_CAPTUREBOTH | PPS_OFFSETASSERT | PPS_OFFSETCLEAR);
if (device->pps == NULL) {
pr_err("couldn't register PPS source\n");
goto err_release_dev;
}
device->cw = clear_wait;
port->ops->enable_irq(port);
pr_info("attached to %s\n", port->name);
return;
err_release_dev:
parport_release(device->pardev);
err_unregister_dev:
parport_unregister_device(device->pardev);
err_free:
kfree(device);
}
static void parport_detach(struct parport *port)
{
struct pardevice *pardev = port->cad;
struct pps_client_pp *device;
/* FIXME: oooh, this is ugly! */
if (strcmp(pardev->name, KBUILD_MODNAME))
/* not our port */
return;
device = pardev->private;
port->ops->disable_irq(port);
pps_unregister_source(device->pps);
parport_release(pardev);
parport_unregister_device(pardev);
kfree(device);
}
static struct parport_driver pps_parport_driver = {
.name = KBUILD_MODNAME,
.attach = parport_attach,
.detach = parport_detach,
};
/* module staff */
static int __init pps_parport_init(void)
{
int ret;
pr_info(DRVDESC "\n");
if (clear_wait > CLEAR_WAIT_MAX) {
pr_err("clear_wait value should be not greater"
" then %d\n", CLEAR_WAIT_MAX);
return -EINVAL;
}
ret = parport_register_driver(&pps_parport_driver);
if (ret) {
pr_err("unable to register with parport\n");
return ret;
}
return 0;
}
static void __exit pps_parport_exit(void)
{
parport_unregister_driver(&pps_parport_driver);
}
module_init(pps_parport_init);
module_exit(pps_parport_exit);
MODULE_AUTHOR("Alexander Gordeev <lasaine@lvk.cs.msu.su>");
MODULE_DESCRIPTION(DRVDESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
TeamEOS/kernel_google_msm | drivers/gpu/drm/drm_fops.c | 3296 | 17657 | /**
* \file drm_fops.c
* File operations for DRM
*
* \author Rickard E. (Rik) Faith <faith@valinux.com>
* \author Daryll Strauss <daryll@valinux.com>
* \author Gareth Hughes <gareth@valinux.com>
*/
/*
* Created: Mon Jan 4 08:58:31 1999 by faith@valinux.com
*
* Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
* Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
* 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
* VA LINUX SYSTEMS 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 <linux/poll.h>
#include <linux/slab.h>
#include <linux/module.h>
/* from BKL pushdown: note that nothing else serializes idr_find() */
DEFINE_MUTEX(drm_global_mutex);
EXPORT_SYMBOL(drm_global_mutex);
static int drm_open_helper(struct inode *inode, struct file *filp,
struct drm_device * dev);
static int drm_setup(struct drm_device * dev)
{
int i;
int ret;
if (dev->driver->firstopen) {
ret = dev->driver->firstopen(dev);
if (ret != 0)
return ret;
}
atomic_set(&dev->ioctl_count, 0);
atomic_set(&dev->vma_count, 0);
if (drm_core_check_feature(dev, DRIVER_HAVE_DMA) &&
!drm_core_check_feature(dev, DRIVER_MODESET)) {
dev->buf_use = 0;
atomic_set(&dev->buf_alloc, 0);
i = drm_dma_setup(dev);
if (i < 0)
return i;
}
for (i = 0; i < ARRAY_SIZE(dev->counts); i++)
atomic_set(&dev->counts[i], 0);
dev->sigdata.lock = NULL;
dev->queue_count = 0;
dev->queue_reserved = 0;
dev->queue_slots = 0;
dev->queuelist = NULL;
dev->context_flag = 0;
dev->interrupt_flag = 0;
dev->dma_flag = 0;
dev->last_context = 0;
dev->last_switch = 0;
dev->last_checked = 0;
init_waitqueue_head(&dev->context_wait);
dev->if_version = 0;
dev->ctx_start = 0;
dev->lck_start = 0;
dev->buf_async = NULL;
init_waitqueue_head(&dev->buf_readers);
init_waitqueue_head(&dev->buf_writers);
DRM_DEBUG("\n");
/*
* The kernel's context could be created here, but is now created
* in drm_dma_enqueue. This is more resource-efficient for
* hardware that does not do DMA, but may mean that
* drm_select_queue fails between the time the interrupt is
* initialized and the time the queues are initialized.
*/
return 0;
}
/**
* Open file.
*
* \param inode device inode
* \param filp file pointer.
* \return zero on success or a negative number on failure.
*
* Searches the DRM device with the same minor number, calls open_helper(), and
* increments the device open count. If the open count was previous at zero,
* i.e., it's the first that the device is open, then calls setup().
*/
int drm_open(struct inode *inode, struct file *filp)
{
struct drm_device *dev = NULL;
int minor_id = iminor(inode);
struct drm_minor *minor;
int retcode = 0;
minor = idr_find(&drm_minors_idr, minor_id);
if (!minor)
return -ENODEV;
if (!(dev = minor->dev))
return -ENODEV;
if (drm_device_is_unplugged(dev))
return -ENODEV;
retcode = drm_open_helper(inode, filp, dev);
if (!retcode) {
atomic_inc(&dev->counts[_DRM_STAT_OPENS]);
if (!dev->open_count++)
retcode = drm_setup(dev);
}
if (!retcode) {
mutex_lock(&dev->struct_mutex);
if (minor->type == DRM_MINOR_LEGACY) {
if (dev->dev_mapping == NULL)
dev->dev_mapping = inode->i_mapping;
else if (dev->dev_mapping != inode->i_mapping)
retcode = -ENODEV;
}
mutex_unlock(&dev->struct_mutex);
}
return retcode;
}
EXPORT_SYMBOL(drm_open);
/**
* File \c open operation.
*
* \param inode device inode.
* \param filp file pointer.
*
* Puts the dev->fops corresponding to the device minor number into
* \p filp, call the \c open method, and restore the file operations.
*/
int drm_stub_open(struct inode *inode, struct file *filp)
{
struct drm_device *dev = NULL;
struct drm_minor *minor;
int minor_id = iminor(inode);
int err = -ENODEV;
const struct file_operations *old_fops;
DRM_DEBUG("\n");
mutex_lock(&drm_global_mutex);
minor = idr_find(&drm_minors_idr, minor_id);
if (!minor)
goto out;
if (!(dev = minor->dev))
goto out;
if (drm_device_is_unplugged(dev))
goto out;
old_fops = filp->f_op;
filp->f_op = fops_get(dev->driver->fops);
if (filp->f_op == NULL) {
filp->f_op = old_fops;
goto out;
}
if (filp->f_op->open && (err = filp->f_op->open(inode, filp))) {
fops_put(filp->f_op);
filp->f_op = fops_get(old_fops);
}
fops_put(old_fops);
out:
mutex_unlock(&drm_global_mutex);
return err;
}
/**
* Check whether DRI will run on this CPU.
*
* \return non-zero if the DRI will run on this CPU, or zero otherwise.
*/
static int drm_cpu_valid(void)
{
#if defined(__i386__)
if (boot_cpu_data.x86 == 3)
return 0; /* No cmpxchg on a 386 */
#endif
#if defined(__sparc__) && !defined(__sparc_v9__)
return 0; /* No cmpxchg before v9 sparc. */
#endif
return 1;
}
/**
* Called whenever a process opens /dev/drm.
*
* \param inode device inode.
* \param filp file pointer.
* \param dev device.
* \return zero on success or a negative number on failure.
*
* Creates and initializes a drm_file structure for the file private data in \p
* filp and add it into the double linked list in \p dev.
*/
static int drm_open_helper(struct inode *inode, struct file *filp,
struct drm_device * dev)
{
int minor_id = iminor(inode);
struct drm_file *priv;
int ret;
if (filp->f_flags & O_EXCL)
return -EBUSY; /* No exclusive opens */
if (!drm_cpu_valid())
return -EINVAL;
if (dev->switch_power_state != DRM_SWITCH_POWER_ON)
return -EINVAL;
DRM_DEBUG("pid = %d, minor = %d\n", task_pid_nr(current), minor_id);
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
filp->private_data = priv;
priv->filp = filp;
priv->uid = current_euid();
priv->pid = task_pid_nr(current);
priv->minor = idr_find(&drm_minors_idr, minor_id);
priv->ioctl_count = 0;
/* for compatibility root is always authenticated */
priv->authenticated = capable(CAP_SYS_ADMIN);
priv->lock_count = 0;
INIT_LIST_HEAD(&priv->lhead);
INIT_LIST_HEAD(&priv->fbs);
INIT_LIST_HEAD(&priv->event_list);
init_waitqueue_head(&priv->event_wait);
priv->event_space = 4096; /* set aside 4k for event buffer */
if (dev->driver->driver_features & DRIVER_GEM)
drm_gem_open(dev, priv);
if (drm_core_check_feature(dev, DRIVER_PRIME))
drm_prime_init_file_private(&priv->prime);
if (dev->driver->open) {
ret = dev->driver->open(dev, priv);
if (ret < 0)
goto out_free;
}
/* if there is no current master make this fd it */
mutex_lock(&dev->struct_mutex);
if (!priv->minor->master) {
/* create a new master */
priv->minor->master = drm_master_create(priv->minor);
if (!priv->minor->master) {
mutex_unlock(&dev->struct_mutex);
ret = -ENOMEM;
goto out_free;
}
priv->is_master = 1;
/* take another reference for the copy in the local file priv */
priv->master = drm_master_get(priv->minor->master);
priv->authenticated = 1;
mutex_unlock(&dev->struct_mutex);
if (dev->driver->master_create) {
ret = dev->driver->master_create(dev, priv->master);
if (ret) {
mutex_lock(&dev->struct_mutex);
/* drop both references if this fails */
drm_master_put(&priv->minor->master);
drm_master_put(&priv->master);
mutex_unlock(&dev->struct_mutex);
goto out_free;
}
}
mutex_lock(&dev->struct_mutex);
if (dev->driver->master_set) {
ret = dev->driver->master_set(dev, priv, true);
if (ret) {
/* drop both references if this fails */
drm_master_put(&priv->minor->master);
drm_master_put(&priv->master);
mutex_unlock(&dev->struct_mutex);
goto out_free;
}
}
mutex_unlock(&dev->struct_mutex);
} else {
/* get a reference to the master */
priv->master = drm_master_get(priv->minor->master);
mutex_unlock(&dev->struct_mutex);
}
mutex_lock(&dev->struct_mutex);
list_add(&priv->lhead, &dev->filelist);
mutex_unlock(&dev->struct_mutex);
#ifdef __alpha__
/*
* Default the hose
*/
if (!dev->hose) {
struct pci_dev *pci_dev;
pci_dev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, NULL);
if (pci_dev) {
dev->hose = pci_dev->sysdata;
pci_dev_put(pci_dev);
}
if (!dev->hose) {
struct pci_bus *b = pci_bus_b(pci_root_buses.next);
if (b)
dev->hose = b->sysdata;
}
}
#endif
return 0;
out_free:
kfree(priv);
filp->private_data = NULL;
return ret;
}
/** No-op. */
int drm_fasync(int fd, struct file *filp, int on)
{
struct drm_file *priv = filp->private_data;
struct drm_device *dev = priv->minor->dev;
DRM_DEBUG("fd = %d, device = 0x%lx\n", fd,
(long)old_encode_dev(priv->minor->device));
return fasync_helper(fd, filp, on, &dev->buf_async);
}
EXPORT_SYMBOL(drm_fasync);
/*
* Reclaim locked buffers; note that this may be a bad idea if the current
* context doesn't have the hw lock...
*/
static void drm_reclaim_locked_buffers(struct drm_device *dev, struct file *f)
{
struct drm_file *file_priv = f->private_data;
if (drm_i_have_hw_lock(dev, file_priv)) {
dev->driver->reclaim_buffers_locked(dev, file_priv);
} else {
unsigned long _end = jiffies + 3 * DRM_HZ;
int locked = 0;
drm_idlelock_take(&file_priv->master->lock);
/*
* Wait for a while.
*/
do {
spin_lock_bh(&file_priv->master->lock.spinlock);
locked = file_priv->master->lock.idle_has_lock;
spin_unlock_bh(&file_priv->master->lock.spinlock);
if (locked)
break;
schedule();
} while (!time_after_eq(jiffies, _end));
if (!locked) {
DRM_ERROR("reclaim_buffers_locked() deadlock. Please rework this\n"
"\tdriver to use reclaim_buffers_idlelocked() instead.\n"
"\tI will go on reclaiming the buffers anyway.\n");
}
dev->driver->reclaim_buffers_locked(dev, file_priv);
drm_idlelock_release(&file_priv->master->lock);
}
}
static void drm_master_release(struct drm_device *dev, struct file *filp)
{
struct drm_file *file_priv = filp->private_data;
if (dev->driver->reclaim_buffers_locked &&
file_priv->master->lock.hw_lock)
drm_reclaim_locked_buffers(dev, filp);
if (dev->driver->reclaim_buffers_idlelocked &&
file_priv->master->lock.hw_lock) {
drm_idlelock_take(&file_priv->master->lock);
dev->driver->reclaim_buffers_idlelocked(dev, file_priv);
drm_idlelock_release(&file_priv->master->lock);
}
if (drm_i_have_hw_lock(dev, file_priv)) {
DRM_DEBUG("File %p released, freeing lock for context %d\n",
filp, _DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock));
drm_lock_free(&file_priv->master->lock,
_DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock));
}
if (drm_core_check_feature(dev, DRIVER_HAVE_DMA) &&
!dev->driver->reclaim_buffers_locked) {
dev->driver->reclaim_buffers(dev, file_priv);
}
}
static void drm_events_release(struct drm_file *file_priv)
{
struct drm_device *dev = file_priv->minor->dev;
struct drm_pending_event *e, *et;
struct drm_pending_vblank_event *v, *vt;
unsigned long flags;
spin_lock_irqsave(&dev->event_lock, flags);
/* Remove pending flips */
list_for_each_entry_safe(v, vt, &dev->vblank_event_list, base.link)
if (v->base.file_priv == file_priv) {
list_del(&v->base.link);
drm_vblank_put(dev, v->pipe);
v->base.destroy(&v->base);
}
/* Remove unconsumed events */
list_for_each_entry_safe(e, et, &file_priv->event_list, link)
e->destroy(e);
spin_unlock_irqrestore(&dev->event_lock, flags);
}
/**
* Release file.
*
* \param inode device inode
* \param file_priv DRM file private.
* \return zero on success or a negative number on failure.
*
* If the hardware lock is held then free it, and take it again for the kernel
* context since it's necessary to reclaim buffers. Unlink the file private
* data from its list and free it. Decreases the open count and if it reaches
* zero calls drm_lastclose().
*/
int drm_release(struct inode *inode, struct file *filp)
{
struct drm_file *file_priv = filp->private_data;
struct drm_device *dev = file_priv->minor->dev;
int retcode = 0;
mutex_lock(&drm_global_mutex);
DRM_DEBUG("open_count = %d\n", dev->open_count);
if (dev->driver->preclose)
dev->driver->preclose(dev, file_priv);
/* ========================================================
* Begin inline drm_release
*/
DRM_DEBUG("pid = %d, device = 0x%lx, open_count = %d\n",
task_pid_nr(current),
(long)old_encode_dev(file_priv->minor->device),
dev->open_count);
/* Release any auth tokens that might point to this file_priv,
(do that under the drm_global_mutex) */
if (file_priv->magic)
(void) drm_remove_magic(file_priv->master, file_priv->magic);
/* if the master has gone away we can't do anything with the lock */
if (file_priv->minor->master)
drm_master_release(dev, filp);
drm_events_release(file_priv);
if (dev->driver->driver_features & DRIVER_MODESET)
drm_fb_release(file_priv);
if (dev->driver->driver_features & DRIVER_GEM)
drm_gem_release(dev, file_priv);
mutex_lock(&dev->ctxlist_mutex);
if (!list_empty(&dev->ctxlist)) {
struct drm_ctx_list *pos, *n;
list_for_each_entry_safe(pos, n, &dev->ctxlist, head) {
if (pos->tag == file_priv &&
pos->handle != DRM_KERNEL_CONTEXT) {
if (dev->driver->context_dtor)
dev->driver->context_dtor(dev,
pos->handle);
drm_ctxbitmap_free(dev, pos->handle);
list_del(&pos->head);
kfree(pos);
--dev->ctx_count;
}
}
}
mutex_unlock(&dev->ctxlist_mutex);
mutex_lock(&dev->struct_mutex);
if (file_priv->is_master) {
struct drm_master *master = file_priv->master;
struct drm_file *temp;
list_for_each_entry(temp, &dev->filelist, lhead) {
if ((temp->master == file_priv->master) &&
(temp != file_priv))
temp->authenticated = 0;
}
/**
* Since the master is disappearing, so is the
* possibility to lock.
*/
if (master->lock.hw_lock) {
if (dev->sigdata.lock == master->lock.hw_lock)
dev->sigdata.lock = NULL;
master->lock.hw_lock = NULL;
master->lock.file_priv = NULL;
wake_up_interruptible_all(&master->lock.lock_queue);
}
if (file_priv->minor->master == file_priv->master) {
/* drop the reference held my the minor */
if (dev->driver->master_drop)
dev->driver->master_drop(dev, file_priv, true);
drm_master_put(&file_priv->minor->master);
}
}
/* drop the reference held my the file priv */
drm_master_put(&file_priv->master);
file_priv->is_master = 0;
list_del(&file_priv->lhead);
mutex_unlock(&dev->struct_mutex);
if (dev->driver->postclose)
dev->driver->postclose(dev, file_priv);
if (drm_core_check_feature(dev, DRIVER_PRIME))
drm_prime_destroy_file_private(&file_priv->prime);
kfree(file_priv);
/* ========================================================
* End inline drm_release
*/
atomic_inc(&dev->counts[_DRM_STAT_CLOSES]);
if (!--dev->open_count) {
if (atomic_read(&dev->ioctl_count)) {
DRM_ERROR("Device busy: %d\n",
atomic_read(&dev->ioctl_count));
retcode = -EBUSY;
} else
retcode = drm_lastclose(dev);
if (drm_device_is_unplugged(dev))
drm_put_dev(dev);
}
mutex_unlock(&drm_global_mutex);
return retcode;
}
EXPORT_SYMBOL(drm_release);
static bool
drm_dequeue_event(struct drm_file *file_priv,
size_t total, size_t max, struct drm_pending_event **out)
{
struct drm_device *dev = file_priv->minor->dev;
struct drm_pending_event *e;
unsigned long flags;
bool ret = false;
spin_lock_irqsave(&dev->event_lock, flags);
*out = NULL;
if (list_empty(&file_priv->event_list))
goto out;
e = list_first_entry(&file_priv->event_list,
struct drm_pending_event, link);
if (e->event->length + total > max)
goto out;
file_priv->event_space += e->event->length;
list_del(&e->link);
*out = e;
ret = true;
out:
spin_unlock_irqrestore(&dev->event_lock, flags);
return ret;
}
ssize_t drm_read(struct file *filp, char __user *buffer,
size_t count, loff_t *offset)
{
struct drm_file *file_priv = filp->private_data;
struct drm_pending_event *e;
size_t total;
ssize_t ret;
ret = wait_event_interruptible(file_priv->event_wait,
!list_empty(&file_priv->event_list));
if (ret < 0)
return ret;
total = 0;
while (drm_dequeue_event(file_priv, total, count, &e)) {
if (copy_to_user(buffer + total,
e->event, e->event->length)) {
total = -EFAULT;
break;
}
total += e->event->length;
e->destroy(e);
}
return total;
}
EXPORT_SYMBOL(drm_read);
unsigned int drm_poll(struct file *filp, struct poll_table_struct *wait)
{
struct drm_file *file_priv = filp->private_data;
unsigned int mask = 0;
poll_wait(filp, &file_priv->event_wait, wait);
if (!list_empty(&file_priv->event_list))
mask |= POLLIN | POLLRDNORM;
return mask;
}
EXPORT_SYMBOL(drm_poll);
| gpl-2.0 |
davidmueller13/TW_Kernel_LP | drivers/edac/ppc4xx_edac.c | 4576 | 40058 | /*
* Copyright (c) 2008 Nuovation System Designs, LLC
* Grant Erickson <gerickson@nuovations.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/edac.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include <linux/types.h>
#include <asm/dcr.h>
#include "edac_core.h"
#include "ppc4xx_edac.h"
/*
* This file implements a driver for monitoring and handling events
* associated with the IMB DDR2 ECC controller found in the AMCC/IBM
* 405EX[r], 440SP, 440SPe, 460EX, 460GT and 460SX.
*
* As realized in the 405EX[r], this controller features:
*
* - Support for registered- and non-registered DDR1 and DDR2 memory.
* - 32-bit or 16-bit memory interface with optional ECC.
*
* o ECC support includes:
*
* - 4-bit SEC/DED
* - Aligned-nibble error detect
* - Bypass mode
*
* - Two (2) memory banks/ranks.
* - Up to 1 GiB per bank/rank in 32-bit mode and up to 512 MiB per
* bank/rank in 16-bit mode.
*
* As realized in the 440SP and 440SPe, this controller changes/adds:
*
* - 64-bit or 32-bit memory interface with optional ECC.
*
* o ECC support includes:
*
* - 8-bit SEC/DED
* - Aligned-nibble error detect
* - Bypass mode
*
* - Up to 4 GiB per bank/rank in 64-bit mode and up to 2 GiB
* per bank/rank in 32-bit mode.
*
* As realized in the 460EX and 460GT, this controller changes/adds:
*
* - 64-bit or 32-bit memory interface with optional ECC.
*
* o ECC support includes:
*
* - 8-bit SEC/DED
* - Aligned-nibble error detect
* - Bypass mode
*
* - Four (4) memory banks/ranks.
* - Up to 16 GiB per bank/rank in 64-bit mode and up to 8 GiB
* per bank/rank in 32-bit mode.
*
* At present, this driver has ONLY been tested against the controller
* realization in the 405EX[r] on the AMCC Kilauea and Haleakala
* boards (256 MiB w/o ECC memory soldered onto the board) and a
* proprietary board based on those designs (128 MiB ECC memory, also
* soldered onto the board).
*
* Dynamic feature detection and handling needs to be added for the
* other realizations of this controller listed above.
*
* Eventually, this driver will likely be adapted to the above variant
* realizations of this controller as well as broken apart to handle
* the other known ECC-capable controllers prevalent in other 4xx
* processors:
*
* - IBM SDRAM (405GP, 405CR and 405EP) "ibm,sdram-4xx"
* - IBM DDR1 (440GP, 440GX, 440EP and 440GR) "ibm,sdram-4xx-ddr"
* - Denali DDR1/DDR2 (440EPX and 440GRX) "denali,sdram-4xx-ddr2"
*
* For this controller, unfortunately, correctable errors report
* nothing more than the beat/cycle and byte/lane the correction
* occurred on and the check bit group that covered the error.
*
* In contrast, uncorrectable errors also report the failing address,
* the bus master and the transaction direction (i.e. read or write)
*
* Regardless of whether the error is a CE or a UE, we report the
* following pieces of information in the driver-unique message to the
* EDAC subsystem:
*
* - Device tree path
* - Bank(s)
* - Check bit error group
* - Beat(s)/lane(s)
*/
/* Preprocessor Definitions */
#define EDAC_OPSTATE_INT_STR "interrupt"
#define EDAC_OPSTATE_POLL_STR "polled"
#define EDAC_OPSTATE_UNKNOWN_STR "unknown"
#define PPC4XX_EDAC_MODULE_NAME "ppc4xx_edac"
#define PPC4XX_EDAC_MODULE_REVISION "v1.0.0"
#define PPC4XX_EDAC_MESSAGE_SIZE 256
/*
* Kernel logging without an EDAC instance
*/
#define ppc4xx_edac_printk(level, fmt, arg...) \
edac_printk(level, "PPC4xx MC", fmt, ##arg)
/*
* Kernel logging with an EDAC instance
*/
#define ppc4xx_edac_mc_printk(level, mci, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "PPC4xx", fmt, ##arg)
/*
* Macros to convert bank configuration size enumerations into MiB and
* page values.
*/
#define SDRAM_MBCF_SZ_MiB_MIN 4
#define SDRAM_MBCF_SZ_TO_MiB(n) (SDRAM_MBCF_SZ_MiB_MIN \
<< (SDRAM_MBCF_SZ_DECODE(n)))
#define SDRAM_MBCF_SZ_TO_PAGES(n) (SDRAM_MBCF_SZ_MiB_MIN \
<< (20 - PAGE_SHIFT + \
SDRAM_MBCF_SZ_DECODE(n)))
/*
* The ibm,sdram-4xx-ddr2 Device Control Registers (DCRs) are
* indirectly accessed and have a base and length defined by the
* device tree. The base can be anything; however, we expect the
* length to be precisely two registers, the first for the address
* window and the second for the data window.
*/
#define SDRAM_DCR_RESOURCE_LEN 2
#define SDRAM_DCR_ADDR_OFFSET 0
#define SDRAM_DCR_DATA_OFFSET 1
/*
* Device tree interrupt indices
*/
#define INTMAP_ECCDED_INDEX 0 /* Double-bit Error Detect */
#define INTMAP_ECCSEC_INDEX 1 /* Single-bit Error Correct */
/* Type Definitions */
/*
* PPC4xx SDRAM memory controller private instance data
*/
struct ppc4xx_edac_pdata {
dcr_host_t dcr_host; /* Indirect DCR address/data window mapping */
struct {
int sec; /* Single-bit correctable error IRQ assigned */
int ded; /* Double-bit detectable error IRQ assigned */
} irqs;
};
/*
* Various status data gathered and manipulated when checking and
* reporting ECC status.
*/
struct ppc4xx_ecc_status {
u32 ecces;
u32 besr;
u32 bearh;
u32 bearl;
u32 wmirq;
};
/* Function Prototypes */
static int ppc4xx_edac_probe(struct platform_device *device);
static int ppc4xx_edac_remove(struct platform_device *device);
/* Global Variables */
/*
* Device tree node type and compatible tuples this driver can match
* on.
*/
static struct of_device_id ppc4xx_edac_match[] = {
{
.compatible = "ibm,sdram-4xx-ddr2"
},
{ }
};
static struct platform_driver ppc4xx_edac_driver = {
.probe = ppc4xx_edac_probe,
.remove = ppc4xx_edac_remove,
.driver = {
.owner = THIS_MODULE,
.name = PPC4XX_EDAC_MODULE_NAME,
.of_match_table = ppc4xx_edac_match,
},
};
/*
* TODO: The row and channel parameters likely need to be dynamically
* set based on the aforementioned variant controller realizations.
*/
static const unsigned ppc4xx_edac_nr_csrows = 2;
static const unsigned ppc4xx_edac_nr_chans = 1;
/*
* Strings associated with PLB master IDs capable of being posted in
* SDRAM_BESR or SDRAM_WMIRQ on uncorrectable ECC errors.
*/
static const char * const ppc4xx_plb_masters[9] = {
[SDRAM_PLB_M0ID_ICU] = "ICU",
[SDRAM_PLB_M0ID_PCIE0] = "PCI-E 0",
[SDRAM_PLB_M0ID_PCIE1] = "PCI-E 1",
[SDRAM_PLB_M0ID_DMA] = "DMA",
[SDRAM_PLB_M0ID_DCU] = "DCU",
[SDRAM_PLB_M0ID_OPB] = "OPB",
[SDRAM_PLB_M0ID_MAL] = "MAL",
[SDRAM_PLB_M0ID_SEC] = "SEC",
[SDRAM_PLB_M0ID_AHB] = "AHB"
};
/**
* mfsdram - read and return controller register data
* @dcr_host: A pointer to the DCR mapping.
* @idcr_n: The indirect DCR register to read.
*
* This routine reads and returns the data associated with the
* controller's specified indirect DCR register.
*
* Returns the read data.
*/
static inline u32
mfsdram(const dcr_host_t *dcr_host, unsigned int idcr_n)
{
return __mfdcri(dcr_host->base + SDRAM_DCR_ADDR_OFFSET,
dcr_host->base + SDRAM_DCR_DATA_OFFSET,
idcr_n);
}
/**
* mtsdram - write controller register data
* @dcr_host: A pointer to the DCR mapping.
* @idcr_n: The indirect DCR register to write.
* @value: The data to write.
*
* This routine writes the provided data to the controller's specified
* indirect DCR register.
*/
static inline void
mtsdram(const dcr_host_t *dcr_host, unsigned int idcr_n, u32 value)
{
return __mtdcri(dcr_host->base + SDRAM_DCR_ADDR_OFFSET,
dcr_host->base + SDRAM_DCR_DATA_OFFSET,
idcr_n,
value);
}
/**
* ppc4xx_edac_check_bank_error - check a bank for an ECC bank error
* @status: A pointer to the ECC status structure to check for an
* ECC bank error.
* @bank: The bank to check for an ECC error.
*
* This routine determines whether the specified bank has an ECC
* error.
*
* Returns true if the specified bank has an ECC error; otherwise,
* false.
*/
static bool
ppc4xx_edac_check_bank_error(const struct ppc4xx_ecc_status *status,
unsigned int bank)
{
switch (bank) {
case 0:
return status->ecces & SDRAM_ECCES_BK0ER;
case 1:
return status->ecces & SDRAM_ECCES_BK1ER;
default:
return false;
}
}
/**
* ppc4xx_edac_generate_bank_message - generate interpretted bank status message
* @mci: A pointer to the EDAC memory controller instance associated
* with the bank message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the portion of the
* driver-unique report message associated with the ECCESS[BKNER]
* field of the specified ECC status.
*
* Returns the number of characters generated on success; otherwise, <
* 0 on error.
*/
static int
ppc4xx_edac_generate_bank_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
int n, total = 0;
unsigned int row, rows;
n = snprintf(buffer, size, "%s: Banks: ", mci->dev_name);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
for (rows = 0, row = 0; row < mci->nr_csrows; row++) {
if (ppc4xx_edac_check_bank_error(status, row)) {
n = snprintf(buffer, size, "%s%u",
(rows++ ? ", " : ""), row);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
}
}
n = snprintf(buffer, size, "%s; ", rows ? "" : "None");
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
fail:
return total;
}
/**
* ppc4xx_edac_generate_checkbit_message - generate interpretted checkbit message
* @mci: A pointer to the EDAC memory controller instance associated
* with the checkbit message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the portion of the
* driver-unique report message associated with the ECCESS[CKBER]
* field of the specified ECC status.
*
* Returns the number of characters generated on success; otherwise, <
* 0 on error.
*/
static int
ppc4xx_edac_generate_checkbit_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
const struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
const char *ckber = NULL;
switch (status->ecces & SDRAM_ECCES_CKBER_MASK) {
case SDRAM_ECCES_CKBER_NONE:
ckber = "None";
break;
case SDRAM_ECCES_CKBER_32_ECC_0_3:
ckber = "ECC0:3";
break;
case SDRAM_ECCES_CKBER_32_ECC_4_8:
switch (mfsdram(&pdata->dcr_host, SDRAM_MCOPT1) &
SDRAM_MCOPT1_WDTH_MASK) {
case SDRAM_MCOPT1_WDTH_16:
ckber = "ECC0:3";
break;
case SDRAM_MCOPT1_WDTH_32:
ckber = "ECC4:8";
break;
default:
ckber = "Unknown";
break;
}
break;
case SDRAM_ECCES_CKBER_32_ECC_0_8:
ckber = "ECC0:8";
break;
default:
ckber = "Unknown";
break;
}
return snprintf(buffer, size, "Checkbit Error: %s", ckber);
}
/**
* ppc4xx_edac_generate_lane_message - generate interpretted byte lane message
* @mci: A pointer to the EDAC memory controller instance associated
* with the byte lane message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the portion of the
* driver-unique report message associated with the ECCESS[BNCE]
* field of the specified ECC status.
*
* Returns the number of characters generated on success; otherwise, <
* 0 on error.
*/
static int
ppc4xx_edac_generate_lane_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
int n, total = 0;
unsigned int lane, lanes;
const unsigned int first_lane = 0;
const unsigned int lane_count = 16;
n = snprintf(buffer, size, "; Byte Lane Errors: ");
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
for (lanes = 0, lane = first_lane; lane < lane_count; lane++) {
if ((status->ecces & SDRAM_ECCES_BNCE_ENCODE(lane)) != 0) {
n = snprintf(buffer, size,
"%s%u",
(lanes++ ? ", " : ""), lane);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
}
}
n = snprintf(buffer, size, "%s; ", lanes ? "" : "None");
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
fail:
return total;
}
/**
* ppc4xx_edac_generate_ecc_message - generate interpretted ECC status message
* @mci: A pointer to the EDAC memory controller instance associated
* with the ECCES message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the portion of the
* driver-unique report message associated with the ECCESS register of
* the specified ECC status.
*
* Returns the number of characters generated on success; otherwise, <
* 0 on error.
*/
static int
ppc4xx_edac_generate_ecc_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
int n, total = 0;
n = ppc4xx_edac_generate_bank_message(mci, status, buffer, size);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
n = ppc4xx_edac_generate_checkbit_message(mci, status, buffer, size);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
n = ppc4xx_edac_generate_lane_message(mci, status, buffer, size);
if (n < 0 || n >= size)
goto fail;
buffer += n;
size -= n;
total += n;
fail:
return total;
}
/**
* ppc4xx_edac_generate_plb_message - generate interpretted PLB status message
* @mci: A pointer to the EDAC memory controller instance associated
* with the PLB message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the portion of the
* driver-unique report message associated with the PLB-related BESR
* and/or WMIRQ registers of the specified ECC status.
*
* Returns the number of characters generated on success; otherwise, <
* 0 on error.
*/
static int
ppc4xx_edac_generate_plb_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
unsigned int master;
bool read;
if ((status->besr & SDRAM_BESR_MASK) == 0)
return 0;
if ((status->besr & SDRAM_BESR_M0ET_MASK) == SDRAM_BESR_M0ET_NONE)
return 0;
read = ((status->besr & SDRAM_BESR_M0RW_MASK) == SDRAM_BESR_M0RW_READ);
master = SDRAM_BESR_M0ID_DECODE(status->besr);
return snprintf(buffer, size,
"%s error w/ PLB master %u \"%s\"; ",
(read ? "Read" : "Write"),
master,
(((master >= SDRAM_PLB_M0ID_FIRST) &&
(master <= SDRAM_PLB_M0ID_LAST)) ?
ppc4xx_plb_masters[master] : "UNKNOWN"));
}
/**
* ppc4xx_edac_generate_message - generate interpretted status message
* @mci: A pointer to the EDAC memory controller instance associated
* with the driver-unique message being generated.
* @status: A pointer to the ECC status structure to generate the
* message from.
* @buffer: A pointer to the buffer in which to generate the
* message.
* @size: The size, in bytes, of space available in buffer.
*
* This routine generates to the provided buffer the driver-unique
* EDAC report message from the specified ECC status.
*/
static void
ppc4xx_edac_generate_message(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status,
char *buffer,
size_t size)
{
int n;
if (buffer == NULL || size == 0)
return;
n = ppc4xx_edac_generate_ecc_message(mci, status, buffer, size);
if (n < 0 || n >= size)
return;
buffer += n;
size -= n;
ppc4xx_edac_generate_plb_message(mci, status, buffer, size);
}
#ifdef DEBUG
/**
* ppc4xx_ecc_dump_status - dump controller ECC status registers
* @mci: A pointer to the EDAC memory controller instance
* associated with the status being dumped.
* @status: A pointer to the ECC status structure to generate the
* dump from.
*
* This routine dumps to the kernel log buffer the raw and
* interpretted specified ECC status.
*/
static void
ppc4xx_ecc_dump_status(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status)
{
char message[PPC4XX_EDAC_MESSAGE_SIZE];
ppc4xx_edac_generate_message(mci, status, message, sizeof(message));
ppc4xx_edac_mc_printk(KERN_INFO, mci,
"\n"
"\tECCES: 0x%08x\n"
"\tWMIRQ: 0x%08x\n"
"\tBESR: 0x%08x\n"
"\tBEAR: 0x%08x%08x\n"
"\t%s\n",
status->ecces,
status->wmirq,
status->besr,
status->bearh,
status->bearl,
message);
}
#endif /* DEBUG */
/**
* ppc4xx_ecc_get_status - get controller ECC status
* @mci: A pointer to the EDAC memory controller instance
* associated with the status being retrieved.
* @status: A pointer to the ECC status structure to populate the
* ECC status with.
*
* This routine reads and masks, as appropriate, all the relevant
* status registers that deal with ibm,sdram-4xx-ddr2 ECC errors.
* While we read all of them, for correctable errors, we only expect
* to deal with ECCES. For uncorrectable errors, we expect to deal
* with all of them.
*/
static void
ppc4xx_ecc_get_status(const struct mem_ctl_info *mci,
struct ppc4xx_ecc_status *status)
{
const struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
const dcr_host_t *dcr_host = &pdata->dcr_host;
status->ecces = mfsdram(dcr_host, SDRAM_ECCES) & SDRAM_ECCES_MASK;
status->wmirq = mfsdram(dcr_host, SDRAM_WMIRQ) & SDRAM_WMIRQ_MASK;
status->besr = mfsdram(dcr_host, SDRAM_BESR) & SDRAM_BESR_MASK;
status->bearl = mfsdram(dcr_host, SDRAM_BEARL);
status->bearh = mfsdram(dcr_host, SDRAM_BEARH);
}
/**
* ppc4xx_ecc_clear_status - clear controller ECC status
* @mci: A pointer to the EDAC memory controller instance
* associated with the status being cleared.
* @status: A pointer to the ECC status structure containing the
* values to write to clear the ECC status.
*
* This routine clears--by writing the masked (as appropriate) status
* values back to--the status registers that deal with
* ibm,sdram-4xx-ddr2 ECC errors.
*/
static void
ppc4xx_ecc_clear_status(const struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status)
{
const struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
const dcr_host_t *dcr_host = &pdata->dcr_host;
mtsdram(dcr_host, SDRAM_ECCES, status->ecces & SDRAM_ECCES_MASK);
mtsdram(dcr_host, SDRAM_WMIRQ, status->wmirq & SDRAM_WMIRQ_MASK);
mtsdram(dcr_host, SDRAM_BESR, status->besr & SDRAM_BESR_MASK);
mtsdram(dcr_host, SDRAM_BEARL, 0);
mtsdram(dcr_host, SDRAM_BEARH, 0);
}
/**
* ppc4xx_edac_handle_ce - handle controller correctable ECC error (CE)
* @mci: A pointer to the EDAC memory controller instance
* associated with the correctable error being handled and reported.
* @status: A pointer to the ECC status structure associated with
* the correctable error being handled and reported.
*
* This routine handles an ibm,sdram-4xx-ddr2 controller ECC
* correctable error. Per the aforementioned discussion, there's not
* enough status available to use the full EDAC correctable error
* interface, so we just pass driver-unique message to the "no info"
* interface.
*/
static void
ppc4xx_edac_handle_ce(struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status)
{
int row;
char message[PPC4XX_EDAC_MESSAGE_SIZE];
ppc4xx_edac_generate_message(mci, status, message, sizeof(message));
for (row = 0; row < mci->nr_csrows; row++)
if (ppc4xx_edac_check_bank_error(status, row))
edac_mc_handle_ce_no_info(mci, message);
}
/**
* ppc4xx_edac_handle_ue - handle controller uncorrectable ECC error (UE)
* @mci: A pointer to the EDAC memory controller instance
* associated with the uncorrectable error being handled and
* reported.
* @status: A pointer to the ECC status structure associated with
* the uncorrectable error being handled and reported.
*
* This routine handles an ibm,sdram-4xx-ddr2 controller ECC
* uncorrectable error.
*/
static void
ppc4xx_edac_handle_ue(struct mem_ctl_info *mci,
const struct ppc4xx_ecc_status *status)
{
const u64 bear = ((u64)status->bearh << 32 | status->bearl);
const unsigned long page = bear >> PAGE_SHIFT;
const unsigned long offset = bear & ~PAGE_MASK;
int row;
char message[PPC4XX_EDAC_MESSAGE_SIZE];
ppc4xx_edac_generate_message(mci, status, message, sizeof(message));
for (row = 0; row < mci->nr_csrows; row++)
if (ppc4xx_edac_check_bank_error(status, row))
edac_mc_handle_ue(mci, page, offset, row, message);
}
/**
* ppc4xx_edac_check - check controller for ECC errors
* @mci: A pointer to the EDAC memory controller instance
* associated with the ibm,sdram-4xx-ddr2 controller being
* checked.
*
* This routine is used to check and post ECC errors and is called by
* both the EDAC polling thread and this driver's CE and UE interrupt
* handler.
*/
static void
ppc4xx_edac_check(struct mem_ctl_info *mci)
{
#ifdef DEBUG
static unsigned int count;
#endif
struct ppc4xx_ecc_status status;
ppc4xx_ecc_get_status(mci, &status);
#ifdef DEBUG
if (count++ % 30 == 0)
ppc4xx_ecc_dump_status(mci, &status);
#endif
if (status.ecces & SDRAM_ECCES_UE)
ppc4xx_edac_handle_ue(mci, &status);
if (status.ecces & SDRAM_ECCES_CE)
ppc4xx_edac_handle_ce(mci, &status);
ppc4xx_ecc_clear_status(mci, &status);
}
/**
* ppc4xx_edac_isr - SEC (CE) and DED (UE) interrupt service routine
* @irq: The virtual interrupt number being serviced.
* @dev_id: A pointer to the EDAC memory controller instance
* associated with the interrupt being handled.
*
* This routine implements the interrupt handler for both correctable
* (CE) and uncorrectable (UE) ECC errors for the ibm,sdram-4xx-ddr2
* controller. It simply calls through to the same routine used during
* polling to check, report and clear the ECC status.
*
* Unconditionally returns IRQ_HANDLED.
*/
static irqreturn_t
ppc4xx_edac_isr(int irq, void *dev_id)
{
struct mem_ctl_info *mci = dev_id;
ppc4xx_edac_check(mci);
return IRQ_HANDLED;
}
/**
* ppc4xx_edac_get_dtype - return the controller memory width
* @mcopt1: The 32-bit Memory Controller Option 1 register value
* currently set for the controller, from which the width
* is derived.
*
* This routine returns the EDAC device type width appropriate for the
* current controller configuration.
*
* TODO: This needs to be conditioned dynamically through feature
* flags or some such when other controller variants are supported as
* the 405EX[r] is 16-/32-bit and the others are 32-/64-bit with the
* 16- and 64-bit field definition/value/enumeration (b1) overloaded
* among them.
*
* Returns a device type width enumeration.
*/
static enum dev_type __devinit
ppc4xx_edac_get_dtype(u32 mcopt1)
{
switch (mcopt1 & SDRAM_MCOPT1_WDTH_MASK) {
case SDRAM_MCOPT1_WDTH_16:
return DEV_X2;
case SDRAM_MCOPT1_WDTH_32:
return DEV_X4;
default:
return DEV_UNKNOWN;
}
}
/**
* ppc4xx_edac_get_mtype - return controller memory type
* @mcopt1: The 32-bit Memory Controller Option 1 register value
* currently set for the controller, from which the memory type
* is derived.
*
* This routine returns the EDAC memory type appropriate for the
* current controller configuration.
*
* Returns a memory type enumeration.
*/
static enum mem_type __devinit
ppc4xx_edac_get_mtype(u32 mcopt1)
{
bool rden = ((mcopt1 & SDRAM_MCOPT1_RDEN_MASK) == SDRAM_MCOPT1_RDEN);
switch (mcopt1 & SDRAM_MCOPT1_DDR_TYPE_MASK) {
case SDRAM_MCOPT1_DDR2_TYPE:
return rden ? MEM_RDDR2 : MEM_DDR2;
case SDRAM_MCOPT1_DDR1_TYPE:
return rden ? MEM_RDDR : MEM_DDR;
default:
return MEM_UNKNOWN;
}
}
/**
* ppc4xx_edac_init_csrows - initialize driver instance rows
* @mci: A pointer to the EDAC memory controller instance
* associated with the ibm,sdram-4xx-ddr2 controller for which
* the csrows (i.e. banks/ranks) are being initialized.
* @mcopt1: The 32-bit Memory Controller Option 1 register value
* currently set for the controller, from which bank width
* and memory typ information is derived.
*
* This routine initializes the virtual "chip select rows" associated
* with the EDAC memory controller instance. An ibm,sdram-4xx-ddr2
* controller bank/rank is mapped to a row.
*
* Returns 0 if OK; otherwise, -EINVAL if the memory bank size
* configuration cannot be determined.
*/
static int __devinit
ppc4xx_edac_init_csrows(struct mem_ctl_info *mci, u32 mcopt1)
{
const struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
int status = 0;
enum mem_type mtype;
enum dev_type dtype;
enum edac_type edac_mode;
int row;
u32 mbxcf, size;
static u32 ppc4xx_last_page;
/* Establish the memory type and width */
mtype = ppc4xx_edac_get_mtype(mcopt1);
dtype = ppc4xx_edac_get_dtype(mcopt1);
/* Establish EDAC mode */
if (mci->edac_cap & EDAC_FLAG_SECDED)
edac_mode = EDAC_SECDED;
else if (mci->edac_cap & EDAC_FLAG_EC)
edac_mode = EDAC_EC;
else
edac_mode = EDAC_NONE;
/*
* Initialize each chip select row structure which correspond
* 1:1 with a controller bank/rank.
*/
for (row = 0; row < mci->nr_csrows; row++) {
struct csrow_info *csi = &mci->csrows[row];
/*
* Get the configuration settings for this
* row/bank/rank and skip disabled banks.
*/
mbxcf = mfsdram(&pdata->dcr_host, SDRAM_MBXCF(row));
if ((mbxcf & SDRAM_MBCF_BE_MASK) != SDRAM_MBCF_BE_ENABLE)
continue;
/* Map the bank configuration size setting to pages. */
size = mbxcf & SDRAM_MBCF_SZ_MASK;
switch (size) {
case SDRAM_MBCF_SZ_4MB:
case SDRAM_MBCF_SZ_8MB:
case SDRAM_MBCF_SZ_16MB:
case SDRAM_MBCF_SZ_32MB:
case SDRAM_MBCF_SZ_64MB:
case SDRAM_MBCF_SZ_128MB:
case SDRAM_MBCF_SZ_256MB:
case SDRAM_MBCF_SZ_512MB:
case SDRAM_MBCF_SZ_1GB:
case SDRAM_MBCF_SZ_2GB:
case SDRAM_MBCF_SZ_4GB:
case SDRAM_MBCF_SZ_8GB:
csi->nr_pages = SDRAM_MBCF_SZ_TO_PAGES(size);
break;
default:
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Unrecognized memory bank %d "
"size 0x%08x\n",
row, SDRAM_MBCF_SZ_DECODE(size));
status = -EINVAL;
goto done;
}
csi->first_page = ppc4xx_last_page;
csi->last_page = csi->first_page + csi->nr_pages - 1;
csi->page_mask = 0;
/*
* It's unclear exactly what grain should be set to
* here. The SDRAM_ECCES register allows resolution of
* an error down to a nibble which would potentially
* argue for a grain of '1' byte, even though we only
* know the associated address for uncorrectable
* errors. This value is not used at present for
* anything other than error reporting so getting it
* wrong should be of little consequence. Other
* possible values would be the PLB width (16), the
* page size (PAGE_SIZE) or the memory width (2 or 4).
*/
csi->grain = 1;
csi->mtype = mtype;
csi->dtype = dtype;
csi->edac_mode = edac_mode;
ppc4xx_last_page += csi->nr_pages;
}
done:
return status;
}
/**
* ppc4xx_edac_mc_init - initialize driver instance
* @mci: A pointer to the EDAC memory controller instance being
* initialized.
* @op: A pointer to the OpenFirmware device tree node associated
* with the controller this EDAC instance is bound to.
* @dcr_host: A pointer to the DCR data containing the DCR mapping
* for this controller instance.
* @mcopt1: The 32-bit Memory Controller Option 1 register value
* currently set for the controller, from which ECC capabilities
* and scrub mode are derived.
*
* This routine performs initialization of the EDAC memory controller
* instance and related driver-private data associated with the
* ibm,sdram-4xx-ddr2 memory controller the instance is bound to.
*
* Returns 0 if OK; otherwise, < 0 on error.
*/
static int __devinit
ppc4xx_edac_mc_init(struct mem_ctl_info *mci,
struct platform_device *op,
const dcr_host_t *dcr_host,
u32 mcopt1)
{
int status = 0;
const u32 memcheck = (mcopt1 & SDRAM_MCOPT1_MCHK_MASK);
struct ppc4xx_edac_pdata *pdata = NULL;
const struct device_node *np = op->dev.of_node;
if (of_match_device(ppc4xx_edac_match, &op->dev) == NULL)
return -EINVAL;
/* Initial driver pointers and private data */
mci->dev = &op->dev;
dev_set_drvdata(mci->dev, mci);
pdata = mci->pvt_info;
pdata->dcr_host = *dcr_host;
pdata->irqs.sec = NO_IRQ;
pdata->irqs.ded = NO_IRQ;
/* Initialize controller capabilities and configuration */
mci->mtype_cap = (MEM_FLAG_DDR | MEM_FLAG_RDDR |
MEM_FLAG_DDR2 | MEM_FLAG_RDDR2);
mci->edac_ctl_cap = (EDAC_FLAG_NONE |
EDAC_FLAG_EC |
EDAC_FLAG_SECDED);
mci->scrub_cap = SCRUB_NONE;
mci->scrub_mode = SCRUB_NONE;
/*
* Update the actual capabilites based on the MCOPT1[MCHK]
* settings. Scrubbing is only useful if reporting is enabled.
*/
switch (memcheck) {
case SDRAM_MCOPT1_MCHK_CHK:
mci->edac_cap = EDAC_FLAG_EC;
break;
case SDRAM_MCOPT1_MCHK_CHK_REP:
mci->edac_cap = (EDAC_FLAG_EC | EDAC_FLAG_SECDED);
mci->scrub_mode = SCRUB_SW_SRC;
break;
default:
mci->edac_cap = EDAC_FLAG_NONE;
break;
}
/* Initialize strings */
mci->mod_name = PPC4XX_EDAC_MODULE_NAME;
mci->mod_ver = PPC4XX_EDAC_MODULE_REVISION;
mci->ctl_name = ppc4xx_edac_match->compatible,
mci->dev_name = np->full_name;
/* Initialize callbacks */
mci->edac_check = ppc4xx_edac_check;
mci->ctl_page_to_phys = NULL;
/* Initialize chip select rows */
status = ppc4xx_edac_init_csrows(mci, mcopt1);
if (status)
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Failed to initialize rows!\n");
return status;
}
/**
* ppc4xx_edac_register_irq - setup and register controller interrupts
* @op: A pointer to the OpenFirmware device tree node associated
* with the controller this EDAC instance is bound to.
* @mci: A pointer to the EDAC memory controller instance
* associated with the ibm,sdram-4xx-ddr2 controller for which
* interrupts are being registered.
*
* This routine parses the correctable (CE) and uncorrectable error (UE)
* interrupts from the device tree node and maps and assigns them to
* the associated EDAC memory controller instance.
*
* Returns 0 if OK; otherwise, -ENODEV if the interrupts could not be
* mapped and assigned.
*/
static int __devinit
ppc4xx_edac_register_irq(struct platform_device *op, struct mem_ctl_info *mci)
{
int status = 0;
int ded_irq, sec_irq;
struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
struct device_node *np = op->dev.of_node;
ded_irq = irq_of_parse_and_map(np, INTMAP_ECCDED_INDEX);
sec_irq = irq_of_parse_and_map(np, INTMAP_ECCSEC_INDEX);
if (ded_irq == NO_IRQ || sec_irq == NO_IRQ) {
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Unable to map interrupts.\n");
status = -ENODEV;
goto fail;
}
status = request_irq(ded_irq,
ppc4xx_edac_isr,
IRQF_DISABLED,
"[EDAC] MC ECCDED",
mci);
if (status < 0) {
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Unable to request irq %d for ECC DED",
ded_irq);
status = -ENODEV;
goto fail1;
}
status = request_irq(sec_irq,
ppc4xx_edac_isr,
IRQF_DISABLED,
"[EDAC] MC ECCSEC",
mci);
if (status < 0) {
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Unable to request irq %d for ECC SEC",
sec_irq);
status = -ENODEV;
goto fail2;
}
ppc4xx_edac_mc_printk(KERN_INFO, mci, "ECCDED irq is %d\n", ded_irq);
ppc4xx_edac_mc_printk(KERN_INFO, mci, "ECCSEC irq is %d\n", sec_irq);
pdata->irqs.ded = ded_irq;
pdata->irqs.sec = sec_irq;
return 0;
fail2:
free_irq(sec_irq, mci);
fail1:
free_irq(ded_irq, mci);
fail:
return status;
}
/**
* ppc4xx_edac_map_dcrs - locate and map controller registers
* @np: A pointer to the device tree node containing the DCR
* resources to map.
* @dcr_host: A pointer to the DCR data to populate with the
* DCR mapping.
*
* This routine attempts to locate in the device tree and map the DCR
* register resources associated with the controller's indirect DCR
* address and data windows.
*
* Returns 0 if the DCRs were successfully mapped; otherwise, < 0 on
* error.
*/
static int __devinit
ppc4xx_edac_map_dcrs(const struct device_node *np, dcr_host_t *dcr_host)
{
unsigned int dcr_base, dcr_len;
if (np == NULL || dcr_host == NULL)
return -EINVAL;
/* Get the DCR resource extent and sanity check the values. */
dcr_base = dcr_resource_start(np, 0);
dcr_len = dcr_resource_len(np, 0);
if (dcr_base == 0 || dcr_len == 0) {
ppc4xx_edac_printk(KERN_ERR,
"Failed to obtain DCR property.\n");
return -ENODEV;
}
if (dcr_len != SDRAM_DCR_RESOURCE_LEN) {
ppc4xx_edac_printk(KERN_ERR,
"Unexpected DCR length %d, expected %d.\n",
dcr_len, SDRAM_DCR_RESOURCE_LEN);
return -ENODEV;
}
/* Attempt to map the DCR extent. */
*dcr_host = dcr_map(np, dcr_base, dcr_len);
if (!DCR_MAP_OK(*dcr_host)) {
ppc4xx_edac_printk(KERN_INFO, "Failed to map DCRs.\n");
return -ENODEV;
}
return 0;
}
/**
* ppc4xx_edac_probe - check controller and bind driver
* @op: A pointer to the OpenFirmware device tree node associated
* with the controller being probed for driver binding.
*
* This routine probes a specific ibm,sdram-4xx-ddr2 controller
* instance for binding with the driver.
*
* Returns 0 if the controller instance was successfully bound to the
* driver; otherwise, < 0 on error.
*/
static int __devinit ppc4xx_edac_probe(struct platform_device *op)
{
int status = 0;
u32 mcopt1, memcheck;
dcr_host_t dcr_host;
const struct device_node *np = op->dev.of_node;
struct mem_ctl_info *mci = NULL;
static int ppc4xx_edac_instance;
/*
* At this point, we only support the controller realized on
* the AMCC PPC 405EX[r]. Reject anything else.
*/
if (!of_device_is_compatible(np, "ibm,sdram-405ex") &&
!of_device_is_compatible(np, "ibm,sdram-405exr")) {
ppc4xx_edac_printk(KERN_NOTICE,
"Only the PPC405EX[r] is supported.\n");
return -ENODEV;
}
/*
* Next, get the DCR property and attempt to map it so that we
* can probe the controller.
*/
status = ppc4xx_edac_map_dcrs(np, &dcr_host);
if (status)
return status;
/*
* First determine whether ECC is enabled at all. If not,
* there is no useful checking or monitoring that can be done
* for this controller.
*/
mcopt1 = mfsdram(&dcr_host, SDRAM_MCOPT1);
memcheck = (mcopt1 & SDRAM_MCOPT1_MCHK_MASK);
if (memcheck == SDRAM_MCOPT1_MCHK_NON) {
ppc4xx_edac_printk(KERN_INFO, "%s: No ECC memory detected or "
"ECC is disabled.\n", np->full_name);
status = -ENODEV;
goto done;
}
/*
* At this point, we know ECC is enabled, allocate an EDAC
* controller instance and perform the appropriate
* initialization.
*/
mci = edac_mc_alloc(sizeof(struct ppc4xx_edac_pdata),
ppc4xx_edac_nr_csrows,
ppc4xx_edac_nr_chans,
ppc4xx_edac_instance);
if (mci == NULL) {
ppc4xx_edac_printk(KERN_ERR, "%s: "
"Failed to allocate EDAC MC instance!\n",
np->full_name);
status = -ENOMEM;
goto done;
}
status = ppc4xx_edac_mc_init(mci, op, &dcr_host, mcopt1);
if (status) {
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Failed to initialize instance!\n");
goto fail;
}
/*
* We have a valid, initialized EDAC instance bound to the
* controller. Attempt to register it with the EDAC subsystem
* and, if necessary, register interrupts.
*/
if (edac_mc_add_mc(mci)) {
ppc4xx_edac_mc_printk(KERN_ERR, mci,
"Failed to add instance!\n");
status = -ENODEV;
goto fail;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
status = ppc4xx_edac_register_irq(op, mci);
if (status)
goto fail1;
}
ppc4xx_edac_instance++;
return 0;
fail1:
edac_mc_del_mc(mci->dev);
fail:
edac_mc_free(mci);
done:
return status;
}
/**
* ppc4xx_edac_remove - unbind driver from controller
* @op: A pointer to the OpenFirmware device tree node associated
* with the controller this EDAC instance is to be unbound/removed
* from.
*
* This routine unbinds the EDAC memory controller instance associated
* with the specified ibm,sdram-4xx-ddr2 controller described by the
* OpenFirmware device tree node passed as a parameter.
*
* Unconditionally returns 0.
*/
static int
ppc4xx_edac_remove(struct platform_device *op)
{
struct mem_ctl_info *mci = dev_get_drvdata(&op->dev);
struct ppc4xx_edac_pdata *pdata = mci->pvt_info;
if (edac_op_state == EDAC_OPSTATE_INT) {
free_irq(pdata->irqs.sec, mci);
free_irq(pdata->irqs.ded, mci);
}
dcr_unmap(pdata->dcr_host, SDRAM_DCR_RESOURCE_LEN);
edac_mc_del_mc(mci->dev);
edac_mc_free(mci);
return 0;
}
/**
* ppc4xx_edac_opstate_init - initialize EDAC reporting method
*
* This routine ensures that the EDAC memory controller reporting
* method is mapped to a sane value as the EDAC core defines the value
* to EDAC_OPSTATE_INVAL by default. We don't call the global
* opstate_init as that defaults to polling and we want interrupt as
* the default.
*/
static inline void __init
ppc4xx_edac_opstate_init(void)
{
switch (edac_op_state) {
case EDAC_OPSTATE_POLL:
case EDAC_OPSTATE_INT:
break;
default:
edac_op_state = EDAC_OPSTATE_INT;
break;
}
ppc4xx_edac_printk(KERN_INFO, "Reporting type: %s\n",
((edac_op_state == EDAC_OPSTATE_POLL) ?
EDAC_OPSTATE_POLL_STR :
((edac_op_state == EDAC_OPSTATE_INT) ?
EDAC_OPSTATE_INT_STR :
EDAC_OPSTATE_UNKNOWN_STR)));
}
/**
* ppc4xx_edac_init - driver/module insertion entry point
*
* This routine is the driver/module insertion entry point. It
* initializes the EDAC memory controller reporting state and
* registers the driver as an OpenFirmware device tree platform
* driver.
*/
static int __init
ppc4xx_edac_init(void)
{
ppc4xx_edac_printk(KERN_INFO, PPC4XX_EDAC_MODULE_REVISION "\n");
ppc4xx_edac_opstate_init();
return platform_driver_register(&ppc4xx_edac_driver);
}
/**
* ppc4xx_edac_exit - driver/module removal entry point
*
* This routine is the driver/module removal entry point. It
* unregisters the driver as an OpenFirmware device tree platform
* driver.
*/
static void __exit
ppc4xx_edac_exit(void)
{
platform_driver_unregister(&ppc4xx_edac_driver);
}
module_init(ppc4xx_edac_init);
module_exit(ppc4xx_edac_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Grant Erickson <gerickson@nuovations.com>");
MODULE_DESCRIPTION("EDAC MC Driver for the PPC4xx IBM DDR2 Memory Controller");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting State: "
"0=" EDAC_OPSTATE_POLL_STR ", 2=" EDAC_OPSTATE_INT_STR);
| gpl-2.0 |
chandrusiva/litmus-rt | arch/um/os-Linux/irq.c | 4576 | 2881 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdlib.h>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
#include <irq_user.h>
#include <os.h>
#include <um_malloc.h>
/*
* Locked by irq_lock in arch/um/kernel/irq.c. Changed by os_create_pollfd
* and os_free_irq_by_cb, which are called under irq_lock.
*/
static struct pollfd *pollfds = NULL;
static int pollfds_num = 0;
static int pollfds_size = 0;
int os_waiting_for_events(struct irq_fd *active_fds)
{
struct irq_fd *irq_fd;
int i, n, err;
n = poll(pollfds, pollfds_num, 0);
if (n < 0) {
err = -errno;
if (errno != EINTR)
printk(UM_KERN_ERR "os_waiting_for_events:"
" poll returned %d, errno = %d\n", n, errno);
return err;
}
if (n == 0)
return 0;
irq_fd = active_fds;
for (i = 0; i < pollfds_num; i++) {
if (pollfds[i].revents != 0) {
irq_fd->current_events = pollfds[i].revents;
pollfds[i].fd = -1;
}
irq_fd = irq_fd->next;
}
return n;
}
int os_create_pollfd(int fd, int events, void *tmp_pfd, int size_tmpfds)
{
if (pollfds_num == pollfds_size) {
if (size_tmpfds <= pollfds_size * sizeof(pollfds[0])) {
/* return min size needed for new pollfds area */
return (pollfds_size + 1) * sizeof(pollfds[0]);
}
if (pollfds != NULL) {
memcpy(tmp_pfd, pollfds,
sizeof(pollfds[0]) * pollfds_size);
/* remove old pollfds */
kfree(pollfds);
}
pollfds = tmp_pfd;
pollfds_size++;
} else
kfree(tmp_pfd); /* remove not used tmp_pfd */
pollfds[pollfds_num] = ((struct pollfd) { .fd = fd,
.events = events,
.revents = 0 });
pollfds_num++;
return 0;
}
void os_free_irq_by_cb(int (*test)(struct irq_fd *, void *), void *arg,
struct irq_fd *active_fds, struct irq_fd ***last_irq_ptr2)
{
struct irq_fd **prev;
int i = 0;
prev = &active_fds;
while (*prev != NULL) {
if ((*test)(*prev, arg)) {
struct irq_fd *old_fd = *prev;
if ((pollfds[i].fd != -1) &&
(pollfds[i].fd != (*prev)->fd)) {
printk(UM_KERN_ERR "os_free_irq_by_cb - "
"mismatch between active_fds and "
"pollfds, fd %d vs %d\n",
(*prev)->fd, pollfds[i].fd);
goto out;
}
pollfds_num--;
/*
* This moves the *whole* array after pollfds[i]
* (though it doesn't spot as such)!
*/
memmove(&pollfds[i], &pollfds[i + 1],
(pollfds_num - i) * sizeof(pollfds[0]));
if (*last_irq_ptr2 == &old_fd->next)
*last_irq_ptr2 = prev;
*prev = (*prev)->next;
if (old_fd->type == IRQ_WRITE)
ignore_sigio_fd(old_fd->fd);
kfree(old_fd);
continue;
}
prev = &(*prev)->next;
i++;
}
out:
return;
}
int os_get_pollfd(int i)
{
return pollfds[i].fd;
}
void os_set_pollfd(int i, int fd)
{
pollfds[i].fd = fd;
}
void os_set_ioignore(void)
{
signal(SIGIO, SIG_IGN);
}
| gpl-2.0 |
shskyinfo/android_kernel_lge_vee7 | net/sunrpc/xprtrdma/rpc_rdma.c | 5088 | 28365 | /*
* Copyright (c) 2003-2007 Network Appliance, 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 BSD-type
* 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.
*
* Neither the name of the Network Appliance, Inc. nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED 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.
*/
/*
* rpc_rdma.c
*
* This file contains the guts of the RPC RDMA protocol, and
* does marshaling/unmarshaling, etc. It is also where interfacing
* to the Linux RPC framework lives.
*/
#include "xprt_rdma.h"
#include <linux/highmem.h>
#ifdef RPC_DEBUG
# define RPCDBG_FACILITY RPCDBG_TRANS
#endif
enum rpcrdma_chunktype {
rpcrdma_noch = 0,
rpcrdma_readch,
rpcrdma_areadch,
rpcrdma_writech,
rpcrdma_replych
};
#ifdef RPC_DEBUG
static const char transfertypes[][12] = {
"pure inline", /* no chunks */
" read chunk", /* some argument via rdma read */
"*read chunk", /* entire request via rdma read */
"write chunk", /* some result via rdma write */
"reply chunk" /* entire reply via rdma write */
};
#endif
/*
* Chunk assembly from upper layer xdr_buf.
*
* Prepare the passed-in xdr_buf into representation as RPC/RDMA chunk
* elements. Segments are then coalesced when registered, if possible
* within the selected memreg mode.
*
* Note, this routine is never called if the connection's memory
* registration strategy is 0 (bounce buffers).
*/
static int
rpcrdma_convert_iovs(struct xdr_buf *xdrbuf, unsigned int pos,
enum rpcrdma_chunktype type, struct rpcrdma_mr_seg *seg, int nsegs)
{
int len, n = 0, p;
int page_base;
struct page **ppages;
if (pos == 0 && xdrbuf->head[0].iov_len) {
seg[n].mr_page = NULL;
seg[n].mr_offset = xdrbuf->head[0].iov_base;
seg[n].mr_len = xdrbuf->head[0].iov_len;
++n;
}
len = xdrbuf->page_len;
ppages = xdrbuf->pages + (xdrbuf->page_base >> PAGE_SHIFT);
page_base = xdrbuf->page_base & ~PAGE_MASK;
p = 0;
while (len && n < nsegs) {
seg[n].mr_page = ppages[p];
seg[n].mr_offset = (void *)(unsigned long) page_base;
seg[n].mr_len = min_t(u32, PAGE_SIZE - page_base, len);
BUG_ON(seg[n].mr_len > PAGE_SIZE);
len -= seg[n].mr_len;
++n;
++p;
page_base = 0; /* page offset only applies to first page */
}
/* Message overflows the seg array */
if (len && n == nsegs)
return 0;
if (xdrbuf->tail[0].iov_len) {
/* the rpcrdma protocol allows us to omit any trailing
* xdr pad bytes, saving the server an RDMA operation. */
if (xdrbuf->tail[0].iov_len < 4 && xprt_rdma_pad_optimize)
return n;
if (n == nsegs)
/* Tail remains, but we're out of segments */
return 0;
seg[n].mr_page = NULL;
seg[n].mr_offset = xdrbuf->tail[0].iov_base;
seg[n].mr_len = xdrbuf->tail[0].iov_len;
++n;
}
return n;
}
/*
* Create read/write chunk lists, and reply chunks, for RDMA
*
* Assume check against THRESHOLD has been done, and chunks are required.
* Assume only encoding one list entry for read|write chunks. The NFSv3
* protocol is simple enough to allow this as it only has a single "bulk
* result" in each procedure - complicated NFSv4 COMPOUNDs are not. (The
* RDMA/Sessions NFSv4 proposal addresses this for future v4 revs.)
*
* When used for a single reply chunk (which is a special write
* chunk used for the entire reply, rather than just the data), it
* is used primarily for READDIR and READLINK which would otherwise
* be severely size-limited by a small rdma inline read max. The server
* response will come back as an RDMA Write, followed by a message
* of type RDMA_NOMSG carrying the xid and length. As a result, reply
* chunks do not provide data alignment, however they do not require
* "fixup" (moving the response to the upper layer buffer) either.
*
* Encoding key for single-list chunks (HLOO = Handle32 Length32 Offset64):
*
* Read chunklist (a linked list):
* N elements, position P (same P for all chunks of same arg!):
* 1 - PHLOO - 1 - PHLOO - ... - 1 - PHLOO - 0
*
* Write chunklist (a list of (one) counted array):
* N elements:
* 1 - N - HLOO - HLOO - ... - HLOO - 0
*
* Reply chunk (a counted array):
* N elements:
* 1 - N - HLOO - HLOO - ... - HLOO
*/
static unsigned int
rpcrdma_create_chunks(struct rpc_rqst *rqst, struct xdr_buf *target,
struct rpcrdma_msg *headerp, enum rpcrdma_chunktype type)
{
struct rpcrdma_req *req = rpcr_to_rdmar(rqst);
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(rqst->rq_task->tk_xprt);
int nsegs, nchunks = 0;
unsigned int pos;
struct rpcrdma_mr_seg *seg = req->rl_segments;
struct rpcrdma_read_chunk *cur_rchunk = NULL;
struct rpcrdma_write_array *warray = NULL;
struct rpcrdma_write_chunk *cur_wchunk = NULL;
__be32 *iptr = headerp->rm_body.rm_chunks;
if (type == rpcrdma_readch || type == rpcrdma_areadch) {
/* a read chunk - server will RDMA Read our memory */
cur_rchunk = (struct rpcrdma_read_chunk *) iptr;
} else {
/* a write or reply chunk - server will RDMA Write our memory */
*iptr++ = xdr_zero; /* encode a NULL read chunk list */
if (type == rpcrdma_replych)
*iptr++ = xdr_zero; /* a NULL write chunk list */
warray = (struct rpcrdma_write_array *) iptr;
cur_wchunk = (struct rpcrdma_write_chunk *) (warray + 1);
}
if (type == rpcrdma_replych || type == rpcrdma_areadch)
pos = 0;
else
pos = target->head[0].iov_len;
nsegs = rpcrdma_convert_iovs(target, pos, type, seg, RPCRDMA_MAX_SEGS);
if (nsegs == 0)
return 0;
do {
/* bind/register the memory, then build chunk from result. */
int n = rpcrdma_register_external(seg, nsegs,
cur_wchunk != NULL, r_xprt);
if (n <= 0)
goto out;
if (cur_rchunk) { /* read */
cur_rchunk->rc_discrim = xdr_one;
/* all read chunks have the same "position" */
cur_rchunk->rc_position = htonl(pos);
cur_rchunk->rc_target.rs_handle = htonl(seg->mr_rkey);
cur_rchunk->rc_target.rs_length = htonl(seg->mr_len);
xdr_encode_hyper(
(__be32 *)&cur_rchunk->rc_target.rs_offset,
seg->mr_base);
dprintk("RPC: %s: read chunk "
"elem %d@0x%llx:0x%x pos %u (%s)\n", __func__,
seg->mr_len, (unsigned long long)seg->mr_base,
seg->mr_rkey, pos, n < nsegs ? "more" : "last");
cur_rchunk++;
r_xprt->rx_stats.read_chunk_count++;
} else { /* write/reply */
cur_wchunk->wc_target.rs_handle = htonl(seg->mr_rkey);
cur_wchunk->wc_target.rs_length = htonl(seg->mr_len);
xdr_encode_hyper(
(__be32 *)&cur_wchunk->wc_target.rs_offset,
seg->mr_base);
dprintk("RPC: %s: %s chunk "
"elem %d@0x%llx:0x%x (%s)\n", __func__,
(type == rpcrdma_replych) ? "reply" : "write",
seg->mr_len, (unsigned long long)seg->mr_base,
seg->mr_rkey, n < nsegs ? "more" : "last");
cur_wchunk++;
if (type == rpcrdma_replych)
r_xprt->rx_stats.reply_chunk_count++;
else
r_xprt->rx_stats.write_chunk_count++;
r_xprt->rx_stats.total_rdma_request += seg->mr_len;
}
nchunks++;
seg += n;
nsegs -= n;
} while (nsegs);
/* success. all failures return above */
req->rl_nchunks = nchunks;
BUG_ON(nchunks == 0);
BUG_ON((r_xprt->rx_ia.ri_memreg_strategy == RPCRDMA_FRMR)
&& (nchunks > 3));
/*
* finish off header. If write, marshal discrim and nchunks.
*/
if (cur_rchunk) {
iptr = (__be32 *) cur_rchunk;
*iptr++ = xdr_zero; /* finish the read chunk list */
*iptr++ = xdr_zero; /* encode a NULL write chunk list */
*iptr++ = xdr_zero; /* encode a NULL reply chunk */
} else {
warray->wc_discrim = xdr_one;
warray->wc_nchunks = htonl(nchunks);
iptr = (__be32 *) cur_wchunk;
if (type == rpcrdma_writech) {
*iptr++ = xdr_zero; /* finish the write chunk list */
*iptr++ = xdr_zero; /* encode a NULL reply chunk */
}
}
/*
* Return header size.
*/
return (unsigned char *)iptr - (unsigned char *)headerp;
out:
for (pos = 0; nchunks--;)
pos += rpcrdma_deregister_external(
&req->rl_segments[pos], r_xprt, NULL);
return 0;
}
/*
* Copy write data inline.
* This function is used for "small" requests. Data which is passed
* to RPC via iovecs (or page list) is copied directly into the
* pre-registered memory buffer for this request. For small amounts
* of data, this is efficient. The cutoff value is tunable.
*/
static int
rpcrdma_inline_pullup(struct rpc_rqst *rqst, int pad)
{
int i, npages, curlen;
int copy_len;
unsigned char *srcp, *destp;
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(rqst->rq_xprt);
int page_base;
struct page **ppages;
destp = rqst->rq_svec[0].iov_base;
curlen = rqst->rq_svec[0].iov_len;
destp += curlen;
/*
* Do optional padding where it makes sense. Alignment of write
* payload can help the server, if our setting is accurate.
*/
pad -= (curlen + 36/*sizeof(struct rpcrdma_msg_padded)*/);
if (pad < 0 || rqst->rq_slen - curlen < RPCRDMA_INLINE_PAD_THRESH)
pad = 0; /* don't pad this request */
dprintk("RPC: %s: pad %d destp 0x%p len %d hdrlen %d\n",
__func__, pad, destp, rqst->rq_slen, curlen);
copy_len = rqst->rq_snd_buf.page_len;
if (rqst->rq_snd_buf.tail[0].iov_len) {
curlen = rqst->rq_snd_buf.tail[0].iov_len;
if (destp + copy_len != rqst->rq_snd_buf.tail[0].iov_base) {
memmove(destp + copy_len,
rqst->rq_snd_buf.tail[0].iov_base, curlen);
r_xprt->rx_stats.pullup_copy_count += curlen;
}
dprintk("RPC: %s: tail destp 0x%p len %d\n",
__func__, destp + copy_len, curlen);
rqst->rq_svec[0].iov_len += curlen;
}
r_xprt->rx_stats.pullup_copy_count += copy_len;
page_base = rqst->rq_snd_buf.page_base;
ppages = rqst->rq_snd_buf.pages + (page_base >> PAGE_SHIFT);
page_base &= ~PAGE_MASK;
npages = PAGE_ALIGN(page_base+copy_len) >> PAGE_SHIFT;
for (i = 0; copy_len && i < npages; i++) {
curlen = PAGE_SIZE - page_base;
if (curlen > copy_len)
curlen = copy_len;
dprintk("RPC: %s: page %d destp 0x%p len %d curlen %d\n",
__func__, i, destp, copy_len, curlen);
srcp = kmap_atomic(ppages[i]);
memcpy(destp, srcp+page_base, curlen);
kunmap_atomic(srcp);
rqst->rq_svec[0].iov_len += curlen;
destp += curlen;
copy_len -= curlen;
page_base = 0;
}
/* header now contains entire send message */
return pad;
}
/*
* Marshal a request: the primary job of this routine is to choose
* the transfer modes. See comments below.
*
* Uses multiple RDMA IOVs for a request:
* [0] -- RPC RDMA header, which uses memory from the *start* of the
* preregistered buffer that already holds the RPC data in
* its middle.
* [1] -- the RPC header/data, marshaled by RPC and the NFS protocol.
* [2] -- optional padding.
* [3] -- if padded, header only in [1] and data here.
*/
int
rpcrdma_marshal_req(struct rpc_rqst *rqst)
{
struct rpc_xprt *xprt = rqst->rq_task->tk_xprt;
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt);
struct rpcrdma_req *req = rpcr_to_rdmar(rqst);
char *base;
size_t hdrlen, rpclen, padlen;
enum rpcrdma_chunktype rtype, wtype;
struct rpcrdma_msg *headerp;
/*
* rpclen gets amount of data in first buffer, which is the
* pre-registered buffer.
*/
base = rqst->rq_svec[0].iov_base;
rpclen = rqst->rq_svec[0].iov_len;
/* build RDMA header in private area at front */
headerp = (struct rpcrdma_msg *) req->rl_base;
/* don't htonl XID, it's already done in request */
headerp->rm_xid = rqst->rq_xid;
headerp->rm_vers = xdr_one;
headerp->rm_credit = htonl(r_xprt->rx_buf.rb_max_requests);
headerp->rm_type = htonl(RDMA_MSG);
/*
* Chunks needed for results?
*
* o If the expected result is under the inline threshold, all ops
* return as inline (but see later).
* o Large non-read ops return as a single reply chunk.
* o Large read ops return data as write chunk(s), header as inline.
*
* Note: the NFS code sending down multiple result segments implies
* the op is one of read, readdir[plus], readlink or NFSv4 getacl.
*/
/*
* This code can handle read chunks, write chunks OR reply
* chunks -- only one type. If the request is too big to fit
* inline, then we will choose read chunks. If the request is
* a READ, then use write chunks to separate the file data
* into pages; otherwise use reply chunks.
*/
if (rqst->rq_rcv_buf.buflen <= RPCRDMA_INLINE_READ_THRESHOLD(rqst))
wtype = rpcrdma_noch;
else if (rqst->rq_rcv_buf.page_len == 0)
wtype = rpcrdma_replych;
else if (rqst->rq_rcv_buf.flags & XDRBUF_READ)
wtype = rpcrdma_writech;
else
wtype = rpcrdma_replych;
/*
* Chunks needed for arguments?
*
* o If the total request is under the inline threshold, all ops
* are sent as inline.
* o Large non-write ops are sent with the entire message as a
* single read chunk (protocol 0-position special case).
* o Large write ops transmit data as read chunk(s), header as
* inline.
*
* Note: the NFS code sending down multiple argument segments
* implies the op is a write.
* TBD check NFSv4 setacl
*/
if (rqst->rq_snd_buf.len <= RPCRDMA_INLINE_WRITE_THRESHOLD(rqst))
rtype = rpcrdma_noch;
else if (rqst->rq_snd_buf.page_len == 0)
rtype = rpcrdma_areadch;
else
rtype = rpcrdma_readch;
/* The following simplification is not true forever */
if (rtype != rpcrdma_noch && wtype == rpcrdma_replych)
wtype = rpcrdma_noch;
BUG_ON(rtype != rpcrdma_noch && wtype != rpcrdma_noch);
if (r_xprt->rx_ia.ri_memreg_strategy == RPCRDMA_BOUNCEBUFFERS &&
(rtype != rpcrdma_noch || wtype != rpcrdma_noch)) {
/* forced to "pure inline"? */
dprintk("RPC: %s: too much data (%d/%d) for inline\n",
__func__, rqst->rq_rcv_buf.len, rqst->rq_snd_buf.len);
return -1;
}
hdrlen = 28; /*sizeof *headerp;*/
padlen = 0;
/*
* Pull up any extra send data into the preregistered buffer.
* When padding is in use and applies to the transfer, insert
* it and change the message type.
*/
if (rtype == rpcrdma_noch) {
padlen = rpcrdma_inline_pullup(rqst,
RPCRDMA_INLINE_PAD_VALUE(rqst));
if (padlen) {
headerp->rm_type = htonl(RDMA_MSGP);
headerp->rm_body.rm_padded.rm_align =
htonl(RPCRDMA_INLINE_PAD_VALUE(rqst));
headerp->rm_body.rm_padded.rm_thresh =
htonl(RPCRDMA_INLINE_PAD_THRESH);
headerp->rm_body.rm_padded.rm_pempty[0] = xdr_zero;
headerp->rm_body.rm_padded.rm_pempty[1] = xdr_zero;
headerp->rm_body.rm_padded.rm_pempty[2] = xdr_zero;
hdrlen += 2 * sizeof(u32); /* extra words in padhdr */
BUG_ON(wtype != rpcrdma_noch);
} else {
headerp->rm_body.rm_nochunks.rm_empty[0] = xdr_zero;
headerp->rm_body.rm_nochunks.rm_empty[1] = xdr_zero;
headerp->rm_body.rm_nochunks.rm_empty[2] = xdr_zero;
/* new length after pullup */
rpclen = rqst->rq_svec[0].iov_len;
/*
* Currently we try to not actually use read inline.
* Reply chunks have the desirable property that
* they land, packed, directly in the target buffers
* without headers, so they require no fixup. The
* additional RDMA Write op sends the same amount
* of data, streams on-the-wire and adds no overhead
* on receive. Therefore, we request a reply chunk
* for non-writes wherever feasible and efficient.
*/
if (wtype == rpcrdma_noch &&
r_xprt->rx_ia.ri_memreg_strategy > RPCRDMA_REGISTER)
wtype = rpcrdma_replych;
}
}
/*
* Marshal chunks. This routine will return the header length
* consumed by marshaling.
*/
if (rtype != rpcrdma_noch) {
hdrlen = rpcrdma_create_chunks(rqst,
&rqst->rq_snd_buf, headerp, rtype);
wtype = rtype; /* simplify dprintk */
} else if (wtype != rpcrdma_noch) {
hdrlen = rpcrdma_create_chunks(rqst,
&rqst->rq_rcv_buf, headerp, wtype);
}
if (hdrlen == 0)
return -1;
dprintk("RPC: %s: %s: hdrlen %zd rpclen %zd padlen %zd"
" headerp 0x%p base 0x%p lkey 0x%x\n",
__func__, transfertypes[wtype], hdrlen, rpclen, padlen,
headerp, base, req->rl_iov.lkey);
/*
* initialize send_iov's - normally only two: rdma chunk header and
* single preregistered RPC header buffer, but if padding is present,
* then use a preregistered (and zeroed) pad buffer between the RPC
* header and any write data. In all non-rdma cases, any following
* data has been copied into the RPC header buffer.
*/
req->rl_send_iov[0].addr = req->rl_iov.addr;
req->rl_send_iov[0].length = hdrlen;
req->rl_send_iov[0].lkey = req->rl_iov.lkey;
req->rl_send_iov[1].addr = req->rl_iov.addr + (base - req->rl_base);
req->rl_send_iov[1].length = rpclen;
req->rl_send_iov[1].lkey = req->rl_iov.lkey;
req->rl_niovs = 2;
if (padlen) {
struct rpcrdma_ep *ep = &r_xprt->rx_ep;
req->rl_send_iov[2].addr = ep->rep_pad.addr;
req->rl_send_iov[2].length = padlen;
req->rl_send_iov[2].lkey = ep->rep_pad.lkey;
req->rl_send_iov[3].addr = req->rl_send_iov[1].addr + rpclen;
req->rl_send_iov[3].length = rqst->rq_slen - rpclen;
req->rl_send_iov[3].lkey = req->rl_iov.lkey;
req->rl_niovs = 4;
}
return 0;
}
/*
* Chase down a received write or reply chunklist to get length
* RDMA'd by server. See map at rpcrdma_create_chunks()! :-)
*/
static int
rpcrdma_count_chunks(struct rpcrdma_rep *rep, unsigned int max, int wrchunk, __be32 **iptrp)
{
unsigned int i, total_len;
struct rpcrdma_write_chunk *cur_wchunk;
i = ntohl(**iptrp); /* get array count */
if (i > max)
return -1;
cur_wchunk = (struct rpcrdma_write_chunk *) (*iptrp + 1);
total_len = 0;
while (i--) {
struct rpcrdma_segment *seg = &cur_wchunk->wc_target;
ifdebug(FACILITY) {
u64 off;
xdr_decode_hyper((__be32 *)&seg->rs_offset, &off);
dprintk("RPC: %s: chunk %d@0x%llx:0x%x\n",
__func__,
ntohl(seg->rs_length),
(unsigned long long)off,
ntohl(seg->rs_handle));
}
total_len += ntohl(seg->rs_length);
++cur_wchunk;
}
/* check and adjust for properly terminated write chunk */
if (wrchunk) {
__be32 *w = (__be32 *) cur_wchunk;
if (*w++ != xdr_zero)
return -1;
cur_wchunk = (struct rpcrdma_write_chunk *) w;
}
if ((char *) cur_wchunk > rep->rr_base + rep->rr_len)
return -1;
*iptrp = (__be32 *) cur_wchunk;
return total_len;
}
/*
* Scatter inline received data back into provided iov's.
*/
static void
rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
{
int i, npages, curlen, olen;
char *destp;
struct page **ppages;
int page_base;
curlen = rqst->rq_rcv_buf.head[0].iov_len;
if (curlen > copy_len) { /* write chunk header fixup */
curlen = copy_len;
rqst->rq_rcv_buf.head[0].iov_len = curlen;
}
dprintk("RPC: %s: srcp 0x%p len %d hdrlen %d\n",
__func__, srcp, copy_len, curlen);
/* Shift pointer for first receive segment only */
rqst->rq_rcv_buf.head[0].iov_base = srcp;
srcp += curlen;
copy_len -= curlen;
olen = copy_len;
i = 0;
rpcx_to_rdmax(rqst->rq_xprt)->rx_stats.fixup_copy_count += olen;
page_base = rqst->rq_rcv_buf.page_base;
ppages = rqst->rq_rcv_buf.pages + (page_base >> PAGE_SHIFT);
page_base &= ~PAGE_MASK;
if (copy_len && rqst->rq_rcv_buf.page_len) {
npages = PAGE_ALIGN(page_base +
rqst->rq_rcv_buf.page_len) >> PAGE_SHIFT;
for (; i < npages; i++) {
curlen = PAGE_SIZE - page_base;
if (curlen > copy_len)
curlen = copy_len;
dprintk("RPC: %s: page %d"
" srcp 0x%p len %d curlen %d\n",
__func__, i, srcp, copy_len, curlen);
destp = kmap_atomic(ppages[i]);
memcpy(destp + page_base, srcp, curlen);
flush_dcache_page(ppages[i]);
kunmap_atomic(destp);
srcp += curlen;
copy_len -= curlen;
if (copy_len == 0)
break;
page_base = 0;
}
rqst->rq_rcv_buf.page_len = olen - copy_len;
} else
rqst->rq_rcv_buf.page_len = 0;
if (copy_len && rqst->rq_rcv_buf.tail[0].iov_len) {
curlen = copy_len;
if (curlen > rqst->rq_rcv_buf.tail[0].iov_len)
curlen = rqst->rq_rcv_buf.tail[0].iov_len;
if (rqst->rq_rcv_buf.tail[0].iov_base != srcp)
memmove(rqst->rq_rcv_buf.tail[0].iov_base, srcp, curlen);
dprintk("RPC: %s: tail srcp 0x%p len %d curlen %d\n",
__func__, srcp, copy_len, curlen);
rqst->rq_rcv_buf.tail[0].iov_len = curlen;
copy_len -= curlen; ++i;
} else
rqst->rq_rcv_buf.tail[0].iov_len = 0;
if (pad) {
/* implicit padding on terminal chunk */
unsigned char *p = rqst->rq_rcv_buf.tail[0].iov_base;
while (pad--)
p[rqst->rq_rcv_buf.tail[0].iov_len++] = 0;
}
if (copy_len)
dprintk("RPC: %s: %d bytes in"
" %d extra segments (%d lost)\n",
__func__, olen, i, copy_len);
/* TBD avoid a warning from call_decode() */
rqst->rq_private_buf = rqst->rq_rcv_buf;
}
/*
* This function is called when an async event is posted to
* the connection which changes the connection state. All it
* does at this point is mark the connection up/down, the rpc
* timers do the rest.
*/
void
rpcrdma_conn_func(struct rpcrdma_ep *ep)
{
struct rpc_xprt *xprt = ep->rep_xprt;
spin_lock_bh(&xprt->transport_lock);
if (++xprt->connect_cookie == 0) /* maintain a reserved value */
++xprt->connect_cookie;
if (ep->rep_connected > 0) {
if (!xprt_test_and_set_connected(xprt))
xprt_wake_pending_tasks(xprt, 0);
} else {
if (xprt_test_and_clear_connected(xprt))
xprt_wake_pending_tasks(xprt, -ENOTCONN);
}
spin_unlock_bh(&xprt->transport_lock);
}
/*
* This function is called when memory window unbind which we are waiting
* for completes. Just use rr_func (zeroed by upcall) to signal completion.
*/
static void
rpcrdma_unbind_func(struct rpcrdma_rep *rep)
{
wake_up(&rep->rr_unbind);
}
/*
* Called as a tasklet to do req/reply match and complete a request
* Errors must result in the RPC task either being awakened, or
* allowed to timeout, to discover the errors at that time.
*/
void
rpcrdma_reply_handler(struct rpcrdma_rep *rep)
{
struct rpcrdma_msg *headerp;
struct rpcrdma_req *req;
struct rpc_rqst *rqst;
struct rpc_xprt *xprt = rep->rr_xprt;
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt);
__be32 *iptr;
int i, rdmalen, status;
/* Check status. If bad, signal disconnect and return rep to pool */
if (rep->rr_len == ~0U) {
rpcrdma_recv_buffer_put(rep);
if (r_xprt->rx_ep.rep_connected == 1) {
r_xprt->rx_ep.rep_connected = -EIO;
rpcrdma_conn_func(&r_xprt->rx_ep);
}
return;
}
if (rep->rr_len < 28) {
dprintk("RPC: %s: short/invalid reply\n", __func__);
goto repost;
}
headerp = (struct rpcrdma_msg *) rep->rr_base;
if (headerp->rm_vers != xdr_one) {
dprintk("RPC: %s: invalid version %d\n",
__func__, ntohl(headerp->rm_vers));
goto repost;
}
/* Get XID and try for a match. */
spin_lock(&xprt->transport_lock);
rqst = xprt_lookup_rqst(xprt, headerp->rm_xid);
if (rqst == NULL) {
spin_unlock(&xprt->transport_lock);
dprintk("RPC: %s: reply 0x%p failed "
"to match any request xid 0x%08x len %d\n",
__func__, rep, headerp->rm_xid, rep->rr_len);
repost:
r_xprt->rx_stats.bad_reply_count++;
rep->rr_func = rpcrdma_reply_handler;
if (rpcrdma_ep_post_recv(&r_xprt->rx_ia, &r_xprt->rx_ep, rep))
rpcrdma_recv_buffer_put(rep);
return;
}
/* get request object */
req = rpcr_to_rdmar(rqst);
if (req->rl_reply) {
spin_unlock(&xprt->transport_lock);
dprintk("RPC: %s: duplicate reply 0x%p to RPC "
"request 0x%p: xid 0x%08x\n", __func__, rep, req,
headerp->rm_xid);
goto repost;
}
dprintk("RPC: %s: reply 0x%p completes request 0x%p\n"
" RPC request 0x%p xid 0x%08x\n",
__func__, rep, req, rqst, headerp->rm_xid);
/* from here on, the reply is no longer an orphan */
req->rl_reply = rep;
/* check for expected message types */
/* The order of some of these tests is important. */
switch (headerp->rm_type) {
case htonl(RDMA_MSG):
/* never expect read chunks */
/* never expect reply chunks (two ways to check) */
/* never expect write chunks without having offered RDMA */
if (headerp->rm_body.rm_chunks[0] != xdr_zero ||
(headerp->rm_body.rm_chunks[1] == xdr_zero &&
headerp->rm_body.rm_chunks[2] != xdr_zero) ||
(headerp->rm_body.rm_chunks[1] != xdr_zero &&
req->rl_nchunks == 0))
goto badheader;
if (headerp->rm_body.rm_chunks[1] != xdr_zero) {
/* count any expected write chunks in read reply */
/* start at write chunk array count */
iptr = &headerp->rm_body.rm_chunks[2];
rdmalen = rpcrdma_count_chunks(rep,
req->rl_nchunks, 1, &iptr);
/* check for validity, and no reply chunk after */
if (rdmalen < 0 || *iptr++ != xdr_zero)
goto badheader;
rep->rr_len -=
((unsigned char *)iptr - (unsigned char *)headerp);
status = rep->rr_len + rdmalen;
r_xprt->rx_stats.total_rdma_reply += rdmalen;
/* special case - last chunk may omit padding */
if (rdmalen &= 3) {
rdmalen = 4 - rdmalen;
status += rdmalen;
}
} else {
/* else ordinary inline */
rdmalen = 0;
iptr = (__be32 *)((unsigned char *)headerp + 28);
rep->rr_len -= 28; /*sizeof *headerp;*/
status = rep->rr_len;
}
/* Fix up the rpc results for upper layer */
rpcrdma_inline_fixup(rqst, (char *)iptr, rep->rr_len, rdmalen);
break;
case htonl(RDMA_NOMSG):
/* never expect read or write chunks, always reply chunks */
if (headerp->rm_body.rm_chunks[0] != xdr_zero ||
headerp->rm_body.rm_chunks[1] != xdr_zero ||
headerp->rm_body.rm_chunks[2] != xdr_one ||
req->rl_nchunks == 0)
goto badheader;
iptr = (__be32 *)((unsigned char *)headerp + 28);
rdmalen = rpcrdma_count_chunks(rep, req->rl_nchunks, 0, &iptr);
if (rdmalen < 0)
goto badheader;
r_xprt->rx_stats.total_rdma_reply += rdmalen;
/* Reply chunk buffer already is the reply vector - no fixup. */
status = rdmalen;
break;
badheader:
default:
dprintk("%s: invalid rpcrdma reply header (type %d):"
" chunks[012] == %d %d %d"
" expected chunks <= %d\n",
__func__, ntohl(headerp->rm_type),
headerp->rm_body.rm_chunks[0],
headerp->rm_body.rm_chunks[1],
headerp->rm_body.rm_chunks[2],
req->rl_nchunks);
status = -EIO;
r_xprt->rx_stats.bad_reply_count++;
break;
}
/* If using mw bind, start the deregister process now. */
/* (Note: if mr_free(), cannot perform it here, in tasklet context) */
if (req->rl_nchunks) switch (r_xprt->rx_ia.ri_memreg_strategy) {
case RPCRDMA_MEMWINDOWS:
for (i = 0; req->rl_nchunks-- > 1;)
i += rpcrdma_deregister_external(
&req->rl_segments[i], r_xprt, NULL);
/* Optionally wait (not here) for unbinds to complete */
rep->rr_func = rpcrdma_unbind_func;
(void) rpcrdma_deregister_external(&req->rl_segments[i],
r_xprt, rep);
break;
case RPCRDMA_MEMWINDOWS_ASYNC:
for (i = 0; req->rl_nchunks--;)
i += rpcrdma_deregister_external(&req->rl_segments[i],
r_xprt, NULL);
break;
default:
break;
}
dprintk("RPC: %s: xprt_complete_rqst(0x%p, 0x%p, %d)\n",
__func__, xprt, rqst, status);
xprt_complete_rqst(rqst->rq_task, status);
spin_unlock(&xprt->transport_lock);
}
| gpl-2.0 |
GameTheory-/android_kernel_lge_l0 | net/ax25/ax25_timer.c | 5088 | 5261 | /*
* 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.
*
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Tomi Manninen OH2BNS (oh2bns@sral.fi)
* Copyright (C) Darryl Miles G7LED (dlm@g7led.demon.co.uk)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
* Copyright (C) Frederic Rible F1OAT (frible@teaser.fr)
* Copyright (C) 2002 Ralf Baechle DO1GRB (ralf@gnu.org)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
static void ax25_heartbeat_expiry(unsigned long);
static void ax25_t1timer_expiry(unsigned long);
static void ax25_t2timer_expiry(unsigned long);
static void ax25_t3timer_expiry(unsigned long);
static void ax25_idletimer_expiry(unsigned long);
void ax25_setup_timers(ax25_cb *ax25)
{
setup_timer(&ax25->timer, ax25_heartbeat_expiry, (unsigned long)ax25);
setup_timer(&ax25->t1timer, ax25_t1timer_expiry, (unsigned long)ax25);
setup_timer(&ax25->t2timer, ax25_t2timer_expiry, (unsigned long)ax25);
setup_timer(&ax25->t3timer, ax25_t3timer_expiry, (unsigned long)ax25);
setup_timer(&ax25->idletimer, ax25_idletimer_expiry,
(unsigned long)ax25);
}
void ax25_start_heartbeat(ax25_cb *ax25)
{
mod_timer(&ax25->timer, jiffies + 5 * HZ);
}
void ax25_start_t1timer(ax25_cb *ax25)
{
mod_timer(&ax25->t1timer, jiffies + ax25->t1);
}
void ax25_start_t2timer(ax25_cb *ax25)
{
mod_timer(&ax25->t2timer, jiffies + ax25->t2);
}
void ax25_start_t3timer(ax25_cb *ax25)
{
if (ax25->t3 > 0)
mod_timer(&ax25->t3timer, jiffies + ax25->t3);
else
del_timer(&ax25->t3timer);
}
void ax25_start_idletimer(ax25_cb *ax25)
{
if (ax25->idle > 0)
mod_timer(&ax25->idletimer, jiffies + ax25->idle);
else
del_timer(&ax25->idletimer);
}
void ax25_stop_heartbeat(ax25_cb *ax25)
{
del_timer(&ax25->timer);
}
void ax25_stop_t1timer(ax25_cb *ax25)
{
del_timer(&ax25->t1timer);
}
void ax25_stop_t2timer(ax25_cb *ax25)
{
del_timer(&ax25->t2timer);
}
void ax25_stop_t3timer(ax25_cb *ax25)
{
del_timer(&ax25->t3timer);
}
void ax25_stop_idletimer(ax25_cb *ax25)
{
del_timer(&ax25->idletimer);
}
int ax25_t1timer_running(ax25_cb *ax25)
{
return timer_pending(&ax25->t1timer);
}
unsigned long ax25_display_timer(struct timer_list *timer)
{
if (!timer_pending(timer))
return 0;
return timer->expires - jiffies;
}
EXPORT_SYMBOL(ax25_display_timer);
static void ax25_heartbeat_expiry(unsigned long param)
{
int proto = AX25_PROTO_STD_SIMPLEX;
ax25_cb *ax25 = (ax25_cb *)param;
if (ax25->ax25_dev)
proto = ax25->ax25_dev->values[AX25_VALUES_PROTOCOL];
switch (proto) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_heartbeat_expiry(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
if (ax25->ax25_dev->dama.slave)
ax25_ds_heartbeat_expiry(ax25);
else
ax25_std_heartbeat_expiry(ax25);
break;
#endif
}
}
static void ax25_t1timer_expiry(unsigned long param)
{
ax25_cb *ax25 = (ax25_cb *)param;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_t1timer_expiry(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
if (!ax25->ax25_dev->dama.slave)
ax25_std_t1timer_expiry(ax25);
break;
#endif
}
}
static void ax25_t2timer_expiry(unsigned long param)
{
ax25_cb *ax25 = (ax25_cb *)param;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_t2timer_expiry(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
if (!ax25->ax25_dev->dama.slave)
ax25_std_t2timer_expiry(ax25);
break;
#endif
}
}
static void ax25_t3timer_expiry(unsigned long param)
{
ax25_cb *ax25 = (ax25_cb *)param;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_t3timer_expiry(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
if (ax25->ax25_dev->dama.slave)
ax25_ds_t3timer_expiry(ax25);
else
ax25_std_t3timer_expiry(ax25);
break;
#endif
}
}
static void ax25_idletimer_expiry(unsigned long param)
{
ax25_cb *ax25 = (ax25_cb *)param;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_idletimer_expiry(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
if (ax25->ax25_dev->dama.slave)
ax25_ds_idletimer_expiry(ax25);
else
ax25_std_idletimer_expiry(ax25);
break;
#endif
}
}
| gpl-2.0 |
nazunamoe/Oxygen_united_kernel-gproj | crypto/async_tx/async_tx.c | 5344 | 7812 | /*
* core routines for the asynchronous memory transfer/transform api
*
* Copyright © 2006, Intel Corporation.
*
* Dan Williams <dan.j.williams@intel.com>
*
* with architecture considerations by:
* Neil Brown <neilb@suse.de>
* Jeff Garzik <jeff@garzik.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/rculist.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/async_tx.h>
#ifdef CONFIG_DMA_ENGINE
static int __init async_tx_init(void)
{
async_dmaengine_get();
printk(KERN_INFO "async_tx: api initialized (async)\n");
return 0;
}
static void __exit async_tx_exit(void)
{
async_dmaengine_put();
}
module_init(async_tx_init);
module_exit(async_tx_exit);
/**
* __async_tx_find_channel - find a channel to carry out the operation or let
* the transaction execute synchronously
* @submit: transaction dependency and submission modifiers
* @tx_type: transaction type
*/
struct dma_chan *
__async_tx_find_channel(struct async_submit_ctl *submit,
enum dma_transaction_type tx_type)
{
struct dma_async_tx_descriptor *depend_tx = submit->depend_tx;
/* see if we can keep the chain on one channel */
if (depend_tx &&
dma_has_cap(tx_type, depend_tx->chan->device->cap_mask))
return depend_tx->chan;
return async_dma_find_channel(tx_type);
}
EXPORT_SYMBOL_GPL(__async_tx_find_channel);
#endif
/**
* async_tx_channel_switch - queue an interrupt descriptor with a dependency
* pre-attached.
* @depend_tx: the operation that must finish before the new operation runs
* @tx: the new operation
*/
static void
async_tx_channel_switch(struct dma_async_tx_descriptor *depend_tx,
struct dma_async_tx_descriptor *tx)
{
struct dma_chan *chan = depend_tx->chan;
struct dma_device *device = chan->device;
struct dma_async_tx_descriptor *intr_tx = (void *) ~0;
/* first check to see if we can still append to depend_tx */
txd_lock(depend_tx);
if (txd_parent(depend_tx) && depend_tx->chan == tx->chan) {
txd_chain(depend_tx, tx);
intr_tx = NULL;
}
txd_unlock(depend_tx);
/* attached dependency, flush the parent channel */
if (!intr_tx) {
device->device_issue_pending(chan);
return;
}
/* see if we can schedule an interrupt
* otherwise poll for completion
*/
if (dma_has_cap(DMA_INTERRUPT, device->cap_mask))
intr_tx = device->device_prep_dma_interrupt(chan, 0);
else
intr_tx = NULL;
if (intr_tx) {
intr_tx->callback = NULL;
intr_tx->callback_param = NULL;
/* safe to chain outside the lock since we know we are
* not submitted yet
*/
txd_chain(intr_tx, tx);
/* check if we need to append */
txd_lock(depend_tx);
if (txd_parent(depend_tx)) {
txd_chain(depend_tx, intr_tx);
async_tx_ack(intr_tx);
intr_tx = NULL;
}
txd_unlock(depend_tx);
if (intr_tx) {
txd_clear_parent(intr_tx);
intr_tx->tx_submit(intr_tx);
async_tx_ack(intr_tx);
}
device->device_issue_pending(chan);
} else {
if (dma_wait_for_async_tx(depend_tx) == DMA_ERROR)
panic("%s: DMA_ERROR waiting for depend_tx\n",
__func__);
tx->tx_submit(tx);
}
}
/**
* submit_disposition - flags for routing an incoming operation
* @ASYNC_TX_SUBMITTED: we were able to append the new operation under the lock
* @ASYNC_TX_CHANNEL_SWITCH: when the lock is dropped schedule a channel switch
* @ASYNC_TX_DIRECT_SUBMIT: when the lock is dropped submit directly
*
* while holding depend_tx->lock we must avoid submitting new operations
* to prevent a circular locking dependency with drivers that already
* hold a channel lock when calling async_tx_run_dependencies.
*/
enum submit_disposition {
ASYNC_TX_SUBMITTED,
ASYNC_TX_CHANNEL_SWITCH,
ASYNC_TX_DIRECT_SUBMIT,
};
void
async_tx_submit(struct dma_chan *chan, struct dma_async_tx_descriptor *tx,
struct async_submit_ctl *submit)
{
struct dma_async_tx_descriptor *depend_tx = submit->depend_tx;
tx->callback = submit->cb_fn;
tx->callback_param = submit->cb_param;
if (depend_tx) {
enum submit_disposition s;
/* sanity check the dependency chain:
* 1/ if ack is already set then we cannot be sure
* we are referring to the correct operation
* 2/ dependencies are 1:1 i.e. two transactions can
* not depend on the same parent
*/
BUG_ON(async_tx_test_ack(depend_tx) || txd_next(depend_tx) ||
txd_parent(tx));
/* the lock prevents async_tx_run_dependencies from missing
* the setting of ->next when ->parent != NULL
*/
txd_lock(depend_tx);
if (txd_parent(depend_tx)) {
/* we have a parent so we can not submit directly
* if we are staying on the same channel: append
* else: channel switch
*/
if (depend_tx->chan == chan) {
txd_chain(depend_tx, tx);
s = ASYNC_TX_SUBMITTED;
} else
s = ASYNC_TX_CHANNEL_SWITCH;
} else {
/* we do not have a parent so we may be able to submit
* directly if we are staying on the same channel
*/
if (depend_tx->chan == chan)
s = ASYNC_TX_DIRECT_SUBMIT;
else
s = ASYNC_TX_CHANNEL_SWITCH;
}
txd_unlock(depend_tx);
switch (s) {
case ASYNC_TX_SUBMITTED:
break;
case ASYNC_TX_CHANNEL_SWITCH:
async_tx_channel_switch(depend_tx, tx);
break;
case ASYNC_TX_DIRECT_SUBMIT:
txd_clear_parent(tx);
tx->tx_submit(tx);
break;
}
} else {
txd_clear_parent(tx);
tx->tx_submit(tx);
}
if (submit->flags & ASYNC_TX_ACK)
async_tx_ack(tx);
if (depend_tx)
async_tx_ack(depend_tx);
}
EXPORT_SYMBOL_GPL(async_tx_submit);
/**
* async_trigger_callback - schedules the callback function to be run
* @submit: submission and completion parameters
*
* honored flags: ASYNC_TX_ACK
*
* The callback is run after any dependent operations have completed.
*/
struct dma_async_tx_descriptor *
async_trigger_callback(struct async_submit_ctl *submit)
{
struct dma_chan *chan;
struct dma_device *device;
struct dma_async_tx_descriptor *tx;
struct dma_async_tx_descriptor *depend_tx = submit->depend_tx;
if (depend_tx) {
chan = depend_tx->chan;
device = chan->device;
/* see if we can schedule an interrupt
* otherwise poll for completion
*/
if (device && !dma_has_cap(DMA_INTERRUPT, device->cap_mask))
device = NULL;
tx = device ? device->device_prep_dma_interrupt(chan, 0) : NULL;
} else
tx = NULL;
if (tx) {
pr_debug("%s: (async)\n", __func__);
async_tx_submit(chan, tx, submit);
} else {
pr_debug("%s: (sync)\n", __func__);
/* wait for any prerequisite operations */
async_tx_quiesce(&submit->depend_tx);
async_tx_sync_epilog(submit);
}
return tx;
}
EXPORT_SYMBOL_GPL(async_trigger_callback);
/**
* async_tx_quiesce - ensure tx is complete and freeable upon return
* @tx - transaction to quiesce
*/
void async_tx_quiesce(struct dma_async_tx_descriptor **tx)
{
if (*tx) {
/* if ack is already set then we cannot be sure
* we are referring to the correct operation
*/
BUG_ON(async_tx_test_ack(*tx));
if (dma_wait_for_async_tx(*tx) == DMA_ERROR)
panic("DMA_ERROR waiting for transaction\n");
async_tx_ack(*tx);
*tx = NULL;
}
}
EXPORT_SYMBOL_GPL(async_tx_quiesce);
MODULE_AUTHOR("Intel Corporation");
MODULE_DESCRIPTION("Asynchronous Bulk Memory Transactions API");
MODULE_LICENSE("GPL");
| gpl-2.0 |
htc-mirror/ruby-ics-crc-3.0.16-fd362fb | fs/nfsd/nfsxdr.c | 8160 | 13276 | /*
* XDR support for nfsd
*
* Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
*/
#include "xdr.h"
#include "auth.h"
#define NFSDDBG_FACILITY NFSDDBG_XDR
/*
* Mapping of S_IF* types to NFS file types
*/
static u32 nfs_ftypes[] = {
NFNON, NFCHR, NFCHR, NFBAD,
NFDIR, NFBAD, NFBLK, NFBAD,
NFREG, NFBAD, NFLNK, NFBAD,
NFSOCK, NFBAD, NFLNK, NFBAD,
};
/*
* XDR functions for basic NFS types
*/
static __be32 *
decode_fh(__be32 *p, struct svc_fh *fhp)
{
fh_init(fhp, NFS_FHSIZE);
memcpy(&fhp->fh_handle.fh_base, p, NFS_FHSIZE);
fhp->fh_handle.fh_size = NFS_FHSIZE;
/* FIXME: Look up export pointer here and verify
* Sun Secure RPC if requested */
return p + (NFS_FHSIZE >> 2);
}
/* Helper function for NFSv2 ACL code */
__be32 *nfs2svc_decode_fh(__be32 *p, struct svc_fh *fhp)
{
return decode_fh(p, fhp);
}
static __be32 *
encode_fh(__be32 *p, struct svc_fh *fhp)
{
memcpy(p, &fhp->fh_handle.fh_base, NFS_FHSIZE);
return p + (NFS_FHSIZE>> 2);
}
/*
* Decode a file name and make sure that the path contains
* no slashes or null bytes.
*/
static __be32 *
decode_filename(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS_MAXNAMLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0' || *name == '/')
return NULL;
}
}
return p;
}
static __be32 *
decode_pathname(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS_MAXPATHLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0')
return NULL;
}
}
return p;
}
static __be32 *
decode_sattr(__be32 *p, struct iattr *iap)
{
u32 tmp, tmp1;
iap->ia_valid = 0;
/* Sun client bug compatibility check: some sun clients seem to
* put 0xffff in the mode field when they mean 0xffffffff.
* Quoting the 4.4BSD nfs server code: Nah nah nah nah na nah.
*/
if ((tmp = ntohl(*p++)) != (u32)-1 && tmp != 0xffff) {
iap->ia_valid |= ATTR_MODE;
iap->ia_mode = tmp;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_valid |= ATTR_UID;
iap->ia_uid = tmp;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_valid |= ATTR_GID;
iap->ia_gid = tmp;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_valid |= ATTR_SIZE;
iap->ia_size = tmp;
}
tmp = ntohl(*p++); tmp1 = ntohl(*p++);
if (tmp != (u32)-1 && tmp1 != (u32)-1) {
iap->ia_valid |= ATTR_ATIME | ATTR_ATIME_SET;
iap->ia_atime.tv_sec = tmp;
iap->ia_atime.tv_nsec = tmp1 * 1000;
}
tmp = ntohl(*p++); tmp1 = ntohl(*p++);
if (tmp != (u32)-1 && tmp1 != (u32)-1) {
iap->ia_valid |= ATTR_MTIME | ATTR_MTIME_SET;
iap->ia_mtime.tv_sec = tmp;
iap->ia_mtime.tv_nsec = tmp1 * 1000;
/*
* Passing the invalid value useconds=1000000 for mtime
* is a Sun convention for "set both mtime and atime to
* current server time". It's needed to make permissions
* checks for the "touch" program across v2 mounts to
* Solaris and Irix boxes work correctly. See description of
* sattr in section 6.1 of "NFS Illustrated" by
* Brent Callaghan, Addison-Wesley, ISBN 0-201-32750-5
*/
if (tmp1 == 1000000)
iap->ia_valid &= ~(ATTR_ATIME_SET|ATTR_MTIME_SET);
}
return p;
}
static __be32 *
encode_fattr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp,
struct kstat *stat)
{
struct dentry *dentry = fhp->fh_dentry;
int type;
struct timespec time;
u32 f;
type = (stat->mode & S_IFMT);
*p++ = htonl(nfs_ftypes[type >> 12]);
*p++ = htonl((u32) stat->mode);
*p++ = htonl((u32) stat->nlink);
*p++ = htonl((u32) nfsd_ruid(rqstp, stat->uid));
*p++ = htonl((u32) nfsd_rgid(rqstp, stat->gid));
if (S_ISLNK(type) && stat->size > NFS_MAXPATHLEN) {
*p++ = htonl(NFS_MAXPATHLEN);
} else {
*p++ = htonl((u32) stat->size);
}
*p++ = htonl((u32) stat->blksize);
if (S_ISCHR(type) || S_ISBLK(type))
*p++ = htonl(new_encode_dev(stat->rdev));
else
*p++ = htonl(0xffffffff);
*p++ = htonl((u32) stat->blocks);
switch (fsid_source(fhp)) {
default:
case FSIDSOURCE_DEV:
*p++ = htonl(new_encode_dev(stat->dev));
break;
case FSIDSOURCE_FSID:
*p++ = htonl((u32) fhp->fh_export->ex_fsid);
break;
case FSIDSOURCE_UUID:
f = ((u32*)fhp->fh_export->ex_uuid)[0];
f ^= ((u32*)fhp->fh_export->ex_uuid)[1];
f ^= ((u32*)fhp->fh_export->ex_uuid)[2];
f ^= ((u32*)fhp->fh_export->ex_uuid)[3];
*p++ = htonl(f);
break;
}
*p++ = htonl((u32) stat->ino);
*p++ = htonl((u32) stat->atime.tv_sec);
*p++ = htonl(stat->atime.tv_nsec ? stat->atime.tv_nsec / 1000 : 0);
lease_get_mtime(dentry->d_inode, &time);
*p++ = htonl((u32) time.tv_sec);
*p++ = htonl(time.tv_nsec ? time.tv_nsec / 1000 : 0);
*p++ = htonl((u32) stat->ctime.tv_sec);
*p++ = htonl(stat->ctime.tv_nsec ? stat->ctime.tv_nsec / 1000 : 0);
return p;
}
/* Helper function for NFSv2 ACL code */
__be32 *nfs2svc_encode_fattr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp)
{
struct kstat stat;
vfs_getattr(fhp->fh_export->ex_path.mnt, fhp->fh_dentry, &stat);
return encode_fattr(rqstp, p, fhp, &stat);
}
/*
* XDR decode functions
*/
int
nfssvc_decode_void(struct svc_rqst *rqstp, __be32 *p, void *dummy)
{
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_fhandle(struct svc_rqst *rqstp, __be32 *p, struct nfsd_fhandle *args)
{
if (!(p = decode_fh(p, &args->fh)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_sattrargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_sattrargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_diropargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_diropargs *args)
{
if (!(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readargs *args)
{
unsigned int len;
int v,pn;
if (!(p = decode_fh(p, &args->fh)))
return 0;
args->offset = ntohl(*p++);
len = args->count = ntohl(*p++);
p++; /* totalcount - unused */
if (len > NFSSVC_MAXBLKSIZE_V2)
len = NFSSVC_MAXBLKSIZE_V2;
/* set up somewhere to store response.
* We take pages, put them on reslist and include in iovec
*/
v=0;
while (len > 0) {
pn = rqstp->rq_resused++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_respages[pn]);
rqstp->rq_vec[v].iov_len = len < PAGE_SIZE?len:PAGE_SIZE;
len -= rqstp->rq_vec[v].iov_len;
v++;
}
args->vlen = v;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_writeargs *args)
{
unsigned int len, hdr, dlen;
int v;
if (!(p = decode_fh(p, &args->fh)))
return 0;
p++; /* beginoffset */
args->offset = ntohl(*p++); /* offset */
p++; /* totalcount */
len = args->len = ntohl(*p++);
/*
* The protocol specifies a maximum of 8192 bytes.
*/
if (len > NFSSVC_MAXBLKSIZE_V2)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - rqstp->rq_arg.head[0].iov_base;
dlen = rqstp->rq_arg.head[0].iov_len + rqstp->rq_arg.page_len
- hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = rqstp->rq_arg.head[0].iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
int
nfssvc_decode_createargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_createargs *args)
{
if ( !(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_renameargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_renameargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_filename(p, &args->fname, &args->flen))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args)
{
if (!(p = decode_fh(p, &args->fh)))
return 0;
args->buffer = page_address(rqstp->rq_respages[rqstp->rq_resused++]);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_linkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_linkargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_symlinkargs *args)
{
if ( !(p = decode_fh(p, &args->ffh))
|| !(p = decode_filename(p, &args->fname, &args->flen))
|| !(p = decode_pathname(p, &args->tname, &args->tlen)))
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readdirargs *args)
{
if (!(p = decode_fh(p, &args->fh)))
return 0;
args->cookie = ntohl(*p++);
args->count = ntohl(*p++);
if (args->count > PAGE_SIZE)
args->count = PAGE_SIZE;
args->buffer = page_address(rqstp->rq_respages[rqstp->rq_resused++]);
return xdr_argsize_check(rqstp, p);
}
/*
* XDR encode functions
*/
int
nfssvc_encode_void(struct svc_rqst *rqstp, __be32 *p, void *dummy)
{
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_attrstat(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_attrstat *resp)
{
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_diropres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_diropres *resp)
{
p = encode_fh(p, &resp->fh);
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_readlinkres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readlinkres *resp)
{
*p++ = htonl(resp->len);
xdr_ressize_check(rqstp, p);
rqstp->rq_res.page_len = resp->len;
if (resp->len & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->len&3);
}
return 1;
}
int
nfssvc_encode_readres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readres *resp)
{
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
*p++ = htonl(resp->count);
xdr_ressize_check(rqstp, p);
/* now update rqstp->rq_res to reflect data as well */
rqstp->rq_res.page_len = resp->count;
if (resp->count & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->count&3);
}
return 1;
}
int
nfssvc_encode_readdirres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readdirres *resp)
{
xdr_ressize_check(rqstp, p);
p = resp->buffer;
*p++ = 0; /* no more entries */
*p++ = htonl((resp->common.err == nfserr_eof));
rqstp->rq_res.page_len = (((unsigned long)p-1) & ~PAGE_MASK)+1;
return 1;
}
int
nfssvc_encode_statfsres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_statfsres *resp)
{
struct kstatfs *stat = &resp->stats;
*p++ = htonl(NFSSVC_MAXBLKSIZE_V2); /* max transfer size */
*p++ = htonl(stat->f_bsize);
*p++ = htonl(stat->f_blocks);
*p++ = htonl(stat->f_bfree);
*p++ = htonl(stat->f_bavail);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_entry(void *ccdv, const char *name,
int namlen, loff_t offset, u64 ino, unsigned int d_type)
{
struct readdir_cd *ccd = ccdv;
struct nfsd_readdirres *cd = container_of(ccd, struct nfsd_readdirres, common);
__be32 *p = cd->buffer;
int buflen, slen;
/*
dprintk("nfsd: entry(%.*s off %ld ino %ld)\n",
namlen, name, offset, ino);
*/
if (offset > ~((u32) 0)) {
cd->common.err = nfserr_fbig;
return -EINVAL;
}
if (cd->offset)
*cd->offset = htonl(offset);
if (namlen > NFS2_MAXNAMLEN)
namlen = NFS2_MAXNAMLEN;/* truncate filename */
slen = XDR_QUADLEN(namlen);
if ((buflen = cd->buflen - slen - 4) < 0) {
cd->common.err = nfserr_toosmall;
return -EINVAL;
}
if (ino > ~((u32) 0)) {
cd->common.err = nfserr_fbig;
return -EINVAL;
}
*p++ = xdr_one; /* mark entry present */
*p++ = htonl((u32) ino); /* file id */
p = xdr_encode_array(p, name, namlen);/* name length & name */
cd->offset = p; /* remember pointer */
*p++ = htonl(~0U); /* offset of next entry */
cd->buflen = buflen;
cd->buffer = p;
cd->common.err = nfs_ok;
return 0;
}
/*
* XDR release functions
*/
int
nfssvc_release_fhandle(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_fhandle *resp)
{
fh_put(&resp->fh);
return 1;
}
| gpl-2.0 |
DZB-Team/android_kernel_samsung_amazing | fs/ubifs/compress.c | 9952 | 6772 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation.
* Copyright (C) 2006, 2007 University of Szeged, Hungary
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Adrian Hunter
* Artem Bityutskiy (Битюцкий Артём)
* Zoltan Sogor
*/
/*
* This file provides a single place to access to compression and
* decompression.
*/
#include <linux/crypto.h>
#include "ubifs.h"
/* Fake description object for the "none" compressor */
static struct ubifs_compressor none_compr = {
.compr_type = UBIFS_COMPR_NONE,
.name = "none",
.capi_name = "",
};
#ifdef CONFIG_UBIFS_FS_LZO
static DEFINE_MUTEX(lzo_mutex);
static struct ubifs_compressor lzo_compr = {
.compr_type = UBIFS_COMPR_LZO,
.comp_mutex = &lzo_mutex,
.name = "lzo",
.capi_name = "lzo",
};
#else
static struct ubifs_compressor lzo_compr = {
.compr_type = UBIFS_COMPR_LZO,
.name = "lzo",
};
#endif
#ifdef CONFIG_UBIFS_FS_ZLIB
static DEFINE_MUTEX(deflate_mutex);
static DEFINE_MUTEX(inflate_mutex);
static struct ubifs_compressor zlib_compr = {
.compr_type = UBIFS_COMPR_ZLIB,
.comp_mutex = &deflate_mutex,
.decomp_mutex = &inflate_mutex,
.name = "zlib",
.capi_name = "deflate",
};
#else
static struct ubifs_compressor zlib_compr = {
.compr_type = UBIFS_COMPR_ZLIB,
.name = "zlib",
};
#endif
/* All UBIFS compressors */
struct ubifs_compressor *ubifs_compressors[UBIFS_COMPR_TYPES_CNT];
/**
* ubifs_compress - compress data.
* @in_buf: data to compress
* @in_len: length of the data to compress
* @out_buf: output buffer where compressed data should be stored
* @out_len: output buffer length is returned here
* @compr_type: type of compression to use on enter, actually used compression
* type on exit
*
* This function compresses input buffer @in_buf of length @in_len and stores
* the result in the output buffer @out_buf and the resulting length in
* @out_len. If the input buffer does not compress, it is just copied to the
* @out_buf. The same happens if @compr_type is %UBIFS_COMPR_NONE or if
* compression error occurred.
*
* Note, if the input buffer was not compressed, it is copied to the output
* buffer and %UBIFS_COMPR_NONE is returned in @compr_type.
*/
void ubifs_compress(const void *in_buf, int in_len, void *out_buf, int *out_len,
int *compr_type)
{
int err;
struct ubifs_compressor *compr = ubifs_compressors[*compr_type];
if (*compr_type == UBIFS_COMPR_NONE)
goto no_compr;
/* If the input data is small, do not even try to compress it */
if (in_len < UBIFS_MIN_COMPR_LEN)
goto no_compr;
if (compr->comp_mutex)
mutex_lock(compr->comp_mutex);
err = crypto_comp_compress(compr->cc, in_buf, in_len, out_buf,
(unsigned int *)out_len);
if (compr->comp_mutex)
mutex_unlock(compr->comp_mutex);
if (unlikely(err)) {
ubifs_warn("cannot compress %d bytes, compressor %s, "
"error %d, leave data uncompressed",
in_len, compr->name, err);
goto no_compr;
}
/*
* If the data compressed only slightly, it is better to leave it
* uncompressed to improve read speed.
*/
if (in_len - *out_len < UBIFS_MIN_COMPRESS_DIFF)
goto no_compr;
return;
no_compr:
memcpy(out_buf, in_buf, in_len);
*out_len = in_len;
*compr_type = UBIFS_COMPR_NONE;
}
/**
* ubifs_decompress - decompress data.
* @in_buf: data to decompress
* @in_len: length of the data to decompress
* @out_buf: output buffer where decompressed data should
* @out_len: output length is returned here
* @compr_type: type of compression
*
* This function decompresses data from buffer @in_buf into buffer @out_buf.
* The length of the uncompressed data is returned in @out_len. This functions
* returns %0 on success or a negative error code on failure.
*/
int ubifs_decompress(const void *in_buf, int in_len, void *out_buf,
int *out_len, int compr_type)
{
int err;
struct ubifs_compressor *compr;
if (unlikely(compr_type < 0 || compr_type >= UBIFS_COMPR_TYPES_CNT)) {
ubifs_err("invalid compression type %d", compr_type);
return -EINVAL;
}
compr = ubifs_compressors[compr_type];
if (unlikely(!compr->capi_name)) {
ubifs_err("%s compression is not compiled in", compr->name);
return -EINVAL;
}
if (compr_type == UBIFS_COMPR_NONE) {
memcpy(out_buf, in_buf, in_len);
*out_len = in_len;
return 0;
}
if (compr->decomp_mutex)
mutex_lock(compr->decomp_mutex);
err = crypto_comp_decompress(compr->cc, in_buf, in_len, out_buf,
(unsigned int *)out_len);
if (compr->decomp_mutex)
mutex_unlock(compr->decomp_mutex);
if (err)
ubifs_err("cannot decompress %d bytes, compressor %s, "
"error %d", in_len, compr->name, err);
return err;
}
/**
* compr_init - initialize a compressor.
* @compr: compressor description object
*
* This function initializes the requested compressor and returns zero in case
* of success or a negative error code in case of failure.
*/
static int __init compr_init(struct ubifs_compressor *compr)
{
if (compr->capi_name) {
compr->cc = crypto_alloc_comp(compr->capi_name, 0, 0);
if (IS_ERR(compr->cc)) {
ubifs_err("cannot initialize compressor %s, error %ld",
compr->name, PTR_ERR(compr->cc));
return PTR_ERR(compr->cc);
}
}
ubifs_compressors[compr->compr_type] = compr;
return 0;
}
/**
* compr_exit - de-initialize a compressor.
* @compr: compressor description object
*/
static void compr_exit(struct ubifs_compressor *compr)
{
if (compr->capi_name)
crypto_free_comp(compr->cc);
return;
}
/**
* ubifs_compressors_init - initialize UBIFS compressors.
*
* This function initializes the compressor which were compiled in. Returns
* zero in case of success and a negative error code in case of failure.
*/
int __init ubifs_compressors_init(void)
{
int err;
err = compr_init(&lzo_compr);
if (err)
return err;
err = compr_init(&zlib_compr);
if (err)
goto out_lzo;
ubifs_compressors[UBIFS_COMPR_NONE] = &none_compr;
return 0;
out_lzo:
compr_exit(&lzo_compr);
return err;
}
/**
* ubifs_compressors_exit - de-initialize UBIFS compressors.
*/
void ubifs_compressors_exit(void)
{
compr_exit(&lzo_compr);
compr_exit(&zlib_compr);
}
| gpl-2.0 |
bheu/odroid_linux | net/sched/em_u32.c | 13024 | 1470 | /*
* net/sched/em_u32.c U32 Ematch
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Thomas Graf <tgraf@suug.ch>
* Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
* Based on net/sched/cls_u32.c
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <net/pkt_cls.h>
static int em_u32_match(struct sk_buff *skb, struct tcf_ematch *em,
struct tcf_pkt_info *info)
{
struct tc_u32_key *key = (struct tc_u32_key *) em->data;
const unsigned char *ptr = skb_network_header(skb);
if (info) {
if (info->ptr)
ptr = info->ptr;
ptr += (info->nexthdr & key->offmask);
}
ptr += key->off;
if (!tcf_valid_offset(skb, ptr, sizeof(u32)))
return 0;
return !(((*(__be32 *) ptr) ^ key->val) & key->mask);
}
static struct tcf_ematch_ops em_u32_ops = {
.kind = TCF_EM_U32,
.datalen = sizeof(struct tc_u32_key),
.match = em_u32_match,
.owner = THIS_MODULE,
.link = LIST_HEAD_INIT(em_u32_ops.link)
};
static int __init init_em_u32(void)
{
return tcf_em_register(&em_u32_ops);
}
static void __exit exit_em_u32(void)
{
tcf_em_unregister(&em_u32_ops);
}
MODULE_LICENSE("GPL");
module_init(init_em_u32);
module_exit(exit_em_u32);
MODULE_ALIAS_TCF_EMATCH(TCF_EM_U32);
| gpl-2.0 |
wanahmadzainie/linux-mainline | sound/soc/pxa/corgi.c | 225 | 8702 | /*
* corgi.c -- SoC audio for Corgi
*
* Copyright 2005 Wolfson Microelectronics PLC.
* Copyright 2005 Openedhand Ltd.
*
* Authors: Liam Girdwood <lrg@slimlogic.co.uk>
* Richard Purdie <richard@openedhand.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/timer.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include <mach/corgi.h>
#include <mach/audio.h>
#include "../codecs/wm8731.h"
#include "pxa2xx-i2s.h"
#define CORGI_HP 0
#define CORGI_MIC 1
#define CORGI_LINE 2
#define CORGI_HEADSET 3
#define CORGI_HP_OFF 4
#define CORGI_SPK_ON 0
#define CORGI_SPK_OFF 1
/* audio clock in Hz - rounded from 12.235MHz */
#define CORGI_AUDIO_CLOCK 12288000
static int corgi_jack_func;
static int corgi_spk_func;
static void corgi_ext_control(struct snd_soc_dapm_context *dapm)
{
snd_soc_dapm_mutex_lock(dapm);
/* set up jack connection */
switch (corgi_jack_func) {
case CORGI_HP:
/* set = unmute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 1);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
snd_soc_dapm_disable_pin_unlocked(dapm, "Mic Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Line Jack");
snd_soc_dapm_enable_pin_unlocked(dapm, "Headphone Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headset Jack");
break;
case CORGI_MIC:
/* reset = mute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 0);
snd_soc_dapm_enable_pin_unlocked(dapm, "Mic Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Line Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headphone Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headset Jack");
break;
case CORGI_LINE:
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 0);
snd_soc_dapm_disable_pin_unlocked(dapm, "Mic Jack");
snd_soc_dapm_enable_pin_unlocked(dapm, "Line Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headphone Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headset Jack");
break;
case CORGI_HEADSET:
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
snd_soc_dapm_enable_pin_unlocked(dapm, "Mic Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Line Jack");
snd_soc_dapm_disable_pin_unlocked(dapm, "Headphone Jack");
snd_soc_dapm_enable_pin_unlocked(dapm, "Headset Jack");
break;
}
if (corgi_spk_func == CORGI_SPK_ON)
snd_soc_dapm_enable_pin_unlocked(dapm, "Ext Spk");
else
snd_soc_dapm_disable_pin_unlocked(dapm, "Ext Spk");
/* signal a DAPM event */
snd_soc_dapm_sync_unlocked(dapm);
snd_soc_dapm_mutex_unlock(dapm);
}
static int corgi_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
/* check the jack status at stream startup */
corgi_ext_control(&rtd->card->dapm);
return 0;
}
/* we need to unmute the HP at shutdown as the mute burns power on corgi */
static void corgi_shutdown(struct snd_pcm_substream *substream)
{
/* set = unmute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 1);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
}
static int corgi_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 = 0;
switch (params_rate(params)) {
case 8000:
case 16000:
case 48000:
case 96000:
clk = 12288000;
break;
case 11025:
case 22050:
case 44100:
clk = 11289600;
break;
}
/* set the codec system clock for DAC and ADC */
ret = snd_soc_dai_set_sysclk(codec_dai, WM8731_SYSCLK_XTAL, 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, 0,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops corgi_ops = {
.startup = corgi_startup,
.hw_params = corgi_hw_params,
.shutdown = corgi_shutdown,
};
static int corgi_get_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.enumerated.item[0] = corgi_jack_func;
return 0;
}
static int corgi_set_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_card *card = snd_kcontrol_chip(kcontrol);
if (corgi_jack_func == ucontrol->value.enumerated.item[0])
return 0;
corgi_jack_func = ucontrol->value.enumerated.item[0];
corgi_ext_control(&card->dapm);
return 1;
}
static int corgi_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.enumerated.item[0] = corgi_spk_func;
return 0;
}
static int corgi_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_card *card = snd_kcontrol_chip(kcontrol);
if (corgi_spk_func == ucontrol->value.enumerated.item[0])
return 0;
corgi_spk_func = ucontrol->value.enumerated.item[0];
corgi_ext_control(&card->dapm);
return 1;
}
static int corgi_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
gpio_set_value(CORGI_GPIO_APM_ON, SND_SOC_DAPM_EVENT_ON(event));
return 0;
}
static int corgi_mic_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
gpio_set_value(CORGI_GPIO_MIC_BIAS, SND_SOC_DAPM_EVENT_ON(event));
return 0;
}
/* corgi machine dapm widgets */
static const struct snd_soc_dapm_widget wm8731_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_MIC("Mic Jack", corgi_mic_event),
SND_SOC_DAPM_SPK("Ext Spk", corgi_amp_event),
SND_SOC_DAPM_LINE("Line Jack", NULL),
SND_SOC_DAPM_HP("Headset Jack", NULL),
};
/* Corgi machine audio map (connections to the codec pins) */
static const struct snd_soc_dapm_route corgi_audio_map[] = {
/* headset Jack - in = micin, out = LHPOUT*/
{"Headset Jack", NULL, "LHPOUT"},
/* headphone connected to LHPOUT1, RHPOUT1 */
{"Headphone Jack", NULL, "LHPOUT"},
{"Headphone Jack", NULL, "RHPOUT"},
/* speaker connected to LOUT, ROUT */
{"Ext Spk", NULL, "ROUT"},
{"Ext Spk", NULL, "LOUT"},
/* mic is connected to MICIN (via right channel of headphone jack) */
{"MICIN", NULL, "Mic Jack"},
/* Same as the above but no mic bias for line signals */
{"MICIN", NULL, "Line Jack"},
};
static const char *jack_function[] = {"Headphone", "Mic", "Line", "Headset",
"Off"};
static const char *spk_function[] = {"On", "Off"};
static const struct soc_enum corgi_enum[] = {
SOC_ENUM_SINGLE_EXT(5, jack_function),
SOC_ENUM_SINGLE_EXT(2, spk_function),
};
static const struct snd_kcontrol_new wm8731_corgi_controls[] = {
SOC_ENUM_EXT("Jack Function", corgi_enum[0], corgi_get_jack,
corgi_set_jack),
SOC_ENUM_EXT("Speaker Function", corgi_enum[1], corgi_get_spk,
corgi_set_spk),
};
/* corgi digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link corgi_dai = {
.name = "WM8731",
.stream_name = "WM8731",
.cpu_dai_name = "pxa2xx-i2s",
.codec_dai_name = "wm8731-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm8731.0-001b",
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBS_CFS,
.ops = &corgi_ops,
};
/* corgi audio machine driver */
static struct snd_soc_card corgi = {
.name = "Corgi",
.owner = THIS_MODULE,
.dai_link = &corgi_dai,
.num_links = 1,
.controls = wm8731_corgi_controls,
.num_controls = ARRAY_SIZE(wm8731_corgi_controls),
.dapm_widgets = wm8731_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8731_dapm_widgets),
.dapm_routes = corgi_audio_map,
.num_dapm_routes = ARRAY_SIZE(corgi_audio_map),
.fully_routed = true,
};
static int corgi_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &corgi;
int ret;
card->dev = &pdev->dev;
ret = devm_snd_soc_register_card(&pdev->dev, card);
if (ret)
dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n",
ret);
return ret;
}
static struct platform_driver corgi_driver = {
.driver = {
.name = "corgi-audio",
.pm = &snd_soc_pm_ops,
},
.probe = corgi_probe,
};
module_platform_driver(corgi_driver);
/* Module information */
MODULE_AUTHOR("Richard Purdie");
MODULE_DESCRIPTION("ALSA SoC Corgi");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:corgi-audio");
| gpl-2.0 |
jameskdev/lge-kernel-batman_skt | arch/arm/mach-msm/dal_axi.c | 481 | 2642 | /* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <mach/dal_axi.h>
/* The AXI device ID */
#define DALDEVICEID_AXI 0x02000053
#define DALRPC_PORT_NAME "DAL00"
enum {
DALRPC_AXI_CONFIGURE_BRIDGE = DALDEVICE_FIRST_DEVICE_API_IDX + 11
};
enum {
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_SYNC_MODE = 14,
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_ASYNC_MODE,
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_ISOSYNC_MODE,
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_DEBUG_EN,
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_DEBUG_DIS,
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_SYNC_MODE,
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_ASYNC_MODE,
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_ISOSYNC_MODE,
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_DEBUG_EN,
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_DEBUG_DIS,
/* 7x27(A) Graphics Subsystem Bridge Configuration */
DAL_AXI_BRIDGE_CFG_GRPSS_XBAR_SYNC_MODE = 58,
DAL_AXI_BRIDGE_CFG_GRPSS_XBAR_ASYNC_MODE = 59,
DAL_AXI_BRIDGE_CFG_GRPSS_XBAR_ISOSYNC_MODE = 60
};
static int axi_configure_bridge_grfx_sync_mode(int bridge_mode)
{
int rc;
void *dev_handle;
/* get device handle */
rc = daldevice_attach(
DALDEVICEID_AXI, DALRPC_PORT_NAME,
DALRPC_DEST_MODEM, &dev_handle
);
if (rc) {
printk(KERN_ERR "%s: failed to attach AXI bus device (%d)\n",
__func__, rc);
goto fail_dal_attach_detach;
}
/* call ConfigureBridge */
rc = dalrpc_fcn_0(
DALRPC_AXI_CONFIGURE_BRIDGE, dev_handle,
bridge_mode
);
if (rc) {
printk(KERN_ERR "%s: AXI bus device (%d) failed to be configured\n",
__func__, rc);
goto fail_dal_fcn_0;
}
/* close device handle */
rc = daldevice_detach(dev_handle);
if (rc) {
printk(KERN_ERR "%s: failed to detach AXI bus device (%d)\n",
__func__, rc);
goto fail_dal_attach_detach;
}
return 0;
fail_dal_fcn_0:
(void)daldevice_detach(dev_handle);
fail_dal_attach_detach:
return rc;
}
int set_grp2d_async(void)
{
return axi_configure_bridge_grfx_sync_mode(
DAL_AXI_BRIDGE_CFG_CGR_SS_2DGRP_ASYNC_MODE);
}
int set_grp3d_async(void)
{
return axi_configure_bridge_grfx_sync_mode(
DAL_AXI_BRIDGE_CFG_CGR_SS_3DGRP_ASYNC_MODE);
}
int set_grp_xbar_async(void)
{ return axi_configure_bridge_grfx_sync_mode(
DAL_AXI_BRIDGE_CFG_GRPSS_XBAR_ASYNC_MODE);
}
| gpl-2.0 |
huwan/linux-buffer-debug | arch/arm/mach-s3c2410/mach-qt2410.c | 481 | 8208 | /* linux/arch/arm/mach-s3c2410/mach-qt2410.c
*
* Copyright (C) 2006 by OpenMoko, Inc.
* Author: Harald Welte <laforge@openmoko.org>
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*/
#include <linux/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/sysdev.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
#include <linux/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/regs-gpio.h>
#include <mach/leds-gpio.h>
#include <plat/regs-serial.h>
#include <mach/fb.h>
#include <plat/nand.h>
#include <plat/udc.h>
#include <mach/spi.h>
#include <mach/spi-gpio.h>
#include <plat/iic.h>
#include <plat/common-smdk.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/pm.h>
static struct map_desc qt2410_iodesc[] __initdata = {
{ 0xe0000000, __phys_to_pfn(S3C2410_CS3+0x01000000), SZ_1M, MT_DEVICE }
};
#define UCON S3C2410_UCON_DEFAULT
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg smdk2410_uartcfgs[] = {
[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,
}
};
/* LCD driver info */
static struct s3c2410fb_display qt2410_lcd_cfg[] __initdata = {
{
/* Configuration for 640x480 SHARP LQ080V3DG01 */
.lcdcon5 = S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_PWREN |
S3C2410_LCDCON5_HWSWP,
.type = S3C2410_LCDCON1_TFT,
.width = 640,
.height = 480,
.pixclock = 40000, /* HCLK/4 */
.xres = 640,
.yres = 480,
.bpp = 16,
.left_margin = 44,
.right_margin = 116,
.hsync_len = 96,
.upper_margin = 19,
.lower_margin = 11,
.vsync_len = 15,
},
{
/* Configuration for 480x640 toppoly TD028TTEC1 */
.lcdcon5 = S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_PWREN |
S3C2410_LCDCON5_HWSWP,
.type = S3C2410_LCDCON1_TFT,
.width = 480,
.height = 640,
.pixclock = 40000, /* HCLK/4 */
.xres = 480,
.yres = 640,
.bpp = 16,
.left_margin = 8,
.right_margin = 24,
.hsync_len = 8,
.upper_margin = 2,
.lower_margin = 4,
.vsync_len = 2,
},
{
/* Config for 240x320 LCD */
.lcdcon5 = S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_PWREN |
S3C2410_LCDCON5_HWSWP,
.type = S3C2410_LCDCON1_TFT,
.width = 240,
.height = 320,
.pixclock = 100000, /* HCLK/10 */
.xres = 240,
.yres = 320,
.bpp = 16,
.left_margin = 13,
.right_margin = 8,
.hsync_len = 4,
.upper_margin = 2,
.lower_margin = 7,
.vsync_len = 4,
},
};
static struct s3c2410fb_mach_info qt2410_fb_info __initdata = {
.displays = qt2410_lcd_cfg,
.num_displays = ARRAY_SIZE(qt2410_lcd_cfg),
.default_display = 0,
.lpcsel = ((0xCE6) & ~7) | 1<<4,
};
/* CS8900 */
static struct resource qt2410_cs89x0_resources[] = {
[0] = {
.start = 0x19000000,
.end = 0x19000000 + 16,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_EINT9,
.end = IRQ_EINT9,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device qt2410_cs89x0 = {
.name = "cirrus-cs89x0",
.num_resources = ARRAY_SIZE(qt2410_cs89x0_resources),
.resource = qt2410_cs89x0_resources,
};
/* LED */
static struct s3c24xx_led_platdata qt2410_pdata_led = {
.gpio = S3C2410_GPB(0),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.name = "led",
.def_trigger = "timer",
};
static struct platform_device qt2410_led = {
.name = "s3c24xx_led",
.id = 0,
.dev = {
.platform_data = &qt2410_pdata_led,
},
};
/* SPI */
static void spi_gpio_cs(struct s3c2410_spigpio_info *spi, int cs)
{
switch (cs) {
case BITBANG_CS_ACTIVE:
s3c2410_gpio_setpin(S3C2410_GPB(5), 0);
break;
case BITBANG_CS_INACTIVE:
s3c2410_gpio_setpin(S3C2410_GPB(5), 1);
break;
}
}
static struct s3c2410_spigpio_info spi_gpio_cfg = {
.pin_clk = S3C2410_GPG(7),
.pin_mosi = S3C2410_GPG(6),
.pin_miso = S3C2410_GPG(5),
.chip_select = &spi_gpio_cs,
};
static struct platform_device qt2410_spi = {
.name = "s3c24xx-spi-gpio",
.id = 1,
.dev = {
.platform_data = &spi_gpio_cfg,
},
};
/* Board devices */
static struct platform_device *qt2410_devices[] __initdata = {
&s3c_device_usb,
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_iis,
&s3c_device_sdi,
&s3c_device_usbgadget,
&qt2410_spi,
&qt2410_cs89x0,
&qt2410_led,
};
static struct mtd_partition qt2410_nand_part[] = {
[0] = {
.name = "U-Boot",
.size = 0x30000,
.offset = 0,
},
[1] = {
.name = "U-Boot environment",
.offset = 0x30000,
.size = 0x4000,
},
[2] = {
.name = "kernel",
.offset = 0x34000,
.size = SZ_2M,
},
[3] = {
.name = "initrd",
.offset = 0x234000,
.size = SZ_4M,
},
[4] = {
.name = "jffs2",
.offset = 0x634000,
.size = 0x39cc000,
},
};
static struct s3c2410_nand_set qt2410_nand_sets[] = {
[0] = {
.name = "NAND",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(qt2410_nand_part),
.partitions = qt2410_nand_part,
},
};
/* choose a set of timings which should suit most 512Mbit
* chips and beyond.
*/
static struct s3c2410_platform_nand qt2410_nand_info = {
.tacls = 20,
.twrph0 = 60,
.twrph1 = 20,
.nr_sets = ARRAY_SIZE(qt2410_nand_sets),
.sets = qt2410_nand_sets,
};
/* UDC */
static struct s3c2410_udc_mach_info qt2410_udc_cfg = {
};
static char tft_type = 's';
static int __init qt2410_tft_setup(char *str)
{
tft_type = str[0];
return 1;
}
__setup("tft=", qt2410_tft_setup);
static void __init qt2410_map_io(void)
{
s3c24xx_init_io(qt2410_iodesc, ARRAY_SIZE(qt2410_iodesc));
s3c24xx_init_clocks(12*1000*1000);
s3c24xx_init_uarts(smdk2410_uartcfgs, ARRAY_SIZE(smdk2410_uartcfgs));
}
static void __init qt2410_machine_init(void)
{
s3c_device_nand.dev.platform_data = &qt2410_nand_info;
switch (tft_type) {
case 'p': /* production */
qt2410_fb_info.default_display = 1;
break;
case 'b': /* big */
qt2410_fb_info.default_display = 0;
break;
case 's': /* small */
default:
qt2410_fb_info.default_display = 2;
break;
}
s3c24xx_fb_set_platdata(&qt2410_fb_info);
s3c2410_gpio_cfgpin(S3C2410_GPB(0), S3C2410_GPIO_OUTPUT);
s3c2410_gpio_setpin(S3C2410_GPB(0), 1);
s3c24xx_udc_set_platdata(&qt2410_udc_cfg);
s3c_i2c0_set_platdata(NULL);
s3c2410_gpio_cfgpin(S3C2410_GPB(5), S3C2410_GPIO_OUTPUT);
platform_add_devices(qt2410_devices, ARRAY_SIZE(qt2410_devices));
s3c_pm_init();
}
MACHINE_START(QT2410, "QT2410")
.phys_io = S3C2410_PA_UART,
.io_pg_offst = (((u32)S3C24XX_VA_UART) >> 18) & 0xfffc,
.boot_params = S3C2410_SDRAM_PA + 0x100,
.map_io = qt2410_map_io,
.init_irq = s3c24xx_init_irq,
.init_machine = qt2410_machine_init,
.timer = &s3c24xx_timer,
MACHINE_END
| gpl-2.0 |
hackerspace/rpi-linux | arch/arm64/kernel/perf_regs.c | 1249 | 1261 | #include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/perf_event.h>
#include <linux/bug.h>
#include <asm/compat.h>
#include <asm/perf_regs.h>
#include <asm/ptrace.h>
u64 perf_reg_value(struct pt_regs *regs, int idx)
{
if (WARN_ON_ONCE((u32)idx >= PERF_REG_ARM64_MAX))
return 0;
/*
* Compat (i.e. 32 bit) mode:
* - PC has been set in the pt_regs struct in kernel_entry,
* - Handle SP and LR here.
*/
if (compat_user_mode(regs)) {
if ((u32)idx == PERF_REG_ARM64_SP)
return regs->compat_sp;
if ((u32)idx == PERF_REG_ARM64_LR)
return regs->compat_lr;
}
if ((u32)idx == PERF_REG_ARM64_SP)
return regs->sp;
if ((u32)idx == PERF_REG_ARM64_PC)
return regs->pc;
return regs->regs[idx];
}
#define REG_RESERVED (~((1ULL << PERF_REG_ARM64_MAX) - 1))
int perf_reg_validate(u64 mask)
{
if (!mask || mask & REG_RESERVED)
return -EINVAL;
return 0;
}
u64 perf_reg_abi(struct task_struct *task)
{
if (is_compat_thread(task_thread_info(task)))
return PERF_SAMPLE_REGS_ABI_32;
else
return PERF_SAMPLE_REGS_ABI_64;
}
void perf_get_regs_user(struct perf_regs *regs_user,
struct pt_regs *regs,
struct pt_regs *regs_user_copy)
{
regs_user->regs = task_pt_regs(current);
regs_user->abi = perf_reg_abi(current);
}
| gpl-2.0 |
ExPeacer/CAF_android-msm-3.0 | drivers/media/radio/radio-mr800.c | 2529 | 18329 | /*
* A driver for the AverMedia MR 800 USB FM radio. This device plugs
* into both the USB and an analog audio input, so this thing
* only deals with initialization and frequency setting, the
* audio data has to be handled by a sound driver.
*
* Copyright (c) 2008 Alexey Klimov <klimov.linux@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Big thanks to authors and contributors of dsbr100.c and radio-si470x.c
*
* When work was looked pretty good, i discover this:
* http://av-usbradio.sourceforge.net/index.php
* http://sourceforge.net/projects/av-usbradio/
* Latest release of theirs project was in 2005.
* Probably, this driver could be improved through using their
* achievements (specifications given).
* Also, Faidon Liambotis <paravoid@debian.org> wrote nice driver for this radio
* in 2007. He allowed to use his driver to improve current mr800 radio driver.
* http://kerneltrap.org/mailarchive/linux-usb-devel/2007/10/11/342492
*
* Version 0.01: First working version.
* It's required to blacklist AverMedia USB Radio
* in usbhid/hid-quirks.c
* Version 0.10: A lot of cleanups and fixes: unpluging the device,
* few mutex locks were added, codinstyle issues, etc.
* Added stereo support. Thanks to
* Douglas Schilling Landgraf <dougsland@gmail.com> and
* David Ellingsworth <david@identd.dyndns.org>
* for discussion, help and support.
* Version 0.11: Converted to v4l2_device.
*
* Many things to do:
* - Correct power management of device (suspend & resume)
* - Add code for scanning and smooth tuning
* - Add code for sensitivity value
* - Correct mistakes
* - In Japan another FREQ_MIN and FREQ_MAX
*/
/* kernel includes */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <linux/usb.h>
#include <linux/version.h> /* for KERNEL_VERSION MACRO */
#include <linux/mutex.h>
/* driver and module definitions */
#define DRIVER_AUTHOR "Alexey Klimov <klimov.linux@gmail.com>"
#define DRIVER_DESC "AverMedia MR 800 USB FM radio driver"
#define DRIVER_VERSION "0.11"
#define RADIO_VERSION KERNEL_VERSION(0, 1, 1)
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define USB_AMRADIO_VENDOR 0x07ca
#define USB_AMRADIO_PRODUCT 0xb800
/* dev_warn macro with driver name */
#define MR800_DRIVER_NAME "radio-mr800"
#define amradio_dev_warn(dev, fmt, arg...) \
dev_warn(dev, MR800_DRIVER_NAME " - " fmt, ##arg)
#define amradio_dev_err(dev, fmt, arg...) \
dev_err(dev, MR800_DRIVER_NAME " - " fmt, ##arg)
/* Probably USB_TIMEOUT should be modified in module parameter */
#define BUFFER_LENGTH 8
#define USB_TIMEOUT 500
/* Frequency limits in MHz -- these are European values. For Japanese
devices, that would be 76 and 91. */
#define FREQ_MIN 87.5
#define FREQ_MAX 108.0
#define FREQ_MUL 16000
/*
* Commands that device should understand
* List isn't full and will be updated with implementation of new functions
*/
#define AMRADIO_SET_FREQ 0xa4
#define AMRADIO_SET_MUTE 0xab
#define AMRADIO_SET_MONO 0xae
/* Comfortable defines for amradio_set_mute */
#define AMRADIO_START 0x00
#define AMRADIO_STOP 0x01
/* Comfortable defines for amradio_set_stereo */
#define WANT_STEREO 0x00
#define WANT_MONO 0x01
/* module parameter */
static int radio_nr = -1;
module_param(radio_nr, int, 0);
MODULE_PARM_DESC(radio_nr, "Radio Nr");
static int usb_amradio_probe(struct usb_interface *intf,
const struct usb_device_id *id);
static void usb_amradio_disconnect(struct usb_interface *intf);
static int usb_amradio_open(struct file *file);
static int usb_amradio_close(struct file *file);
static int usb_amradio_suspend(struct usb_interface *intf,
pm_message_t message);
static int usb_amradio_resume(struct usb_interface *intf);
/* Data for one (physical) device */
struct amradio_device {
/* reference to USB and video device */
struct usb_device *usbdev;
struct usb_interface *intf;
struct video_device videodev;
struct v4l2_device v4l2_dev;
unsigned char *buffer;
struct mutex lock; /* buffer locking */
int curfreq;
int stereo;
int muted;
int initialized;
};
static inline struct amradio_device *to_amradio_dev(struct v4l2_device *v4l2_dev)
{
return container_of(v4l2_dev, struct amradio_device, v4l2_dev);
}
/* USB Device ID List */
static struct usb_device_id usb_amradio_device_table[] = {
{USB_DEVICE_AND_INTERFACE_INFO(USB_AMRADIO_VENDOR, USB_AMRADIO_PRODUCT,
USB_CLASS_HID, 0, 0) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_amradio_device_table);
/* USB subsystem interface */
static struct usb_driver usb_amradio_driver = {
.name = MR800_DRIVER_NAME,
.probe = usb_amradio_probe,
.disconnect = usb_amradio_disconnect,
.suspend = usb_amradio_suspend,
.resume = usb_amradio_resume,
.reset_resume = usb_amradio_resume,
.id_table = usb_amradio_device_table,
.supports_autosuspend = 1,
};
/* switch on/off the radio. Send 8 bytes to device */
static int amradio_set_mute(struct amradio_device *radio, char argument)
{
int retval;
int size;
radio->buffer[0] = 0x00;
radio->buffer[1] = 0x55;
radio->buffer[2] = 0xaa;
radio->buffer[3] = 0x00;
radio->buffer[4] = AMRADIO_SET_MUTE;
radio->buffer[5] = argument;
radio->buffer[6] = 0x00;
radio->buffer[7] = 0x00;
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
(void *) (radio->buffer), BUFFER_LENGTH, &size, USB_TIMEOUT);
if (retval < 0 || size != BUFFER_LENGTH) {
amradio_dev_warn(&radio->videodev.dev, "set mute failed\n");
return retval;
}
radio->muted = argument;
return retval;
}
/* set a frequency, freq is defined by v4l's TUNER_LOW, i.e. 1/16th kHz */
static int amradio_setfreq(struct amradio_device *radio, int freq)
{
int retval;
int size;
unsigned short freq_send = 0x10 + (freq >> 3) / 25;
radio->buffer[0] = 0x00;
radio->buffer[1] = 0x55;
radio->buffer[2] = 0xaa;
radio->buffer[3] = 0x03;
radio->buffer[4] = AMRADIO_SET_FREQ;
radio->buffer[5] = 0x00;
radio->buffer[6] = 0x00;
radio->buffer[7] = 0x08;
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
(void *) (radio->buffer), BUFFER_LENGTH, &size, USB_TIMEOUT);
if (retval < 0 || size != BUFFER_LENGTH)
goto out_err;
/* frequency is calculated from freq_send and placed in first 2 bytes */
radio->buffer[0] = (freq_send >> 8) & 0xff;
radio->buffer[1] = freq_send & 0xff;
radio->buffer[2] = 0x01;
radio->buffer[3] = 0x00;
radio->buffer[4] = 0x00;
/* 5 and 6 bytes of buffer already = 0x00 */
radio->buffer[7] = 0x00;
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
(void *) (radio->buffer), BUFFER_LENGTH, &size, USB_TIMEOUT);
if (retval < 0 || size != BUFFER_LENGTH)
goto out_err;
radio->curfreq = freq;
goto out;
out_err:
amradio_dev_warn(&radio->videodev.dev, "set frequency failed\n");
out:
return retval;
}
static int amradio_set_stereo(struct amradio_device *radio, char argument)
{
int retval;
int size;
radio->buffer[0] = 0x00;
radio->buffer[1] = 0x55;
radio->buffer[2] = 0xaa;
radio->buffer[3] = 0x00;
radio->buffer[4] = AMRADIO_SET_MONO;
radio->buffer[5] = argument;
radio->buffer[6] = 0x00;
radio->buffer[7] = 0x00;
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
(void *) (radio->buffer), BUFFER_LENGTH, &size, USB_TIMEOUT);
if (retval < 0 || size != BUFFER_LENGTH) {
amradio_dev_warn(&radio->videodev.dev, "set stereo failed\n");
return retval;
}
if (argument == WANT_STEREO)
radio->stereo = 1;
else
radio->stereo = 0;
return retval;
}
/* Handle unplugging the device.
* We call video_unregister_device in any case.
* The last function called in this procedure is
* usb_amradio_device_release.
*/
static void usb_amradio_disconnect(struct usb_interface *intf)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
/* increase the device node's refcount */
get_device(&radio->videodev.dev);
v4l2_device_disconnect(&radio->v4l2_dev);
video_unregister_device(&radio->videodev);
mutex_unlock(&radio->lock);
/* decrease the device node's refcount, allowing it to be released */
put_device(&radio->videodev.dev);
}
/* vidioc_querycap - query device capabilities */
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
struct amradio_device *radio = file->private_data;
strlcpy(v->driver, "radio-mr800", sizeof(v->driver));
strlcpy(v->card, "AverMedia MR 800 USB FM Radio", sizeof(v->card));
usb_make_path(radio->usbdev, v->bus_info, sizeof(v->bus_info));
v->version = RADIO_VERSION;
v->capabilities = V4L2_CAP_TUNER;
return 0;
}
/* vidioc_g_tuner - get tuner attributes */
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct amradio_device *radio = file->private_data;
int retval;
if (v->index > 0)
return -EINVAL;
/* TODO: Add function which look is signal stereo or not
* amradio_getstat(radio);
*/
/* we call amradio_set_stereo to set radio->stereo
* Honestly, amradio_getstat should cover this in future and
* amradio_set_stereo shouldn't be here
*/
retval = amradio_set_stereo(radio, WANT_STEREO);
strcpy(v->name, "FM");
v->type = V4L2_TUNER_RADIO;
v->rangelow = FREQ_MIN * FREQ_MUL;
v->rangehigh = FREQ_MAX * FREQ_MUL;
v->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_STEREO;
v->capability = V4L2_TUNER_CAP_LOW;
if (radio->stereo)
v->audmode = V4L2_TUNER_MODE_STEREO;
else
v->audmode = V4L2_TUNER_MODE_MONO;
v->signal = 0xffff; /* Can't get the signal strength, sad.. */
v->afc = 0; /* Don't know what is this */
return retval;
}
/* vidioc_s_tuner - set tuner attributes */
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct amradio_device *radio = file->private_data;
int retval = -EINVAL;
if (v->index > 0)
return -EINVAL;
/* mono/stereo selector */
switch (v->audmode) {
case V4L2_TUNER_MODE_MONO:
retval = amradio_set_stereo(radio, WANT_MONO);
break;
case V4L2_TUNER_MODE_STEREO:
retval = amradio_set_stereo(radio, WANT_STEREO);
break;
}
return retval;
}
/* vidioc_s_frequency - set tuner radio frequency */
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct amradio_device *radio = file->private_data;
if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO)
return -EINVAL;
return amradio_setfreq(radio, f->frequency);
}
/* vidioc_g_frequency - get tuner radio frequency */
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct amradio_device *radio = file->private_data;
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = radio->curfreq;
return 0;
}
/* vidioc_queryctrl - enumerate control items */
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 1);
}
return -EINVAL;
}
/* vidioc_g_ctrl - get the value of a control */
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct amradio_device *radio = file->private_data;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
ctrl->value = radio->muted;
return 0;
}
return -EINVAL;
}
/* vidioc_s_ctrl - set the value of a control */
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct amradio_device *radio = file->private_data;
int retval = -EINVAL;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (ctrl->value)
retval = amradio_set_mute(radio, AMRADIO_STOP);
else
retval = amradio_set_mute(radio, AMRADIO_START);
break;
}
return retval;
}
/* vidioc_g_audio - get audio attributes */
static int vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
if (a->index > 1)
return -EINVAL;
strcpy(a->name, "Radio");
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
/* vidioc_s_audio - set audio attributes */
static int vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
if (a->index != 0)
return -EINVAL;
return 0;
}
/* vidioc_g_input - get input */
static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
/* vidioc_s_input - set input */
static int vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
if (i != 0)
return -EINVAL;
return 0;
}
static int usb_amradio_init(struct amradio_device *radio)
{
int retval;
retval = amradio_set_mute(radio, AMRADIO_STOP);
if (retval)
goto out_err;
retval = amradio_set_stereo(radio, WANT_STEREO);
if (retval)
goto out_err;
radio->initialized = 1;
goto out;
out_err:
amradio_dev_err(&radio->videodev.dev, "initialization failed\n");
out:
return retval;
}
/* open device - amradio_start() and amradio_setfreq() */
static int usb_amradio_open(struct file *file)
{
struct amradio_device *radio = video_drvdata(file);
int retval;
file->private_data = radio;
retval = usb_autopm_get_interface(radio->intf);
if (retval)
return retval;
if (unlikely(!radio->initialized)) {
retval = usb_amradio_init(radio);
if (retval)
usb_autopm_put_interface(radio->intf);
}
return retval;
}
/*close device */
static int usb_amradio_close(struct file *file)
{
struct amradio_device *radio = file->private_data;
if (video_is_registered(&radio->videodev))
usb_autopm_put_interface(radio->intf);
return 0;
}
/* Suspend device - stop device. Need to be checked and fixed */
static int usb_amradio_suspend(struct usb_interface *intf, pm_message_t message)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
if (!radio->muted && radio->initialized) {
amradio_set_mute(radio, AMRADIO_STOP);
radio->muted = 0;
}
mutex_unlock(&radio->lock);
dev_info(&intf->dev, "going into suspend..\n");
return 0;
}
/* Resume device - start device. Need to be checked and fixed */
static int usb_amradio_resume(struct usb_interface *intf)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
if (unlikely(!radio->initialized))
goto unlock;
if (radio->stereo)
amradio_set_stereo(radio, WANT_STEREO);
else
amradio_set_stereo(radio, WANT_MONO);
amradio_setfreq(radio, radio->curfreq);
if (!radio->muted)
amradio_set_mute(radio, AMRADIO_START);
unlock:
mutex_unlock(&radio->lock);
dev_info(&intf->dev, "coming out of suspend..\n");
return 0;
}
/* File system interface */
static const struct v4l2_file_operations usb_amradio_fops = {
.owner = THIS_MODULE,
.open = usb_amradio_open,
.release = usb_amradio_close,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops usb_amradio_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
};
static void usb_amradio_video_device_release(struct video_device *videodev)
{
struct amradio_device *radio = video_get_drvdata(videodev);
/* free rest memory */
kfree(radio->buffer);
kfree(radio);
}
/* check if the device is present and register with v4l and usb if it is */
static int usb_amradio_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct amradio_device *radio;
int retval = 0;
radio = kzalloc(sizeof(struct amradio_device), GFP_KERNEL);
if (!radio) {
dev_err(&intf->dev, "kmalloc for amradio_device failed\n");
retval = -ENOMEM;
goto err;
}
radio->buffer = kmalloc(BUFFER_LENGTH, GFP_KERNEL);
if (!radio->buffer) {
dev_err(&intf->dev, "kmalloc for radio->buffer failed\n");
retval = -ENOMEM;
goto err_nobuf;
}
retval = v4l2_device_register(&intf->dev, &radio->v4l2_dev);
if (retval < 0) {
dev_err(&intf->dev, "couldn't register v4l2_device\n");
goto err_v4l2;
}
mutex_init(&radio->lock);
strlcpy(radio->videodev.name, radio->v4l2_dev.name,
sizeof(radio->videodev.name));
radio->videodev.v4l2_dev = &radio->v4l2_dev;
radio->videodev.fops = &usb_amradio_fops;
radio->videodev.ioctl_ops = &usb_amradio_ioctl_ops;
radio->videodev.release = usb_amradio_video_device_release;
radio->videodev.lock = &radio->lock;
radio->usbdev = interface_to_usbdev(intf);
radio->intf = intf;
radio->curfreq = 95.16 * FREQ_MUL;
video_set_drvdata(&radio->videodev, radio);
retval = video_register_device(&radio->videodev, VFL_TYPE_RADIO,
radio_nr);
if (retval < 0) {
dev_err(&intf->dev, "could not register video device\n");
goto err_vdev;
}
return 0;
err_vdev:
v4l2_device_unregister(&radio->v4l2_dev);
err_v4l2:
kfree(radio->buffer);
err_nobuf:
kfree(radio);
err:
return retval;
}
static int __init amradio_init(void)
{
int retval = usb_register(&usb_amradio_driver);
pr_info(KBUILD_MODNAME
": version " DRIVER_VERSION " " DRIVER_DESC "\n");
if (retval)
pr_err(KBUILD_MODNAME
": usb_register failed. Error number %d\n", retval);
return retval;
}
static void __exit amradio_exit(void)
{
usb_deregister(&usb_amradio_driver);
}
module_init(amradio_init);
module_exit(amradio_exit);
| gpl-2.0 |
kykdev/lolliwiz_lentislte | arch/x86/kernel/apic/apic_noop.c | 2529 | 4699 | /*
* NOOP APIC driver.
*
* Does almost nothing and should be substituted by a real apic driver via
* probe routine.
*
* Though in case if apic is disabled (for some reason) we try
* to not uglify the caller's code and allow to call (some) apic routines
* like self-ipi, etc...
*/
#include <linux/threads.h>
#include <linux/cpumask.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <asm/fixmap.h>
#include <asm/mpspec.h>
#include <asm/apicdef.h>
#include <asm/apic.h>
#include <asm/setup.h>
#include <linux/smp.h>
#include <asm/ipi.h>
#include <linux/interrupt.h>
#include <asm/acpi.h>
#include <asm/e820.h>
static void noop_init_apic_ldr(void) { }
static void noop_send_IPI_mask(const struct cpumask *cpumask, int vector) { }
static void noop_send_IPI_mask_allbutself(const struct cpumask *cpumask, int vector) { }
static void noop_send_IPI_allbutself(int vector) { }
static void noop_send_IPI_all(int vector) { }
static void noop_send_IPI_self(int vector) { }
static void noop_apic_wait_icr_idle(void) { }
static void noop_apic_icr_write(u32 low, u32 id) { }
static int noop_wakeup_secondary_cpu(int apicid, unsigned long start_eip)
{
return -1;
}
static u32 noop_safe_apic_wait_icr_idle(void)
{
return 0;
}
static u64 noop_apic_icr_read(void)
{
return 0;
}
static int noop_phys_pkg_id(int cpuid_apic, int index_msb)
{
return 0;
}
static unsigned int noop_get_apic_id(unsigned long x)
{
return 0;
}
static int noop_probe(void)
{
/*
* NOOP apic should not ever be
* enabled via probe routine
*/
return 0;
}
static int noop_apic_id_registered(void)
{
/*
* if we would be really "pedantic"
* we should pass read_apic_id() here
* but since NOOP suppose APIC ID = 0
* lets save a few cycles
*/
return physid_isset(0, phys_cpu_present_map);
}
static const struct cpumask *noop_target_cpus(void)
{
/* only BSP here */
return cpumask_of(0);
}
static unsigned long noop_check_apicid_used(physid_mask_t *map, int apicid)
{
return physid_isset(apicid, *map);
}
static unsigned long noop_check_apicid_present(int bit)
{
return physid_isset(bit, phys_cpu_present_map);
}
static void noop_vector_allocation_domain(int cpu, struct cpumask *retmask,
const struct cpumask *mask)
{
if (cpu != 0)
pr_warning("APIC: Vector allocated for non-BSP cpu\n");
cpumask_copy(retmask, cpumask_of(cpu));
}
static u32 noop_apic_read(u32 reg)
{
WARN_ON_ONCE((cpu_has_apic && !disable_apic));
return 0;
}
static void noop_apic_write(u32 reg, u32 v)
{
WARN_ON_ONCE(cpu_has_apic && !disable_apic);
}
struct apic apic_noop = {
.name = "noop",
.probe = noop_probe,
.acpi_madt_oem_check = NULL,
.apic_id_valid = default_apic_id_valid,
.apic_id_registered = noop_apic_id_registered,
.irq_delivery_mode = dest_LowestPrio,
/* logical delivery broadcast to all CPUs: */
.irq_dest_mode = 1,
.target_cpus = noop_target_cpus,
.disable_esr = 0,
.dest_logical = APIC_DEST_LOGICAL,
.check_apicid_used = noop_check_apicid_used,
.check_apicid_present = noop_check_apicid_present,
.vector_allocation_domain = noop_vector_allocation_domain,
.init_apic_ldr = noop_init_apic_ldr,
.ioapic_phys_id_map = default_ioapic_phys_id_map,
.setup_apic_routing = NULL,
.multi_timer_check = NULL,
.cpu_present_to_apicid = default_cpu_present_to_apicid,
.apicid_to_cpu_present = physid_set_mask_of_physid,
.setup_portio_remap = NULL,
.check_phys_apicid_present = default_check_phys_apicid_present,
.enable_apic_mode = NULL,
.phys_pkg_id = noop_phys_pkg_id,
.mps_oem_check = NULL,
.get_apic_id = noop_get_apic_id,
.set_apic_id = NULL,
.apic_id_mask = 0x0F << 24,
.cpu_mask_to_apicid_and = flat_cpu_mask_to_apicid_and,
.send_IPI_mask = noop_send_IPI_mask,
.send_IPI_mask_allbutself = noop_send_IPI_mask_allbutself,
.send_IPI_allbutself = noop_send_IPI_allbutself,
.send_IPI_all = noop_send_IPI_all,
.send_IPI_self = noop_send_IPI_self,
.wakeup_secondary_cpu = noop_wakeup_secondary_cpu,
/* should be safe */
.trampoline_phys_low = DEFAULT_TRAMPOLINE_PHYS_LOW,
.trampoline_phys_high = DEFAULT_TRAMPOLINE_PHYS_HIGH,
.wait_for_init_deassert = NULL,
.smp_callin_clear_local_apic = NULL,
.inquire_remote_apic = NULL,
.read = noop_apic_read,
.write = noop_apic_write,
.eoi_write = noop_apic_write,
.icr_read = noop_apic_icr_read,
.icr_write = noop_apic_icr_write,
.wait_icr_idle = noop_apic_wait_icr_idle,
.safe_wait_icr_idle = noop_safe_apic_wait_icr_idle,
#ifdef CONFIG_X86_32
.x86_32_early_logical_apicid = noop_x86_32_early_logical_apicid,
#endif
};
| gpl-2.0 |
RaYmunDooo/RaYmunDooo | drivers/staging/comedi/drivers/unioxx5.c | 2785 | 17016 | /***************************************************************************
* *
* comedi/drivers/unioxx5.c *
* Driver for Fastwel UNIOxx-5 (analog and digital i/o) boards. *
* *
* Copyright (C) 2006 Kruchinin Daniil (asgard) [asgard@etersoft.ru] *
* *
* COMEDI - Linux Control and Measurement Device Interface *
* Copyright (C) 1998,2000 David A. Schleef <ds@schleef.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
***************************************************************************/
/*
Driver: unioxx5
Description: Driver for Fastwel UNIOxx-5 (analog and digital i/o) boards.
Author: Kruchinin Daniil (asgard) <asgard@etersoft.ru>
Status: unknown
Updated: 2006-10-09
Devices: [Fastwel] UNIOxx-5 (unioxx5),
This card supports digital and analog I/O. It written for g01
subdevices only.
channels range: 0 .. 23 dio channels
and 0 .. 11 analog modules range
During attaching unioxx5 module displays modules identifiers
(see dmesg after comedi_config) in format:
| [module_number] module_id |
*/
#include "../comedidev.h"
#include <linux/ioport.h>
#include <linux/slab.h>
#define DRIVER_NAME "unioxx5"
#define UNIOXX5_SIZE 0x10
#define UNIOXX5_SUBDEV_BASE 0xA000 /* base addr of first subdev */
#define UNIOXX5_SUBDEV_ODDS 0x400
/* modules types */
#define MODULE_DIGITAL 0
#define MODULE_OUTPUT_MASK 0x80 /* analog input/output */
/* constants for digital i/o */
#define UNIOXX5_NUM_OF_CHANS 24
/* constants for analog i/o */
#define TxBE 0x10 /* transmit buffer enable */
#define RxCA 0x20 /* 1 receive character available */
#define Rx2CA 0x40 /* 2 receive character available */
#define Rx4CA 0x80 /* 4 receive character available */
/* bytes mask errors */
#define Rx2CA_ERR_MASK 0x04 /* 2 bytes receiving error */
#define Rx4CA_ERR_MASK 0x08 /* 4 bytes receiving error */
/* channel modes */
#define ALL_2_INPUT 0 /* config all digital channels to input */
#define ALL_2_OUTPUT 1 /* config all digital channels to output */
/* 'private' structure for each subdevice */
struct unioxx5_subd_priv {
int usp_iobase;
unsigned char usp_module_type[12]; /* 12 modules. each can be 70L or 73L */
unsigned char usp_extra_data[12][4]; /* for saving previous written value for analog modules */
unsigned char usp_prev_wr_val[3]; /* previous written value */
unsigned char usp_prev_cn_val[3]; /* previous channel value */
};
static int unioxx5_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int unioxx5_subdev_write(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data);
static int unioxx5_subdev_read(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data);
static int unioxx5_insn_config(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data);
static int unioxx5_detach(struct comedi_device *dev);
static int __unioxx5_subdev_init(struct comedi_subdevice *subdev,
int subdev_iobase, int minor);
static int __unioxx5_digital_write(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor);
static int __unioxx5_digital_read(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor);
/* static void __unioxx5_digital_config(struct unioxx5_subd_priv* usp, int mode); */
static int __unioxx5_analog_write(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor);
static int __unioxx5_analog_read(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor);
static int __unioxx5_define_chan_offset(int chan_num);
static void __unioxx5_analog_config(struct unioxx5_subd_priv *usp, int channel);
static struct comedi_driver unioxx5_driver = {
.driver_name = DRIVER_NAME,
.module = THIS_MODULE,
.attach = unioxx5_attach,
.detach = unioxx5_detach
};
static int __init unioxx5_driver_init_module(void)
{
return comedi_driver_register(&unioxx5_driver);
}
static void __exit unioxx5_driver_cleanup_module(void)
{
comedi_driver_unregister(&unioxx5_driver);
}
module_init(unioxx5_driver_init_module);
module_exit(unioxx5_driver_cleanup_module);
static int unioxx5_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
int iobase, i, n_subd;
int id, num, ba;
iobase = it->options[0];
dev->board_name = DRIVER_NAME;
dev->iobase = iobase;
iobase += UNIOXX5_SUBDEV_BASE;
/* defining number of subdevices and getting they types (it must be 'g01') */
for (i = n_subd = 0, ba = iobase; i < 4; i++, ba += UNIOXX5_SUBDEV_ODDS) {
id = inb(ba + 0xE);
num = inb(ba + 0xF);
if (id != 'g' || num != 1)
continue;
n_subd++;
}
/* unioxx5 can has from two to four subdevices */
if (n_subd < 2) {
printk(KERN_ERR
"your card must has at least 2 'g01' subdevices\n");
return -1;
}
if (alloc_subdevices(dev, n_subd) < 0) {
printk(KERN_ERR "out of memory\n");
return -ENOMEM;
}
/* initializing each of for same subdevices */
for (i = 0; i < n_subd; i++, iobase += UNIOXX5_SUBDEV_ODDS) {
if (__unioxx5_subdev_init(&dev->subdevices[i], iobase,
dev->minor) < 0)
return -1;
}
printk("attached\n");
return 0;
}
static int unioxx5_subdev_read(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data)
{
struct unioxx5_subd_priv *usp = subdev->private;
int channel, type;
channel = CR_CHAN(insn->chanspec);
type = usp->usp_module_type[channel / 2]; /* defining module type(analog or digital) */
if (type == MODULE_DIGITAL) {
if (!__unioxx5_digital_read(usp, data, channel, dev->minor))
return -1;
} else {
if (!__unioxx5_analog_read(usp, data, channel, dev->minor))
return -1;
}
return 1;
}
static int unioxx5_subdev_write(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data)
{
struct unioxx5_subd_priv *usp = subdev->private;
int channel, type;
channel = CR_CHAN(insn->chanspec);
type = usp->usp_module_type[channel / 2]; /* defining module type(analog or digital) */
if (type == MODULE_DIGITAL) {
if (!__unioxx5_digital_write(usp, data, channel, dev->minor))
return -1;
} else {
if (!__unioxx5_analog_write(usp, data, channel, dev->minor))
return -1;
}
return 1;
}
/* for digital modules only */
static int unioxx5_insn_config(struct comedi_device *dev,
struct comedi_subdevice *subdev,
struct comedi_insn *insn, unsigned int *data)
{
int channel_offset, flags, channel = CR_CHAN(insn->chanspec), type;
struct unioxx5_subd_priv *usp = subdev->private;
int mask = 1 << (channel & 0x07);
type = usp->usp_module_type[channel / 2];
if (type != MODULE_DIGITAL) {
printk(KERN_ERR
"comedi%d: channel configuration accessible only for digital modules\n",
dev->minor);
return -1;
}
channel_offset = __unioxx5_define_chan_offset(channel);
if (channel_offset < 0) {
printk(KERN_ERR
"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
dev->minor, channel);
return -1;
}
/* gets previously written value */
flags = usp->usp_prev_cn_val[channel_offset - 1];
switch (*data) {
case COMEDI_INPUT:
flags &= ~mask;
break;
case COMEDI_OUTPUT:
flags |= mask;
break;
default:
printk(KERN_ERR "comedi%d: unknown flag\n", dev->minor);
return -1;
}
/* *\
* sets channels buffer to 1(after this we are allowed to *
* change channel type on input or output) *
\* */
outb(1, usp->usp_iobase + 0);
outb(flags, usp->usp_iobase + channel_offset); /* changes type of _one_ channel */
outb(0, usp->usp_iobase + 0); /* sets channels bank to 0(allows directly input/output) */
usp->usp_prev_cn_val[channel_offset - 1] = flags; /* saves written value */
return 0;
}
static int unioxx5_detach(struct comedi_device *dev)
{
int i;
struct comedi_subdevice *subdev;
struct unioxx5_subd_priv *usp;
for (i = 0; i < dev->n_subdevices; i++) {
subdev = &dev->subdevices[i];
usp = subdev->private;
release_region(usp->usp_iobase, UNIOXX5_SIZE);
kfree(subdev->private);
}
return 0;
}
/* initializing subdevice with given address */
static int __unioxx5_subdev_init(struct comedi_subdevice *subdev,
int subdev_iobase, int minor)
{
struct unioxx5_subd_priv *usp;
int i, to, ndef_flag = 0;
if (!request_region(subdev_iobase, UNIOXX5_SIZE, DRIVER_NAME)) {
printk(KERN_ERR "comedi%d: I/O port conflict\n", minor);
return -EIO;
}
usp = kzalloc(sizeof(*usp), GFP_KERNEL);
if (usp == NULL) {
printk(KERN_ERR "comedi%d: erorr! --> out of memory!\n", minor);
return -1;
}
usp->usp_iobase = subdev_iobase;
printk("comedi%d: |", minor);
/* defining modules types */
for (i = 0; i < 12; i++) {
to = 10000;
__unioxx5_analog_config(usp, i * 2);
outb(i + 1, subdev_iobase + 5); /* sends channel number to card */
outb('H', subdev_iobase + 6); /* requests EEPROM world */
while (!(inb(subdev_iobase + 0) & TxBE))
; /* waits while writting will be allowed */
outb(0, subdev_iobase + 6);
/* waits while reading of two bytes will be allowed */
while (!(inb(subdev_iobase + 0) & Rx2CA)) {
if (--to <= 0) {
ndef_flag = 1;
break;
}
}
if (ndef_flag) {
usp->usp_module_type[i] = 0;
ndef_flag = 0;
} else
usp->usp_module_type[i] = inb(subdev_iobase + 6);
printk(" [%d] 0x%02x |", i, usp->usp_module_type[i]);
udelay(1);
}
printk("\n");
/* initial subdevice for digital or analog i/o */
subdev->type = COMEDI_SUBD_DIO;
subdev->private = usp;
subdev->subdev_flags = SDF_READABLE | SDF_WRITABLE;
subdev->n_chan = UNIOXX5_NUM_OF_CHANS;
subdev->maxdata = 0xFFF;
subdev->range_table = &range_digital;
subdev->insn_read = unioxx5_subdev_read;
subdev->insn_write = unioxx5_subdev_write;
subdev->insn_config = unioxx5_insn_config; /* for digital modules only!!! */
printk("subdevice configured\n");
return 0;
}
static int __unioxx5_digital_write(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor)
{
int channel_offset, val;
int mask = 1 << (channel & 0x07);
channel_offset = __unioxx5_define_chan_offset(channel);
if (channel_offset < 0) {
printk(KERN_ERR
"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
minor, channel);
return 0;
}
val = usp->usp_prev_wr_val[channel_offset - 1]; /* getting previous written value */
if (*data)
val |= mask;
else
val &= ~mask;
outb(val, usp->usp_iobase + channel_offset);
usp->usp_prev_wr_val[channel_offset - 1] = val; /* saving new written value */
return 1;
}
/* function for digital reading */
static int __unioxx5_digital_read(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor)
{
int channel_offset, mask = 1 << (channel & 0x07);
channel_offset = __unioxx5_define_chan_offset(channel);
if (channel_offset < 0) {
printk(KERN_ERR
"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
minor, channel);
return 0;
}
*data = inb(usp->usp_iobase + channel_offset);
*data &= mask;
if (channel_offset > 1)
channel -= 2 << channel_offset; /* this operation is created for correct readed value to 0 or 1 */
*data >>= channel;
return 1;
}
#if 0 /* not used? */
static void __unioxx5_digital_config(struct unioxx5_subd_priv *usp, int mode)
{
int i, mask;
mask = (mode == ALL_2_OUTPUT) ? 0xFF : 0x00;
printk("COMEDI: mode = %d\n", mask);
outb(1, usp->usp_iobase + 0);
for (i = 0; i < 3; i++)
outb(mask, usp->usp_iobase + i);
outb(0, usp->usp_iobase + 0);
}
#endif
static int __unioxx5_analog_write(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor)
{
int module, i;
module = channel / 2; /* definig module number(0 .. 11) */
i = (channel % 2) << 1; /* depends on type of channel (A or B) */
/* defining if given module can work on output */
if (!(usp->usp_module_type[module] & MODULE_OUTPUT_MASK)) {
printk(KERN_ERR
"comedi%d: module in position %d with id 0x%0x is for input only!\n",
minor, module, usp->usp_module_type[module]);
return 0;
}
__unioxx5_analog_config(usp, channel);
/* saving minor byte */
usp->usp_extra_data[module][i++] = (unsigned char)(*data & 0x00FF);
/* saving major byte */
usp->usp_extra_data[module][i] = (unsigned char)((*data & 0xFF00) >> 8);
/* while(!((inb(usp->usp_iobase + 0)) & TxBE)); */
outb(module + 1, usp->usp_iobase + 5); /* sending module number to card(1 .. 12) */
outb('W', usp->usp_iobase + 6); /* sends (W)rite command to module */
/* sending for bytes to module(one byte per cycle iteration) */
for (i = 0; i < 4; i++) {
while (!((inb(usp->usp_iobase + 0)) & TxBE))
; /* waits while writting will be allowed */
outb(usp->usp_extra_data[module][i], usp->usp_iobase + 6);
}
return 1;
}
static int __unioxx5_analog_read(struct unioxx5_subd_priv *usp,
unsigned int *data, int channel, int minor)
{
int module_no, read_ch;
char control;
module_no = channel / 2;
read_ch = channel % 2; /* depend on type of channel (A or B) */
/* defining if given module can work on input */
if (usp->usp_module_type[module_no] & MODULE_OUTPUT_MASK) {
printk(KERN_ERR
"comedi%d: module in position %d with id 0x%02x is for output only",
minor, module_no, usp->usp_module_type[module_no]);
return 0;
}
__unioxx5_analog_config(usp, channel);
outb(module_no + 1, usp->usp_iobase + 5); /* sends module number to card(1 .. 12) */
outb('V', usp->usp_iobase + 6); /* sends to module (V)erify command */
control = inb(usp->usp_iobase); /* get control register byte */
/* waits while reading four bytes will be allowed */
while (!((control = inb(usp->usp_iobase + 0)) & Rx4CA))
;
/* if four bytes readding error occurs - return 0(false) */
if ((control & Rx4CA_ERR_MASK)) {
printk("COMEDI: 4 bytes error\n");
return 0;
}
if (read_ch)
*data = inw(usp->usp_iobase + 6); /* channel B */
else
*data = inw(usp->usp_iobase + 4); /* channel A */
return 1;
}
/* configure channels for analog i/o (even to output, odd to input) */
static void __unioxx5_analog_config(struct unioxx5_subd_priv *usp, int channel)
{
int chan_a, chan_b, conf, channel_offset;
channel_offset = __unioxx5_define_chan_offset(channel);
conf = usp->usp_prev_cn_val[channel_offset - 1];
chan_a = chan_b = 1;
/* setting channel A and channel B mask */
if (channel % 2 == 0) {
chan_a <<= channel & 0x07;
chan_b <<= (channel + 1) & 0x07;
} else {
chan_a <<= (channel - 1) & 0x07;
chan_b <<= channel & 0x07;
}
conf |= chan_a; /* even channel ot output */
conf &= ~chan_b; /* odd channel to input */
outb(1, usp->usp_iobase + 0);
outb(conf, usp->usp_iobase + channel_offset);
outb(0, usp->usp_iobase + 0);
usp->usp_prev_cn_val[channel_offset - 1] = conf;
}
/* *\
* this function defines if the given channel number *
* enters in default numeric interspace(from 0 to 23) *
* and it returns address offset for usage needed *
* channel. *
\* */
static int __unioxx5_define_chan_offset(int chan_num)
{
if (chan_num < 0 || chan_num > 23)
return -1;
return (chan_num >> 3) + 1;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
davidmueller13/Fulgor_Kernel_Lollipop | drivers/staging/comedi/comedi_fops.c | 2785 | 63289 | /*
comedi/comedi_fops.c
comedi kernel module
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#undef DEBUG
#define __NO_VERSION__
#include "comedi_fops.h"
#include "comedi_compat32.h"
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fcntl.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include "comedidev.h"
#include <linux/cdev.h>
#include <linux/stat.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include "internal.h"
MODULE_AUTHOR("http://www.comedi.org");
MODULE_DESCRIPTION("Comedi core module");
MODULE_LICENSE("GPL");
#ifdef CONFIG_COMEDI_DEBUG
int comedi_debug;
EXPORT_SYMBOL(comedi_debug);
module_param(comedi_debug, int, 0644);
#endif
bool comedi_autoconfig = 1;
module_param(comedi_autoconfig, bool, 0444);
static int comedi_num_legacy_minors;
module_param(comedi_num_legacy_minors, int, 0444);
static DEFINE_SPINLOCK(comedi_file_info_table_lock);
static struct comedi_device_file_info
*comedi_file_info_table[COMEDI_NUM_MINORS];
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg);
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg);
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file);
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file);
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg);
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file);
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file);
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file);
static int do_poll_ioctl(struct comedi_device *dev, unsigned int subd,
void *file);
static void do_become_nonbusy(struct comedi_device *dev,
struct comedi_subdevice *s);
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static int comedi_fasync(int fd, struct file *file, int on);
static int is_device_busy(struct comedi_device *dev);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size);
/* declarations for sysfs attribute files */
static struct device_attribute dev_attr_max_read_buffer_kb;
static struct device_attribute dev_attr_read_buffer_kb;
static struct device_attribute dev_attr_max_write_buffer_kb;
static struct device_attribute dev_attr_write_buffer_kb;
static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev;
int rc;
if (dev_file_info == NULL || dev_file_info->device == NULL)
return -ENODEV;
dev = dev_file_info->device;
mutex_lock(&dev->mutex);
/* Device config is special, because it must work on
* an unconfigured device. */
if (cmd == COMEDI_DEVCONFIG) {
rc = do_devconfig_ioctl(dev,
(struct comedi_devconfig __user *)arg);
goto done;
}
if (!dev->attached) {
DPRINTK("no driver configured on /dev/comedi%i\n", dev->minor);
rc = -ENODEV;
goto done;
}
switch (cmd) {
case COMEDI_BUFCONFIG:
rc = do_bufconfig_ioctl(dev,
(struct comedi_bufconfig __user *)arg);
break;
case COMEDI_DEVINFO:
rc = do_devinfo_ioctl(dev, (struct comedi_devinfo __user *)arg,
file);
break;
case COMEDI_SUBDINFO:
rc = do_subdinfo_ioctl(dev,
(struct comedi_subdinfo __user *)arg,
file);
break;
case COMEDI_CHANINFO:
rc = do_chaninfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_RANGEINFO:
rc = do_rangeinfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_BUFINFO:
rc = do_bufinfo_ioctl(dev,
(struct comedi_bufinfo __user *)arg,
file);
break;
case COMEDI_LOCK:
rc = do_lock_ioctl(dev, arg, file);
break;
case COMEDI_UNLOCK:
rc = do_unlock_ioctl(dev, arg, file);
break;
case COMEDI_CANCEL:
rc = do_cancel_ioctl(dev, arg, file);
break;
case COMEDI_CMD:
rc = do_cmd_ioctl(dev, (struct comedi_cmd __user *)arg, file);
break;
case COMEDI_CMDTEST:
rc = do_cmdtest_ioctl(dev, (struct comedi_cmd __user *)arg,
file);
break;
case COMEDI_INSNLIST:
rc = do_insnlist_ioctl(dev,
(struct comedi_insnlist __user *)arg,
file);
break;
case COMEDI_INSN:
rc = do_insn_ioctl(dev, (struct comedi_insn __user *)arg,
file);
break;
case COMEDI_POLL:
rc = do_poll_ioctl(dev, arg, file);
break;
default:
rc = -ENOTTY;
break;
}
done:
mutex_unlock(&dev->mutex);
return rc;
}
/*
COMEDI_DEVCONFIG
device config ioctl
arg:
pointer to devconfig structure
reads:
devconfig structure at arg
writes:
none
*/
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg)
{
struct comedi_devconfig it;
int ret;
unsigned char *aux_data = NULL;
int aux_len;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (arg == NULL) {
if (is_device_busy(dev))
return -EBUSY;
if (dev->attached) {
struct module *driver_module = dev->driver->module;
comedi_device_detach(dev);
module_put(driver_module);
}
return 0;
}
if (copy_from_user(&it, arg, sizeof(struct comedi_devconfig)))
return -EFAULT;
it.board_name[COMEDI_NAMELEN - 1] = 0;
if (comedi_aux_data(it.options, 0) &&
it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
int bit_shift;
aux_len = it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH];
if (aux_len < 0)
return -EFAULT;
aux_data = vmalloc(aux_len);
if (!aux_data)
return -ENOMEM;
if (copy_from_user(aux_data,
comedi_aux_data(it.options, 0), aux_len)) {
vfree(aux_data);
return -EFAULT;
}
it.options[COMEDI_DEVCONF_AUX_DATA_LO] =
(unsigned long)aux_data;
if (sizeof(void *) > sizeof(int)) {
bit_shift = sizeof(int) * 8;
it.options[COMEDI_DEVCONF_AUX_DATA_HI] =
((unsigned long)aux_data) >> bit_shift;
} else
it.options[COMEDI_DEVCONF_AUX_DATA_HI] = 0;
}
ret = comedi_device_attach(dev, &it);
if (ret == 0) {
if (!try_module_get(dev->driver->module)) {
comedi_device_detach(dev);
return -ENOSYS;
}
}
if (aux_data)
vfree(aux_data);
return ret;
}
/*
COMEDI_BUFCONFIG
buffer configuration ioctl
arg:
pointer to bufconfig structure
reads:
bufconfig at arg
writes:
modified bufconfig at arg
*/
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg)
{
struct comedi_bufconfig bc;
struct comedi_async *async;
struct comedi_subdevice *s;
int retval = 0;
if (copy_from_user(&bc, arg, sizeof(struct comedi_bufconfig)))
return -EFAULT;
if (bc.subdevice >= dev->n_subdevices || bc.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bc.subdevice;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bc.size = 0;
bc.maximum_size = 0;
goto copyback;
}
if (bc.maximum_size) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
async->max_bufsize = bc.maximum_size;
}
if (bc.size) {
retval = resize_async_buffer(dev, s, async, bc.size);
if (retval < 0)
return retval;
}
bc.size = async->prealloc_bufsz;
bc.maximum_size = async->max_bufsize;
copyback:
if (copy_to_user(arg, &bc, sizeof(struct comedi_bufconfig)))
return -EFAULT;
return 0;
}
/*
COMEDI_DEVINFO
device info ioctl
arg:
pointer to devinfo structure
reads:
none
writes:
devinfo structure
*/
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file)
{
struct comedi_devinfo devinfo;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_subdevice *read_subdev =
comedi_get_read_subdevice(dev_file_info);
struct comedi_subdevice *write_subdev =
comedi_get_write_subdevice(dev_file_info);
memset(&devinfo, 0, sizeof(devinfo));
/* fill devinfo structure */
devinfo.version_code = COMEDI_VERSION_CODE;
devinfo.n_subdevs = dev->n_subdevices;
strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
if (read_subdev)
devinfo.read_subdevice = read_subdev - dev->subdevices;
else
devinfo.read_subdevice = -1;
if (write_subdev)
devinfo.write_subdevice = write_subdev - dev->subdevices;
else
devinfo.write_subdevice = -1;
if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo)))
return -EFAULT;
return 0;
}
/*
COMEDI_SUBDINFO
subdevice info ioctl
arg:
pointer to array of subdevice info structures
reads:
none
writes:
array of subdevice info structures at arg
*/
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file)
{
int ret, i;
struct comedi_subdinfo *tmp, *us;
struct comedi_subdevice *s;
tmp =
kcalloc(dev->n_subdevices, sizeof(struct comedi_subdinfo),
GFP_KERNEL);
if (!tmp)
return -ENOMEM;
/* fill subdinfo structs */
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
us = tmp + i;
us->type = s->type;
us->n_chan = s->n_chan;
us->subd_flags = s->subdev_flags;
if (comedi_get_subdevice_runflags(s) & SRF_RUNNING)
us->subd_flags |= SDF_RUNNING;
#define TIMER_nanosec 5 /* backwards compatibility */
us->timer_type = TIMER_nanosec;
us->len_chanlist = s->len_chanlist;
us->maxdata = s->maxdata;
if (s->range_table) {
us->range_type =
(i << 24) | (0 << 16) | (s->range_table->length);
} else {
us->range_type = 0; /* XXX */
}
us->flags = s->flags;
if (s->busy)
us->subd_flags |= SDF_BUSY;
if (s->busy == file)
us->subd_flags |= SDF_BUSY_OWNER;
if (s->lock)
us->subd_flags |= SDF_LOCKED;
if (s->lock == file)
us->subd_flags |= SDF_LOCK_OWNER;
if (!s->maxdata && s->maxdata_list)
us->subd_flags |= SDF_MAXDATA;
if (s->flaglist)
us->subd_flags |= SDF_FLAGS;
if (s->range_table_list)
us->subd_flags |= SDF_RANGETYPE;
if (s->do_cmd)
us->subd_flags |= SDF_CMD;
if (s->insn_bits != &insn_inval)
us->insn_bits_support = COMEDI_SUPPORTED;
else
us->insn_bits_support = COMEDI_UNSUPPORTED;
us->settling_time_0 = s->settling_time_0;
}
ret = copy_to_user(arg, tmp,
dev->n_subdevices * sizeof(struct comedi_subdinfo));
kfree(tmp);
return ret ? -EFAULT : 0;
}
/*
COMEDI_CHANINFO
subdevice info ioctl
arg:
pointer to chaninfo structure
reads:
chaninfo structure at arg
writes:
arrays at elements of chaninfo structure
*/
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg)
{
struct comedi_subdevice *s;
struct comedi_chaninfo it;
if (copy_from_user(&it, arg, sizeof(struct comedi_chaninfo)))
return -EFAULT;
if (it.subdev >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + it.subdev;
if (it.maxdata_list) {
if (s->maxdata || !s->maxdata_list)
return -EINVAL;
if (copy_to_user(it.maxdata_list, s->maxdata_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.flaglist) {
if (!s->flaglist)
return -EINVAL;
if (copy_to_user(it.flaglist, s->flaglist,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.rangelist) {
int i;
if (!s->range_table_list)
return -EINVAL;
for (i = 0; i < s->n_chan; i++) {
int x;
x = (dev->minor << 28) | (it.subdev << 24) | (i << 16) |
(s->range_table_list[i]->length);
if (put_user(x, it.rangelist + i))
return -EFAULT;
}
#if 0
if (copy_to_user(it.rangelist, s->range_type_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
#endif
}
return 0;
}
/*
COMEDI_BUFINFO
buffer information ioctl
arg:
pointer to bufinfo structure
reads:
bufinfo at arg
writes:
modified bufinfo at arg
*/
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file)
{
struct comedi_bufinfo bi;
struct comedi_subdevice *s;
struct comedi_async *async;
if (copy_from_user(&bi, arg, sizeof(struct comedi_bufinfo)))
return -EFAULT;
if (bi.subdevice >= dev->n_subdevices || bi.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bi.subdevice;
if (s->lock && s->lock != file)
return -EACCES;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bi.buf_write_ptr = 0;
bi.buf_read_ptr = 0;
bi.buf_write_count = 0;
bi.buf_read_count = 0;
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback;
}
if (!s->busy) {
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback_position;
}
if (s->busy != file)
return -EACCES;
if (bi.bytes_read && (s->subdev_flags & SDF_CMD_READ)) {
bi.bytes_read = comedi_buf_read_alloc(async, bi.bytes_read);
comedi_buf_read_free(async, bi.bytes_read);
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR |
SRF_RUNNING))
&& async->buf_write_count == async->buf_read_count) {
do_become_nonbusy(dev, s);
}
}
if (bi.bytes_written && (s->subdev_flags & SDF_CMD_WRITE)) {
bi.bytes_written =
comedi_buf_write_alloc(async, bi.bytes_written);
comedi_buf_write_free(async, bi.bytes_written);
}
copyback_position:
bi.buf_write_count = async->buf_write_count;
bi.buf_write_ptr = async->buf_write_ptr;
bi.buf_read_count = async->buf_read_count;
bi.buf_read_ptr = async->buf_read_ptr;
copyback:
if (copy_to_user(arg, &bi, sizeof(struct comedi_bufinfo)))
return -EFAULT;
return 0;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file);
/*
* COMEDI_INSNLIST
* synchronous instructions
*
* arg:
* pointer to sync cmd structure
*
* reads:
* sync cmd struct at arg
* instruction list
* data (for writes)
*
* writes:
* data (for reads)
*/
/* arbitrary limits */
#define MAX_SAMPLES 256
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file)
{
struct comedi_insnlist insnlist;
struct comedi_insn *insns = NULL;
unsigned int *data = NULL;
int i = 0;
int ret = 0;
if (copy_from_user(&insnlist, arg, sizeof(struct comedi_insnlist)))
return -EFAULT;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
insns =
kcalloc(insnlist.n_insns, sizeof(struct comedi_insn), GFP_KERNEL);
if (!insns) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
if (copy_from_user(insns, insnlist.insns,
sizeof(struct comedi_insn) * insnlist.n_insns)) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
for (i = 0; i < insnlist.n_insns; i++) {
if (insns[i].n > MAX_SAMPLES) {
DPRINTK("number of samples too large\n");
ret = -EINVAL;
goto error;
}
if (insns[i].insn & INSN_MASK_WRITE) {
if (copy_from_user(data, insns[i].data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, insns + i, data, file);
if (ret < 0)
goto error;
if (insns[i].insn & INSN_MASK_READ) {
if (copy_to_user(insns[i].data, data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_to_user failed\n");
ret = -EFAULT;
goto error;
}
}
if (need_resched())
schedule();
}
error:
kfree(insns);
kfree(data);
if (ret < 0)
return ret;
return i;
}
static int check_insn_config_length(struct comedi_insn *insn,
unsigned int *data)
{
if (insn->n < 1)
return -EINVAL;
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
case INSN_CONFIG_DIO_INPUT:
case INSN_CONFIG_DISARM:
case INSN_CONFIG_RESET:
if (insn->n == 1)
return 0;
break;
case INSN_CONFIG_ARM:
case INSN_CONFIG_DIO_QUERY:
case INSN_CONFIG_BLOCK_SIZE:
case INSN_CONFIG_FILTER:
case INSN_CONFIG_SERIAL_CLOCK:
case INSN_CONFIG_BIDIRECTIONAL_DATA:
case INSN_CONFIG_ALT_SOURCE:
case INSN_CONFIG_SET_COUNTER_MODE:
case INSN_CONFIG_8254_READ_STATUS:
case INSN_CONFIG_SET_ROUTING:
case INSN_CONFIG_GET_ROUTING:
case INSN_CONFIG_GET_PWM_STATUS:
case INSN_CONFIG_PWM_SET_PERIOD:
case INSN_CONFIG_PWM_GET_PERIOD:
if (insn->n == 2)
return 0;
break;
case INSN_CONFIG_SET_GATE_SRC:
case INSN_CONFIG_GET_GATE_SRC:
case INSN_CONFIG_SET_CLOCK_SRC:
case INSN_CONFIG_GET_CLOCK_SRC:
case INSN_CONFIG_SET_OTHER_SRC:
case INSN_CONFIG_GET_COUNTER_STATUS:
case INSN_CONFIG_PWM_SET_H_BRIDGE:
case INSN_CONFIG_PWM_GET_H_BRIDGE:
case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
if (insn->n == 3)
return 0;
break;
case INSN_CONFIG_PWM_OUTPUT:
case INSN_CONFIG_ANALOG_TRIG:
if (insn->n == 5)
return 0;
break;
/* by default we allow the insn since we don't have checks for
* all possible cases yet */
default:
printk(KERN_WARNING
"comedi: no check for data length of config insn id "
"%i is implemented.\n"
" Add a check to %s in %s.\n"
" Assuming n=%i is correct.\n", data[0], __func__,
__FILE__, insn->n);
return 0;
break;
}
return -EINVAL;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file)
{
struct comedi_subdevice *s;
int ret = 0;
int i;
if (insn->insn & INSN_MASK_SPECIAL) {
/* a non-subdevice instruction */
switch (insn->insn) {
case INSN_GTOD:
{
struct timeval tv;
if (insn->n != 2) {
ret = -EINVAL;
break;
}
do_gettimeofday(&tv);
data[0] = tv.tv_sec;
data[1] = tv.tv_usec;
ret = 2;
break;
}
case INSN_WAIT:
if (insn->n != 1 || data[0] >= 100000) {
ret = -EINVAL;
break;
}
udelay(data[0] / 1000);
ret = 1;
break;
case INSN_INTTRIG:
if (insn->n != 1) {
ret = -EINVAL;
break;
}
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("%d not usable subdevice\n",
insn->subdev);
ret = -EINVAL;
break;
}
s = dev->subdevices + insn->subdev;
if (!s->async) {
DPRINTK("no async\n");
ret = -EINVAL;
break;
}
if (!s->async->inttrig) {
DPRINTK("no inttrig\n");
ret = -EAGAIN;
break;
}
ret = s->async->inttrig(dev, s, insn->data[0]);
if (ret >= 0)
ret = 1;
break;
default:
DPRINTK("invalid insn\n");
ret = -EINVAL;
break;
}
} else {
/* a subdevice instruction */
unsigned int maxdata;
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("subdevice %d out of range\n", insn->subdev);
ret = -EINVAL;
goto out;
}
s = dev->subdevices + insn->subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not usable subdevice\n", insn->subdev);
ret = -EIO;
goto out;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("device locked\n");
ret = -EACCES;
goto out;
}
ret = comedi_check_chanlist(s, 1, &insn->chanspec);
if (ret < 0) {
ret = -EINVAL;
DPRINTK("bad chanspec\n");
goto out;
}
if (s->busy) {
ret = -EBUSY;
goto out;
}
/* This looks arbitrary. It is. */
s->busy = &parse_insn;
switch (insn->insn) {
case INSN_READ:
ret = s->insn_read(dev, s, insn, data);
break;
case INSN_WRITE:
maxdata = s->maxdata_list
? s->maxdata_list[CR_CHAN(insn->chanspec)]
: s->maxdata;
for (i = 0; i < insn->n; ++i) {
if (data[i] > maxdata) {
ret = -EINVAL;
DPRINTK("bad data value(s)\n");
break;
}
}
if (ret == 0)
ret = s->insn_write(dev, s, insn, data);
break;
case INSN_BITS:
if (insn->n != 2) {
ret = -EINVAL;
} else {
/* Most drivers ignore the base channel in
* insn->chanspec. Fix this here if
* the subdevice has <= 32 channels. */
unsigned int shift;
unsigned int orig_mask;
orig_mask = data[0];
if (s->n_chan <= 32) {
shift = CR_CHAN(insn->chanspec);
if (shift > 0) {
insn->chanspec = 0;
data[0] <<= shift;
data[1] <<= shift;
}
} else
shift = 0;
ret = s->insn_bits(dev, s, insn, data);
data[0] = orig_mask;
if (shift > 0)
data[1] >>= shift;
}
break;
case INSN_CONFIG:
ret = check_insn_config_length(insn, data);
if (ret)
break;
ret = s->insn_config(dev, s, insn, data);
break;
default:
ret = -EINVAL;
break;
}
s->busy = NULL;
}
out:
return ret;
}
/*
* COMEDI_INSN
* synchronous instructions
*
* arg:
* pointer to insn
*
* reads:
* struct comedi_insn struct at arg
* data (for writes)
*
* writes:
* data (for reads)
*/
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file)
{
struct comedi_insn insn;
unsigned int *data = NULL;
int ret = 0;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
ret = -ENOMEM;
goto error;
}
if (copy_from_user(&insn, arg, sizeof(struct comedi_insn))) {
ret = -EFAULT;
goto error;
}
/* This is where the behavior of insn and insnlist deviate. */
if (insn.n > MAX_SAMPLES)
insn.n = MAX_SAMPLES;
if (insn.insn & INSN_MASK_WRITE) {
if (copy_from_user(data,
insn.data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, &insn, data, file);
if (ret < 0)
goto error;
if (insn.insn & INSN_MASK_READ) {
if (copy_to_user(insn.data,
data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = insn.n;
error:
kfree(data);
return ret;
}
static void comedi_set_subdevice_runflags(struct comedi_subdevice *s,
unsigned mask, unsigned bits)
{
unsigned long flags;
spin_lock_irqsave(&s->spin_lock, flags);
s->runflags &= ~mask;
s->runflags |= (bits & mask);
spin_unlock_irqrestore(&s->spin_lock, flags);
}
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *cmd, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
struct comedi_async *async;
int ret = 0;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
async = s->async;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest || !s->async) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("subdevice locked\n");
return -EACCES;
}
/* are we busy? */
if (s->busy) {
DPRINTK("subdevice busy\n");
return -EBUSY;
}
s->busy = file;
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %u > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* make sure channel/gain list isn't too short */
if (user_cmd.chanlist_len < 1) {
DPRINTK("channel/gain list too short %u < 1\n",
user_cmd.chanlist_len);
ret = -EINVAL;
goto cleanup;
}
kfree(async->cmd.chanlist);
async->cmd = user_cmd;
async->cmd.data = NULL;
/* load channel/gain list */
async->cmd.chanlist =
kmalloc(async->cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!async->cmd.chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(async->cmd.chanlist, user_cmd.chanlist,
async->cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s,
async->cmd.chanlist_len,
async->cmd.chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
ret = s->do_cmdtest(dev, s, &async->cmd);
if (async->cmd.flags & TRIG_BOGUS || ret) {
DPRINTK("test returned %d\n", ret);
user_cmd = async->cmd;
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
user_cmd.data = NULL;
if (copy_to_user(cmd, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("fault writing cmd\n");
ret = -EFAULT;
goto cleanup;
}
ret = -EAGAIN;
goto cleanup;
}
if (!async->prealloc_bufsz) {
ret = -ENOMEM;
DPRINTK("no buffer (?)\n");
goto cleanup;
}
comedi_reset_async_buf(async);
async->cb_mask =
COMEDI_CB_EOA | COMEDI_CB_BLOCK | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW;
if (async->cmd.flags & TRIG_WAKE_EOS)
async->cb_mask |= COMEDI_CB_EOS;
comedi_set_subdevice_runflags(s, ~0, SRF_USER | SRF_RUNNING);
ret = s->do_cmd(dev, s);
if (ret == 0)
return 0;
cleanup:
do_become_nonbusy(dev, s);
return ret;
}
/*
COMEDI_CMDTEST
command testing ioctl
arg:
pointer to cmd structure
reads:
cmd structure at arg
channel/range list
writes:
modified cmd structure at arg
*/
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
int ret = 0;
unsigned int *chanlist = NULL;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, arg, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %d > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* load channel/gain list */
if (user_cmd.chanlist) {
chanlist =
kmalloc(user_cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(chanlist, user_cmd.chanlist,
user_cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s, user_cmd.chanlist_len, chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
user_cmd.chanlist = chanlist;
}
ret = s->do_cmdtest(dev, s, &user_cmd);
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
if (copy_to_user(arg, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
ret = -EFAULT;
goto cleanup;
}
cleanup:
kfree(chanlist);
return ret;
}
/*
COMEDI_LOCK
lock subdevice
arg:
subdevice number
reads:
none
writes:
none
*/
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
int ret = 0;
unsigned long flags;
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
spin_lock_irqsave(&s->spin_lock, flags);
if (s->busy || s->lock)
ret = -EBUSY;
else
s->lock = file;
spin_unlock_irqrestore(&s->spin_lock, flags);
#if 0
if (ret < 0)
return ret;
if (s->lock_f)
ret = s->lock_f(dev, s);
#endif
return ret;
}
/*
COMEDI_UNLOCK
unlock subdevice
arg:
subdevice number
reads:
none
writes:
none
This function isn't protected by the semaphore, since
we already own the lock.
*/
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->busy)
return -EBUSY;
if (s->lock && s->lock != file)
return -EACCES;
if (s->lock == file) {
#if 0
if (s->unlock)
s->unlock(dev, s);
#endif
s->lock = NULL;
}
return 0;
}
/*
COMEDI_CANCEL
cancel acquisition ioctl
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->async == NULL)
return -EINVAL;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
return do_cancel(dev, s);
}
/*
COMEDI_POLL ioctl
instructs driver to synchronize buffers
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_poll_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
if (s->poll)
return s->poll(dev, s);
return -EINVAL;
}
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
int ret = 0;
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) && s->cancel)
ret = s->cancel(dev, s);
do_become_nonbusy(dev, s);
return ret;
}
static void comedi_vm_open(struct vm_area_struct *area)
{
struct comedi_async *async;
struct comedi_device *dev;
async = area->vm_private_data;
dev = async->subdevice->device;
mutex_lock(&dev->mutex);
async->mmap_count++;
mutex_unlock(&dev->mutex);
}
static void comedi_vm_close(struct vm_area_struct *area)
{
struct comedi_async *async;
struct comedi_device *dev;
async = area->vm_private_data;
dev = async->subdevice->device;
mutex_lock(&dev->mutex);
async->mmap_count--;
mutex_unlock(&dev->mutex);
}
static struct vm_operations_struct comedi_vm_ops = {
.open = comedi_vm_open,
.close = comedi_vm_close,
};
static int comedi_mmap(struct file *file, struct vm_area_struct *vma)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_async *async = NULL;
unsigned long start = vma->vm_start;
unsigned long size;
int n_pages;
int i;
int retval;
struct comedi_subdevice *s;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
if (vma->vm_flags & VM_WRITE)
s = comedi_get_write_subdevice(dev_file_info);
else
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EINVAL;
goto done;
}
async = s->async;
if (async == NULL) {
retval = -EINVAL;
goto done;
}
if (vma->vm_pgoff != 0) {
DPRINTK("comedi: mmap() offset must be 0.\n");
retval = -EINVAL;
goto done;
}
size = vma->vm_end - vma->vm_start;
if (size > async->prealloc_bufsz) {
retval = -EFAULT;
goto done;
}
if (size & (~PAGE_MASK)) {
retval = -EFAULT;
goto done;
}
n_pages = size >> PAGE_SHIFT;
for (i = 0; i < n_pages; ++i) {
if (remap_pfn_range(vma, start,
page_to_pfn(virt_to_page
(async->buf_page_list
[i].virt_addr)), PAGE_SIZE,
PAGE_SHARED)) {
retval = -EAGAIN;
goto done;
}
start += PAGE_SIZE;
}
vma->vm_ops = &comedi_vm_ops;
vma->vm_private_data = async;
async->mmap_count++;
retval = 0;
done:
mutex_unlock(&dev->mutex);
return retval;
}
static unsigned int comedi_poll(struct file *file, poll_table * wait)
{
unsigned int mask = 0;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_subdevice *read_subdev;
struct comedi_subdevice *write_subdev;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
mutex_unlock(&dev->mutex);
return 0;
}
mask = 0;
read_subdev = comedi_get_read_subdevice(dev_file_info);
if (read_subdev) {
poll_wait(file, &read_subdev->async->wait_head, wait);
if (!read_subdev->busy
|| comedi_buf_read_n_available(read_subdev->async) > 0
|| !(comedi_get_subdevice_runflags(read_subdev) &
SRF_RUNNING)) {
mask |= POLLIN | POLLRDNORM;
}
}
write_subdev = comedi_get_write_subdevice(dev_file_info);
if (write_subdev) {
poll_wait(file, &write_subdev->async->wait_head, wait);
comedi_buf_write_alloc(write_subdev->async,
write_subdev->async->prealloc_bufsz);
if (!write_subdev->busy
|| !(comedi_get_subdevice_runflags(write_subdev) &
SRF_RUNNING)
|| comedi_buf_write_n_allocated(write_subdev->async) >=
bytes_per_sample(write_subdev->async->subdevice)) {
mask |= POLLOUT | POLLWRNORM;
}
}
mutex_unlock(&dev->mutex);
return mask;
}
static ssize_t comedi_write(struct file *file, const char __user *buf,
size_t nbytes, loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_write_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
if (count == 0) {
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
do_become_nonbusy(dev, s);
}
break;
}
n = nbytes;
m = n;
if (async->buf_write_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_write_ptr;
comedi_buf_write_alloc(async, async->prealloc_bufsz);
if (m > comedi_buf_write_n_allocated(async))
m = comedi_buf_write_n_allocated(async);
if (m < n)
n = m;
if (n == 0) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (!s->busy)
break;
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_from_user(async->prealloc_buf + async->buf_write_ptr,
buf, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_write_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
static ssize_t comedi_read(struct file *file, char __user *buf, size_t nbytes,
loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
n = nbytes;
m = comedi_buf_read_n_available(async);
/* printk("%d available\n",m); */
if (async->buf_read_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_read_ptr;
/* printk("%d contiguous\n",m); */
if (m < n)
n = m;
if (n == 0) {
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
do_become_nonbusy(dev, s);
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
break;
}
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (!s->busy) {
retval = 0;
break;
}
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_to_user(buf, async->prealloc_buf +
async->buf_read_ptr, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_read_alloc(async, n);
comedi_buf_read_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR | SRF_RUNNING)) &&
async->buf_read_count - async->buf_write_count == 0) {
do_become_nonbusy(dev, s);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
/*
This function restores a subdevice to an idle state.
*/
void do_become_nonbusy(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
comedi_set_subdevice_runflags(s, SRF_RUNNING, 0);
if (async) {
comedi_reset_async_buf(async);
async->inttrig = NULL;
} else {
printk(KERN_ERR
"BUG: (?) do_become_nonbusy called with async=0\n");
}
s->busy = NULL;
}
static int comedi_open(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev =
dev_file_info ? dev_file_info->device : NULL;
if (dev == NULL) {
DPRINTK("invalid minor number\n");
return -ENODEV;
}
/* This is slightly hacky, but we want module autoloading
* to work for root.
* case: user opens device, attached -> ok
* case: user opens device, unattached, in_request_module=0 -> autoload
* case: user opens device, unattached, in_request_module=1 -> fail
* case: root opens device, attached -> ok
* case: root opens device, unattached, in_request_module=1 -> ok
* (typically called from modprobe)
* case: root opens device, unattached, in_request_module=0 -> autoload
*
* The last could be changed to "-> ok", which would deny root
* autoloading.
*/
mutex_lock(&dev->mutex);
if (dev->attached)
goto ok;
if (!capable(CAP_NET_ADMIN) && dev->in_request_module) {
DPRINTK("in request module\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
if (capable(CAP_NET_ADMIN) && dev->in_request_module)
goto ok;
dev->in_request_module = 1;
#ifdef CONFIG_KMOD
mutex_unlock(&dev->mutex);
request_module("char-major-%i-%i", COMEDI_MAJOR, dev->minor);
mutex_lock(&dev->mutex);
#endif
dev->in_request_module = 0;
if (!dev->attached && !capable(CAP_NET_ADMIN)) {
DPRINTK("not attached and not CAP_NET_ADMIN\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
ok:
__module_get(THIS_MODULE);
if (dev->attached) {
if (!try_module_get(dev->driver->module)) {
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return -ENOSYS;
}
}
if (dev->attached && dev->use_count == 0 && dev->open) {
int rc = dev->open(dev);
if (rc < 0) {
module_put(dev->driver->module);
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return rc;
}
}
dev->use_count++;
mutex_unlock(&dev->mutex);
return 0;
}
static int comedi_close(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_subdevice *s = NULL;
int i;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (dev->subdevices) {
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy == file)
do_cancel(dev, s);
if (s->lock == file)
s->lock = NULL;
}
}
if (dev->attached && dev->use_count == 1 && dev->close)
dev->close(dev);
module_put(THIS_MODULE);
if (dev->attached)
module_put(dev->driver->module);
dev->use_count--;
mutex_unlock(&dev->mutex);
if (file->f_flags & FASYNC)
comedi_fasync(-1, file, 0);
return 0;
}
static int comedi_fasync(int fd, struct file *file, int on)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
return fasync_helper(fd, file, on, &dev->async_queue);
}
const struct file_operations comedi_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = comedi_unlocked_ioctl,
.compat_ioctl = comedi_compat_ioctl,
.open = comedi_open,
.release = comedi_close,
.read = comedi_read,
.write = comedi_write,
.mmap = comedi_mmap,
.poll = comedi_poll,
.fasync = comedi_fasync,
.llseek = noop_llseek,
};
struct class *comedi_class;
static struct cdev comedi_cdev;
static void comedi_cleanup_legacy_minors(void)
{
unsigned i;
for (i = 0; i < comedi_num_legacy_minors; i++)
comedi_free_board_minor(i);
}
static int __init comedi_init(void)
{
int i;
int retval;
printk(KERN_INFO "comedi: version " COMEDI_RELEASE
" - http://www.comedi.org\n");
if (comedi_num_legacy_minors < 0 ||
comedi_num_legacy_minors > COMEDI_NUM_BOARD_MINORS) {
printk(KERN_ERR "comedi: error: invalid value for module "
"parameter \"comedi_num_legacy_minors\". Valid values "
"are 0 through %i.\n", COMEDI_NUM_BOARD_MINORS);
return -EINVAL;
}
/*
* comedi is unusable if both comedi_autoconfig and
* comedi_num_legacy_minors are zero, so we might as well adjust the
* defaults in that case
*/
if (comedi_autoconfig == 0 && comedi_num_legacy_minors == 0)
comedi_num_legacy_minors = 16;
memset(comedi_file_info_table, 0,
sizeof(struct comedi_device_file_info *) * COMEDI_NUM_MINORS);
retval = register_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS, "comedi");
if (retval)
return -EIO;
cdev_init(&comedi_cdev, &comedi_fops);
comedi_cdev.owner = THIS_MODULE;
kobject_set_name(&comedi_cdev.kobj, "comedi");
if (cdev_add(&comedi_cdev, MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS)) {
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return -EIO;
}
comedi_class = class_create(THIS_MODULE, "comedi");
if (IS_ERR(comedi_class)) {
printk(KERN_ERR "comedi: failed to create class");
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return PTR_ERR(comedi_class);
}
/* XXX requires /proc interface */
comedi_proc_init();
/* create devices files for legacy/manual use */
for (i = 0; i < comedi_num_legacy_minors; i++) {
int minor;
minor = comedi_alloc_board_minor(NULL);
if (minor < 0) {
comedi_cleanup_legacy_minors();
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return minor;
}
}
return 0;
}
static void __exit comedi_cleanup(void)
{
int i;
comedi_cleanup_legacy_minors();
for (i = 0; i < COMEDI_NUM_MINORS; ++i)
BUG_ON(comedi_file_info_table[i]);
class_destroy(comedi_class);
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS);
comedi_proc_cleanup();
}
module_init(comedi_init);
module_exit(comedi_cleanup);
void comedi_error(const struct comedi_device *dev, const char *s)
{
printk(KERN_ERR "comedi%d: %s: %s\n", dev->minor,
dev->driver->driver_name, s);
}
EXPORT_SYMBOL(comedi_error);
void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
unsigned runflags = 0;
unsigned runflags_mask = 0;
/* DPRINTK("comedi_event 0x%x\n",mask); */
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) == 0)
return;
if (s->
async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_RUNNING;
}
/* remember if an error event has occurred, so an error
* can be returned the next time the user does a read() */
if (s->async->events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_ERROR;
runflags |= SRF_ERROR;
}
if (runflags_mask) {
/*sets SRF_ERROR and SRF_RUNNING together atomically */
comedi_set_subdevice_runflags(s, runflags_mask, runflags);
}
if (async->cb_mask & s->async->events) {
if (comedi_get_subdevice_runflags(s) & SRF_USER) {
wake_up_interruptible(&async->wait_head);
if (s->subdev_flags & SDF_CMD_READ)
kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
if (s->subdev_flags & SDF_CMD_WRITE)
kill_fasync(&dev->async_queue, SIGIO, POLL_OUT);
} else {
if (async->cb_func)
async->cb_func(s->async->events, async->cb_arg);
}
}
s->async->events = 0;
}
EXPORT_SYMBOL(comedi_event);
unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s)
{
unsigned long flags;
unsigned runflags;
spin_lock_irqsave(&s->spin_lock, flags);
runflags = s->runflags;
spin_unlock_irqrestore(&s->spin_lock, flags);
return runflags;
}
EXPORT_SYMBOL(comedi_get_subdevice_runflags);
static int is_device_busy(struct comedi_device *dev)
{
struct comedi_subdevice *s;
int i;
if (!dev->attached)
return 0;
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy)
return 1;
if (s->async && s->async->mmap_count)
return 1;
}
return 0;
}
static void comedi_device_init(struct comedi_device *dev)
{
memset(dev, 0, sizeof(struct comedi_device));
spin_lock_init(&dev->spinlock);
mutex_init(&dev->mutex);
dev->minor = -1;
}
static void comedi_device_cleanup(struct comedi_device *dev)
{
if (dev == NULL)
return;
mutex_lock(&dev->mutex);
comedi_device_detach(dev);
mutex_unlock(&dev->mutex);
mutex_destroy(&dev->mutex);
}
int comedi_alloc_board_minor(struct device *hardware_device)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kzalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = kzalloc(sizeof(struct comedi_device), GFP_KERNEL);
if (info->device == NULL) {
kfree(info);
return -ENOMEM;
}
comedi_device_init(info->device);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_BOARD_MINORS) {
comedi_device_cleanup(info->device);
kfree(info->device);
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
info->device->minor = i;
csdev = device_create(comedi_class, hardware_device,
MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i", i);
if (!IS_ERR(csdev))
info->device->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
return i;
}
void comedi_free_board_minor(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
comedi_file_info_table[minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (info) {
struct comedi_device *dev = info->device;
if (dev) {
if (dev->class_dev) {
device_destroy(comedi_class,
MKDEV(COMEDI_MAJOR, dev->minor));
}
comedi_device_cleanup(dev);
kfree(dev);
}
kfree(info);
}
}
int comedi_alloc_subdevice_minor(struct comedi_device *dev,
struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kmalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = dev;
info->read_subdevice = s;
info->write_subdevice = s;
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = COMEDI_FIRST_SUBDEVICE_MINOR; i < COMEDI_NUM_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_MINORS) {
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
s->minor = i;
csdev = device_create(comedi_class, dev->class_dev,
MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i_subd%i",
dev->minor, (int)(s - dev->subdevices));
if (!IS_ERR(csdev))
s->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
return i;
}
void comedi_free_subdevice_minor(struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
if (s == NULL)
return;
if (s->minor < 0)
return;
BUG_ON(s->minor >= COMEDI_NUM_MINORS);
BUG_ON(s->minor < COMEDI_FIRST_SUBDEVICE_MINOR);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[s->minor];
comedi_file_info_table[s->minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (s->class_dev) {
device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor));
s->class_dev = NULL;
}
kfree(info);
}
struct comedi_device_file_info *comedi_get_device_file_info(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
return info;
}
EXPORT_SYMBOL_GPL(comedi_get_device_file_info);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size)
{
int retval;
if (new_size > async->max_bufsize)
return -EPERM;
if (s->busy) {
DPRINTK("subdevice is busy, cannot resize buffer\n");
return -EBUSY;
}
if (async->mmap_count) {
DPRINTK("subdevice is mmapped, cannot resize buffer\n");
return -EBUSY;
}
if (!async->prealloc_buf)
return -EINVAL;
/* make sure buffer is an integral number of pages
* (we round up) */
new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK;
retval = comedi_buf_alloc(dev, s, new_size);
if (retval < 0)
return retval;
if (s->buf_change) {
retval = s->buf_change(dev, s, new_size);
if (retval < 0)
return retval;
}
DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
dev->minor, (int)(s - dev->subdevices), async->prealloc_bufsz);
return 0;
}
/* sysfs attribute files */
static const unsigned bytes_per_kibi = 1024;
static ssize_t show_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
max_buffer_size_kb = read_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_max_size_kb;
unsigned int new_max_size;
int ret;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
ret = kstrtouint(buf, 10, &new_max_size_kb);
if (ret)
return ret;
if (new_max_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_max_size = new_max_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
read_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_read_buffer_kb = {
.attr = {
.name = "max_read_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_read_buffer_kb,
.store = &store_max_read_buffer_kb
};
static ssize_t show_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
buffer_size_kb = read_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_size_kb;
unsigned int new_size;
int retval;
int ret;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
ret = kstrtouint(buf, 10, &new_size_kb);
if (ret)
return ret;
if (new_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_size = new_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, read_subdevice,
read_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_read_buffer_kb = {
.attr = {
.name = "read_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_read_buffer_kb,
.store = &store_read_buffer_kb
};
static ssize_t show_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
max_buffer_size_kb = write_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_max_size_kb;
unsigned int new_max_size;
int ret;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
ret = kstrtouint(buf, 10, &new_max_size_kb);
if (ret)
return ret;
if (new_max_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_max_size = new_max_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
write_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_write_buffer_kb = {
.attr = {
.name = "max_write_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_write_buffer_kb,
.store = &store_max_write_buffer_kb
};
static ssize_t show_write_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
buffer_size_kb = write_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_size_kb;
unsigned int new_size;
int retval;
int ret;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
ret = kstrtouint(buf, 10, &new_size_kb);
if (ret)
return ret;
if (new_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_size = ((uint64_t) new_size_kb) * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, write_subdevice,
write_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_write_buffer_kb = {
.attr = {
.name = "write_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_write_buffer_kb,
.store = &store_write_buffer_kb
};
| gpl-2.0 |
wrxtasy/linux | drivers/char/agp/uninorth-agp.c | 4065 | 18337 | /*
* UniNorth AGPGART routines.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/agp_backend.h>
#include <linux/delay.h>
#include <linux/vmalloc.h>
#include <asm/uninorth.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#include <asm/pmac_feature.h>
#include "agp.h"
/*
* NOTES for uninorth3 (G5 AGP) supports :
*
* There maybe also possibility to have bigger cache line size for
* agp (see pmac_pci.c and look for cache line). Need to be investigated
* by someone.
*
* PAGE size are hardcoded but this may change, see asm/page.h.
*
* Jerome Glisse <j.glisse@gmail.com>
*/
static int uninorth_rev;
static int is_u3;
static u32 scratch_value;
#define DEFAULT_APERTURE_SIZE 256
#define DEFAULT_APERTURE_STRING "256"
static char *aperture = NULL;
static int uninorth_fetch_size(void)
{
int i, size = 0;
struct aper_size_info_32 *values =
A_SIZE_32(agp_bridge->driver->aperture_sizes);
if (aperture) {
char *save = aperture;
size = memparse(aperture, &aperture) >> 20;
aperture = save;
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++)
if (size == values[i].size)
break;
if (i == agp_bridge->driver->num_aperture_sizes) {
dev_err(&agp_bridge->dev->dev, "invalid aperture size, "
"using default\n");
size = 0;
aperture = NULL;
}
}
if (!size) {
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++)
if (values[i].size == DEFAULT_APERTURE_SIZE)
break;
}
agp_bridge->previous_size =
agp_bridge->current_size = (void *)(values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
static void uninorth_tlbflush(struct agp_memory *mem)
{
u32 ctrl = UNI_N_CFG_GART_ENABLE;
if (is_u3)
ctrl |= U3_N_CFG_GART_PERFRD;
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL,
ctrl | UNI_N_CFG_GART_INVAL);
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL, ctrl);
if (!mem && uninorth_rev <= 0x30) {
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL,
ctrl | UNI_N_CFG_GART_2xRESET);
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL,
ctrl);
}
}
static void uninorth_cleanup(void)
{
u32 tmp;
pci_read_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL, &tmp);
if (!(tmp & UNI_N_CFG_GART_ENABLE))
return;
tmp |= UNI_N_CFG_GART_INVAL;
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL, tmp);
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL, 0);
if (uninorth_rev <= 0x30) {
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL,
UNI_N_CFG_GART_2xRESET);
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_GART_CTRL,
0);
}
}
static int uninorth_configure(void)
{
struct aper_size_info_32 *current_size;
current_size = A_SIZE_32(agp_bridge->current_size);
dev_info(&agp_bridge->dev->dev, "configuring for size idx: %d\n",
current_size->size_value);
/* aperture size and gatt addr */
pci_write_config_dword(agp_bridge->dev,
UNI_N_CFG_GART_BASE,
(agp_bridge->gatt_bus_addr & 0xfffff000)
| current_size->size_value);
/* HACK ALERT
* UniNorth seem to be buggy enough not to handle properly when
* the AGP aperture isn't mapped at bus physical address 0
*/
agp_bridge->gart_bus_addr = 0;
#ifdef CONFIG_PPC64
/* Assume U3 or later on PPC64 systems */
/* high 4 bits of GART physical address go in UNI_N_CFG_AGP_BASE */
pci_write_config_dword(agp_bridge->dev, UNI_N_CFG_AGP_BASE,
(agp_bridge->gatt_bus_addr >> 32) & 0xf);
#else
pci_write_config_dword(agp_bridge->dev,
UNI_N_CFG_AGP_BASE, agp_bridge->gart_bus_addr);
#endif
if (is_u3) {
pci_write_config_dword(agp_bridge->dev,
UNI_N_CFG_GART_DUMMY_PAGE,
page_to_phys(agp_bridge->scratch_page_page) >> 12);
}
return 0;
}
static int uninorth_insert_memory(struct agp_memory *mem, off_t pg_start, int type)
{
int i, num_entries;
void *temp;
u32 *gp;
int mask_type;
if (type != mem->type)
return -EINVAL;
mask_type = agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type);
if (mask_type != 0) {
/* We know nothing of memory types */
return -EINVAL;
}
if (mem->page_count == 0)
return 0;
temp = agp_bridge->current_size;
num_entries = A_SIZE_32(temp)->num_entries;
if ((pg_start + mem->page_count) > num_entries)
return -EINVAL;
gp = (u32 *) &agp_bridge->gatt_table[pg_start];
for (i = 0; i < mem->page_count; ++i) {
if (gp[i] != scratch_value) {
dev_info(&agp_bridge->dev->dev,
"uninorth_insert_memory: entry 0x%x occupied (%x)\n",
i, gp[i]);
return -EBUSY;
}
}
for (i = 0; i < mem->page_count; i++) {
if (is_u3)
gp[i] = (page_to_phys(mem->pages[i]) >> PAGE_SHIFT) | 0x80000000UL;
else
gp[i] = cpu_to_le32((page_to_phys(mem->pages[i]) & 0xFFFFF000UL) |
0x1UL);
flush_dcache_range((unsigned long)__va(page_to_phys(mem->pages[i])),
(unsigned long)__va(page_to_phys(mem->pages[i]))+0x1000);
}
mb();
uninorth_tlbflush(mem);
return 0;
}
int uninorth_remove_memory(struct agp_memory *mem, off_t pg_start, int type)
{
size_t i;
u32 *gp;
int mask_type;
if (type != mem->type)
return -EINVAL;
mask_type = agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type);
if (mask_type != 0) {
/* We know nothing of memory types */
return -EINVAL;
}
if (mem->page_count == 0)
return 0;
gp = (u32 *) &agp_bridge->gatt_table[pg_start];
for (i = 0; i < mem->page_count; ++i) {
gp[i] = scratch_value;
}
mb();
uninorth_tlbflush(mem);
return 0;
}
static void uninorth_agp_enable(struct agp_bridge_data *bridge, u32 mode)
{
u32 command, scratch, status;
int timeout;
pci_read_config_dword(bridge->dev,
bridge->capndx + PCI_AGP_STATUS,
&status);
command = agp_collect_device_status(bridge, mode, status);
command |= PCI_AGP_COMMAND_AGP;
if (uninorth_rev == 0x21) {
/*
* Darwin disable AGP 4x on this revision, thus we
* may assume it's broken. This is an AGP2 controller.
*/
command &= ~AGPSTAT2_4X;
}
if ((uninorth_rev >= 0x30) && (uninorth_rev <= 0x33)) {
/*
* We need to set REQ_DEPTH to 7 for U3 versions 1.0, 2.1,
* 2.2 and 2.3, Darwin do so.
*/
if ((command >> AGPSTAT_RQ_DEPTH_SHIFT) > 7)
command = (command & ~AGPSTAT_RQ_DEPTH)
| (7 << AGPSTAT_RQ_DEPTH_SHIFT);
}
uninorth_tlbflush(NULL);
timeout = 0;
do {
pci_write_config_dword(bridge->dev,
bridge->capndx + PCI_AGP_COMMAND,
command);
pci_read_config_dword(bridge->dev,
bridge->capndx + PCI_AGP_COMMAND,
&scratch);
} while ((scratch & PCI_AGP_COMMAND_AGP) == 0 && ++timeout < 1000);
if ((scratch & PCI_AGP_COMMAND_AGP) == 0)
dev_err(&bridge->dev->dev, "can't write UniNorth AGP "
"command register\n");
if (uninorth_rev >= 0x30) {
/* This is an AGP V3 */
agp_device_command(command, (status & AGPSTAT_MODE_3_0) != 0);
} else {
/* AGP V2 */
agp_device_command(command, false);
}
uninorth_tlbflush(NULL);
}
#ifdef CONFIG_PM
/*
* These Power Management routines are _not_ called by the normal PCI PM layer,
* but directly by the video driver through function pointers in the device
* tree.
*/
static int agp_uninorth_suspend(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge;
u32 cmd;
u8 agp;
struct pci_dev *device = NULL;
bridge = agp_find_bridge(pdev);
if (bridge == NULL)
return -ENODEV;
/* Only one suspend supported */
if (bridge->dev_private_data)
return 0;
/* turn off AGP on the video chip, if it was enabled */
for_each_pci_dev(device) {
/* Don't touch the bridge yet, device first */
if (device == pdev)
continue;
/* Only deal with devices on the same bus here, no Mac has a P2P
* bridge on the AGP port, and mucking around the entire PCI
* tree is source of problems on some machines because of a bug
* in some versions of pci_find_capability() when hitting a dead
* device
*/
if (device->bus != pdev->bus)
continue;
agp = pci_find_capability(device, PCI_CAP_ID_AGP);
if (!agp)
continue;
pci_read_config_dword(device, agp + PCI_AGP_COMMAND, &cmd);
if (!(cmd & PCI_AGP_COMMAND_AGP))
continue;
dev_info(&pdev->dev, "disabling AGP on device %s\n",
pci_name(device));
cmd &= ~PCI_AGP_COMMAND_AGP;
pci_write_config_dword(device, agp + PCI_AGP_COMMAND, cmd);
}
/* turn off AGP on the bridge */
agp = pci_find_capability(pdev, PCI_CAP_ID_AGP);
pci_read_config_dword(pdev, agp + PCI_AGP_COMMAND, &cmd);
bridge->dev_private_data = (void *)(long)cmd;
if (cmd & PCI_AGP_COMMAND_AGP) {
dev_info(&pdev->dev, "disabling AGP on bridge\n");
cmd &= ~PCI_AGP_COMMAND_AGP;
pci_write_config_dword(pdev, agp + PCI_AGP_COMMAND, cmd);
}
/* turn off the GART */
uninorth_cleanup();
return 0;
}
static int agp_uninorth_resume(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge;
u32 command;
bridge = agp_find_bridge(pdev);
if (bridge == NULL)
return -ENODEV;
command = (long)bridge->dev_private_data;
bridge->dev_private_data = NULL;
if (!(command & PCI_AGP_COMMAND_AGP))
return 0;
uninorth_agp_enable(bridge, command);
return 0;
}
#endif /* CONFIG_PM */
static int uninorth_create_gatt_table(struct agp_bridge_data *bridge)
{
char *table;
char *table_end;
int size;
int page_order;
int num_entries;
int i;
void *temp;
struct page *page;
struct page **pages;
/* We can't handle 2 level gatt's */
if (bridge->driver->size_type == LVL2_APER_SIZE)
return -EINVAL;
table = NULL;
i = bridge->aperture_size_idx;
temp = bridge->current_size;
size = page_order = num_entries = 0;
do {
size = A_SIZE_32(temp)->size;
page_order = A_SIZE_32(temp)->page_order;
num_entries = A_SIZE_32(temp)->num_entries;
table = (char *) __get_free_pages(GFP_KERNEL, page_order);
if (table == NULL) {
i++;
bridge->current_size = A_IDX32(bridge);
} else {
bridge->aperture_size_idx = i;
}
} while (!table && (i < bridge->driver->num_aperture_sizes));
if (table == NULL)
return -ENOMEM;
pages = kmalloc((1 << page_order) * sizeof(struct page*), GFP_KERNEL);
if (pages == NULL)
goto enomem;
table_end = table + ((PAGE_SIZE * (1 << page_order)) - 1);
for (page = virt_to_page(table), i = 0; page <= virt_to_page(table_end);
page++, i++) {
SetPageReserved(page);
pages[i] = page;
}
bridge->gatt_table_real = (u32 *) table;
/* Need to clear out any dirty data still sitting in caches */
flush_dcache_range((unsigned long)table,
(unsigned long)table_end + 1);
bridge->gatt_table = vmap(pages, (1 << page_order), 0, PAGE_KERNEL_NCG);
if (bridge->gatt_table == NULL)
goto enomem;
bridge->gatt_bus_addr = virt_to_phys(table);
if (is_u3)
scratch_value = (page_to_phys(agp_bridge->scratch_page_page) >> PAGE_SHIFT) | 0x80000000UL;
else
scratch_value = cpu_to_le32((page_to_phys(agp_bridge->scratch_page_page) & 0xFFFFF000UL) |
0x1UL);
for (i = 0; i < num_entries; i++)
bridge->gatt_table[i] = scratch_value;
return 0;
enomem:
kfree(pages);
if (table)
free_pages((unsigned long)table, page_order);
return -ENOMEM;
}
static int uninorth_free_gatt_table(struct agp_bridge_data *bridge)
{
int page_order;
char *table, *table_end;
void *temp;
struct page *page;
temp = bridge->current_size;
page_order = A_SIZE_32(temp)->page_order;
/* Do not worry about freeing memory, because if this is
* called, then all agp memory is deallocated and removed
* from the table.
*/
vunmap(bridge->gatt_table);
table = (char *) bridge->gatt_table_real;
table_end = table + ((PAGE_SIZE * (1 << page_order)) - 1);
for (page = virt_to_page(table); page <= virt_to_page(table_end); page++)
ClearPageReserved(page);
free_pages((unsigned long) bridge->gatt_table_real, page_order);
return 0;
}
void null_cache_flush(void)
{
mb();
}
/* Setup function */
static const struct aper_size_info_32 uninorth_sizes[] =
{
{256, 65536, 6, 64},
{128, 32768, 5, 32},
{64, 16384, 4, 16},
{32, 8192, 3, 8},
{16, 4096, 2, 4},
{8, 2048, 1, 2},
{4, 1024, 0, 1}
};
/*
* Not sure that u3 supports that high aperture sizes but it
* would strange if it did not :)
*/
static const struct aper_size_info_32 u3_sizes[] =
{
{512, 131072, 7, 128},
{256, 65536, 6, 64},
{128, 32768, 5, 32},
{64, 16384, 4, 16},
{32, 8192, 3, 8},
{16, 4096, 2, 4},
{8, 2048, 1, 2},
{4, 1024, 0, 1}
};
const struct agp_bridge_driver uninorth_agp_driver = {
.owner = THIS_MODULE,
.aperture_sizes = (void *)uninorth_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = ARRAY_SIZE(uninorth_sizes),
.configure = uninorth_configure,
.fetch_size = uninorth_fetch_size,
.cleanup = uninorth_cleanup,
.tlb_flush = uninorth_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.cache_flush = null_cache_flush,
.agp_enable = uninorth_agp_enable,
.create_gatt_table = uninorth_create_gatt_table,
.free_gatt_table = uninorth_free_gatt_table,
.insert_memory = uninorth_insert_memory,
.remove_memory = uninorth_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
.cant_use_aperture = true,
.needs_scratch_page = true,
};
const struct agp_bridge_driver u3_agp_driver = {
.owner = THIS_MODULE,
.aperture_sizes = (void *)u3_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = ARRAY_SIZE(u3_sizes),
.configure = uninorth_configure,
.fetch_size = uninorth_fetch_size,
.cleanup = uninorth_cleanup,
.tlb_flush = uninorth_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.cache_flush = null_cache_flush,
.agp_enable = uninorth_agp_enable,
.create_gatt_table = uninorth_create_gatt_table,
.free_gatt_table = uninorth_free_gatt_table,
.insert_memory = uninorth_insert_memory,
.remove_memory = uninorth_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
.cant_use_aperture = true,
.needs_scratch_page = true,
};
static struct agp_device_ids uninorth_agp_device_ids[] = {
{
.device_id = PCI_DEVICE_ID_APPLE_UNI_N_AGP,
.chipset_name = "UniNorth",
},
{
.device_id = PCI_DEVICE_ID_APPLE_UNI_N_AGP_P,
.chipset_name = "UniNorth/Pangea",
},
{
.device_id = PCI_DEVICE_ID_APPLE_UNI_N_AGP15,
.chipset_name = "UniNorth 1.5",
},
{
.device_id = PCI_DEVICE_ID_APPLE_UNI_N_AGP2,
.chipset_name = "UniNorth 2",
},
{
.device_id = PCI_DEVICE_ID_APPLE_U3_AGP,
.chipset_name = "U3",
},
{
.device_id = PCI_DEVICE_ID_APPLE_U3L_AGP,
.chipset_name = "U3L",
},
{
.device_id = PCI_DEVICE_ID_APPLE_U3H_AGP,
.chipset_name = "U3H",
},
{
.device_id = PCI_DEVICE_ID_APPLE_IPID2_AGP,
.chipset_name = "UniNorth/Intrepid2",
},
};
static int agp_uninorth_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_device_ids *devs = uninorth_agp_device_ids;
struct agp_bridge_data *bridge;
struct device_node *uninorth_node;
u8 cap_ptr;
int j;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (cap_ptr == 0)
return -ENODEV;
/* probe for known chipsets */
for (j = 0; devs[j].chipset_name != NULL; ++j) {
if (pdev->device == devs[j].device_id) {
dev_info(&pdev->dev, "Apple %s chipset\n",
devs[j].chipset_name);
goto found;
}
}
dev_err(&pdev->dev, "unsupported Apple chipset [%04x/%04x]\n",
pdev->vendor, pdev->device);
return -ENODEV;
found:
/* Set revision to 0 if we could not read it. */
uninorth_rev = 0;
is_u3 = 0;
/* Locate core99 Uni-N */
uninorth_node = of_find_node_by_name(NULL, "uni-n");
/* Locate G5 u3 */
if (uninorth_node == NULL) {
is_u3 = 1;
uninorth_node = of_find_node_by_name(NULL, "u3");
}
if (uninorth_node) {
const int *revprop = of_get_property(uninorth_node,
"device-rev", NULL);
if (revprop != NULL)
uninorth_rev = *revprop & 0x3f;
of_node_put(uninorth_node);
}
#ifdef CONFIG_PM
/* Inform platform of our suspend/resume caps */
pmac_register_agp_pm(pdev, agp_uninorth_suspend, agp_uninorth_resume);
#endif
/* Allocate & setup our driver */
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
if (is_u3)
bridge->driver = &u3_agp_driver;
else
bridge->driver = &uninorth_agp_driver;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
bridge->flags = AGP_ERRATA_FASTWRITES;
/* Fill in the mode register */
pci_read_config_dword(pdev, cap_ptr+PCI_AGP_STATUS, &bridge->mode);
pci_set_drvdata(pdev, bridge);
return agp_add_bridge(bridge);
}
static void agp_uninorth_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
#ifdef CONFIG_PM
/* Inform platform of our suspend/resume caps */
pmac_register_agp_pm(pdev, NULL, NULL);
#endif
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
}
static struct pci_device_id agp_uninorth_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_APPLE,
.device = PCI_ANY_ID,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_uninorth_pci_table);
static struct pci_driver agp_uninorth_pci_driver = {
.name = "agpgart-uninorth",
.id_table = agp_uninorth_pci_table,
.probe = agp_uninorth_probe,
.remove = agp_uninorth_remove,
};
static int __init agp_uninorth_init(void)
{
if (agp_off)
return -EINVAL;
return pci_register_driver(&agp_uninorth_pci_driver);
}
static void __exit agp_uninorth_cleanup(void)
{
pci_unregister_driver(&agp_uninorth_pci_driver);
}
module_init(agp_uninorth_init);
module_exit(agp_uninorth_cleanup);
module_param(aperture, charp, 0);
MODULE_PARM_DESC(aperture,
"Aperture size, must be power of two between 4MB and an\n"
"\t\tupper limit specific to the UniNorth revision.\n"
"\t\tDefault: " DEFAULT_APERTURE_STRING "M");
MODULE_AUTHOR("Ben Herrenschmidt & Paul Mackerras");
MODULE_LICENSE("GPL");
| gpl-2.0 |
yank555-lu/N3-Sourcedrops | arch/arm/plat-s5p/irq-gpioint.c | 4577 | 5649 | /* linux/arch/arm/plat-s5p/irq-gpioint.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* Author: Kyungmin Park <kyungmin.park@samsung.com>
* Author: Joonyoung Shim <jy0922.shim@samsung.com>
* Author: Marek Szyprowski <m.szyprowski@samsung.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <mach/map.h>
#include <plat/gpio-core.h>
#include <plat/gpio-cfg.h>
#include <asm/mach/irq.h>
#define GPIO_BASE(chip) (((unsigned long)(chip)->base) & 0xFFFFF000u)
#define CON_OFFSET 0x700
#define MASK_OFFSET 0x900
#define PEND_OFFSET 0xA00
#define REG_OFFSET(x) ((x) << 2)
struct s5p_gpioint_bank {
struct list_head list;
int start;
int nr_groups;
int irq;
struct samsung_gpio_chip **chips;
void (*handler)(unsigned int, struct irq_desc *);
};
static LIST_HEAD(banks);
static int s5p_gpioint_set_type(struct irq_data *d, unsigned int type)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
struct irq_chip_type *ct = gc->chip_types;
unsigned int shift = (d->irq - gc->irq_base) << 2;
switch (type) {
case IRQ_TYPE_EDGE_RISING:
type = S5P_IRQ_TYPE_EDGE_RISING;
break;
case IRQ_TYPE_EDGE_FALLING:
type = S5P_IRQ_TYPE_EDGE_FALLING;
break;
case IRQ_TYPE_EDGE_BOTH:
type = S5P_IRQ_TYPE_EDGE_BOTH;
break;
case IRQ_TYPE_LEVEL_HIGH:
type = S5P_IRQ_TYPE_LEVEL_HIGH;
break;
case IRQ_TYPE_LEVEL_LOW:
type = S5P_IRQ_TYPE_LEVEL_LOW;
break;
case IRQ_TYPE_NONE:
default:
printk(KERN_WARNING "No irq type\n");
return -EINVAL;
}
gc->type_cache &= ~(0x7 << shift);
gc->type_cache |= type << shift;
writel(gc->type_cache, gc->reg_base + ct->regs.type);
return 0;
}
static void s5p_gpioint_handler(unsigned int irq, struct irq_desc *desc)
{
struct s5p_gpioint_bank *bank = irq_get_handler_data(irq);
int group, pend_offset, mask_offset;
unsigned int pend, mask;
struct irq_chip *chip = irq_get_chip(irq);
chained_irq_enter(chip, desc);
for (group = 0; group < bank->nr_groups; group++) {
struct samsung_gpio_chip *chip = bank->chips[group];
if (!chip)
continue;
pend_offset = REG_OFFSET(group);
pend = __raw_readl(GPIO_BASE(chip) + PEND_OFFSET + pend_offset);
if (!pend)
continue;
mask_offset = REG_OFFSET(group);
mask = __raw_readl(GPIO_BASE(chip) + MASK_OFFSET + mask_offset);
pend &= ~mask;
while (pend) {
int offset = fls(pend) - 1;
int real_irq = chip->irq_base + offset;
generic_handle_irq(real_irq);
pend &= ~BIT(offset);
}
}
chained_irq_exit(chip, desc);
}
static __init int s5p_gpioint_add(struct samsung_gpio_chip *chip)
{
static int used_gpioint_groups = 0;
int group = chip->group;
struct s5p_gpioint_bank *b, *bank = NULL;
struct irq_chip_generic *gc;
struct irq_chip_type *ct;
if (used_gpioint_groups >= S5P_GPIOINT_GROUP_COUNT)
return -ENOMEM;
list_for_each_entry(b, &banks, list) {
if (group >= b->start && group < b->start + b->nr_groups) {
bank = b;
break;
}
}
if (!bank)
return -EINVAL;
if (!bank->handler) {
bank->chips = kzalloc(sizeof(struct samsung_gpio_chip *) *
bank->nr_groups, GFP_KERNEL);
if (!bank->chips)
return -ENOMEM;
irq_set_chained_handler(bank->irq, s5p_gpioint_handler);
irq_set_handler_data(bank->irq, bank);
bank->handler = s5p_gpioint_handler;
printk(KERN_INFO "Registered chained gpio int handler for interrupt %d.\n",
bank->irq);
}
/*
* chained GPIO irq has been successfully registered, allocate new gpio
* int group and assign irq nubmers
*/
chip->irq_base = S5P_GPIOINT_BASE +
used_gpioint_groups * S5P_GPIOINT_GROUP_SIZE;
used_gpioint_groups++;
bank->chips[group - bank->start] = chip;
gc = irq_alloc_generic_chip("s5p_gpioint", 1, chip->irq_base,
(void __iomem *)GPIO_BASE(chip),
handle_level_irq);
if (!gc)
return -ENOMEM;
ct = gc->chip_types;
ct->chip.irq_ack = irq_gc_ack_set_bit;
ct->chip.irq_mask = irq_gc_mask_set_bit;
ct->chip.irq_unmask = irq_gc_mask_clr_bit;
ct->chip.irq_set_type = s5p_gpioint_set_type,
ct->regs.ack = PEND_OFFSET + REG_OFFSET(group - bank->start);
ct->regs.mask = MASK_OFFSET + REG_OFFSET(group - bank->start);
ct->regs.type = CON_OFFSET + REG_OFFSET(group - bank->start);
irq_setup_generic_chip(gc, IRQ_MSK(chip->chip.ngpio),
IRQ_GC_INIT_MASK_CACHE,
IRQ_NOREQUEST | IRQ_NOPROBE, 0);
return 0;
}
int __init s5p_register_gpio_interrupt(int pin)
{
struct samsung_gpio_chip *my_chip = samsung_gpiolib_getchip(pin);
int offset, group;
int ret;
if (!my_chip)
return -EINVAL;
offset = pin - my_chip->chip.base;
group = my_chip->group;
/* check if the group has been already registered */
if (my_chip->irq_base)
return my_chip->irq_base + offset;
/* register gpio group */
ret = s5p_gpioint_add(my_chip);
if (ret == 0) {
my_chip->chip.to_irq = samsung_gpiolib_to_irq;
printk(KERN_INFO "Registered interrupt support for gpio group %d.\n",
group);
return my_chip->irq_base + offset;
}
return ret;
}
int __init s5p_register_gpioint_bank(int chain_irq, int start, int nr_groups)
{
struct s5p_gpioint_bank *bank;
bank = kzalloc(sizeof(*bank), GFP_KERNEL);
if (!bank)
return -ENOMEM;
bank->start = start;
bank->nr_groups = nr_groups;
bank->irq = chain_irq;
list_add_tail(&bank->list, &banks);
return 0;
}
| gpl-2.0 |
18712886438/android_kernel_motorola_quark | drivers/video/sis/initextlfb.c | 4833 | 7140 | /*
* SiS 300/540/630[S]/730[S]
* SiS 315[E|PRO]/550/[M]65x/[M]66x[F|M|G]X/[M]74x[GX]/330/[M]76x[GX]
* XGI V3XT/V5/V8, Z7
* frame buffer driver for Linux kernels >= 2.4.14 and >=2.6.3
*
* Linux kernel specific extensions to init.c/init301.c
*
* Copyright (C) 2001-2005 Thomas Winischhofer, Vienna, Austria.
*
* 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 named License,
* or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
*
* Author: Thomas Winischhofer <thomas@winischhofer.net>
*/
#include "initdef.h"
#include "vgatypes.h"
#include "vstruct.h"
#include <linux/types.h>
#include <linux/fb.h>
int sisfb_mode_rate_to_dclock(struct SiS_Private *SiS_Pr,
unsigned char modeno, unsigned char rateindex);
int sisfb_mode_rate_to_ddata(struct SiS_Private *SiS_Pr, unsigned char modeno,
unsigned char rateindex, struct fb_var_screeninfo *var);
bool sisfb_gettotalfrommode(struct SiS_Private *SiS_Pr, unsigned char modeno,
int *htotal, int *vtotal, unsigned char rateindex);
extern bool SiSInitPtr(struct SiS_Private *SiS_Pr);
extern bool SiS_SearchModeID(struct SiS_Private *SiS_Pr, unsigned short *ModeNo,
unsigned short *ModeIdIndex);
extern void SiS_Generic_ConvertCRData(struct SiS_Private *SiS_Pr, unsigned char *crdata,
int xres, int yres, struct fb_var_screeninfo *var, bool writeres);
int
sisfb_mode_rate_to_dclock(struct SiS_Private *SiS_Pr, unsigned char modeno,
unsigned char rateindex)
{
unsigned short ModeNo = modeno;
unsigned short ModeIdIndex = 0, ClockIndex = 0;
unsigned short RRTI = 0;
int Clock;
if(!SiSInitPtr(SiS_Pr)) return 65000;
if(rateindex > 0) rateindex--;
#ifdef CONFIG_FB_SIS_315
switch(ModeNo) {
case 0x5a: ModeNo = 0x50; break;
case 0x5b: ModeNo = 0x56;
}
#endif
if(!(SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex))) {
printk(KERN_ERR "Could not find mode %x\n", ModeNo);
return 65000;
}
RRTI = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].REFindex;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & HaveWideTiming) {
if(SiS_Pr->SiS_UseWide == 1) {
/* Wide screen: Ignore rateindex */
ClockIndex = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRTVCLK_WIDE;
} else {
RRTI += rateindex;
ClockIndex = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRTVCLK_NORM;
}
} else {
RRTI += rateindex;
ClockIndex = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRTVCLK;
}
Clock = SiS_Pr->SiS_VCLKData[ClockIndex].CLOCK * 1000;
return Clock;
}
int
sisfb_mode_rate_to_ddata(struct SiS_Private *SiS_Pr, unsigned char modeno,
unsigned char rateindex, struct fb_var_screeninfo *var)
{
unsigned short ModeNo = modeno;
unsigned short ModeIdIndex = 0, index = 0, RRTI = 0;
int j;
if(!SiSInitPtr(SiS_Pr)) return 0;
if(rateindex > 0) rateindex--;
#ifdef CONFIG_FB_SIS_315
switch(ModeNo) {
case 0x5a: ModeNo = 0x50; break;
case 0x5b: ModeNo = 0x56;
}
#endif
if(!(SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex))) return 0;
RRTI = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].REFindex;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & HaveWideTiming) {
if(SiS_Pr->SiS_UseWide == 1) {
/* Wide screen: Ignore rateindex */
index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC_WIDE;
} else {
RRTI += rateindex;
index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC_NORM;
}
} else {
RRTI += rateindex;
index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC;
}
SiS_Generic_ConvertCRData(SiS_Pr,
(unsigned char *)&SiS_Pr->SiS_CRT1Table[index].CR[0],
SiS_Pr->SiS_RefIndex[RRTI].XRes,
SiS_Pr->SiS_RefIndex[RRTI].YRes,
var, false);
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & 0x8000)
var->sync &= ~FB_SYNC_VERT_HIGH_ACT;
else
var->sync |= FB_SYNC_VERT_HIGH_ACT;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & 0x4000)
var->sync &= ~FB_SYNC_HOR_HIGH_ACT;
else
var->sync |= FB_SYNC_HOR_HIGH_ACT;
var->vmode = FB_VMODE_NONINTERLACED;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & 0x0080)
var->vmode = FB_VMODE_INTERLACED;
else {
j = 0;
while(SiS_Pr->SiS_EModeIDTable[j].Ext_ModeID != 0xff) {
if(SiS_Pr->SiS_EModeIDTable[j].Ext_ModeID ==
SiS_Pr->SiS_RefIndex[RRTI].ModeID) {
if(SiS_Pr->SiS_EModeIDTable[j].Ext_ModeFlag & DoubleScanMode) {
var->vmode = FB_VMODE_DOUBLE;
}
break;
}
j++;
}
}
if((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) {
#if 0 /* Do this? */
var->upper_margin <<= 1;
var->lower_margin <<= 1;
var->vsync_len <<= 1;
#endif
} else if((var->vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
var->upper_margin >>= 1;
var->lower_margin >>= 1;
var->vsync_len >>= 1;
}
return 1;
}
bool
sisfb_gettotalfrommode(struct SiS_Private *SiS_Pr, unsigned char modeno, int *htotal,
int *vtotal, unsigned char rateindex)
{
unsigned short ModeNo = modeno;
unsigned short ModeIdIndex = 0, CRT1Index = 0;
unsigned short RRTI = 0;
unsigned char sr_data, cr_data, cr_data2;
if(!SiSInitPtr(SiS_Pr)) return false;
if(rateindex > 0) rateindex--;
#ifdef CONFIG_FB_SIS_315
switch(ModeNo) {
case 0x5a: ModeNo = 0x50; break;
case 0x5b: ModeNo = 0x56;
}
#endif
if(!(SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex))) return false;
RRTI = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].REFindex;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & HaveWideTiming) {
if(SiS_Pr->SiS_UseWide == 1) {
/* Wide screen: Ignore rateindex */
CRT1Index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC_WIDE;
} else {
RRTI += rateindex;
CRT1Index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC_NORM;
}
} else {
RRTI += rateindex;
CRT1Index = SiS_Pr->SiS_RefIndex[RRTI].Ext_CRT1CRTC;
}
sr_data = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[14];
cr_data = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[0];
*htotal = (((cr_data & 0xff) | ((unsigned short) (sr_data & 0x03) << 8)) + 5) * 8;
sr_data = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[13];
cr_data = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[6];
cr_data2 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[7];
*vtotal = ((cr_data & 0xFF) |
((unsigned short)(cr_data2 & 0x01) << 8) |
((unsigned short)(cr_data2 & 0x20) << 4) |
((unsigned short)(sr_data & 0x01) << 10)) + 2;
if(SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag & InterlaceMode)
*vtotal *= 2;
return true;
}
| gpl-2.0 |
DirtyUnicorns/android_kernel_htc_pyramid | drivers/net/ethernet/8390/ac3200.c | 5089 | 11825 | /* ac3200.c: A driver for the Ansel Communications EISA ethernet adaptor. */
/*
Written 1993, 1994 by Donald Becker.
Copyright 1993 United States Government as represented by the Director,
National Security Agency. This software may only be used and distributed
according to the terms of the GNU General Public License as modified by SRC,
incorporated herein by reference.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
This is driver for the Ansel Communications Model 3200 EISA Ethernet LAN
Adapter. The programming information is from the users manual, as related
by glee@ardnassak.math.clemson.edu.
Changelog:
Paul Gortmaker 05/98 : add support for shared mem above 1MB.
*/
static const char version[] =
"ac3200.c:v1.01 7/1/94 Donald Becker (becker@cesdis.gsfc.nasa.gov)\n";
#include <linux/module.h>
#include <linux/eisa.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <asm/irq.h>
#include "8390.h"
#define DRV_NAME "ac3200"
/* Offsets from the base address. */
#define AC_NIC_BASE 0x00
#define AC_SA_PROM 0x16 /* The station address PROM. */
#define AC_ADDR0 0x00 /* Prefix station address values. */
#define AC_ADDR1 0x40
#define AC_ADDR2 0x90
#define AC_ID_PORT 0xC80
#define AC_EISA_ID 0x0110d305
#define AC_RESET_PORT 0xC84
#define AC_RESET 0x00
#define AC_ENABLE 0x01
#define AC_CONFIG 0xC90 /* The configuration port. */
#define AC_IO_EXTENT 0x20
/* Actually accessed is:
* AC_NIC_BASE (0-15)
* AC_SA_PROM (0-5)
* AC_ID_PORT (0-3)
* AC_RESET_PORT
* AC_CONFIG
*/
/* Decoding of the configuration register. */
static unsigned char config2irqmap[8] __initdata = {15, 12, 11, 10, 9, 7, 5, 3};
static int addrmap[8] =
{0xFF0000, 0xFE0000, 0xFD0000, 0xFFF0000, 0xFFE0000, 0xFFC0000, 0xD0000, 0 };
static const char *port_name[4] = { "10baseT", "invalid", "AUI", "10base2"};
#define config2irq(configval) config2irqmap[((configval) >> 3) & 7]
#define config2mem(configval) addrmap[(configval) & 7]
#define config2name(configval) port_name[((configval) >> 6) & 3]
/* First and last 8390 pages. */
#define AC_START_PG 0x00 /* First page of 8390 TX buffer */
#define AC_STOP_PG 0x80 /* Last page +1 of the 8390 RX ring */
static int ac_probe1(int ioaddr, struct net_device *dev);
static int ac_open(struct net_device *dev);
static void ac_reset_8390(struct net_device *dev);
static void ac_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset);
static void ac_block_output(struct net_device *dev, const int count,
const unsigned char *buf, const int start_page);
static void ac_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static int ac_close_card(struct net_device *dev);
/* Probe for the AC3200.
The AC3200 can be identified by either the EISA configuration registers,
or the unique value in the station address PROM.
*/
static int __init do_ac3200_probe(struct net_device *dev)
{
unsigned short ioaddr = dev->base_addr;
int irq = dev->irq;
int mem_start = dev->mem_start;
if (ioaddr > 0x1ff) /* Check a single specified location. */
return ac_probe1(ioaddr, dev);
else if (ioaddr > 0) /* Don't probe at all. */
return -ENXIO;
if ( ! EISA_bus)
return -ENXIO;
for (ioaddr = 0x1000; ioaddr < 0x9000; ioaddr += 0x1000) {
if (ac_probe1(ioaddr, dev) == 0)
return 0;
dev->irq = irq;
dev->mem_start = mem_start;
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init ac3200_probe(int unit)
{
struct net_device *dev = alloc_ei_netdev();
int err;
if (!dev)
return ERR_PTR(-ENOMEM);
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
err = do_ac3200_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static const struct net_device_ops ac_netdev_ops = {
.ndo_open = ac_open,
.ndo_stop = ac_close_card,
.ndo_start_xmit = ei_start_xmit,
.ndo_tx_timeout = ei_tx_timeout,
.ndo_get_stats = ei_get_stats,
.ndo_set_rx_mode = ei_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ei_poll,
#endif
};
static int __init ac_probe1(int ioaddr, struct net_device *dev)
{
int i, retval;
if (!request_region(ioaddr, AC_IO_EXTENT, DRV_NAME))
return -EBUSY;
if (inb_p(ioaddr + AC_ID_PORT) == 0xff) {
retval = -ENODEV;
goto out;
}
if (inl(ioaddr + AC_ID_PORT) != AC_EISA_ID) {
retval = -ENODEV;
goto out;
}
#ifndef final_version
printk(KERN_DEBUG "AC3200 ethercard configuration register is %#02x,"
" EISA ID %02x %02x %02x %02x.\n", inb(ioaddr + AC_CONFIG),
inb(ioaddr + AC_ID_PORT + 0), inb(ioaddr + AC_ID_PORT + 1),
inb(ioaddr + AC_ID_PORT + 2), inb(ioaddr + AC_ID_PORT + 3));
#endif
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + AC_SA_PROM + i);
printk(KERN_DEBUG "AC3200 in EISA slot %d, node %pM",
ioaddr/0x1000, dev->dev_addr);
#if 0
/* Check the vendor ID/prefix. Redundant after checking the EISA ID */
if (inb(ioaddr + AC_SA_PROM + 0) != AC_ADDR0
|| inb(ioaddr + AC_SA_PROM + 1) != AC_ADDR1
|| inb(ioaddr + AC_SA_PROM + 2) != AC_ADDR2 ) {
printk(", not found (invalid prefix).\n");
retval = -ENODEV;
goto out;
}
#endif
/* Assign and allocate the interrupt now. */
if (dev->irq == 0) {
dev->irq = config2irq(inb(ioaddr + AC_CONFIG));
printk(", using");
} else {
dev->irq = irq_canonicalize(dev->irq);
printk(", assigning");
}
retval = request_irq(dev->irq, ei_interrupt, 0, DRV_NAME, dev);
if (retval) {
printk (" nothing! Unable to get IRQ %d.\n", dev->irq);
goto out;
}
printk(" IRQ %d, %s port\n", dev->irq, port_name[dev->if_port]);
dev->base_addr = ioaddr;
#ifdef notyet
if (dev->mem_start) { /* Override the value from the board. */
for (i = 0; i < 7; i++)
if (addrmap[i] == dev->mem_start)
break;
if (i >= 7)
i = 0;
outb((inb(ioaddr + AC_CONFIG) & ~7) | i, ioaddr + AC_CONFIG);
}
#endif
dev->if_port = inb(ioaddr + AC_CONFIG) >> 6;
dev->mem_start = config2mem(inb(ioaddr + AC_CONFIG));
printk("%s: AC3200 at %#3x with %dkB memory at physical address %#lx.\n",
dev->name, ioaddr, AC_STOP_PG/4, dev->mem_start);
/*
* BEWARE!! Some dain-bramaged EISA SCUs will allow you to put
* the card mem within the region covered by `normal' RAM !!!
*
* ioremap() will fail in that case.
*/
ei_status.mem = ioremap(dev->mem_start, AC_STOP_PG*0x100);
if (!ei_status.mem) {
printk(KERN_ERR "ac3200.c: Unable to remap card memory above 1MB !!\n");
printk(KERN_ERR "ac3200.c: Try using EISA SCU to set memory below 1MB.\n");
printk(KERN_ERR "ac3200.c: Driver NOT installed.\n");
retval = -EINVAL;
goto out1;
}
printk("ac3200.c: remapped %dkB card memory to virtual address %p\n",
AC_STOP_PG/4, ei_status.mem);
dev->mem_start = (unsigned long)ei_status.mem;
dev->mem_end = dev->mem_start + (AC_STOP_PG - AC_START_PG)*256;
ei_status.name = "AC3200";
ei_status.tx_start_page = AC_START_PG;
ei_status.rx_start_page = AC_START_PG + TX_PAGES;
ei_status.stop_page = AC_STOP_PG;
ei_status.word16 = 1;
if (ei_debug > 0)
printk(version);
ei_status.reset_8390 = &ac_reset_8390;
ei_status.block_input = &ac_block_input;
ei_status.block_output = &ac_block_output;
ei_status.get_8390_hdr = &ac_get_8390_hdr;
dev->netdev_ops = &ac_netdev_ops;
NS8390_init(dev, 0);
retval = register_netdev(dev);
if (retval)
goto out2;
return 0;
out2:
if (ei_status.reg0)
iounmap(ei_status.mem);
out1:
free_irq(dev->irq, dev);
out:
release_region(ioaddr, AC_IO_EXTENT);
return retval;
}
static int ac_open(struct net_device *dev)
{
#ifdef notyet
/* Someday we may enable the IRQ and shared memory here. */
int ioaddr = dev->base_addr;
#endif
ei_open(dev);
return 0;
}
static void ac_reset_8390(struct net_device *dev)
{
ushort ioaddr = dev->base_addr;
outb(AC_RESET, ioaddr + AC_RESET_PORT);
if (ei_debug > 1) printk("resetting AC3200, t=%ld...", jiffies);
ei_status.txing = 0;
outb(AC_ENABLE, ioaddr + AC_RESET_PORT);
if (ei_debug > 1) printk("reset done\n");
}
/* Grab the 8390 specific header. Similar to the block_input routine, but
we don't need to be concerned with ring wrap as the header will be at
the start of a page, so we optimize accordingly. */
static void
ac_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page)
{
void __iomem *hdr_start = ei_status.mem + ((ring_page - AC_START_PG)<<8);
memcpy_fromio(hdr, hdr_start, sizeof(struct e8390_pkt_hdr));
}
/* Block input and output are easy on shared memory ethercards, the only
complication is when the ring buffer wraps. */
static void ac_block_input(struct net_device *dev, int count, struct sk_buff *skb,
int ring_offset)
{
void __iomem *start = ei_status.mem + ring_offset - AC_START_PG*256;
if (ring_offset + count > AC_STOP_PG*256) {
/* We must wrap the input move. */
int semi_count = AC_STOP_PG*256 - ring_offset;
memcpy_fromio(skb->data, start, semi_count);
count -= semi_count;
memcpy_fromio(skb->data + semi_count,
ei_status.mem + TX_PAGES*256, count);
} else {
memcpy_fromio(skb->data, start, count);
}
}
static void ac_block_output(struct net_device *dev, int count,
const unsigned char *buf, int start_page)
{
void __iomem *shmem = ei_status.mem + ((start_page - AC_START_PG)<<8);
memcpy_toio(shmem, buf, count);
}
static int ac_close_card(struct net_device *dev)
{
if (ei_debug > 1)
printk("%s: Shutting down ethercard.\n", dev->name);
#ifdef notyet
/* We should someday disable shared memory and interrupts. */
outb(0x00, ioaddr + 6); /* Disable interrupts. */
free_irq(dev->irq, dev);
#endif
ei_close(dev);
return 0;
}
#ifdef MODULE
#define MAX_AC32_CARDS 4 /* Max number of AC32 cards per module */
static struct net_device *dev_ac32[MAX_AC32_CARDS];
static int io[MAX_AC32_CARDS];
static int irq[MAX_AC32_CARDS];
static int mem[MAX_AC32_CARDS];
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(mem, int, NULL, 0);
MODULE_PARM_DESC(io, "I/O base address(es)");
MODULE_PARM_DESC(irq, "IRQ number(s)");
MODULE_PARM_DESC(mem, "Memory base address(es)");
MODULE_DESCRIPTION("Ansel AC3200 EISA ethernet driver");
MODULE_LICENSE("GPL");
static int __init ac3200_module_init(void)
{
struct net_device *dev;
int this_dev, found = 0;
for (this_dev = 0; this_dev < MAX_AC32_CARDS; this_dev++) {
if (io[this_dev] == 0 && this_dev != 0)
break;
dev = alloc_ei_netdev();
if (!dev)
break;
dev->irq = irq[this_dev];
dev->base_addr = io[this_dev];
dev->mem_start = mem[this_dev]; /* Currently ignored by driver */
if (do_ac3200_probe(dev) == 0) {
dev_ac32[found++] = dev;
continue;
}
free_netdev(dev);
printk(KERN_WARNING "ac3200.c: No ac3200 card found (i/o = 0x%x).\n", io[this_dev]);
break;
}
if (found)
return 0;
return -ENXIO;
}
static void cleanup_card(struct net_device *dev)
{
/* Someday free_irq may be in ac_close_card() */
free_irq(dev->irq, dev);
release_region(dev->base_addr, AC_IO_EXTENT);
iounmap(ei_status.mem);
}
static void __exit ac3200_module_exit(void)
{
int this_dev;
for (this_dev = 0; this_dev < MAX_AC32_CARDS; this_dev++) {
struct net_device *dev = dev_ac32[this_dev];
if (dev) {
unregister_netdev(dev);
cleanup_card(dev);
free_netdev(dev);
}
}
}
module_init(ac3200_module_init);
module_exit(ac3200_module_exit);
#endif /* MODULE */
| gpl-2.0 |
wzhy90/Huawei_Watch_Kernel | arch/mn10300/kernel/fpu.c | 8929 | 4214 | /* MN10300 FPU management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <asm/uaccess.h>
#include <asm/fpu.h>
#include <asm/elf.h>
#include <asm/exceptions.h>
#ifdef CONFIG_LAZY_SAVE_FPU
struct task_struct *fpu_state_owner;
#endif
/*
* error functions in FPU disabled exception
*/
asmlinkage void fpu_disabled_in_kernel(struct pt_regs *regs)
{
die_if_no_fixup("An FPU Disabled exception happened in kernel space\n",
regs, EXCEP_FPU_DISABLED);
}
/*
* handle an FPU operational exception
* - there's a possibility that if the FPU is asynchronous, the signal might
* be meant for a process other than the current one
*/
asmlinkage void fpu_exception(struct pt_regs *regs, enum exception_code code)
{
struct task_struct *tsk = current;
siginfo_t info;
u32 fpcr;
if (!user_mode(regs))
die_if_no_fixup("An FPU Operation exception happened in"
" kernel space\n",
regs, code);
if (!is_using_fpu(tsk))
die_if_no_fixup("An FPU Operation exception happened,"
" but the FPU is not in use",
regs, code);
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_addr = (void *) tsk->thread.uregs->pc;
info.si_code = FPE_FLTINV;
unlazy_fpu(tsk);
fpcr = tsk->thread.fpu_state.fpcr;
if (fpcr & FPCR_EC_Z)
info.si_code = FPE_FLTDIV;
else if (fpcr & FPCR_EC_O)
info.si_code = FPE_FLTOVF;
else if (fpcr & FPCR_EC_U)
info.si_code = FPE_FLTUND;
else if (fpcr & FPCR_EC_I)
info.si_code = FPE_FLTRES;
force_sig_info(SIGFPE, &info, tsk);
}
/*
* save the FPU state to a signal context
*/
int fpu_setup_sigcontext(struct fpucontext *fpucontext)
{
struct task_struct *tsk = current;
if (!is_using_fpu(tsk))
return 0;
/* transfer the current FPU state to memory and cause fpu_init() to be
* triggered by the next attempted FPU operation by the current
* process.
*/
preempt_disable();
#ifndef CONFIG_LAZY_SAVE_FPU
if (tsk->thread.fpu_flags & THREAD_HAS_FPU) {
fpu_save(&tsk->thread.fpu_state);
tsk->thread.uregs->epsw &= ~EPSW_FE;
tsk->thread.fpu_flags &= ~THREAD_HAS_FPU;
}
#else /* !CONFIG_LAZY_SAVE_FPU */
if (fpu_state_owner == tsk) {
fpu_save(&tsk->thread.fpu_state);
fpu_state_owner->thread.uregs->epsw &= ~EPSW_FE;
fpu_state_owner = NULL;
}
#endif /* !CONFIG_LAZY_SAVE_FPU */
preempt_enable();
/* we no longer have a valid current FPU state */
clear_using_fpu(tsk);
/* transfer the saved FPU state onto the userspace stack */
if (copy_to_user(fpucontext,
&tsk->thread.fpu_state,
min(sizeof(struct fpu_state_struct),
sizeof(struct fpucontext))))
return -1;
return 1;
}
/*
* kill a process's FPU state during restoration after signal handling
*/
void fpu_kill_state(struct task_struct *tsk)
{
/* disown anything left in the FPU */
preempt_disable();
#ifndef CONFIG_LAZY_SAVE_FPU
if (tsk->thread.fpu_flags & THREAD_HAS_FPU) {
tsk->thread.uregs->epsw &= ~EPSW_FE;
tsk->thread.fpu_flags &= ~THREAD_HAS_FPU;
}
#else /* !CONFIG_LAZY_SAVE_FPU */
if (fpu_state_owner == tsk) {
fpu_state_owner->thread.uregs->epsw &= ~EPSW_FE;
fpu_state_owner = NULL;
}
#endif /* !CONFIG_LAZY_SAVE_FPU */
preempt_enable();
/* we no longer have a valid current FPU state */
clear_using_fpu(tsk);
}
/*
* restore the FPU state from a signal context
*/
int fpu_restore_sigcontext(struct fpucontext *fpucontext)
{
struct task_struct *tsk = current;
int ret;
/* load up the old FPU state */
ret = copy_from_user(&tsk->thread.fpu_state, fpucontext,
min(sizeof(struct fpu_state_struct),
sizeof(struct fpucontext)));
if (!ret)
set_using_fpu(tsk);
return ret;
}
/*
* fill in the FPU structure for a core dump
*/
int dump_fpu(struct pt_regs *regs, elf_fpregset_t *fpreg)
{
struct task_struct *tsk = current;
int fpvalid;
fpvalid = is_using_fpu(tsk);
if (fpvalid) {
unlazy_fpu(tsk);
memcpy(fpreg, &tsk->thread.fpu_state, sizeof(*fpreg));
}
return fpvalid;
}
| gpl-2.0 |
KylinUI/android_kernel_samsung_exynos5410 | drivers/staging/media/go7007/go7007-fw.c | 9185 | 41220 | /*
* Copyright (C) 2005-2006 Micronas USA Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
/*
* This file contains code to generate a firmware image for the GO7007SB
* encoder. Much of the firmware is read verbatim from a file, but some of
* it concerning bitrate control and other things that can be configured at
* run-time are generated dynamically. Note that the format headers
* generated here do not affect the functioning of the encoder; they are
* merely parroted back to the host at the start of each frame.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include "go7007-priv.h"
/* Constants used in the source firmware image to describe code segments */
#define FLAG_MODE_MJPEG (1)
#define FLAG_MODE_MPEG1 (1<<1)
#define FLAG_MODE_MPEG2 (1<<2)
#define FLAG_MODE_MPEG4 (1<<3)
#define FLAG_MODE_H263 (1<<4)
#define FLAG_MODE_ALL (FLAG_MODE_MJPEG | FLAG_MODE_MPEG1 | \
FLAG_MODE_MPEG2 | FLAG_MODE_MPEG4 | \
FLAG_MODE_H263)
#define FLAG_SPECIAL (1<<8)
#define SPECIAL_FRM_HEAD 0
#define SPECIAL_BRC_CTRL 1
#define SPECIAL_CONFIG 2
#define SPECIAL_SEQHEAD 3
#define SPECIAL_AV_SYNC 4
#define SPECIAL_FINAL 5
#define SPECIAL_AUDIO 6
#define SPECIAL_MODET 7
/* Little data class for creating MPEG headers bit-by-bit */
struct code_gen {
unsigned char *p; /* destination */
u32 a; /* collects bits at the top of the variable */
int b; /* bit position of most recently-written bit */
int len; /* written out so far */
};
#define CODE_GEN(name, dest) struct code_gen name = { dest, 0, 32, 0 }
#define CODE_ADD(name, val, length) do { \
name.b -= (length); \
name.a |= (val) << name.b; \
while (name.b <= 24) { \
*name.p = name.a >> 24; \
++name.p; \
name.a <<= 8; \
name.b += 8; \
name.len += 8; \
} \
} while (0)
#define CODE_LENGTH(name) (name.len + (32 - name.b))
/* Tables for creating the bitrate control data */
static const s16 converge_speed_ip[101] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
5, 5, 5, 6, 6, 6, 7, 7, 8, 8,
9, 10, 10, 11, 12, 13, 14, 15, 16, 17,
19, 20, 22, 23, 25, 27, 30, 32, 35, 38,
41, 45, 49, 53, 58, 63, 69, 76, 83, 91,
100
};
static const s16 converge_speed_ipb[101] = {
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
6, 6, 6, 7, 7, 7, 7, 8, 8, 9,
9, 9, 10, 10, 11, 12, 12, 13, 14, 14,
15, 16, 17, 18, 19, 20, 22, 23, 25, 26,
28, 30, 32, 34, 37, 40, 42, 46, 49, 53,
57, 61, 66, 71, 77, 83, 90, 97, 106, 115,
125, 135, 147, 161, 175, 191, 209, 228, 249, 273,
300
};
static const s16 LAMBDA_table[4][101] = {
{ 16, 16, 16, 16, 17, 17, 17, 18, 18, 18,
19, 19, 19, 20, 20, 20, 21, 21, 22, 22,
22, 23, 23, 24, 24, 25, 25, 25, 26, 26,
27, 27, 28, 28, 29, 29, 30, 31, 31, 32,
32, 33, 33, 34, 35, 35, 36, 37, 37, 38,
39, 39, 40, 41, 42, 42, 43, 44, 45, 46,
46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
67, 68, 69, 70, 72, 73, 74, 76, 77, 78,
80, 81, 83, 84, 86, 87, 89, 90, 92, 94,
96
},
{
20, 20, 20, 21, 21, 21, 22, 22, 23, 23,
23, 24, 24, 25, 25, 26, 26, 27, 27, 28,
28, 29, 29, 30, 30, 31, 31, 32, 33, 33,
34, 34, 35, 36, 36, 37, 38, 38, 39, 40,
40, 41, 42, 43, 43, 44, 45, 46, 47, 48,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 64, 65, 66, 67, 68,
70, 71, 72, 73, 75, 76, 78, 79, 80, 82,
83, 85, 86, 88, 90, 91, 93, 95, 96, 98,
100, 102, 103, 105, 107, 109, 111, 113, 115, 117,
120
},
{
24, 24, 24, 25, 25, 26, 26, 27, 27, 28,
28, 29, 29, 30, 30, 31, 31, 32, 33, 33,
34, 34, 35, 36, 36, 37, 38, 38, 39, 40,
41, 41, 42, 43, 44, 44, 45, 46, 47, 48,
49, 50, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 62, 63, 64, 65, 66, 67, 69,
70, 71, 72, 74, 75, 76, 78, 79, 81, 82,
84, 85, 87, 88, 90, 92, 93, 95, 97, 98,
100, 102, 104, 106, 108, 110, 112, 114, 116, 118,
120, 122, 124, 127, 129, 131, 134, 136, 138, 141,
144
},
{
32, 32, 33, 33, 34, 34, 35, 36, 36, 37,
38, 38, 39, 40, 41, 41, 42, 43, 44, 44,
45, 46, 47, 48, 49, 50, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 62, 63, 64,
65, 66, 67, 69, 70, 71, 72, 74, 75, 76,
78, 79, 81, 82, 84, 85, 87, 88, 90, 92,
93, 95, 97, 98, 100, 102, 104, 106, 108, 110,
112, 114, 116, 118, 120, 122, 124, 127, 129, 131,
134, 136, 139, 141, 144, 146, 149, 152, 154, 157,
160, 163, 166, 169, 172, 175, 178, 181, 185, 188,
192
}
};
/* MPEG blank frame generation tables */
enum mpeg_frame_type {
PFRAME,
BFRAME_PRE,
BFRAME_POST,
BFRAME_BIDIR,
BFRAME_EMPTY
};
static const u32 addrinctab[33][2] = {
{ 0x01, 1 }, { 0x03, 3 }, { 0x02, 3 }, { 0x03, 4 },
{ 0x02, 4 }, { 0x03, 5 }, { 0x02, 5 }, { 0x07, 7 },
{ 0x06, 7 }, { 0x0b, 8 }, { 0x0a, 8 }, { 0x09, 8 },
{ 0x08, 8 }, { 0x07, 8 }, { 0x06, 8 }, { 0x17, 10 },
{ 0x16, 10 }, { 0x15, 10 }, { 0x14, 10 }, { 0x13, 10 },
{ 0x12, 10 }, { 0x23, 11 }, { 0x22, 11 }, { 0x21, 11 },
{ 0x20, 11 }, { 0x1f, 11 }, { 0x1e, 11 }, { 0x1d, 11 },
{ 0x1c, 11 }, { 0x1b, 11 }, { 0x1a, 11 }, { 0x19, 11 },
{ 0x18, 11 }
};
/* Standard JPEG tables */
static const u8 default_intra_quant_table[] = {
8, 16, 19, 22, 26, 27, 29, 34,
16, 16, 22, 24, 27, 29, 34, 37,
19, 22, 26, 27, 29, 34, 34, 38,
22, 22, 26, 27, 29, 34, 37, 40,
22, 26, 27, 29, 32, 35, 40, 48,
26, 27, 29, 32, 35, 40, 48, 58,
26, 27, 29, 34, 38, 46, 56, 69,
27, 29, 35, 38, 46, 56, 69, 83
};
static const u8 bits_dc_luminance[] = {
0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
};
static const u8 val_dc_luminance[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
static const u8 bits_dc_chrominance[] = {
0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
static const u8 val_dc_chrominance[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
static const u8 bits_ac_luminance[] = {
0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d
};
static const u8 val_ac_luminance[] = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa
};
static const u8 bits_ac_chrominance[] = {
0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77
};
static const u8 val_ac_chrominance[] = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa
};
/* Zig-zag mapping for quant table
*
* OK, let's do this mapping on the actual table above so it doesn't have
* to be done on the fly.
*/
static const int zz[64] = {
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
};
static int copy_packages(__le16 *dest, u16 *src, int pkg_cnt, int space)
{
int i, cnt = pkg_cnt * 32;
if (space < cnt)
return -1;
for (i = 0; i < cnt; ++i)
dest[i] = cpu_to_le16p(src + i);
return cnt;
}
static int mjpeg_frame_header(struct go7007 *go, unsigned char *buf, int q)
{
int i, p = 0;
buf[p++] = 0xff;
buf[p++] = 0xd8;
buf[p++] = 0xff;
buf[p++] = 0xdb;
buf[p++] = 0;
buf[p++] = 2 + 65;
buf[p++] = 0;
buf[p++] = default_intra_quant_table[0];
for (i = 1; i < 64; ++i)
/* buf[p++] = (default_intra_quant_table[i] * q) >> 3; */
buf[p++] = (default_intra_quant_table[zz[i]] * q) >> 3;
buf[p++] = 0xff;
buf[p++] = 0xc0;
buf[p++] = 0;
buf[p++] = 17;
buf[p++] = 8;
buf[p++] = go->height >> 8;
buf[p++] = go->height & 0xff;
buf[p++] = go->width >> 8;
buf[p++] = go->width & 0xff;
buf[p++] = 3;
buf[p++] = 1;
buf[p++] = 0x22;
buf[p++] = 0;
buf[p++] = 2;
buf[p++] = 0x11;
buf[p++] = 0;
buf[p++] = 3;
buf[p++] = 0x11;
buf[p++] = 0;
buf[p++] = 0xff;
buf[p++] = 0xc4;
buf[p++] = 418 >> 8;
buf[p++] = 418 & 0xff;
buf[p++] = 0x00;
memcpy(buf + p, bits_dc_luminance + 1, 16);
p += 16;
memcpy(buf + p, val_dc_luminance, sizeof(val_dc_luminance));
p += sizeof(val_dc_luminance);
buf[p++] = 0x01;
memcpy(buf + p, bits_dc_chrominance + 1, 16);
p += 16;
memcpy(buf + p, val_dc_chrominance, sizeof(val_dc_chrominance));
p += sizeof(val_dc_chrominance);
buf[p++] = 0x10;
memcpy(buf + p, bits_ac_luminance + 1, 16);
p += 16;
memcpy(buf + p, val_ac_luminance, sizeof(val_ac_luminance));
p += sizeof(val_ac_luminance);
buf[p++] = 0x11;
memcpy(buf + p, bits_ac_chrominance + 1, 16);
p += 16;
memcpy(buf + p, val_ac_chrominance, sizeof(val_ac_chrominance));
p += sizeof(val_ac_chrominance);
buf[p++] = 0xff;
buf[p++] = 0xda;
buf[p++] = 0;
buf[p++] = 12;
buf[p++] = 3;
buf[p++] = 1;
buf[p++] = 0x00;
buf[p++] = 2;
buf[p++] = 0x11;
buf[p++] = 3;
buf[p++] = 0x11;
buf[p++] = 0;
buf[p++] = 63;
buf[p++] = 0;
return p;
}
static int gen_mjpeghdr_to_package(struct go7007 *go, __le16 *code, int space)
{
u8 *buf;
u16 mem = 0x3e00;
unsigned int addr = 0x19;
int size = 0, i, off = 0, chunk;
buf = kzalloc(4096, GFP_KERNEL);
if (buf == NULL) {
printk(KERN_ERR "go7007: unable to allocate 4096 bytes for "
"firmware construction\n");
return -1;
}
for (i = 1; i < 32; ++i) {
mjpeg_frame_header(go, buf + size, i);
size += 80;
}
chunk = mjpeg_frame_header(go, buf + size, 1);
memmove(buf + size, buf + size + 80, chunk - 80);
size += chunk - 80;
for (i = 0; i < size; i += chunk * 2) {
if (space - off < 32) {
off = -1;
goto done;
}
code[off + 1] = __cpu_to_le16(0x8000 | mem);
chunk = 28;
if (mem + chunk > 0x4000)
chunk = 0x4000 - mem;
if (i + 2 * chunk > size)
chunk = (size - i) / 2;
if (chunk < 28) {
code[off] = __cpu_to_le16(0x4000 | chunk);
code[off + 31] = __cpu_to_le16(addr++);
mem = 0x3e00;
} else {
code[off] = __cpu_to_le16(0x1000 | 28);
code[off + 31] = 0;
mem += 28;
}
memcpy(&code[off + 2], buf + i, chunk * 2);
off += 32;
}
done:
kfree(buf);
return off;
}
static int mpeg1_frame_header(struct go7007 *go, unsigned char *buf,
int modulo, int pict_struct, enum mpeg_frame_type frame)
{
int i, j, mb_code, mb_len;
int rows = go->interlace_coding ? go->height / 32 : go->height / 16;
CODE_GEN(c, buf + 6);
switch (frame) {
case PFRAME:
mb_code = 0x1;
mb_len = 3;
break;
case BFRAME_PRE:
mb_code = 0x2;
mb_len = 4;
break;
case BFRAME_POST:
mb_code = 0x2;
mb_len = 3;
break;
case BFRAME_BIDIR:
mb_code = 0x2;
mb_len = 2;
break;
default: /* keep the compiler happy */
mb_code = mb_len = 0;
break;
}
CODE_ADD(c, frame == PFRAME ? 0x2 : 0x3, 13);
CODE_ADD(c, 0xffff, 16);
CODE_ADD(c, go->format == GO7007_FORMAT_MPEG2 ? 0x7 : 0x4, 4);
if (frame != PFRAME)
CODE_ADD(c, go->format == GO7007_FORMAT_MPEG2 ? 0x7 : 0x4, 4);
else
CODE_ADD(c, 0, 4); /* Is this supposed to be here?? */
CODE_ADD(c, 0, 3); /* What is this?? */
/* Byte-align with zeros */
j = 8 - (CODE_LENGTH(c) % 8);
if (j != 8)
CODE_ADD(c, 0, j);
if (go->format == GO7007_FORMAT_MPEG2) {
CODE_ADD(c, 0x1, 24);
CODE_ADD(c, 0xb5, 8);
CODE_ADD(c, 0x844, 12);
CODE_ADD(c, frame == PFRAME ? 0xff : 0x44, 8);
if (go->interlace_coding) {
CODE_ADD(c, pict_struct, 4);
if (go->dvd_mode)
CODE_ADD(c, 0x000, 11);
else
CODE_ADD(c, 0x200, 11);
} else {
CODE_ADD(c, 0x3, 4);
CODE_ADD(c, 0x20c, 11);
}
/* Byte-align with zeros */
j = 8 - (CODE_LENGTH(c) % 8);
if (j != 8)
CODE_ADD(c, 0, j);
}
for (i = 0; i < rows; ++i) {
CODE_ADD(c, 1, 24);
CODE_ADD(c, i + 1, 8);
CODE_ADD(c, 0x2, 6);
CODE_ADD(c, 0x1, 1);
CODE_ADD(c, mb_code, mb_len);
if (go->interlace_coding) {
CODE_ADD(c, 0x1, 2);
CODE_ADD(c, pict_struct == 1 ? 0x0 : 0x1, 1);
}
if (frame == BFRAME_BIDIR) {
CODE_ADD(c, 0x3, 2);
if (go->interlace_coding)
CODE_ADD(c, pict_struct == 1 ? 0x0 : 0x1, 1);
}
CODE_ADD(c, 0x3, 2);
for (j = (go->width >> 4) - 2; j >= 33; j -= 33)
CODE_ADD(c, 0x8, 11);
CODE_ADD(c, addrinctab[j][0], addrinctab[j][1]);
CODE_ADD(c, mb_code, mb_len);
if (go->interlace_coding) {
CODE_ADD(c, 0x1, 2);
CODE_ADD(c, pict_struct == 1 ? 0x0 : 0x1, 1);
}
if (frame == BFRAME_BIDIR) {
CODE_ADD(c, 0x3, 2);
if (go->interlace_coding)
CODE_ADD(c, pict_struct == 1 ? 0x0 : 0x1, 1);
}
CODE_ADD(c, 0x3, 2);
/* Byte-align with zeros */
j = 8 - (CODE_LENGTH(c) % 8);
if (j != 8)
CODE_ADD(c, 0, j);
}
i = CODE_LENGTH(c) + 4 * 8;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = 0x01;
buf[5] = 0x00;
return i;
}
static int mpeg1_sequence_header(struct go7007 *go, unsigned char *buf, int ext)
{
int i, aspect_ratio, picture_rate;
CODE_GEN(c, buf + 6);
if (go->format == GO7007_FORMAT_MPEG1) {
switch (go->aspect_ratio) {
case GO7007_RATIO_4_3:
aspect_ratio = go->standard == GO7007_STD_NTSC ? 3 : 2;
break;
case GO7007_RATIO_16_9:
aspect_ratio = go->standard == GO7007_STD_NTSC ? 5 : 4;
break;
default:
aspect_ratio = 1;
break;
}
} else {
switch (go->aspect_ratio) {
case GO7007_RATIO_4_3:
aspect_ratio = 2;
break;
case GO7007_RATIO_16_9:
aspect_ratio = 3;
break;
default:
aspect_ratio = 1;
break;
}
}
switch (go->sensor_framerate) {
case 24000:
picture_rate = 1;
break;
case 24024:
picture_rate = 2;
break;
case 25025:
picture_rate = go->interlace_coding ? 6 : 3;
break;
case 30000:
picture_rate = go->interlace_coding ? 7 : 4;
break;
case 30030:
picture_rate = go->interlace_coding ? 8 : 5;
break;
default:
picture_rate = 5; /* 30 fps seems like a reasonable default */
break;
}
CODE_ADD(c, go->width, 12);
CODE_ADD(c, go->height, 12);
CODE_ADD(c, aspect_ratio, 4);
CODE_ADD(c, picture_rate, 4);
CODE_ADD(c, go->format == GO7007_FORMAT_MPEG2 ? 20000 : 0x3ffff, 18);
CODE_ADD(c, 1, 1);
CODE_ADD(c, go->format == GO7007_FORMAT_MPEG2 ? 112 : 20, 10);
CODE_ADD(c, 0, 3);
/* Byte-align with zeros */
i = 8 - (CODE_LENGTH(c) % 8);
if (i != 8)
CODE_ADD(c, 0, i);
if (go->format == GO7007_FORMAT_MPEG2) {
CODE_ADD(c, 0x1, 24);
CODE_ADD(c, 0xb5, 8);
CODE_ADD(c, 0x148, 12);
if (go->interlace_coding)
CODE_ADD(c, 0x20001, 20);
else
CODE_ADD(c, 0xa0001, 20);
CODE_ADD(c, 0, 16);
/* Byte-align with zeros */
i = 8 - (CODE_LENGTH(c) % 8);
if (i != 8)
CODE_ADD(c, 0, i);
if (ext) {
CODE_ADD(c, 0x1, 24);
CODE_ADD(c, 0xb52, 12);
CODE_ADD(c, go->standard == GO7007_STD_NTSC ? 2 : 1, 3);
CODE_ADD(c, 0x105, 9);
CODE_ADD(c, 0x505, 16);
CODE_ADD(c, go->width, 14);
CODE_ADD(c, 1, 1);
CODE_ADD(c, go->height, 14);
/* Byte-align with zeros */
i = 8 - (CODE_LENGTH(c) % 8);
if (i != 8)
CODE_ADD(c, 0, i);
}
}
i = CODE_LENGTH(c) + 4 * 8;
buf[0] = i & 0xff;
buf[1] = i >> 8;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = 0x01;
buf[5] = 0xb3;
return i;
}
static int gen_mpeg1hdr_to_package(struct go7007 *go,
__le16 *code, int space, int *framelen)
{
u8 *buf;
u16 mem = 0x3e00;
unsigned int addr = 0x19;
int i, off = 0, chunk;
buf = kzalloc(5120, GFP_KERNEL);
if (buf == NULL) {
printk(KERN_ERR "go7007: unable to allocate 5120 bytes for "
"firmware construction\n");
return -1;
}
framelen[0] = mpeg1_frame_header(go, buf, 0, 1, PFRAME);
if (go->interlace_coding)
framelen[0] += mpeg1_frame_header(go, buf + framelen[0] / 8,
0, 2, PFRAME);
buf[0] = framelen[0] & 0xff;
buf[1] = framelen[0] >> 8;
i = 368;
framelen[1] = mpeg1_frame_header(go, buf + i, 0, 1, BFRAME_PRE);
if (go->interlace_coding)
framelen[1] += mpeg1_frame_header(go, buf + i + framelen[1] / 8,
0, 2, BFRAME_PRE);
buf[i] = framelen[1] & 0xff;
buf[i + 1] = framelen[1] >> 8;
i += 1632;
framelen[2] = mpeg1_frame_header(go, buf + i, 0, 1, BFRAME_POST);
if (go->interlace_coding)
framelen[2] += mpeg1_frame_header(go, buf + i + framelen[2] / 8,
0, 2, BFRAME_POST);
buf[i] = framelen[2] & 0xff;
buf[i + 1] = framelen[2] >> 8;
i += 1432;
framelen[3] = mpeg1_frame_header(go, buf + i, 0, 1, BFRAME_BIDIR);
if (go->interlace_coding)
framelen[3] += mpeg1_frame_header(go, buf + i + framelen[3] / 8,
0, 2, BFRAME_BIDIR);
buf[i] = framelen[3] & 0xff;
buf[i + 1] = framelen[3] >> 8;
i += 1632 + 16;
mpeg1_sequence_header(go, buf + i, 0);
i += 40;
for (i = 0; i < 5120; i += chunk * 2) {
if (space - off < 32) {
off = -1;
goto done;
}
code[off + 1] = __cpu_to_le16(0x8000 | mem);
chunk = 28;
if (mem + chunk > 0x4000)
chunk = 0x4000 - mem;
if (i + 2 * chunk > 5120)
chunk = (5120 - i) / 2;
if (chunk < 28) {
code[off] = __cpu_to_le16(0x4000 | chunk);
code[off + 31] = __cpu_to_le16(addr);
if (mem + chunk == 0x4000) {
mem = 0x3e00;
++addr;
}
} else {
code[off] = __cpu_to_le16(0x1000 | 28);
code[off + 31] = 0;
mem += 28;
}
memcpy(&code[off + 2], buf + i, chunk * 2);
off += 32;
}
done:
kfree(buf);
return off;
}
static int vti_bitlen(struct go7007 *go)
{
unsigned int i, max_time_incr = go->sensor_framerate / go->fps_scale;
for (i = 31; (max_time_incr & ((1 << i) - 1)) == max_time_incr; --i);
return i + 1;
}
static int mpeg4_frame_header(struct go7007 *go, unsigned char *buf,
int modulo, enum mpeg_frame_type frame)
{
int i;
CODE_GEN(c, buf + 6);
int mb_count = (go->width >> 4) * (go->height >> 4);
CODE_ADD(c, frame == PFRAME ? 0x1 : 0x2, 2);
if (modulo)
CODE_ADD(c, 0x1, 1);
CODE_ADD(c, 0x1, 2);
CODE_ADD(c, 0, vti_bitlen(go));
CODE_ADD(c, 0x3, 2);
if (frame == PFRAME)
CODE_ADD(c, 0, 1);
CODE_ADD(c, 0xc, 11);
if (frame != PFRAME)
CODE_ADD(c, 0x4, 3);
if (frame != BFRAME_EMPTY) {
for (i = 0; i < mb_count; ++i) {
switch (frame) {
case PFRAME:
CODE_ADD(c, 0x1, 1);
break;
case BFRAME_PRE:
CODE_ADD(c, 0x47, 8);
break;
case BFRAME_POST:
CODE_ADD(c, 0x27, 7);
break;
case BFRAME_BIDIR:
CODE_ADD(c, 0x5f, 8);
break;
case BFRAME_EMPTY: /* keep compiler quiet */
break;
}
}
}
/* Byte-align with a zero followed by ones */
i = 8 - (CODE_LENGTH(c) % 8);
CODE_ADD(c, 0, 1);
CODE_ADD(c, (1 << (i - 1)) - 1, i - 1);
i = CODE_LENGTH(c) + 4 * 8;
buf[0] = i & 0xff;
buf[1] = i >> 8;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = 0x01;
buf[5] = 0xb6;
return i;
}
static int mpeg4_sequence_header(struct go7007 *go, unsigned char *buf, int ext)
{
const unsigned char head[] = { 0x00, 0x00, 0x01, 0xb0, go->pali,
0x00, 0x00, 0x01, 0xb5, 0x09,
0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x01, 0x20, };
int i, aspect_ratio;
int fps = go->sensor_framerate / go->fps_scale;
CODE_GEN(c, buf + 2 + sizeof(head));
switch (go->aspect_ratio) {
case GO7007_RATIO_4_3:
aspect_ratio = go->standard == GO7007_STD_NTSC ? 3 : 2;
break;
case GO7007_RATIO_16_9:
aspect_ratio = go->standard == GO7007_STD_NTSC ? 5 : 4;
break;
default:
aspect_ratio = 1;
break;
}
memcpy(buf + 2, head, sizeof(head));
CODE_ADD(c, 0x191, 17);
CODE_ADD(c, aspect_ratio, 4);
CODE_ADD(c, 0x1, 4);
CODE_ADD(c, fps, 16);
CODE_ADD(c, 0x3, 2);
CODE_ADD(c, 1001, vti_bitlen(go));
CODE_ADD(c, 1, 1);
CODE_ADD(c, go->width, 13);
CODE_ADD(c, 1, 1);
CODE_ADD(c, go->height, 13);
CODE_ADD(c, 0x2830, 14);
/* Byte-align */
i = 8 - (CODE_LENGTH(c) % 8);
CODE_ADD(c, 0, 1);
CODE_ADD(c, (1 << (i - 1)) - 1, i - 1);
i = CODE_LENGTH(c) + sizeof(head) * 8;
buf[0] = i & 0xff;
buf[1] = i >> 8;
return i;
}
static int gen_mpeg4hdr_to_package(struct go7007 *go,
__le16 *code, int space, int *framelen)
{
u8 *buf;
u16 mem = 0x3e00;
unsigned int addr = 0x19;
int i, off = 0, chunk;
buf = kzalloc(5120, GFP_KERNEL);
if (buf == NULL) {
printk(KERN_ERR "go7007: unable to allocate 5120 bytes for "
"firmware construction\n");
return -1;
}
framelen[0] = mpeg4_frame_header(go, buf, 0, PFRAME);
i = 368;
framelen[1] = mpeg4_frame_header(go, buf + i, 0, BFRAME_PRE);
i += 1632;
framelen[2] = mpeg4_frame_header(go, buf + i, 0, BFRAME_POST);
i += 1432;
framelen[3] = mpeg4_frame_header(go, buf + i, 0, BFRAME_BIDIR);
i += 1632;
mpeg4_frame_header(go, buf + i, 0, BFRAME_EMPTY);
i += 16;
mpeg4_sequence_header(go, buf + i, 0);
i += 40;
for (i = 0; i < 5120; i += chunk * 2) {
if (space - off < 32) {
off = -1;
goto done;
}
code[off + 1] = __cpu_to_le16(0x8000 | mem);
chunk = 28;
if (mem + chunk > 0x4000)
chunk = 0x4000 - mem;
if (i + 2 * chunk > 5120)
chunk = (5120 - i) / 2;
if (chunk < 28) {
code[off] = __cpu_to_le16(0x4000 | chunk);
code[off + 31] = __cpu_to_le16(addr);
if (mem + chunk == 0x4000) {
mem = 0x3e00;
++addr;
}
} else {
code[off] = __cpu_to_le16(0x1000 | 28);
code[off + 31] = 0;
mem += 28;
}
memcpy(&code[off + 2], buf + i, chunk * 2);
off += 32;
}
mem = 0x3e00;
addr = go->ipb ? 0x14f9 : 0x0af9;
memset(buf, 0, 5120);
framelen[4] = mpeg4_frame_header(go, buf, 1, PFRAME);
i = 368;
framelen[5] = mpeg4_frame_header(go, buf + i, 1, BFRAME_PRE);
i += 1632;
framelen[6] = mpeg4_frame_header(go, buf + i, 1, BFRAME_POST);
i += 1432;
framelen[7] = mpeg4_frame_header(go, buf + i, 1, BFRAME_BIDIR);
i += 1632;
mpeg4_frame_header(go, buf + i, 1, BFRAME_EMPTY);
i += 16;
for (i = 0; i < 5120; i += chunk * 2) {
if (space - off < 32) {
off = -1;
goto done;
}
code[off + 1] = __cpu_to_le16(0x8000 | mem);
chunk = 28;
if (mem + chunk > 0x4000)
chunk = 0x4000 - mem;
if (i + 2 * chunk > 5120)
chunk = (5120 - i) / 2;
if (chunk < 28) {
code[off] = __cpu_to_le16(0x4000 | chunk);
code[off + 31] = __cpu_to_le16(addr);
if (mem + chunk == 0x4000) {
mem = 0x3e00;
++addr;
}
} else {
code[off] = __cpu_to_le16(0x1000 | 28);
code[off + 31] = 0;
mem += 28;
}
memcpy(&code[off + 2], buf + i, chunk * 2);
off += 32;
}
done:
kfree(buf);
return off;
}
static int brctrl_to_package(struct go7007 *go,
__le16 *code, int space, int *framelen)
{
int converge_speed = 0;
int lambda = (go->format == GO7007_FORMAT_MJPEG || go->dvd_mode) ?
100 : 0;
int peak_rate = 6 * go->bitrate / 5;
int vbv_buffer = go->format == GO7007_FORMAT_MJPEG ?
go->bitrate :
(go->dvd_mode ? 900000 : peak_rate);
int fps = go->sensor_framerate / go->fps_scale;
int q = 0;
/* Bizarre math below depends on rounding errors in division */
u32 sgop_expt_addr = go->bitrate / 32 * (go->ipb ? 3 : 1) * 1001 / fps;
u32 sgop_peak_addr = peak_rate / 32 * 1001 / fps;
u32 total_expt_addr = go->bitrate / 32 * 1000 / fps * (fps / 1000);
u32 vbv_alert_addr = vbv_buffer * 3 / (4 * 32);
u32 cplx[] = {
q > 0 ? sgop_expt_addr * q :
2 * go->width * go->height * (go->ipb ? 6 : 4) / 32,
q > 0 ? sgop_expt_addr * q :
2 * go->width * go->height * (go->ipb ? 6 : 4) / 32,
q > 0 ? sgop_expt_addr * q :
2 * go->width * go->height * (go->ipb ? 6 : 4) / 32,
q > 0 ? sgop_expt_addr * q :
2 * go->width * go->height * (go->ipb ? 6 : 4) / 32,
};
u32 calc_q = q > 0 ? q : cplx[0] / sgop_expt_addr;
u16 pack[] = {
0x200e, 0x0000,
0xBF20, go->ipb ? converge_speed_ipb[converge_speed]
: converge_speed_ip[converge_speed],
0xBF21, go->ipb ? 2 : 0,
0xBF22, go->ipb ? LAMBDA_table[0][lambda / 2 + 50]
: 32767,
0xBF23, go->ipb ? LAMBDA_table[1][lambda] : 32767,
0xBF24, 32767,
0xBF25, lambda > 99 ? 32767 : LAMBDA_table[3][lambda],
0xBF26, sgop_expt_addr & 0x0000FFFF,
0xBF27, sgop_expt_addr >> 16,
0xBF28, sgop_peak_addr & 0x0000FFFF,
0xBF29, sgop_peak_addr >> 16,
0xBF2A, vbv_alert_addr & 0x0000FFFF,
0xBF2B, vbv_alert_addr >> 16,
0xBF2C, 0,
0xBF2D, 0,
0, 0,
0x200e, 0x0000,
0xBF2E, vbv_alert_addr & 0x0000FFFF,
0xBF2F, vbv_alert_addr >> 16,
0xBF30, cplx[0] & 0x0000FFFF,
0xBF31, cplx[0] >> 16,
0xBF32, cplx[1] & 0x0000FFFF,
0xBF33, cplx[1] >> 16,
0xBF34, cplx[2] & 0x0000FFFF,
0xBF35, cplx[2] >> 16,
0xBF36, cplx[3] & 0x0000FFFF,
0xBF37, cplx[3] >> 16,
0xBF38, 0,
0xBF39, 0,
0xBF3A, total_expt_addr & 0x0000FFFF,
0xBF3B, total_expt_addr >> 16,
0, 0,
0x200e, 0x0000,
0xBF3C, total_expt_addr & 0x0000FFFF,
0xBF3D, total_expt_addr >> 16,
0xBF3E, 0,
0xBF3F, 0,
0xBF48, 0,
0xBF49, 0,
0xBF4A, calc_q < 4 ? 4 : (calc_q > 124 ? 124 : calc_q),
0xBF4B, 4,
0xBF4C, 0,
0xBF4D, 0,
0xBF4E, 0,
0xBF4F, 0,
0xBF50, 0,
0xBF51, 0,
0, 0,
0x200e, 0x0000,
0xBF40, sgop_expt_addr & 0x0000FFFF,
0xBF41, sgop_expt_addr >> 16,
0xBF42, 0,
0xBF43, 0,
0xBF44, 0,
0xBF45, 0,
0xBF46, (go->width >> 4) * (go->height >> 4),
0xBF47, 0,
0xBF64, 0,
0xBF65, 0,
0xBF18, framelen[4],
0xBF19, framelen[5],
0xBF1A, framelen[6],
0xBF1B, framelen[7],
0, 0,
#if 0
/* Remove once we don't care about matching */
0x200e, 0x0000,
0xBF56, 4,
0xBF57, 0,
0xBF58, 5,
0xBF59, 0,
0xBF5A, 6,
0xBF5B, 0,
0xBF5C, 8,
0xBF5D, 0,
0xBF5E, 1,
0xBF5F, 0,
0xBF60, 1,
0xBF61, 0,
0xBF62, 0,
0xBF63, 0,
0, 0,
#else
0x2008, 0x0000,
0xBF56, 4,
0xBF57, 0,
0xBF58, 5,
0xBF59, 0,
0xBF5A, 6,
0xBF5B, 0,
0xBF5C, 8,
0xBF5D, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
#endif
0x200e, 0x0000,
0xBF10, 0,
0xBF11, 0,
0xBF12, 0,
0xBF13, 0,
0xBF14, 0,
0xBF15, 0,
0xBF16, 0,
0xBF17, 0,
0xBF7E, 0,
0xBF7F, 1,
0xBF52, framelen[0],
0xBF53, framelen[1],
0xBF54, framelen[2],
0xBF55, framelen[3],
0, 0,
};
return copy_packages(code, pack, 6, space);
}
static int config_package(struct go7007 *go, __le16 *code, int space)
{
int fps = go->sensor_framerate / go->fps_scale / 1000;
int rows = go->interlace_coding ? go->height / 32 : go->height / 16;
int brc_window_size = fps;
int q_min = 2, q_max = 31;
int THACCoeffSet0 = 0;
u16 pack[] = {
0x200e, 0x0000,
0xc002, 0x14b4,
0xc003, 0x28b4,
0xc004, 0x3c5a,
0xdc05, 0x2a77,
0xc6c3, go->format == GO7007_FORMAT_MPEG4 ? 0 :
(go->format == GO7007_FORMAT_H263 ? 0 : 1),
0xc680, go->format == GO7007_FORMAT_MPEG4 ? 0xf1 :
(go->format == GO7007_FORMAT_H263 ? 0x61 :
0xd3),
0xc780, 0x0140,
0xe009, 0x0001,
0xc60f, 0x0008,
0xd4ff, 0x0002,
0xe403, 2340,
0xe406, 75,
0xd411, 0x0001,
0xd410, 0xa1d6,
0x0001, 0x2801,
0x200d, 0x0000,
0xe402, 0x018b,
0xe401, 0x8b01,
0xd472, (go->board_info->sensor_flags &
GO7007_SENSOR_TV) &&
(!go->interlace_coding) ?
0x01b0 : 0x0170,
0xd475, (go->board_info->sensor_flags &
GO7007_SENSOR_TV) &&
(!go->interlace_coding) ?
0x0008 : 0x0009,
0xc404, go->interlace_coding ? 0x44 :
(go->format == GO7007_FORMAT_MPEG4 ? 0x11 :
(go->format == GO7007_FORMAT_MPEG1 ? 0x02 :
(go->format == GO7007_FORMAT_MPEG2 ? 0x04 :
(go->format == GO7007_FORMAT_H263 ? 0x08 :
0x20)))),
0xbf0a, (go->format == GO7007_FORMAT_MPEG4 ? 8 :
(go->format == GO7007_FORMAT_MPEG1 ? 1 :
(go->format == GO7007_FORMAT_MPEG2 ? 2 :
(go->format == GO7007_FORMAT_H263 ? 4 : 16)))) |
((go->repeat_seqhead ? 1 : 0) << 6) |
((go->dvd_mode ? 1 : 0) << 9) |
((go->gop_header_enable ? 1 : 0) << 10),
0xbf0b, 0,
0xdd5a, go->ipb ? 0x14 : 0x0a,
0xbf0c, 0,
0xbf0d, 0,
0xc683, THACCoeffSet0,
0xc40a, (go->width << 4) | rows,
0xe01a, go->board_info->hpi_buffer_cap,
0, 0,
0, 0,
0x2008, 0,
0xe402, 0x88,
0xe401, 0x8f01,
0xbf6a, 0,
0xbf6b, 0,
0xbf6c, 0,
0xbf6d, 0,
0xbf6e, 0,
0xbf6f, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0x200e, 0,
0xbf66, brc_window_size,
0xbf67, 0,
0xbf68, q_min,
0xbf69, q_max,
0xbfe0, 0,
0xbfe1, 0,
0xbfe2, 0,
0xbfe3, go->ipb ? 3 : 1,
0xc031, go->board_info->sensor_flags &
GO7007_SENSOR_VBI ? 1 : 0,
0xc01c, 0x1f,
0xdd8c, 0x15,
0xdd94, 0x15,
0xdd88, go->ipb ? 0x1401 : 0x0a01,
0xdd90, go->ipb ? 0x1401 : 0x0a01,
0, 0,
0x200e, 0,
0xbfe4, 0,
0xbfe5, 0,
0xbfe6, 0,
0xbfe7, fps << 8,
0xbfe8, 0x3a00,
0xbfe9, 0,
0xbfea, 0,
0xbfeb, 0,
0xbfec, (go->interlace_coding ? 1 << 15 : 0) |
(go->modet_enable ? 0xa : 0) |
(go->board_info->sensor_flags &
GO7007_SENSOR_VBI ? 1 : 0),
0xbfed, 0,
0xbfee, 0,
0xbfef, 0,
0xbff0, go->board_info->sensor_flags &
GO7007_SENSOR_TV ? 0xf060 : 0xb060,
0xbff1, 0,
0, 0,
};
return copy_packages(code, pack, 5, space);
}
static int seqhead_to_package(struct go7007 *go, __le16 *code, int space,
int (*sequence_header_func)(struct go7007 *go,
unsigned char *buf, int ext))
{
int vop_time_increment_bitlength = vti_bitlen(go);
int fps = go->sensor_framerate / go->fps_scale *
(go->interlace_coding ? 2 : 1);
unsigned char buf[40] = { };
int len = sequence_header_func(go, buf, 1);
u16 pack[] = {
0x2006, 0,
0xbf08, fps,
0xbf09, 0,
0xbff2, vop_time_increment_bitlength,
0xbff3, (1 << vop_time_increment_bitlength) - 1,
0xbfe6, 0,
0xbfe7, (fps / 1000) << 8,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0x2007, 0,
0xc800, buf[2] << 8 | buf[3],
0xc801, buf[4] << 8 | buf[5],
0xc802, buf[6] << 8 | buf[7],
0xc803, buf[8] << 8 | buf[9],
0xc406, 64,
0xc407, len - 64,
0xc61b, 1,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0x200e, 0,
0xc808, buf[10] << 8 | buf[11],
0xc809, buf[12] << 8 | buf[13],
0xc80a, buf[14] << 8 | buf[15],
0xc80b, buf[16] << 8 | buf[17],
0xc80c, buf[18] << 8 | buf[19],
0xc80d, buf[20] << 8 | buf[21],
0xc80e, buf[22] << 8 | buf[23],
0xc80f, buf[24] << 8 | buf[25],
0xc810, buf[26] << 8 | buf[27],
0xc811, buf[28] << 8 | buf[29],
0xc812, buf[30] << 8 | buf[31],
0xc813, buf[32] << 8 | buf[33],
0xc814, buf[34] << 8 | buf[35],
0xc815, buf[36] << 8 | buf[37],
0, 0,
0, 0,
0, 0,
};
return copy_packages(code, pack, 3, space);
}
static int relative_prime(int big, int little)
{
int remainder;
while (little != 0) {
remainder = big % little;
big = little;
little = remainder;
}
return big;
}
static int avsync_to_package(struct go7007 *go, __le16 *code, int space)
{
int arate = go->board_info->audio_rate * 1001 * go->fps_scale;
int ratio = arate / go->sensor_framerate;
int adjratio = ratio * 215 / 100;
int rprime = relative_prime(go->sensor_framerate,
arate % go->sensor_framerate);
int f1 = (arate % go->sensor_framerate) / rprime;
int f2 = (go->sensor_framerate - arate % go->sensor_framerate) / rprime;
u16 pack[] = {
0x200e, 0,
0xbf98, (u16)((-adjratio) & 0xffff),
0xbf99, (u16)((-adjratio) >> 16),
0xbf92, 0,
0xbf93, 0,
0xbff4, f1 > f2 ? f1 : f2,
0xbff5, f1 < f2 ? f1 : f2,
0xbff6, f1 < f2 ? ratio : ratio + 1,
0xbff7, f1 > f2 ? ratio : ratio + 1,
0xbff8, 0,
0xbff9, 0,
0xbffa, adjratio & 0xffff,
0xbffb, adjratio >> 16,
0xbf94, 0,
0xbf95, 0,
0, 0,
};
return copy_packages(code, pack, 1, space);
}
static int final_package(struct go7007 *go, __le16 *code, int space)
{
int rows = go->interlace_coding ? go->height / 32 : go->height / 16;
u16 pack[] = {
0x8000,
0,
0,
0,
0,
0,
0,
2,
((go->board_info->sensor_flags & GO7007_SENSOR_TV) &&
(!go->interlace_coding) ?
(1 << 14) | (1 << 9) : 0) |
((go->encoder_subsample ? 1 : 0) << 8) |
(go->board_info->sensor_flags &
GO7007_SENSOR_CONFIG_MASK),
((go->encoder_v_halve ? 1 : 0) << 14) |
(go->encoder_v_halve ? rows << 9 : rows << 8) |
(go->encoder_h_halve ? 1 << 6 : 0) |
(go->encoder_h_halve ? go->width >> 3 : go->width >> 4),
(1 << 15) | (go->encoder_v_offset << 6) |
(1 << 7) | (go->encoder_h_offset >> 2),
(1 << 6),
0,
0,
((go->fps_scale - 1) << 8) |
(go->board_info->sensor_flags & GO7007_SENSOR_TV ?
(1 << 7) : 0) |
0x41,
go->ipb ? 0xd4c : 0x36b,
(rows << 8) | (go->width >> 4),
go->format == GO7007_FORMAT_MPEG4 ? 0x0404 : 0,
(1 << 15) | ((go->interlace_coding ? 1 : 0) << 13) |
((go->closed_gop ? 1 : 0) << 12) |
((go->format == GO7007_FORMAT_MPEG4 ? 1 : 0) << 11) |
/* (1 << 9) | */
((go->ipb ? 3 : 0) << 7) |
((go->modet_enable ? 1 : 0) << 2) |
((go->dvd_mode ? 1 : 0) << 1) | 1,
(go->format == GO7007_FORMAT_MPEG1 ? 0x89a0 :
(go->format == GO7007_FORMAT_MPEG2 ? 0x89a0 :
(go->format == GO7007_FORMAT_MJPEG ? 0x89a0 :
(go->format == GO7007_FORMAT_MPEG4 ? 0x8920 :
(go->format == GO7007_FORMAT_H263 ? 0x8920 : 0))))),
go->ipb ? 0x1f15 : 0x1f0b,
go->ipb ? 0x0015 : 0x000b,
go->ipb ? 0xa800 : 0x5800,
0xffff,
0x0020 + 0x034b * 0,
0x0020 + 0x034b * 1,
0x0020 + 0x034b * 2,
0x0020 + 0x034b * 3,
0x0020 + 0x034b * 4,
0x0020 + 0x034b * 5,
go->ipb ? (go->gop_size / 3) : go->gop_size,
(go->height >> 4) * (go->width >> 4) * 110 / 100,
};
return copy_packages(code, pack, 1, space);
}
static int audio_to_package(struct go7007 *go, __le16 *code, int space)
{
int clock_config = ((go->board_info->audio_flags &
GO7007_AUDIO_I2S_MASTER ? 1 : 0) << 11) |
((go->board_info->audio_flags &
GO7007_AUDIO_OKI_MODE ? 1 : 0) << 8) |
(((go->board_info->audio_bclk_div / 4) - 1) << 4) |
(go->board_info->audio_main_div - 1);
u16 pack[] = {
0x200d, 0,
0x9002, 0,
0x9002, 0,
0x9031, 0,
0x9032, 0,
0x9033, 0,
0x9034, 0,
0x9035, 0,
0x9036, 0,
0x9037, 0,
0x9040, 0,
0x9000, clock_config,
0x9001, (go->board_info->audio_flags & 0xffff) |
(1 << 9),
0x9000, ((go->board_info->audio_flags &
GO7007_AUDIO_I2S_MASTER ?
1 : 0) << 10) |
clock_config,
0, 0,
0, 0,
0x2005, 0,
0x9041, 0,
0x9042, 256,
0x9043, 0,
0x9044, 16,
0x9045, 16,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
};
return copy_packages(code, pack, 2, space);
}
static int modet_to_package(struct go7007 *go, __le16 *code, int space)
{
int ret, mb, i, addr, cnt = 0;
u16 pack[32];
u16 thresholds[] = {
0x200e, 0,
0xbf82, go->modet[0].pixel_threshold,
0xbf83, go->modet[1].pixel_threshold,
0xbf84, go->modet[2].pixel_threshold,
0xbf85, go->modet[3].pixel_threshold,
0xbf86, go->modet[0].motion_threshold,
0xbf87, go->modet[1].motion_threshold,
0xbf88, go->modet[2].motion_threshold,
0xbf89, go->modet[3].motion_threshold,
0xbf8a, go->modet[0].mb_threshold,
0xbf8b, go->modet[1].mb_threshold,
0xbf8c, go->modet[2].mb_threshold,
0xbf8d, go->modet[3].mb_threshold,
0xbf8e, 0,
0xbf8f, 0,
0, 0,
};
ret = copy_packages(code, thresholds, 1, space);
if (ret < 0)
return -1;
cnt += ret;
addr = 0xbac0;
memset(pack, 0, 64);
i = 0;
for (mb = 0; mb < 1624; ++mb) {
pack[i * 2 + 3] <<= 2;
pack[i * 2 + 3] |= go->modet_map[mb];
if (mb % 8 != 7)
continue;
pack[i * 2 + 2] = addr++;
++i;
if (i == 10 || mb == 1623) {
pack[0] = 0x2000 | i;
ret = copy_packages(code + cnt, pack, 1, space - cnt);
if (ret < 0)
return -1;
cnt += ret;
i = 0;
memset(pack, 0, 64);
}
pack[i * 2 + 3] = 0;
}
memset(pack, 0, 64);
i = 0;
for (addr = 0xbb90; addr < 0xbbfa; ++addr) {
pack[i * 2 + 2] = addr;
pack[i * 2 + 3] = 0;
++i;
if (i == 10 || addr == 0xbbf9) {
pack[0] = 0x2000 | i;
ret = copy_packages(code + cnt, pack, 1, space - cnt);
if (ret < 0)
return -1;
cnt += ret;
i = 0;
memset(pack, 0, 64);
}
}
return cnt;
}
static int do_special(struct go7007 *go, u16 type, __le16 *code, int space,
int *framelen)
{
switch (type) {
case SPECIAL_FRM_HEAD:
switch (go->format) {
case GO7007_FORMAT_MJPEG:
return gen_mjpeghdr_to_package(go, code, space);
case GO7007_FORMAT_MPEG1:
case GO7007_FORMAT_MPEG2:
return gen_mpeg1hdr_to_package(go, code, space,
framelen);
case GO7007_FORMAT_MPEG4:
return gen_mpeg4hdr_to_package(go, code, space,
framelen);
}
case SPECIAL_BRC_CTRL:
return brctrl_to_package(go, code, space, framelen);
case SPECIAL_CONFIG:
return config_package(go, code, space);
case SPECIAL_SEQHEAD:
switch (go->format) {
case GO7007_FORMAT_MPEG1:
case GO7007_FORMAT_MPEG2:
return seqhead_to_package(go, code, space,
mpeg1_sequence_header);
case GO7007_FORMAT_MPEG4:
return seqhead_to_package(go, code, space,
mpeg4_sequence_header);
default:
return 0;
}
case SPECIAL_AV_SYNC:
return avsync_to_package(go, code, space);
case SPECIAL_FINAL:
return final_package(go, code, space);
case SPECIAL_AUDIO:
return audio_to_package(go, code, space);
case SPECIAL_MODET:
return modet_to_package(go, code, space);
}
printk(KERN_ERR
"go7007: firmware file contains unsupported feature %04x\n",
type);
return -1;
}
int go7007_construct_fw_image(struct go7007 *go, u8 **fw, int *fwlen)
{
const struct firmware *fw_entry;
__le16 *code, *src;
int framelen[8] = { }; /* holds the lengths of empty frame templates */
int codespace = 64 * 1024, i = 0, srclen, chunk_len, chunk_flags;
int mode_flag;
int ret;
switch (go->format) {
case GO7007_FORMAT_MJPEG:
mode_flag = FLAG_MODE_MJPEG;
break;
case GO7007_FORMAT_MPEG1:
mode_flag = FLAG_MODE_MPEG1;
break;
case GO7007_FORMAT_MPEG2:
mode_flag = FLAG_MODE_MPEG2;
break;
case GO7007_FORMAT_MPEG4:
mode_flag = FLAG_MODE_MPEG4;
break;
default:
return -1;
}
if (request_firmware(&fw_entry, go->board_info->firmware, go->dev)) {
printk(KERN_ERR
"go7007: unable to load firmware from file \"%s\"\n",
go->board_info->firmware);
return -1;
}
code = kzalloc(codespace * 2, GFP_KERNEL);
if (code == NULL) {
printk(KERN_ERR "go7007: unable to allocate %d bytes for "
"firmware construction\n", codespace * 2);
goto fw_failed;
}
src = (__le16 *)fw_entry->data;
srclen = fw_entry->size / 2;
while (srclen >= 2) {
chunk_flags = __le16_to_cpu(src[0]);
chunk_len = __le16_to_cpu(src[1]);
if (chunk_len + 2 > srclen) {
printk(KERN_ERR "go7007: firmware file \"%s\" "
"appears to be corrupted\n",
go->board_info->firmware);
goto fw_failed;
}
if (chunk_flags & mode_flag) {
if (chunk_flags & FLAG_SPECIAL) {
ret = do_special(go, __le16_to_cpu(src[2]),
&code[i], codespace - i, framelen);
if (ret < 0) {
printk(KERN_ERR "go7007: insufficient "
"memory for firmware "
"construction\n");
goto fw_failed;
}
i += ret;
} else {
if (codespace - i < chunk_len) {
printk(KERN_ERR "go7007: insufficient "
"memory for firmware "
"construction\n");
goto fw_failed;
}
memcpy(&code[i], &src[2], chunk_len * 2);
i += chunk_len;
}
}
srclen -= chunk_len + 2;
src += chunk_len + 2;
}
release_firmware(fw_entry);
*fw = (u8 *)code;
*fwlen = i * 2;
return 0;
fw_failed:
kfree(code);
release_firmware(fw_entry);
return -1;
}
| gpl-2.0 |
nutsboard/linux-am335x | drivers/infiniband/hw/mthca/mthca_mr.c | 9953 | 23989 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/slab.h>
#include <linux/errno.h>
#include "mthca_dev.h"
#include "mthca_cmd.h"
#include "mthca_memfree.h"
struct mthca_mtt {
struct mthca_buddy *buddy;
int order;
u32 first_seg;
};
/*
* Must be packed because mtt_seg is 64 bits but only aligned to 32 bits.
*/
struct mthca_mpt_entry {
__be32 flags;
__be32 page_size;
__be32 key;
__be32 pd;
__be64 start;
__be64 length;
__be32 lkey;
__be32 window_count;
__be32 window_count_limit;
__be64 mtt_seg;
__be32 mtt_sz; /* Arbel only */
u32 reserved[2];
} __attribute__((packed));
#define MTHCA_MPT_FLAG_SW_OWNS (0xfUL << 28)
#define MTHCA_MPT_FLAG_MIO (1 << 17)
#define MTHCA_MPT_FLAG_BIND_ENABLE (1 << 15)
#define MTHCA_MPT_FLAG_PHYSICAL (1 << 9)
#define MTHCA_MPT_FLAG_REGION (1 << 8)
#define MTHCA_MTT_FLAG_PRESENT 1
#define MTHCA_MPT_STATUS_SW 0xF0
#define MTHCA_MPT_STATUS_HW 0x00
#define SINAI_FMR_KEY_INC 0x1000000
/*
* Buddy allocator for MTT segments (currently not very efficient
* since it doesn't keep a free list and just searches linearly
* through the bitmaps)
*/
static u32 mthca_buddy_alloc(struct mthca_buddy *buddy, int order)
{
int o;
int m;
u32 seg;
spin_lock(&buddy->lock);
for (o = order; o <= buddy->max_order; ++o)
if (buddy->num_free[o]) {
m = 1 << (buddy->max_order - o);
seg = find_first_bit(buddy->bits[o], m);
if (seg < m)
goto found;
}
spin_unlock(&buddy->lock);
return -1;
found:
clear_bit(seg, buddy->bits[o]);
--buddy->num_free[o];
while (o > order) {
--o;
seg <<= 1;
set_bit(seg ^ 1, buddy->bits[o]);
++buddy->num_free[o];
}
spin_unlock(&buddy->lock);
seg <<= order;
return seg;
}
static void mthca_buddy_free(struct mthca_buddy *buddy, u32 seg, int order)
{
seg >>= order;
spin_lock(&buddy->lock);
while (test_bit(seg ^ 1, buddy->bits[order])) {
clear_bit(seg ^ 1, buddy->bits[order]);
--buddy->num_free[order];
seg >>= 1;
++order;
}
set_bit(seg, buddy->bits[order]);
++buddy->num_free[order];
spin_unlock(&buddy->lock);
}
static int mthca_buddy_init(struct mthca_buddy *buddy, int max_order)
{
int i, s;
buddy->max_order = max_order;
spin_lock_init(&buddy->lock);
buddy->bits = kzalloc((buddy->max_order + 1) * sizeof (long *),
GFP_KERNEL);
buddy->num_free = kcalloc((buddy->max_order + 1), sizeof *buddy->num_free,
GFP_KERNEL);
if (!buddy->bits || !buddy->num_free)
goto err_out;
for (i = 0; i <= buddy->max_order; ++i) {
s = BITS_TO_LONGS(1 << (buddy->max_order - i));
buddy->bits[i] = kmalloc(s * sizeof (long), GFP_KERNEL);
if (!buddy->bits[i])
goto err_out_free;
bitmap_zero(buddy->bits[i],
1 << (buddy->max_order - i));
}
set_bit(0, buddy->bits[buddy->max_order]);
buddy->num_free[buddy->max_order] = 1;
return 0;
err_out_free:
for (i = 0; i <= buddy->max_order; ++i)
kfree(buddy->bits[i]);
err_out:
kfree(buddy->bits);
kfree(buddy->num_free);
return -ENOMEM;
}
static void mthca_buddy_cleanup(struct mthca_buddy *buddy)
{
int i;
for (i = 0; i <= buddy->max_order; ++i)
kfree(buddy->bits[i]);
kfree(buddy->bits);
kfree(buddy->num_free);
}
static u32 mthca_alloc_mtt_range(struct mthca_dev *dev, int order,
struct mthca_buddy *buddy)
{
u32 seg = mthca_buddy_alloc(buddy, order);
if (seg == -1)
return -1;
if (mthca_is_memfree(dev))
if (mthca_table_get_range(dev, dev->mr_table.mtt_table, seg,
seg + (1 << order) - 1)) {
mthca_buddy_free(buddy, seg, order);
seg = -1;
}
return seg;
}
static struct mthca_mtt *__mthca_alloc_mtt(struct mthca_dev *dev, int size,
struct mthca_buddy *buddy)
{
struct mthca_mtt *mtt;
int i;
if (size <= 0)
return ERR_PTR(-EINVAL);
mtt = kmalloc(sizeof *mtt, GFP_KERNEL);
if (!mtt)
return ERR_PTR(-ENOMEM);
mtt->buddy = buddy;
mtt->order = 0;
for (i = dev->limits.mtt_seg_size / 8; i < size; i <<= 1)
++mtt->order;
mtt->first_seg = mthca_alloc_mtt_range(dev, mtt->order, buddy);
if (mtt->first_seg == -1) {
kfree(mtt);
return ERR_PTR(-ENOMEM);
}
return mtt;
}
struct mthca_mtt *mthca_alloc_mtt(struct mthca_dev *dev, int size)
{
return __mthca_alloc_mtt(dev, size, &dev->mr_table.mtt_buddy);
}
void mthca_free_mtt(struct mthca_dev *dev, struct mthca_mtt *mtt)
{
if (!mtt)
return;
mthca_buddy_free(mtt->buddy, mtt->first_seg, mtt->order);
mthca_table_put_range(dev, dev->mr_table.mtt_table,
mtt->first_seg,
mtt->first_seg + (1 << mtt->order) - 1);
kfree(mtt);
}
static int __mthca_write_mtt(struct mthca_dev *dev, struct mthca_mtt *mtt,
int start_index, u64 *buffer_list, int list_len)
{
struct mthca_mailbox *mailbox;
__be64 *mtt_entry;
int err = 0;
int i;
mailbox = mthca_alloc_mailbox(dev, GFP_KERNEL);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
mtt_entry = mailbox->buf;
while (list_len > 0) {
mtt_entry[0] = cpu_to_be64(dev->mr_table.mtt_base +
mtt->first_seg * dev->limits.mtt_seg_size +
start_index * 8);
mtt_entry[1] = 0;
for (i = 0; i < list_len && i < MTHCA_MAILBOX_SIZE / 8 - 2; ++i)
mtt_entry[i + 2] = cpu_to_be64(buffer_list[i] |
MTHCA_MTT_FLAG_PRESENT);
/*
* If we have an odd number of entries to write, add
* one more dummy entry for firmware efficiency.
*/
if (i & 1)
mtt_entry[i + 2] = 0;
err = mthca_WRITE_MTT(dev, mailbox, (i + 1) & ~1);
if (err) {
mthca_warn(dev, "WRITE_MTT failed (%d)\n", err);
goto out;
}
list_len -= i;
start_index += i;
buffer_list += i;
}
out:
mthca_free_mailbox(dev, mailbox);
return err;
}
int mthca_write_mtt_size(struct mthca_dev *dev)
{
if (dev->mr_table.fmr_mtt_buddy != &dev->mr_table.mtt_buddy ||
!(dev->mthca_flags & MTHCA_FLAG_FMR))
/*
* Be friendly to WRITE_MTT command
* and leave two empty slots for the
* index and reserved fields of the
* mailbox.
*/
return PAGE_SIZE / sizeof (u64) - 2;
/* For Arbel, all MTTs must fit in the same page. */
return mthca_is_memfree(dev) ? (PAGE_SIZE / sizeof (u64)) : 0x7ffffff;
}
static void mthca_tavor_write_mtt_seg(struct mthca_dev *dev,
struct mthca_mtt *mtt, int start_index,
u64 *buffer_list, int list_len)
{
u64 __iomem *mtts;
int i;
mtts = dev->mr_table.tavor_fmr.mtt_base + mtt->first_seg * dev->limits.mtt_seg_size +
start_index * sizeof (u64);
for (i = 0; i < list_len; ++i)
mthca_write64_raw(cpu_to_be64(buffer_list[i] | MTHCA_MTT_FLAG_PRESENT),
mtts + i);
}
static void mthca_arbel_write_mtt_seg(struct mthca_dev *dev,
struct mthca_mtt *mtt, int start_index,
u64 *buffer_list, int list_len)
{
__be64 *mtts;
dma_addr_t dma_handle;
int i;
int s = start_index * sizeof (u64);
/* For Arbel, all MTTs must fit in the same page. */
BUG_ON(s / PAGE_SIZE != (s + list_len * sizeof(u64) - 1) / PAGE_SIZE);
/* Require full segments */
BUG_ON(s % dev->limits.mtt_seg_size);
mtts = mthca_table_find(dev->mr_table.mtt_table, mtt->first_seg +
s / dev->limits.mtt_seg_size, &dma_handle);
BUG_ON(!mtts);
dma_sync_single_for_cpu(&dev->pdev->dev, dma_handle,
list_len * sizeof (u64), DMA_TO_DEVICE);
for (i = 0; i < list_len; ++i)
mtts[i] = cpu_to_be64(buffer_list[i] | MTHCA_MTT_FLAG_PRESENT);
dma_sync_single_for_device(&dev->pdev->dev, dma_handle,
list_len * sizeof (u64), DMA_TO_DEVICE);
}
int mthca_write_mtt(struct mthca_dev *dev, struct mthca_mtt *mtt,
int start_index, u64 *buffer_list, int list_len)
{
int size = mthca_write_mtt_size(dev);
int chunk;
if (dev->mr_table.fmr_mtt_buddy != &dev->mr_table.mtt_buddy ||
!(dev->mthca_flags & MTHCA_FLAG_FMR))
return __mthca_write_mtt(dev, mtt, start_index, buffer_list, list_len);
while (list_len > 0) {
chunk = min(size, list_len);
if (mthca_is_memfree(dev))
mthca_arbel_write_mtt_seg(dev, mtt, start_index,
buffer_list, chunk);
else
mthca_tavor_write_mtt_seg(dev, mtt, start_index,
buffer_list, chunk);
list_len -= chunk;
start_index += chunk;
buffer_list += chunk;
}
return 0;
}
static inline u32 tavor_hw_index_to_key(u32 ind)
{
return ind;
}
static inline u32 tavor_key_to_hw_index(u32 key)
{
return key;
}
static inline u32 arbel_hw_index_to_key(u32 ind)
{
return (ind >> 24) | (ind << 8);
}
static inline u32 arbel_key_to_hw_index(u32 key)
{
return (key << 24) | (key >> 8);
}
static inline u32 hw_index_to_key(struct mthca_dev *dev, u32 ind)
{
if (mthca_is_memfree(dev))
return arbel_hw_index_to_key(ind);
else
return tavor_hw_index_to_key(ind);
}
static inline u32 key_to_hw_index(struct mthca_dev *dev, u32 key)
{
if (mthca_is_memfree(dev))
return arbel_key_to_hw_index(key);
else
return tavor_key_to_hw_index(key);
}
static inline u32 adjust_key(struct mthca_dev *dev, u32 key)
{
if (dev->mthca_flags & MTHCA_FLAG_SINAI_OPT)
return ((key << 20) & 0x800000) | (key & 0x7fffff);
else
return key;
}
int mthca_mr_alloc(struct mthca_dev *dev, u32 pd, int buffer_size_shift,
u64 iova, u64 total_size, u32 access, struct mthca_mr *mr)
{
struct mthca_mailbox *mailbox;
struct mthca_mpt_entry *mpt_entry;
u32 key;
int i;
int err;
WARN_ON(buffer_size_shift >= 32);
key = mthca_alloc(&dev->mr_table.mpt_alloc);
if (key == -1)
return -ENOMEM;
key = adjust_key(dev, key);
mr->ibmr.rkey = mr->ibmr.lkey = hw_index_to_key(dev, key);
if (mthca_is_memfree(dev)) {
err = mthca_table_get(dev, dev->mr_table.mpt_table, key);
if (err)
goto err_out_mpt_free;
}
mailbox = mthca_alloc_mailbox(dev, GFP_KERNEL);
if (IS_ERR(mailbox)) {
err = PTR_ERR(mailbox);
goto err_out_table;
}
mpt_entry = mailbox->buf;
mpt_entry->flags = cpu_to_be32(MTHCA_MPT_FLAG_SW_OWNS |
MTHCA_MPT_FLAG_MIO |
MTHCA_MPT_FLAG_REGION |
access);
if (!mr->mtt)
mpt_entry->flags |= cpu_to_be32(MTHCA_MPT_FLAG_PHYSICAL);
mpt_entry->page_size = cpu_to_be32(buffer_size_shift - 12);
mpt_entry->key = cpu_to_be32(key);
mpt_entry->pd = cpu_to_be32(pd);
mpt_entry->start = cpu_to_be64(iova);
mpt_entry->length = cpu_to_be64(total_size);
memset(&mpt_entry->lkey, 0,
sizeof *mpt_entry - offsetof(struct mthca_mpt_entry, lkey));
if (mr->mtt)
mpt_entry->mtt_seg =
cpu_to_be64(dev->mr_table.mtt_base +
mr->mtt->first_seg * dev->limits.mtt_seg_size);
if (0) {
mthca_dbg(dev, "Dumping MPT entry %08x:\n", mr->ibmr.lkey);
for (i = 0; i < sizeof (struct mthca_mpt_entry) / 4; ++i) {
if (i % 4 == 0)
printk("[%02x] ", i * 4);
printk(" %08x", be32_to_cpu(((__be32 *) mpt_entry)[i]));
if ((i + 1) % 4 == 0)
printk("\n");
}
}
err = mthca_SW2HW_MPT(dev, mailbox,
key & (dev->limits.num_mpts - 1));
if (err) {
mthca_warn(dev, "SW2HW_MPT failed (%d)\n", err);
goto err_out_mailbox;
}
mthca_free_mailbox(dev, mailbox);
return err;
err_out_mailbox:
mthca_free_mailbox(dev, mailbox);
err_out_table:
mthca_table_put(dev, dev->mr_table.mpt_table, key);
err_out_mpt_free:
mthca_free(&dev->mr_table.mpt_alloc, key);
return err;
}
int mthca_mr_alloc_notrans(struct mthca_dev *dev, u32 pd,
u32 access, struct mthca_mr *mr)
{
mr->mtt = NULL;
return mthca_mr_alloc(dev, pd, 12, 0, ~0ULL, access, mr);
}
int mthca_mr_alloc_phys(struct mthca_dev *dev, u32 pd,
u64 *buffer_list, int buffer_size_shift,
int list_len, u64 iova, u64 total_size,
u32 access, struct mthca_mr *mr)
{
int err;
mr->mtt = mthca_alloc_mtt(dev, list_len);
if (IS_ERR(mr->mtt))
return PTR_ERR(mr->mtt);
err = mthca_write_mtt(dev, mr->mtt, 0, buffer_list, list_len);
if (err) {
mthca_free_mtt(dev, mr->mtt);
return err;
}
err = mthca_mr_alloc(dev, pd, buffer_size_shift, iova,
total_size, access, mr);
if (err)
mthca_free_mtt(dev, mr->mtt);
return err;
}
/* Free mr or fmr */
static void mthca_free_region(struct mthca_dev *dev, u32 lkey)
{
mthca_table_put(dev, dev->mr_table.mpt_table,
key_to_hw_index(dev, lkey));
mthca_free(&dev->mr_table.mpt_alloc, key_to_hw_index(dev, lkey));
}
void mthca_free_mr(struct mthca_dev *dev, struct mthca_mr *mr)
{
int err;
err = mthca_HW2SW_MPT(dev, NULL,
key_to_hw_index(dev, mr->ibmr.lkey) &
(dev->limits.num_mpts - 1));
if (err)
mthca_warn(dev, "HW2SW_MPT failed (%d)\n", err);
mthca_free_region(dev, mr->ibmr.lkey);
mthca_free_mtt(dev, mr->mtt);
}
int mthca_fmr_alloc(struct mthca_dev *dev, u32 pd,
u32 access, struct mthca_fmr *mr)
{
struct mthca_mpt_entry *mpt_entry;
struct mthca_mailbox *mailbox;
u64 mtt_seg;
u32 key, idx;
int list_len = mr->attr.max_pages;
int err = -ENOMEM;
int i;
if (mr->attr.page_shift < 12 || mr->attr.page_shift >= 32)
return -EINVAL;
/* For Arbel, all MTTs must fit in the same page. */
if (mthca_is_memfree(dev) &&
mr->attr.max_pages * sizeof *mr->mem.arbel.mtts > PAGE_SIZE)
return -EINVAL;
mr->maps = 0;
key = mthca_alloc(&dev->mr_table.mpt_alloc);
if (key == -1)
return -ENOMEM;
key = adjust_key(dev, key);
idx = key & (dev->limits.num_mpts - 1);
mr->ibmr.rkey = mr->ibmr.lkey = hw_index_to_key(dev, key);
if (mthca_is_memfree(dev)) {
err = mthca_table_get(dev, dev->mr_table.mpt_table, key);
if (err)
goto err_out_mpt_free;
mr->mem.arbel.mpt = mthca_table_find(dev->mr_table.mpt_table, key, NULL);
BUG_ON(!mr->mem.arbel.mpt);
} else
mr->mem.tavor.mpt = dev->mr_table.tavor_fmr.mpt_base +
sizeof *(mr->mem.tavor.mpt) * idx;
mr->mtt = __mthca_alloc_mtt(dev, list_len, dev->mr_table.fmr_mtt_buddy);
if (IS_ERR(mr->mtt)) {
err = PTR_ERR(mr->mtt);
goto err_out_table;
}
mtt_seg = mr->mtt->first_seg * dev->limits.mtt_seg_size;
if (mthca_is_memfree(dev)) {
mr->mem.arbel.mtts = mthca_table_find(dev->mr_table.mtt_table,
mr->mtt->first_seg,
&mr->mem.arbel.dma_handle);
BUG_ON(!mr->mem.arbel.mtts);
} else
mr->mem.tavor.mtts = dev->mr_table.tavor_fmr.mtt_base + mtt_seg;
mailbox = mthca_alloc_mailbox(dev, GFP_KERNEL);
if (IS_ERR(mailbox)) {
err = PTR_ERR(mailbox);
goto err_out_free_mtt;
}
mpt_entry = mailbox->buf;
mpt_entry->flags = cpu_to_be32(MTHCA_MPT_FLAG_SW_OWNS |
MTHCA_MPT_FLAG_MIO |
MTHCA_MPT_FLAG_REGION |
access);
mpt_entry->page_size = cpu_to_be32(mr->attr.page_shift - 12);
mpt_entry->key = cpu_to_be32(key);
mpt_entry->pd = cpu_to_be32(pd);
memset(&mpt_entry->start, 0,
sizeof *mpt_entry - offsetof(struct mthca_mpt_entry, start));
mpt_entry->mtt_seg = cpu_to_be64(dev->mr_table.mtt_base + mtt_seg);
if (0) {
mthca_dbg(dev, "Dumping MPT entry %08x:\n", mr->ibmr.lkey);
for (i = 0; i < sizeof (struct mthca_mpt_entry) / 4; ++i) {
if (i % 4 == 0)
printk("[%02x] ", i * 4);
printk(" %08x", be32_to_cpu(((__be32 *) mpt_entry)[i]));
if ((i + 1) % 4 == 0)
printk("\n");
}
}
err = mthca_SW2HW_MPT(dev, mailbox,
key & (dev->limits.num_mpts - 1));
if (err) {
mthca_warn(dev, "SW2HW_MPT failed (%d)\n", err);
goto err_out_mailbox_free;
}
mthca_free_mailbox(dev, mailbox);
return 0;
err_out_mailbox_free:
mthca_free_mailbox(dev, mailbox);
err_out_free_mtt:
mthca_free_mtt(dev, mr->mtt);
err_out_table:
mthca_table_put(dev, dev->mr_table.mpt_table, key);
err_out_mpt_free:
mthca_free(&dev->mr_table.mpt_alloc, key);
return err;
}
int mthca_free_fmr(struct mthca_dev *dev, struct mthca_fmr *fmr)
{
if (fmr->maps)
return -EBUSY;
mthca_free_region(dev, fmr->ibmr.lkey);
mthca_free_mtt(dev, fmr->mtt);
return 0;
}
static inline int mthca_check_fmr(struct mthca_fmr *fmr, u64 *page_list,
int list_len, u64 iova)
{
int i, page_mask;
if (list_len > fmr->attr.max_pages)
return -EINVAL;
page_mask = (1 << fmr->attr.page_shift) - 1;
/* We are getting page lists, so va must be page aligned. */
if (iova & page_mask)
return -EINVAL;
/* Trust the user not to pass misaligned data in page_list */
if (0)
for (i = 0; i < list_len; ++i) {
if (page_list[i] & ~page_mask)
return -EINVAL;
}
if (fmr->maps >= fmr->attr.max_maps)
return -EINVAL;
return 0;
}
int mthca_tavor_map_phys_fmr(struct ib_fmr *ibfmr, u64 *page_list,
int list_len, u64 iova)
{
struct mthca_fmr *fmr = to_mfmr(ibfmr);
struct mthca_dev *dev = to_mdev(ibfmr->device);
struct mthca_mpt_entry mpt_entry;
u32 key;
int i, err;
err = mthca_check_fmr(fmr, page_list, list_len, iova);
if (err)
return err;
++fmr->maps;
key = tavor_key_to_hw_index(fmr->ibmr.lkey);
key += dev->limits.num_mpts;
fmr->ibmr.lkey = fmr->ibmr.rkey = tavor_hw_index_to_key(key);
writeb(MTHCA_MPT_STATUS_SW, fmr->mem.tavor.mpt);
for (i = 0; i < list_len; ++i) {
__be64 mtt_entry = cpu_to_be64(page_list[i] |
MTHCA_MTT_FLAG_PRESENT);
mthca_write64_raw(mtt_entry, fmr->mem.tavor.mtts + i);
}
mpt_entry.lkey = cpu_to_be32(key);
mpt_entry.length = cpu_to_be64(list_len * (1ull << fmr->attr.page_shift));
mpt_entry.start = cpu_to_be64(iova);
__raw_writel((__force u32) mpt_entry.lkey, &fmr->mem.tavor.mpt->key);
memcpy_toio(&fmr->mem.tavor.mpt->start, &mpt_entry.start,
offsetof(struct mthca_mpt_entry, window_count) -
offsetof(struct mthca_mpt_entry, start));
writeb(MTHCA_MPT_STATUS_HW, fmr->mem.tavor.mpt);
return 0;
}
int mthca_arbel_map_phys_fmr(struct ib_fmr *ibfmr, u64 *page_list,
int list_len, u64 iova)
{
struct mthca_fmr *fmr = to_mfmr(ibfmr);
struct mthca_dev *dev = to_mdev(ibfmr->device);
u32 key;
int i, err;
err = mthca_check_fmr(fmr, page_list, list_len, iova);
if (err)
return err;
++fmr->maps;
key = arbel_key_to_hw_index(fmr->ibmr.lkey);
if (dev->mthca_flags & MTHCA_FLAG_SINAI_OPT)
key += SINAI_FMR_KEY_INC;
else
key += dev->limits.num_mpts;
fmr->ibmr.lkey = fmr->ibmr.rkey = arbel_hw_index_to_key(key);
*(u8 *) fmr->mem.arbel.mpt = MTHCA_MPT_STATUS_SW;
wmb();
dma_sync_single_for_cpu(&dev->pdev->dev, fmr->mem.arbel.dma_handle,
list_len * sizeof(u64), DMA_TO_DEVICE);
for (i = 0; i < list_len; ++i)
fmr->mem.arbel.mtts[i] = cpu_to_be64(page_list[i] |
MTHCA_MTT_FLAG_PRESENT);
dma_sync_single_for_device(&dev->pdev->dev, fmr->mem.arbel.dma_handle,
list_len * sizeof(u64), DMA_TO_DEVICE);
fmr->mem.arbel.mpt->key = cpu_to_be32(key);
fmr->mem.arbel.mpt->lkey = cpu_to_be32(key);
fmr->mem.arbel.mpt->length = cpu_to_be64(list_len * (1ull << fmr->attr.page_shift));
fmr->mem.arbel.mpt->start = cpu_to_be64(iova);
wmb();
*(u8 *) fmr->mem.arbel.mpt = MTHCA_MPT_STATUS_HW;
wmb();
return 0;
}
void mthca_tavor_fmr_unmap(struct mthca_dev *dev, struct mthca_fmr *fmr)
{
if (!fmr->maps)
return;
fmr->maps = 0;
writeb(MTHCA_MPT_STATUS_SW, fmr->mem.tavor.mpt);
}
void mthca_arbel_fmr_unmap(struct mthca_dev *dev, struct mthca_fmr *fmr)
{
if (!fmr->maps)
return;
fmr->maps = 0;
*(u8 *) fmr->mem.arbel.mpt = MTHCA_MPT_STATUS_SW;
}
int mthca_init_mr_table(struct mthca_dev *dev)
{
phys_addr_t addr;
int mpts, mtts, err, i;
err = mthca_alloc_init(&dev->mr_table.mpt_alloc,
dev->limits.num_mpts,
~0, dev->limits.reserved_mrws);
if (err)
return err;
if (!mthca_is_memfree(dev) &&
(dev->mthca_flags & MTHCA_FLAG_DDR_HIDDEN))
dev->limits.fmr_reserved_mtts = 0;
else
dev->mthca_flags |= MTHCA_FLAG_FMR;
if (dev->mthca_flags & MTHCA_FLAG_SINAI_OPT)
mthca_dbg(dev, "Memory key throughput optimization activated.\n");
err = mthca_buddy_init(&dev->mr_table.mtt_buddy,
fls(dev->limits.num_mtt_segs - 1));
if (err)
goto err_mtt_buddy;
dev->mr_table.tavor_fmr.mpt_base = NULL;
dev->mr_table.tavor_fmr.mtt_base = NULL;
if (dev->limits.fmr_reserved_mtts) {
i = fls(dev->limits.fmr_reserved_mtts - 1);
if (i >= 31) {
mthca_warn(dev, "Unable to reserve 2^31 FMR MTTs.\n");
err = -EINVAL;
goto err_fmr_mpt;
}
mpts = mtts = 1 << i;
} else {
mtts = dev->limits.num_mtt_segs;
mpts = dev->limits.num_mpts;
}
if (!mthca_is_memfree(dev) &&
(dev->mthca_flags & MTHCA_FLAG_FMR)) {
addr = pci_resource_start(dev->pdev, 4) +
((pci_resource_len(dev->pdev, 4) - 1) &
dev->mr_table.mpt_base);
dev->mr_table.tavor_fmr.mpt_base =
ioremap(addr, mpts * sizeof(struct mthca_mpt_entry));
if (!dev->mr_table.tavor_fmr.mpt_base) {
mthca_warn(dev, "MPT ioremap for FMR failed.\n");
err = -ENOMEM;
goto err_fmr_mpt;
}
addr = pci_resource_start(dev->pdev, 4) +
((pci_resource_len(dev->pdev, 4) - 1) &
dev->mr_table.mtt_base);
dev->mr_table.tavor_fmr.mtt_base =
ioremap(addr, mtts * dev->limits.mtt_seg_size);
if (!dev->mr_table.tavor_fmr.mtt_base) {
mthca_warn(dev, "MTT ioremap for FMR failed.\n");
err = -ENOMEM;
goto err_fmr_mtt;
}
}
if (dev->limits.fmr_reserved_mtts) {
err = mthca_buddy_init(&dev->mr_table.tavor_fmr.mtt_buddy, fls(mtts - 1));
if (err)
goto err_fmr_mtt_buddy;
/* Prevent regular MRs from using FMR keys */
err = mthca_buddy_alloc(&dev->mr_table.mtt_buddy, fls(mtts - 1));
if (err)
goto err_reserve_fmr;
dev->mr_table.fmr_mtt_buddy =
&dev->mr_table.tavor_fmr.mtt_buddy;
} else
dev->mr_table.fmr_mtt_buddy = &dev->mr_table.mtt_buddy;
/* FMR table is always the first, take reserved MTTs out of there */
if (dev->limits.reserved_mtts) {
i = fls(dev->limits.reserved_mtts - 1);
if (mthca_alloc_mtt_range(dev, i,
dev->mr_table.fmr_mtt_buddy) == -1) {
mthca_warn(dev, "MTT table of order %d is too small.\n",
dev->mr_table.fmr_mtt_buddy->max_order);
err = -ENOMEM;
goto err_reserve_mtts;
}
}
return 0;
err_reserve_mtts:
err_reserve_fmr:
if (dev->limits.fmr_reserved_mtts)
mthca_buddy_cleanup(&dev->mr_table.tavor_fmr.mtt_buddy);
err_fmr_mtt_buddy:
if (dev->mr_table.tavor_fmr.mtt_base)
iounmap(dev->mr_table.tavor_fmr.mtt_base);
err_fmr_mtt:
if (dev->mr_table.tavor_fmr.mpt_base)
iounmap(dev->mr_table.tavor_fmr.mpt_base);
err_fmr_mpt:
mthca_buddy_cleanup(&dev->mr_table.mtt_buddy);
err_mtt_buddy:
mthca_alloc_cleanup(&dev->mr_table.mpt_alloc);
return err;
}
void mthca_cleanup_mr_table(struct mthca_dev *dev)
{
/* XXX check if any MRs are still allocated? */
if (dev->limits.fmr_reserved_mtts)
mthca_buddy_cleanup(&dev->mr_table.tavor_fmr.mtt_buddy);
mthca_buddy_cleanup(&dev->mr_table.mtt_buddy);
if (dev->mr_table.tavor_fmr.mtt_base)
iounmap(dev->mr_table.tavor_fmr.mtt_base);
if (dev->mr_table.tavor_fmr.mpt_base)
iounmap(dev->mr_table.tavor_fmr.mpt_base);
mthca_alloc_cleanup(&dev->mr_table.mpt_alloc);
}
| gpl-2.0 |
bestmjh47/kernel_msm | drivers/sfi/sfi_core.c | 11489 | 13280 | /* sfi_core.c Simple Firmware Interface - core internals */
/*
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) 2009 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 St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution
in the file called LICENSE.GPL.
BSD LICENSE
Copyright(c) 2009 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of 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.
*/
#define KMSG_COMPONENT "SFI"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/bootmem.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/acpi.h>
#include <linux/init.h>
#include <linux/sfi.h>
#include <linux/slab.h>
#include "sfi_core.h"
#define ON_SAME_PAGE(addr1, addr2) \
(((unsigned long)(addr1) & PAGE_MASK) == \
((unsigned long)(addr2) & PAGE_MASK))
#define TABLE_ON_PAGE(page, table, size) (ON_SAME_PAGE(page, table) && \
ON_SAME_PAGE(page, table + size))
int sfi_disabled __read_mostly;
EXPORT_SYMBOL(sfi_disabled);
static u64 syst_pa __read_mostly;
static struct sfi_table_simple *syst_va __read_mostly;
/*
* FW creates and saves the SFI tables in memory. When these tables get
* used, they may need to be mapped to virtual address space, and the mapping
* can happen before or after the ioremap() is ready, so a flag is needed
* to indicating this
*/
static u32 sfi_use_ioremap __read_mostly;
/*
* sfi_un/map_memory calls early_ioremap/iounmap which is a __init function
* and introduces section mismatch. So use __ref to make it calm.
*/
static void __iomem * __ref sfi_map_memory(u64 phys, u32 size)
{
if (!phys || !size)
return NULL;
if (sfi_use_ioremap)
return ioremap_cache(phys, size);
else
return early_ioremap(phys, size);
}
static void __ref sfi_unmap_memory(void __iomem *virt, u32 size)
{
if (!virt || !size)
return;
if (sfi_use_ioremap)
iounmap(virt);
else
early_iounmap(virt, size);
}
static void sfi_print_table_header(unsigned long long pa,
struct sfi_table_header *header)
{
pr_info("%4.4s %llX, %04X (v%d %6.6s %8.8s)\n",
header->sig, pa,
header->len, header->rev, header->oem_id,
header->oem_table_id);
}
/*
* sfi_verify_table()
* Sanity check table lengh, calculate checksum
*/
static int sfi_verify_table(struct sfi_table_header *table)
{
u8 checksum = 0;
u8 *puchar = (u8 *)table;
u32 length = table->len;
/* Sanity check table length against arbitrary 1MB limit */
if (length > 0x100000) {
pr_err("Invalid table length 0x%x\n", length);
return -1;
}
while (length--)
checksum += *puchar++;
if (checksum) {
pr_err("Checksum %2.2X should be %2.2X\n",
table->csum, table->csum - checksum);
return -1;
}
return 0;
}
/*
* sfi_map_table()
*
* Return address of mapped table
* Check for common case that we can re-use mapping to SYST,
* which requires syst_pa, syst_va to be initialized.
*/
struct sfi_table_header *sfi_map_table(u64 pa)
{
struct sfi_table_header *th;
u32 length;
if (!TABLE_ON_PAGE(syst_pa, pa, sizeof(struct sfi_table_header)))
th = sfi_map_memory(pa, sizeof(struct sfi_table_header));
else
th = (void *)syst_va + (pa - syst_pa);
/* If table fits on same page as its header, we are done */
if (TABLE_ON_PAGE(th, th, th->len))
return th;
/* Entire table does not fit on same page as SYST */
length = th->len;
if (!TABLE_ON_PAGE(syst_pa, pa, sizeof(struct sfi_table_header)))
sfi_unmap_memory(th, sizeof(struct sfi_table_header));
return sfi_map_memory(pa, length);
}
/*
* sfi_unmap_table()
*
* Undoes effect of sfi_map_table() by unmapping table
* if it did not completely fit on same page as SYST.
*/
void sfi_unmap_table(struct sfi_table_header *th)
{
if (!TABLE_ON_PAGE(syst_va, th, th->len))
sfi_unmap_memory(th, TABLE_ON_PAGE(th, th, th->len) ?
sizeof(*th) : th->len);
}
static int sfi_table_check_key(struct sfi_table_header *th,
struct sfi_table_key *key)
{
if (strncmp(th->sig, key->sig, SFI_SIGNATURE_SIZE)
|| (key->oem_id && strncmp(th->oem_id,
key->oem_id, SFI_OEM_ID_SIZE))
|| (key->oem_table_id && strncmp(th->oem_table_id,
key->oem_table_id, SFI_OEM_TABLE_ID_SIZE)))
return -1;
return 0;
}
/*
* This function will be used in 2 cases:
* 1. used to enumerate and verify the tables addressed by SYST/XSDT,
* thus no signature will be given (in kernel boot phase)
* 2. used to parse one specific table, signature must exist, and
* the mapped virt address will be returned, and the virt space
* will be released by call sfi_put_table() later
*
* This two cases are from two different functions with two different
* sections and causes section mismatch warning. So use __ref to tell
* modpost not to make any noise.
*
* Return value:
* NULL: when can't find a table matching the key
* ERR_PTR(error): error value
* virt table address: when a matched table is found
*/
struct sfi_table_header *
__ref sfi_check_table(u64 pa, struct sfi_table_key *key)
{
struct sfi_table_header *th;
void *ret = NULL;
th = sfi_map_table(pa);
if (!th)
return ERR_PTR(-ENOMEM);
if (!key->sig) {
sfi_print_table_header(pa, th);
if (sfi_verify_table(th))
ret = ERR_PTR(-EINVAL);
} else {
if (!sfi_table_check_key(th, key))
return th; /* Success */
}
sfi_unmap_table(th);
return ret;
}
/*
* sfi_get_table()
*
* Search SYST for the specified table with the signature in
* the key, and return the mapped table
*/
struct sfi_table_header *sfi_get_table(struct sfi_table_key *key)
{
struct sfi_table_header *th;
u32 tbl_cnt, i;
tbl_cnt = SFI_GET_NUM_ENTRIES(syst_va, u64);
for (i = 0; i < tbl_cnt; i++) {
th = sfi_check_table(syst_va->pentry[i], key);
if (!IS_ERR(th) && th)
return th;
}
return NULL;
}
void sfi_put_table(struct sfi_table_header *th)
{
sfi_unmap_table(th);
}
/* Find table with signature, run handler on it */
int sfi_table_parse(char *signature, char *oem_id, char *oem_table_id,
sfi_table_handler handler)
{
struct sfi_table_header *table = NULL;
struct sfi_table_key key;
int ret = -EINVAL;
if (sfi_disabled || !handler || !signature)
goto exit;
key.sig = signature;
key.oem_id = oem_id;
key.oem_table_id = oem_table_id;
table = sfi_get_table(&key);
if (!table)
goto exit;
ret = handler(table);
sfi_put_table(table);
exit:
return ret;
}
EXPORT_SYMBOL_GPL(sfi_table_parse);
/*
* sfi_parse_syst()
* Checksum all the tables in SYST and print their headers
*
* success: set syst_va, return 0
*/
static int __init sfi_parse_syst(void)
{
struct sfi_table_key key = SFI_ANY_KEY;
int tbl_cnt, i;
void *ret;
syst_va = sfi_map_memory(syst_pa, sizeof(struct sfi_table_simple));
if (!syst_va)
return -ENOMEM;
tbl_cnt = SFI_GET_NUM_ENTRIES(syst_va, u64);
for (i = 0; i < tbl_cnt; i++) {
ret = sfi_check_table(syst_va->pentry[i], &key);
if (IS_ERR(ret))
return PTR_ERR(ret);
}
return 0;
}
/*
* The OS finds the System Table by searching 16-byte boundaries between
* physical address 0x000E0000 and 0x000FFFFF. The OS shall search this region
* starting at the low address and shall stop searching when the 1st valid SFI
* System Table is found.
*
* success: set syst_pa, return 0
* fail: return -1
*/
static __init int sfi_find_syst(void)
{
unsigned long offset, len;
void *start;
len = SFI_SYST_SEARCH_END - SFI_SYST_SEARCH_BEGIN;
start = sfi_map_memory(SFI_SYST_SEARCH_BEGIN, len);
if (!start)
return -1;
for (offset = 0; offset < len; offset += 16) {
struct sfi_table_header *syst_hdr;
syst_hdr = start + offset;
if (strncmp(syst_hdr->sig, SFI_SIG_SYST,
SFI_SIGNATURE_SIZE))
continue;
if (syst_hdr->len > PAGE_SIZE)
continue;
sfi_print_table_header(SFI_SYST_SEARCH_BEGIN + offset,
syst_hdr);
if (sfi_verify_table(syst_hdr))
continue;
/*
* Enforce SFI spec mandate that SYST reside within a page.
*/
if (!ON_SAME_PAGE(syst_pa, syst_pa + syst_hdr->len)) {
pr_info("SYST 0x%llx + 0x%x crosses page\n",
syst_pa, syst_hdr->len);
continue;
}
/* Success */
syst_pa = SFI_SYST_SEARCH_BEGIN + offset;
sfi_unmap_memory(start, len);
return 0;
}
sfi_unmap_memory(start, len);
return -1;
}
static struct kobject *sfi_kobj;
static struct kobject *tables_kobj;
static ssize_t sfi_table_show(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr, char *buf,
loff_t offset, size_t count)
{
struct sfi_table_attr *tbl_attr =
container_of(bin_attr, struct sfi_table_attr, attr);
struct sfi_table_header *th = NULL;
struct sfi_table_key key;
ssize_t cnt;
key.sig = tbl_attr->name;
key.oem_id = NULL;
key.oem_table_id = NULL;
if (strncmp(SFI_SIG_SYST, tbl_attr->name, SFI_SIGNATURE_SIZE)) {
th = sfi_get_table(&key);
if (!th)
return 0;
cnt = memory_read_from_buffer(buf, count, &offset,
th, th->len);
sfi_put_table(th);
} else
cnt = memory_read_from_buffer(buf, count, &offset,
syst_va, syst_va->header.len);
return cnt;
}
struct sfi_table_attr __init *sfi_sysfs_install_table(u64 pa)
{
struct sfi_table_attr *tbl_attr;
struct sfi_table_header *th;
int ret;
tbl_attr = kzalloc(sizeof(struct sfi_table_attr), GFP_KERNEL);
if (!tbl_attr)
return NULL;
th = sfi_map_table(pa);
if (!th || !th->sig[0]) {
kfree(tbl_attr);
return NULL;
}
sysfs_attr_init(&tbl_attr->attr.attr);
memcpy(tbl_attr->name, th->sig, SFI_SIGNATURE_SIZE);
tbl_attr->attr.size = 0;
tbl_attr->attr.read = sfi_table_show;
tbl_attr->attr.attr.name = tbl_attr->name;
tbl_attr->attr.attr.mode = 0400;
ret = sysfs_create_bin_file(tables_kobj,
&tbl_attr->attr);
if (ret) {
kfree(tbl_attr);
tbl_attr = NULL;
}
sfi_unmap_table(th);
return tbl_attr;
}
static int __init sfi_sysfs_init(void)
{
int tbl_cnt, i;
if (sfi_disabled)
return 0;
sfi_kobj = kobject_create_and_add("sfi", firmware_kobj);
if (!sfi_kobj)
return 0;
tables_kobj = kobject_create_and_add("tables", sfi_kobj);
if (!tables_kobj) {
kobject_put(sfi_kobj);
return 0;
}
sfi_sysfs_install_table(syst_pa);
tbl_cnt = SFI_GET_NUM_ENTRIES(syst_va, u64);
for (i = 0; i < tbl_cnt; i++)
sfi_sysfs_install_table(syst_va->pentry[i]);
sfi_acpi_sysfs_init();
kobject_uevent(sfi_kobj, KOBJ_ADD);
kobject_uevent(tables_kobj, KOBJ_ADD);
pr_info("SFI sysfs interfaces init success\n");
return 0;
}
void __init sfi_init(void)
{
if (!acpi_disabled)
disable_sfi();
if (sfi_disabled)
return;
pr_info("Simple Firmware Interface v0.81 http://simplefirmware.org\n");
if (sfi_find_syst() || sfi_parse_syst() || sfi_platform_init())
disable_sfi();
return;
}
void __init sfi_init_late(void)
{
int length;
if (sfi_disabled)
return;
length = syst_va->header.len;
sfi_unmap_memory(syst_va, sizeof(struct sfi_table_simple));
/* Use ioremap now after it is ready */
sfi_use_ioremap = 1;
syst_va = sfi_map_memory(syst_pa, length);
sfi_acpi_init();
}
/*
* The reason we put it here because we need wait till the /sys/firmware
* is setup, then our interface can be registered in /sys/firmware/sfi
*/
core_initcall(sfi_sysfs_init);
| gpl-2.0 |
yangyang1989/linux-3.8.2-mini2440 | fs/ext2/symlink.c | 12769 | 1344 | /*
* linux/fs/ext2/symlink.c
*
* Only fast symlinks left here - the rest is done by generic code. AV, 1999
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/symlink.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext2 symlink handling code
*/
#include "ext2.h"
#include "xattr.h"
#include <linux/namei.h>
static void *ext2_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct ext2_inode_info *ei = EXT2_I(dentry->d_inode);
nd_set_link(nd, (char *)ei->i_data);
return NULL;
}
const struct inode_operations ext2_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
.setattr = ext2_setattr,
#ifdef CONFIG_EXT2_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext2_listxattr,
.removexattr = generic_removexattr,
#endif
};
const struct inode_operations ext2_fast_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = ext2_follow_link,
.setattr = ext2_setattr,
#ifdef CONFIG_EXT2_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext2_listxattr,
.removexattr = generic_removexattr,
#endif
};
| gpl-2.0 |
JoeyJiao/kernel-2.6.32-V858 | fs/ext2/super.c | 482 | 40400 | /*
* linux/fs/ext2/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/parser.h>
#include <linux/random.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/smp_lock.h>
#include <linux/vfs.h>
#include <linux/seq_file.h>
#include <linux/mount.h>
#include <linux/log2.h>
#include <linux/quotaops.h>
#include <asm/uaccess.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
#include "xip.h"
static void ext2_sync_super(struct super_block *sb,
struct ext2_super_block *es);
static int ext2_remount (struct super_block * sb, int * flags, char * data);
static int ext2_statfs (struct dentry * dentry, struct kstatfs * buf);
static int ext2_sync_fs(struct super_block *sb, int wait);
void ext2_error (struct super_block * sb, const char * function,
const char * fmt, ...)
{
va_list args;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
if (!(sb->s_flags & MS_RDONLY)) {
sbi->s_mount_state |= EXT2_ERROR_FS;
es->s_state |= cpu_to_le16(EXT2_ERROR_FS);
ext2_sync_super(sb, es);
}
va_start(args, fmt);
printk(KERN_CRIT "EXT2-fs error (device %s): %s: ",sb->s_id, function);
vprintk(fmt, args);
printk("\n");
va_end(args);
if (test_opt(sb, ERRORS_PANIC))
panic("EXT2-fs panic from previous error\n");
if (test_opt(sb, ERRORS_RO)) {
printk("Remounting filesystem read-only\n");
sb->s_flags |= MS_RDONLY;
}
}
void ext2_warning (struct super_block * sb, const char * function,
const char * fmt, ...)
{
va_list args;
va_start(args, fmt);
printk(KERN_WARNING "EXT2-fs warning (device %s): %s: ",
sb->s_id, function);
vprintk(fmt, args);
printk("\n");
va_end(args);
}
void ext2_update_dynamic_rev(struct super_block *sb)
{
struct ext2_super_block *es = EXT2_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT2_GOOD_OLD_REV)
return;
ext2_warning(sb, __func__,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT2_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT2_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT2_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT2_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
lock_kernel();
if (sb->s_dirt)
ext2_write_super(sb);
ext2_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
es->s_state = cpu_to_le16(sbi->s_mount_state);
ext2_sync_super(sb, es);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
unlock_kernel();
}
static struct kmem_cache * ext2_inode_cachep;
static struct inode *ext2_alloc_inode(struct super_block *sb)
{
struct ext2_inode_info *ei;
ei = (struct ext2_inode_info *)kmem_cache_alloc(ext2_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
ei->i_block_alloc_info = NULL;
ei->vfs_inode.i_version = 1;
return &ei->vfs_inode;
}
static void ext2_destroy_inode(struct inode *inode)
{
kmem_cache_free(ext2_inode_cachep, EXT2_I(inode));
}
static void init_once(void *foo)
{
struct ext2_inode_info *ei = (struct ext2_inode_info *) foo;
rwlock_init(&ei->i_meta_lock);
#ifdef CONFIG_EXT2_FS_XATTR
init_rwsem(&ei->xattr_sem);
#endif
mutex_init(&ei->truncate_mutex);
inode_init_once(&ei->vfs_inode);
}
static int init_inodecache(void)
{
ext2_inode_cachep = kmem_cache_create("ext2_inode_cache",
sizeof(struct ext2_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (ext2_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
kmem_cache_destroy(ext2_inode_cachep);
}
static void ext2_clear_inode(struct inode *inode)
{
struct ext2_block_alloc_info *rsv = EXT2_I(inode)->i_block_alloc_info;
ext2_discard_reservation(inode);
EXT2_I(inode)->i_block_alloc_info = NULL;
if (unlikely(rsv))
kfree(rsv);
}
static int ext2_show_options(struct seq_file *seq, struct vfsmount *vfs)
{
struct super_block *sb = vfs->mnt_sb;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
unsigned long def_mount_opts;
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (sbi->s_sb_block != 1)
seq_printf(seq, ",sb=%lu", sbi->s_sb_block);
if (test_opt(sb, MINIX_DF))
seq_puts(seq, ",minixdf");
if (test_opt(sb, GRPID))
seq_puts(seq, ",grpid");
if (!test_opt(sb, GRPID) && (def_mount_opts & EXT2_DEFM_BSDGROUPS))
seq_puts(seq, ",nogrpid");
if (sbi->s_resuid != EXT2_DEF_RESUID ||
le16_to_cpu(es->s_def_resuid) != EXT2_DEF_RESUID) {
seq_printf(seq, ",resuid=%u", sbi->s_resuid);
}
if (sbi->s_resgid != EXT2_DEF_RESGID ||
le16_to_cpu(es->s_def_resgid) != EXT2_DEF_RESGID) {
seq_printf(seq, ",resgid=%u", sbi->s_resgid);
}
if (test_opt(sb, ERRORS_RO)) {
int def_errors = le16_to_cpu(es->s_errors);
if (def_errors == EXT2_ERRORS_PANIC ||
def_errors == EXT2_ERRORS_CONTINUE) {
seq_puts(seq, ",errors=remount-ro");
}
}
if (test_opt(sb, ERRORS_CONT))
seq_puts(seq, ",errors=continue");
if (test_opt(sb, ERRORS_PANIC))
seq_puts(seq, ",errors=panic");
if (test_opt(sb, NO_UID32))
seq_puts(seq, ",nouid32");
if (test_opt(sb, DEBUG))
seq_puts(seq, ",debug");
if (test_opt(sb, OLDALLOC))
seq_puts(seq, ",oldalloc");
#ifdef CONFIG_EXT2_FS_XATTR
if (test_opt(sb, XATTR_USER))
seq_puts(seq, ",user_xattr");
if (!test_opt(sb, XATTR_USER) &&
(def_mount_opts & EXT2_DEFM_XATTR_USER)) {
seq_puts(seq, ",nouser_xattr");
}
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
if (test_opt(sb, POSIX_ACL))
seq_puts(seq, ",acl");
if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT2_DEFM_ACL))
seq_puts(seq, ",noacl");
#endif
if (test_opt(sb, NOBH))
seq_puts(seq, ",nobh");
#if defined(CONFIG_QUOTA)
if (sbi->s_mount_opt & EXT2_MOUNT_USRQUOTA)
seq_puts(seq, ",usrquota");
if (sbi->s_mount_opt & EXT2_MOUNT_GRPQUOTA)
seq_puts(seq, ",grpquota");
#endif
#if defined(CONFIG_EXT2_FS_XIP)
if (sbi->s_mount_opt & EXT2_MOUNT_XIP)
seq_puts(seq, ",xip");
#endif
if (!test_opt(sb, RESERVATION))
seq_puts(seq, ",noreservation");
return 0;
}
#ifdef CONFIG_QUOTA
static ssize_t ext2_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off);
static ssize_t ext2_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off);
#endif
static const struct super_operations ext2_sops = {
.alloc_inode = ext2_alloc_inode,
.destroy_inode = ext2_destroy_inode,
.write_inode = ext2_write_inode,
.delete_inode = ext2_delete_inode,
.put_super = ext2_put_super,
.write_super = ext2_write_super,
.sync_fs = ext2_sync_fs,
.statfs = ext2_statfs,
.remount_fs = ext2_remount,
.clear_inode = ext2_clear_inode,
.show_options = ext2_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext2_quota_read,
.quota_write = ext2_quota_write,
#endif
};
static struct inode *ext2_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT2_FIRST_INO(sb) && ino != EXT2_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
* ext2_read_inode currently does appropriate checks, but
* it might be "neater" to call ext2_get_inode first and check
* if the inode is valid.....
*/
inode = ext2_iget(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
/* we didn't find the right inode.. */
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext2_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext2_nfs_get_inode);
}
static struct dentry *ext2_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext2_nfs_get_inode);
}
/* Yes, most of these are left as NULL!!
* A NULL value implies the default, which works with ext2-like file
* systems, but can be improved upon.
* Currently only get_parent is required.
*/
static const struct export_operations ext2_export_ops = {
.fh_to_dentry = ext2_fh_to_dentry,
.fh_to_parent = ext2_fh_to_parent,
.get_parent = ext2_get_parent,
};
static unsigned long get_sb_block(void **data)
{
unsigned long sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk("EXT2-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic,
Opt_err_ro, Opt_nouid32, Opt_nocheck, Opt_debug,
Opt_oldalloc, Opt_orlov, Opt_nobh, Opt_user_xattr, Opt_nouser_xattr,
Opt_acl, Opt_noacl, Opt_xip, Opt_ignore, Opt_err, Opt_quota,
Opt_usrquota, Opt_grpquota, Opt_reservation, Opt_noreservation
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_nocheck, "check=none"},
{Opt_nocheck, "nocheck"},
{Opt_debug, "debug"},
{Opt_oldalloc, "oldalloc"},
{Opt_orlov, "orlov"},
{Opt_nobh, "nobh"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_xip, "xip"},
{Opt_grpquota, "grpquota"},
{Opt_ignore, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_reservation, "reservation"},
{Opt_noreservation, "noreservation"},
{Opt_err, NULL}
};
static int parse_options (char * options,
struct ext2_sb_info *sbi)
{
char * p;
substring_t args[MAX_OPT_ARGS];
int option;
if (!options)
return 1;
while ((p = strsep (&options, ",")) != NULL) {
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_bsd_df:
clear_opt (sbi->s_mount_opt, MINIX_DF);
break;
case Opt_minix_df:
set_opt (sbi->s_mount_opt, MINIX_DF);
break;
case Opt_grpid:
set_opt (sbi->s_mount_opt, GRPID);
break;
case Opt_nogrpid:
clear_opt (sbi->s_mount_opt, GRPID);
break;
case Opt_resuid:
if (match_int(&args[0], &option))
return 0;
sbi->s_resuid = option;
break;
case Opt_resgid:
if (match_int(&args[0], &option))
return 0;
sbi->s_resgid = option;
break;
case Opt_sb:
/* handled by get_sb_block() instead of here */
/* *sb_block = match_int(&args[0]); */
break;
case Opt_err_panic:
clear_opt (sbi->s_mount_opt, ERRORS_CONT);
clear_opt (sbi->s_mount_opt, ERRORS_RO);
set_opt (sbi->s_mount_opt, ERRORS_PANIC);
break;
case Opt_err_ro:
clear_opt (sbi->s_mount_opt, ERRORS_CONT);
clear_opt (sbi->s_mount_opt, ERRORS_PANIC);
set_opt (sbi->s_mount_opt, ERRORS_RO);
break;
case Opt_err_cont:
clear_opt (sbi->s_mount_opt, ERRORS_RO);
clear_opt (sbi->s_mount_opt, ERRORS_PANIC);
set_opt (sbi->s_mount_opt, ERRORS_CONT);
break;
case Opt_nouid32:
set_opt (sbi->s_mount_opt, NO_UID32);
break;
case Opt_nocheck:
clear_opt (sbi->s_mount_opt, CHECK);
break;
case Opt_debug:
set_opt (sbi->s_mount_opt, DEBUG);
break;
case Opt_oldalloc:
set_opt (sbi->s_mount_opt, OLDALLOC);
break;
case Opt_orlov:
clear_opt (sbi->s_mount_opt, OLDALLOC);
break;
case Opt_nobh:
set_opt (sbi->s_mount_opt, NOBH);
break;
#ifdef CONFIG_EXT2_FS_XATTR
case Opt_user_xattr:
set_opt (sbi->s_mount_opt, XATTR_USER);
break;
case Opt_nouser_xattr:
clear_opt (sbi->s_mount_opt, XATTR_USER);
break;
#else
case Opt_user_xattr:
case Opt_nouser_xattr:
printk("EXT2 (no)user_xattr options not supported\n");
break;
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
case Opt_acl:
set_opt(sbi->s_mount_opt, POSIX_ACL);
break;
case Opt_noacl:
clear_opt(sbi->s_mount_opt, POSIX_ACL);
break;
#else
case Opt_acl:
case Opt_noacl:
printk("EXT2 (no)acl options not supported\n");
break;
#endif
case Opt_xip:
#ifdef CONFIG_EXT2_FS_XIP
set_opt (sbi->s_mount_opt, XIP);
#else
printk("EXT2 xip option not supported\n");
#endif
break;
#if defined(CONFIG_QUOTA)
case Opt_quota:
case Opt_usrquota:
set_opt(sbi->s_mount_opt, USRQUOTA);
break;
case Opt_grpquota:
set_opt(sbi->s_mount_opt, GRPQUOTA);
break;
#else
case Opt_quota:
case Opt_usrquota:
case Opt_grpquota:
printk(KERN_ERR
"EXT2-fs: quota operations not supported.\n");
break;
#endif
case Opt_reservation:
set_opt(sbi->s_mount_opt, RESERVATION);
printk("reservations ON\n");
break;
case Opt_noreservation:
clear_opt(sbi->s_mount_opt, RESERVATION);
printk("reservations OFF\n");
break;
case Opt_ignore:
break;
default:
return 0;
}
}
return 1;
}
static int ext2_setup_super (struct super_block * sb,
struct ext2_super_block * es,
int read_only)
{
int res = 0;
struct ext2_sb_info *sbi = EXT2_SB(sb);
if (le32_to_cpu(es->s_rev_level) > EXT2_MAX_SUPP_REV) {
printk ("EXT2-fs warning: revision level too high, "
"forcing read-only mode\n");
res = MS_RDONLY;
}
if (read_only)
return res;
if (!(sbi->s_mount_state & EXT2_VALID_FS))
printk ("EXT2-fs warning: mounting unchecked fs, "
"running e2fsck is recommended\n");
else if ((sbi->s_mount_state & EXT2_ERROR_FS))
printk ("EXT2-fs warning: mounting fs with errors, "
"running e2fsck is recommended\n");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) >= 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
printk ("EXT2-fs warning: maximal mount count reached, "
"running e2fsck is recommended\n");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) + le32_to_cpu(es->s_checkinterval) <= get_seconds()))
printk ("EXT2-fs warning: checktime reached, "
"running e2fsck is recommended\n");
if (!le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT2_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
ext2_write_super(sb);
if (test_opt (sb, DEBUG))
printk ("[EXT II FS %s, %s, bs=%lu, fs=%lu, gc=%lu, "
"bpg=%lu, ipg=%lu, mo=%04lx]\n",
EXT2FS_VERSION, EXT2FS_DATE, sb->s_blocksize,
sbi->s_frag_size,
sbi->s_groups_count,
EXT2_BLOCKS_PER_GROUP(sb),
EXT2_INODES_PER_GROUP(sb),
sbi->s_mount_opt);
return res;
}
static int ext2_check_descriptors(struct super_block *sb)
{
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
ext2_debug ("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext2_group_desc *gdp = ext2_get_group_desc(sb, i, NULL);
ext2_fsblk_t first_block = ext2_group_first_block_no(sb, i);
ext2_fsblk_t last_block;
if (i == sbi->s_groups_count - 1)
last_block = le32_to_cpu(sbi->s_es->s_blocks_count) - 1;
else
last_block = first_block +
(EXT2_BLOCKS_PER_GROUP(sb) - 1);
if (le32_to_cpu(gdp->bg_block_bitmap) < first_block ||
le32_to_cpu(gdp->bg_block_bitmap) > last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Block bitmap for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_block_bitmap));
return 0;
}
if (le32_to_cpu(gdp->bg_inode_bitmap) < first_block ||
le32_to_cpu(gdp->bg_inode_bitmap) > last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Inode bitmap for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_inode_bitmap));
return 0;
}
if (le32_to_cpu(gdp->bg_inode_table) < first_block ||
le32_to_cpu(gdp->bg_inode_table) + sbi->s_itb_per_group - 1 >
last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Inode table for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_inode_table));
return 0;
}
}
return 1;
}
/*
* Maximal file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^32 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^32 sector limit.
*/
static loff_t ext2_max_size(int bits)
{
loff_t res = EXT2_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a
* dense, file such that the total number of
* sectors in the file, including data and all indirect blocks,
* does not exceed 2^32 -1
* __u32 i_blocks representing the total number of
* 512 bytes blocks of the file
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static unsigned long descriptor_loc(struct super_block *sb,
unsigned long logic_sb_block,
int nr)
{
struct ext2_sb_info *sbi = EXT2_SB(sb);
unsigned long bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!EXT2_HAS_INCOMPAT_FEATURE(sb, EXT2_FEATURE_INCOMPAT_META_BG) ||
nr < first_meta_bg)
return (logic_sb_block + nr + 1);
bg = sbi->s_desc_per_block * nr;
if (ext2_bg_has_super(sb, bg))
has_super = 1;
return ext2_group_first_block_no(sb, bg) + has_super;
}
static int ext2_fill_super(struct super_block *sb, void *data, int silent)
{
struct buffer_head * bh;
struct ext2_sb_info * sbi;
struct ext2_super_block * es;
struct inode *root;
unsigned long block;
unsigned long sb_block = get_sb_block(&data);
unsigned long logic_sb_block;
unsigned long offset = 0;
unsigned long def_mount_opts;
long ret = -EINVAL;
int blocksize = BLOCK_SIZE;
int db_count;
int i, j;
__le32 features;
int err;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
return -ENOMEM;
}
sb->s_fs_info = sbi;
sbi->s_sb_block = sb_block;
/*
* See what the current blocksize for the device is, and
* use that as the blocksize. Otherwise (or if the blocksize
* is smaller than the default) use the default.
* This is important for devices that have a hardware
* sectorsize that is larger than the default.
*/
blocksize = sb_min_blocksize(sb, BLOCK_SIZE);
if (!blocksize) {
printk ("EXT2-fs: unable to set blocksize\n");
goto failed_sbi;
}
/*
* If the superblock doesn't start on a hardware sector boundary,
* calculate the offset.
*/
if (blocksize != BLOCK_SIZE) {
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
} else {
logic_sb_block = sb_block;
}
if (!(bh = sb_bread(sb, logic_sb_block))) {
printk ("EXT2-fs: unable to read superblock\n");
goto failed_sbi;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext2 macro-instructions depend on its value
*/
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (def_mount_opts & EXT2_DEFM_DEBUG)
set_opt(sbi->s_mount_opt, DEBUG);
if (def_mount_opts & EXT2_DEFM_BSDGROUPS)
set_opt(sbi->s_mount_opt, GRPID);
if (def_mount_opts & EXT2_DEFM_UID16)
set_opt(sbi->s_mount_opt, NO_UID32);
#ifdef CONFIG_EXT2_FS_XATTR
if (def_mount_opts & EXT2_DEFM_XATTR_USER)
set_opt(sbi->s_mount_opt, XATTR_USER);
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
if (def_mount_opts & EXT2_DEFM_ACL)
set_opt(sbi->s_mount_opt, POSIX_ACL);
#endif
if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_PANIC)
set_opt(sbi->s_mount_opt, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_CONTINUE)
set_opt(sbi->s_mount_opt, ERRORS_CONT);
else
set_opt(sbi->s_mount_opt, ERRORS_RO);
sbi->s_resuid = le16_to_cpu(es->s_def_resuid);
sbi->s_resgid = le16_to_cpu(es->s_def_resgid);
set_opt(sbi->s_mount_opt, RESERVATION);
if (!parse_options ((char *) data, sbi))
goto failed_mount;
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((EXT2_SB(sb)->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ?
MS_POSIXACL : 0);
ext2_xip_verify_sb(sb); /* see if bdev supports xip, unset
EXT2_MOUNT_XIP if not */
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV &&
(EXT2_HAS_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_INCOMPAT_FEATURE(sb, ~0U)))
printk("EXT2-fs warning: feature flags set on rev 0 fs, "
"running e2fsck is recommended\n");
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
features = EXT2_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP);
if (features) {
printk("EXT2-fs: %s: couldn't mount because of "
"unsupported optional features (%x).\n",
sb->s_id, le32_to_cpu(features));
goto failed_mount;
}
if (!(sb->s_flags & MS_RDONLY) &&
(features = EXT2_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))){
printk("EXT2-fs: %s: couldn't mount RDWR because of "
"unsupported optional features (%x).\n",
sb->s_id, le32_to_cpu(features));
goto failed_mount;
}
blocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (ext2_use_xip(sb) && blocksize != PAGE_SIZE) {
if (!silent)
printk("XIP: Unsupported blocksize\n");
goto failed_mount;
}
/* If the blocksize doesn't match, re-read the thing.. */
if (sb->s_blocksize != blocksize) {
brelse(bh);
if (!sb_set_blocksize(sb, blocksize)) {
printk(KERN_ERR "EXT2-fs: blocksize too small for device.\n");
goto failed_sbi;
}
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
bh = sb_bread(sb, logic_sb_block);
if(!bh) {
printk("EXT2-fs: Couldn't read superblock on "
"2nd try.\n");
goto failed_sbi;
}
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT2_SUPER_MAGIC)) {
printk ("EXT2-fs: Magic mismatch, very weird !\n");
goto failed_mount;
}
}
sb->s_maxbytes = ext2_max_size(sb->s_blocksize_bits);
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV) {
sbi->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT2_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT2_GOOD_OLD_INODE_SIZE) ||
!is_power_of_2(sbi->s_inode_size) ||
(sbi->s_inode_size > blocksize)) {
printk ("EXT2-fs: unsupported inode size: %d\n",
sbi->s_inode_size);
goto failed_mount;
}
}
sbi->s_frag_size = EXT2_MIN_FRAG_SIZE <<
le32_to_cpu(es->s_log_frag_size);
if (sbi->s_frag_size == 0)
goto cantfind_ext2;
sbi->s_frags_per_block = sb->s_blocksize / sbi->s_frag_size;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT2_INODE_SIZE(sb) == 0)
goto cantfind_ext2;
sbi->s_inodes_per_block = sb->s_blocksize / EXT2_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0 || sbi->s_inodes_per_group == 0)
goto cantfind_ext2;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = sb->s_blocksize /
sizeof (struct ext2_group_desc);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits =
ilog2 (EXT2_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits =
ilog2 (EXT2_DESC_PER_BLOCK(sb));
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
if (sb->s_blocksize != bh->b_size) {
if (!silent)
printk ("VFS: Unsupported blocksize on dev "
"%s.\n", sb->s_id);
goto failed_mount;
}
if (sb->s_blocksize != sbi->s_frag_size) {
printk ("EXT2-fs: fragsize %lu != blocksize %lu (not supported yet)\n",
sbi->s_frag_size, sb->s_blocksize);
goto failed_mount;
}
if (sbi->s_blocks_per_group > sb->s_blocksize * 8) {
printk ("EXT2-fs: #blocks per group too big: %lu\n",
sbi->s_blocks_per_group);
goto failed_mount;
}
if (sbi->s_frags_per_group > sb->s_blocksize * 8) {
printk ("EXT2-fs: #fragments per group too big: %lu\n",
sbi->s_frags_per_group);
goto failed_mount;
}
if (sbi->s_inodes_per_group > sb->s_blocksize * 8) {
printk ("EXT2-fs: #inodes per group too big: %lu\n",
sbi->s_inodes_per_group);
goto failed_mount;
}
if (EXT2_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext2;
sbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) -
le32_to_cpu(es->s_first_data_block) - 1)
/ EXT2_BLOCKS_PER_GROUP(sb)) + 1;
db_count = (sbi->s_groups_count + EXT2_DESC_PER_BLOCK(sb) - 1) /
EXT2_DESC_PER_BLOCK(sb);
sbi->s_group_desc = kmalloc (db_count * sizeof (struct buffer_head *), GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
printk ("EXT2-fs: not enough memory\n");
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
sbi->s_debts = kcalloc(sbi->s_groups_count, sizeof(*sbi->s_debts), GFP_KERNEL);
if (!sbi->s_debts) {
printk ("EXT2-fs: not enough memory\n");
goto failed_mount_group_desc;
}
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logic_sb_block, i);
sbi->s_group_desc[i] = sb_bread(sb, block);
if (!sbi->s_group_desc[i]) {
for (j = 0; j < i; j++)
brelse (sbi->s_group_desc[j]);
printk ("EXT2-fs: unable to read group descriptors\n");
goto failed_mount_group_desc;
}
}
if (!ext2_check_descriptors (sb)) {
printk ("EXT2-fs: group descriptors corrupted!\n");
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
/* per fileystem reservation list head & lock */
spin_lock_init(&sbi->s_rsv_window_lock);
sbi->s_rsv_window_root = RB_ROOT;
/*
* Add a single, static dummy reservation to the start of the
* reservation window list --- it gives us a placeholder for
* append-at-start-of-list which makes the allocation logic
* _much_ simpler.
*/
sbi->s_rsv_window_head.rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_alloc_hit = 0;
sbi->s_rsv_window_head.rsv_goal_size = 0;
ext2_rsv_window_add(sb, &sbi->s_rsv_window_head);
err = percpu_counter_init(&sbi->s_freeblocks_counter,
ext2_count_free_blocks(sb));
if (!err) {
err = percpu_counter_init(&sbi->s_freeinodes_counter,
ext2_count_free_inodes(sb));
}
if (!err) {
err = percpu_counter_init(&sbi->s_dirs_counter,
ext2_count_dirs(sb));
}
if (err) {
printk(KERN_ERR "EXT2-fs: insufficient memory\n");
goto failed_mount3;
}
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext2_sops;
sb->s_export_op = &ext2_export_ops;
sb->s_xattr = ext2_xattr_handlers;
root = ext2_iget(sb, EXT2_ROOT_INO);
if (IS_ERR(root)) {
ret = PTR_ERR(root);
goto failed_mount3;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
iput(root);
printk(KERN_ERR "EXT2-fs: corrupt root inode, run e2fsck\n");
goto failed_mount3;
}
sb->s_root = d_alloc_root(root);
if (!sb->s_root) {
iput(root);
printk(KERN_ERR "EXT2-fs: get root inode failed\n");
ret = -ENOMEM;
goto failed_mount3;
}
if (EXT2_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL))
ext2_warning(sb, __func__,
"mounting ext3 filesystem as ext2");
ext2_setup_super (sb, es, sb->s_flags & MS_RDONLY);
return 0;
cantfind_ext2:
if (!silent)
printk("VFS: Can't find an ext2 filesystem on dev %s.\n",
sb->s_id);
goto failed_mount;
failed_mount3:
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
failed_mount_group_desc:
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
failed_mount:
brelse(bh);
failed_sbi:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
return ret;
}
static void ext2_commit_super (struct super_block * sb,
struct ext2_super_block * es)
{
es->s_wtime = cpu_to_le32(get_seconds());
mark_buffer_dirty(EXT2_SB(sb)->s_sbh);
sb->s_dirt = 0;
}
static void ext2_sync_super(struct super_block *sb, struct ext2_super_block *es)
{
es->s_free_blocks_count = cpu_to_le32(ext2_count_free_blocks(sb));
es->s_free_inodes_count = cpu_to_le32(ext2_count_free_inodes(sb));
es->s_wtime = cpu_to_le32(get_seconds());
mark_buffer_dirty(EXT2_SB(sb)->s_sbh);
sync_dirty_buffer(EXT2_SB(sb)->s_sbh);
sb->s_dirt = 0;
}
/*
* In the second extended file system, it is not necessary to
* write the super block since we use a mapping of the
* disk super block in a buffer.
*
* However, this function is still used to set the fs valid
* flags to 0. We need to set this flag to 0 since the fs
* may have been checked while mounted and e2fsck may have
* set s_state to EXT2_VALID_FS after some corrections.
*/
static int ext2_sync_fs(struct super_block *sb, int wait)
{
struct ext2_super_block *es = EXT2_SB(sb)->s_es;
lock_kernel();
if (es->s_state & cpu_to_le16(EXT2_VALID_FS)) {
ext2_debug("setting valid to 0\n");
es->s_state &= cpu_to_le16(~EXT2_VALID_FS);
es->s_free_blocks_count =
cpu_to_le32(ext2_count_free_blocks(sb));
es->s_free_inodes_count =
cpu_to_le32(ext2_count_free_inodes(sb));
es->s_mtime = cpu_to_le32(get_seconds());
ext2_sync_super(sb, es);
} else {
ext2_commit_super(sb, es);
}
sb->s_dirt = 0;
unlock_kernel();
return 0;
}
void ext2_write_super(struct super_block *sb)
{
if (!(sb->s_flags & MS_RDONLY))
ext2_sync_fs(sb, 1);
else
sb->s_dirt = 0;
}
static int ext2_remount (struct super_block * sb, int * flags, char * data)
{
struct ext2_sb_info * sbi = EXT2_SB(sb);
struct ext2_super_block * es;
unsigned long old_mount_opt = sbi->s_mount_opt;
struct ext2_mount_options old_opts;
unsigned long old_sb_flags;
int err;
lock_kernel();
/* Store the old options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
/*
* Allow the "check" option to be passed as a remount option.
*/
if (!parse_options (data, sbi)) {
err = -EINVAL;
goto restore_opts;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((sbi->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0);
ext2_xip_verify_sb(sb); /* see if bdev supports xip, unset
EXT2_MOUNT_XIP if not */
if ((ext2_use_xip(sb)) && (sb->s_blocksize != PAGE_SIZE)) {
printk("XIP: Unsupported blocksize\n");
err = -EINVAL;
goto restore_opts;
}
es = sbi->s_es;
if (((sbi->s_mount_opt & EXT2_MOUNT_XIP) !=
(old_mount_opt & EXT2_MOUNT_XIP)) &&
invalidate_inodes(sb)) {
ext2_warning(sb, __func__, "refusing change of xip flag "
"with busy inodes while remounting");
sbi->s_mount_opt &= ~EXT2_MOUNT_XIP;
sbi->s_mount_opt |= old_mount_opt & EXT2_MOUNT_XIP;
}
if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) {
unlock_kernel();
return 0;
}
if (*flags & MS_RDONLY) {
if (le16_to_cpu(es->s_state) & EXT2_VALID_FS ||
!(sbi->s_mount_state & EXT2_VALID_FS)) {
unlock_kernel();
return 0;
}
/*
* OK, we are remounting a valid rw partition rdonly, so set
* the rdonly flag and then mark the partition as valid again.
*/
es->s_state = cpu_to_le16(sbi->s_mount_state);
es->s_mtime = cpu_to_le32(get_seconds());
} else {
__le32 ret = EXT2_HAS_RO_COMPAT_FEATURE(sb,
~EXT2_FEATURE_RO_COMPAT_SUPP);
if (ret) {
printk("EXT2-fs: %s: couldn't remount RDWR because of "
"unsupported optional features (%x).\n",
sb->s_id, le32_to_cpu(ret));
err = -EROFS;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread and
* store the current valid flag. (It may have been changed
* by e2fsck since we originally mounted the partition.)
*/
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext2_setup_super (sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
}
ext2_sync_super(sb, es);
unlock_kernel();
return 0;
restore_opts:
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sb->s_flags = old_sb_flags;
unlock_kernel();
return err;
}
static int ext2_statfs (struct dentry * dentry, struct kstatfs * buf)
{
struct super_block *sb = dentry->d_sb;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
u64 fsid;
if (test_opt (sb, MINIX_DF))
sbi->s_overhead_last = 0;
else if (sbi->s_blocks_last != le32_to_cpu(es->s_blocks_count)) {
unsigned long i, overhead = 0;
smp_rmb();
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are
* overhead
*/
overhead = le32_to_cpu(es->s_first_data_block);
/*
* Add the overhead attributed to the superblock and
* block group descriptors. If the sparse superblocks
* feature is turned on, then not all groups have this.
*/
for (i = 0; i < sbi->s_groups_count; i++)
overhead += ext2_bg_has_super(sb, i) +
ext2_bg_num_gdb(sb, i);
/*
* Every block group has an inode bitmap, a block
* bitmap, and an inode table.
*/
overhead += (sbi->s_groups_count *
(2 + sbi->s_itb_per_group));
sbi->s_overhead_last = overhead;
smp_wmb();
sbi->s_blocks_last = le32_to_cpu(es->s_blocks_count);
}
buf->f_type = EXT2_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = le32_to_cpu(es->s_blocks_count) - sbi->s_overhead_last;
buf->f_bfree = ext2_count_free_blocks(sb);
es->s_free_blocks_count = cpu_to_le32(buf->f_bfree);
buf->f_bavail = buf->f_bfree - le32_to_cpu(es->s_r_blocks_count);
if (buf->f_bfree < le32_to_cpu(es->s_r_blocks_count))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = ext2_count_free_inodes(sb);
es->s_free_inodes_count = cpu_to_le32(buf->f_ffree);
buf->f_namelen = EXT2_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
return 0;
}
static int ext2_get_sb(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data, struct vfsmount *mnt)
{
return get_sb_bdev(fs_type, flags, dev_name, data, ext2_fill_super, mnt);
}
#ifdef CONFIG_QUOTA
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and noone else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext2_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
sector_t blk = off >> EXT2_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head tmp_bh;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
tmp_bh.b_state = 0;
tmp_bh.b_size = sb->s_blocksize;
err = ext2_get_block(inode, blk, &tmp_bh, 0);
if (err < 0)
return err;
if (!buffer_mapped(&tmp_bh)) /* A hole? */
memset(data, 0, tocopy);
else {
bh = sb_bread(sb, tmp_bh.b_blocknr);
if (!bh)
return -EIO;
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
}
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile */
static ssize_t ext2_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
sector_t blk = off >> EXT2_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t towrite = len;
struct buffer_head tmp_bh;
struct buffer_head *bh;
mutex_lock_nested(&inode->i_mutex, I_MUTEX_QUOTA);
while (towrite > 0) {
tocopy = sb->s_blocksize - offset < towrite ?
sb->s_blocksize - offset : towrite;
tmp_bh.b_state = 0;
err = ext2_get_block(inode, blk, &tmp_bh, 1);
if (err < 0)
goto out;
if (offset || tocopy != EXT2_BLOCK_SIZE(sb))
bh = sb_bread(sb, tmp_bh.b_blocknr);
else
bh = sb_getblk(sb, tmp_bh.b_blocknr);
if (!bh) {
err = -EIO;
goto out;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, tocopy);
flush_dcache_page(bh->b_page);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
brelse(bh);
offset = 0;
towrite -= tocopy;
data += tocopy;
blk++;
}
out:
if (len == towrite) {
mutex_unlock(&inode->i_mutex);
return err;
}
if (inode->i_size < off+len-towrite)
i_size_write(inode, off+len-towrite);
inode->i_version++;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
mutex_unlock(&inode->i_mutex);
return len - towrite;
}
#endif
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.get_sb = ext2_get_sb,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
static int __init init_ext2_fs(void)
{
int err = init_ext2_xattr();
if (err)
return err;
err = init_inodecache();
if (err)
goto out1;
err = register_filesystem(&ext2_fs_type);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
out1:
exit_ext2_xattr();
return err;
}
static void __exit exit_ext2_fs(void)
{
unregister_filesystem(&ext2_fs_type);
destroy_inodecache();
exit_ext2_xattr();
}
module_init(init_ext2_fs)
module_exit(exit_ext2_fs)
| gpl-2.0 |
webos-internals/webos-linux-kernel | drivers/serial/serial_ks8695.c | 1250 | 16093 | /*
* drivers/serial/serial_ks8695.c
*
* Driver for KS8695 serial ports
*
* Based on drivers/serial/serial_amba.c, by Kam Lee.
*
* Copyright 2002-2005 Micrel Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <linux/module.h>
#include <linux/tty.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/device.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <mach/regs-uart.h>
#include <mach/regs-irq.h>
#if defined(CONFIG_SERIAL_KS8695_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/serial_core.h>
#define SERIAL_KS8695_MAJOR 204
#define SERIAL_KS8695_MINOR 16
#define SERIAL_KS8695_DEVNAME "ttyAM"
#define SERIAL_KS8695_NR 1
/*
* Access macros for the KS8695 UART
*/
#define UART_GET_CHAR(p) (__raw_readl((p)->membase + KS8695_URRB) & 0xFF)
#define UART_PUT_CHAR(p, c) __raw_writel((c), (p)->membase + KS8695_URTH)
#define UART_GET_FCR(p) __raw_readl((p)->membase + KS8695_URFC)
#define UART_PUT_FCR(p, c) __raw_writel((c), (p)->membase + KS8695_URFC)
#define UART_GET_MSR(p) __raw_readl((p)->membase + KS8695_URMS)
#define UART_GET_LSR(p) __raw_readl((p)->membase + KS8695_URLS)
#define UART_GET_LCR(p) __raw_readl((p)->membase + KS8695_URLC)
#define UART_PUT_LCR(p, c) __raw_writel((c), (p)->membase + KS8695_URLC)
#define UART_GET_MCR(p) __raw_readl((p)->membase + KS8695_URMC)
#define UART_PUT_MCR(p, c) __raw_writel((c), (p)->membase + KS8695_URMC)
#define UART_GET_BRDR(p) __raw_readl((p)->membase + KS8695_URBD)
#define UART_PUT_BRDR(p, c) __raw_writel((c), (p)->membase + KS8695_URBD)
#define KS8695_CLR_TX_INT() __raw_writel(1 << KS8695_IRQ_UART_TX, KS8695_IRQ_VA + KS8695_INTST)
#define UART_DUMMY_LSR_RX 0x100
#define UART_PORT_SIZE (KS8695_USR - KS8695_URRB + 4)
static inline int tx_enabled(struct uart_port *port)
{
return port->unused[0] & 1;
}
static inline int rx_enabled(struct uart_port *port)
{
return port->unused[0] & 2;
}
static inline int ms_enabled(struct uart_port *port)
{
return port->unused[0] & 4;
}
static inline void ms_enable(struct uart_port *port, int enabled)
{
if(enabled)
port->unused[0] |= 4;
else
port->unused[0] &= ~4;
}
static inline void rx_enable(struct uart_port *port, int enabled)
{
if(enabled)
port->unused[0] |= 2;
else
port->unused[0] &= ~2;
}
static inline void tx_enable(struct uart_port *port, int enabled)
{
if(enabled)
port->unused[0] |= 1;
else
port->unused[0] &= ~1;
}
#ifdef SUPPORT_SYSRQ
static struct console ks8695_console;
#endif
static void ks8695uart_stop_tx(struct uart_port *port)
{
if (tx_enabled(port)) {
/* use disable_irq_nosync() and not disable_irq() to avoid self
* imposed deadlock by not waiting for irq handler to end,
* since this ks8695uart_stop_tx() is called from interrupt context.
*/
disable_irq_nosync(KS8695_IRQ_UART_TX);
tx_enable(port, 0);
}
}
static void ks8695uart_start_tx(struct uart_port *port)
{
if (!tx_enabled(port)) {
enable_irq(KS8695_IRQ_UART_TX);
tx_enable(port, 1);
}
}
static void ks8695uart_stop_rx(struct uart_port *port)
{
if (rx_enabled(port)) {
disable_irq(KS8695_IRQ_UART_RX);
rx_enable(port, 0);
}
}
static void ks8695uart_enable_ms(struct uart_port *port)
{
if (!ms_enabled(port)) {
enable_irq(KS8695_IRQ_UART_MODEM_STATUS);
ms_enable(port,1);
}
}
static void ks8695uart_disable_ms(struct uart_port *port)
{
if (ms_enabled(port)) {
disable_irq(KS8695_IRQ_UART_MODEM_STATUS);
ms_enable(port,0);
}
}
static irqreturn_t ks8695uart_rx_chars(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
struct tty_struct *tty = port->state->port.tty;
unsigned int status, ch, lsr, flg, max_count = 256;
status = UART_GET_LSR(port); /* clears pending LSR interrupts */
while ((status & URLS_URDR) && max_count--) {
ch = UART_GET_CHAR(port);
flg = TTY_NORMAL;
port->icount.rx++;
/*
* Note that the error handling code is
* out of the main execution path
*/
lsr = UART_GET_LSR(port) | UART_DUMMY_LSR_RX;
if (unlikely(lsr & (URLS_URBI | URLS_URPE | URLS_URFE | URLS_URROE))) {
if (lsr & URLS_URBI) {
lsr &= ~(URLS_URFE | URLS_URPE);
port->icount.brk++;
if (uart_handle_break(port))
goto ignore_char;
}
if (lsr & URLS_URPE)
port->icount.parity++;
if (lsr & URLS_URFE)
port->icount.frame++;
if (lsr & URLS_URROE)
port->icount.overrun++;
lsr &= port->read_status_mask;
if (lsr & URLS_URBI)
flg = TTY_BREAK;
else if (lsr & URLS_URPE)
flg = TTY_PARITY;
else if (lsr & URLS_URFE)
flg = TTY_FRAME;
}
if (uart_handle_sysrq_char(port, ch))
goto ignore_char;
uart_insert_char(port, lsr, URLS_URROE, ch, flg);
ignore_char:
status = UART_GET_LSR(port);
}
tty_flip_buffer_push(tty);
return IRQ_HANDLED;
}
static irqreturn_t ks8695uart_tx_chars(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
struct circ_buf *xmit = &port->state->xmit;
unsigned int count;
if (port->x_char) {
KS8695_CLR_TX_INT();
UART_PUT_CHAR(port, port->x_char);
port->icount.tx++;
port->x_char = 0;
return IRQ_HANDLED;
}
if (uart_tx_stopped(port) || uart_circ_empty(xmit)) {
ks8695uart_stop_tx(port);
return IRQ_HANDLED;
}
count = 16; /* fifo size */
while (!uart_circ_empty(xmit) && (count-- > 0)) {
KS8695_CLR_TX_INT();
UART_PUT_CHAR(port, xmit->buf[xmit->tail]);
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
port->icount.tx++;
}
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(port);
if (uart_circ_empty(xmit))
ks8695uart_stop_tx(port);
return IRQ_HANDLED;
}
static irqreturn_t ks8695uart_modem_status(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
unsigned int status;
/*
* clear modem interrupt by reading MSR
*/
status = UART_GET_MSR(port);
if (status & URMS_URDDCD)
uart_handle_dcd_change(port, status & URMS_URDDCD);
if (status & URMS_URDDST)
port->icount.dsr++;
if (status & URMS_URDCTS)
uart_handle_cts_change(port, status & URMS_URDCTS);
if (status & URMS_URTERI)
port->icount.rng++;
wake_up_interruptible(&port->state->port.delta_msr_wait);
return IRQ_HANDLED;
}
static unsigned int ks8695uart_tx_empty(struct uart_port *port)
{
return (UART_GET_LSR(port) & URLS_URTE) ? TIOCSER_TEMT : 0;
}
static unsigned int ks8695uart_get_mctrl(struct uart_port *port)
{
unsigned int result = 0;
unsigned int status;
status = UART_GET_MSR(port);
if (status & URMS_URDCD)
result |= TIOCM_CAR;
if (status & URMS_URDSR)
result |= TIOCM_DSR;
if (status & URMS_URCTS)
result |= TIOCM_CTS;
if (status & URMS_URRI)
result |= TIOCM_RI;
return result;
}
static void ks8695uart_set_mctrl(struct uart_port *port, u_int mctrl)
{
unsigned int mcr;
mcr = UART_GET_MCR(port);
if (mctrl & TIOCM_RTS)
mcr |= URMC_URRTS;
else
mcr &= ~URMC_URRTS;
if (mctrl & TIOCM_DTR)
mcr |= URMC_URDTR;
else
mcr &= ~URMC_URDTR;
UART_PUT_MCR(port, mcr);
}
static void ks8695uart_break_ctl(struct uart_port *port, int break_state)
{
unsigned int lcr;
lcr = UART_GET_LCR(port);
if (break_state == -1)
lcr |= URLC_URSBC;
else
lcr &= ~URLC_URSBC;
UART_PUT_LCR(port, lcr);
}
static int ks8695uart_startup(struct uart_port *port)
{
int retval;
set_irq_flags(KS8695_IRQ_UART_TX, IRQF_VALID | IRQF_NOAUTOEN);
tx_enable(port, 0);
rx_enable(port, 1);
ms_enable(port, 1);
/*
* Allocate the IRQ
*/
retval = request_irq(KS8695_IRQ_UART_TX, ks8695uart_tx_chars, IRQF_DISABLED, "UART TX", port);
if (retval)
goto err_tx;
retval = request_irq(KS8695_IRQ_UART_RX, ks8695uart_rx_chars, IRQF_DISABLED, "UART RX", port);
if (retval)
goto err_rx;
retval = request_irq(KS8695_IRQ_UART_LINE_STATUS, ks8695uart_rx_chars, IRQF_DISABLED, "UART LineStatus", port);
if (retval)
goto err_ls;
retval = request_irq(KS8695_IRQ_UART_MODEM_STATUS, ks8695uart_modem_status, IRQF_DISABLED, "UART ModemStatus", port);
if (retval)
goto err_ms;
return 0;
err_ms:
free_irq(KS8695_IRQ_UART_LINE_STATUS, port);
err_ls:
free_irq(KS8695_IRQ_UART_RX, port);
err_rx:
free_irq(KS8695_IRQ_UART_TX, port);
err_tx:
return retval;
}
static void ks8695uart_shutdown(struct uart_port *port)
{
/*
* Free the interrupt
*/
free_irq(KS8695_IRQ_UART_RX, port);
free_irq(KS8695_IRQ_UART_TX, port);
free_irq(KS8695_IRQ_UART_MODEM_STATUS, port);
free_irq(KS8695_IRQ_UART_LINE_STATUS, port);
/* disable break condition and fifos */
UART_PUT_LCR(port, UART_GET_LCR(port) & ~URLC_URSBC);
UART_PUT_FCR(port, UART_GET_FCR(port) & ~URFC_URFE);
}
static void ks8695uart_set_termios(struct uart_port *port, struct ktermios *termios, struct ktermios *old)
{
unsigned int lcr, fcr = 0;
unsigned long flags;
unsigned int baud, quot;
/*
* Ask the core to calculate the divisor for us.
*/
baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);
quot = uart_get_divisor(port, baud);
switch (termios->c_cflag & CSIZE) {
case CS5:
lcr = URCL_5;
break;
case CS6:
lcr = URCL_6;
break;
case CS7:
lcr = URCL_7;
break;
default:
lcr = URCL_8;
break;
}
/* stop bits */
if (termios->c_cflag & CSTOPB)
lcr |= URLC_URSB;
/* parity */
if (termios->c_cflag & PARENB) {
if (termios->c_cflag & CMSPAR) { /* Mark or Space parity */
if (termios->c_cflag & PARODD)
lcr |= URPE_MARK;
else
lcr |= URPE_SPACE;
}
else if (termios->c_cflag & PARODD)
lcr |= URPE_ODD;
else
lcr |= URPE_EVEN;
}
if (port->fifosize > 1)
fcr = URFC_URFRT_8 | URFC_URTFR | URFC_URRFR | URFC_URFE;
spin_lock_irqsave(&port->lock, flags);
/*
* Update the per-port timeout.
*/
uart_update_timeout(port, termios->c_cflag, baud);
port->read_status_mask = URLS_URROE;
if (termios->c_iflag & INPCK)
port->read_status_mask |= (URLS_URFE | URLS_URPE);
if (termios->c_iflag & (BRKINT | PARMRK))
port->read_status_mask |= URLS_URBI;
/*
* Characters to ignore
*/
port->ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= (URLS_URFE | URLS_URPE);
if (termios->c_iflag & IGNBRK) {
port->ignore_status_mask |= URLS_URBI;
/*
* If we're ignoring parity and break indicators,
* ignore overruns too (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= URLS_URROE;
}
/*
* Ignore all characters if CREAD is not set.
*/
if ((termios->c_cflag & CREAD) == 0)
port->ignore_status_mask |= UART_DUMMY_LSR_RX;
/* first, disable everything */
if (UART_ENABLE_MS(port, termios->c_cflag))
ks8695uart_enable_ms(port);
else
ks8695uart_disable_ms(port);
/* Set baud rate */
UART_PUT_BRDR(port, quot);
UART_PUT_LCR(port, lcr);
UART_PUT_FCR(port, fcr);
spin_unlock_irqrestore(&port->lock, flags);
}
static const char *ks8695uart_type(struct uart_port *port)
{
return port->type == PORT_KS8695 ? "KS8695" : NULL;
}
/*
* Release the memory region(s) being used by 'port'
*/
static void ks8695uart_release_port(struct uart_port *port)
{
release_mem_region(port->mapbase, UART_PORT_SIZE);
}
/*
* Request the memory region(s) being used by 'port'
*/
static int ks8695uart_request_port(struct uart_port *port)
{
return request_mem_region(port->mapbase, UART_PORT_SIZE,
"serial_ks8695") != NULL ? 0 : -EBUSY;
}
/*
* Configure/autoconfigure the port.
*/
static void ks8695uart_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE) {
port->type = PORT_KS8695;
ks8695uart_request_port(port);
}
}
/*
* verify the new serial_struct (for TIOCSSERIAL).
*/
static int ks8695uart_verify_port(struct uart_port *port, struct serial_struct *ser)
{
int ret = 0;
if (ser->type != PORT_UNKNOWN && ser->type != PORT_KS8695)
ret = -EINVAL;
if (ser->irq != port->irq)
ret = -EINVAL;
if (ser->baud_base < 9600)
ret = -EINVAL;
return ret;
}
static struct uart_ops ks8695uart_pops = {
.tx_empty = ks8695uart_tx_empty,
.set_mctrl = ks8695uart_set_mctrl,
.get_mctrl = ks8695uart_get_mctrl,
.stop_tx = ks8695uart_stop_tx,
.start_tx = ks8695uart_start_tx,
.stop_rx = ks8695uart_stop_rx,
.enable_ms = ks8695uart_enable_ms,
.break_ctl = ks8695uart_break_ctl,
.startup = ks8695uart_startup,
.shutdown = ks8695uart_shutdown,
.set_termios = ks8695uart_set_termios,
.type = ks8695uart_type,
.release_port = ks8695uart_release_port,
.request_port = ks8695uart_request_port,
.config_port = ks8695uart_config_port,
.verify_port = ks8695uart_verify_port,
};
static struct uart_port ks8695uart_ports[SERIAL_KS8695_NR] = {
{
.membase = (void *) KS8695_UART_VA,
.mapbase = KS8695_UART_VA,
.iotype = SERIAL_IO_MEM,
.irq = KS8695_IRQ_UART_TX,
.uartclk = KS8695_CLOCK_RATE * 16,
.fifosize = 16,
.ops = &ks8695uart_pops,
.flags = ASYNC_BOOT_AUTOCONF,
.line = 0,
}
};
#ifdef CONFIG_SERIAL_KS8695_CONSOLE
static void ks8695_console_putchar(struct uart_port *port, int ch)
{
while (!(UART_GET_LSR(port) & URLS_URTHRE))
barrier();
UART_PUT_CHAR(port, ch);
}
static void ks8695_console_write(struct console *co, const char *s, u_int count)
{
struct uart_port *port = ks8695uart_ports + co->index;
uart_console_write(port, s, count, ks8695_console_putchar);
}
static void __init ks8695_console_get_options(struct uart_port *port, int *baud, int *parity, int *bits)
{
unsigned int lcr;
lcr = UART_GET_LCR(port);
switch (lcr & URLC_PARITY) {
case URPE_ODD:
*parity = 'o';
break;
case URPE_EVEN:
*parity = 'e';
break;
default:
*parity = 'n';
}
switch (lcr & URLC_URCL) {
case URCL_5:
*bits = 5;
break;
case URCL_6:
*bits = 6;
break;
case URCL_7:
*bits = 7;
break;
default:
*bits = 8;
}
*baud = port->uartclk / (UART_GET_BRDR(port) & 0x0FFF);
*baud /= 16;
*baud &= 0xFFFFFFF0;
}
static int __init ks8695_console_setup(struct console *co, char *options)
{
struct uart_port *port;
int baud = 115200;
int bits = 8;
int parity = 'n';
int flow = 'n';
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
port = uart_get_console(ks8695uart_ports, SERIAL_KS8695_NR, co);
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
else
ks8695_console_get_options(port, &baud, &parity, &bits);
return uart_set_options(port, co, baud, parity, bits, flow);
}
static struct uart_driver ks8695_reg;
static struct console ks8695_console = {
.name = SERIAL_KS8695_DEVNAME,
.write = ks8695_console_write,
.device = uart_console_device,
.setup = ks8695_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &ks8695_reg,
};
static int __init ks8695_console_init(void)
{
add_preferred_console(SERIAL_KS8695_DEVNAME, 0, NULL);
register_console(&ks8695_console);
return 0;
}
console_initcall(ks8695_console_init);
#define KS8695_CONSOLE &ks8695_console
#else
#define KS8695_CONSOLE NULL
#endif
static struct uart_driver ks8695_reg = {
.owner = THIS_MODULE,
.driver_name = "serial_ks8695",
.dev_name = SERIAL_KS8695_DEVNAME,
.major = SERIAL_KS8695_MAJOR,
.minor = SERIAL_KS8695_MINOR,
.nr = SERIAL_KS8695_NR,
.cons = KS8695_CONSOLE,
};
static int __init ks8695uart_init(void)
{
int i, ret;
printk(KERN_INFO "Serial: Micrel KS8695 UART driver\n");
ret = uart_register_driver(&ks8695_reg);
if (ret)
return ret;
for (i = 0; i < SERIAL_KS8695_NR; i++)
uart_add_one_port(&ks8695_reg, &ks8695uart_ports[0]);
return 0;
}
static void __exit ks8695uart_exit(void)
{
int i;
for (i = 0; i < SERIAL_KS8695_NR; i++)
uart_remove_one_port(&ks8695_reg, &ks8695uart_ports[0]);
uart_unregister_driver(&ks8695_reg);
}
module_init(ks8695uart_init);
module_exit(ks8695uart_exit);
MODULE_DESCRIPTION("KS8695 serial port driver");
MODULE_AUTHOR("Micrel Inc.");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jeremytrimble/adi-linux | arch/x86/boot/edd.c | 2018 | 4223 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
* Copyright 2009 Intel Corporation; author H. Peter Anvin
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* Get EDD BIOS disk information
*/
#include "boot.h"
#include <linux/edd.h>
#include "string.h"
#if defined(CONFIG_EDD) || defined(CONFIG_EDD_MODULE)
/*
* Read the MBR (first sector) from a specific device.
*/
static int read_mbr(u8 devno, void *buf)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ax = 0x0201; /* Legacy Read, one sector */
ireg.cx = 0x0001; /* Sector 0-0-1 */
ireg.dl = devno;
ireg.bx = (size_t)buf;
intcall(0x13, &ireg, &oreg);
return -(oreg.eflags & X86_EFLAGS_CF); /* 0 or -1 */
}
static u32 read_mbr_sig(u8 devno, struct edd_info *ei, u32 *mbrsig)
{
int sector_size;
char *mbrbuf_ptr, *mbrbuf_end;
u32 buf_base, mbr_base;
extern char _end[];
u16 mbr_magic;
sector_size = ei->params.bytes_per_sector;
if (!sector_size)
sector_size = 512; /* Best available guess */
/* Produce a naturally aligned buffer on the heap */
buf_base = (ds() << 4) + (u32)&_end;
mbr_base = (buf_base+sector_size-1) & ~(sector_size-1);
mbrbuf_ptr = _end + (mbr_base-buf_base);
mbrbuf_end = mbrbuf_ptr + sector_size;
/* Make sure we actually have space on the heap... */
if (!(boot_params.hdr.loadflags & CAN_USE_HEAP))
return -1;
if (mbrbuf_end > (char *)(size_t)boot_params.hdr.heap_end_ptr)
return -1;
memset(mbrbuf_ptr, 0, sector_size);
if (read_mbr(devno, mbrbuf_ptr))
return -1;
*mbrsig = *(u32 *)&mbrbuf_ptr[EDD_MBR_SIG_OFFSET];
mbr_magic = *(u16 *)&mbrbuf_ptr[510];
/* check for valid MBR magic */
return mbr_magic == 0xAA55 ? 0 : -1;
}
static int get_edd_info(u8 devno, struct edd_info *ei)
{
struct biosregs ireg, oreg;
memset(ei, 0, sizeof *ei);
/* Check Extensions Present */
initregs(&ireg);
ireg.ah = 0x41;
ireg.bx = EDDMAGIC1;
ireg.dl = devno;
intcall(0x13, &ireg, &oreg);
if (oreg.eflags & X86_EFLAGS_CF)
return -1; /* No extended information */
if (oreg.bx != EDDMAGIC2)
return -1;
ei->device = devno;
ei->version = oreg.ah; /* EDD version number */
ei->interface_support = oreg.cx; /* EDD functionality subsets */
/* Extended Get Device Parameters */
ei->params.length = sizeof(ei->params);
ireg.ah = 0x48;
ireg.si = (size_t)&ei->params;
intcall(0x13, &ireg, &oreg);
/* Get legacy CHS parameters */
/* Ralf Brown recommends setting ES:DI to 0:0 */
ireg.ah = 0x08;
ireg.es = 0;
intcall(0x13, &ireg, &oreg);
if (!(oreg.eflags & X86_EFLAGS_CF)) {
ei->legacy_max_cylinder = oreg.ch + ((oreg.cl & 0xc0) << 2);
ei->legacy_max_head = oreg.dh;
ei->legacy_sectors_per_track = oreg.cl & 0x3f;
}
return 0;
}
void query_edd(void)
{
char eddarg[8];
int do_mbr = 1;
#ifdef CONFIG_EDD_OFF
int do_edd = 0;
#else
int do_edd = 1;
#endif
int be_quiet;
int devno;
struct edd_info ei, *edp;
u32 *mbrptr;
if (cmdline_find_option("edd", eddarg, sizeof eddarg) > 0) {
if (!strcmp(eddarg, "skipmbr") || !strcmp(eddarg, "skip")) {
do_edd = 1;
do_mbr = 0;
}
else if (!strcmp(eddarg, "off"))
do_edd = 0;
else if (!strcmp(eddarg, "on"))
do_edd = 1;
}
be_quiet = cmdline_find_option_bool("quiet");
edp = boot_params.eddbuf;
mbrptr = boot_params.edd_mbr_sig_buffer;
if (!do_edd)
return;
/* Bugs in OnBoard or AddOnCards Bios may hang the EDD probe,
* so give a hint if this happens.
*/
if (!be_quiet)
printf("Probing EDD (edd=off to disable)... ");
for (devno = 0x80; devno < 0x80+EDD_MBR_SIG_MAX; devno++) {
/*
* Scan the BIOS-supported hard disks and query EDD
* information...
*/
if (!get_edd_info(devno, &ei)
&& boot_params.eddbuf_entries < EDDMAXNR) {
memcpy(edp, &ei, sizeof ei);
edp++;
boot_params.eddbuf_entries++;
}
if (do_mbr && !read_mbr_sig(devno, &ei, mbrptr++))
boot_params.edd_mbr_sig_buf_entries = devno-0x80+1;
}
if (!be_quiet)
printf("ok\n");
}
#endif
| gpl-2.0 |
h8rift/android_kernel_htc_msm8960-evita | drivers/usb/musb/ux500_dma.c | 2274 | 12549 | /*
* drivers/usb/musb/ux500_dma.c
*
* U8500 and U5500 DMA support code
*
* Copyright (C) 2009 STMicroelectronics
* Copyright (C) 2011 ST-Ericsson SA
* Authors:
* Mian Yousaf Kaukab <mian.yousaf.kaukab@stericsson.com>
* Praveena Nadahally <praveen.nadahally@stericsson.com>
* Rajaram Regupathy <ragupathy.rajaram@stericsson.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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/pfn.h>
#include <mach/usb.h>
#include "musb_core.h"
struct ux500_dma_channel {
struct dma_channel channel;
struct ux500_dma_controller *controller;
struct musb_hw_ep *hw_ep;
struct work_struct channel_work;
struct dma_chan *dma_chan;
unsigned int cur_len;
dma_cookie_t cookie;
u8 ch_num;
u8 is_tx;
u8 is_allocated;
};
struct ux500_dma_controller {
struct dma_controller controller;
struct ux500_dma_channel rx_channel[UX500_MUSB_DMA_NUM_RX_CHANNELS];
struct ux500_dma_channel tx_channel[UX500_MUSB_DMA_NUM_TX_CHANNELS];
u32 num_rx_channels;
u32 num_tx_channels;
void *private_data;
dma_addr_t phy_base;
};
/* Work function invoked from DMA callback to handle tx transfers. */
static void ux500_tx_work(struct work_struct *data)
{
struct ux500_dma_channel *ux500_channel = container_of(data,
struct ux500_dma_channel, channel_work);
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct musb *musb = hw_ep->musb;
unsigned long flags;
DBG(4, "DMA tx transfer done on hw_ep=%d\n", hw_ep->epnum);
spin_lock_irqsave(&musb->lock, flags);
ux500_channel->channel.actual_len = ux500_channel->cur_len;
ux500_channel->channel.status = MUSB_DMA_STATUS_FREE;
musb_dma_completion(musb, hw_ep->epnum,
ux500_channel->is_tx);
spin_unlock_irqrestore(&musb->lock, flags);
}
/* Work function invoked from DMA callback to handle rx transfers. */
static void ux500_rx_work(struct work_struct *data)
{
struct ux500_dma_channel *ux500_channel = container_of(data,
struct ux500_dma_channel, channel_work);
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct musb *musb = hw_ep->musb;
unsigned long flags;
DBG(4, "DMA rx transfer done on hw_ep=%d\n", hw_ep->epnum);
spin_lock_irqsave(&musb->lock, flags);
ux500_channel->channel.actual_len = ux500_channel->cur_len;
ux500_channel->channel.status = MUSB_DMA_STATUS_FREE;
musb_dma_completion(musb, hw_ep->epnum,
ux500_channel->is_tx);
spin_unlock_irqrestore(&musb->lock, flags);
}
void ux500_dma_callback(void *private_data)
{
struct dma_channel *channel = (struct dma_channel *)private_data;
struct ux500_dma_channel *ux500_channel = channel->private_data;
schedule_work(&ux500_channel->channel_work);
}
static bool ux500_configure_channel(struct dma_channel *channel,
u16 packet_sz, u8 mode,
dma_addr_t dma_addr, u32 len)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct dma_chan *dma_chan = ux500_channel->dma_chan;
struct dma_async_tx_descriptor *dma_desc;
enum dma_data_direction direction;
struct scatterlist sg;
struct dma_slave_config slave_conf;
enum dma_slave_buswidth addr_width;
dma_addr_t usb_fifo_addr = (MUSB_FIFO_OFFSET(hw_ep->epnum) +
ux500_channel->controller->phy_base);
DBG(4, "packet_sz=%d, mode=%d, dma_addr=0x%x, len=%d is_tx=%d\n",
packet_sz, mode, dma_addr, len, ux500_channel->is_tx);
ux500_channel->cur_len = len;
sg_init_table(&sg, 1);
sg_set_page(&sg, pfn_to_page(PFN_DOWN(dma_addr)), len,
offset_in_page(dma_addr));
sg_dma_address(&sg) = dma_addr;
sg_dma_len(&sg) = len;
direction = ux500_channel->is_tx ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
addr_width = (len & 0x3) ? DMA_SLAVE_BUSWIDTH_1_BYTE :
DMA_SLAVE_BUSWIDTH_4_BYTES;
slave_conf.direction = direction;
if (direction == DMA_FROM_DEVICE) {
slave_conf.src_addr = usb_fifo_addr;
slave_conf.src_addr_width = addr_width;
slave_conf.src_maxburst = 16;
} else {
slave_conf.dst_addr = usb_fifo_addr;
slave_conf.dst_addr_width = addr_width;
slave_conf.dst_maxburst = 16;
}
dma_chan->device->device_control(dma_chan, DMA_SLAVE_CONFIG,
(unsigned long) &slave_conf);
dma_desc = dma_chan->device->
device_prep_slave_sg(dma_chan, &sg, 1, direction,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!dma_desc)
return false;
dma_desc->callback = ux500_dma_callback;
dma_desc->callback_param = channel;
ux500_channel->cookie = dma_desc->tx_submit(dma_desc);
dma_async_issue_pending(dma_chan);
return true;
}
static struct dma_channel *ux500_dma_channel_allocate(struct dma_controller *c,
struct musb_hw_ep *hw_ep, u8 is_tx)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel = NULL;
u8 ch_num = hw_ep->epnum - 1;
u32 max_ch;
/* Max 8 DMA channels (0 - 7). Each DMA channel can only be allocated
* to specified hw_ep. For example DMA channel 0 can only be allocated
* to hw_ep 1 and 9.
*/
if (ch_num > 7)
ch_num -= 8;
max_ch = is_tx ? controller->num_tx_channels :
controller->num_rx_channels;
if (ch_num >= max_ch)
return NULL;
ux500_channel = is_tx ? &(controller->tx_channel[ch_num]) :
&(controller->rx_channel[ch_num]) ;
/* Check if channel is already used. */
if (ux500_channel->is_allocated)
return NULL;
ux500_channel->hw_ep = hw_ep;
ux500_channel->is_allocated = 1;
DBG(7, "hw_ep=%d, is_tx=0x%x, channel=%d\n",
hw_ep->epnum, is_tx, ch_num);
return &(ux500_channel->channel);
}
static void ux500_dma_channel_release(struct dma_channel *channel)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
DBG(7, "channel=%d\n", ux500_channel->ch_num);
if (ux500_channel->is_allocated) {
ux500_channel->is_allocated = 0;
channel->status = MUSB_DMA_STATUS_FREE;
channel->actual_len = 0;
}
}
static int ux500_dma_is_compatible(struct dma_channel *channel,
u16 maxpacket, void *buf, u32 length)
{
if ((maxpacket & 0x3) ||
((int)buf & 0x3) ||
(length < 512) ||
(length & 0x3))
return false;
else
return true;
}
static int ux500_dma_channel_program(struct dma_channel *channel,
u16 packet_sz, u8 mode,
dma_addr_t dma_addr, u32 len)
{
int ret;
BUG_ON(channel->status == MUSB_DMA_STATUS_UNKNOWN ||
channel->status == MUSB_DMA_STATUS_BUSY);
if (!ux500_dma_is_compatible(channel, packet_sz, (void *)dma_addr, len))
return false;
channel->status = MUSB_DMA_STATUS_BUSY;
channel->actual_len = 0;
ret = ux500_configure_channel(channel, packet_sz, mode, dma_addr, len);
if (!ret)
channel->status = MUSB_DMA_STATUS_FREE;
return ret;
}
static int ux500_dma_channel_abort(struct dma_channel *channel)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
struct ux500_dma_controller *controller = ux500_channel->controller;
struct musb *musb = controller->private_data;
void __iomem *epio = musb->endpoints[ux500_channel->hw_ep->epnum].regs;
u16 csr;
DBG(4, "channel=%d, is_tx=%d\n", ux500_channel->ch_num,
ux500_channel->is_tx);
if (channel->status == MUSB_DMA_STATUS_BUSY) {
if (ux500_channel->is_tx) {
csr = musb_readw(epio, MUSB_TXCSR);
csr &= ~(MUSB_TXCSR_AUTOSET |
MUSB_TXCSR_DMAENAB |
MUSB_TXCSR_DMAMODE);
musb_writew(epio, MUSB_TXCSR, csr);
} else {
csr = musb_readw(epio, MUSB_RXCSR);
csr &= ~(MUSB_RXCSR_AUTOCLEAR |
MUSB_RXCSR_DMAENAB |
MUSB_RXCSR_DMAMODE);
musb_writew(epio, MUSB_RXCSR, csr);
}
ux500_channel->dma_chan->device->
device_control(ux500_channel->dma_chan,
DMA_TERMINATE_ALL, 0);
channel->status = MUSB_DMA_STATUS_FREE;
}
return 0;
}
static int ux500_dma_controller_stop(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel;
struct dma_channel *channel;
u8 ch_num;
for (ch_num = 0; ch_num < controller->num_rx_channels; ch_num++) {
channel = &controller->rx_channel[ch_num].channel;
ux500_channel = channel->private_data;
ux500_dma_channel_release(channel);
if (ux500_channel->dma_chan)
dma_release_channel(ux500_channel->dma_chan);
}
for (ch_num = 0; ch_num < controller->num_tx_channels; ch_num++) {
channel = &controller->tx_channel[ch_num].channel;
ux500_channel = channel->private_data;
ux500_dma_channel_release(channel);
if (ux500_channel->dma_chan)
dma_release_channel(ux500_channel->dma_chan);
}
return 0;
}
static int ux500_dma_controller_start(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel = NULL;
struct musb *musb = controller->private_data;
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct ux500_musb_board_data *data = plat->board_data;
struct dma_channel *dma_channel = NULL;
u32 ch_num;
u8 dir;
u8 is_tx = 0;
void **param_array;
struct ux500_dma_channel *channel_array;
u32 ch_count;
void (*musb_channel_work)(struct work_struct *);
dma_cap_mask_t mask;
if ((data->num_rx_channels > UX500_MUSB_DMA_NUM_RX_CHANNELS) ||
(data->num_tx_channels > UX500_MUSB_DMA_NUM_TX_CHANNELS))
return -EINVAL;
controller->num_rx_channels = data->num_rx_channels;
controller->num_tx_channels = data->num_tx_channels;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
/* Prepare the loop for RX channels */
channel_array = controller->rx_channel;
ch_count = data->num_rx_channels;
param_array = data->dma_rx_param_array;
musb_channel_work = ux500_rx_work;
for (dir = 0; dir < 2; dir++) {
for (ch_num = 0; ch_num < ch_count; ch_num++) {
ux500_channel = &channel_array[ch_num];
ux500_channel->controller = controller;
ux500_channel->ch_num = ch_num;
ux500_channel->is_tx = is_tx;
dma_channel = &(ux500_channel->channel);
dma_channel->private_data = ux500_channel;
dma_channel->status = MUSB_DMA_STATUS_FREE;
dma_channel->max_len = SZ_16M;
ux500_channel->dma_chan = dma_request_channel(mask,
data->dma_filter,
param_array[ch_num]);
if (!ux500_channel->dma_chan) {
ERR("Dma pipe allocation error dir=%d ch=%d\n",
dir, ch_num);
/* Release already allocated channels */
ux500_dma_controller_stop(c);
return -EBUSY;
}
INIT_WORK(&ux500_channel->channel_work,
musb_channel_work);
}
/* Prepare the loop for TX channels */
channel_array = controller->tx_channel;
ch_count = data->num_tx_channels;
param_array = data->dma_tx_param_array;
musb_channel_work = ux500_tx_work;
is_tx = 1;
}
return 0;
}
void dma_controller_destroy(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
kfree(controller);
}
struct dma_controller *__init
dma_controller_create(struct musb *musb, void __iomem *base)
{
struct ux500_dma_controller *controller;
struct platform_device *pdev = to_platform_device(musb->controller);
struct resource *iomem;
controller = kzalloc(sizeof(*controller), GFP_KERNEL);
if (!controller)
return NULL;
controller->private_data = musb;
/* Save physical address for DMA controller. */
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
controller->phy_base = (dma_addr_t) iomem->start;
controller->controller.start = ux500_dma_controller_start;
controller->controller.stop = ux500_dma_controller_stop;
controller->controller.channel_alloc = ux500_dma_channel_allocate;
controller->controller.channel_release = ux500_dma_channel_release;
controller->controller.channel_program = ux500_dma_channel_program;
controller->controller.channel_abort = ux500_dma_channel_abort;
controller->controller.is_compatible = ux500_dma_is_compatible;
return &controller->controller;
}
| gpl-2.0 |
djmax81/android_kernel_samsung_exynos5433_LL | fs/signalfd.c | 2530 | 9349 | /*
* fs/signalfd.c
*
* Copyright (C) 2003 Linus Torvalds
*
* Mon Mar 5, 2007: Davide Libenzi <davidel@xmailserver.org>
* Changed ->read() to return a siginfo strcture instead of signal number.
* Fixed locking in ->poll().
* Added sighand-detach notification.
* Added fd re-use in sys_signalfd() syscall.
* Now using anonymous inode source.
* Thanks to Oleg Nesterov for useful code review and suggestions.
* More comments and suggestions from Arnd Bergmann.
* Sat May 19, 2007: Davi E. M. Arnaut <davi@haxent.com.br>
* Retrieve multiple signals with one read() call
* Sun Jul 15, 2007: Davide Libenzi <davidel@xmailserver.org>
* Attach to the sighand only during read() and poll().
*/
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/list.h>
#include <linux/anon_inodes.h>
#include <linux/signalfd.h>
#include <linux/syscalls.h>
#include <linux/proc_fs.h>
#include <linux/compat.h>
void signalfd_cleanup(struct sighand_struct *sighand)
{
wait_queue_head_t *wqh = &sighand->signalfd_wqh;
/*
* The lockless check can race with remove_wait_queue() in progress,
* but in this case its caller should run under rcu_read_lock() and
* sighand_cachep is SLAB_DESTROY_BY_RCU, we can safely return.
*/
if (likely(!waitqueue_active(wqh)))
return;
/* wait_queue_t->func(POLLFREE) should do remove_wait_queue() */
wake_up_poll(wqh, POLLHUP | POLLFREE);
}
struct signalfd_ctx {
sigset_t sigmask;
};
static int signalfd_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static unsigned int signalfd_poll(struct file *file, poll_table *wait)
{
struct signalfd_ctx *ctx = file->private_data;
unsigned int events = 0;
poll_wait(file, ¤t->sighand->signalfd_wqh, wait);
spin_lock_irq(¤t->sighand->siglock);
if (next_signal(¤t->pending, &ctx->sigmask) ||
next_signal(¤t->signal->shared_pending,
&ctx->sigmask))
events |= POLLIN;
spin_unlock_irq(¤t->sighand->siglock);
return events;
}
/*
* Copied from copy_siginfo_to_user() in kernel/signal.c
*/
static int signalfd_copyinfo(struct signalfd_siginfo __user *uinfo,
siginfo_t const *kinfo)
{
long err;
BUILD_BUG_ON(sizeof(struct signalfd_siginfo) != 128);
/*
* Unused members should be zero ...
*/
err = __clear_user(uinfo, sizeof(*uinfo));
/*
* If you change siginfo_t structure, please be sure
* this code is fixed accordingly.
*/
err |= __put_user(kinfo->si_signo, &uinfo->ssi_signo);
err |= __put_user(kinfo->si_errno, &uinfo->ssi_errno);
err |= __put_user((short) kinfo->si_code, &uinfo->ssi_code);
switch (kinfo->si_code & __SI_MASK) {
case __SI_KILL:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
break;
case __SI_TIMER:
err |= __put_user(kinfo->si_tid, &uinfo->ssi_tid);
err |= __put_user(kinfo->si_overrun, &uinfo->ssi_overrun);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
case __SI_POLL:
err |= __put_user(kinfo->si_band, &uinfo->ssi_band);
err |= __put_user(kinfo->si_fd, &uinfo->ssi_fd);
break;
case __SI_FAULT:
err |= __put_user((long) kinfo->si_addr, &uinfo->ssi_addr);
#ifdef __ARCH_SI_TRAPNO
err |= __put_user(kinfo->si_trapno, &uinfo->ssi_trapno);
#endif
#ifdef BUS_MCEERR_AO
/*
* Other callers might not initialize the si_lsb field,
* so check explicitly for the right codes here.
*/
if (kinfo->si_code == BUS_MCEERR_AR ||
kinfo->si_code == BUS_MCEERR_AO)
err |= __put_user((short) kinfo->si_addr_lsb,
&uinfo->ssi_addr_lsb);
#endif
break;
case __SI_CHLD:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user(kinfo->si_status, &uinfo->ssi_status);
err |= __put_user(kinfo->si_utime, &uinfo->ssi_utime);
err |= __put_user(kinfo->si_stime, &uinfo->ssi_stime);
break;
case __SI_RT: /* This is not generated by the kernel as of now. */
case __SI_MESGQ: /* But this is */
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
default:
/*
* This case catches also the signals queued by sigqueue().
*/
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
}
return err ? -EFAULT: sizeof(*uinfo);
}
static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, siginfo_t *info,
int nonblock)
{
ssize_t ret;
DECLARE_WAITQUEUE(wait, current);
spin_lock_irq(¤t->sighand->siglock);
ret = dequeue_signal(current, &ctx->sigmask, info);
switch (ret) {
case 0:
if (!nonblock)
break;
ret = -EAGAIN;
default:
spin_unlock_irq(¤t->sighand->siglock);
return ret;
}
add_wait_queue(¤t->sighand->signalfd_wqh, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
ret = dequeue_signal(current, &ctx->sigmask, info);
if (ret != 0)
break;
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
spin_unlock_irq(¤t->sighand->siglock);
schedule();
spin_lock_irq(¤t->sighand->siglock);
}
spin_unlock_irq(¤t->sighand->siglock);
remove_wait_queue(¤t->sighand->signalfd_wqh, &wait);
__set_current_state(TASK_RUNNING);
return ret;
}
/*
* Returns a multiple of the size of a "struct signalfd_siginfo", or a negative
* error code. The "count" parameter must be at least the size of a
* "struct signalfd_siginfo".
*/
static ssize_t signalfd_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
struct signalfd_ctx *ctx = file->private_data;
struct signalfd_siginfo __user *siginfo;
int nonblock = file->f_flags & O_NONBLOCK;
ssize_t ret, total = 0;
siginfo_t info;
count /= sizeof(struct signalfd_siginfo);
if (!count)
return -EINVAL;
siginfo = (struct signalfd_siginfo __user *) buf;
do {
ret = signalfd_dequeue(ctx, &info, nonblock);
if (unlikely(ret <= 0))
break;
ret = signalfd_copyinfo(siginfo, &info);
if (ret < 0)
break;
siginfo++;
total += ret;
nonblock = 1;
} while (--count);
return total ? total: ret;
}
#ifdef CONFIG_PROC_FS
static int signalfd_show_fdinfo(struct seq_file *m, struct file *f)
{
struct signalfd_ctx *ctx = f->private_data;
sigset_t sigmask;
sigmask = ctx->sigmask;
signotset(&sigmask);
render_sigset_t(m, "sigmask:\t", &sigmask);
return 0;
}
#endif
static const struct file_operations signalfd_fops = {
#ifdef CONFIG_PROC_FS
.show_fdinfo = signalfd_show_fdinfo,
#endif
.release = signalfd_release,
.poll = signalfd_poll,
.read = signalfd_read,
.llseek = noop_llseek,
};
SYSCALL_DEFINE4(signalfd4, int, ufd, sigset_t __user *, user_mask,
size_t, sizemask, int, flags)
{
sigset_t sigmask;
struct signalfd_ctx *ctx;
/* Check the SFD_* constants for consistency. */
BUILD_BUG_ON(SFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(SFD_NONBLOCK != O_NONBLOCK);
if (flags & ~(SFD_CLOEXEC | SFD_NONBLOCK))
return -EINVAL;
if (sizemask != sizeof(sigset_t) ||
copy_from_user(&sigmask, user_mask, sizeof(sigmask)))
return -EINVAL;
sigdelsetmask(&sigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
signotset(&sigmask);
if (ufd == -1) {
ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->sigmask = sigmask;
/*
* When we call this, the initialization must be complete, since
* anon_inode_getfd() will install the fd.
*/
ufd = anon_inode_getfd("[signalfd]", &signalfd_fops, ctx,
O_RDWR | (flags & (O_CLOEXEC | O_NONBLOCK)));
if (ufd < 0)
kfree(ctx);
} else {
struct fd f = fdget(ufd);
if (!f.file)
return -EBADF;
ctx = f.file->private_data;
if (f.file->f_op != &signalfd_fops) {
fdput(f);
return -EINVAL;
}
spin_lock_irq(¤t->sighand->siglock);
ctx->sigmask = sigmask;
spin_unlock_irq(¤t->sighand->siglock);
wake_up(¤t->sighand->signalfd_wqh);
fdput(f);
}
return ufd;
}
SYSCALL_DEFINE3(signalfd, int, ufd, sigset_t __user *, user_mask,
size_t, sizemask)
{
return sys_signalfd4(ufd, user_mask, sizemask, 0);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(signalfd4, int, ufd,
const compat_sigset_t __user *,sigmask,
compat_size_t, sigsetsize,
int, flags)
{
compat_sigset_t ss32;
sigset_t tmp;
sigset_t __user *ksigmask;
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (copy_from_user(&ss32, sigmask, sizeof(ss32)))
return -EFAULT;
sigset_from_compat(&tmp, &ss32);
ksigmask = compat_alloc_user_space(sizeof(sigset_t));
if (copy_to_user(ksigmask, &tmp, sizeof(sigset_t)))
return -EFAULT;
return sys_signalfd4(ufd, ksigmask, sizeof(sigset_t), flags);
}
COMPAT_SYSCALL_DEFINE3(signalfd, int, ufd,
const compat_sigset_t __user *,sigmask,
compat_size_t, sigsetsize)
{
return compat_sys_signalfd4(ufd, sigmask, sigsetsize, 0);
}
#endif
| gpl-2.0 |
SlimRoms/kernel_asus_grouper | drivers/media/common/saa7146_core.c | 2786 | 15358 | /*
saa7146.o - driver for generic saa7146-based hardware
Copyright (C) 1998-2003 Michael Hunold <michael@mihu.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 <media/saa7146.h>
LIST_HEAD(saa7146_devices);
DEFINE_MUTEX(saa7146_devices_lock);
static int saa7146_num;
unsigned int saa7146_debug;
module_param(saa7146_debug, uint, 0644);
MODULE_PARM_DESC(saa7146_debug, "debug level (default: 0)");
#if 0
static void dump_registers(struct saa7146_dev* dev)
{
int i = 0;
INFO((" @ %li jiffies:\n",jiffies));
for(i = 0; i <= 0x148; i+=4) {
printk("0x%03x: 0x%08x\n",i,saa7146_read(dev,i));
}
}
#endif
/****************************************************************************
* gpio and debi helper functions
****************************************************************************/
void saa7146_setgpio(struct saa7146_dev *dev, int port, u32 data)
{
u32 value = 0;
BUG_ON(port > 3);
value = saa7146_read(dev, GPIO_CTRL);
value &= ~(0xff << (8*port));
value |= (data << (8*port));
saa7146_write(dev, GPIO_CTRL, value);
}
/* This DEBI code is based on the saa7146 Stradis driver by Nathan Laredo */
static inline int saa7146_wait_for_debi_done_sleep(struct saa7146_dev *dev,
unsigned long us1, unsigned long us2)
{
unsigned long timeout;
int err;
/* wait for registers to be programmed */
timeout = jiffies + usecs_to_jiffies(us1);
while (1) {
err = time_after(jiffies, timeout);
if (saa7146_read(dev, MC2) & 2)
break;
if (err) {
printk(KERN_ERR "%s: %s timed out while waiting for "
"registers getting programmed\n",
dev->name, __func__);
return -ETIMEDOUT;
}
msleep(1);
}
/* wait for transfer to complete */
timeout = jiffies + usecs_to_jiffies(us2);
while (1) {
err = time_after(jiffies, timeout);
if (!(saa7146_read(dev, PSR) & SPCI_DEBI_S))
break;
saa7146_read(dev, MC2);
if (err) {
DEB_S(("%s: %s timed out while waiting for transfer "
"completion\n", dev->name, __func__));
return -ETIMEDOUT;
}
msleep(1);
}
return 0;
}
static inline int saa7146_wait_for_debi_done_busyloop(struct saa7146_dev *dev,
unsigned long us1, unsigned long us2)
{
unsigned long loops;
/* wait for registers to be programmed */
loops = us1;
while (1) {
if (saa7146_read(dev, MC2) & 2)
break;
if (!loops--) {
printk(KERN_ERR "%s: %s timed out while waiting for "
"registers getting programmed\n",
dev->name, __func__);
return -ETIMEDOUT;
}
udelay(1);
}
/* wait for transfer to complete */
loops = us2 / 5;
while (1) {
if (!(saa7146_read(dev, PSR) & SPCI_DEBI_S))
break;
saa7146_read(dev, MC2);
if (!loops--) {
DEB_S(("%s: %s timed out while waiting for transfer "
"completion\n", dev->name, __func__));
return -ETIMEDOUT;
}
udelay(5);
}
return 0;
}
int saa7146_wait_for_debi_done(struct saa7146_dev *dev, int nobusyloop)
{
if (nobusyloop)
return saa7146_wait_for_debi_done_sleep(dev, 50000, 250000);
else
return saa7146_wait_for_debi_done_busyloop(dev, 50000, 250000);
}
/****************************************************************************
* general helper functions
****************************************************************************/
/* this is videobuf_vmalloc_to_sg() from videobuf-dma-sg.c
make sure virt has been allocated with vmalloc_32(), otherwise the BUG()
may be triggered on highmem machines */
static struct scatterlist* vmalloc_to_sg(unsigned char *virt, int nr_pages)
{
struct scatterlist *sglist;
struct page *pg;
int i;
sglist = kcalloc(nr_pages, sizeof(struct scatterlist), GFP_KERNEL);
if (NULL == sglist)
return NULL;
sg_init_table(sglist, nr_pages);
for (i = 0; i < nr_pages; i++, virt += PAGE_SIZE) {
pg = vmalloc_to_page(virt);
if (NULL == pg)
goto err;
BUG_ON(PageHighMem(pg));
sg_set_page(&sglist[i], pg, PAGE_SIZE, 0);
}
return sglist;
err:
kfree(sglist);
return NULL;
}
/********************************************************************************/
/* common page table functions */
void *saa7146_vmalloc_build_pgtable(struct pci_dev *pci, long length, struct saa7146_pgtable *pt)
{
int pages = (length+PAGE_SIZE-1)/PAGE_SIZE;
void *mem = vmalloc_32(length);
int slen = 0;
if (NULL == mem)
goto err_null;
if (!(pt->slist = vmalloc_to_sg(mem, pages)))
goto err_free_mem;
if (saa7146_pgtable_alloc(pci, pt))
goto err_free_slist;
pt->nents = pages;
slen = pci_map_sg(pci,pt->slist,pt->nents,PCI_DMA_FROMDEVICE);
if (0 == slen)
goto err_free_pgtable;
if (0 != saa7146_pgtable_build_single(pci, pt, pt->slist, slen))
goto err_unmap_sg;
return mem;
err_unmap_sg:
pci_unmap_sg(pci, pt->slist, pt->nents, PCI_DMA_FROMDEVICE);
err_free_pgtable:
saa7146_pgtable_free(pci, pt);
err_free_slist:
kfree(pt->slist);
pt->slist = NULL;
err_free_mem:
vfree(mem);
err_null:
return NULL;
}
void saa7146_vfree_destroy_pgtable(struct pci_dev *pci, void *mem, struct saa7146_pgtable *pt)
{
pci_unmap_sg(pci, pt->slist, pt->nents, PCI_DMA_FROMDEVICE);
saa7146_pgtable_free(pci, pt);
kfree(pt->slist);
pt->slist = NULL;
vfree(mem);
}
void saa7146_pgtable_free(struct pci_dev *pci, struct saa7146_pgtable *pt)
{
if (NULL == pt->cpu)
return;
pci_free_consistent(pci, pt->size, pt->cpu, pt->dma);
pt->cpu = NULL;
}
int saa7146_pgtable_alloc(struct pci_dev *pci, struct saa7146_pgtable *pt)
{
__le32 *cpu;
dma_addr_t dma_addr = 0;
cpu = pci_alloc_consistent(pci, PAGE_SIZE, &dma_addr);
if (NULL == cpu) {
return -ENOMEM;
}
pt->size = PAGE_SIZE;
pt->cpu = cpu;
pt->dma = dma_addr;
return 0;
}
int saa7146_pgtable_build_single(struct pci_dev *pci, struct saa7146_pgtable *pt,
struct scatterlist *list, int sglen )
{
__le32 *ptr, fill;
int nr_pages = 0;
int i,p;
BUG_ON(0 == sglen);
BUG_ON(list->offset > PAGE_SIZE);
/* if we have a user buffer, the first page may not be
aligned to a page boundary. */
pt->offset = list->offset;
ptr = pt->cpu;
for (i = 0; i < sglen; i++, list++) {
/*
printk("i:%d, adr:0x%08x, len:%d, offset:%d\n", i,sg_dma_address(list), sg_dma_len(list), list->offset);
*/
for (p = 0; p * 4096 < list->length; p++, ptr++) {
*ptr = cpu_to_le32(sg_dma_address(list) + p * 4096);
nr_pages++;
}
}
/* safety; fill the page table up with the last valid page */
fill = *(ptr-1);
for(i=nr_pages;i<1024;i++) {
*ptr++ = fill;
}
/*
ptr = pt->cpu;
printk("offset: %d\n",pt->offset);
for(i=0;i<5;i++) {
printk("ptr1 %d: 0x%08x\n",i,ptr[i]);
}
*/
return 0;
}
/********************************************************************************/
/* interrupt handler */
static irqreturn_t interrupt_hw(int irq, void *dev_id)
{
struct saa7146_dev *dev = dev_id;
u32 isr;
u32 ack_isr;
/* read out the interrupt status register */
ack_isr = isr = saa7146_read(dev, ISR);
/* is this our interrupt? */
if ( 0 == isr ) {
/* nope, some other device */
return IRQ_NONE;
}
if (dev->ext) {
if (dev->ext->irq_mask & isr) {
if (dev->ext->irq_func)
dev->ext->irq_func(dev, &isr);
isr &= ~dev->ext->irq_mask;
}
}
if (0 != (isr & (MASK_27))) {
DEB_INT(("irq: RPS0 (0x%08x).\n",isr));
if (dev->vv_data && dev->vv_callback)
dev->vv_callback(dev,isr);
isr &= ~MASK_27;
}
if (0 != (isr & (MASK_28))) {
if (dev->vv_data && dev->vv_callback)
dev->vv_callback(dev,isr);
isr &= ~MASK_28;
}
if (0 != (isr & (MASK_16|MASK_17))) {
SAA7146_IER_DISABLE(dev, MASK_16|MASK_17);
/* only wake up if we expect something */
if (0 != dev->i2c_op) {
dev->i2c_op = 0;
wake_up(&dev->i2c_wq);
} else {
u32 psr = saa7146_read(dev, PSR);
u32 ssr = saa7146_read(dev, SSR);
printk(KERN_WARNING "%s: unexpected i2c irq: isr %08x psr %08x ssr %08x\n",
dev->name, isr, psr, ssr);
}
isr &= ~(MASK_16|MASK_17);
}
if( 0 != isr ) {
ERR(("warning: interrupt enabled, but not handled properly.(0x%08x)\n",isr));
ERR(("disabling interrupt source(s)!\n"));
SAA7146_IER_DISABLE(dev,isr);
}
saa7146_write(dev, ISR, ack_isr);
return IRQ_HANDLED;
}
/*********************************************************************************/
/* configuration-functions */
static int saa7146_init_one(struct pci_dev *pci, const struct pci_device_id *ent)
{
struct saa7146_pci_extension_data *pci_ext = (struct saa7146_pci_extension_data *)ent->driver_data;
struct saa7146_extension *ext = pci_ext->ext;
struct saa7146_dev *dev;
int err = -ENOMEM;
/* clear out mem for sure */
dev = kzalloc(sizeof(struct saa7146_dev), GFP_KERNEL);
if (!dev) {
ERR(("out of memory.\n"));
goto out;
}
DEB_EE(("pci:%p\n",pci));
err = pci_enable_device(pci);
if (err < 0) {
ERR(("pci_enable_device() failed.\n"));
goto err_free;
}
/* enable bus-mastering */
pci_set_master(pci);
dev->pci = pci;
/* get chip-revision; this is needed to enable bug-fixes */
dev->revision = pci->revision;
/* remap the memory from virtual to physical address */
err = pci_request_region(pci, 0, "saa7146");
if (err < 0)
goto err_disable;
dev->mem = ioremap(pci_resource_start(pci, 0),
pci_resource_len(pci, 0));
if (!dev->mem) {
ERR(("ioremap() failed.\n"));
err = -ENODEV;
goto err_release;
}
/* we don't do a master reset here anymore, it screws up
some boards that don't have an i2c-eeprom for configuration
values */
/*
saa7146_write(dev, MC1, MASK_31);
*/
/* disable all irqs */
saa7146_write(dev, IER, 0);
/* shut down all dma transfers and rps tasks */
saa7146_write(dev, MC1, 0x30ff0000);
/* clear out any rps-signals pending */
saa7146_write(dev, MC2, 0xf8000000);
/* request an interrupt for the saa7146 */
err = request_irq(pci->irq, interrupt_hw, IRQF_SHARED | IRQF_DISABLED,
dev->name, dev);
if (err < 0) {
ERR(("request_irq() failed.\n"));
goto err_unmap;
}
err = -ENOMEM;
/* get memory for various stuff */
dev->d_rps0.cpu_addr = pci_alloc_consistent(pci, SAA7146_RPS_MEM,
&dev->d_rps0.dma_handle);
if (!dev->d_rps0.cpu_addr)
goto err_free_irq;
memset(dev->d_rps0.cpu_addr, 0x0, SAA7146_RPS_MEM);
dev->d_rps1.cpu_addr = pci_alloc_consistent(pci, SAA7146_RPS_MEM,
&dev->d_rps1.dma_handle);
if (!dev->d_rps1.cpu_addr)
goto err_free_rps0;
memset(dev->d_rps1.cpu_addr, 0x0, SAA7146_RPS_MEM);
dev->d_i2c.cpu_addr = pci_alloc_consistent(pci, SAA7146_RPS_MEM,
&dev->d_i2c.dma_handle);
if (!dev->d_i2c.cpu_addr)
goto err_free_rps1;
memset(dev->d_i2c.cpu_addr, 0x0, SAA7146_RPS_MEM);
/* the rest + print status message */
/* create a nice device name */
sprintf(dev->name, "saa7146 (%d)", saa7146_num);
INFO(("found saa7146 @ mem %p (revision %d, irq %d) (0x%04x,0x%04x).\n", dev->mem, dev->revision, pci->irq, pci->subsystem_vendor, pci->subsystem_device));
dev->ext = ext;
mutex_init(&dev->v4l2_lock);
spin_lock_init(&dev->int_slock);
spin_lock_init(&dev->slock);
mutex_init(&dev->i2c_lock);
dev->module = THIS_MODULE;
init_waitqueue_head(&dev->i2c_wq);
/* set some sane pci arbitrition values */
saa7146_write(dev, PCI_BT_V1, 0x1c00101f);
/* TODO: use the status code of the callback */
err = -ENODEV;
if (ext->probe && ext->probe(dev)) {
DEB_D(("ext->probe() failed for %p. skipping device.\n",dev));
goto err_free_i2c;
}
if (ext->attach(dev, pci_ext)) {
DEB_D(("ext->attach() failed for %p. skipping device.\n",dev));
goto err_free_i2c;
}
/* V4L extensions will set the pci drvdata to the v4l2_device in the
attach() above. So for those cards that do not use V4L we have to
set it explicitly. */
pci_set_drvdata(pci, &dev->v4l2_dev);
INIT_LIST_HEAD(&dev->item);
list_add_tail(&dev->item,&saa7146_devices);
saa7146_num++;
err = 0;
out:
return err;
err_free_i2c:
pci_free_consistent(pci, SAA7146_RPS_MEM, dev->d_i2c.cpu_addr,
dev->d_i2c.dma_handle);
err_free_rps1:
pci_free_consistent(pci, SAA7146_RPS_MEM, dev->d_rps1.cpu_addr,
dev->d_rps1.dma_handle);
err_free_rps0:
pci_free_consistent(pci, SAA7146_RPS_MEM, dev->d_rps0.cpu_addr,
dev->d_rps0.dma_handle);
err_free_irq:
free_irq(pci->irq, (void *)dev);
err_unmap:
iounmap(dev->mem);
err_release:
pci_release_region(pci, 0);
err_disable:
pci_disable_device(pci);
err_free:
kfree(dev);
goto out;
}
static void saa7146_remove_one(struct pci_dev *pdev)
{
struct v4l2_device *v4l2_dev = pci_get_drvdata(pdev);
struct saa7146_dev *dev = to_saa7146_dev(v4l2_dev);
struct {
void *addr;
dma_addr_t dma;
} dev_map[] = {
{ dev->d_i2c.cpu_addr, dev->d_i2c.dma_handle },
{ dev->d_rps1.cpu_addr, dev->d_rps1.dma_handle },
{ dev->d_rps0.cpu_addr, dev->d_rps0.dma_handle },
{ NULL, 0 }
}, *p;
DEB_EE(("dev:%p\n",dev));
dev->ext->detach(dev);
/* Zero the PCI drvdata after use. */
pci_set_drvdata(pdev, NULL);
/* shut down all video dma transfers */
saa7146_write(dev, MC1, 0x00ff0000);
/* disable all irqs, release irq-routine */
saa7146_write(dev, IER, 0);
free_irq(pdev->irq, dev);
for (p = dev_map; p->addr; p++)
pci_free_consistent(pdev, SAA7146_RPS_MEM, p->addr, p->dma);
iounmap(dev->mem);
pci_release_region(pdev, 0);
list_del(&dev->item);
pci_disable_device(pdev);
kfree(dev);
saa7146_num--;
}
/*********************************************************************************/
/* extension handling functions */
int saa7146_register_extension(struct saa7146_extension* ext)
{
DEB_EE(("ext:%p\n",ext));
ext->driver.name = ext->name;
ext->driver.id_table = ext->pci_tbl;
ext->driver.probe = saa7146_init_one;
ext->driver.remove = saa7146_remove_one;
printk("saa7146: register extension '%s'.\n",ext->name);
return pci_register_driver(&ext->driver);
}
int saa7146_unregister_extension(struct saa7146_extension* ext)
{
DEB_EE(("ext:%p\n",ext));
printk("saa7146: unregister extension '%s'.\n",ext->name);
pci_unregister_driver(&ext->driver);
return 0;
}
EXPORT_SYMBOL_GPL(saa7146_register_extension);
EXPORT_SYMBOL_GPL(saa7146_unregister_extension);
/* misc functions used by extension modules */
EXPORT_SYMBOL_GPL(saa7146_pgtable_alloc);
EXPORT_SYMBOL_GPL(saa7146_pgtable_free);
EXPORT_SYMBOL_GPL(saa7146_pgtable_build_single);
EXPORT_SYMBOL_GPL(saa7146_vmalloc_build_pgtable);
EXPORT_SYMBOL_GPL(saa7146_vfree_destroy_pgtable);
EXPORT_SYMBOL_GPL(saa7146_wait_for_debi_done);
EXPORT_SYMBOL_GPL(saa7146_setgpio);
EXPORT_SYMBOL_GPL(saa7146_i2c_adapter_prepare);
EXPORT_SYMBOL_GPL(saa7146_debug);
EXPORT_SYMBOL_GPL(saa7146_devices);
EXPORT_SYMBOL_GPL(saa7146_devices_lock);
MODULE_AUTHOR("Michael Hunold <michael@mihu.de>");
MODULE_DESCRIPTION("driver for generic saa7146-based hardware");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Fagulhas/android_kernel_huawei_u8815 | drivers/target/target_core_hba.c | 5090 | 4538 | /*******************************************************************************
* Filename: target_core_hba.c
*
* This file contains the TCM HBA Transport related functions.
*
* Copyright (c) 2003, 2004, 2005 PyX Technologies, Inc.
* Copyright (c) 2005, 2006, 2007 SBE, Inc.
* Copyright (c) 2007-2010 Rising Tide Systems
* Copyright (c) 2008-2010 Linux-iSCSI.org
*
* Nicholas A. Bellinger <nab@kernel.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
******************************************************************************/
#include <linux/net.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/module.h>
#include <net/sock.h>
#include <net/tcp.h>
#include <target/target_core_base.h>
#include <target/target_core_backend.h>
#include <target/target_core_fabric.h>
#include "target_core_internal.h"
static LIST_HEAD(subsystem_list);
static DEFINE_MUTEX(subsystem_mutex);
static u32 hba_id_counter;
static DEFINE_SPINLOCK(hba_lock);
static LIST_HEAD(hba_list);
int transport_subsystem_register(struct se_subsystem_api *sub_api)
{
struct se_subsystem_api *s;
INIT_LIST_HEAD(&sub_api->sub_api_list);
mutex_lock(&subsystem_mutex);
list_for_each_entry(s, &subsystem_list, sub_api_list) {
if (!strcmp(s->name, sub_api->name)) {
pr_err("%p is already registered with"
" duplicate name %s, unable to process"
" request\n", s, s->name);
mutex_unlock(&subsystem_mutex);
return -EEXIST;
}
}
list_add_tail(&sub_api->sub_api_list, &subsystem_list);
mutex_unlock(&subsystem_mutex);
pr_debug("TCM: Registered subsystem plugin: %s struct module:"
" %p\n", sub_api->name, sub_api->owner);
return 0;
}
EXPORT_SYMBOL(transport_subsystem_register);
void transport_subsystem_release(struct se_subsystem_api *sub_api)
{
mutex_lock(&subsystem_mutex);
list_del(&sub_api->sub_api_list);
mutex_unlock(&subsystem_mutex);
}
EXPORT_SYMBOL(transport_subsystem_release);
static struct se_subsystem_api *core_get_backend(const char *sub_name)
{
struct se_subsystem_api *s;
mutex_lock(&subsystem_mutex);
list_for_each_entry(s, &subsystem_list, sub_api_list) {
if (!strcmp(s->name, sub_name))
goto found;
}
mutex_unlock(&subsystem_mutex);
return NULL;
found:
if (s->owner && !try_module_get(s->owner))
s = NULL;
mutex_unlock(&subsystem_mutex);
return s;
}
struct se_hba *
core_alloc_hba(const char *plugin_name, u32 plugin_dep_id, u32 hba_flags)
{
struct se_hba *hba;
int ret = 0;
hba = kzalloc(sizeof(*hba), GFP_KERNEL);
if (!hba) {
pr_err("Unable to allocate struct se_hba\n");
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&hba->hba_dev_list);
spin_lock_init(&hba->device_lock);
mutex_init(&hba->hba_access_mutex);
hba->hba_index = scsi_get_new_index(SCSI_INST_INDEX);
hba->hba_flags |= hba_flags;
hba->transport = core_get_backend(plugin_name);
if (!hba->transport) {
ret = -EINVAL;
goto out_free_hba;
}
ret = hba->transport->attach_hba(hba, plugin_dep_id);
if (ret < 0)
goto out_module_put;
spin_lock(&hba_lock);
hba->hba_id = hba_id_counter++;
list_add_tail(&hba->hba_node, &hba_list);
spin_unlock(&hba_lock);
pr_debug("CORE_HBA[%d] - Attached HBA to Generic Target"
" Core\n", hba->hba_id);
return hba;
out_module_put:
if (hba->transport->owner)
module_put(hba->transport->owner);
hba->transport = NULL;
out_free_hba:
kfree(hba);
return ERR_PTR(ret);
}
int
core_delete_hba(struct se_hba *hba)
{
if (!list_empty(&hba->hba_dev_list))
dump_stack();
hba->transport->detach_hba(hba);
spin_lock(&hba_lock);
list_del(&hba->hba_node);
spin_unlock(&hba_lock);
pr_debug("CORE_HBA[%d] - Detached HBA from Generic Target"
" Core\n", hba->hba_id);
if (hba->transport->owner)
module_put(hba->transport->owner);
hba->transport = NULL;
kfree(hba);
return 0;
}
| gpl-2.0 |
mrjaydee82/SinLessKernelNew1 | drivers/staging/tidspbridge/core/msg_sm.c | 5090 | 15328 | /*
* msg_sm.c
*
* DSP-BIOS Bridge driver support functions for TI OMAP processors.
*
* Implements upper edge functions for Bridge message module.
*
* Copyright (C) 2005-2006 Texas Instruments, Inc.
*
* This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <linux/types.h>
/* ----------------------------------- DSP/BIOS Bridge */
#include <dspbridge/dbdefs.h>
/* ----------------------------------- OS Adaptation Layer */
#include <dspbridge/sync.h>
/* ----------------------------------- Platform Manager */
#include <dspbridge/dev.h>
/* ----------------------------------- Others */
#include <dspbridge/io_sm.h>
/* ----------------------------------- This */
#include <_msg_sm.h>
#include <dspbridge/dspmsg.h>
/* ----------------------------------- Function Prototypes */
static int add_new_msg(struct list_head *msg_list);
static void delete_msg_mgr(struct msg_mgr *hmsg_mgr);
static void delete_msg_queue(struct msg_queue *msg_queue_obj, u32 num_to_dsp);
static void free_msg_list(struct list_head *msg_list);
/*
* ======== bridge_msg_create ========
* Create an object to manage message queues. Only one of these objects
* can exist per device object.
*/
int bridge_msg_create(struct msg_mgr **msg_man,
struct dev_object *hdev_obj,
msg_onexit msg_callback)
{
struct msg_mgr *msg_mgr_obj;
struct io_mgr *hio_mgr;
int status = 0;
if (!msg_man || !msg_callback || !hdev_obj)
return -EFAULT;
dev_get_io_mgr(hdev_obj, &hio_mgr);
if (!hio_mgr)
return -EFAULT;
*msg_man = NULL;
/* Allocate msg_ctrl manager object */
msg_mgr_obj = kzalloc(sizeof(struct msg_mgr), GFP_KERNEL);
if (!msg_mgr_obj)
return -ENOMEM;
msg_mgr_obj->on_exit = msg_callback;
msg_mgr_obj->iomgr = hio_mgr;
/* List of MSG_QUEUEs */
INIT_LIST_HEAD(&msg_mgr_obj->queue_list);
/*
* Queues of message frames for messages to the DSP. Message
* frames will only be added to the free queue when a
* msg_queue object is created.
*/
INIT_LIST_HEAD(&msg_mgr_obj->msg_free_list);
INIT_LIST_HEAD(&msg_mgr_obj->msg_used_list);
spin_lock_init(&msg_mgr_obj->msg_mgr_lock);
/*
* Create an event to be used by bridge_msg_put() in waiting
* for an available free frame from the message manager.
*/
msg_mgr_obj->sync_event =
kzalloc(sizeof(struct sync_object), GFP_KERNEL);
if (!msg_mgr_obj->sync_event) {
kfree(msg_mgr_obj);
return -ENOMEM;
}
sync_init_event(msg_mgr_obj->sync_event);
*msg_man = msg_mgr_obj;
return status;
}
/*
* ======== bridge_msg_create_queue ========
* Create a msg_queue for sending/receiving messages to/from a node
* on the DSP.
*/
int bridge_msg_create_queue(struct msg_mgr *hmsg_mgr, struct msg_queue **msgq,
u32 msgq_id, u32 max_msgs, void *arg)
{
u32 i;
u32 num_allocated = 0;
struct msg_queue *msg_q;
int status = 0;
if (!hmsg_mgr || msgq == NULL)
return -EFAULT;
*msgq = NULL;
/* Allocate msg_queue object */
msg_q = kzalloc(sizeof(struct msg_queue), GFP_KERNEL);
if (!msg_q)
return -ENOMEM;
msg_q->max_msgs = max_msgs;
msg_q->msg_mgr = hmsg_mgr;
msg_q->arg = arg; /* Node handle */
msg_q->msgq_id = msgq_id; /* Node env (not valid yet) */
/* Queues of Message frames for messages from the DSP */
INIT_LIST_HEAD(&msg_q->msg_free_list);
INIT_LIST_HEAD(&msg_q->msg_used_list);
/* Create event that will be signalled when a message from
* the DSP is available. */
msg_q->sync_event = kzalloc(sizeof(struct sync_object), GFP_KERNEL);
if (!msg_q->sync_event) {
status = -ENOMEM;
goto out_err;
}
sync_init_event(msg_q->sync_event);
/* Create a notification list for message ready notification. */
msg_q->ntfy_obj = kmalloc(sizeof(struct ntfy_object), GFP_KERNEL);
if (!msg_q->ntfy_obj) {
status = -ENOMEM;
goto out_err;
}
ntfy_init(msg_q->ntfy_obj);
/* Create events that will be used to synchronize cleanup
* when the object is deleted. sync_done will be set to
* unblock threads in MSG_Put() or MSG_Get(). sync_done_ack
* will be set by the unblocked thread to signal that it
* is unblocked and will no longer reference the object. */
msg_q->sync_done = kzalloc(sizeof(struct sync_object), GFP_KERNEL);
if (!msg_q->sync_done) {
status = -ENOMEM;
goto out_err;
}
sync_init_event(msg_q->sync_done);
msg_q->sync_done_ack = kzalloc(sizeof(struct sync_object), GFP_KERNEL);
if (!msg_q->sync_done_ack) {
status = -ENOMEM;
goto out_err;
}
sync_init_event(msg_q->sync_done_ack);
/* Enter critical section */
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
/* Initialize message frames and put in appropriate queues */
for (i = 0; i < max_msgs && !status; i++) {
status = add_new_msg(&hmsg_mgr->msg_free_list);
if (!status) {
num_allocated++;
status = add_new_msg(&msg_q->msg_free_list);
}
}
if (status) {
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
goto out_err;
}
list_add_tail(&msg_q->list_elem, &hmsg_mgr->queue_list);
*msgq = msg_q;
/* Signal that free frames are now available */
if (!list_empty(&hmsg_mgr->msg_free_list))
sync_set_event(hmsg_mgr->sync_event);
/* Exit critical section */
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return 0;
out_err:
delete_msg_queue(msg_q, num_allocated);
return status;
}
/*
* ======== bridge_msg_delete ========
* Delete a msg_ctrl manager allocated in bridge_msg_create().
*/
void bridge_msg_delete(struct msg_mgr *hmsg_mgr)
{
if (hmsg_mgr)
delete_msg_mgr(hmsg_mgr);
}
/*
* ======== bridge_msg_delete_queue ========
* Delete a msg_ctrl queue allocated in bridge_msg_create_queue.
*/
void bridge_msg_delete_queue(struct msg_queue *msg_queue_obj)
{
struct msg_mgr *hmsg_mgr;
u32 io_msg_pend;
if (!msg_queue_obj || !msg_queue_obj->msg_mgr)
return;
hmsg_mgr = msg_queue_obj->msg_mgr;
msg_queue_obj->done = true;
/* Unblock all threads blocked in MSG_Get() or MSG_Put(). */
io_msg_pend = msg_queue_obj->io_msg_pend;
while (io_msg_pend) {
/* Unblock thread */
sync_set_event(msg_queue_obj->sync_done);
/* Wait for acknowledgement */
sync_wait_on_event(msg_queue_obj->sync_done_ack, SYNC_INFINITE);
io_msg_pend = msg_queue_obj->io_msg_pend;
}
/* Remove message queue from hmsg_mgr->queue_list */
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
list_del(&msg_queue_obj->list_elem);
/* Free the message queue object */
delete_msg_queue(msg_queue_obj, msg_queue_obj->max_msgs);
if (list_empty(&hmsg_mgr->msg_free_list))
sync_reset_event(hmsg_mgr->sync_event);
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
}
/*
* ======== bridge_msg_get ========
* Get a message from a msg_ctrl queue.
*/
int bridge_msg_get(struct msg_queue *msg_queue_obj,
struct dsp_msg *pmsg, u32 utimeout)
{
struct msg_frame *msg_frame_obj;
struct msg_mgr *hmsg_mgr;
struct sync_object *syncs[2];
u32 index;
int status = 0;
if (!msg_queue_obj || pmsg == NULL)
return -ENOMEM;
hmsg_mgr = msg_queue_obj->msg_mgr;
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
/* If a message is already there, get it */
if (!list_empty(&msg_queue_obj->msg_used_list)) {
msg_frame_obj = list_first_entry(&msg_queue_obj->msg_used_list,
struct msg_frame, list_elem);
list_del(&msg_frame_obj->list_elem);
*pmsg = msg_frame_obj->msg_data.msg;
list_add_tail(&msg_frame_obj->list_elem,
&msg_queue_obj->msg_free_list);
if (list_empty(&msg_queue_obj->msg_used_list))
sync_reset_event(msg_queue_obj->sync_event);
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return 0;
}
if (msg_queue_obj->done) {
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return -EPERM;
}
msg_queue_obj->io_msg_pend++;
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
/*
* Wait til message is available, timeout, or done. We don't
* have to schedule the DPC, since the DSP will send messages
* when they are available.
*/
syncs[0] = msg_queue_obj->sync_event;
syncs[1] = msg_queue_obj->sync_done;
status = sync_wait_on_multiple_events(syncs, 2, utimeout, &index);
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
if (msg_queue_obj->done) {
msg_queue_obj->io_msg_pend--;
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
/*
* Signal that we're not going to access msg_queue_obj
* anymore, so it can be deleted.
*/
sync_set_event(msg_queue_obj->sync_done_ack);
return -EPERM;
}
if (!status && !list_empty(&msg_queue_obj->msg_used_list)) {
/* Get msg from used list */
msg_frame_obj = list_first_entry(&msg_queue_obj->msg_used_list,
struct msg_frame, list_elem);
list_del(&msg_frame_obj->list_elem);
/* Copy message into pmsg and put frame on the free list */
*pmsg = msg_frame_obj->msg_data.msg;
list_add_tail(&msg_frame_obj->list_elem,
&msg_queue_obj->msg_free_list);
}
msg_queue_obj->io_msg_pend--;
/* Reset the event if there are still queued messages */
if (!list_empty(&msg_queue_obj->msg_used_list))
sync_set_event(msg_queue_obj->sync_event);
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return status;
}
/*
* ======== bridge_msg_put ========
* Put a message onto a msg_ctrl queue.
*/
int bridge_msg_put(struct msg_queue *msg_queue_obj,
const struct dsp_msg *pmsg, u32 utimeout)
{
struct msg_frame *msg_frame_obj;
struct msg_mgr *hmsg_mgr;
struct sync_object *syncs[2];
u32 index;
int status;
if (!msg_queue_obj || !pmsg || !msg_queue_obj->msg_mgr)
return -EFAULT;
hmsg_mgr = msg_queue_obj->msg_mgr;
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
/* If a message frame is available, use it */
if (!list_empty(&hmsg_mgr->msg_free_list)) {
msg_frame_obj = list_first_entry(&hmsg_mgr->msg_free_list,
struct msg_frame, list_elem);
list_del(&msg_frame_obj->list_elem);
msg_frame_obj->msg_data.msg = *pmsg;
msg_frame_obj->msg_data.msgq_id =
msg_queue_obj->msgq_id;
list_add_tail(&msg_frame_obj->list_elem,
&hmsg_mgr->msg_used_list);
hmsg_mgr->msgs_pending++;
if (list_empty(&hmsg_mgr->msg_free_list))
sync_reset_event(hmsg_mgr->sync_event);
/* Release critical section before scheduling DPC */
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
/* Schedule a DPC, to do the actual data transfer: */
iosm_schedule(hmsg_mgr->iomgr);
return 0;
}
if (msg_queue_obj->done) {
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return -EPERM;
}
msg_queue_obj->io_msg_pend++;
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
/* Wait til a free message frame is available, timeout, or done */
syncs[0] = hmsg_mgr->sync_event;
syncs[1] = msg_queue_obj->sync_done;
status = sync_wait_on_multiple_events(syncs, 2, utimeout, &index);
if (status)
return status;
/* Enter critical section */
spin_lock_bh(&hmsg_mgr->msg_mgr_lock);
if (msg_queue_obj->done) {
msg_queue_obj->io_msg_pend--;
/* Exit critical section */
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
/*
* Signal that we're not going to access msg_queue_obj
* anymore, so it can be deleted.
*/
sync_set_event(msg_queue_obj->sync_done_ack);
return -EPERM;
}
if (list_empty(&hmsg_mgr->msg_free_list)) {
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return -EFAULT;
}
/* Get msg from free list */
msg_frame_obj = list_first_entry(&hmsg_mgr->msg_free_list,
struct msg_frame, list_elem);
/*
* Copy message into pmsg and put frame on the
* used list.
*/
list_del(&msg_frame_obj->list_elem);
msg_frame_obj->msg_data.msg = *pmsg;
msg_frame_obj->msg_data.msgq_id = msg_queue_obj->msgq_id;
list_add_tail(&msg_frame_obj->list_elem, &hmsg_mgr->msg_used_list);
hmsg_mgr->msgs_pending++;
/*
* Schedule a DPC, to do the actual
* data transfer.
*/
iosm_schedule(hmsg_mgr->iomgr);
msg_queue_obj->io_msg_pend--;
/* Reset event if there are still frames available */
if (!list_empty(&hmsg_mgr->msg_free_list))
sync_set_event(hmsg_mgr->sync_event);
/* Exit critical section */
spin_unlock_bh(&hmsg_mgr->msg_mgr_lock);
return 0;
}
/*
* ======== bridge_msg_register_notify ========
*/
int bridge_msg_register_notify(struct msg_queue *msg_queue_obj,
u32 event_mask, u32 notify_type,
struct dsp_notification *hnotification)
{
int status = 0;
if (!msg_queue_obj || !hnotification) {
status = -ENOMEM;
goto func_end;
}
if (!(event_mask == DSP_NODEMESSAGEREADY || event_mask == 0)) {
status = -EPERM;
goto func_end;
}
if (notify_type != DSP_SIGNALEVENT) {
status = -EBADR;
goto func_end;
}
if (event_mask)
status = ntfy_register(msg_queue_obj->ntfy_obj, hnotification,
event_mask, notify_type);
else
status = ntfy_unregister(msg_queue_obj->ntfy_obj,
hnotification);
if (status == -EINVAL) {
/* Not registered. Ok, since we couldn't have known. Node
* notifications are split between node state change handled
* by NODE, and message ready handled by msg_ctrl. */
status = 0;
}
func_end:
return status;
}
/*
* ======== bridge_msg_set_queue_id ========
*/
void bridge_msg_set_queue_id(struct msg_queue *msg_queue_obj, u32 msgq_id)
{
/*
* A message queue must be created when a node is allocated,
* so that node_register_notify() can be called before the node
* is created. Since we don't know the node environment until the
* node is created, we need this function to set msg_queue_obj->msgq_id
* to the node environment, after the node is created.
*/
if (msg_queue_obj)
msg_queue_obj->msgq_id = msgq_id;
}
/*
* ======== add_new_msg ========
* Must be called in message manager critical section.
*/
static int add_new_msg(struct list_head *msg_list)
{
struct msg_frame *pmsg;
pmsg = kzalloc(sizeof(struct msg_frame), GFP_ATOMIC);
if (!pmsg)
return -ENOMEM;
list_add_tail(&pmsg->list_elem, msg_list);
return 0;
}
/*
* ======== delete_msg_mgr ========
*/
static void delete_msg_mgr(struct msg_mgr *hmsg_mgr)
{
if (!hmsg_mgr)
return;
/* FIXME: free elements from queue_list? */
free_msg_list(&hmsg_mgr->msg_free_list);
free_msg_list(&hmsg_mgr->msg_used_list);
kfree(hmsg_mgr->sync_event);
kfree(hmsg_mgr);
}
/*
* ======== delete_msg_queue ========
*/
static void delete_msg_queue(struct msg_queue *msg_queue_obj, u32 num_to_dsp)
{
struct msg_mgr *hmsg_mgr;
struct msg_frame *pmsg, *tmp;
u32 i;
if (!msg_queue_obj || !msg_queue_obj->msg_mgr)
return;
hmsg_mgr = msg_queue_obj->msg_mgr;
/* Pull off num_to_dsp message frames from Msg manager and free */
i = 0;
list_for_each_entry_safe(pmsg, tmp, &hmsg_mgr->msg_free_list,
list_elem) {
list_del(&pmsg->list_elem);
kfree(pmsg);
if (i++ >= num_to_dsp)
break;
}
free_msg_list(&msg_queue_obj->msg_free_list);
free_msg_list(&msg_queue_obj->msg_used_list);
if (msg_queue_obj->ntfy_obj) {
ntfy_delete(msg_queue_obj->ntfy_obj);
kfree(msg_queue_obj->ntfy_obj);
}
kfree(msg_queue_obj->sync_event);
kfree(msg_queue_obj->sync_done);
kfree(msg_queue_obj->sync_done_ack);
kfree(msg_queue_obj);
}
/*
* ======== free_msg_list ========
*/
static void free_msg_list(struct list_head *msg_list)
{
struct msg_frame *pmsg, *tmp;
if (!msg_list)
return;
list_for_each_entry_safe(pmsg, tmp, msg_list, list_elem) {
list_del(&pmsg->list_elem);
kfree(pmsg);
}
}
| gpl-2.0 |
evnit/android_kernel_samsung_msm8660-common | drivers/input/gameport/fm801-gp.c | 8162 | 4210 | /*
* FM801 gameport driver for Linux
*
* Copyright (c) by Takashi Iwai <tiwai@suse.de>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 <asm/io.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#define PCI_VENDOR_ID_FORTEMEDIA 0x1319
#define PCI_DEVICE_ID_FM801_GP 0x0802
#define HAVE_COOKED
struct fm801_gp {
struct gameport *gameport;
struct resource *res_port;
};
#ifdef HAVE_COOKED
static int fm801_gp_cooked_read(struct gameport *gameport, int *axes, int *buttons)
{
unsigned short w;
w = inw(gameport->io + 2);
*buttons = (~w >> 14) & 0x03;
axes[0] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 4);
axes[1] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 6);
*buttons |= ((~w >> 14) & 0x03) << 2;
axes[2] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 8);
axes[3] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
outw(0xff, gameport->io); /* reset */
return 0;
}
#endif
static int fm801_gp_open(struct gameport *gameport, int mode)
{
switch (mode) {
#ifdef HAVE_COOKED
case GAMEPORT_MODE_COOKED:
return 0;
#endif
case GAMEPORT_MODE_RAW:
return 0;
default:
return -1;
}
return 0;
}
static int __devinit fm801_gp_probe(struct pci_dev *pci, const struct pci_device_id *id)
{
struct fm801_gp *gp;
struct gameport *port;
int error;
gp = kzalloc(sizeof(struct fm801_gp), GFP_KERNEL);
port = gameport_allocate_port();
if (!gp || !port) {
printk(KERN_ERR "fm801-gp: Memory allocation failed\n");
error = -ENOMEM;
goto err_out_free;
}
error = pci_enable_device(pci);
if (error)
goto err_out_free;
port->open = fm801_gp_open;
#ifdef HAVE_COOKED
port->cooked_read = fm801_gp_cooked_read;
#endif
gameport_set_name(port, "FM801");
gameport_set_phys(port, "pci%s/gameport0", pci_name(pci));
port->dev.parent = &pci->dev;
port->io = pci_resource_start(pci, 0);
gp->gameport = port;
gp->res_port = request_region(port->io, 0x10, "FM801 GP");
if (!gp->res_port) {
printk(KERN_DEBUG "fm801-gp: unable to grab region 0x%x-0x%x\n",
port->io, port->io + 0x0f);
error = -EBUSY;
goto err_out_disable_dev;
}
pci_set_drvdata(pci, gp);
outb(0x60, port->io + 0x0d); /* enable joystick 1 and 2 */
gameport_register_port(port);
return 0;
err_out_disable_dev:
pci_disable_device(pci);
err_out_free:
gameport_free_port(port);
kfree(gp);
return error;
}
static void __devexit fm801_gp_remove(struct pci_dev *pci)
{
struct fm801_gp *gp = pci_get_drvdata(pci);
gameport_unregister_port(gp->gameport);
release_resource(gp->res_port);
kfree(gp);
pci_disable_device(pci);
}
static const struct pci_device_id fm801_gp_id_table[] = {
{ PCI_VENDOR_ID_FORTEMEDIA, PCI_DEVICE_ID_FM801_GP, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ 0 }
};
static struct pci_driver fm801_gp_driver = {
.name = "FM801_gameport",
.id_table = fm801_gp_id_table,
.probe = fm801_gp_probe,
.remove = __devexit_p(fm801_gp_remove),
};
static int __init fm801_gp_init(void)
{
return pci_register_driver(&fm801_gp_driver);
}
static void __exit fm801_gp_exit(void)
{
pci_unregister_driver(&fm801_gp_driver);
}
module_init(fm801_gp_init);
module_exit(fm801_gp_exit);
MODULE_DEVICE_TABLE(pci, fm801_gp_id_table);
MODULE_DESCRIPTION("FM801 gameport driver");
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
infraredbg/Lenovo_A820_kernel_kk | kernel/drivers/infiniband/hw/amso1100/c2_qp.c | 8162 | 25087 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2004 Voltaire, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/delay.h>
#include <linux/gfp.h>
#include "c2.h"
#include "c2_vq.h"
#include "c2_status.h"
#define C2_MAX_ORD_PER_QP 128
#define C2_MAX_IRD_PER_QP 128
#define C2_HINT_MAKE(q_index, hint_count) (((q_index) << 16) | hint_count)
#define C2_HINT_GET_INDEX(hint) (((hint) & 0x7FFF0000) >> 16)
#define C2_HINT_GET_COUNT(hint) ((hint) & 0x0000FFFF)
#define NO_SUPPORT -1
static const u8 c2_opcode[] = {
[IB_WR_SEND] = C2_WR_TYPE_SEND,
[IB_WR_SEND_WITH_IMM] = NO_SUPPORT,
[IB_WR_RDMA_WRITE] = C2_WR_TYPE_RDMA_WRITE,
[IB_WR_RDMA_WRITE_WITH_IMM] = NO_SUPPORT,
[IB_WR_RDMA_READ] = C2_WR_TYPE_RDMA_READ,
[IB_WR_ATOMIC_CMP_AND_SWP] = NO_SUPPORT,
[IB_WR_ATOMIC_FETCH_AND_ADD] = NO_SUPPORT,
};
static int to_c2_state(enum ib_qp_state ib_state)
{
switch (ib_state) {
case IB_QPS_RESET:
return C2_QP_STATE_IDLE;
case IB_QPS_RTS:
return C2_QP_STATE_RTS;
case IB_QPS_SQD:
return C2_QP_STATE_CLOSING;
case IB_QPS_SQE:
return C2_QP_STATE_CLOSING;
case IB_QPS_ERR:
return C2_QP_STATE_ERROR;
default:
return -1;
}
}
static int to_ib_state(enum c2_qp_state c2_state)
{
switch (c2_state) {
case C2_QP_STATE_IDLE:
return IB_QPS_RESET;
case C2_QP_STATE_CONNECTING:
return IB_QPS_RTR;
case C2_QP_STATE_RTS:
return IB_QPS_RTS;
case C2_QP_STATE_CLOSING:
return IB_QPS_SQD;
case C2_QP_STATE_ERROR:
return IB_QPS_ERR;
case C2_QP_STATE_TERMINATE:
return IB_QPS_SQE;
default:
return -1;
}
}
static const char *to_ib_state_str(int ib_state)
{
static const char *state_str[] = {
"IB_QPS_RESET",
"IB_QPS_INIT",
"IB_QPS_RTR",
"IB_QPS_RTS",
"IB_QPS_SQD",
"IB_QPS_SQE",
"IB_QPS_ERR"
};
if (ib_state < IB_QPS_RESET ||
ib_state > IB_QPS_ERR)
return "<invalid IB QP state>";
ib_state -= IB_QPS_RESET;
return state_str[ib_state];
}
void c2_set_qp_state(struct c2_qp *qp, int c2_state)
{
int new_state = to_ib_state(c2_state);
pr_debug("%s: qp[%p] state modify %s --> %s\n",
__func__,
qp,
to_ib_state_str(qp->state),
to_ib_state_str(new_state));
qp->state = new_state;
}
#define C2_QP_NO_ATTR_CHANGE 0xFFFFFFFF
int c2_qp_modify(struct c2_dev *c2dev, struct c2_qp *qp,
struct ib_qp_attr *attr, int attr_mask)
{
struct c2wr_qp_modify_req wr;
struct c2wr_qp_modify_rep *reply;
struct c2_vq_req *vq_req;
unsigned long flags;
u8 next_state;
int err;
pr_debug("%s:%d qp=%p, %s --> %s\n",
__func__, __LINE__,
qp,
to_ib_state_str(qp->state),
to_ib_state_str(attr->qp_state));
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
c2_wr_set_id(&wr, CCWR_QP_MODIFY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.qp_handle = qp->adapter_handle;
wr.ord = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
wr.ird = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
wr.sq_depth = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
wr.rq_depth = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
if (attr_mask & IB_QP_STATE) {
/* Ensure the state is valid */
if (attr->qp_state < 0 || attr->qp_state > IB_QPS_ERR) {
err = -EINVAL;
goto bail0;
}
wr.next_qp_state = cpu_to_be32(to_c2_state(attr->qp_state));
if (attr->qp_state == IB_QPS_ERR) {
spin_lock_irqsave(&qp->lock, flags);
if (qp->cm_id && qp->state == IB_QPS_RTS) {
pr_debug("Generating CLOSE event for QP-->ERR, "
"qp=%p, cm_id=%p\n",qp,qp->cm_id);
/* Generate an CLOSE event */
vq_req->cm_id = qp->cm_id;
vq_req->event = IW_CM_EVENT_CLOSE;
}
spin_unlock_irqrestore(&qp->lock, flags);
}
next_state = attr->qp_state;
} else if (attr_mask & IB_QP_CUR_STATE) {
if (attr->cur_qp_state != IB_QPS_RTR &&
attr->cur_qp_state != IB_QPS_RTS &&
attr->cur_qp_state != IB_QPS_SQD &&
attr->cur_qp_state != IB_QPS_SQE) {
err = -EINVAL;
goto bail0;
} else
wr.next_qp_state =
cpu_to_be32(to_c2_state(attr->cur_qp_state));
next_state = attr->cur_qp_state;
} else {
err = 0;
goto bail0;
}
/* reference the request struct */
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
reply = (struct c2wr_qp_modify_rep *) (unsigned long) vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
err = c2_errno(reply);
if (!err)
qp->state = next_state;
#ifdef DEBUG
else
pr_debug("%s: c2_errno=%d\n", __func__, err);
#endif
/*
* If we're going to error and generating the event here, then
* we need to remove the reference because there will be no
* close event generated by the adapter
*/
spin_lock_irqsave(&qp->lock, flags);
if (vq_req->event==IW_CM_EVENT_CLOSE && qp->cm_id) {
qp->cm_id->rem_ref(qp->cm_id);
qp->cm_id = NULL;
}
spin_unlock_irqrestore(&qp->lock, flags);
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
pr_debug("%s:%d qp=%p, cur_state=%s\n",
__func__, __LINE__,
qp,
to_ib_state_str(qp->state));
return err;
}
int c2_qp_set_read_limits(struct c2_dev *c2dev, struct c2_qp *qp,
int ord, int ird)
{
struct c2wr_qp_modify_req wr;
struct c2wr_qp_modify_rep *reply;
struct c2_vq_req *vq_req;
int err;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
c2_wr_set_id(&wr, CCWR_QP_MODIFY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.qp_handle = qp->adapter_handle;
wr.ord = cpu_to_be32(ord);
wr.ird = cpu_to_be32(ird);
wr.sq_depth = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
wr.rq_depth = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
wr.next_qp_state = cpu_to_be32(C2_QP_NO_ATTR_CHANGE);
/* reference the request struct */
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
reply = (struct c2wr_qp_modify_rep *) (unsigned long)
vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
static int destroy_qp(struct c2_dev *c2dev, struct c2_qp *qp)
{
struct c2_vq_req *vq_req;
struct c2wr_qp_destroy_req wr;
struct c2wr_qp_destroy_rep *reply;
unsigned long flags;
int err;
/*
* Allocate a verb request message
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req) {
return -ENOMEM;
}
/*
* Initialize the WR
*/
c2_wr_set_id(&wr, CCWR_QP_DESTROY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.qp_handle = qp->adapter_handle;
/*
* reference the request struct. dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
spin_lock_irqsave(&qp->lock, flags);
if (qp->cm_id && qp->state == IB_QPS_RTS) {
pr_debug("destroy_qp: generating CLOSE event for QP-->ERR, "
"qp=%p, cm_id=%p\n",qp,qp->cm_id);
/* Generate an CLOSE event */
vq_req->qp = qp;
vq_req->cm_id = qp->cm_id;
vq_req->event = IW_CM_EVENT_CLOSE;
}
spin_unlock_irqrestore(&qp->lock, flags);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail0;
}
/*
* Process reply
*/
reply = (struct c2wr_qp_destroy_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail0;
}
spin_lock_irqsave(&qp->lock, flags);
if (qp->cm_id) {
qp->cm_id->rem_ref(qp->cm_id);
qp->cm_id = NULL;
}
spin_unlock_irqrestore(&qp->lock, flags);
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
static int c2_alloc_qpn(struct c2_dev *c2dev, struct c2_qp *qp)
{
int ret;
do {
spin_lock_irq(&c2dev->qp_table.lock);
ret = idr_get_new_above(&c2dev->qp_table.idr, qp,
c2dev->qp_table.last++, &qp->qpn);
spin_unlock_irq(&c2dev->qp_table.lock);
} while ((ret == -EAGAIN) &&
idr_pre_get(&c2dev->qp_table.idr, GFP_KERNEL));
return ret;
}
static void c2_free_qpn(struct c2_dev *c2dev, int qpn)
{
spin_lock_irq(&c2dev->qp_table.lock);
idr_remove(&c2dev->qp_table.idr, qpn);
spin_unlock_irq(&c2dev->qp_table.lock);
}
struct c2_qp *c2_find_qpn(struct c2_dev *c2dev, int qpn)
{
unsigned long flags;
struct c2_qp *qp;
spin_lock_irqsave(&c2dev->qp_table.lock, flags);
qp = idr_find(&c2dev->qp_table.idr, qpn);
spin_unlock_irqrestore(&c2dev->qp_table.lock, flags);
return qp;
}
int c2_alloc_qp(struct c2_dev *c2dev,
struct c2_pd *pd,
struct ib_qp_init_attr *qp_attrs, struct c2_qp *qp)
{
struct c2wr_qp_create_req wr;
struct c2wr_qp_create_rep *reply;
struct c2_vq_req *vq_req;
struct c2_cq *send_cq = to_c2cq(qp_attrs->send_cq);
struct c2_cq *recv_cq = to_c2cq(qp_attrs->recv_cq);
unsigned long peer_pa;
u32 q_size, msg_size, mmap_size;
void __iomem *mmap;
int err;
err = c2_alloc_qpn(c2dev, qp);
if (err)
return err;
qp->ibqp.qp_num = qp->qpn;
qp->ibqp.qp_type = IB_QPT_RC;
/* Allocate the SQ and RQ shared pointers */
qp->sq_mq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&qp->sq_mq.shared_dma, GFP_KERNEL);
if (!qp->sq_mq.shared) {
err = -ENOMEM;
goto bail0;
}
qp->rq_mq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&qp->rq_mq.shared_dma, GFP_KERNEL);
if (!qp->rq_mq.shared) {
err = -ENOMEM;
goto bail1;
}
/* Allocate the verbs request */
vq_req = vq_req_alloc(c2dev);
if (vq_req == NULL) {
err = -ENOMEM;
goto bail2;
}
/* Initialize the work request */
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_QP_CREATE);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.sq_cq_handle = send_cq->adapter_handle;
wr.rq_cq_handle = recv_cq->adapter_handle;
wr.sq_depth = cpu_to_be32(qp_attrs->cap.max_send_wr + 1);
wr.rq_depth = cpu_to_be32(qp_attrs->cap.max_recv_wr + 1);
wr.srq_handle = 0;
wr.flags = cpu_to_be32(QP_RDMA_READ | QP_RDMA_WRITE | QP_MW_BIND |
QP_ZERO_STAG | QP_RDMA_READ_RESPONSE);
wr.send_sgl_depth = cpu_to_be32(qp_attrs->cap.max_send_sge);
wr.recv_sgl_depth = cpu_to_be32(qp_attrs->cap.max_recv_sge);
wr.rdma_write_sgl_depth = cpu_to_be32(qp_attrs->cap.max_send_sge);
wr.shared_sq_ht = cpu_to_be64(qp->sq_mq.shared_dma);
wr.shared_rq_ht = cpu_to_be64(qp->rq_mq.shared_dma);
wr.ord = cpu_to_be32(C2_MAX_ORD_PER_QP);
wr.ird = cpu_to_be32(C2_MAX_IRD_PER_QP);
wr.pd_id = pd->pd_id;
wr.user_context = (unsigned long) qp;
vq_req_get(c2dev, vq_req);
/* Send the WR to the adapter */
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail3;
}
/* Wait for the verb reply */
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail3;
}
/* Process the reply */
reply = (struct c2wr_qp_create_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail3;
}
if ((err = c2_wr_get_result(reply)) != 0) {
goto bail4;
}
/* Fill in the kernel QP struct */
atomic_set(&qp->refcount, 1);
qp->adapter_handle = reply->qp_handle;
qp->state = IB_QPS_RESET;
qp->send_sgl_depth = qp_attrs->cap.max_send_sge;
qp->rdma_write_sgl_depth = qp_attrs->cap.max_send_sge;
qp->recv_sgl_depth = qp_attrs->cap.max_recv_sge;
init_waitqueue_head(&qp->wait);
/* Initialize the SQ MQ */
q_size = be32_to_cpu(reply->sq_depth);
msg_size = be32_to_cpu(reply->sq_msg_size);
peer_pa = c2dev->pa + be32_to_cpu(reply->sq_mq_start);
mmap_size = PAGE_ALIGN(sizeof(struct c2_mq_shared) + msg_size * q_size);
mmap = ioremap_nocache(peer_pa, mmap_size);
if (!mmap) {
err = -ENOMEM;
goto bail5;
}
c2_mq_req_init(&qp->sq_mq,
be32_to_cpu(reply->sq_mq_index),
q_size,
msg_size,
mmap + sizeof(struct c2_mq_shared), /* pool start */
mmap, /* peer */
C2_MQ_ADAPTER_TARGET);
/* Initialize the RQ mq */
q_size = be32_to_cpu(reply->rq_depth);
msg_size = be32_to_cpu(reply->rq_msg_size);
peer_pa = c2dev->pa + be32_to_cpu(reply->rq_mq_start);
mmap_size = PAGE_ALIGN(sizeof(struct c2_mq_shared) + msg_size * q_size);
mmap = ioremap_nocache(peer_pa, mmap_size);
if (!mmap) {
err = -ENOMEM;
goto bail6;
}
c2_mq_req_init(&qp->rq_mq,
be32_to_cpu(reply->rq_mq_index),
q_size,
msg_size,
mmap + sizeof(struct c2_mq_shared), /* pool start */
mmap, /* peer */
C2_MQ_ADAPTER_TARGET);
vq_repbuf_free(c2dev, reply);
vq_req_free(c2dev, vq_req);
return 0;
bail6:
iounmap(qp->sq_mq.peer);
bail5:
destroy_qp(c2dev, qp);
bail4:
vq_repbuf_free(c2dev, reply);
bail3:
vq_req_free(c2dev, vq_req);
bail2:
c2_free_mqsp(qp->rq_mq.shared);
bail1:
c2_free_mqsp(qp->sq_mq.shared);
bail0:
c2_free_qpn(c2dev, qp->qpn);
return err;
}
static inline void c2_lock_cqs(struct c2_cq *send_cq, struct c2_cq *recv_cq)
{
if (send_cq == recv_cq)
spin_lock_irq(&send_cq->lock);
else if (send_cq > recv_cq) {
spin_lock_irq(&send_cq->lock);
spin_lock_nested(&recv_cq->lock, SINGLE_DEPTH_NESTING);
} else {
spin_lock_irq(&recv_cq->lock);
spin_lock_nested(&send_cq->lock, SINGLE_DEPTH_NESTING);
}
}
static inline void c2_unlock_cqs(struct c2_cq *send_cq, struct c2_cq *recv_cq)
{
if (send_cq == recv_cq)
spin_unlock_irq(&send_cq->lock);
else if (send_cq > recv_cq) {
spin_unlock(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
} else {
spin_unlock(&send_cq->lock);
spin_unlock_irq(&recv_cq->lock);
}
}
void c2_free_qp(struct c2_dev *c2dev, struct c2_qp *qp)
{
struct c2_cq *send_cq;
struct c2_cq *recv_cq;
send_cq = to_c2cq(qp->ibqp.send_cq);
recv_cq = to_c2cq(qp->ibqp.recv_cq);
/*
* Lock CQs here, so that CQ polling code can do QP lookup
* without taking a lock.
*/
c2_lock_cqs(send_cq, recv_cq);
c2_free_qpn(c2dev, qp->qpn);
c2_unlock_cqs(send_cq, recv_cq);
/*
* Destroy qp in the rnic...
*/
destroy_qp(c2dev, qp);
/*
* Mark any unreaped CQEs as null and void.
*/
c2_cq_clean(c2dev, qp, send_cq->cqn);
if (send_cq != recv_cq)
c2_cq_clean(c2dev, qp, recv_cq->cqn);
/*
* Unmap the MQs and return the shared pointers
* to the message pool.
*/
iounmap(qp->sq_mq.peer);
iounmap(qp->rq_mq.peer);
c2_free_mqsp(qp->sq_mq.shared);
c2_free_mqsp(qp->rq_mq.shared);
atomic_dec(&qp->refcount);
wait_event(qp->wait, !atomic_read(&qp->refcount));
}
/*
* Function: move_sgl
*
* Description:
* Move an SGL from the user's work request struct into a CCIL Work Request
* message, swapping to WR byte order and ensure the total length doesn't
* overflow.
*
* IN:
* dst - ptr to CCIL Work Request message SGL memory.
* src - ptr to the consumers SGL memory.
*
* OUT: none
*
* Return:
* CCIL status codes.
*/
static int
move_sgl(struct c2_data_addr * dst, struct ib_sge *src, int count, u32 * p_len,
u8 * actual_count)
{
u32 tot = 0; /* running total */
u8 acount = 0; /* running total non-0 len sge's */
while (count > 0) {
/*
* If the addition of this SGE causes the
* total SGL length to exceed 2^32-1, then
* fail-n-bail.
*
* If the current total plus the next element length
* wraps, then it will go negative and be less than the
* current total...
*/
if ((tot + src->length) < tot) {
return -EINVAL;
}
/*
* Bug: 1456 (as well as 1498 & 1643)
* Skip over any sge's supplied with len=0
*/
if (src->length) {
tot += src->length;
dst->stag = cpu_to_be32(src->lkey);
dst->to = cpu_to_be64(src->addr);
dst->length = cpu_to_be32(src->length);
dst++;
acount++;
}
src++;
count--;
}
if (acount == 0) {
/*
* Bug: 1476 (as well as 1498, 1456 and 1643)
* Setup the SGL in the WR to make it easier for the RNIC.
* This way, the FW doesn't have to deal with special cases.
* Setting length=0 should be sufficient.
*/
dst->stag = 0;
dst->to = 0;
dst->length = 0;
}
*p_len = tot;
*actual_count = acount;
return 0;
}
/*
* Function: c2_activity (private function)
*
* Description:
* Post an mq index to the host->adapter activity fifo.
*
* IN:
* c2dev - ptr to c2dev structure
* mq_index - mq index to post
* shared - value most recently written to shared
*
* OUT:
*
* Return:
* none
*/
static inline void c2_activity(struct c2_dev *c2dev, u32 mq_index, u16 shared)
{
/*
* First read the register to see if the FIFO is full, and if so,
* spin until it's not. This isn't perfect -- there is no
* synchronization among the clients of the register, but in
* practice it prevents multiple CPU from hammering the bus
* with PCI RETRY. Note that when this does happen, the card
* cannot get on the bus and the card and system hang in a
* deadlock -- thus the need for this code. [TOT]
*/
while (readl(c2dev->regs + PCI_BAR0_ADAPTER_HINT) & 0x80000000)
udelay(10);
__raw_writel(C2_HINT_MAKE(mq_index, shared),
c2dev->regs + PCI_BAR0_ADAPTER_HINT);
}
/*
* Function: qp_wr_post
*
* Description:
* This in-line function allocates a MQ msg, then moves the host-copy of
* the completed WR into msg. Then it posts the message.
*
* IN:
* q - ptr to user MQ.
* wr - ptr to host-copy of the WR.
* qp - ptr to user qp
* size - Number of bytes to post. Assumed to be divisible by 4.
*
* OUT: none
*
* Return:
* CCIL status codes.
*/
static int qp_wr_post(struct c2_mq *q, union c2wr * wr, struct c2_qp *qp, u32 size)
{
union c2wr *msg;
msg = c2_mq_alloc(q);
if (msg == NULL) {
return -EINVAL;
}
#ifdef CCMSGMAGIC
((c2wr_hdr_t *) wr)->magic = cpu_to_be32(CCWR_MAGIC);
#endif
/*
* Since all header fields in the WR are the same as the
* CQE, set the following so the adapter need not.
*/
c2_wr_set_result(wr, CCERR_PENDING);
/*
* Copy the wr down to the adapter
*/
memcpy((void *) msg, (void *) wr, size);
c2_mq_produce(q);
return 0;
}
int c2_post_send(struct ib_qp *ibqp, struct ib_send_wr *ib_wr,
struct ib_send_wr **bad_wr)
{
struct c2_dev *c2dev = to_c2dev(ibqp->device);
struct c2_qp *qp = to_c2qp(ibqp);
union c2wr wr;
unsigned long lock_flags;
int err = 0;
u32 flags;
u32 tot_len;
u8 actual_sge_count;
u32 msg_size;
if (qp->state > IB_QPS_RTS) {
err = -EINVAL;
goto out;
}
while (ib_wr) {
flags = 0;
wr.sqwr.sq_hdr.user_hdr.hdr.context = ib_wr->wr_id;
if (ib_wr->send_flags & IB_SEND_SIGNALED) {
flags |= SQ_SIGNALED;
}
switch (ib_wr->opcode) {
case IB_WR_SEND:
case IB_WR_SEND_WITH_INV:
if (ib_wr->opcode == IB_WR_SEND) {
if (ib_wr->send_flags & IB_SEND_SOLICITED)
c2_wr_set_id(&wr, C2_WR_TYPE_SEND_SE);
else
c2_wr_set_id(&wr, C2_WR_TYPE_SEND);
wr.sqwr.send.remote_stag = 0;
} else {
if (ib_wr->send_flags & IB_SEND_SOLICITED)
c2_wr_set_id(&wr, C2_WR_TYPE_SEND_SE_INV);
else
c2_wr_set_id(&wr, C2_WR_TYPE_SEND_INV);
wr.sqwr.send.remote_stag =
cpu_to_be32(ib_wr->ex.invalidate_rkey);
}
msg_size = sizeof(struct c2wr_send_req) +
sizeof(struct c2_data_addr) * ib_wr->num_sge;
if (ib_wr->num_sge > qp->send_sgl_depth) {
err = -EINVAL;
break;
}
if (ib_wr->send_flags & IB_SEND_FENCE) {
flags |= SQ_READ_FENCE;
}
err = move_sgl((struct c2_data_addr *) & (wr.sqwr.send.data),
ib_wr->sg_list,
ib_wr->num_sge,
&tot_len, &actual_sge_count);
wr.sqwr.send.sge_len = cpu_to_be32(tot_len);
c2_wr_set_sge_count(&wr, actual_sge_count);
break;
case IB_WR_RDMA_WRITE:
c2_wr_set_id(&wr, C2_WR_TYPE_RDMA_WRITE);
msg_size = sizeof(struct c2wr_rdma_write_req) +
(sizeof(struct c2_data_addr) * ib_wr->num_sge);
if (ib_wr->num_sge > qp->rdma_write_sgl_depth) {
err = -EINVAL;
break;
}
if (ib_wr->send_flags & IB_SEND_FENCE) {
flags |= SQ_READ_FENCE;
}
wr.sqwr.rdma_write.remote_stag =
cpu_to_be32(ib_wr->wr.rdma.rkey);
wr.sqwr.rdma_write.remote_to =
cpu_to_be64(ib_wr->wr.rdma.remote_addr);
err = move_sgl((struct c2_data_addr *)
& (wr.sqwr.rdma_write.data),
ib_wr->sg_list,
ib_wr->num_sge,
&tot_len, &actual_sge_count);
wr.sqwr.rdma_write.sge_len = cpu_to_be32(tot_len);
c2_wr_set_sge_count(&wr, actual_sge_count);
break;
case IB_WR_RDMA_READ:
c2_wr_set_id(&wr, C2_WR_TYPE_RDMA_READ);
msg_size = sizeof(struct c2wr_rdma_read_req);
/* IWarp only suppots 1 sge for RDMA reads */
if (ib_wr->num_sge > 1) {
err = -EINVAL;
break;
}
/*
* Move the local and remote stag/to/len into the WR.
*/
wr.sqwr.rdma_read.local_stag =
cpu_to_be32(ib_wr->sg_list->lkey);
wr.sqwr.rdma_read.local_to =
cpu_to_be64(ib_wr->sg_list->addr);
wr.sqwr.rdma_read.remote_stag =
cpu_to_be32(ib_wr->wr.rdma.rkey);
wr.sqwr.rdma_read.remote_to =
cpu_to_be64(ib_wr->wr.rdma.remote_addr);
wr.sqwr.rdma_read.length =
cpu_to_be32(ib_wr->sg_list->length);
break;
default:
/* error */
msg_size = 0;
err = -EINVAL;
break;
}
/*
* If we had an error on the last wr build, then
* break out. Possible errors include bogus WR
* type, and a bogus SGL length...
*/
if (err) {
break;
}
/*
* Store flags
*/
c2_wr_set_flags(&wr, flags);
/*
* Post the puppy!
*/
spin_lock_irqsave(&qp->lock, lock_flags);
err = qp_wr_post(&qp->sq_mq, &wr, qp, msg_size);
if (err) {
spin_unlock_irqrestore(&qp->lock, lock_flags);
break;
}
/*
* Enqueue mq index to activity FIFO.
*/
c2_activity(c2dev, qp->sq_mq.index, qp->sq_mq.hint_count);
spin_unlock_irqrestore(&qp->lock, lock_flags);
ib_wr = ib_wr->next;
}
out:
if (err)
*bad_wr = ib_wr;
return err;
}
int c2_post_receive(struct ib_qp *ibqp, struct ib_recv_wr *ib_wr,
struct ib_recv_wr **bad_wr)
{
struct c2_dev *c2dev = to_c2dev(ibqp->device);
struct c2_qp *qp = to_c2qp(ibqp);
union c2wr wr;
unsigned long lock_flags;
int err = 0;
if (qp->state > IB_QPS_RTS) {
err = -EINVAL;
goto out;
}
/*
* Try and post each work request
*/
while (ib_wr) {
u32 tot_len;
u8 actual_sge_count;
if (ib_wr->num_sge > qp->recv_sgl_depth) {
err = -EINVAL;
break;
}
/*
* Create local host-copy of the WR
*/
wr.rqwr.rq_hdr.user_hdr.hdr.context = ib_wr->wr_id;
c2_wr_set_id(&wr, CCWR_RECV);
c2_wr_set_flags(&wr, 0);
/* sge_count is limited to eight bits. */
BUG_ON(ib_wr->num_sge >= 256);
err = move_sgl((struct c2_data_addr *) & (wr.rqwr.data),
ib_wr->sg_list,
ib_wr->num_sge, &tot_len, &actual_sge_count);
c2_wr_set_sge_count(&wr, actual_sge_count);
/*
* If we had an error on the last wr build, then
* break out. Possible errors include bogus WR
* type, and a bogus SGL length...
*/
if (err) {
break;
}
spin_lock_irqsave(&qp->lock, lock_flags);
err = qp_wr_post(&qp->rq_mq, &wr, qp, qp->rq_mq.msg_size);
if (err) {
spin_unlock_irqrestore(&qp->lock, lock_flags);
break;
}
/*
* Enqueue mq index to activity FIFO
*/
c2_activity(c2dev, qp->rq_mq.index, qp->rq_mq.hint_count);
spin_unlock_irqrestore(&qp->lock, lock_flags);
ib_wr = ib_wr->next;
}
out:
if (err)
*bad_wr = ib_wr;
return err;
}
void __devinit c2_init_qp_table(struct c2_dev *c2dev)
{
spin_lock_init(&c2dev->qp_table.lock);
idr_init(&c2dev->qp_table.idr);
}
void __devexit c2_cleanup_qp_table(struct c2_dev *c2dev)
{
idr_destroy(&c2dev->qp_table.idr);
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.