repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
librae8226/rpi | arch/mips/powertv/time.c | 10666 | 1134 | /*
* Carsten Langgaard, carstenl@mips.com
* Copyright (C) 1999,2000 MIPS Technologies, Inc. All rights reserved.
* Portions copyright (C) 2009 Cisco Systems, Inc.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Setting up the clock on the MIPS boards.
*/
#include <linux/init.h>
#include <asm/mach-powertv/interrupts.h>
#include <asm/time.h>
#include "powertv-clock.h"
unsigned int __cpuinit get_c0_compare_int(void)
{
return irq_mips_timer;
}
void __init plat_time_init(void)
{
powertv_clocksource_init();
}
| gpl-2.0 |
victormlourenco/red_kernel_lge_v500 | arch/m32r/mm/ioremap-nommu.c | 13994 | 1282 | /*
* linux/arch/m32r/mm/ioremap-nommu.c
*
* Copyright (c) 2001, 2002 Hiroyuki Kondo
*
* Taken from mips version.
* (C) Copyright 1995 1996 Linus Torvalds
* (C) Copyright 2001 Ralf Baechle
*/
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
*/
#include <linux/module.h>
#include <asm/addrspace.h>
#include <asm/byteorder.h>
#include <linux/vmalloc.h>
#include <asm/io.h>
#include <asm/pgalloc.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
/*
* Remap an arbitrary physical address space into the kernel virtual
* address space. Needed when the kernel wants to access high addresses
* directly.
*
* NOTE! We need to allow non-page-aligned mappings too: we will obviously
* have to convert them into an offset in a page-aligned mapping, but the
* caller shouldn't need to know that small detail.
*/
#define IS_LOW512(addr) (!((unsigned long)(addr) & ~0x1fffffffUL))
void __iomem *
__ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags)
{
return (void *)phys_addr;
}
#define IS_KSEG1(addr) (((unsigned long)(addr) & ~0x1fffffffUL) == KSEG1)
void iounmap(volatile void __iomem *addr)
{
}
| gpl-2.0 |
shichao-an/linux-2.6.34.7 | drivers/video/i810/i810_gtf.c | 15530 | 9148 | /*-*- linux-c -*-
* linux/drivers/video/i810_main.h -- Intel 810 Non-discrete Video Timings
* (VESA GTF)
*
* Copyright (C) 2001 Antonino Daplas<adaplas@pol.net>
* All Rights Reserved
*
*
* 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 "i810_regs.h"
#include "i810.h"
#include "i810_main.h"
/*
* FIFO and Watermark tables - based almost wholly on i810_wmark.c in
* XFree86 v4.03 by Precision Insight. Slightly modified for integer
* operation, instead of float
*/
struct wm_info {
u32 freq;
u32 wm;
};
static struct wm_info i810_wm_8_100[] = {
{ 15, 0x0070c000 }, { 19, 0x0070c000 }, { 25, 0x22003000 },
{ 28, 0x22003000 }, { 31, 0x22003000 }, { 36, 0x22007000 },
{ 40, 0x22007000 }, { 45, 0x22007000 }, { 49, 0x22008000 },
{ 50, 0x22008000 }, { 56, 0x22008000 }, { 65, 0x22008000 },
{ 75, 0x22008000 }, { 78, 0x22008000 }, { 80, 0x22008000 },
{ 94, 0x22008000 }, { 96, 0x22107000 }, { 99, 0x22107000 },
{ 108, 0x22107000 }, { 121, 0x22107000 }, { 128, 0x22107000 },
{ 132, 0x22109000 }, { 135, 0x22109000 }, { 157, 0x2210b000 },
{ 162, 0x2210b000 }, { 175, 0x2210b000 }, { 189, 0x2220e000 },
{ 195, 0x2220e000 }, { 202, 0x2220e000 }, { 204, 0x2220e000 },
{ 218, 0x2220f000 }, { 229, 0x22210000 }, { 234, 0x22210000 },
};
static struct wm_info i810_wm_16_100[] = {
{ 15, 0x0070c000 }, { 19, 0x0020c000 }, { 25, 0x22006000 },
{ 28, 0x22006000 }, { 31, 0x22007000 }, { 36, 0x22007000 },
{ 40, 0x22007000 }, { 45, 0x22007000 }, { 49, 0x22009000 },
{ 50, 0x22009000 }, { 56, 0x22108000 }, { 65, 0x2210e000 },
{ 75, 0x2210e000 }, { 78, 0x2210e000 }, { 80, 0x22210000 },
{ 94, 0x22210000 }, { 96, 0x22210000 }, { 99, 0x22210000 },
{ 108, 0x22210000 }, { 121, 0x22210000 }, { 128, 0x22210000 },
{ 132, 0x22314000 }, { 135, 0x22314000 }, { 157, 0x22415000 },
{ 162, 0x22416000 }, { 175, 0x22416000 }, { 189, 0x22416000 },
{ 195, 0x22416000 }, { 202, 0x22416000 }, { 204, 0x22416000 },
{ 218, 0x22416000 }, { 229, 0x22416000 },
};
static struct wm_info i810_wm_24_100[] = {
{ 15, 0x0020c000 }, { 19, 0x0040c000 }, { 25, 0x22009000 },
{ 28, 0x22009000 }, { 31, 0x2200a000 }, { 36, 0x2210c000 },
{ 40, 0x2210c000 }, { 45, 0x2210c000 }, { 49, 0x22111000 },
{ 50, 0x22111000 }, { 56, 0x22111000 }, { 65, 0x22214000 },
{ 75, 0x22214000 }, { 78, 0x22215000 }, { 80, 0x22216000 },
{ 94, 0x22218000 }, { 96, 0x22418000 }, { 99, 0x22418000 },
{ 108, 0x22418000 }, { 121, 0x22418000 }, { 128, 0x22419000 },
{ 132, 0x22519000 }, { 135, 0x4441d000 }, { 157, 0x44419000 },
{ 162, 0x44419000 }, { 175, 0x44419000 }, { 189, 0x44419000 },
{ 195, 0x44419000 }, { 202, 0x44419000 }, { 204, 0x44419000 },
};
static struct wm_info i810_wm_8_133[] = {
{ 15, 0x0070c000 }, { 19, 0x0070c000 }, { 25, 0x22003000 },
{ 28, 0x22003000 }, { 31, 0x22003000 }, { 36, 0x22007000 },
{ 40, 0x22007000 }, { 45, 0x22007000 }, { 49, 0x22008000 },
{ 50, 0x22008000 }, { 56, 0x22008000 }, { 65, 0x22008000 },
{ 75, 0x22008000 }, { 78, 0x22008000 }, { 80, 0x22008000 },
{ 94, 0x22008000 }, { 96, 0x22107000 }, { 99, 0x22107000 },
{ 108, 0x22107000 }, { 121, 0x22107000 }, { 128, 0x22107000 },
{ 132, 0x22109000 }, { 135, 0x22109000 }, { 157, 0x2210b000 },
{ 162, 0x2210b000 }, { 175, 0x2210b000 }, { 189, 0x2220e000 },
{ 195, 0x2220e000 }, { 202, 0x2220e000 }, { 204, 0x2220e000 },
{ 218, 0x2220f000 }, { 229, 0x22210000 }, { 234, 0x22210000 },
};
static struct wm_info i810_wm_16_133[] = {
{ 15, 0x0020c000 }, { 19, 0x0020c000 }, { 25, 0x22006000 },
{ 28, 0x22006000 }, { 31, 0x22007000 }, { 36, 0x22007000 },
{ 40, 0x22007000 }, { 45, 0x22007000 }, { 49, 0x22009000 },
{ 50, 0x22009000 }, { 56, 0x22108000 }, { 65, 0x2210e000 },
{ 75, 0x2210e000 }, { 78, 0x2210e000 }, { 80, 0x22210000 },
{ 94, 0x22210000 }, { 96, 0x22210000 }, { 99, 0x22210000 },
{ 108, 0x22210000 }, { 121, 0x22210000 }, { 128, 0x22210000 },
{ 132, 0x22314000 }, { 135, 0x22314000 }, { 157, 0x22415000 },
{ 162, 0x22416000 }, { 175, 0x22416000 }, { 189, 0x22416000 },
{ 195, 0x22416000 }, { 202, 0x22416000 }, { 204, 0x22416000 },
{ 218, 0x22416000 }, { 229, 0x22416000 },
};
static struct wm_info i810_wm_24_133[] = {
{ 15, 0x0020c000 }, { 19, 0x00408000 }, { 25, 0x22009000 },
{ 28, 0x22009000 }, { 31, 0x2200a000 }, { 36, 0x2210c000 },
{ 40, 0x2210c000 }, { 45, 0x2210c000 }, { 49, 0x22111000 },
{ 50, 0x22111000 }, { 56, 0x22111000 }, { 65, 0x22214000 },
{ 75, 0x22214000 }, { 78, 0x22215000 }, { 80, 0x22216000 },
{ 94, 0x22218000 }, { 96, 0x22418000 }, { 99, 0x22418000 },
{ 108, 0x22418000 }, { 121, 0x22418000 }, { 128, 0x22419000 },
{ 132, 0x22519000 }, { 135, 0x4441d000 }, { 157, 0x44419000 },
{ 162, 0x44419000 }, { 175, 0x44419000 }, { 189, 0x44419000 },
{ 195, 0x44419000 }, { 202, 0x44419000 }, { 204, 0x44419000 },
};
void round_off_xres(u32 *xres) { }
void round_off_yres(u32 *xres, u32 *yres) { }
/**
* i810fb_encode_registers - encode @var to hardware register values
* @var: pointer to var structure
* @par: pointer to hardware par structure
*
* DESCRIPTION:
* Timing values in @var will be converted to appropriate
* register values of @par.
*/
void i810fb_encode_registers(const struct fb_var_screeninfo *var,
struct i810fb_par *par, u32 xres, u32 yres)
{
int n, blank_s, blank_e;
u8 __iomem *mmio = par->mmio_start_virtual;
u8 msr = 0;
/* Horizontal */
/* htotal */
n = ((xres + var->right_margin + var->hsync_len +
var->left_margin) >> 3) - 5;
par->regs.cr00 = (u8) n;
par->regs.cr35 = (u8) ((n >> 8) & 1);
/* xres */
par->regs.cr01 = (u8) ((xres >> 3) - 1);
/* hblank */
blank_e = (xres + var->right_margin + var->hsync_len +
var->left_margin) >> 3;
blank_e--;
blank_s = blank_e - 127;
if (blank_s < (xres >> 3))
blank_s = xres >> 3;
par->regs.cr02 = (u8) blank_s;
par->regs.cr03 = (u8) (blank_e & 0x1F);
par->regs.cr05 = (u8) ((blank_e & (1 << 5)) << 2);
par->regs.cr39 = (u8) ((blank_e >> 6) & 1);
/* hsync */
par->regs.cr04 = (u8) ((xres + var->right_margin) >> 3);
par->regs.cr05 |= (u8) (((xres + var->right_margin +
var->hsync_len) >> 3) & 0x1F);
/* Vertical */
/* vtotal */
n = yres + var->lower_margin + var->vsync_len + var->upper_margin - 2;
par->regs.cr06 = (u8) (n & 0xFF);
par->regs.cr30 = (u8) ((n >> 8) & 0x0F);
/* vsync */
n = yres + var->lower_margin;
par->regs.cr10 = (u8) (n & 0xFF);
par->regs.cr32 = (u8) ((n >> 8) & 0x0F);
par->regs.cr11 = i810_readb(CR11, mmio) & ~0x0F;
par->regs.cr11 |= (u8) ((yres + var->lower_margin +
var->vsync_len) & 0x0F);
/* yres */
n = yres - 1;
par->regs.cr12 = (u8) (n & 0xFF);
par->regs.cr31 = (u8) ((n >> 8) & 0x0F);
/* vblank */
blank_e = yres + var->lower_margin + var->vsync_len +
var->upper_margin;
blank_e--;
blank_s = blank_e - 127;
if (blank_s < yres)
blank_s = yres;
par->regs.cr15 = (u8) (blank_s & 0xFF);
par->regs.cr33 = (u8) ((blank_s >> 8) & 0x0F);
par->regs.cr16 = (u8) (blank_e & 0xFF);
par->regs.cr09 = 0;
/* sync polarity */
if (!(var->sync & FB_SYNC_HOR_HIGH_ACT))
msr |= 1 << 6;
if (!(var->sync & FB_SYNC_VERT_HIGH_ACT))
msr |= 1 << 7;
par->regs.msr = msr;
/* interlace */
if (var->vmode & FB_VMODE_INTERLACED)
par->interlace = (1 << 7) | ((u8) (var->yres >> 4));
else
par->interlace = 0;
if (var->vmode & FB_VMODE_DOUBLE)
par->regs.cr09 |= 1 << 7;
/* overlay */
par->ovract = ((var->xres + var->right_margin + var->hsync_len +
var->left_margin - 32) | ((var->xres - 32) << 16));
}
void i810fb_fill_var_timings(struct fb_var_screeninfo *var) { }
/**
* i810_get_watermark - gets watermark
* @var: pointer to fb_var_screeninfo
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* Gets the required watermark based on
* pixelclock and RAMBUS frequency.
*
* RETURNS:
* watermark
*/
u32 i810_get_watermark(const struct fb_var_screeninfo *var,
struct i810fb_par *par)
{
struct wm_info *wmark = NULL;
u32 i, size = 0, pixclock, wm_best = 0, min, diff;
if (par->mem_freq == 100) {
switch (var->bits_per_pixel) {
case 8:
wmark = i810_wm_8_100;
size = ARRAY_SIZE(i810_wm_8_100);
break;
case 16:
wmark = i810_wm_16_100;
size = ARRAY_SIZE(i810_wm_16_100);
break;
case 24:
case 32:
wmark = i810_wm_24_100;
size = ARRAY_SIZE(i810_wm_24_100);
}
} else {
switch(var->bits_per_pixel) {
case 8:
wmark = i810_wm_8_133;
size = ARRAY_SIZE(i810_wm_8_133);
break;
case 16:
wmark = i810_wm_16_133;
size = ARRAY_SIZE(i810_wm_16_133);
break;
case 24:
case 32:
wmark = i810_wm_24_133;
size = ARRAY_SIZE(i810_wm_24_133);
}
}
pixclock = 1000000/var->pixclock;
min = ~0;
for (i = 0; i < size; i++) {
if (pixclock <= wmark[i].freq)
diff = wmark[i].freq - pixclock;
else
diff = pixclock - wmark[i].freq;
if (diff < min) {
wm_best = wmark[i].wm;
min = diff;
}
}
return wm_best;
}
| gpl-2.0 |
jenswi-linaro/linux | drivers/net/fjes/fjes_main.c | 427 | 34327 | /*
* FUJITSU Extended Socket Network Device driver
* Copyright (c) 2015 FUJITSU LIMITED
*
* 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, see <http://www.gnu.org/licenses/>.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/nls.h>
#include <linux/platform_device.h>
#include <linux/netdevice.h>
#include <linux/interrupt.h>
#include "fjes.h"
#define MAJ 1
#define MIN 0
#define DRV_VERSION __stringify(MAJ) "." __stringify(MIN)
#define DRV_NAME "fjes"
char fjes_driver_name[] = DRV_NAME;
char fjes_driver_version[] = DRV_VERSION;
static const char fjes_driver_string[] =
"FUJITSU Extended Socket Network Device Driver";
static const char fjes_copyright[] =
"Copyright (c) 2015 FUJITSU LIMITED";
MODULE_AUTHOR("Taku Izumi <izumi.taku@jp.fujitsu.com>");
MODULE_DESCRIPTION("FUJITSU Extended Socket Network Device Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
static int fjes_request_irq(struct fjes_adapter *);
static void fjes_free_irq(struct fjes_adapter *);
static int fjes_open(struct net_device *);
static int fjes_close(struct net_device *);
static int fjes_setup_resources(struct fjes_adapter *);
static void fjes_free_resources(struct fjes_adapter *);
static netdev_tx_t fjes_xmit_frame(struct sk_buff *, struct net_device *);
static void fjes_raise_intr_rxdata_task(struct work_struct *);
static void fjes_tx_stall_task(struct work_struct *);
static void fjes_force_close_task(struct work_struct *);
static irqreturn_t fjes_intr(int, void*);
static struct rtnl_link_stats64 *
fjes_get_stats64(struct net_device *, struct rtnl_link_stats64 *);
static int fjes_change_mtu(struct net_device *, int);
static int fjes_vlan_rx_add_vid(struct net_device *, __be16 proto, u16);
static int fjes_vlan_rx_kill_vid(struct net_device *, __be16 proto, u16);
static void fjes_tx_retry(struct net_device *);
static int fjes_acpi_add(struct acpi_device *);
static int fjes_acpi_remove(struct acpi_device *);
static acpi_status fjes_get_acpi_resource(struct acpi_resource *, void*);
static int fjes_probe(struct platform_device *);
static int fjes_remove(struct platform_device *);
static int fjes_sw_init(struct fjes_adapter *);
static void fjes_netdev_setup(struct net_device *);
static void fjes_irq_watch_task(struct work_struct *);
static void fjes_watch_unshare_task(struct work_struct *);
static void fjes_rx_irq(struct fjes_adapter *, int);
static int fjes_poll(struct napi_struct *, int);
static const struct acpi_device_id fjes_acpi_ids[] = {
{"PNP0C02", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, fjes_acpi_ids);
static struct acpi_driver fjes_acpi_driver = {
.name = DRV_NAME,
.class = DRV_NAME,
.owner = THIS_MODULE,
.ids = fjes_acpi_ids,
.ops = {
.add = fjes_acpi_add,
.remove = fjes_acpi_remove,
},
};
static struct platform_driver fjes_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = fjes_probe,
.remove = fjes_remove,
};
static struct resource fjes_resource[] = {
{
.flags = IORESOURCE_MEM,
.start = 0,
.end = 0,
},
{
.flags = IORESOURCE_IRQ,
.start = 0,
.end = 0,
},
};
static int fjes_acpi_add(struct acpi_device *device)
{
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL};
char str_buf[sizeof(FJES_ACPI_SYMBOL) + 1];
struct platform_device *plat_dev;
union acpi_object *str;
acpi_status status;
int result;
status = acpi_evaluate_object(device->handle, "_STR", NULL, &buffer);
if (ACPI_FAILURE(status))
return -ENODEV;
str = buffer.pointer;
result = utf16s_to_utf8s((wchar_t *)str->string.pointer,
str->string.length, UTF16_LITTLE_ENDIAN,
str_buf, sizeof(str_buf) - 1);
str_buf[result] = 0;
if (strncmp(FJES_ACPI_SYMBOL, str_buf, strlen(FJES_ACPI_SYMBOL)) != 0) {
kfree(buffer.pointer);
return -ENODEV;
}
kfree(buffer.pointer);
status = acpi_walk_resources(device->handle, METHOD_NAME__CRS,
fjes_get_acpi_resource, fjes_resource);
if (ACPI_FAILURE(status))
return -ENODEV;
/* create platform_device */
plat_dev = platform_device_register_simple(DRV_NAME, 0, fjes_resource,
ARRAY_SIZE(fjes_resource));
device->driver_data = plat_dev;
return 0;
}
static int fjes_acpi_remove(struct acpi_device *device)
{
struct platform_device *plat_dev;
plat_dev = (struct platform_device *)acpi_driver_data(device);
platform_device_unregister(plat_dev);
return 0;
}
static acpi_status
fjes_get_acpi_resource(struct acpi_resource *acpi_res, void *data)
{
struct acpi_resource_address32 *addr;
struct acpi_resource_irq *irq;
struct resource *res = data;
switch (acpi_res->type) {
case ACPI_RESOURCE_TYPE_ADDRESS32:
addr = &acpi_res->data.address32;
res[0].start = addr->address.minimum;
res[0].end = addr->address.minimum +
addr->address.address_length - 1;
break;
case ACPI_RESOURCE_TYPE_IRQ:
irq = &acpi_res->data.irq;
if (irq->interrupt_count != 1)
return AE_ERROR;
res[1].start = irq->interrupts[0];
res[1].end = irq->interrupts[0];
break;
default:
break;
}
return AE_OK;
}
static int fjes_request_irq(struct fjes_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int result = -1;
adapter->interrupt_watch_enable = true;
if (!delayed_work_pending(&adapter->interrupt_watch_task)) {
queue_delayed_work(adapter->control_wq,
&adapter->interrupt_watch_task,
FJES_IRQ_WATCH_DELAY);
}
if (!adapter->irq_registered) {
result = request_irq(adapter->hw.hw_res.irq, fjes_intr,
IRQF_SHARED, netdev->name, adapter);
if (result)
adapter->irq_registered = false;
else
adapter->irq_registered = true;
}
return result;
}
static void fjes_free_irq(struct fjes_adapter *adapter)
{
struct fjes_hw *hw = &adapter->hw;
adapter->interrupt_watch_enable = false;
cancel_delayed_work_sync(&adapter->interrupt_watch_task);
fjes_hw_set_irqmask(hw, REG_ICTL_MASK_ALL, true);
if (adapter->irq_registered) {
free_irq(adapter->hw.hw_res.irq, adapter);
adapter->irq_registered = false;
}
}
static const struct net_device_ops fjes_netdev_ops = {
.ndo_open = fjes_open,
.ndo_stop = fjes_close,
.ndo_start_xmit = fjes_xmit_frame,
.ndo_get_stats64 = fjes_get_stats64,
.ndo_change_mtu = fjes_change_mtu,
.ndo_tx_timeout = fjes_tx_retry,
.ndo_vlan_rx_add_vid = fjes_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = fjes_vlan_rx_kill_vid,
};
/* fjes_open - Called when a network interface is made active */
static int fjes_open(struct net_device *netdev)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
struct fjes_hw *hw = &adapter->hw;
int result;
if (adapter->open_guard)
return -ENXIO;
result = fjes_setup_resources(adapter);
if (result)
goto err_setup_res;
hw->txrx_stop_req_bit = 0;
hw->epstop_req_bit = 0;
napi_enable(&adapter->napi);
fjes_hw_capture_interrupt_status(hw);
result = fjes_request_irq(adapter);
if (result)
goto err_req_irq;
fjes_hw_set_irqmask(hw, REG_ICTL_MASK_ALL, false);
netif_tx_start_all_queues(netdev);
netif_carrier_on(netdev);
return 0;
err_req_irq:
fjes_free_irq(adapter);
napi_disable(&adapter->napi);
err_setup_res:
fjes_free_resources(adapter);
return result;
}
/* fjes_close - Disables a network interface */
static int fjes_close(struct net_device *netdev)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
struct fjes_hw *hw = &adapter->hw;
int epidx;
netif_tx_stop_all_queues(netdev);
netif_carrier_off(netdev);
fjes_hw_raise_epstop(hw);
napi_disable(&adapter->napi);
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
adapter->hw.ep_shm_info[epidx].tx.info->v1i.rx_status &=
~FJES_RX_POLL_WORK;
}
fjes_free_irq(adapter);
cancel_delayed_work_sync(&adapter->interrupt_watch_task);
cancel_work_sync(&adapter->unshare_watch_task);
adapter->unshare_watch_bitmask = 0;
cancel_work_sync(&adapter->raise_intr_rxdata_task);
cancel_work_sync(&adapter->tx_stall_task);
cancel_work_sync(&hw->update_zone_task);
cancel_work_sync(&hw->epstop_task);
fjes_hw_wait_epstop(hw);
fjes_free_resources(adapter);
return 0;
}
static int fjes_setup_resources(struct fjes_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct ep_share_mem_info *buf_pair;
struct fjes_hw *hw = &adapter->hw;
int result;
int epidx;
mutex_lock(&hw->hw_info.lock);
result = fjes_hw_request_info(hw);
switch (result) {
case 0:
for (epidx = 0; epidx < hw->max_epid; epidx++) {
hw->ep_shm_info[epidx].es_status =
hw->hw_info.res_buf->info.info[epidx].es_status;
hw->ep_shm_info[epidx].zone =
hw->hw_info.res_buf->info.info[epidx].zone;
}
break;
default:
case -ENOMSG:
case -EBUSY:
adapter->force_reset = true;
mutex_unlock(&hw->hw_info.lock);
return result;
}
mutex_unlock(&hw->hw_info.lock);
for (epidx = 0; epidx < (hw->max_epid); epidx++) {
if ((epidx != hw->my_epid) &&
(hw->ep_shm_info[epidx].es_status ==
FJES_ZONING_STATUS_ENABLE)) {
fjes_hw_raise_interrupt(hw, epidx,
REG_ICTL_MASK_INFO_UPDATE);
}
}
msleep(FJES_OPEN_ZONE_UPDATE_WAIT * hw->max_epid);
for (epidx = 0; epidx < (hw->max_epid); epidx++) {
if (epidx == hw->my_epid)
continue;
buf_pair = &hw->ep_shm_info[epidx];
fjes_hw_setup_epbuf(&buf_pair->tx, netdev->dev_addr,
netdev->mtu);
if (fjes_hw_epid_is_same_zone(hw, epidx)) {
mutex_lock(&hw->hw_info.lock);
result =
fjes_hw_register_buff_addr(hw, epidx, buf_pair);
mutex_unlock(&hw->hw_info.lock);
switch (result) {
case 0:
break;
case -ENOMSG:
case -EBUSY:
default:
adapter->force_reset = true;
return result;
}
}
}
return 0;
}
static void fjes_free_resources(struct fjes_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct fjes_device_command_param param;
struct ep_share_mem_info *buf_pair;
struct fjes_hw *hw = &adapter->hw;
bool reset_flag = false;
int result;
int epidx;
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
mutex_lock(&hw->hw_info.lock);
result = fjes_hw_unregister_buff_addr(hw, epidx);
mutex_unlock(&hw->hw_info.lock);
if (result)
reset_flag = true;
buf_pair = &hw->ep_shm_info[epidx];
fjes_hw_setup_epbuf(&buf_pair->tx,
netdev->dev_addr, netdev->mtu);
clear_bit(epidx, &hw->txrx_stop_req_bit);
}
if (reset_flag || adapter->force_reset) {
result = fjes_hw_reset(hw);
adapter->force_reset = false;
if (result)
adapter->open_guard = true;
hw->hw_info.buffer_share_bit = 0;
memset((void *)¶m, 0, sizeof(param));
param.req_len = hw->hw_info.req_buf_size;
param.req_start = __pa(hw->hw_info.req_buf);
param.res_len = hw->hw_info.res_buf_size;
param.res_start = __pa(hw->hw_info.res_buf);
param.share_start = __pa(hw->hw_info.share->ep_status);
fjes_hw_init_command_registers(hw, ¶m);
}
}
static void fjes_tx_stall_task(struct work_struct *work)
{
struct fjes_adapter *adapter = container_of(work,
struct fjes_adapter, tx_stall_task);
struct net_device *netdev = adapter->netdev;
struct fjes_hw *hw = &adapter->hw;
int all_queue_available, sendable;
enum ep_partner_status pstatus;
int max_epid, my_epid, epid;
union ep_buffer_info *info;
int i;
if (((long)jiffies -
(long)(netdev->trans_start)) > FJES_TX_TX_STALL_TIMEOUT) {
netif_wake_queue(netdev);
return;
}
my_epid = hw->my_epid;
max_epid = hw->max_epid;
for (i = 0; i < 5; i++) {
all_queue_available = 1;
for (epid = 0; epid < max_epid; epid++) {
if (my_epid == epid)
continue;
pstatus = fjes_hw_get_partner_ep_status(hw, epid);
sendable = (pstatus == EP_PARTNER_SHARED);
if (!sendable)
continue;
info = adapter->hw.ep_shm_info[epid].tx.info;
if (EP_RING_FULL(info->v1i.head, info->v1i.tail,
info->v1i.count_max)) {
all_queue_available = 0;
break;
}
}
if (all_queue_available) {
netif_wake_queue(netdev);
return;
}
}
usleep_range(50, 100);
queue_work(adapter->txrx_wq, &adapter->tx_stall_task);
}
static void fjes_force_close_task(struct work_struct *work)
{
struct fjes_adapter *adapter = container_of(work,
struct fjes_adapter, force_close_task);
struct net_device *netdev = adapter->netdev;
rtnl_lock();
dev_close(netdev);
rtnl_unlock();
}
static void fjes_raise_intr_rxdata_task(struct work_struct *work)
{
struct fjes_adapter *adapter = container_of(work,
struct fjes_adapter, raise_intr_rxdata_task);
struct fjes_hw *hw = &adapter->hw;
enum ep_partner_status pstatus;
int max_epid, my_epid, epid;
my_epid = hw->my_epid;
max_epid = hw->max_epid;
for (epid = 0; epid < max_epid; epid++)
hw->ep_shm_info[epid].tx_status_work = 0;
for (epid = 0; epid < max_epid; epid++) {
if (epid == my_epid)
continue;
pstatus = fjes_hw_get_partner_ep_status(hw, epid);
if (pstatus == EP_PARTNER_SHARED) {
hw->ep_shm_info[epid].tx_status_work =
hw->ep_shm_info[epid].tx.info->v1i.tx_status;
if (hw->ep_shm_info[epid].tx_status_work ==
FJES_TX_DELAY_SEND_PENDING) {
hw->ep_shm_info[epid].tx.info->v1i.tx_status =
FJES_TX_DELAY_SEND_NONE;
}
}
}
for (epid = 0; epid < max_epid; epid++) {
if (epid == my_epid)
continue;
pstatus = fjes_hw_get_partner_ep_status(hw, epid);
if ((hw->ep_shm_info[epid].tx_status_work ==
FJES_TX_DELAY_SEND_PENDING) &&
(pstatus == EP_PARTNER_SHARED) &&
!(hw->ep_shm_info[epid].rx.info->v1i.rx_status)) {
fjes_hw_raise_interrupt(hw, epid,
REG_ICTL_MASK_RX_DATA);
}
}
usleep_range(500, 1000);
}
static int fjes_tx_send(struct fjes_adapter *adapter, int dest,
void *data, size_t len)
{
int retval;
retval = fjes_hw_epbuf_tx_pkt_send(&adapter->hw.ep_shm_info[dest].tx,
data, len);
if (retval)
return retval;
adapter->hw.ep_shm_info[dest].tx.info->v1i.tx_status =
FJES_TX_DELAY_SEND_PENDING;
if (!work_pending(&adapter->raise_intr_rxdata_task))
queue_work(adapter->txrx_wq,
&adapter->raise_intr_rxdata_task);
retval = 0;
return retval;
}
static netdev_tx_t
fjes_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
struct fjes_hw *hw = &adapter->hw;
int max_epid, my_epid, dest_epid;
enum ep_partner_status pstatus;
struct netdev_queue *cur_queue;
char shortpkt[VLAN_ETH_HLEN];
bool is_multi, vlan;
struct ethhdr *eth;
u16 queue_no = 0;
u16 vlan_id = 0;
netdev_tx_t ret;
char *data;
int len;
ret = NETDEV_TX_OK;
is_multi = false;
cur_queue = netdev_get_tx_queue(netdev, queue_no);
eth = (struct ethhdr *)skb->data;
my_epid = hw->my_epid;
vlan = (vlan_get_tag(skb, &vlan_id) == 0) ? true : false;
data = skb->data;
len = skb->len;
if (is_multicast_ether_addr(eth->h_dest)) {
dest_epid = 0;
max_epid = hw->max_epid;
is_multi = true;
} else if (is_local_ether_addr(eth->h_dest)) {
dest_epid = eth->h_dest[ETH_ALEN - 1];
max_epid = dest_epid + 1;
if ((eth->h_dest[0] == 0x02) &&
(0x00 == (eth->h_dest[1] | eth->h_dest[2] |
eth->h_dest[3] | eth->h_dest[4])) &&
(dest_epid < hw->max_epid)) {
;
} else {
dest_epid = 0;
max_epid = 0;
ret = NETDEV_TX_OK;
adapter->stats64.tx_packets += 1;
hw->ep_shm_info[my_epid].net_stats.tx_packets += 1;
adapter->stats64.tx_bytes += len;
hw->ep_shm_info[my_epid].net_stats.tx_bytes += len;
}
} else {
dest_epid = 0;
max_epid = 0;
ret = NETDEV_TX_OK;
adapter->stats64.tx_packets += 1;
hw->ep_shm_info[my_epid].net_stats.tx_packets += 1;
adapter->stats64.tx_bytes += len;
hw->ep_shm_info[my_epid].net_stats.tx_bytes += len;
}
for (; dest_epid < max_epid; dest_epid++) {
if (my_epid == dest_epid)
continue;
pstatus = fjes_hw_get_partner_ep_status(hw, dest_epid);
if (pstatus != EP_PARTNER_SHARED) {
ret = NETDEV_TX_OK;
} else if (!fjes_hw_check_epbuf_version(
&adapter->hw.ep_shm_info[dest_epid].rx, 0)) {
/* version is NOT 0 */
adapter->stats64.tx_carrier_errors += 1;
hw->ep_shm_info[my_epid].net_stats
.tx_carrier_errors += 1;
ret = NETDEV_TX_OK;
} else if (!fjes_hw_check_mtu(
&adapter->hw.ep_shm_info[dest_epid].rx,
netdev->mtu)) {
adapter->stats64.tx_dropped += 1;
hw->ep_shm_info[my_epid].net_stats.tx_dropped += 1;
adapter->stats64.tx_errors += 1;
hw->ep_shm_info[my_epid].net_stats.tx_errors += 1;
ret = NETDEV_TX_OK;
} else if (vlan &&
!fjes_hw_check_vlan_id(
&adapter->hw.ep_shm_info[dest_epid].rx,
vlan_id)) {
ret = NETDEV_TX_OK;
} else {
if (len < VLAN_ETH_HLEN) {
memset(shortpkt, 0, VLAN_ETH_HLEN);
memcpy(shortpkt, skb->data, skb->len);
len = VLAN_ETH_HLEN;
data = shortpkt;
}
if (adapter->tx_retry_count == 0) {
adapter->tx_start_jiffies = jiffies;
adapter->tx_retry_count = 1;
} else {
adapter->tx_retry_count++;
}
if (fjes_tx_send(adapter, dest_epid, data, len)) {
if (is_multi) {
ret = NETDEV_TX_OK;
} else if (
((long)jiffies -
(long)adapter->tx_start_jiffies) >=
FJES_TX_RETRY_TIMEOUT) {
adapter->stats64.tx_fifo_errors += 1;
hw->ep_shm_info[my_epid].net_stats
.tx_fifo_errors += 1;
adapter->stats64.tx_errors += 1;
hw->ep_shm_info[my_epid].net_stats
.tx_errors += 1;
ret = NETDEV_TX_OK;
} else {
netdev->trans_start = jiffies;
netif_tx_stop_queue(cur_queue);
if (!work_pending(&adapter->tx_stall_task))
queue_work(adapter->txrx_wq,
&adapter->tx_stall_task);
ret = NETDEV_TX_BUSY;
}
} else {
if (!is_multi) {
adapter->stats64.tx_packets += 1;
hw->ep_shm_info[my_epid].net_stats
.tx_packets += 1;
adapter->stats64.tx_bytes += len;
hw->ep_shm_info[my_epid].net_stats
.tx_bytes += len;
}
adapter->tx_retry_count = 0;
ret = NETDEV_TX_OK;
}
}
}
if (ret == NETDEV_TX_OK) {
dev_kfree_skb(skb);
if (is_multi) {
adapter->stats64.tx_packets += 1;
hw->ep_shm_info[my_epid].net_stats.tx_packets += 1;
adapter->stats64.tx_bytes += 1;
hw->ep_shm_info[my_epid].net_stats.tx_bytes += len;
}
}
return ret;
}
static void fjes_tx_retry(struct net_device *netdev)
{
struct netdev_queue *queue = netdev_get_tx_queue(netdev, 0);
netif_tx_wake_queue(queue);
}
static struct rtnl_link_stats64 *
fjes_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
memcpy(stats, &adapter->stats64, sizeof(struct rtnl_link_stats64));
return stats;
}
static int fjes_change_mtu(struct net_device *netdev, int new_mtu)
{
bool running = netif_running(netdev);
int ret = 0;
int idx;
for (idx = 0; fjes_support_mtu[idx] != 0; idx++) {
if (new_mtu <= fjes_support_mtu[idx]) {
new_mtu = fjes_support_mtu[idx];
if (new_mtu == netdev->mtu)
return 0;
if (running)
fjes_close(netdev);
netdev->mtu = new_mtu;
if (running)
ret = fjes_open(netdev);
return ret;
}
}
return -EINVAL;
}
static int fjes_vlan_rx_add_vid(struct net_device *netdev,
__be16 proto, u16 vid)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
bool ret = true;
int epid;
for (epid = 0; epid < adapter->hw.max_epid; epid++) {
if (epid == adapter->hw.my_epid)
continue;
if (!fjes_hw_check_vlan_id(
&adapter->hw.ep_shm_info[epid].tx, vid))
ret = fjes_hw_set_vlan_id(
&adapter->hw.ep_shm_info[epid].tx, vid);
}
return ret ? 0 : -ENOSPC;
}
static int fjes_vlan_rx_kill_vid(struct net_device *netdev,
__be16 proto, u16 vid)
{
struct fjes_adapter *adapter = netdev_priv(netdev);
int epid;
for (epid = 0; epid < adapter->hw.max_epid; epid++) {
if (epid == adapter->hw.my_epid)
continue;
fjes_hw_del_vlan_id(&adapter->hw.ep_shm_info[epid].tx, vid);
}
return 0;
}
static void fjes_txrx_stop_req_irq(struct fjes_adapter *adapter,
int src_epid)
{
struct fjes_hw *hw = &adapter->hw;
enum ep_partner_status status;
status = fjes_hw_get_partner_ep_status(hw, src_epid);
switch (status) {
case EP_PARTNER_UNSHARE:
case EP_PARTNER_COMPLETE:
default:
break;
case EP_PARTNER_WAITING:
if (src_epid < hw->my_epid) {
hw->ep_shm_info[src_epid].tx.info->v1i.rx_status |=
FJES_RX_STOP_REQ_DONE;
clear_bit(src_epid, &hw->txrx_stop_req_bit);
set_bit(src_epid, &adapter->unshare_watch_bitmask);
if (!work_pending(&adapter->unshare_watch_task))
queue_work(adapter->control_wq,
&adapter->unshare_watch_task);
}
break;
case EP_PARTNER_SHARED:
if (hw->ep_shm_info[src_epid].rx.info->v1i.rx_status &
FJES_RX_STOP_REQ_REQUEST) {
set_bit(src_epid, &hw->epstop_req_bit);
if (!work_pending(&hw->epstop_task))
queue_work(adapter->control_wq,
&hw->epstop_task);
}
break;
}
}
static void fjes_stop_req_irq(struct fjes_adapter *adapter, int src_epid)
{
struct fjes_hw *hw = &adapter->hw;
enum ep_partner_status status;
set_bit(src_epid, &hw->hw_info.buffer_unshare_reserve_bit);
status = fjes_hw_get_partner_ep_status(hw, src_epid);
switch (status) {
case EP_PARTNER_WAITING:
hw->ep_shm_info[src_epid].tx.info->v1i.rx_status |=
FJES_RX_STOP_REQ_DONE;
clear_bit(src_epid, &hw->txrx_stop_req_bit);
/* fall through */
case EP_PARTNER_UNSHARE:
case EP_PARTNER_COMPLETE:
default:
set_bit(src_epid, &adapter->unshare_watch_bitmask);
if (!work_pending(&adapter->unshare_watch_task))
queue_work(adapter->control_wq,
&adapter->unshare_watch_task);
break;
case EP_PARTNER_SHARED:
set_bit(src_epid, &hw->epstop_req_bit);
if (!work_pending(&hw->epstop_task))
queue_work(adapter->control_wq, &hw->epstop_task);
break;
}
}
static void fjes_update_zone_irq(struct fjes_adapter *adapter,
int src_epid)
{
struct fjes_hw *hw = &adapter->hw;
if (!work_pending(&hw->update_zone_task))
queue_work(adapter->control_wq, &hw->update_zone_task);
}
static irqreturn_t fjes_intr(int irq, void *data)
{
struct fjes_adapter *adapter = data;
struct fjes_hw *hw = &adapter->hw;
irqreturn_t ret;
u32 icr;
icr = fjes_hw_capture_interrupt_status(hw);
if (icr & REG_IS_MASK_IS_ASSERT) {
if (icr & REG_ICTL_MASK_RX_DATA)
fjes_rx_irq(adapter, icr & REG_IS_MASK_EPID);
if (icr & REG_ICTL_MASK_DEV_STOP_REQ)
fjes_stop_req_irq(adapter, icr & REG_IS_MASK_EPID);
if (icr & REG_ICTL_MASK_TXRX_STOP_REQ)
fjes_txrx_stop_req_irq(adapter, icr & REG_IS_MASK_EPID);
if (icr & REG_ICTL_MASK_TXRX_STOP_DONE)
fjes_hw_set_irqmask(hw,
REG_ICTL_MASK_TXRX_STOP_DONE, true);
if (icr & REG_ICTL_MASK_INFO_UPDATE)
fjes_update_zone_irq(adapter, icr & REG_IS_MASK_EPID);
ret = IRQ_HANDLED;
} else {
ret = IRQ_NONE;
}
return ret;
}
static int fjes_rxframe_search_exist(struct fjes_adapter *adapter,
int start_epid)
{
struct fjes_hw *hw = &adapter->hw;
enum ep_partner_status pstatus;
int max_epid, cur_epid;
int i;
max_epid = hw->max_epid;
start_epid = (start_epid + 1 + max_epid) % max_epid;
for (i = 0; i < max_epid; i++) {
cur_epid = (start_epid + i) % max_epid;
if (cur_epid == hw->my_epid)
continue;
pstatus = fjes_hw_get_partner_ep_status(hw, cur_epid);
if (pstatus == EP_PARTNER_SHARED) {
if (!fjes_hw_epbuf_rx_is_empty(
&hw->ep_shm_info[cur_epid].rx))
return cur_epid;
}
}
return -1;
}
static void *fjes_rxframe_get(struct fjes_adapter *adapter, size_t *psize,
int *cur_epid)
{
void *frame;
*cur_epid = fjes_rxframe_search_exist(adapter, *cur_epid);
if (*cur_epid < 0)
return NULL;
frame =
fjes_hw_epbuf_rx_curpkt_get_addr(
&adapter->hw.ep_shm_info[*cur_epid].rx, psize);
return frame;
}
static void fjes_rxframe_release(struct fjes_adapter *adapter, int cur_epid)
{
fjes_hw_epbuf_rx_curpkt_drop(&adapter->hw.ep_shm_info[cur_epid].rx);
}
static void fjes_rx_irq(struct fjes_adapter *adapter, int src_epid)
{
struct fjes_hw *hw = &adapter->hw;
fjes_hw_set_irqmask(hw, REG_ICTL_MASK_RX_DATA, true);
adapter->unset_rx_last = true;
napi_schedule(&adapter->napi);
}
static int fjes_poll(struct napi_struct *napi, int budget)
{
struct fjes_adapter *adapter =
container_of(napi, struct fjes_adapter, napi);
struct net_device *netdev = napi->dev;
struct fjes_hw *hw = &adapter->hw;
struct sk_buff *skb;
int work_done = 0;
int cur_epid = 0;
int epidx;
size_t frame_len;
void *frame;
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
adapter->hw.ep_shm_info[epidx].tx.info->v1i.rx_status |=
FJES_RX_POLL_WORK;
}
while (work_done < budget) {
prefetch(&adapter->hw);
frame = fjes_rxframe_get(adapter, &frame_len, &cur_epid);
if (frame) {
skb = napi_alloc_skb(napi, frame_len);
if (!skb) {
adapter->stats64.rx_dropped += 1;
hw->ep_shm_info[cur_epid].net_stats
.rx_dropped += 1;
adapter->stats64.rx_errors += 1;
hw->ep_shm_info[cur_epid].net_stats
.rx_errors += 1;
} else {
memcpy(skb_put(skb, frame_len),
frame, frame_len);
skb->protocol = eth_type_trans(skb, netdev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_receive_skb(skb);
work_done++;
adapter->stats64.rx_packets += 1;
hw->ep_shm_info[cur_epid].net_stats
.rx_packets += 1;
adapter->stats64.rx_bytes += frame_len;
hw->ep_shm_info[cur_epid].net_stats
.rx_bytes += frame_len;
if (is_multicast_ether_addr(
((struct ethhdr *)frame)->h_dest)) {
adapter->stats64.multicast += 1;
hw->ep_shm_info[cur_epid].net_stats
.multicast += 1;
}
}
fjes_rxframe_release(adapter, cur_epid);
adapter->unset_rx_last = true;
} else {
break;
}
}
if (work_done < budget) {
napi_complete(napi);
if (adapter->unset_rx_last) {
adapter->rx_last_jiffies = jiffies;
adapter->unset_rx_last = false;
}
if (((long)jiffies - (long)adapter->rx_last_jiffies) < 3) {
napi_reschedule(napi);
} else {
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
adapter->hw.ep_shm_info[epidx]
.tx.info->v1i.rx_status &=
~FJES_RX_POLL_WORK;
}
fjes_hw_set_irqmask(hw, REG_ICTL_MASK_RX_DATA, false);
}
}
return work_done;
}
/* fjes_probe - Device Initialization Routine */
static int fjes_probe(struct platform_device *plat_dev)
{
struct fjes_adapter *adapter;
struct net_device *netdev;
struct resource *res;
struct fjes_hw *hw;
int err;
err = -ENOMEM;
netdev = alloc_netdev_mq(sizeof(struct fjes_adapter), "es%d",
NET_NAME_UNKNOWN, fjes_netdev_setup,
FJES_MAX_QUEUES);
if (!netdev)
goto err_out;
SET_NETDEV_DEV(netdev, &plat_dev->dev);
dev_set_drvdata(&plat_dev->dev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->plat_dev = plat_dev;
hw = &adapter->hw;
hw->back = adapter;
/* setup the private structure */
err = fjes_sw_init(adapter);
if (err)
goto err_free_netdev;
INIT_WORK(&adapter->force_close_task, fjes_force_close_task);
adapter->force_reset = false;
adapter->open_guard = false;
adapter->txrx_wq = create_workqueue(DRV_NAME "/txrx");
adapter->control_wq = create_workqueue(DRV_NAME "/control");
INIT_WORK(&adapter->tx_stall_task, fjes_tx_stall_task);
INIT_WORK(&adapter->raise_intr_rxdata_task,
fjes_raise_intr_rxdata_task);
INIT_WORK(&adapter->unshare_watch_task, fjes_watch_unshare_task);
adapter->unshare_watch_bitmask = 0;
INIT_DELAYED_WORK(&adapter->interrupt_watch_task, fjes_irq_watch_task);
adapter->interrupt_watch_enable = false;
res = platform_get_resource(plat_dev, IORESOURCE_MEM, 0);
hw->hw_res.start = res->start;
hw->hw_res.size = res->end - res->start + 1;
hw->hw_res.irq = platform_get_irq(plat_dev, 0);
err = fjes_hw_init(&adapter->hw);
if (err)
goto err_free_netdev;
/* setup MAC address (02:00:00:00:00:[epid])*/
netdev->dev_addr[0] = 2;
netdev->dev_addr[1] = 0;
netdev->dev_addr[2] = 0;
netdev->dev_addr[3] = 0;
netdev->dev_addr[4] = 0;
netdev->dev_addr[5] = hw->my_epid; /* EPID */
err = register_netdev(netdev);
if (err)
goto err_hw_exit;
netif_carrier_off(netdev);
return 0;
err_hw_exit:
fjes_hw_exit(&adapter->hw);
err_free_netdev:
free_netdev(netdev);
err_out:
return err;
}
/* fjes_remove - Device Removal Routine */
static int fjes_remove(struct platform_device *plat_dev)
{
struct net_device *netdev = dev_get_drvdata(&plat_dev->dev);
struct fjes_adapter *adapter = netdev_priv(netdev);
struct fjes_hw *hw = &adapter->hw;
cancel_delayed_work_sync(&adapter->interrupt_watch_task);
cancel_work_sync(&adapter->unshare_watch_task);
cancel_work_sync(&adapter->raise_intr_rxdata_task);
cancel_work_sync(&adapter->tx_stall_task);
if (adapter->control_wq)
destroy_workqueue(adapter->control_wq);
if (adapter->txrx_wq)
destroy_workqueue(adapter->txrx_wq);
unregister_netdev(netdev);
fjes_hw_exit(hw);
netif_napi_del(&adapter->napi);
free_netdev(netdev);
return 0;
}
static int fjes_sw_init(struct fjes_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
netif_napi_add(netdev, &adapter->napi, fjes_poll, 64);
return 0;
}
/* fjes_netdev_setup - netdevice initialization routine */
static void fjes_netdev_setup(struct net_device *netdev)
{
ether_setup(netdev);
netdev->watchdog_timeo = FJES_TX_RETRY_INTERVAL;
netdev->netdev_ops = &fjes_netdev_ops;
fjes_set_ethtool_ops(netdev);
netdev->mtu = fjes_support_mtu[0];
netdev->flags |= IFF_BROADCAST;
netdev->features |= NETIF_F_HW_CSUM | NETIF_F_HW_VLAN_CTAG_FILTER;
}
static void fjes_irq_watch_task(struct work_struct *work)
{
struct fjes_adapter *adapter = container_of(to_delayed_work(work),
struct fjes_adapter, interrupt_watch_task);
local_irq_disable();
fjes_intr(adapter->hw.hw_res.irq, adapter);
local_irq_enable();
if (fjes_rxframe_search_exist(adapter, 0) >= 0)
napi_schedule(&adapter->napi);
if (adapter->interrupt_watch_enable) {
if (!delayed_work_pending(&adapter->interrupt_watch_task))
queue_delayed_work(adapter->control_wq,
&adapter->interrupt_watch_task,
FJES_IRQ_WATCH_DELAY);
}
}
static void fjes_watch_unshare_task(struct work_struct *work)
{
struct fjes_adapter *adapter =
container_of(work, struct fjes_adapter, unshare_watch_task);
struct net_device *netdev = adapter->netdev;
struct fjes_hw *hw = &adapter->hw;
int unshare_watch, unshare_reserve;
int max_epid, my_epid, epidx;
int stop_req, stop_req_done;
ulong unshare_watch_bitmask;
int wait_time = 0;
int is_shared;
int ret;
my_epid = hw->my_epid;
max_epid = hw->max_epid;
unshare_watch_bitmask = adapter->unshare_watch_bitmask;
adapter->unshare_watch_bitmask = 0;
while ((unshare_watch_bitmask || hw->txrx_stop_req_bit) &&
(wait_time < 3000)) {
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
is_shared = fjes_hw_epid_is_shared(hw->hw_info.share,
epidx);
stop_req = test_bit(epidx, &hw->txrx_stop_req_bit);
stop_req_done = hw->ep_shm_info[epidx].rx.info->v1i.rx_status &
FJES_RX_STOP_REQ_DONE;
unshare_watch = test_bit(epidx, &unshare_watch_bitmask);
unshare_reserve = test_bit(epidx,
&hw->hw_info.buffer_unshare_reserve_bit);
if ((!stop_req ||
(is_shared && (!is_shared || !stop_req_done))) &&
(is_shared || !unshare_watch || !unshare_reserve))
continue;
mutex_lock(&hw->hw_info.lock);
ret = fjes_hw_unregister_buff_addr(hw, epidx);
switch (ret) {
case 0:
break;
case -ENOMSG:
case -EBUSY:
default:
if (!work_pending(
&adapter->force_close_task)) {
adapter->force_reset = true;
schedule_work(
&adapter->force_close_task);
}
break;
}
mutex_unlock(&hw->hw_info.lock);
fjes_hw_setup_epbuf(&hw->ep_shm_info[epidx].tx,
netdev->dev_addr, netdev->mtu);
clear_bit(epidx, &hw->txrx_stop_req_bit);
clear_bit(epidx, &unshare_watch_bitmask);
clear_bit(epidx,
&hw->hw_info.buffer_unshare_reserve_bit);
}
msleep(100);
wait_time += 100;
}
if (hw->hw_info.buffer_unshare_reserve_bit) {
for (epidx = 0; epidx < hw->max_epid; epidx++) {
if (epidx == hw->my_epid)
continue;
if (test_bit(epidx,
&hw->hw_info.buffer_unshare_reserve_bit)) {
mutex_lock(&hw->hw_info.lock);
ret = fjes_hw_unregister_buff_addr(hw, epidx);
switch (ret) {
case 0:
break;
case -ENOMSG:
case -EBUSY:
default:
if (!work_pending(
&adapter->force_close_task)) {
adapter->force_reset = true;
schedule_work(
&adapter->force_close_task);
}
break;
}
mutex_unlock(&hw->hw_info.lock);
fjes_hw_setup_epbuf(
&hw->ep_shm_info[epidx].tx,
netdev->dev_addr, netdev->mtu);
clear_bit(epidx, &hw->txrx_stop_req_bit);
clear_bit(epidx, &unshare_watch_bitmask);
clear_bit(epidx, &hw->hw_info.buffer_unshare_reserve_bit);
}
if (test_bit(epidx, &unshare_watch_bitmask)) {
hw->ep_shm_info[epidx].tx.info->v1i.rx_status &=
~FJES_RX_STOP_REQ_DONE;
}
}
}
}
/* fjes_init_module - Driver Registration Routine */
static int __init fjes_init_module(void)
{
int result;
pr_info("%s - version %s - %s\n",
fjes_driver_string, fjes_driver_version, fjes_copyright);
result = platform_driver_register(&fjes_driver);
if (result < 0)
return result;
result = acpi_bus_register_driver(&fjes_acpi_driver);
if (result < 0)
goto fail_acpi_driver;
return 0;
fail_acpi_driver:
platform_driver_unregister(&fjes_driver);
return result;
}
module_init(fjes_init_module);
/* fjes_exit_module - Driver Exit Cleanup Routine */
static void __exit fjes_exit_module(void)
{
acpi_bus_unregister_driver(&fjes_acpi_driver);
platform_driver_unregister(&fjes_driver);
}
module_exit(fjes_exit_module);
| gpl-2.0 |
aloksinha2001/Linux3188 | drivers/pci/hotplug/acpiphp_glue.c | 939 | 36318 | /*
* ACPI PCI HotPlug glue functions to ACPI CA subsystem
*
* Copyright (C) 2002,2003 Takayoshi Kochi (t-kochi@bq.jp.nec.com)
* Copyright (C) 2002 Hiroshi Aono (h-aono@ap.jp.nec.com)
* Copyright (C) 2002,2003 NEC Corporation
* Copyright (C) 2003-2005 Matthew Wilcox (matthew.wilcox@hp.com)
* Copyright (C) 2003-2005 Hewlett Packard
* Copyright (C) 2005 Rajesh Shah (rajesh.shah@intel.com)
* Copyright (C) 2005 Intel 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <kristen.c.accardi@intel.com>
*
*/
/*
* Lifetime rules for pci_dev:
* - The one in acpiphp_bridge has its refcount elevated by pci_get_slot()
* when the bridge is scanned and it loses a refcount when the bridge
* is removed.
* - When a P2P bridge is present, we elevate the refcount on the subordinate
* bus. It loses the refcount when the the driver unloads.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/pci-acpi.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include "../pci.h"
#include "acpiphp.h"
static LIST_HEAD(bridge_list);
#define MY_NAME "acpiphp_glue"
static void handle_hotplug_event_bridge (acpi_handle, u32, void *);
static void acpiphp_sanitize_bus(struct pci_bus *bus);
static void acpiphp_set_hpp_values(struct pci_bus *bus);
static void handle_hotplug_event_func(acpi_handle handle, u32 type, void *context);
/* callback routine to check for the existence of a pci dock device */
static acpi_status
is_pci_dock_device(acpi_handle handle, u32 lvl, void *context, void **rv)
{
int *count = (int *)context;
if (is_dock_device(handle)) {
(*count)++;
return AE_CTRL_TERMINATE;
} else {
return AE_OK;
}
}
/*
* the _DCK method can do funny things... and sometimes not
* hah-hah funny.
*
* TBD - figure out a way to only call fixups for
* systems that require them.
*/
static int post_dock_fixups(struct notifier_block *nb, unsigned long val,
void *v)
{
struct acpiphp_func *func = container_of(nb, struct acpiphp_func, nb);
struct pci_bus *bus = func->slot->bridge->pci_bus;
u32 buses;
if (!bus->self)
return NOTIFY_OK;
/* fixup bad _DCK function that rewrites
* secondary bridge on slot
*/
pci_read_config_dword(bus->self,
PCI_PRIMARY_BUS,
&buses);
if (((buses >> 8) & 0xff) != bus->secondary) {
buses = (buses & 0xff000000)
| ((unsigned int)(bus->primary) << 0)
| ((unsigned int)(bus->secondary) << 8)
| ((unsigned int)(bus->subordinate) << 16);
pci_write_config_dword(bus->self, PCI_PRIMARY_BUS, buses);
}
return NOTIFY_OK;
}
static struct acpi_dock_ops acpiphp_dock_ops = {
.handler = handle_hotplug_event_func,
};
/* callback routine to register each ACPI PCI slot object */
static acpi_status
register_slot(acpi_handle handle, u32 lvl, void *context, void **rv)
{
struct acpiphp_bridge *bridge = (struct acpiphp_bridge *)context;
struct acpiphp_slot *slot;
struct acpiphp_func *newfunc;
acpi_handle tmp;
acpi_status status = AE_OK;
unsigned long long adr, sun;
int device, function, retval;
struct pci_bus *pbus = bridge->pci_bus;
struct pci_dev *pdev;
if (!acpi_pci_check_ejectable(pbus, handle) && !is_dock_device(handle))
return AE_OK;
status = acpi_evaluate_integer(handle, "_ADR", NULL, &adr);
if (ACPI_FAILURE(status)) {
warn("can't evaluate _ADR (%#x)\n", status);
return AE_OK;
}
device = (adr >> 16) & 0xffff;
function = adr & 0xffff;
newfunc = kzalloc(sizeof(struct acpiphp_func), GFP_KERNEL);
if (!newfunc)
return AE_NO_MEMORY;
INIT_LIST_HEAD(&newfunc->sibling);
newfunc->handle = handle;
newfunc->function = function;
if (ACPI_SUCCESS(acpi_get_handle(handle, "_EJ0", &tmp)))
newfunc->flags = FUNC_HAS_EJ0;
if (ACPI_SUCCESS(acpi_get_handle(handle, "_STA", &tmp)))
newfunc->flags |= FUNC_HAS_STA;
if (ACPI_SUCCESS(acpi_get_handle(handle, "_PS0", &tmp)))
newfunc->flags |= FUNC_HAS_PS0;
if (ACPI_SUCCESS(acpi_get_handle(handle, "_PS3", &tmp)))
newfunc->flags |= FUNC_HAS_PS3;
if (ACPI_SUCCESS(acpi_get_handle(handle, "_DCK", &tmp)))
newfunc->flags |= FUNC_HAS_DCK;
status = acpi_evaluate_integer(handle, "_SUN", NULL, &sun);
if (ACPI_FAILURE(status)) {
/*
* use the count of the number of slots we've found
* for the number of the slot
*/
sun = bridge->nr_slots+1;
}
/* search for objects that share the same slot */
for (slot = bridge->slots; slot; slot = slot->next)
if (slot->device == device) {
if (slot->sun != sun)
warn("sibling found, but _SUN doesn't match!\n");
break;
}
if (!slot) {
slot = kzalloc(sizeof(struct acpiphp_slot), GFP_KERNEL);
if (!slot) {
kfree(newfunc);
return AE_NO_MEMORY;
}
slot->bridge = bridge;
slot->device = device;
slot->sun = sun;
INIT_LIST_HEAD(&slot->funcs);
mutex_init(&slot->crit_sect);
slot->next = bridge->slots;
bridge->slots = slot;
bridge->nr_slots++;
dbg("found ACPI PCI Hotplug slot %llu at PCI %04x:%02x:%02x\n",
slot->sun, pci_domain_nr(pbus), pbus->number, device);
retval = acpiphp_register_hotplug_slot(slot);
if (retval) {
if (retval == -EBUSY)
warn("Slot %llu already registered by another "
"hotplug driver\n", slot->sun);
else
warn("acpiphp_register_hotplug_slot failed "
"(err code = 0x%x)\n", retval);
goto err_exit;
}
}
newfunc->slot = slot;
list_add_tail(&newfunc->sibling, &slot->funcs);
pdev = pci_get_slot(pbus, PCI_DEVFN(device, function));
if (pdev) {
pdev->current_state = PCI_D0;
slot->flags |= (SLOT_ENABLED | SLOT_POWEREDON);
pci_dev_put(pdev);
}
if (is_dock_device(handle)) {
/* we don't want to call this device's _EJ0
* because we want the dock notify handler
* to call it after it calls _DCK
*/
newfunc->flags &= ~FUNC_HAS_EJ0;
if (register_hotplug_dock_device(handle,
&acpiphp_dock_ops, newfunc))
dbg("failed to register dock device\n");
/* we need to be notified when dock events happen
* outside of the hotplug operation, since we may
* need to do fixups before we can hotplug.
*/
newfunc->nb.notifier_call = post_dock_fixups;
if (register_dock_notifier(&newfunc->nb))
dbg("failed to register a dock notifier");
}
/* install notify handler */
if (!(newfunc->flags & FUNC_HAS_DCK)) {
status = acpi_install_notify_handler(handle,
ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_func,
newfunc);
if (ACPI_FAILURE(status))
err("failed to register interrupt notify handler\n");
} else
status = AE_OK;
return status;
err_exit:
bridge->nr_slots--;
bridge->slots = slot->next;
kfree(slot);
kfree(newfunc);
return AE_OK;
}
/* see if it's worth looking at this bridge */
static int detect_ejectable_slots(acpi_handle handle)
{
int found = acpi_pci_detect_ejectable(handle);
if (!found) {
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, (u32)1,
is_pci_dock_device, NULL, (void *)&found, NULL);
}
return found;
}
/* initialize miscellaneous stuff for both root and PCI-to-PCI bridge */
static void init_bridge_misc(struct acpiphp_bridge *bridge)
{
acpi_status status;
/* must be added to the list prior to calling register_slot */
list_add(&bridge->list, &bridge_list);
/* register all slot objects under this bridge */
status = acpi_walk_namespace(ACPI_TYPE_DEVICE, bridge->handle, (u32)1,
register_slot, NULL, bridge, NULL);
if (ACPI_FAILURE(status)) {
list_del(&bridge->list);
return;
}
/* install notify handler */
if (bridge->type != BRIDGE_TYPE_HOST) {
if ((bridge->flags & BRIDGE_HAS_EJ0) && bridge->func) {
status = acpi_remove_notify_handler(bridge->func->handle,
ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_func);
if (ACPI_FAILURE(status))
err("failed to remove notify handler\n");
}
status = acpi_install_notify_handler(bridge->handle,
ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_bridge,
bridge);
if (ACPI_FAILURE(status)) {
err("failed to register interrupt notify handler\n");
}
}
}
/* find acpiphp_func from acpiphp_bridge */
static struct acpiphp_func *acpiphp_bridge_handle_to_function(acpi_handle handle)
{
struct acpiphp_bridge *bridge;
struct acpiphp_slot *slot;
struct acpiphp_func *func;
list_for_each_entry(bridge, &bridge_list, list) {
for (slot = bridge->slots; slot; slot = slot->next) {
list_for_each_entry(func, &slot->funcs, sibling) {
if (func->handle == handle)
return func;
}
}
}
return NULL;
}
static inline void config_p2p_bridge_flags(struct acpiphp_bridge *bridge)
{
acpi_handle dummy_handle;
if (ACPI_SUCCESS(acpi_get_handle(bridge->handle,
"_STA", &dummy_handle)))
bridge->flags |= BRIDGE_HAS_STA;
if (ACPI_SUCCESS(acpi_get_handle(bridge->handle,
"_EJ0", &dummy_handle)))
bridge->flags |= BRIDGE_HAS_EJ0;
if (ACPI_SUCCESS(acpi_get_handle(bridge->handle,
"_PS0", &dummy_handle)))
bridge->flags |= BRIDGE_HAS_PS0;
if (ACPI_SUCCESS(acpi_get_handle(bridge->handle,
"_PS3", &dummy_handle)))
bridge->flags |= BRIDGE_HAS_PS3;
/* is this ejectable p2p bridge? */
if (bridge->flags & BRIDGE_HAS_EJ0) {
struct acpiphp_func *func;
dbg("found ejectable p2p bridge\n");
/* make link between PCI bridge and PCI function */
func = acpiphp_bridge_handle_to_function(bridge->handle);
if (!func)
return;
bridge->func = func;
func->bridge = bridge;
}
}
/* allocate and initialize host bridge data structure */
static void add_host_bridge(acpi_handle *handle)
{
struct acpiphp_bridge *bridge;
struct acpi_pci_root *root = acpi_pci_find_root(handle);
bridge = kzalloc(sizeof(struct acpiphp_bridge), GFP_KERNEL);
if (bridge == NULL)
return;
bridge->type = BRIDGE_TYPE_HOST;
bridge->handle = handle;
bridge->pci_bus = root->bus;
spin_lock_init(&bridge->res_lock);
init_bridge_misc(bridge);
}
/* allocate and initialize PCI-to-PCI bridge data structure */
static void add_p2p_bridge(acpi_handle *handle)
{
struct acpiphp_bridge *bridge;
bridge = kzalloc(sizeof(struct acpiphp_bridge), GFP_KERNEL);
if (bridge == NULL) {
err("out of memory\n");
return;
}
bridge->type = BRIDGE_TYPE_P2P;
bridge->handle = handle;
config_p2p_bridge_flags(bridge);
bridge->pci_dev = acpi_get_pci_dev(handle);
bridge->pci_bus = bridge->pci_dev->subordinate;
if (!bridge->pci_bus) {
err("This is not a PCI-to-PCI bridge!\n");
goto err;
}
/*
* Grab a ref to the subordinate PCI bus in case the bus is
* removed via PCI core logical hotplug. The ref pins the bus
* (which we access during module unload).
*/
get_device(&bridge->pci_bus->dev);
spin_lock_init(&bridge->res_lock);
init_bridge_misc(bridge);
return;
err:
pci_dev_put(bridge->pci_dev);
kfree(bridge);
return;
}
/* callback routine to find P2P bridges */
static acpi_status
find_p2p_bridge(acpi_handle handle, u32 lvl, void *context, void **rv)
{
acpi_status status;
struct pci_dev *dev;
dev = acpi_get_pci_dev(handle);
if (!dev || !dev->subordinate)
goto out;
/* check if this bridge has ejectable slots */
if ((detect_ejectable_slots(handle) > 0)) {
dbg("found PCI-to-PCI bridge at PCI %s\n", pci_name(dev));
add_p2p_bridge(handle);
}
/* search P2P bridges under this p2p bridge */
status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, (u32)1,
find_p2p_bridge, NULL, NULL, NULL);
if (ACPI_FAILURE(status))
warn("find_p2p_bridge failed (error code = 0x%x)\n", status);
out:
pci_dev_put(dev);
return AE_OK;
}
/* find hot-pluggable slots, and then find P2P bridge */
static int add_bridge(acpi_handle handle)
{
acpi_status status;
unsigned long long tmp;
acpi_handle dummy_handle;
/* if the bridge doesn't have _STA, we assume it is always there */
status = acpi_get_handle(handle, "_STA", &dummy_handle);
if (ACPI_SUCCESS(status)) {
status = acpi_evaluate_integer(handle, "_STA", NULL, &tmp);
if (ACPI_FAILURE(status)) {
dbg("%s: _STA evaluation failure\n", __func__);
return 0;
}
if ((tmp & ACPI_STA_FUNCTIONING) == 0)
/* don't register this object */
return 0;
}
/* check if this bridge has ejectable slots */
if (detect_ejectable_slots(handle) > 0) {
dbg("found PCI host-bus bridge with hot-pluggable slots\n");
add_host_bridge(handle);
}
/* search P2P bridges under this host bridge */
status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, (u32)1,
find_p2p_bridge, NULL, NULL, NULL);
if (ACPI_FAILURE(status))
warn("find_p2p_bridge failed (error code = 0x%x)\n", status);
return 0;
}
static struct acpiphp_bridge *acpiphp_handle_to_bridge(acpi_handle handle)
{
struct acpiphp_bridge *bridge;
list_for_each_entry(bridge, &bridge_list, list)
if (bridge->handle == handle)
return bridge;
return NULL;
}
static void cleanup_bridge(struct acpiphp_bridge *bridge)
{
struct acpiphp_slot *slot, *next;
struct acpiphp_func *func, *tmp;
acpi_status status;
acpi_handle handle = bridge->handle;
status = acpi_remove_notify_handler(handle, ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_bridge);
if (ACPI_FAILURE(status))
err("failed to remove notify handler\n");
if ((bridge->type != BRIDGE_TYPE_HOST) &&
((bridge->flags & BRIDGE_HAS_EJ0) && bridge->func)) {
status = acpi_install_notify_handler(bridge->func->handle,
ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_func,
bridge->func);
if (ACPI_FAILURE(status))
err("failed to install interrupt notify handler\n");
}
slot = bridge->slots;
while (slot) {
next = slot->next;
list_for_each_entry_safe(func, tmp, &slot->funcs, sibling) {
if (is_dock_device(func->handle)) {
unregister_hotplug_dock_device(func->handle);
unregister_dock_notifier(&func->nb);
}
if (!(func->flags & FUNC_HAS_DCK)) {
status = acpi_remove_notify_handler(func->handle,
ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_func);
if (ACPI_FAILURE(status))
err("failed to remove notify handler\n");
}
list_del(&func->sibling);
kfree(func);
}
acpiphp_unregister_hotplug_slot(slot);
list_del(&slot->funcs);
kfree(slot);
slot = next;
}
/*
* Only P2P bridges have a pci_dev
*/
if (bridge->pci_dev)
put_device(&bridge->pci_bus->dev);
pci_dev_put(bridge->pci_dev);
list_del(&bridge->list);
kfree(bridge);
}
static acpi_status
cleanup_p2p_bridge(acpi_handle handle, u32 lvl, void *context, void **rv)
{
struct acpiphp_bridge *bridge;
/* cleanup p2p bridges under this P2P bridge
in a depth-first manner */
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, (u32)1,
cleanup_p2p_bridge, NULL, NULL, NULL);
bridge = acpiphp_handle_to_bridge(handle);
if (bridge)
cleanup_bridge(bridge);
return AE_OK;
}
static void remove_bridge(acpi_handle handle)
{
struct acpiphp_bridge *bridge;
/* cleanup p2p bridges under this host bridge
in a depth-first manner */
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle,
(u32)1, cleanup_p2p_bridge, NULL, NULL, NULL);
/*
* On root bridges with hotplug slots directly underneath (ie,
* no p2p bridge between), we call cleanup_bridge().
*
* The else clause cleans up root bridges that either had no
* hotplug slots at all, or had a p2p bridge underneath.
*/
bridge = acpiphp_handle_to_bridge(handle);
if (bridge)
cleanup_bridge(bridge);
else
acpi_remove_notify_handler(handle, ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_bridge);
}
static int power_on_slot(struct acpiphp_slot *slot)
{
acpi_status status;
struct acpiphp_func *func;
int retval = 0;
/* if already enabled, just skip */
if (slot->flags & SLOT_POWEREDON)
goto err_exit;
list_for_each_entry(func, &slot->funcs, sibling) {
if (func->flags & FUNC_HAS_PS0) {
dbg("%s: executing _PS0\n", __func__);
status = acpi_evaluate_object(func->handle, "_PS0", NULL, NULL);
if (ACPI_FAILURE(status)) {
warn("%s: _PS0 failed\n", __func__);
retval = -1;
goto err_exit;
} else
break;
}
}
/* TBD: evaluate _STA to check if the slot is enabled */
slot->flags |= SLOT_POWEREDON;
err_exit:
return retval;
}
static int power_off_slot(struct acpiphp_slot *slot)
{
acpi_status status;
struct acpiphp_func *func;
int retval = 0;
/* if already disabled, just skip */
if ((slot->flags & SLOT_POWEREDON) == 0)
goto err_exit;
list_for_each_entry(func, &slot->funcs, sibling) {
if (func->flags & FUNC_HAS_PS3) {
status = acpi_evaluate_object(func->handle, "_PS3", NULL, NULL);
if (ACPI_FAILURE(status)) {
warn("%s: _PS3 failed\n", __func__);
retval = -1;
goto err_exit;
} else
break;
}
}
/* TBD: evaluate _STA to check if the slot is disabled */
slot->flags &= (~SLOT_POWEREDON);
err_exit:
return retval;
}
/**
* acpiphp_max_busnr - return the highest reserved bus number under the given bus.
* @bus: bus to start search with
*/
static unsigned char acpiphp_max_busnr(struct pci_bus *bus)
{
struct list_head *tmp;
unsigned char max, n;
/*
* pci_bus_max_busnr will return the highest
* reserved busnr for all these children.
* that is equivalent to the bus->subordinate
* value. We don't want to use the parent's
* bus->subordinate value because it could have
* padding in it.
*/
max = bus->secondary;
list_for_each(tmp, &bus->children) {
n = pci_bus_max_busnr(pci_bus_b(tmp));
if (n > max)
max = n;
}
return max;
}
/**
* acpiphp_bus_add - add a new bus to acpi subsystem
* @func: acpiphp_func of the bridge
*/
static int acpiphp_bus_add(struct acpiphp_func *func)
{
acpi_handle phandle;
struct acpi_device *device, *pdevice;
int ret_val;
acpi_get_parent(func->handle, &phandle);
if (acpi_bus_get_device(phandle, &pdevice)) {
dbg("no parent device, assuming NULL\n");
pdevice = NULL;
}
if (!acpi_bus_get_device(func->handle, &device)) {
dbg("bus exists... trim\n");
/* this shouldn't be in here, so remove
* the bus then re-add it...
*/
ret_val = acpi_bus_trim(device, 1);
dbg("acpi_bus_trim return %x\n", ret_val);
}
ret_val = acpi_bus_add(&device, pdevice, func->handle,
ACPI_BUS_TYPE_DEVICE);
if (ret_val) {
dbg("error adding bus, %x\n",
-ret_val);
goto acpiphp_bus_add_out;
}
ret_val = acpi_bus_start(device);
acpiphp_bus_add_out:
return ret_val;
}
/**
* acpiphp_bus_trim - trim a bus from acpi subsystem
* @handle: handle to acpi namespace
*/
static int acpiphp_bus_trim(acpi_handle handle)
{
struct acpi_device *device;
int retval;
retval = acpi_bus_get_device(handle, &device);
if (retval) {
dbg("acpi_device not found\n");
return retval;
}
retval = acpi_bus_trim(device, 1);
if (retval)
err("cannot remove from acpi list\n");
return retval;
}
static void acpiphp_set_acpi_region(struct acpiphp_slot *slot)
{
struct acpiphp_func *func;
union acpi_object params[2];
struct acpi_object_list arg_list;
list_for_each_entry(func, &slot->funcs, sibling) {
arg_list.count = 2;
arg_list.pointer = params;
params[0].type = ACPI_TYPE_INTEGER;
params[0].integer.value = ACPI_ADR_SPACE_PCI_CONFIG;
params[1].type = ACPI_TYPE_INTEGER;
params[1].integer.value = 1;
/* _REG is optional, we don't care about if there is failure */
acpi_evaluate_object(func->handle, "_REG", &arg_list, NULL);
}
}
/**
* enable_device - enable, configure a slot
* @slot: slot to be enabled
*
* This function should be called per *physical slot*,
* not per each slot object in ACPI namespace.
*/
static int __ref enable_device(struct acpiphp_slot *slot)
{
struct pci_dev *dev;
struct pci_bus *bus = slot->bridge->pci_bus;
struct acpiphp_func *func;
int retval = 0;
int num, max, pass;
acpi_status status;
if (slot->flags & SLOT_ENABLED)
goto err_exit;
/* sanity check: dev should be NULL when hot-plugged in */
dev = pci_get_slot(bus, PCI_DEVFN(slot->device, 0));
if (dev) {
/* This case shouldn't happen */
err("pci_dev structure already exists.\n");
pci_dev_put(dev);
retval = -1;
goto err_exit;
}
num = pci_scan_slot(bus, PCI_DEVFN(slot->device, 0));
if (num == 0) {
err("No new device found\n");
retval = -1;
goto err_exit;
}
max = acpiphp_max_busnr(bus);
for (pass = 0; pass < 2; pass++) {
list_for_each_entry(dev, &bus->devices, bus_list) {
if (PCI_SLOT(dev->devfn) != slot->device)
continue;
if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE ||
dev->hdr_type == PCI_HEADER_TYPE_CARDBUS) {
max = pci_scan_bridge(bus, dev, max, pass);
if (pass && dev->subordinate)
pci_bus_size_bridges(dev->subordinate);
}
}
}
list_for_each_entry(func, &slot->funcs, sibling)
acpiphp_bus_add(func);
pci_bus_assign_resources(bus);
acpiphp_sanitize_bus(bus);
acpiphp_set_hpp_values(bus);
acpiphp_set_acpi_region(slot);
pci_enable_bridges(bus);
list_for_each_entry(dev, &bus->devices, bus_list) {
/* Assume that newly added devices are powered on already. */
if (!dev->is_added)
dev->current_state = PCI_D0;
}
pci_bus_add_devices(bus);
list_for_each_entry(func, &slot->funcs, sibling) {
dev = pci_get_slot(bus, PCI_DEVFN(slot->device,
func->function));
if (!dev)
continue;
if (dev->hdr_type != PCI_HEADER_TYPE_BRIDGE &&
dev->hdr_type != PCI_HEADER_TYPE_CARDBUS) {
pci_dev_put(dev);
continue;
}
status = find_p2p_bridge(func->handle, (u32)1, bus, NULL);
if (ACPI_FAILURE(status))
warn("find_p2p_bridge failed (error code = 0x%x)\n",
status);
pci_dev_put(dev);
}
slot->flags |= SLOT_ENABLED;
err_exit:
return retval;
}
static void disable_bridges(struct pci_bus *bus)
{
struct pci_dev *dev;
list_for_each_entry(dev, &bus->devices, bus_list) {
if (dev->subordinate) {
disable_bridges(dev->subordinate);
pci_disable_device(dev);
}
}
}
/**
* disable_device - disable a slot
* @slot: ACPI PHP slot
*/
static int disable_device(struct acpiphp_slot *slot)
{
struct acpiphp_func *func;
struct pci_dev *pdev;
/* is this slot already disabled? */
if (!(slot->flags & SLOT_ENABLED))
goto err_exit;
list_for_each_entry(func, &slot->funcs, sibling) {
if (func->bridge) {
/* cleanup p2p bridges under this P2P bridge */
cleanup_p2p_bridge(func->bridge->handle,
(u32)1, NULL, NULL);
func->bridge = NULL;
}
pdev = pci_get_slot(slot->bridge->pci_bus,
PCI_DEVFN(slot->device, func->function));
if (pdev) {
pci_stop_bus_device(pdev);
if (pdev->subordinate) {
disable_bridges(pdev->subordinate);
pci_disable_device(pdev);
}
pci_remove_bus_device(pdev);
pci_dev_put(pdev);
}
}
list_for_each_entry(func, &slot->funcs, sibling) {
acpiphp_bus_trim(func->handle);
}
slot->flags &= (~SLOT_ENABLED);
err_exit:
return 0;
}
/**
* get_slot_status - get ACPI slot status
* @slot: ACPI PHP slot
*
* If a slot has _STA for each function and if any one of them
* returned non-zero status, return it.
*
* If a slot doesn't have _STA and if any one of its functions'
* configuration space is configured, return 0x0f as a _STA.
*
* Otherwise return 0.
*/
static unsigned int get_slot_status(struct acpiphp_slot *slot)
{
acpi_status status;
unsigned long long sta = 0;
u32 dvid;
struct acpiphp_func *func;
list_for_each_entry(func, &slot->funcs, sibling) {
if (func->flags & FUNC_HAS_STA) {
status = acpi_evaluate_integer(func->handle, "_STA", NULL, &sta);
if (ACPI_SUCCESS(status) && sta)
break;
} else {
pci_bus_read_config_dword(slot->bridge->pci_bus,
PCI_DEVFN(slot->device,
func->function),
PCI_VENDOR_ID, &dvid);
if (dvid != 0xffffffff) {
sta = ACPI_STA_ALL;
break;
}
}
}
return (unsigned int)sta;
}
/**
* acpiphp_eject_slot - physically eject the slot
* @slot: ACPI PHP slot
*/
int acpiphp_eject_slot(struct acpiphp_slot *slot)
{
acpi_status status;
struct acpiphp_func *func;
struct acpi_object_list arg_list;
union acpi_object arg;
list_for_each_entry(func, &slot->funcs, sibling) {
/* We don't want to call _EJ0 on non-existing functions. */
if ((func->flags & FUNC_HAS_EJ0)) {
/* _EJ0 method take one argument */
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = 1;
status = acpi_evaluate_object(func->handle, "_EJ0", &arg_list, NULL);
if (ACPI_FAILURE(status)) {
warn("%s: _EJ0 failed\n", __func__);
return -1;
} else
break;
}
}
return 0;
}
/**
* acpiphp_check_bridge - re-enumerate devices
* @bridge: where to begin re-enumeration
*
* Iterate over all slots under this bridge and make sure that if a
* card is present they are enabled, and if not they are disabled.
*/
static int acpiphp_check_bridge(struct acpiphp_bridge *bridge)
{
struct acpiphp_slot *slot;
int retval = 0;
int enabled, disabled;
enabled = disabled = 0;
for (slot = bridge->slots; slot; slot = slot->next) {
unsigned int status = get_slot_status(slot);
if (slot->flags & SLOT_ENABLED) {
if (status == ACPI_STA_ALL)
continue;
retval = acpiphp_disable_slot(slot);
if (retval) {
err("Error occurred in disabling\n");
goto err_exit;
} else {
acpiphp_eject_slot(slot);
}
disabled++;
} else {
if (status != ACPI_STA_ALL)
continue;
retval = acpiphp_enable_slot(slot);
if (retval) {
err("Error occurred in enabling\n");
goto err_exit;
}
enabled++;
}
}
dbg("%s: %d enabled, %d disabled\n", __func__, enabled, disabled);
err_exit:
return retval;
}
static void acpiphp_set_hpp_values(struct pci_bus *bus)
{
struct pci_dev *dev;
list_for_each_entry(dev, &bus->devices, bus_list)
pci_configure_slot(dev);
}
/*
* Remove devices for which we could not assign resources, call
* arch specific code to fix-up the bus
*/
static void acpiphp_sanitize_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
int i;
unsigned long type_mask = IORESOURCE_IO | IORESOURCE_MEM;
list_for_each_entry(dev, &bus->devices, bus_list) {
for (i=0; i<PCI_BRIDGE_RESOURCES; i++) {
struct resource *res = &dev->resource[i];
if ((res->flags & type_mask) && !res->start &&
res->end) {
/* Could not assign a required resources
* for this device, remove it */
pci_remove_bus_device(dev);
break;
}
}
}
}
/* Program resources in newly inserted bridge */
static int acpiphp_configure_bridge (acpi_handle handle)
{
struct pci_bus *bus;
if (acpi_is_root_bridge(handle)) {
struct acpi_pci_root *root = acpi_pci_find_root(handle);
bus = root->bus;
} else {
struct pci_dev *pdev = acpi_get_pci_dev(handle);
bus = pdev->subordinate;
pci_dev_put(pdev);
}
pci_bus_size_bridges(bus);
pci_bus_assign_resources(bus);
acpiphp_sanitize_bus(bus);
acpiphp_set_hpp_values(bus);
pci_enable_bridges(bus);
return 0;
}
static void handle_bridge_insertion(acpi_handle handle, u32 type)
{
struct acpi_device *device, *pdevice;
acpi_handle phandle;
if ((type != ACPI_NOTIFY_BUS_CHECK) &&
(type != ACPI_NOTIFY_DEVICE_CHECK)) {
err("unexpected notification type %d\n", type);
return;
}
acpi_get_parent(handle, &phandle);
if (acpi_bus_get_device(phandle, &pdevice)) {
dbg("no parent device, assuming NULL\n");
pdevice = NULL;
}
if (acpi_bus_add(&device, pdevice, handle, ACPI_BUS_TYPE_DEVICE)) {
err("cannot add bridge to acpi list\n");
return;
}
if (!acpiphp_configure_bridge(handle) &&
!acpi_bus_start(device))
add_bridge(handle);
else
err("cannot configure and start bridge\n");
}
/*
* ACPI event handlers
*/
static acpi_status
count_sub_bridges(acpi_handle handle, u32 lvl, void *context, void **rv)
{
int *count = (int *)context;
struct acpiphp_bridge *bridge;
bridge = acpiphp_handle_to_bridge(handle);
if (bridge)
(*count)++;
return AE_OK ;
}
static acpi_status
check_sub_bridges(acpi_handle handle, u32 lvl, void *context, void **rv)
{
struct acpiphp_bridge *bridge;
char objname[64];
struct acpi_buffer buffer = { .length = sizeof(objname),
.pointer = objname };
bridge = acpiphp_handle_to_bridge(handle);
if (bridge) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer);
dbg("%s: re-enumerating slots under %s\n",
__func__, objname);
acpiphp_check_bridge(bridge);
}
return AE_OK ;
}
/**
* handle_hotplug_event_bridge - handle ACPI event on bridges
* @handle: Notify()'ed acpi_handle
* @type: Notify code
* @context: pointer to acpiphp_bridge structure
*
* Handles ACPI event notification on {host,p2p} bridges.
*/
static void handle_hotplug_event_bridge(acpi_handle handle, u32 type, void *context)
{
struct acpiphp_bridge *bridge;
char objname[64];
struct acpi_buffer buffer = { .length = sizeof(objname),
.pointer = objname };
struct acpi_device *device;
int num_sub_bridges = 0;
if (acpi_bus_get_device(handle, &device)) {
/* This bridge must have just been physically inserted */
handle_bridge_insertion(handle, type);
return;
}
bridge = acpiphp_handle_to_bridge(handle);
if (type == ACPI_NOTIFY_BUS_CHECK) {
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, ACPI_UINT32_MAX,
count_sub_bridges, NULL, &num_sub_bridges, NULL);
}
if (!bridge && !num_sub_bridges) {
err("cannot get bridge info\n");
return;
}
acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer);
switch (type) {
case ACPI_NOTIFY_BUS_CHECK:
/* bus re-enumerate */
dbg("%s: Bus check notify on %s\n", __func__, objname);
if (bridge) {
dbg("%s: re-enumerating slots under %s\n",
__func__, objname);
acpiphp_check_bridge(bridge);
}
if (num_sub_bridges)
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle,
ACPI_UINT32_MAX, check_sub_bridges, NULL, NULL, NULL);
break;
case ACPI_NOTIFY_DEVICE_CHECK:
/* device check */
dbg("%s: Device check notify on %s\n", __func__, objname);
acpiphp_check_bridge(bridge);
break;
case ACPI_NOTIFY_DEVICE_WAKE:
/* wake event */
dbg("%s: Device wake notify on %s\n", __func__, objname);
break;
case ACPI_NOTIFY_EJECT_REQUEST:
/* request device eject */
dbg("%s: Device eject notify on %s\n", __func__, objname);
if ((bridge->type != BRIDGE_TYPE_HOST) &&
(bridge->flags & BRIDGE_HAS_EJ0)) {
struct acpiphp_slot *slot;
slot = bridge->func->slot;
if (!acpiphp_disable_slot(slot))
acpiphp_eject_slot(slot);
}
break;
case ACPI_NOTIFY_FREQUENCY_MISMATCH:
printk(KERN_ERR "Device %s cannot be configured due"
" to a frequency mismatch\n", objname);
break;
case ACPI_NOTIFY_BUS_MODE_MISMATCH:
printk(KERN_ERR "Device %s cannot be configured due"
" to a bus mode mismatch\n", objname);
break;
case ACPI_NOTIFY_POWER_FAULT:
printk(KERN_ERR "Device %s has suffered a power fault\n",
objname);
break;
default:
warn("notify_handler: unknown event type 0x%x for %s\n", type, objname);
break;
}
}
/**
* handle_hotplug_event_func - handle ACPI event on functions (i.e. slots)
* @handle: Notify()'ed acpi_handle
* @type: Notify code
* @context: pointer to acpiphp_func structure
*
* Handles ACPI event notification on slots.
*/
static void handle_hotplug_event_func(acpi_handle handle, u32 type, void *context)
{
struct acpiphp_func *func;
char objname[64];
struct acpi_buffer buffer = { .length = sizeof(objname),
.pointer = objname };
acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer);
func = (struct acpiphp_func *)context;
switch (type) {
case ACPI_NOTIFY_BUS_CHECK:
/* bus re-enumerate */
dbg("%s: Bus check notify on %s\n", __func__, objname);
acpiphp_enable_slot(func->slot);
break;
case ACPI_NOTIFY_DEVICE_CHECK:
/* device check : re-enumerate from parent bus */
dbg("%s: Device check notify on %s\n", __func__, objname);
acpiphp_check_bridge(func->slot->bridge);
break;
case ACPI_NOTIFY_DEVICE_WAKE:
/* wake event */
dbg("%s: Device wake notify on %s\n", __func__, objname);
break;
case ACPI_NOTIFY_EJECT_REQUEST:
/* request device eject */
dbg("%s: Device eject notify on %s\n", __func__, objname);
if (!(acpiphp_disable_slot(func->slot)))
acpiphp_eject_slot(func->slot);
break;
default:
warn("notify_handler: unknown event type 0x%x for %s\n", type, objname);
break;
}
}
static acpi_status
find_root_bridges(acpi_handle handle, u32 lvl, void *context, void **rv)
{
int *count = (int *)context;
if (acpi_is_root_bridge(handle)) {
acpi_install_notify_handler(handle, ACPI_SYSTEM_NOTIFY,
handle_hotplug_event_bridge, NULL);
(*count)++;
}
return AE_OK ;
}
static struct acpi_pci_driver acpi_pci_hp_driver = {
.add = add_bridge,
.remove = remove_bridge,
};
/**
* acpiphp_glue_init - initializes all PCI hotplug - ACPI glue data structures
*/
int __init acpiphp_glue_init(void)
{
int num = 0;
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_root_bridges, NULL, &num, NULL);
if (num <= 0)
return -1;
else
acpi_pci_register_driver(&acpi_pci_hp_driver);
return 0;
}
/**
* acpiphp_glue_exit - terminates all PCI hotplug - ACPI glue data structures
*
* This function frees all data allocated in acpiphp_glue_init().
*/
void acpiphp_glue_exit(void)
{
acpi_pci_unregister_driver(&acpi_pci_hp_driver);
}
/**
* acpiphp_get_num_slots - count number of slots in a system
*/
int __init acpiphp_get_num_slots(void)
{
struct acpiphp_bridge *bridge;
int num_slots = 0;
list_for_each_entry(bridge, &bridge_list, list) {
dbg("Bus %04x:%02x has %d slot%s\n",
pci_domain_nr(bridge->pci_bus),
bridge->pci_bus->number, bridge->nr_slots,
bridge->nr_slots == 1 ? "" : "s");
num_slots += bridge->nr_slots;
}
dbg("Total %d slots\n", num_slots);
return num_slots;
}
#if 0
/**
* acpiphp_for_each_slot - call function for each slot
* @fn: callback function
* @data: context to be passed to callback function
*/
static int acpiphp_for_each_slot(acpiphp_callback fn, void *data)
{
struct list_head *node;
struct acpiphp_bridge *bridge;
struct acpiphp_slot *slot;
int retval = 0;
list_for_each (node, &bridge_list) {
bridge = (struct acpiphp_bridge *)node;
for (slot = bridge->slots; slot; slot = slot->next) {
retval = fn(slot, data);
if (!retval)
goto err_exit;
}
}
err_exit:
return retval;
}
#endif
/**
* acpiphp_enable_slot - power on slot
* @slot: ACPI PHP slot
*/
int acpiphp_enable_slot(struct acpiphp_slot *slot)
{
int retval;
mutex_lock(&slot->crit_sect);
/* wake up all functions */
retval = power_on_slot(slot);
if (retval)
goto err_exit;
if (get_slot_status(slot) == ACPI_STA_ALL) {
/* configure all functions */
retval = enable_device(slot);
if (retval)
power_off_slot(slot);
} else {
dbg("%s: Slot status is not ACPI_STA_ALL\n", __func__);
power_off_slot(slot);
}
err_exit:
mutex_unlock(&slot->crit_sect);
return retval;
}
/**
* acpiphp_disable_slot - power off slot
* @slot: ACPI PHP slot
*/
int acpiphp_disable_slot(struct acpiphp_slot *slot)
{
int retval = 0;
mutex_lock(&slot->crit_sect);
/* unconfigure all functions */
retval = disable_device(slot);
if (retval)
goto err_exit;
/* power off all functions */
retval = power_off_slot(slot);
if (retval)
goto err_exit;
err_exit:
mutex_unlock(&slot->crit_sect);
return retval;
}
/*
* slot enabled: 1
* slot disabled: 0
*/
u8 acpiphp_get_power_status(struct acpiphp_slot *slot)
{
return (slot->flags & SLOT_POWEREDON);
}
/*
* latch open: 1
* latch closed: 0
*/
u8 acpiphp_get_latch_status(struct acpiphp_slot *slot)
{
unsigned int sta;
sta = get_slot_status(slot);
return (sta & ACPI_STA_SHOW_IN_UI) ? 0 : 1;
}
/*
* adapter presence : 1
* absence : 0
*/
u8 acpiphp_get_adapter_status(struct acpiphp_slot *slot)
{
unsigned int sta;
sta = get_slot_status(slot);
return (sta == 0) ? 0 : 1;
}
| gpl-2.0 |
jamal-ahmad/Logging-Kernel | arch/sparc/kernel/of_device_common.c | 1963 | 3978 | #include <linux/string.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/export.h>
#include <linux/mod_devicetable.h>
#include <linux/errno.h>
#include <linux/irq.h>
#include <linux/of_platform.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include "of_device_common.h"
unsigned int irq_of_parse_and_map(struct device_node *node, int index)
{
struct platform_device *op = of_find_device_by_node(node);
if (!op || index >= op->archdata.num_irqs)
return 0;
return op->archdata.irqs[index];
}
EXPORT_SYMBOL(irq_of_parse_and_map);
int of_address_to_resource(struct device_node *node, int index,
struct resource *r)
{
struct platform_device *op = of_find_device_by_node(node);
if (!op || index >= op->num_resources)
return -EINVAL;
memcpy(r, &op->archdata.resource[index], sizeof(*r));
return 0;
}
EXPORT_SYMBOL_GPL(of_address_to_resource);
void __iomem *of_iomap(struct device_node *node, int index)
{
struct platform_device *op = of_find_device_by_node(node);
struct resource *r;
if (!op || index >= op->num_resources)
return NULL;
r = &op->archdata.resource[index];
return of_ioremap(r, 0, resource_size(r), (char *) r->name);
}
EXPORT_SYMBOL(of_iomap);
/* Take the archdata values for IOMMU, STC, and HOSTDATA found in
* BUS and propagate to all child platform_device objects.
*/
void of_propagate_archdata(struct platform_device *bus)
{
struct dev_archdata *bus_sd = &bus->dev.archdata;
struct device_node *bus_dp = bus->dev.of_node;
struct device_node *dp;
for (dp = bus_dp->child; dp; dp = dp->sibling) {
struct platform_device *op = of_find_device_by_node(dp);
op->dev.archdata.iommu = bus_sd->iommu;
op->dev.archdata.stc = bus_sd->stc;
op->dev.archdata.host_controller = bus_sd->host_controller;
op->dev.archdata.numa_node = bus_sd->numa_node;
if (dp->child)
of_propagate_archdata(op);
}
}
static void get_cells(struct device_node *dp, int *addrc, int *sizec)
{
if (addrc)
*addrc = of_n_addr_cells(dp);
if (sizec)
*sizec = of_n_size_cells(dp);
}
/*
* Default translator (generic bus)
*/
void of_bus_default_count_cells(struct device_node *dev, int *addrc, int *sizec)
{
get_cells(dev, addrc, sizec);
}
/* Make sure the least significant 64-bits are in-range. Even
* for 3 or 4 cell values it is a good enough approximation.
*/
int of_out_of_range(const u32 *addr, const u32 *base,
const u32 *size, int na, int ns)
{
u64 a = of_read_addr(addr, na);
u64 b = of_read_addr(base, na);
if (a < b)
return 1;
b += of_read_addr(size, ns);
if (a >= b)
return 1;
return 0;
}
int of_bus_default_map(u32 *addr, const u32 *range, int na, int ns, int pna)
{
u32 result[OF_MAX_ADDR_CELLS];
int i;
if (ns > 2) {
printk("of_device: Cannot handle size cells (%d) > 2.", ns);
return -EINVAL;
}
if (of_out_of_range(addr, range, range + na + pna, na, ns))
return -EINVAL;
/* Start with the parent range base. */
memcpy(result, range + na, pna * 4);
/* Add in the child address offset. */
for (i = 0; i < na; i++)
result[pna - 1 - i] +=
(addr[na - 1 - i] -
range[na - 1 - i]);
memcpy(addr, result, pna * 4);
return 0;
}
unsigned long of_bus_default_get_flags(const u32 *addr, unsigned long flags)
{
if (flags)
return flags;
return IORESOURCE_MEM;
}
/*
* SBUS bus specific translator
*/
int of_bus_sbus_match(struct device_node *np)
{
struct device_node *dp = np;
while (dp) {
if (!strcmp(dp->name, "sbus") ||
!strcmp(dp->name, "sbi"))
return 1;
/* Have a look at use_1to1_mapping(). We're trying
* to match SBUS if that's the top-level bus and we
* don't have some intervening real bus that provides
* ranges based translations.
*/
if (of_find_property(dp, "ranges", NULL) != NULL)
break;
dp = dp->parent;
}
return 0;
}
void of_bus_sbus_count_cells(struct device_node *child, int *addrc, int *sizec)
{
if (addrc)
*addrc = 2;
if (sizec)
*sizec = 1;
}
| gpl-2.0 |
OwnROM-Devices/OwnKernel-sprout | arch/x86/tools/relocs.c | 2219 | 25353 | /* This is included from relocs_32/64.c */
#define ElfW(type) _ElfW(ELF_BITS, type)
#define _ElfW(bits, type) __ElfW(bits, type)
#define __ElfW(bits, type) Elf##bits##_##type
#define Elf_Addr ElfW(Addr)
#define Elf_Ehdr ElfW(Ehdr)
#define Elf_Phdr ElfW(Phdr)
#define Elf_Shdr ElfW(Shdr)
#define Elf_Sym ElfW(Sym)
static Elf_Ehdr ehdr;
struct relocs {
uint32_t *offset;
unsigned long count;
unsigned long size;
};
static struct relocs relocs16;
static struct relocs relocs32;
static struct relocs relocs64;
struct section {
Elf_Shdr shdr;
struct section *link;
Elf_Sym *symtab;
Elf_Rel *reltab;
char *strtab;
};
static struct section *secs;
static const char * const sym_regex_kernel[S_NSYMTYPES] = {
/*
* Following symbols have been audited. There values are constant and do
* not change if bzImage is loaded at a different physical address than
* the address for which it has been compiled. Don't warn user about
* absolute relocations present w.r.t these symbols.
*/
[S_ABS] =
"^(xen_irq_disable_direct_reloc$|"
"xen_save_fl_direct_reloc$|"
"VDSO|"
"__crc_)",
/*
* These symbols are known to be relative, even if the linker marks them
* as absolute (typically defined outside any section in the linker script.)
*/
[S_REL] =
"^(__init_(begin|end)|"
"__x86_cpu_dev_(start|end)|"
"(__parainstructions|__alt_instructions)(|_end)|"
"(__iommu_table|__apicdrivers|__smp_locks)(|_end)|"
"__(start|end)_pci_.*|"
"__(start|end)_builtin_fw|"
"__(start|stop)___ksymtab(|_gpl|_unused|_unused_gpl|_gpl_future)|"
"__(start|stop)___kcrctab(|_gpl|_unused|_unused_gpl|_gpl_future)|"
"__(start|stop)___param|"
"__(start|stop)___modver|"
"__(start|stop)___bug_table|"
"__tracedata_(start|end)|"
"__(start|stop)_notes|"
"__end_rodata|"
"__initramfs_start|"
"(jiffies|jiffies_64)|"
#if ELF_BITS == 64
"__per_cpu_load|"
"init_per_cpu__.*|"
"__end_rodata_hpage_align|"
"__vvar_page|"
#endif
"_end)$"
};
static const char * const sym_regex_realmode[S_NSYMTYPES] = {
/*
* These symbols are known to be relative, even if the linker marks them
* as absolute (typically defined outside any section in the linker script.)
*/
[S_REL] =
"^pa_",
/*
* These are 16-bit segment symbols when compiling 16-bit code.
*/
[S_SEG] =
"^real_mode_seg$",
/*
* These are offsets belonging to segments, as opposed to linear addresses,
* when compiling 16-bit code.
*/
[S_LIN] =
"^pa_",
};
static const char * const *sym_regex;
static regex_t sym_regex_c[S_NSYMTYPES];
static int is_reloc(enum symtype type, const char *sym_name)
{
return sym_regex[type] &&
!regexec(&sym_regex_c[type], sym_name, 0, NULL, 0);
}
static void regex_init(int use_real_mode)
{
char errbuf[128];
int err;
int i;
if (use_real_mode)
sym_regex = sym_regex_realmode;
else
sym_regex = sym_regex_kernel;
for (i = 0; i < S_NSYMTYPES; i++) {
if (!sym_regex[i])
continue;
err = regcomp(&sym_regex_c[i], sym_regex[i],
REG_EXTENDED|REG_NOSUB);
if (err) {
regerror(err, &sym_regex_c[i], errbuf, sizeof errbuf);
die("%s", errbuf);
}
}
}
static const char *sym_type(unsigned type)
{
static const char *type_name[] = {
#define SYM_TYPE(X) [X] = #X
SYM_TYPE(STT_NOTYPE),
SYM_TYPE(STT_OBJECT),
SYM_TYPE(STT_FUNC),
SYM_TYPE(STT_SECTION),
SYM_TYPE(STT_FILE),
SYM_TYPE(STT_COMMON),
SYM_TYPE(STT_TLS),
#undef SYM_TYPE
};
const char *name = "unknown sym type name";
if (type < ARRAY_SIZE(type_name)) {
name = type_name[type];
}
return name;
}
static const char *sym_bind(unsigned bind)
{
static const char *bind_name[] = {
#define SYM_BIND(X) [X] = #X
SYM_BIND(STB_LOCAL),
SYM_BIND(STB_GLOBAL),
SYM_BIND(STB_WEAK),
#undef SYM_BIND
};
const char *name = "unknown sym bind name";
if (bind < ARRAY_SIZE(bind_name)) {
name = bind_name[bind];
}
return name;
}
static const char *sym_visibility(unsigned visibility)
{
static const char *visibility_name[] = {
#define SYM_VISIBILITY(X) [X] = #X
SYM_VISIBILITY(STV_DEFAULT),
SYM_VISIBILITY(STV_INTERNAL),
SYM_VISIBILITY(STV_HIDDEN),
SYM_VISIBILITY(STV_PROTECTED),
#undef SYM_VISIBILITY
};
const char *name = "unknown sym visibility name";
if (visibility < ARRAY_SIZE(visibility_name)) {
name = visibility_name[visibility];
}
return name;
}
static const char *rel_type(unsigned type)
{
static const char *type_name[] = {
#define REL_TYPE(X) [X] = #X
#if ELF_BITS == 64
REL_TYPE(R_X86_64_NONE),
REL_TYPE(R_X86_64_64),
REL_TYPE(R_X86_64_PC32),
REL_TYPE(R_X86_64_GOT32),
REL_TYPE(R_X86_64_PLT32),
REL_TYPE(R_X86_64_COPY),
REL_TYPE(R_X86_64_GLOB_DAT),
REL_TYPE(R_X86_64_JUMP_SLOT),
REL_TYPE(R_X86_64_RELATIVE),
REL_TYPE(R_X86_64_GOTPCREL),
REL_TYPE(R_X86_64_32),
REL_TYPE(R_X86_64_32S),
REL_TYPE(R_X86_64_16),
REL_TYPE(R_X86_64_PC16),
REL_TYPE(R_X86_64_8),
REL_TYPE(R_X86_64_PC8),
#else
REL_TYPE(R_386_NONE),
REL_TYPE(R_386_32),
REL_TYPE(R_386_PC32),
REL_TYPE(R_386_GOT32),
REL_TYPE(R_386_PLT32),
REL_TYPE(R_386_COPY),
REL_TYPE(R_386_GLOB_DAT),
REL_TYPE(R_386_JMP_SLOT),
REL_TYPE(R_386_RELATIVE),
REL_TYPE(R_386_GOTOFF),
REL_TYPE(R_386_GOTPC),
REL_TYPE(R_386_8),
REL_TYPE(R_386_PC8),
REL_TYPE(R_386_16),
REL_TYPE(R_386_PC16),
#endif
#undef REL_TYPE
};
const char *name = "unknown type rel type name";
if (type < ARRAY_SIZE(type_name) && type_name[type]) {
name = type_name[type];
}
return name;
}
static const char *sec_name(unsigned shndx)
{
const char *sec_strtab;
const char *name;
sec_strtab = secs[ehdr.e_shstrndx].strtab;
name = "<noname>";
if (shndx < ehdr.e_shnum) {
name = sec_strtab + secs[shndx].shdr.sh_name;
}
else if (shndx == SHN_ABS) {
name = "ABSOLUTE";
}
else if (shndx == SHN_COMMON) {
name = "COMMON";
}
return name;
}
static const char *sym_name(const char *sym_strtab, Elf_Sym *sym)
{
const char *name;
name = "<noname>";
if (sym->st_name) {
name = sym_strtab + sym->st_name;
}
else {
name = sec_name(sym->st_shndx);
}
return name;
}
static Elf_Sym *sym_lookup(const char *symname)
{
int i;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
long nsyms;
char *strtab;
Elf_Sym *symtab;
Elf_Sym *sym;
if (sec->shdr.sh_type != SHT_SYMTAB)
continue;
nsyms = sec->shdr.sh_size/sizeof(Elf_Sym);
symtab = sec->symtab;
strtab = sec->link->strtab;
for (sym = symtab; --nsyms >= 0; sym++) {
if (!sym->st_name)
continue;
if (strcmp(symname, strtab + sym->st_name) == 0)
return sym;
}
}
return 0;
}
#if BYTE_ORDER == LITTLE_ENDIAN
#define le16_to_cpu(val) (val)
#define le32_to_cpu(val) (val)
#define le64_to_cpu(val) (val)
#endif
#if BYTE_ORDER == BIG_ENDIAN
#define le16_to_cpu(val) bswap_16(val)
#define le32_to_cpu(val) bswap_32(val)
#define le64_to_cpu(val) bswap_64(val)
#endif
static uint16_t elf16_to_cpu(uint16_t val)
{
return le16_to_cpu(val);
}
static uint32_t elf32_to_cpu(uint32_t val)
{
return le32_to_cpu(val);
}
#define elf_half_to_cpu(x) elf16_to_cpu(x)
#define elf_word_to_cpu(x) elf32_to_cpu(x)
#if ELF_BITS == 64
static uint64_t elf64_to_cpu(uint64_t val)
{
return le64_to_cpu(val);
}
#define elf_addr_to_cpu(x) elf64_to_cpu(x)
#define elf_off_to_cpu(x) elf64_to_cpu(x)
#define elf_xword_to_cpu(x) elf64_to_cpu(x)
#else
#define elf_addr_to_cpu(x) elf32_to_cpu(x)
#define elf_off_to_cpu(x) elf32_to_cpu(x)
#define elf_xword_to_cpu(x) elf32_to_cpu(x)
#endif
static void read_ehdr(FILE *fp)
{
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1) {
die("Cannot read ELF header: %s\n",
strerror(errno));
}
if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) {
die("No ELF magic\n");
}
if (ehdr.e_ident[EI_CLASS] != ELF_CLASS) {
die("Not a %d bit executable\n", ELF_BITS);
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
die("Not a LSB ELF executable\n");
}
if (ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
die("Unknown ELF version\n");
}
/* Convert the fields to native endian */
ehdr.e_type = elf_half_to_cpu(ehdr.e_type);
ehdr.e_machine = elf_half_to_cpu(ehdr.e_machine);
ehdr.e_version = elf_word_to_cpu(ehdr.e_version);
ehdr.e_entry = elf_addr_to_cpu(ehdr.e_entry);
ehdr.e_phoff = elf_off_to_cpu(ehdr.e_phoff);
ehdr.e_shoff = elf_off_to_cpu(ehdr.e_shoff);
ehdr.e_flags = elf_word_to_cpu(ehdr.e_flags);
ehdr.e_ehsize = elf_half_to_cpu(ehdr.e_ehsize);
ehdr.e_phentsize = elf_half_to_cpu(ehdr.e_phentsize);
ehdr.e_phnum = elf_half_to_cpu(ehdr.e_phnum);
ehdr.e_shentsize = elf_half_to_cpu(ehdr.e_shentsize);
ehdr.e_shnum = elf_half_to_cpu(ehdr.e_shnum);
ehdr.e_shstrndx = elf_half_to_cpu(ehdr.e_shstrndx);
if ((ehdr.e_type != ET_EXEC) && (ehdr.e_type != ET_DYN)) {
die("Unsupported ELF header type\n");
}
if (ehdr.e_machine != ELF_MACHINE) {
die("Not for %s\n", ELF_MACHINE_NAME);
}
if (ehdr.e_version != EV_CURRENT) {
die("Unknown ELF version\n");
}
if (ehdr.e_ehsize != sizeof(Elf_Ehdr)) {
die("Bad Elf header size\n");
}
if (ehdr.e_phentsize != sizeof(Elf_Phdr)) {
die("Bad program header entry\n");
}
if (ehdr.e_shentsize != sizeof(Elf_Shdr)) {
die("Bad section header entry\n");
}
if (ehdr.e_shstrndx >= ehdr.e_shnum) {
die("String table index out of bounds\n");
}
}
static void read_shdrs(FILE *fp)
{
int i;
Elf_Shdr shdr;
secs = calloc(ehdr.e_shnum, sizeof(struct section));
if (!secs) {
die("Unable to allocate %d section headers\n",
ehdr.e_shnum);
}
if (fseek(fp, ehdr.e_shoff, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
ehdr.e_shoff, strerror(errno));
}
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (fread(&shdr, sizeof shdr, 1, fp) != 1)
die("Cannot read ELF section headers %d/%d: %s\n",
i, ehdr.e_shnum, strerror(errno));
sec->shdr.sh_name = elf_word_to_cpu(shdr.sh_name);
sec->shdr.sh_type = elf_word_to_cpu(shdr.sh_type);
sec->shdr.sh_flags = elf_xword_to_cpu(shdr.sh_flags);
sec->shdr.sh_addr = elf_addr_to_cpu(shdr.sh_addr);
sec->shdr.sh_offset = elf_off_to_cpu(shdr.sh_offset);
sec->shdr.sh_size = elf_xword_to_cpu(shdr.sh_size);
sec->shdr.sh_link = elf_word_to_cpu(shdr.sh_link);
sec->shdr.sh_info = elf_word_to_cpu(shdr.sh_info);
sec->shdr.sh_addralign = elf_xword_to_cpu(shdr.sh_addralign);
sec->shdr.sh_entsize = elf_xword_to_cpu(shdr.sh_entsize);
if (sec->shdr.sh_link < ehdr.e_shnum)
sec->link = &secs[sec->shdr.sh_link];
}
}
static void read_strtabs(FILE *fp)
{
int i;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_STRTAB) {
continue;
}
sec->strtab = malloc(sec->shdr.sh_size);
if (!sec->strtab) {
die("malloc of %d bytes for strtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->strtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
}
}
static void read_symtabs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sec->symtab = malloc(sec->shdr.sh_size);
if (!sec->symtab) {
die("malloc of %d bytes for symtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->symtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Sym); j++) {
Elf_Sym *sym = &sec->symtab[j];
sym->st_name = elf_word_to_cpu(sym->st_name);
sym->st_value = elf_addr_to_cpu(sym->st_value);
sym->st_size = elf_xword_to_cpu(sym->st_size);
sym->st_shndx = elf_half_to_cpu(sym->st_shndx);
}
}
}
static void read_relocs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL_TYPE) {
continue;
}
sec->reltab = malloc(sec->shdr.sh_size);
if (!sec->reltab) {
die("malloc of %d bytes for relocs failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->reltab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
Elf_Rel *rel = &sec->reltab[j];
rel->r_offset = elf_addr_to_cpu(rel->r_offset);
rel->r_info = elf_xword_to_cpu(rel->r_info);
#if (SHT_REL_TYPE == SHT_RELA)
rel->r_addend = elf_xword_to_cpu(rel->r_addend);
#endif
}
}
}
static void print_absolute_symbols(void)
{
int i;
const char *format;
if (ELF_BITS == 64)
format = "%5d %016"PRIx64" %5"PRId64" %10s %10s %12s %s\n";
else
format = "%5d %08"PRIx32" %5"PRId32" %10s %10s %12s %s\n";
printf("Absolute symbols\n");
printf(" Num: Value Size Type Bind Visibility Name\n");
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
char *sym_strtab;
int j;
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sym_strtab = sec->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Sym); j++) {
Elf_Sym *sym;
const char *name;
sym = &sec->symtab[j];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
printf(format,
j, sym->st_value, sym->st_size,
sym_type(ELF_ST_TYPE(sym->st_info)),
sym_bind(ELF_ST_BIND(sym->st_info)),
sym_visibility(ELF_ST_VISIBILITY(sym->st_other)),
name);
}
}
printf("\n");
}
static void print_absolute_relocs(void)
{
int i, printed = 0;
const char *format;
if (ELF_BITS == 64)
format = "%016"PRIx64" %016"PRIx64" %10s %016"PRIx64" %s\n";
else
format = "%08"PRIx32" %08"PRIx32" %10s %08"PRIx32" %s\n";
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
struct section *sec_applies, *sec_symtab;
char *sym_strtab;
Elf_Sym *sh_symtab;
int j;
if (sec->shdr.sh_type != SHT_REL_TYPE) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
Elf_Rel *rel;
Elf_Sym *sym;
const char *name;
rel = &sec->reltab[j];
sym = &sh_symtab[ELF_R_SYM(rel->r_info)];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
/* Absolute symbols are not relocated if bzImage is
* loaded at a non-compiled address. Display a warning
* to user at compile time about the absolute
* relocations present.
*
* User need to audit the code to make sure
* some symbols which should have been section
* relative have not become absolute because of some
* linker optimization or wrong programming usage.
*
* Before warning check if this absolute symbol
* relocation is harmless.
*/
if (is_reloc(S_ABS, name) || is_reloc(S_REL, name))
continue;
if (!printed) {
printf("WARNING: Absolute relocations"
" present\n");
printf("Offset Info Type Sym.Value "
"Sym.Name\n");
printed = 1;
}
printf(format,
rel->r_offset,
rel->r_info,
rel_type(ELF_R_TYPE(rel->r_info)),
sym->st_value,
name);
}
}
if (printed)
printf("\n");
}
static void add_reloc(struct relocs *r, uint32_t offset)
{
if (r->count == r->size) {
unsigned long newsize = r->size + 50000;
void *mem = realloc(r->offset, newsize * sizeof(r->offset[0]));
if (!mem)
die("realloc of %ld entries for relocs failed\n",
newsize);
r->offset = mem;
r->size = newsize;
}
r->offset[r->count++] = offset;
}
static void walk_relocs(int (*process)(struct section *sec, Elf_Rel *rel,
Elf_Sym *sym, const char *symname))
{
int i;
/* Walk through the relocations */
for (i = 0; i < ehdr.e_shnum; i++) {
char *sym_strtab;
Elf_Sym *sh_symtab;
struct section *sec_applies, *sec_symtab;
int j;
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL_TYPE) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
Elf_Rel *rel = &sec->reltab[j];
Elf_Sym *sym = &sh_symtab[ELF_R_SYM(rel->r_info)];
const char *symname = sym_name(sym_strtab, sym);
process(sec, rel, sym, symname);
}
}
}
/*
* The .data..percpu section is a special case for x86_64 SMP kernels.
* It is used to initialize the actual per_cpu areas and to provide
* definitions for the per_cpu variables that correspond to their offsets
* within the percpu area. Since the values of all of the symbols need
* to be offsets from the start of the per_cpu area the virtual address
* (sh_addr) of .data..percpu is 0 in SMP kernels.
*
* This means that:
*
* Relocations that reference symbols in the per_cpu area do not
* need further relocation (since the value is an offset relative
* to the start of the per_cpu area that does not change).
*
* Relocations that apply to the per_cpu area need to have their
* offset adjusted by by the value of __per_cpu_load to make them
* point to the correct place in the loaded image (because the
* virtual address of .data..percpu is 0).
*
* For non SMP kernels .data..percpu is linked as part of the normal
* kernel data and does not require special treatment.
*
*/
static int per_cpu_shndx = -1;
Elf_Addr per_cpu_load_addr;
static void percpu_init(void)
{
int i;
for (i = 0; i < ehdr.e_shnum; i++) {
ElfW(Sym) *sym;
if (strcmp(sec_name(i), ".data..percpu"))
continue;
if (secs[i].shdr.sh_addr != 0) /* non SMP kernel */
return;
sym = sym_lookup("__per_cpu_load");
if (!sym)
die("can't find __per_cpu_load\n");
per_cpu_shndx = i;
per_cpu_load_addr = sym->st_value;
return;
}
}
#if ELF_BITS == 64
/*
* Check to see if a symbol lies in the .data..percpu section.
* For some as yet not understood reason the "__init_begin"
* symbol which immediately preceeds the .data..percpu section
* also shows up as it it were part of it so we do an explict
* check for that symbol name and ignore it.
*/
static int is_percpu_sym(ElfW(Sym) *sym, const char *symname)
{
return (sym->st_shndx == per_cpu_shndx) &&
strcmp(symname, "__init_begin");
}
static int do_reloc64(struct section *sec, Elf_Rel *rel, ElfW(Sym) *sym,
const char *symname)
{
unsigned r_type = ELF64_R_TYPE(rel->r_info);
ElfW(Addr) offset = rel->r_offset;
int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
if (sym->st_shndx == SHN_UNDEF)
return 0;
/*
* Adjust the offset if this reloc applies to the percpu section.
*/
if (sec->shdr.sh_info == per_cpu_shndx)
offset += per_cpu_load_addr;
switch (r_type) {
case R_X86_64_NONE:
case R_X86_64_PC32:
/*
* NONE can be ignored and PC relative relocations don't
* need to be adjusted.
*/
break;
case R_X86_64_32:
case R_X86_64_32S:
case R_X86_64_64:
/*
* References to the percpu area don't need to be adjusted.
*/
if (is_percpu_sym(sym, symname))
break;
if (shn_abs) {
/*
* Whitelisted absolute symbols do not require
* relocation.
*/
if (is_reloc(S_ABS, symname))
break;
die("Invalid absolute %s relocation: %s\n",
rel_type(r_type), symname);
break;
}
/*
* Relocation offsets for 64 bit kernels are output
* as 32 bits and sign extended back to 64 bits when
* the relocations are processed.
* Make sure that the offset will fit.
*/
if ((int32_t)offset != (int64_t)offset)
die("Relocation offset doesn't fit in 32 bits\n");
if (r_type == R_X86_64_64)
add_reloc(&relocs64, offset);
else
add_reloc(&relocs32, offset);
break;
default:
die("Unsupported relocation type: %s (%d)\n",
rel_type(r_type), r_type);
break;
}
return 0;
}
#else
static int do_reloc32(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
const char *symname)
{
unsigned r_type = ELF32_R_TYPE(rel->r_info);
int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
switch (r_type) {
case R_386_NONE:
case R_386_PC32:
case R_386_PC16:
case R_386_PC8:
/*
* NONE can be ignored and PC relative relocations don't
* need to be adjusted.
*/
break;
case R_386_32:
if (shn_abs) {
/*
* Whitelisted absolute symbols do not require
* relocation.
*/
if (is_reloc(S_ABS, symname))
break;
die("Invalid absolute %s relocation: %s\n",
rel_type(r_type), symname);
break;
}
add_reloc(&relocs32, rel->r_offset);
break;
default:
die("Unsupported relocation type: %s (%d)\n",
rel_type(r_type), r_type);
break;
}
return 0;
}
static int do_reloc_real(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
const char *symname)
{
unsigned r_type = ELF32_R_TYPE(rel->r_info);
int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
switch (r_type) {
case R_386_NONE:
case R_386_PC32:
case R_386_PC16:
case R_386_PC8:
/*
* NONE can be ignored and PC relative relocations don't
* need to be adjusted.
*/
break;
case R_386_16:
if (shn_abs) {
/*
* Whitelisted absolute symbols do not require
* relocation.
*/
if (is_reloc(S_ABS, symname))
break;
if (is_reloc(S_SEG, symname)) {
add_reloc(&relocs16, rel->r_offset);
break;
}
} else {
if (!is_reloc(S_LIN, symname))
break;
}
die("Invalid %s %s relocation: %s\n",
shn_abs ? "absolute" : "relative",
rel_type(r_type), symname);
break;
case R_386_32:
if (shn_abs) {
/*
* Whitelisted absolute symbols do not require
* relocation.
*/
if (is_reloc(S_ABS, symname))
break;
if (is_reloc(S_REL, symname)) {
add_reloc(&relocs32, rel->r_offset);
break;
}
} else {
if (is_reloc(S_LIN, symname))
add_reloc(&relocs32, rel->r_offset);
break;
}
die("Invalid %s %s relocation: %s\n",
shn_abs ? "absolute" : "relative",
rel_type(r_type), symname);
break;
default:
die("Unsupported relocation type: %s (%d)\n",
rel_type(r_type), r_type);
break;
}
return 0;
}
#endif
static int cmp_relocs(const void *va, const void *vb)
{
const uint32_t *a, *b;
a = va; b = vb;
return (*a == *b)? 0 : (*a > *b)? 1 : -1;
}
static void sort_relocs(struct relocs *r)
{
qsort(r->offset, r->count, sizeof(r->offset[0]), cmp_relocs);
}
static int write32(uint32_t v, FILE *f)
{
unsigned char buf[4];
put_unaligned_le32(v, buf);
return fwrite(buf, 1, 4, f) == 4 ? 0 : -1;
}
static int write32_as_text(uint32_t v, FILE *f)
{
return fprintf(f, "\t.long 0x%08"PRIx32"\n", v) > 0 ? 0 : -1;
}
static void emit_relocs(int as_text, int use_real_mode)
{
int i;
int (*write_reloc)(uint32_t, FILE *) = write32;
int (*do_reloc)(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
const char *symname);
#if ELF_BITS == 64
if (!use_real_mode)
do_reloc = do_reloc64;
else
die("--realmode not valid for a 64-bit ELF file");
#else
if (!use_real_mode)
do_reloc = do_reloc32;
else
do_reloc = do_reloc_real;
#endif
/* Collect up the relocations */
walk_relocs(do_reloc);
if (relocs16.count && !use_real_mode)
die("Segment relocations found but --realmode not specified\n");
/* Order the relocations for more efficient processing */
sort_relocs(&relocs16);
sort_relocs(&relocs32);
sort_relocs(&relocs64);
/* Print the relocations */
if (as_text) {
/* Print the relocations in a form suitable that
* gas will like.
*/
printf(".section \".data.reloc\",\"a\"\n");
printf(".balign 4\n");
write_reloc = write32_as_text;
}
if (use_real_mode) {
write_reloc(relocs16.count, stdout);
for (i = 0; i < relocs16.count; i++)
write_reloc(relocs16.offset[i], stdout);
write_reloc(relocs32.count, stdout);
for (i = 0; i < relocs32.count; i++)
write_reloc(relocs32.offset[i], stdout);
} else {
if (ELF_BITS == 64) {
/* Print a stop */
write_reloc(0, stdout);
/* Now print each relocation */
for (i = 0; i < relocs64.count; i++)
write_reloc(relocs64.offset[i], stdout);
}
/* Print a stop */
write_reloc(0, stdout);
/* Now print each relocation */
for (i = 0; i < relocs32.count; i++)
write_reloc(relocs32.offset[i], stdout);
}
}
#if ELF_BITS == 64
# define process process_64
#else
# define process process_32
#endif
void process(FILE *fp, int use_real_mode, int as_text,
int show_absolute_syms, int show_absolute_relocs)
{
regex_init(use_real_mode);
read_ehdr(fp);
read_shdrs(fp);
read_strtabs(fp);
read_symtabs(fp);
read_relocs(fp);
if (ELF_BITS == 64)
percpu_init();
if (show_absolute_syms) {
print_absolute_symbols();
return;
}
if (show_absolute_relocs) {
print_absolute_relocs();
return;
}
emit_relocs(as_text, use_real_mode);
}
| gpl-2.0 |
yseung123/android_kernel_oneplus_msm8994 | drivers/input/serio/ct82c710.c | 3243 | 6758 | /*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* 82C710 C&T mouse port chip driver for Linux
*/
/*
* 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
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/serio.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/io.h>
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("82C710 C&T mouse port chip driver");
MODULE_LICENSE("GPL");
/*
* ct82c710 interface
*/
#define CT82C710_DEV_IDLE 0x01 /* Device Idle */
#define CT82C710_RX_FULL 0x02 /* Device Char received */
#define CT82C710_TX_IDLE 0x04 /* Device XMIT Idle */
#define CT82C710_RESET 0x08 /* Device Reset */
#define CT82C710_INTS_ON 0x10 /* Device Interrupt On */
#define CT82C710_ERROR_FLAG 0x20 /* Device Error */
#define CT82C710_CLEAR 0x40 /* Device Clear */
#define CT82C710_ENABLE 0x80 /* Device Enable */
#define CT82C710_IRQ 12
#define CT82C710_DATA ct82c710_iores.start
#define CT82C710_STATUS (ct82c710_iores.start + 1)
static struct serio *ct82c710_port;
static struct platform_device *ct82c710_device;
static struct resource ct82c710_iores;
/*
* Interrupt handler for the 82C710 mouse port. A character
* is waiting in the 82C710.
*/
static irqreturn_t ct82c710_interrupt(int cpl, void *dev_id)
{
return serio_interrupt(ct82c710_port, inb(CT82C710_DATA), 0);
}
/*
* Wait for device to send output char and flush any input char.
*/
static int ct82c170_wait(void)
{
int timeout = 60000;
while ((inb(CT82C710_STATUS) & (CT82C710_RX_FULL | CT82C710_TX_IDLE | CT82C710_DEV_IDLE))
!= (CT82C710_DEV_IDLE | CT82C710_TX_IDLE) && timeout) {
if (inb_p(CT82C710_STATUS) & CT82C710_RX_FULL) inb_p(CT82C710_DATA);
udelay(1);
timeout--;
}
return !timeout;
}
static void ct82c710_close(struct serio *serio)
{
if (ct82c170_wait())
printk(KERN_WARNING "ct82c710.c: Device busy in close()\n");
outb_p(inb_p(CT82C710_STATUS) & ~(CT82C710_ENABLE | CT82C710_INTS_ON), CT82C710_STATUS);
if (ct82c170_wait())
printk(KERN_WARNING "ct82c710.c: Device busy in close()\n");
free_irq(CT82C710_IRQ, NULL);
}
static int ct82c710_open(struct serio *serio)
{
unsigned char status;
int err;
err = request_irq(CT82C710_IRQ, ct82c710_interrupt, 0, "ct82c710", NULL);
if (err)
return err;
status = inb_p(CT82C710_STATUS);
status |= (CT82C710_ENABLE | CT82C710_RESET);
outb_p(status, CT82C710_STATUS);
status &= ~(CT82C710_RESET);
outb_p(status, CT82C710_STATUS);
status |= CT82C710_INTS_ON;
outb_p(status, CT82C710_STATUS); /* Enable interrupts */
while (ct82c170_wait()) {
printk(KERN_ERR "ct82c710: Device busy in open()\n");
status &= ~(CT82C710_ENABLE | CT82C710_INTS_ON);
outb_p(status, CT82C710_STATUS);
free_irq(CT82C710_IRQ, NULL);
return -EBUSY;
}
return 0;
}
/*
* Write to the 82C710 mouse device.
*/
static int ct82c710_write(struct serio *port, unsigned char c)
{
if (ct82c170_wait()) return -1;
outb_p(c, CT82C710_DATA);
return 0;
}
/*
* See if we can find a 82C710 device. Read mouse address.
*/
static int __init ct82c710_detect(void)
{
outb_p(0x55, 0x2fa); /* Any value except 9, ff or 36 */
outb_p(0xaa, 0x3fa); /* Inverse of 55 */
outb_p(0x36, 0x3fa); /* Address the chip */
outb_p(0xe4, 0x3fa); /* 390/4; 390 = config address */
outb_p(0x1b, 0x2fa); /* Inverse of e4 */
outb_p(0x0f, 0x390); /* Write index */
if (inb_p(0x391) != 0xe4) /* Config address found? */
return -ENODEV; /* No: no 82C710 here */
outb_p(0x0d, 0x390); /* Write index */
ct82c710_iores.start = inb_p(0x391) << 2; /* Get mouse I/O address */
ct82c710_iores.end = ct82c710_iores.start + 1;
ct82c710_iores.flags = IORESOURCE_IO;
outb_p(0x0f, 0x390);
outb_p(0x0f, 0x391); /* Close config mode */
return 0;
}
static int ct82c710_probe(struct platform_device *dev)
{
ct82c710_port = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!ct82c710_port)
return -ENOMEM;
ct82c710_port->id.type = SERIO_8042;
ct82c710_port->dev.parent = &dev->dev;
ct82c710_port->open = ct82c710_open;
ct82c710_port->close = ct82c710_close;
ct82c710_port->write = ct82c710_write;
strlcpy(ct82c710_port->name, "C&T 82c710 mouse port",
sizeof(ct82c710_port->name));
snprintf(ct82c710_port->phys, sizeof(ct82c710_port->phys),
"isa%16llx/serio0", (unsigned long long)CT82C710_DATA);
serio_register_port(ct82c710_port);
printk(KERN_INFO "serio: C&T 82c710 mouse port at %#llx irq %d\n",
(unsigned long long)CT82C710_DATA, CT82C710_IRQ);
return 0;
}
static int ct82c710_remove(struct platform_device *dev)
{
serio_unregister_port(ct82c710_port);
return 0;
}
static struct platform_driver ct82c710_driver = {
.driver = {
.name = "ct82c710",
.owner = THIS_MODULE,
},
.probe = ct82c710_probe,
.remove = ct82c710_remove,
};
static int __init ct82c710_init(void)
{
int error;
error = ct82c710_detect();
if (error)
return error;
error = platform_driver_register(&ct82c710_driver);
if (error)
return error;
ct82c710_device = platform_device_alloc("ct82c710", -1);
if (!ct82c710_device) {
error = -ENOMEM;
goto err_unregister_driver;
}
error = platform_device_add_resources(ct82c710_device, &ct82c710_iores, 1);
if (error)
goto err_free_device;
error = platform_device_add(ct82c710_device);
if (error)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(ct82c710_device);
err_unregister_driver:
platform_driver_unregister(&ct82c710_driver);
return error;
}
static void __exit ct82c710_exit(void)
{
platform_device_unregister(ct82c710_device);
platform_driver_unregister(&ct82c710_driver);
}
module_init(ct82c710_init);
module_exit(ct82c710_exit);
| gpl-2.0 |
TeskeVirtualSystem/odroid_mptcp | drivers/staging/frontier/tranzport.c | 3243 | 27195 | /*
* Frontier Designs Tranzport driver
*
* Copyright (C) 2007 Michael Taht (m@taht.net)
*
* Based on the usbled driver and ldusb drivers by
*
* Copyright (C) 2004 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2005 Michael Hund <mhund@ld-didactic.de>
*
* The ldusb driver was, in turn, derived from Lego USB Tower driver
* Copyright (C) 2003 David Glance <advidgsf@sourceforge.net>
* 2001-2004 Juergen Stuber <starblue@users.sourceforge.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, version 2.
*
*/
/*
* This driver uses a ring buffer for time critical reading of
* interrupt in reports and provides read and write methods for
* raw interrupt reports.
*/
/* Note: this currently uses a dumb ringbuffer for reads and writes.
* A more optimal driver would cache and kill off outstanding urbs that are
* now invalid, and ignore ones that already were in the queue but valid
* as we only have 17 commands for the tranzport. In particular this is
* key for getting lights to flash in time as otherwise many commands
* can be buffered up before the light change makes it to the interface.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/poll.h>
/* Define these values to match your devices */
#define VENDOR_ID 0x165b
#define PRODUCT_ID 0x8101
#ifdef CONFIG_USB_DYNAMIC_MINORS
#define USB_TRANZPORT_MINOR_BASE 0
#else /* FIXME 177- is the another driver's minor - apply for a minor soon */
#define USB_TRANZPORT_MINOR_BASE 177
#endif
/* table of devices that work with this driver */
static const struct usb_device_id usb_tranzport_table[] = {
{USB_DEVICE(VENDOR_ID, PRODUCT_ID)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_tranzport_table);
MODULE_VERSION("0.35");
MODULE_AUTHOR("Mike Taht <m@taht.net>");
MODULE_DESCRIPTION("Tranzport USB Driver");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("Frontier Designs Tranzport Control Surface");
#define SUPPRESS_EXTRA_OFFLINE_EVENTS 1
#define COMPRESS_WHEEL_EVENTS 1
#define BUFFERED_READS 1
#define RING_BUFFER_SIZE 1000
#define WRITE_BUFFER_SIZE 34
#define TRANZPORT_USB_TIMEOUT 10
#define TRANZPORT_DEBUG 0
static int debug = TRANZPORT_DEBUG;
/* Use our own dbg macro */
#define dbg_info(dev, format, arg...) do \
{ if (debug) dev_info(dev , format , ## arg); } while (0)
/* Module parameters */
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
/* All interrupt in transfers are collected in a ring buffer to
* avoid racing conditions and get better performance of the driver.
*/
static int ring_buffer_size = RING_BUFFER_SIZE;
module_param(ring_buffer_size, int, S_IRUGO);
MODULE_PARM_DESC(ring_buffer_size, "Read ring buffer size in reports");
/* The write_buffer can one day contain more than one interrupt out transfer.
*/
static int write_buffer_size = WRITE_BUFFER_SIZE;
module_param(write_buffer_size, int, S_IRUGO);
MODULE_PARM_DESC(write_buffer_size, "Write buffer size");
/*
* Increase the interval for debugging purposes.
* or set to 1 to use the standard interval from the endpoint descriptors.
*/
static int min_interrupt_in_interval = TRANZPORT_USB_TIMEOUT;
module_param(min_interrupt_in_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_in_interval,
"Minimum interrupt in interval in ms");
static int min_interrupt_out_interval = TRANZPORT_USB_TIMEOUT;
module_param(min_interrupt_out_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_out_interval,
"Minimum interrupt out interval in ms");
struct tranzport_cmd {
unsigned char cmd[8];
};
/* Structure to hold all of our device specific stuff */
struct usb_tranzport {
struct mutex mtx; /* locks this structure */
struct usb_interface *intf; /* save off the usb interface pointer */
int open_count; /* number of times this port opened */
struct tranzport_cmd (*ring_buffer)[RING_BUFFER_SIZE];
unsigned int ring_head;
unsigned int ring_tail;
wait_queue_head_t read_wait;
wait_queue_head_t write_wait;
unsigned char *interrupt_in_buffer;
struct usb_endpoint_descriptor *interrupt_in_endpoint;
struct urb *interrupt_in_urb;
int interrupt_in_interval;
size_t interrupt_in_endpoint_size;
int interrupt_in_running;
int interrupt_in_done;
char *interrupt_out_buffer;
struct usb_endpoint_descriptor *interrupt_out_endpoint;
struct urb *interrupt_out_urb;
int interrupt_out_interval;
size_t interrupt_out_endpoint_size;
int interrupt_out_busy;
/* Sysfs support */
unsigned char enable; /* 0 if disabled 1 if enabled */
unsigned char offline; /* if the device is out of range or asleep */
unsigned char compress_wheel; /* flag to compress wheel events */
};
/* prevent races between open() and disconnect() */
static DEFINE_MUTEX(disconnect_mutex);
static struct usb_driver usb_tranzport_driver;
/**
* usb_tranzport_abort_transfers
* aborts transfers and frees associated data structures
*/
static void usb_tranzport_abort_transfers(struct usb_tranzport *dev)
{
/* shutdown transfer */
if (dev->interrupt_in_running) {
dev->interrupt_in_running = 0;
if (dev->intf)
usb_kill_urb(dev->interrupt_in_urb);
}
if (dev->interrupt_out_busy)
if (dev->intf)
usb_kill_urb(dev->interrupt_out_urb);
}
#define show_int(value) \
static ssize_t show_##value(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
return sprintf(buf, "%d\n", t->value); \
} \
static DEVICE_ATTR(value, S_IRUGO, show_##value, NULL);
#define show_set_int(value) \
static ssize_t show_##value(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
return sprintf(buf, "%d\n", t->value); \
} \
static ssize_t set_##value(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
unsigned long temp; \
if (strict_strtoul(buf, 10, &temp)) \
return -EINVAL; \
t->value = temp; \
return count; \
} \
static DEVICE_ATTR(value, S_IWUSR | S_IRUGO, show_##value, set_##value);
show_int(enable);
show_int(offline);
show_set_int(compress_wheel);
/**
* usb_tranzport_delete
*/
static void usb_tranzport_delete(struct usb_tranzport *dev)
{
usb_tranzport_abort_transfers(dev);
if (dev->intf != NULL) {
device_remove_file(&dev->intf->dev, &dev_attr_enable);
device_remove_file(&dev->intf->dev, &dev_attr_offline);
device_remove_file(&dev->intf->dev, &dev_attr_compress_wheel);
}
/* free data structures */
usb_free_urb(dev->interrupt_in_urb);
usb_free_urb(dev->interrupt_out_urb);
kfree(dev->ring_buffer);
kfree(dev->interrupt_in_buffer);
kfree(dev->interrupt_out_buffer);
kfree(dev);
}
/**
* usb_tranzport_interrupt_in_callback
*/
static void usb_tranzport_interrupt_in_callback(struct urb *urb)
{
struct usb_tranzport *dev = urb->context;
unsigned int next_ring_head;
int retval = -1;
if (urb->status) {
if (urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN) {
goto exit;
} else {
dbg_info(&dev->intf->dev,
"%s: nonzero status received: %d\n",
__func__, urb->status);
goto resubmit; /* maybe we can recover */
}
}
if (urb->actual_length != 8) {
dev_warn(&dev->intf->dev,
"Urb length was %d bytes!!"
"Do something intelligent\n",
urb->actual_length);
} else {
dbg_info(&dev->intf->dev,
"%s: received: %02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__, dev->interrupt_in_buffer[0],
dev->interrupt_in_buffer[1],
dev->interrupt_in_buffer[2],
dev->interrupt_in_buffer[3],
dev->interrupt_in_buffer[4],
dev->interrupt_in_buffer[5],
dev->interrupt_in_buffer[6],
dev->interrupt_in_buffer[7]);
#if SUPPRESS_EXTRA_OFFLINE_EVENTS
if (dev->offline == 2 && dev->interrupt_in_buffer[1] == 0xff)
goto resubmit;
if (dev->offline == 1 && dev->interrupt_in_buffer[1] == 0xff) {
dev->offline = 2;
goto resubmit;
}
/* Always pass one offline event up the stack */
if (dev->offline > 0 && dev->interrupt_in_buffer[1] != 0xff)
dev->offline = 0;
if (dev->offline == 0 && dev->interrupt_in_buffer[1] == 0xff)
dev->offline = 1;
#endif /* SUPPRESS_EXTRA_OFFLINE_EVENTS */
dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
next_ring_head = (dev->ring_head + 1) % ring_buffer_size;
if (next_ring_head != dev->ring_tail) {
memcpy(&((*dev->ring_buffer)[dev->ring_head]),
dev->interrupt_in_buffer, urb->actual_length);
dev->ring_head = next_ring_head;
retval = 0;
memset(dev->interrupt_in_buffer, 0, urb->actual_length);
} else {
dev_warn(&dev->intf->dev,
"Ring buffer overflow, %d bytes dropped\n",
urb->actual_length);
memset(dev->interrupt_in_buffer, 0, urb->actual_length);
}
}
resubmit:
/* resubmit if we're still running */
if (dev->interrupt_in_running && dev->intf) {
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_ATOMIC);
if (retval)
dev_err(&dev->intf->dev,
"usb_submit_urb failed (%d)\n", retval);
}
exit:
dev->interrupt_in_done = 1;
wake_up_interruptible(&dev->read_wait);
}
/**
* usb_tranzport_interrupt_out_callback
*/
static void usb_tranzport_interrupt_out_callback(struct urb *urb)
{
struct usb_tranzport *dev = urb->context;
/* sync/async unlink faults aren't errors */
if (urb->status && !(urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN))
dbg_info(&dev->intf->dev,
"%s - nonzero write interrupt status received: %d\n",
__func__, urb->status);
dev->interrupt_out_busy = 0;
wake_up_interruptible(&dev->write_wait);
}
/**
* usb_tranzport_open
*/
static int usb_tranzport_open(struct inode *inode, struct file *file)
{
struct usb_tranzport *dev;
int subminor;
int retval = 0;
struct usb_interface *interface;
nonseekable_open(inode, file);
subminor = iminor(inode);
mutex_lock(&disconnect_mutex);
interface = usb_find_interface(&usb_tranzport_driver, subminor);
if (!interface) {
err("%s - error, can't find device for minor %d\n",
__func__, subminor);
retval = -ENODEV;
goto unlock_disconnect_exit;
}
dev = usb_get_intfdata(interface);
if (!dev) {
retval = -ENODEV;
goto unlock_disconnect_exit;
}
/* lock this device */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto unlock_disconnect_exit;
}
/* allow opening only once */
if (dev->open_count) {
retval = -EBUSY;
goto unlock_exit;
}
dev->open_count = 1;
/* initialize in direction */
dev->ring_head = 0;
dev->ring_tail = 0;
usb_fill_int_urb(dev->interrupt_in_urb,
interface_to_usbdev(interface),
usb_rcvintpipe(interface_to_usbdev(interface),
dev->interrupt_in_endpoint->
bEndpointAddress),
dev->interrupt_in_buffer,
dev->interrupt_in_endpoint_size,
usb_tranzport_interrupt_in_callback, dev,
dev->interrupt_in_interval);
dev->interrupt_in_running = 1;
dev->interrupt_in_done = 0;
dev->enable = 1;
dev->offline = 0;
dev->compress_wheel = 1;
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL);
if (retval) {
dev_err(&interface->dev,
"Couldn't submit interrupt_in_urb %d\n", retval);
dev->interrupt_in_running = 0;
dev->open_count = 0;
goto unlock_exit;
}
/* save device in the file's private structure */
file->private_data = dev;
unlock_exit:
mutex_unlock(&dev->mtx);
unlock_disconnect_exit:
mutex_unlock(&disconnect_mutex);
return retval;
}
/**
* usb_tranzport_release
*/
static int usb_tranzport_release(struct inode *inode, struct file *file)
{
struct usb_tranzport *dev;
int retval = 0;
dev = file->private_data;
if (dev == NULL) {
retval = -ENODEV;
goto exit;
}
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
if (dev->open_count != 1) {
retval = -ENODEV;
goto unlock_exit;
}
if (dev->intf == NULL) {
/* the device was unplugged before the file was released */
mutex_unlock(&dev->mtx);
/* unlock here as usb_tranzport_delete frees dev */
usb_tranzport_delete(dev);
retval = -ENODEV;
goto exit;
}
/* wait until write transfer is finished */
if (dev->interrupt_out_busy)
wait_event_interruptible_timeout(dev->write_wait,
!dev->interrupt_out_busy,
2 * HZ);
usb_tranzport_abort_transfers(dev);
dev->open_count = 0;
unlock_exit:
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/**
* usb_tranzport_poll
*/
static unsigned int usb_tranzport_poll(struct file *file, poll_table * wait)
{
struct usb_tranzport *dev;
unsigned int mask = 0;
dev = file->private_data;
poll_wait(file, &dev->read_wait, wait);
poll_wait(file, &dev->write_wait, wait);
if (dev->ring_head != dev->ring_tail)
mask |= POLLIN | POLLRDNORM;
if (!dev->interrupt_out_busy)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/**
* usb_tranzport_read
*/
static ssize_t usb_tranzport_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct usb_tranzport *dev;
int retval = 0;
#if BUFFERED_READS
int c = 0;
#endif
#if COMPRESS_WHEEL_EVENTS
signed char oldwheel;
signed char newwheel;
int cancompress = 1;
int next_tail;
#endif
/* do I have such a thing as a null event? */
dev = file->private_data;
/* verify that we actually have some data to read */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */ if (dev->intf == NULL) {
retval = -ENODEV;
err("No device or device unplugged %d\n", retval);
goto unlock_exit;
}
while (dev->ring_head == dev->ring_tail) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
/* tiny race - FIXME: make atomic? */
/* atomic_cmp_exchange(&dev->interrupt_in_done,0,0); */
dev->interrupt_in_done = 0;
retval = wait_event_interruptible(dev->read_wait,
dev->interrupt_in_done);
if (retval < 0)
goto unlock_exit;
}
dbg_info(&dev->intf->dev,
"%s: copying to userspace: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].cmd[0],
(*dev->ring_buffer)[dev->ring_tail].cmd[1],
(*dev->ring_buffer)[dev->ring_tail].cmd[2],
(*dev->ring_buffer)[dev->ring_tail].cmd[3],
(*dev->ring_buffer)[dev->ring_tail].cmd[4],
(*dev->ring_buffer)[dev->ring_tail].cmd[5],
(*dev->ring_buffer)[dev->ring_tail].cmd[6],
(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
#if BUFFERED_READS
c = 0;
while ((c < count) && (dev->ring_tail != dev->ring_head)) {
#if COMPRESS_WHEEL_EVENTS
next_tail = (dev->ring_tail+1) % ring_buffer_size;
if (dev->compress_wheel)
cancompress = 1;
while (dev->ring_head != next_tail && cancompress == 1) {
newwheel = (*dev->ring_buffer)[next_tail].cmd[6];
oldwheel = (*dev->ring_buffer)[dev->ring_tail].cmd[6];
/* if both are wheel events, and
no buttons have changes (FIXME, do I have to check?),
and we are the same sign, we can compress +- 7F
*/
dbg_info(&dev->intf->dev,
"%s: trying to compress: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].cmd[0],
(*dev->ring_buffer)[dev->ring_tail].cmd[1],
(*dev->ring_buffer)[dev->ring_tail].cmd[2],
(*dev->ring_buffer)[dev->ring_tail].cmd[3],
(*dev->ring_buffer)[dev->ring_tail].cmd[4],
(*dev->ring_buffer)[dev->ring_tail].cmd[5],
(*dev->ring_buffer)[dev->ring_tail].cmd[6],
(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
if (((*dev->ring_buffer)[dev->ring_tail].cmd[6] != 0 &&
(*dev->ring_buffer)[next_tail].cmd[6] != 0) &&
((newwheel > 0 && oldwheel > 0) ||
(newwheel < 0 && oldwheel < 0)) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[2] ==
(*dev->ring_buffer)[next_tail].cmd[2]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[3] ==
(*dev->ring_buffer)[next_tail].cmd[3]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[4] ==
(*dev->ring_buffer)[next_tail].cmd[4]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[5] ==
(*dev->ring_buffer)[next_tail].cmd[5])) {
dbg_info(&dev->intf->dev,
"%s: should compress: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].
cmd[0],
(*dev->ring_buffer)[dev->ring_tail].
cmd[1],
(*dev->ring_buffer)[dev->ring_tail].
cmd[2],
(*dev->ring_buffer)[dev->ring_tail].
cmd[3],
(*dev->ring_buffer)[dev->ring_tail].
cmd[4],
(*dev->ring_buffer)[dev->ring_tail].
cmd[5],
(*dev->ring_buffer)[dev->ring_tail].
cmd[6],
(*dev->ring_buffer)[dev->ring_tail].
cmd[7]);
newwheel += oldwheel;
if (oldwheel > 0 && !(newwheel > 0)) {
newwheel = 0x7f;
cancompress = 0;
}
if (oldwheel < 0 && !(newwheel < 0)) {
newwheel = 0x80;
cancompress = 0;
}
(*dev->ring_buffer)[next_tail].cmd[6] =
newwheel;
dev->ring_tail = next_tail;
next_tail =
(dev->ring_tail + 1) % ring_buffer_size;
} else {
cancompress = 0;
}
}
#endif /* COMPRESS_WHEEL_EVENTS */
if (copy_to_user(
&buffer[c],
&(*dev->ring_buffer)[dev->ring_tail], 8)) {
retval = -EFAULT;
goto unlock_exit;
}
dev->ring_tail = (dev->ring_tail + 1) % ring_buffer_size;
c += 8;
dbg_info(&dev->intf->dev,
"%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
}
retval = c;
#else
/* if (copy_to_user(buffer, &(*dev->ring_buffer)[dev->ring_tail], 8)) { */
retval = -EFAULT;
goto unlock_exit;
}
dev->ring_tail = (dev->ring_tail + 1) % ring_buffer_size;
dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
retval = 8;
#endif /* BUFFERED_READS */
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/**
* usb_tranzport_write
*/
static ssize_t usb_tranzport_write(struct file *file,
const char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_tranzport *dev;
size_t bytes_to_write;
int retval = 0;
dev = file->private_data;
/* verify that we actually have some data to write */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */
if (dev->intf == NULL) {
retval = -ENODEV;
err("No device or device unplugged %d\n", retval);
goto unlock_exit;
}
/* wait until previous transfer is finished */
if (dev->interrupt_out_busy) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
retval = wait_event_interruptible(dev->write_wait,
!dev->interrupt_out_busy);
if (retval < 0)
goto unlock_exit;
}
/* write the data into interrupt_out_buffer from userspace */
bytes_to_write = min(count,
write_buffer_size *
dev->interrupt_out_endpoint_size);
if (bytes_to_write < count)
dev_warn(&dev->intf->dev,
"Write buffer overflow, %zd bytes dropped\n",
count - bytes_to_write);
dbg_info(&dev->intf->dev,
"%s: count = %zd, bytes_to_write = %zd\n", __func__,
count, bytes_to_write);
if (copy_from_user(dev->interrupt_out_buffer, buffer, bytes_to_write)) {
retval = -EFAULT;
goto unlock_exit;
}
if (dev->interrupt_out_endpoint == NULL) {
err("Endpoint should not be be null!\n");
goto unlock_exit;
}
/* send off the urb */
usb_fill_int_urb(dev->interrupt_out_urb,
interface_to_usbdev(dev->intf),
usb_sndintpipe(interface_to_usbdev(dev->intf),
dev->interrupt_out_endpoint->
bEndpointAddress),
dev->interrupt_out_buffer, bytes_to_write,
usb_tranzport_interrupt_out_callback, dev,
dev->interrupt_out_interval);
dev->interrupt_out_busy = 1;
wmb();
retval = usb_submit_urb(dev->interrupt_out_urb, GFP_KERNEL);
if (retval) {
dev->interrupt_out_busy = 0;
err("Couldn't submit interrupt_out_urb %d\n", retval);
goto unlock_exit;
}
retval = bytes_to_write;
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/* file operations needed when we register this driver */
static const struct file_operations usb_tranzport_fops = {
.owner = THIS_MODULE,
.read = usb_tranzport_read,
.write = usb_tranzport_write,
.open = usb_tranzport_open,
.release = usb_tranzport_release,
.poll = usb_tranzport_poll,
.llseek = no_llseek,
};
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver usb_tranzport_class = {
.name = "tranzport%d",
.fops = &usb_tranzport_fops,
.minor_base = USB_TRANZPORT_MINOR_BASE,
};
/**
* usb_tranzport_probe
*
* Called by the usb core when a new device is connected that it thinks
* this driver might be interested in.
*/
static int usb_tranzport_probe(struct usb_interface *intf,
const struct usb_device_id *id) {
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_tranzport *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
int true_size;
int retval = -ENOMEM;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
dev_err(&intf->dev, "Out of memory\n");
goto exit;
}
mutex_init(&dev->mtx);
dev->intf = intf;
init_waitqueue_head(&dev->read_wait);
init_waitqueue_head(&dev->write_wait);
iface_desc = intf->cur_altsetting;
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint))
dev->interrupt_in_endpoint = endpoint;
if (usb_endpoint_is_int_out(endpoint))
dev->interrupt_out_endpoint = endpoint;
}
if (dev->interrupt_in_endpoint == NULL) {
dev_err(&intf->dev, "Interrupt in endpoint not found\n");
goto error;
}
if (dev->interrupt_out_endpoint == NULL)
dev_warn(&intf->dev,
"Interrupt out endpoint not found"
"(using control endpoint instead)\n");
dev->interrupt_in_endpoint_size =
le16_to_cpu(dev->interrupt_in_endpoint->wMaxPacketSize);
if (dev->interrupt_in_endpoint_size != 8)
dev_warn(&intf->dev, "Interrupt in endpoint size is not 8!\n");
if (ring_buffer_size == 0)
ring_buffer_size = RING_BUFFER_SIZE;
true_size = min(ring_buffer_size, RING_BUFFER_SIZE);
/* FIXME - there are more usb_alloc routines for dma correctness.
Needed? */
dev->ring_buffer =
kmalloc((true_size * sizeof(struct tranzport_cmd)) + 8, GFP_KERNEL);
if (!dev->ring_buffer) {
dev_err(&intf->dev,
"Couldn't allocate ring_buffer size %d\n", true_size);
goto error;
}
dev->interrupt_in_buffer =
kmalloc(dev->interrupt_in_endpoint_size, GFP_KERNEL);
if (!dev->interrupt_in_buffer) {
dev_err(&intf->dev, "Couldn't allocate interrupt_in_buffer\n");
goto error;
}
dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_in_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_in_urb\n");
goto error;
}
dev->interrupt_out_endpoint_size =
dev->interrupt_out_endpoint ?
le16_to_cpu(dev->interrupt_out_endpoint->wMaxPacketSize) :
udev->descriptor.bMaxPacketSize0;
if (dev->interrupt_out_endpoint_size != 8)
dev_warn(&intf->dev,
"Interrupt out endpoint size is not 8!)\n");
dev->interrupt_out_buffer =
kmalloc(write_buffer_size * dev->interrupt_out_endpoint_size,
GFP_KERNEL);
if (!dev->interrupt_out_buffer) {
dev_err(&intf->dev, "Couldn't allocate interrupt_out_buffer\n");
goto error;
}
dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_out_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_out_urb\n");
goto error;
}
dev->interrupt_in_interval =
min_interrupt_in_interval >
dev->interrupt_in_endpoint->bInterval ? min_interrupt_in_interval
: dev->interrupt_in_endpoint->bInterval;
if (dev->interrupt_out_endpoint) {
dev->interrupt_out_interval =
min_interrupt_out_interval >
dev->interrupt_out_endpoint->bInterval ?
min_interrupt_out_interval :
dev->interrupt_out_endpoint->bInterval;
}
/* we can register the device now, as it is ready */
usb_set_intfdata(intf, dev);
retval = usb_register_dev(intf, &usb_tranzport_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(&intf->dev,
"Not able to get a minor for this device.\n");
usb_set_intfdata(intf, NULL);
goto error;
}
retval = device_create_file(&intf->dev, &dev_attr_compress_wheel);
if (retval)
goto error;
retval = device_create_file(&intf->dev, &dev_attr_enable);
if (retval)
goto error;
retval = device_create_file(&intf->dev, &dev_attr_offline);
if (retval)
goto error;
/* let the user know what node this device is now attached to */
dev_info(&intf->dev,
"Tranzport Device #%d now attached to major %d minor %d\n",
(intf->minor - USB_TRANZPORT_MINOR_BASE), USB_MAJOR,
intf->minor);
exit:
return retval;
error:
usb_tranzport_delete(dev);
return retval;
}
/**
* usb_tranzport_disconnect
*
* Called by the usb core when the device is removed from the system.
*/
static void usb_tranzport_disconnect(struct usb_interface *intf)
{
struct usb_tranzport *dev;
int minor;
mutex_lock(&disconnect_mutex);
dev = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
mutex_lock(&dev->mtx);
minor = intf->minor;
/* give back our minor */
usb_deregister_dev(intf, &usb_tranzport_class);
/* if the device is not opened, then we clean up right now */
if (!dev->open_count) {
mutex_unlock(&dev->mtx);
usb_tranzport_delete(dev);
} else {
dev->intf = NULL;
mutex_unlock(&dev->mtx);
}
mutex_unlock(&disconnect_mutex);
dev_info(&intf->dev, "Tranzport Surface #%d now disconnected\n",
(minor - USB_TRANZPORT_MINOR_BASE));
}
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver usb_tranzport_driver = {
.name = "tranzport",
.probe = usb_tranzport_probe,
.disconnect = usb_tranzport_disconnect,
.id_table = usb_tranzport_table,
};
/**
* usb_tranzport_init
*/
static int __init usb_tranzport_init(void)
{
int retval;
/* register this driver with the USB subsystem */
retval = usb_register(&usb_tranzport_driver);
if (retval)
err("usb_register failed for the " __FILE__
" driver. Error number %d\n", retval);
return retval;
}
/**
* usb_tranzport_exit
*/
static void __exit usb_tranzport_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&usb_tranzport_driver);
}
module_init(usb_tranzport_init);
module_exit(usb_tranzport_exit);
| gpl-2.0 |
indorocker/kernel-cm10.1-3.4 | arch/mips/ath79/mach-ap121.c | 4779 | 2191 | /*
* Atheros AP121 board support
*
* Copyright (C) 2011 Gabor Juhos <juhosg@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "machtypes.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-spi.h"
#include "dev-usb.h"
#include "dev-wmac.h"
#define AP121_GPIO_LED_WLAN 0
#define AP121_GPIO_LED_USB 1
#define AP121_GPIO_BTN_JUMPSTART 11
#define AP121_GPIO_BTN_RESET 12
#define AP121_KEYS_POLL_INTERVAL 20 /* msecs */
#define AP121_KEYS_DEBOUNCE_INTERVAL (3 * AP121_KEYS_POLL_INTERVAL)
#define AP121_CAL_DATA_ADDR 0x1fff1000
static struct gpio_led ap121_leds_gpio[] __initdata = {
{
.name = "ap121:green:usb",
.gpio = AP121_GPIO_LED_USB,
.active_low = 0,
},
{
.name = "ap121:green:wlan",
.gpio = AP121_GPIO_LED_WLAN,
.active_low = 0,
},
};
static struct gpio_keys_button ap121_gpio_keys[] __initdata = {
{
.desc = "jumpstart button",
.type = EV_KEY,
.code = KEY_WPS_BUTTON,
.debounce_interval = AP121_KEYS_DEBOUNCE_INTERVAL,
.gpio = AP121_GPIO_BTN_JUMPSTART,
.active_low = 1,
},
{
.desc = "reset button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = AP121_KEYS_DEBOUNCE_INTERVAL,
.gpio = AP121_GPIO_BTN_RESET,
.active_low = 1,
}
};
static struct spi_board_info ap121_spi_info[] = {
{
.bus_num = 0,
.chip_select = 0,
.max_speed_hz = 25000000,
.modalias = "mx25l1606e",
}
};
static struct ath79_spi_platform_data ap121_spi_data = {
.bus_num = 0,
.num_chipselect = 1,
};
static void __init ap121_setup(void)
{
u8 *cal_data = (u8 *) KSEG1ADDR(AP121_CAL_DATA_ADDR);
ath79_register_leds_gpio(-1, ARRAY_SIZE(ap121_leds_gpio),
ap121_leds_gpio);
ath79_register_gpio_keys_polled(-1, AP121_KEYS_POLL_INTERVAL,
ARRAY_SIZE(ap121_gpio_keys),
ap121_gpio_keys);
ath79_register_spi(&ap121_spi_data, ap121_spi_info,
ARRAY_SIZE(ap121_spi_info));
ath79_register_usb();
ath79_register_wmac(cal_data);
}
MIPS_MACHINE(ATH79_MACH_AP121, "AP121", "Atheros AP121 reference board",
ap121_setup);
| gpl-2.0 |
sicknemesis/AK-OnePone | arch/arm/plat-mxc/3ds_debugboard.c | 4779 | 5663 | /*
* 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/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/smsc911x.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <mach/hardware.h>
/* LAN9217 ethernet base address */
#define LAN9217_BASE_ADDR(n) (n + 0x0)
/* External UART */
#define UARTA_BASE_ADDR(n) (n + 0x8000)
#define UARTB_BASE_ADDR(n) (n + 0x10000)
#define BOARD_IO_ADDR(n) (n + 0x20000)
/* LED switchs */
#define LED_SWITCH_REG 0x00
/* buttons */
#define SWITCH_BUTTONS_REG 0x08
/* status, interrupt */
#define INTR_STATUS_REG 0x10
#define INTR_MASK_REG 0x38
#define INTR_RESET_REG 0x20
/* magic word for debug CPLD */
#define MAGIC_NUMBER1_REG 0x40
#define MAGIC_NUMBER2_REG 0x48
/* CPLD code version */
#define CPLD_CODE_VER_REG 0x50
/* magic word for debug CPLD */
#define MAGIC_NUMBER3_REG 0x58
/* module reset register*/
#define MODULE_RESET_REG 0x60
/* CPU ID and Personality ID */
#define MCU_BOARD_ID_REG 0x68
#define MXC_IRQ_TO_EXPIO(irq) ((irq) - MXC_BOARD_IRQ_START)
#define MXC_IRQ_TO_GPIO(irq) ((irq) - MXC_INTERNAL_IRQS)
#define MXC_EXP_IO_BASE (MXC_BOARD_IRQ_START)
#define MXC_MAX_EXP_IO_LINES 16
/* interrupts like external uart , external ethernet etc*/
#define EXPIO_INT_ENET (MXC_BOARD_IRQ_START + 0)
#define EXPIO_INT_XUART_A (MXC_BOARD_IRQ_START + 1)
#define EXPIO_INT_XUART_B (MXC_BOARD_IRQ_START + 2)
#define EXPIO_INT_BUTTON_A (MXC_BOARD_IRQ_START + 3)
#define EXPIO_INT_BUTTON_B (MXC_BOARD_IRQ_START + 4)
static void __iomem *brd_io;
static struct resource smsc911x_resources[] = {
{
.flags = IORESOURCE_MEM,
} , {
.start = EXPIO_INT_ENET,
.end = EXPIO_INT_ENET,
.flags = IORESOURCE_IRQ,
},
};
static struct smsc911x_platform_config smsc911x_config = {
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.flags = SMSC911X_USE_32BIT | SMSC911X_FORCE_INTERNAL_PHY,
};
static struct platform_device smsc_lan9217_device = {
.name = "smsc911x",
.id = -1,
.dev = {
.platform_data = &smsc911x_config,
},
.num_resources = ARRAY_SIZE(smsc911x_resources),
.resource = smsc911x_resources,
};
static void mxc_expio_irq_handler(u32 irq, struct irq_desc *desc)
{
u32 imr_val;
u32 int_valid;
u32 expio_irq;
/* irq = gpio irq number */
desc->irq_data.chip->irq_mask(&desc->irq_data);
imr_val = __raw_readw(brd_io + INTR_MASK_REG);
int_valid = __raw_readw(brd_io + INTR_STATUS_REG) & ~imr_val;
expio_irq = MXC_BOARD_IRQ_START;
for (; int_valid != 0; int_valid >>= 1, expio_irq++) {
if ((int_valid & 1) == 0)
continue;
generic_handle_irq(expio_irq);
}
desc->irq_data.chip->irq_ack(&desc->irq_data);
desc->irq_data.chip->irq_unmask(&desc->irq_data);
}
/*
* Disable an expio pin's interrupt by setting the bit in the imr.
* Irq is an expio virtual irq number
*/
static void expio_mask_irq(struct irq_data *d)
{
u16 reg;
u32 expio = MXC_IRQ_TO_EXPIO(d->irq);
reg = __raw_readw(brd_io + INTR_MASK_REG);
reg |= (1 << expio);
__raw_writew(reg, brd_io + INTR_MASK_REG);
}
static void expio_ack_irq(struct irq_data *d)
{
u32 expio = MXC_IRQ_TO_EXPIO(d->irq);
__raw_writew(1 << expio, brd_io + INTR_RESET_REG);
__raw_writew(0, brd_io + INTR_RESET_REG);
expio_mask_irq(d);
}
static void expio_unmask_irq(struct irq_data *d)
{
u16 reg;
u32 expio = MXC_IRQ_TO_EXPIO(d->irq);
reg = __raw_readw(brd_io + INTR_MASK_REG);
reg &= ~(1 << expio);
__raw_writew(reg, brd_io + INTR_MASK_REG);
}
static struct irq_chip expio_irq_chip = {
.irq_ack = expio_ack_irq,
.irq_mask = expio_mask_irq,
.irq_unmask = expio_unmask_irq,
};
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vdd33a", "smsc911x"),
REGULATOR_SUPPLY("vddvario", "smsc911x"),
};
int __init mxc_expio_init(u32 base, u32 p_irq)
{
int i;
brd_io = ioremap(BOARD_IO_ADDR(base), SZ_4K);
if (brd_io == NULL)
return -ENOMEM;
if ((__raw_readw(brd_io + MAGIC_NUMBER1_REG) != 0xAAAA) ||
(__raw_readw(brd_io + MAGIC_NUMBER2_REG) != 0x5555) ||
(__raw_readw(brd_io + MAGIC_NUMBER3_REG) != 0xCAFE)) {
pr_info("3-Stack Debug board not detected\n");
iounmap(brd_io);
brd_io = NULL;
return -ENODEV;
}
pr_info("3-Stack Debug board detected, rev = 0x%04X\n",
readw(brd_io + CPLD_CODE_VER_REG));
/*
* Configure INT line as GPIO input
*/
gpio_request(MXC_IRQ_TO_GPIO(p_irq), "expio_pirq");
gpio_direction_input(MXC_IRQ_TO_GPIO(p_irq));
/* disable the interrupt and clear the status */
__raw_writew(0, brd_io + INTR_MASK_REG);
__raw_writew(0xFFFF, brd_io + INTR_RESET_REG);
__raw_writew(0, brd_io + INTR_RESET_REG);
__raw_writew(0x1F, brd_io + INTR_MASK_REG);
for (i = MXC_EXP_IO_BASE;
i < (MXC_EXP_IO_BASE + MXC_MAX_EXP_IO_LINES); i++) {
irq_set_chip_and_handler(i, &expio_irq_chip, handle_level_irq);
set_irq_flags(i, IRQF_VALID);
}
irq_set_irq_type(p_irq, IRQF_TRIGGER_LOW);
irq_set_chained_handler(p_irq, mxc_expio_irq_handler);
/* Register Lan device on the debugboard */
regulator_register_fixed(0, dummy_supplies, ARRAY_SIZE(dummy_supplies));
smsc911x_resources[0].start = LAN9217_BASE_ADDR(base);
smsc911x_resources[0].end = LAN9217_BASE_ADDR(base) + 0x100 - 1;
platform_device_register(&smsc_lan9217_device);
return 0;
}
| gpl-2.0 |
QduZ9zEVr6/kernel-msm | drivers/dma/amba-pl08x.c | 4779 | 55144 | /*
* Copyright (c) 2006 ARM Ltd.
* Copyright (c) 2010 ST-Ericsson SA
*
* Author: Peter Pearse <peter.pearse@arm.com>
* Author: Linus Walleij <linus.walleij@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, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The full GNU General Public License is in this distribution in the file
* called COPYING.
*
* Documentation: ARM DDI 0196G == PL080
* Documentation: ARM DDI 0218E == PL081
*
* PL080 & PL081 both have 16 sets of DMA signals that can be routed to any
* channel.
*
* The PL080 has 8 channels available for simultaneous use, and the PL081
* has only two channels. So on these DMA controllers the number of channels
* and the number of incoming DMA signals are two totally different things.
* It is usually not possible to theoretically handle all physical signals,
* so a multiplexing scheme with possible denial of use is necessary.
*
* The PL080 has a dual bus master, PL081 has a single master.
*
* Memory to peripheral transfer may be visualized as
* Get data from memory to DMAC
* Until no data left
* On burst request from peripheral
* Destination burst from DMAC to peripheral
* Clear burst request
* Raise terminal count interrupt
*
* For peripherals with a FIFO:
* Source burst size == half the depth of the peripheral FIFO
* Destination burst size == the depth of the peripheral FIFO
*
* (Bursts are irrelevant for mem to mem transfers - there are no burst
* signals, the DMA controller will simply facilitate its AHB master.)
*
* ASSUMES default (little) endianness for DMA transfers
*
* The PL08x has two flow control settings:
* - DMAC flow control: the transfer size defines the number of transfers
* which occur for the current LLI entry, and the DMAC raises TC at the
* end of every LLI entry. Observed behaviour shows the DMAC listening
* to both the BREQ and SREQ signals (contrary to documented),
* transferring data if either is active. The LBREQ and LSREQ signals
* are ignored.
*
* - Peripheral flow control: the transfer size is ignored (and should be
* zero). The data is transferred from the current LLI entry, until
* after the final transfer signalled by LBREQ or LSREQ. The DMAC
* will then move to the next LLI entry.
*
* Global TODO:
* - Break out common code from arch/arm/mach-s3c64xx and share
*/
#include <linux/amba/bus.h>
#include <linux/amba/pl08x.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dmaengine.h>
#include <linux/dmapool.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <asm/hardware/pl080.h>
#include "dmaengine.h"
#define DRIVER_NAME "pl08xdmac"
static struct amba_driver pl08x_amba_driver;
/**
* struct vendor_data - vendor-specific config parameters for PL08x derivatives
* @channels: the number of channels available in this variant
* @dualmaster: whether this version supports dual AHB masters or not.
*/
struct vendor_data {
u8 channels;
bool dualmaster;
};
/*
* PL08X private data structures
* An LLI struct - see PL08x TRM. Note that next uses bit[0] as a bus bit,
* start & end do not - their bus bit info is in cctl. Also note that these
* are fixed 32-bit quantities.
*/
struct pl08x_lli {
u32 src;
u32 dst;
u32 lli;
u32 cctl;
};
/**
* struct pl08x_driver_data - the local state holder for the PL08x
* @slave: slave engine for this instance
* @memcpy: memcpy engine for this instance
* @base: virtual memory base (remapped) for the PL08x
* @adev: the corresponding AMBA (PrimeCell) bus entry
* @vd: vendor data for this PL08x variant
* @pd: platform data passed in from the platform/machine
* @phy_chans: array of data for the physical channels
* @pool: a pool for the LLI descriptors
* @pool_ctr: counter of LLIs in the pool
* @lli_buses: bitmask to or in to LLI pointer selecting AHB port for LLI
* fetches
* @mem_buses: set to indicate memory transfers on AHB2.
* @lock: a spinlock for this struct
*/
struct pl08x_driver_data {
struct dma_device slave;
struct dma_device memcpy;
void __iomem *base;
struct amba_device *adev;
const struct vendor_data *vd;
struct pl08x_platform_data *pd;
struct pl08x_phy_chan *phy_chans;
struct dma_pool *pool;
int pool_ctr;
u8 lli_buses;
u8 mem_buses;
spinlock_t lock;
};
/*
* PL08X specific defines
*/
/* Size (bytes) of each LLI buffer allocated for one transfer */
# define PL08X_LLI_TSFR_SIZE 0x2000
/* Maximum times we call dma_pool_alloc on this pool without freeing */
#define MAX_NUM_TSFR_LLIS (PL08X_LLI_TSFR_SIZE/sizeof(struct pl08x_lli))
#define PL08X_ALIGN 8
static inline struct pl08x_dma_chan *to_pl08x_chan(struct dma_chan *chan)
{
return container_of(chan, struct pl08x_dma_chan, chan);
}
static inline struct pl08x_txd *to_pl08x_txd(struct dma_async_tx_descriptor *tx)
{
return container_of(tx, struct pl08x_txd, tx);
}
/*
* Physical channel handling
*/
/* Whether a certain channel is busy or not */
static int pl08x_phy_channel_busy(struct pl08x_phy_chan *ch)
{
unsigned int val;
val = readl(ch->base + PL080_CH_CONFIG);
return val & PL080_CONFIG_ACTIVE;
}
/*
* Set the initial DMA register values i.e. those for the first LLI
* The next LLI pointer and the configuration interrupt bit have
* been set when the LLIs were constructed. Poke them into the hardware
* and start the transfer.
*/
static void pl08x_start_txd(struct pl08x_dma_chan *plchan,
struct pl08x_txd *txd)
{
struct pl08x_driver_data *pl08x = plchan->host;
struct pl08x_phy_chan *phychan = plchan->phychan;
struct pl08x_lli *lli = &txd->llis_va[0];
u32 val;
plchan->at = txd;
/* Wait for channel inactive */
while (pl08x_phy_channel_busy(phychan))
cpu_relax();
dev_vdbg(&pl08x->adev->dev,
"WRITE channel %d: csrc=0x%08x, cdst=0x%08x, "
"clli=0x%08x, cctl=0x%08x, ccfg=0x%08x\n",
phychan->id, lli->src, lli->dst, lli->lli, lli->cctl,
txd->ccfg);
writel(lli->src, phychan->base + PL080_CH_SRC_ADDR);
writel(lli->dst, phychan->base + PL080_CH_DST_ADDR);
writel(lli->lli, phychan->base + PL080_CH_LLI);
writel(lli->cctl, phychan->base + PL080_CH_CONTROL);
writel(txd->ccfg, phychan->base + PL080_CH_CONFIG);
/* Enable the DMA channel */
/* Do not access config register until channel shows as disabled */
while (readl(pl08x->base + PL080_EN_CHAN) & (1 << phychan->id))
cpu_relax();
/* Do not access config register until channel shows as inactive */
val = readl(phychan->base + PL080_CH_CONFIG);
while ((val & PL080_CONFIG_ACTIVE) || (val & PL080_CONFIG_ENABLE))
val = readl(phychan->base + PL080_CH_CONFIG);
writel(val | PL080_CONFIG_ENABLE, phychan->base + PL080_CH_CONFIG);
}
/*
* Pause the channel by setting the HALT bit.
*
* For M->P transfers, pause the DMAC first and then stop the peripheral -
* the FIFO can only drain if the peripheral is still requesting data.
* (note: this can still timeout if the DMAC FIFO never drains of data.)
*
* For P->M transfers, disable the peripheral first to stop it filling
* the DMAC FIFO, and then pause the DMAC.
*/
static void pl08x_pause_phy_chan(struct pl08x_phy_chan *ch)
{
u32 val;
int timeout;
/* Set the HALT bit and wait for the FIFO to drain */
val = readl(ch->base + PL080_CH_CONFIG);
val |= PL080_CONFIG_HALT;
writel(val, ch->base + PL080_CH_CONFIG);
/* Wait for channel inactive */
for (timeout = 1000; timeout; timeout--) {
if (!pl08x_phy_channel_busy(ch))
break;
udelay(1);
}
if (pl08x_phy_channel_busy(ch))
pr_err("pl08x: channel%u timeout waiting for pause\n", ch->id);
}
static void pl08x_resume_phy_chan(struct pl08x_phy_chan *ch)
{
u32 val;
/* Clear the HALT bit */
val = readl(ch->base + PL080_CH_CONFIG);
val &= ~PL080_CONFIG_HALT;
writel(val, ch->base + PL080_CH_CONFIG);
}
/*
* pl08x_terminate_phy_chan() stops the channel, clears the FIFO and
* clears any pending interrupt status. This should not be used for
* an on-going transfer, but as a method of shutting down a channel
* (eg, when it's no longer used) or terminating a transfer.
*/
static void pl08x_terminate_phy_chan(struct pl08x_driver_data *pl08x,
struct pl08x_phy_chan *ch)
{
u32 val = readl(ch->base + PL080_CH_CONFIG);
val &= ~(PL080_CONFIG_ENABLE | PL080_CONFIG_ERR_IRQ_MASK |
PL080_CONFIG_TC_IRQ_MASK);
writel(val, ch->base + PL080_CH_CONFIG);
writel(1 << ch->id, pl08x->base + PL080_ERR_CLEAR);
writel(1 << ch->id, pl08x->base + PL080_TC_CLEAR);
}
static inline u32 get_bytes_in_cctl(u32 cctl)
{
/* The source width defines the number of bytes */
u32 bytes = cctl & PL080_CONTROL_TRANSFER_SIZE_MASK;
switch (cctl >> PL080_CONTROL_SWIDTH_SHIFT) {
case PL080_WIDTH_8BIT:
break;
case PL080_WIDTH_16BIT:
bytes *= 2;
break;
case PL080_WIDTH_32BIT:
bytes *= 4;
break;
}
return bytes;
}
/* The channel should be paused when calling this */
static u32 pl08x_getbytes_chan(struct pl08x_dma_chan *plchan)
{
struct pl08x_phy_chan *ch;
struct pl08x_txd *txd;
unsigned long flags;
size_t bytes = 0;
spin_lock_irqsave(&plchan->lock, flags);
ch = plchan->phychan;
txd = plchan->at;
/*
* Follow the LLIs to get the number of remaining
* bytes in the currently active transaction.
*/
if (ch && txd) {
u32 clli = readl(ch->base + PL080_CH_LLI) & ~PL080_LLI_LM_AHB2;
/* First get the remaining bytes in the active transfer */
bytes = get_bytes_in_cctl(readl(ch->base + PL080_CH_CONTROL));
if (clli) {
struct pl08x_lli *llis_va = txd->llis_va;
dma_addr_t llis_bus = txd->llis_bus;
int index;
BUG_ON(clli < llis_bus || clli >= llis_bus +
sizeof(struct pl08x_lli) * MAX_NUM_TSFR_LLIS);
/*
* Locate the next LLI - as this is an array,
* it's simple maths to find.
*/
index = (clli - llis_bus) / sizeof(struct pl08x_lli);
for (; index < MAX_NUM_TSFR_LLIS; index++) {
bytes += get_bytes_in_cctl(llis_va[index].cctl);
/*
* A LLI pointer of 0 terminates the LLI list
*/
if (!llis_va[index].lli)
break;
}
}
}
/* Sum up all queued transactions */
if (!list_empty(&plchan->pend_list)) {
struct pl08x_txd *txdi;
list_for_each_entry(txdi, &plchan->pend_list, node) {
struct pl08x_sg *dsg;
list_for_each_entry(dsg, &txd->dsg_list, node)
bytes += dsg->len;
}
}
spin_unlock_irqrestore(&plchan->lock, flags);
return bytes;
}
/*
* Allocate a physical channel for a virtual channel
*
* Try to locate a physical channel to be used for this transfer. If all
* are taken return NULL and the requester will have to cope by using
* some fallback PIO mode or retrying later.
*/
static struct pl08x_phy_chan *
pl08x_get_phy_channel(struct pl08x_driver_data *pl08x,
struct pl08x_dma_chan *virt_chan)
{
struct pl08x_phy_chan *ch = NULL;
unsigned long flags;
int i;
for (i = 0; i < pl08x->vd->channels; i++) {
ch = &pl08x->phy_chans[i];
spin_lock_irqsave(&ch->lock, flags);
if (!ch->serving) {
ch->serving = virt_chan;
ch->signal = -1;
spin_unlock_irqrestore(&ch->lock, flags);
break;
}
spin_unlock_irqrestore(&ch->lock, flags);
}
if (i == pl08x->vd->channels) {
/* No physical channel available, cope with it */
return NULL;
}
pm_runtime_get_sync(&pl08x->adev->dev);
return ch;
}
static inline void pl08x_put_phy_channel(struct pl08x_driver_data *pl08x,
struct pl08x_phy_chan *ch)
{
unsigned long flags;
spin_lock_irqsave(&ch->lock, flags);
/* Stop the channel and clear its interrupts */
pl08x_terminate_phy_chan(pl08x, ch);
pm_runtime_put(&pl08x->adev->dev);
/* Mark it as free */
ch->serving = NULL;
spin_unlock_irqrestore(&ch->lock, flags);
}
/*
* LLI handling
*/
static inline unsigned int pl08x_get_bytes_for_cctl(unsigned int coded)
{
switch (coded) {
case PL080_WIDTH_8BIT:
return 1;
case PL080_WIDTH_16BIT:
return 2;
case PL080_WIDTH_32BIT:
return 4;
default:
break;
}
BUG();
return 0;
}
static inline u32 pl08x_cctl_bits(u32 cctl, u8 srcwidth, u8 dstwidth,
size_t tsize)
{
u32 retbits = cctl;
/* Remove all src, dst and transfer size bits */
retbits &= ~PL080_CONTROL_DWIDTH_MASK;
retbits &= ~PL080_CONTROL_SWIDTH_MASK;
retbits &= ~PL080_CONTROL_TRANSFER_SIZE_MASK;
/* Then set the bits according to the parameters */
switch (srcwidth) {
case 1:
retbits |= PL080_WIDTH_8BIT << PL080_CONTROL_SWIDTH_SHIFT;
break;
case 2:
retbits |= PL080_WIDTH_16BIT << PL080_CONTROL_SWIDTH_SHIFT;
break;
case 4:
retbits |= PL080_WIDTH_32BIT << PL080_CONTROL_SWIDTH_SHIFT;
break;
default:
BUG();
break;
}
switch (dstwidth) {
case 1:
retbits |= PL080_WIDTH_8BIT << PL080_CONTROL_DWIDTH_SHIFT;
break;
case 2:
retbits |= PL080_WIDTH_16BIT << PL080_CONTROL_DWIDTH_SHIFT;
break;
case 4:
retbits |= PL080_WIDTH_32BIT << PL080_CONTROL_DWIDTH_SHIFT;
break;
default:
BUG();
break;
}
retbits |= tsize << PL080_CONTROL_TRANSFER_SIZE_SHIFT;
return retbits;
}
struct pl08x_lli_build_data {
struct pl08x_txd *txd;
struct pl08x_bus_data srcbus;
struct pl08x_bus_data dstbus;
size_t remainder;
u32 lli_bus;
};
/*
* Autoselect a master bus to use for the transfer. Slave will be the chosen as
* victim in case src & dest are not similarly aligned. i.e. If after aligning
* masters address with width requirements of transfer (by sending few byte by
* byte data), slave is still not aligned, then its width will be reduced to
* BYTE.
* - prefers the destination bus if both available
* - prefers bus with fixed address (i.e. peripheral)
*/
static void pl08x_choose_master_bus(struct pl08x_lli_build_data *bd,
struct pl08x_bus_data **mbus, struct pl08x_bus_data **sbus, u32 cctl)
{
if (!(cctl & PL080_CONTROL_DST_INCR)) {
*mbus = &bd->dstbus;
*sbus = &bd->srcbus;
} else if (!(cctl & PL080_CONTROL_SRC_INCR)) {
*mbus = &bd->srcbus;
*sbus = &bd->dstbus;
} else {
if (bd->dstbus.buswidth >= bd->srcbus.buswidth) {
*mbus = &bd->dstbus;
*sbus = &bd->srcbus;
} else {
*mbus = &bd->srcbus;
*sbus = &bd->dstbus;
}
}
}
/*
* Fills in one LLI for a certain transfer descriptor and advance the counter
*/
static void pl08x_fill_lli_for_desc(struct pl08x_lli_build_data *bd,
int num_llis, int len, u32 cctl)
{
struct pl08x_lli *llis_va = bd->txd->llis_va;
dma_addr_t llis_bus = bd->txd->llis_bus;
BUG_ON(num_llis >= MAX_NUM_TSFR_LLIS);
llis_va[num_llis].cctl = cctl;
llis_va[num_llis].src = bd->srcbus.addr;
llis_va[num_llis].dst = bd->dstbus.addr;
llis_va[num_llis].lli = llis_bus + (num_llis + 1) *
sizeof(struct pl08x_lli);
llis_va[num_llis].lli |= bd->lli_bus;
if (cctl & PL080_CONTROL_SRC_INCR)
bd->srcbus.addr += len;
if (cctl & PL080_CONTROL_DST_INCR)
bd->dstbus.addr += len;
BUG_ON(bd->remainder < len);
bd->remainder -= len;
}
static inline void prep_byte_width_lli(struct pl08x_lli_build_data *bd,
u32 *cctl, u32 len, int num_llis, size_t *total_bytes)
{
*cctl = pl08x_cctl_bits(*cctl, 1, 1, len);
pl08x_fill_lli_for_desc(bd, num_llis, len, *cctl);
(*total_bytes) += len;
}
/*
* This fills in the table of LLIs for the transfer descriptor
* Note that we assume we never have to change the burst sizes
* Return 0 for error
*/
static int pl08x_fill_llis_for_desc(struct pl08x_driver_data *pl08x,
struct pl08x_txd *txd)
{
struct pl08x_bus_data *mbus, *sbus;
struct pl08x_lli_build_data bd;
int num_llis = 0;
u32 cctl, early_bytes = 0;
size_t max_bytes_per_lli, total_bytes;
struct pl08x_lli *llis_va;
struct pl08x_sg *dsg;
txd->llis_va = dma_pool_alloc(pl08x->pool, GFP_NOWAIT, &txd->llis_bus);
if (!txd->llis_va) {
dev_err(&pl08x->adev->dev, "%s no memory for llis\n", __func__);
return 0;
}
pl08x->pool_ctr++;
bd.txd = txd;
bd.lli_bus = (pl08x->lli_buses & PL08X_AHB2) ? PL080_LLI_LM_AHB2 : 0;
cctl = txd->cctl;
/* Find maximum width of the source bus */
bd.srcbus.maxwidth =
pl08x_get_bytes_for_cctl((cctl & PL080_CONTROL_SWIDTH_MASK) >>
PL080_CONTROL_SWIDTH_SHIFT);
/* Find maximum width of the destination bus */
bd.dstbus.maxwidth =
pl08x_get_bytes_for_cctl((cctl & PL080_CONTROL_DWIDTH_MASK) >>
PL080_CONTROL_DWIDTH_SHIFT);
list_for_each_entry(dsg, &txd->dsg_list, node) {
total_bytes = 0;
cctl = txd->cctl;
bd.srcbus.addr = dsg->src_addr;
bd.dstbus.addr = dsg->dst_addr;
bd.remainder = dsg->len;
bd.srcbus.buswidth = bd.srcbus.maxwidth;
bd.dstbus.buswidth = bd.dstbus.maxwidth;
pl08x_choose_master_bus(&bd, &mbus, &sbus, cctl);
dev_vdbg(&pl08x->adev->dev, "src=0x%08x%s/%u dst=0x%08x%s/%u len=%zu\n",
bd.srcbus.addr, cctl & PL080_CONTROL_SRC_INCR ? "+" : "",
bd.srcbus.buswidth,
bd.dstbus.addr, cctl & PL080_CONTROL_DST_INCR ? "+" : "",
bd.dstbus.buswidth,
bd.remainder);
dev_vdbg(&pl08x->adev->dev, "mbus=%s sbus=%s\n",
mbus == &bd.srcbus ? "src" : "dst",
sbus == &bd.srcbus ? "src" : "dst");
/*
* Zero length is only allowed if all these requirements are
* met:
* - flow controller is peripheral.
* - src.addr is aligned to src.width
* - dst.addr is aligned to dst.width
*
* sg_len == 1 should be true, as there can be two cases here:
*
* - Memory addresses are contiguous and are not scattered.
* Here, Only one sg will be passed by user driver, with
* memory address and zero length. We pass this to controller
* and after the transfer it will receive the last burst
* request from peripheral and so transfer finishes.
*
* - Memory addresses are scattered and are not contiguous.
* Here, Obviously as DMA controller doesn't know when a lli's
* transfer gets over, it can't load next lli. So in this
* case, there has to be an assumption that only one lli is
* supported. Thus, we can't have scattered addresses.
*/
if (!bd.remainder) {
u32 fc = (txd->ccfg & PL080_CONFIG_FLOW_CONTROL_MASK) >>
PL080_CONFIG_FLOW_CONTROL_SHIFT;
if (!((fc >= PL080_FLOW_SRC2DST_DST) &&
(fc <= PL080_FLOW_SRC2DST_SRC))) {
dev_err(&pl08x->adev->dev, "%s sg len can't be zero",
__func__);
return 0;
}
if ((bd.srcbus.addr % bd.srcbus.buswidth) ||
(bd.dstbus.addr % bd.dstbus.buswidth)) {
dev_err(&pl08x->adev->dev,
"%s src & dst address must be aligned to src"
" & dst width if peripheral is flow controller",
__func__);
return 0;
}
cctl = pl08x_cctl_bits(cctl, bd.srcbus.buswidth,
bd.dstbus.buswidth, 0);
pl08x_fill_lli_for_desc(&bd, num_llis++, 0, cctl);
break;
}
/*
* Send byte by byte for following cases
* - Less than a bus width available
* - until master bus is aligned
*/
if (bd.remainder < mbus->buswidth)
early_bytes = bd.remainder;
else if ((mbus->addr) % (mbus->buswidth)) {
early_bytes = mbus->buswidth - (mbus->addr) %
(mbus->buswidth);
if ((bd.remainder - early_bytes) < mbus->buswidth)
early_bytes = bd.remainder;
}
if (early_bytes) {
dev_vdbg(&pl08x->adev->dev,
"%s byte width LLIs (remain 0x%08x)\n",
__func__, bd.remainder);
prep_byte_width_lli(&bd, &cctl, early_bytes, num_llis++,
&total_bytes);
}
if (bd.remainder) {
/*
* Master now aligned
* - if slave is not then we must set its width down
*/
if (sbus->addr % sbus->buswidth) {
dev_dbg(&pl08x->adev->dev,
"%s set down bus width to one byte\n",
__func__);
sbus->buswidth = 1;
}
/*
* Bytes transferred = tsize * src width, not
* MIN(buswidths)
*/
max_bytes_per_lli = bd.srcbus.buswidth *
PL080_CONTROL_TRANSFER_SIZE_MASK;
dev_vdbg(&pl08x->adev->dev,
"%s max bytes per lli = %zu\n",
__func__, max_bytes_per_lli);
/*
* Make largest possible LLIs until less than one bus
* width left
*/
while (bd.remainder > (mbus->buswidth - 1)) {
size_t lli_len, tsize, width;
/*
* If enough left try to send max possible,
* otherwise try to send the remainder
*/
lli_len = min(bd.remainder, max_bytes_per_lli);
/*
* Check against maximum bus alignment:
* Calculate actual transfer size in relation to
* bus width an get a maximum remainder of the
* highest bus width - 1
*/
width = max(mbus->buswidth, sbus->buswidth);
lli_len = (lli_len / width) * width;
tsize = lli_len / bd.srcbus.buswidth;
dev_vdbg(&pl08x->adev->dev,
"%s fill lli with single lli chunk of "
"size 0x%08zx (remainder 0x%08zx)\n",
__func__, lli_len, bd.remainder);
cctl = pl08x_cctl_bits(cctl, bd.srcbus.buswidth,
bd.dstbus.buswidth, tsize);
pl08x_fill_lli_for_desc(&bd, num_llis++,
lli_len, cctl);
total_bytes += lli_len;
}
/*
* Send any odd bytes
*/
if (bd.remainder) {
dev_vdbg(&pl08x->adev->dev,
"%s align with boundary, send odd bytes (remain %zu)\n",
__func__, bd.remainder);
prep_byte_width_lli(&bd, &cctl, bd.remainder,
num_llis++, &total_bytes);
}
}
if (total_bytes != dsg->len) {
dev_err(&pl08x->adev->dev,
"%s size of encoded lli:s don't match total txd, transferred 0x%08zx from size 0x%08zx\n",
__func__, total_bytes, dsg->len);
return 0;
}
if (num_llis >= MAX_NUM_TSFR_LLIS) {
dev_err(&pl08x->adev->dev,
"%s need to increase MAX_NUM_TSFR_LLIS from 0x%08x\n",
__func__, (u32) MAX_NUM_TSFR_LLIS);
return 0;
}
}
llis_va = txd->llis_va;
/* The final LLI terminates the LLI. */
llis_va[num_llis - 1].lli = 0;
/* The final LLI element shall also fire an interrupt. */
llis_va[num_llis - 1].cctl |= PL080_CONTROL_TC_IRQ_EN;
#ifdef VERBOSE_DEBUG
{
int i;
dev_vdbg(&pl08x->adev->dev,
"%-3s %-9s %-10s %-10s %-10s %s\n",
"lli", "", "csrc", "cdst", "clli", "cctl");
for (i = 0; i < num_llis; i++) {
dev_vdbg(&pl08x->adev->dev,
"%3d @%p: 0x%08x 0x%08x 0x%08x 0x%08x\n",
i, &llis_va[i], llis_va[i].src,
llis_va[i].dst, llis_va[i].lli, llis_va[i].cctl
);
}
}
#endif
return num_llis;
}
/* You should call this with the struct pl08x lock held */
static void pl08x_free_txd(struct pl08x_driver_data *pl08x,
struct pl08x_txd *txd)
{
struct pl08x_sg *dsg, *_dsg;
/* Free the LLI */
if (txd->llis_va)
dma_pool_free(pl08x->pool, txd->llis_va, txd->llis_bus);
pl08x->pool_ctr--;
list_for_each_entry_safe(dsg, _dsg, &txd->dsg_list, node) {
list_del(&dsg->node);
kfree(dsg);
}
kfree(txd);
}
static void pl08x_free_txd_list(struct pl08x_driver_data *pl08x,
struct pl08x_dma_chan *plchan)
{
struct pl08x_txd *txdi = NULL;
struct pl08x_txd *next;
if (!list_empty(&plchan->pend_list)) {
list_for_each_entry_safe(txdi,
next, &plchan->pend_list, node) {
list_del(&txdi->node);
pl08x_free_txd(pl08x, txdi);
}
}
}
/*
* The DMA ENGINE API
*/
static int pl08x_alloc_chan_resources(struct dma_chan *chan)
{
return 0;
}
static void pl08x_free_chan_resources(struct dma_chan *chan)
{
}
/*
* This should be called with the channel plchan->lock held
*/
static int prep_phy_channel(struct pl08x_dma_chan *plchan,
struct pl08x_txd *txd)
{
struct pl08x_driver_data *pl08x = plchan->host;
struct pl08x_phy_chan *ch;
int ret;
/* Check if we already have a channel */
if (plchan->phychan) {
ch = plchan->phychan;
goto got_channel;
}
ch = pl08x_get_phy_channel(pl08x, plchan);
if (!ch) {
/* No physical channel available, cope with it */
dev_dbg(&pl08x->adev->dev, "no physical channel available for xfer on %s\n", plchan->name);
return -EBUSY;
}
/*
* OK we have a physical channel: for memcpy() this is all we
* need, but for slaves the physical signals may be muxed!
* Can the platform allow us to use this channel?
*/
if (plchan->slave && pl08x->pd->get_signal) {
ret = pl08x->pd->get_signal(plchan);
if (ret < 0) {
dev_dbg(&pl08x->adev->dev,
"unable to use physical channel %d for transfer on %s due to platform restrictions\n",
ch->id, plchan->name);
/* Release physical channel & return */
pl08x_put_phy_channel(pl08x, ch);
return -EBUSY;
}
ch->signal = ret;
}
plchan->phychan = ch;
dev_dbg(&pl08x->adev->dev, "allocated physical channel %d and signal %d for xfer on %s\n",
ch->id,
ch->signal,
plchan->name);
got_channel:
/* Assign the flow control signal to this channel */
if (txd->direction == DMA_MEM_TO_DEV)
txd->ccfg |= ch->signal << PL080_CONFIG_DST_SEL_SHIFT;
else if (txd->direction == DMA_DEV_TO_MEM)
txd->ccfg |= ch->signal << PL080_CONFIG_SRC_SEL_SHIFT;
plchan->phychan_hold++;
return 0;
}
static void release_phy_channel(struct pl08x_dma_chan *plchan)
{
struct pl08x_driver_data *pl08x = plchan->host;
if ((plchan->phychan->signal >= 0) && pl08x->pd->put_signal) {
pl08x->pd->put_signal(plchan);
plchan->phychan->signal = -1;
}
pl08x_put_phy_channel(pl08x, plchan->phychan);
plchan->phychan = NULL;
}
static dma_cookie_t pl08x_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(tx->chan);
struct pl08x_txd *txd = to_pl08x_txd(tx);
unsigned long flags;
dma_cookie_t cookie;
spin_lock_irqsave(&plchan->lock, flags);
cookie = dma_cookie_assign(tx);
/* Put this onto the pending list */
list_add_tail(&txd->node, &plchan->pend_list);
/*
* If there was no physical channel available for this memcpy,
* stack the request up and indicate that the channel is waiting
* for a free physical channel.
*/
if (!plchan->slave && !plchan->phychan) {
/* Do this memcpy whenever there is a channel ready */
plchan->state = PL08X_CHAN_WAITING;
plchan->waiting = txd;
} else {
plchan->phychan_hold--;
}
spin_unlock_irqrestore(&plchan->lock, flags);
return cookie;
}
static struct dma_async_tx_descriptor *pl08x_prep_dma_interrupt(
struct dma_chan *chan, unsigned long flags)
{
struct dma_async_tx_descriptor *retval = NULL;
return retval;
}
/*
* Code accessing dma_async_is_complete() in a tight loop may give problems.
* If slaves are relying on interrupts to signal completion this function
* must not be called with interrupts disabled.
*/
static enum dma_status pl08x_dma_tx_status(struct dma_chan *chan,
dma_cookie_t cookie, struct dma_tx_state *txstate)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
enum dma_status ret;
ret = dma_cookie_status(chan, cookie, txstate);
if (ret == DMA_SUCCESS)
return ret;
/*
* This cookie not complete yet
* Get number of bytes left in the active transactions and queue
*/
dma_set_residue(txstate, pl08x_getbytes_chan(plchan));
if (plchan->state == PL08X_CHAN_PAUSED)
return DMA_PAUSED;
/* Whether waiting or running, we're in progress */
return DMA_IN_PROGRESS;
}
/* PrimeCell DMA extension */
struct burst_table {
u32 burstwords;
u32 reg;
};
static const struct burst_table burst_sizes[] = {
{
.burstwords = 256,
.reg = PL080_BSIZE_256,
},
{
.burstwords = 128,
.reg = PL080_BSIZE_128,
},
{
.burstwords = 64,
.reg = PL080_BSIZE_64,
},
{
.burstwords = 32,
.reg = PL080_BSIZE_32,
},
{
.burstwords = 16,
.reg = PL080_BSIZE_16,
},
{
.burstwords = 8,
.reg = PL080_BSIZE_8,
},
{
.burstwords = 4,
.reg = PL080_BSIZE_4,
},
{
.burstwords = 0,
.reg = PL080_BSIZE_1,
},
};
/*
* Given the source and destination available bus masks, select which
* will be routed to each port. We try to have source and destination
* on separate ports, but always respect the allowable settings.
*/
static u32 pl08x_select_bus(u8 src, u8 dst)
{
u32 cctl = 0;
if (!(dst & PL08X_AHB1) || ((dst & PL08X_AHB2) && (src & PL08X_AHB1)))
cctl |= PL080_CONTROL_DST_AHB2;
if (!(src & PL08X_AHB1) || ((src & PL08X_AHB2) && !(dst & PL08X_AHB2)))
cctl |= PL080_CONTROL_SRC_AHB2;
return cctl;
}
static u32 pl08x_cctl(u32 cctl)
{
cctl &= ~(PL080_CONTROL_SRC_AHB2 | PL080_CONTROL_DST_AHB2 |
PL080_CONTROL_SRC_INCR | PL080_CONTROL_DST_INCR |
PL080_CONTROL_PROT_MASK);
/* Access the cell in privileged mode, non-bufferable, non-cacheable */
return cctl | PL080_CONTROL_PROT_SYS;
}
static u32 pl08x_width(enum dma_slave_buswidth width)
{
switch (width) {
case DMA_SLAVE_BUSWIDTH_1_BYTE:
return PL080_WIDTH_8BIT;
case DMA_SLAVE_BUSWIDTH_2_BYTES:
return PL080_WIDTH_16BIT;
case DMA_SLAVE_BUSWIDTH_4_BYTES:
return PL080_WIDTH_32BIT;
default:
return ~0;
}
}
static u32 pl08x_burst(u32 maxburst)
{
int i;
for (i = 0; i < ARRAY_SIZE(burst_sizes); i++)
if (burst_sizes[i].burstwords <= maxburst)
break;
return burst_sizes[i].reg;
}
static int dma_set_runtime_config(struct dma_chan *chan,
struct dma_slave_config *config)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
struct pl08x_driver_data *pl08x = plchan->host;
enum dma_slave_buswidth addr_width;
u32 width, burst, maxburst;
u32 cctl = 0;
if (!plchan->slave)
return -EINVAL;
/* Transfer direction */
plchan->runtime_direction = config->direction;
if (config->direction == DMA_MEM_TO_DEV) {
addr_width = config->dst_addr_width;
maxburst = config->dst_maxburst;
} else if (config->direction == DMA_DEV_TO_MEM) {
addr_width = config->src_addr_width;
maxburst = config->src_maxburst;
} else {
dev_err(&pl08x->adev->dev,
"bad runtime_config: alien transfer direction\n");
return -EINVAL;
}
width = pl08x_width(addr_width);
if (width == ~0) {
dev_err(&pl08x->adev->dev,
"bad runtime_config: alien address width\n");
return -EINVAL;
}
cctl |= width << PL080_CONTROL_SWIDTH_SHIFT;
cctl |= width << PL080_CONTROL_DWIDTH_SHIFT;
/*
* If this channel will only request single transfers, set this
* down to ONE element. Also select one element if no maxburst
* is specified.
*/
if (plchan->cd->single)
maxburst = 1;
burst = pl08x_burst(maxburst);
cctl |= burst << PL080_CONTROL_SB_SIZE_SHIFT;
cctl |= burst << PL080_CONTROL_DB_SIZE_SHIFT;
plchan->device_fc = config->device_fc;
if (plchan->runtime_direction == DMA_DEV_TO_MEM) {
plchan->src_addr = config->src_addr;
plchan->src_cctl = pl08x_cctl(cctl) | PL080_CONTROL_DST_INCR |
pl08x_select_bus(plchan->cd->periph_buses,
pl08x->mem_buses);
} else {
plchan->dst_addr = config->dst_addr;
plchan->dst_cctl = pl08x_cctl(cctl) | PL080_CONTROL_SRC_INCR |
pl08x_select_bus(pl08x->mem_buses,
plchan->cd->periph_buses);
}
dev_dbg(&pl08x->adev->dev,
"configured channel %s (%s) for %s, data width %d, "
"maxburst %d words, LE, CCTL=0x%08x\n",
dma_chan_name(chan), plchan->name,
(config->direction == DMA_DEV_TO_MEM) ? "RX" : "TX",
addr_width,
maxburst,
cctl);
return 0;
}
/*
* Slave transactions callback to the slave device to allow
* synchronization of slave DMA signals with the DMAC enable
*/
static void pl08x_issue_pending(struct dma_chan *chan)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
unsigned long flags;
spin_lock_irqsave(&plchan->lock, flags);
/* Something is already active, or we're waiting for a channel... */
if (plchan->at || plchan->state == PL08X_CHAN_WAITING) {
spin_unlock_irqrestore(&plchan->lock, flags);
return;
}
/* Take the first element in the queue and execute it */
if (!list_empty(&plchan->pend_list)) {
struct pl08x_txd *next;
next = list_first_entry(&plchan->pend_list,
struct pl08x_txd,
node);
list_del(&next->node);
plchan->state = PL08X_CHAN_RUNNING;
pl08x_start_txd(plchan, next);
}
spin_unlock_irqrestore(&plchan->lock, flags);
}
static int pl08x_prep_channel_resources(struct pl08x_dma_chan *plchan,
struct pl08x_txd *txd)
{
struct pl08x_driver_data *pl08x = plchan->host;
unsigned long flags;
int num_llis, ret;
num_llis = pl08x_fill_llis_for_desc(pl08x, txd);
if (!num_llis) {
spin_lock_irqsave(&plchan->lock, flags);
pl08x_free_txd(pl08x, txd);
spin_unlock_irqrestore(&plchan->lock, flags);
return -EINVAL;
}
spin_lock_irqsave(&plchan->lock, flags);
/*
* See if we already have a physical channel allocated,
* else this is the time to try to get one.
*/
ret = prep_phy_channel(plchan, txd);
if (ret) {
/*
* No physical channel was available.
*
* memcpy transfers can be sorted out at submission time.
*
* Slave transfers may have been denied due to platform
* channel muxing restrictions. Since there is no guarantee
* that this will ever be resolved, and the signal must be
* acquired AFTER acquiring the physical channel, we will let
* them be NACK:ed with -EBUSY here. The drivers can retry
* the prep() call if they are eager on doing this using DMA.
*/
if (plchan->slave) {
pl08x_free_txd_list(pl08x, plchan);
pl08x_free_txd(pl08x, txd);
spin_unlock_irqrestore(&plchan->lock, flags);
return -EBUSY;
}
} else
/*
* Else we're all set, paused and ready to roll, status
* will switch to PL08X_CHAN_RUNNING when we call
* issue_pending(). If there is something running on the
* channel already we don't change its state.
*/
if (plchan->state == PL08X_CHAN_IDLE)
plchan->state = PL08X_CHAN_PAUSED;
spin_unlock_irqrestore(&plchan->lock, flags);
return 0;
}
static struct pl08x_txd *pl08x_get_txd(struct pl08x_dma_chan *plchan,
unsigned long flags)
{
struct pl08x_txd *txd = kzalloc(sizeof(*txd), GFP_NOWAIT);
if (txd) {
dma_async_tx_descriptor_init(&txd->tx, &plchan->chan);
txd->tx.flags = flags;
txd->tx.tx_submit = pl08x_tx_submit;
INIT_LIST_HEAD(&txd->node);
INIT_LIST_HEAD(&txd->dsg_list);
/* Always enable error and terminal interrupts */
txd->ccfg = PL080_CONFIG_ERR_IRQ_MASK |
PL080_CONFIG_TC_IRQ_MASK;
}
return txd;
}
/*
* Initialize a descriptor to be used by memcpy submit
*/
static struct dma_async_tx_descriptor *pl08x_prep_dma_memcpy(
struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
size_t len, unsigned long flags)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
struct pl08x_driver_data *pl08x = plchan->host;
struct pl08x_txd *txd;
struct pl08x_sg *dsg;
int ret;
txd = pl08x_get_txd(plchan, flags);
if (!txd) {
dev_err(&pl08x->adev->dev,
"%s no memory for descriptor\n", __func__);
return NULL;
}
dsg = kzalloc(sizeof(struct pl08x_sg), GFP_NOWAIT);
if (!dsg) {
pl08x_free_txd(pl08x, txd);
dev_err(&pl08x->adev->dev, "%s no memory for pl080 sg\n",
__func__);
return NULL;
}
list_add_tail(&dsg->node, &txd->dsg_list);
txd->direction = DMA_NONE;
dsg->src_addr = src;
dsg->dst_addr = dest;
dsg->len = len;
/* Set platform data for m2m */
txd->ccfg |= PL080_FLOW_MEM2MEM << PL080_CONFIG_FLOW_CONTROL_SHIFT;
txd->cctl = pl08x->pd->memcpy_channel.cctl &
~(PL080_CONTROL_DST_AHB2 | PL080_CONTROL_SRC_AHB2);
/* Both to be incremented or the code will break */
txd->cctl |= PL080_CONTROL_SRC_INCR | PL080_CONTROL_DST_INCR;
if (pl08x->vd->dualmaster)
txd->cctl |= pl08x_select_bus(pl08x->mem_buses,
pl08x->mem_buses);
ret = pl08x_prep_channel_resources(plchan, txd);
if (ret)
return NULL;
return &txd->tx;
}
static struct dma_async_tx_descriptor *pl08x_prep_slave_sg(
struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction direction,
unsigned long flags, void *context)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
struct pl08x_driver_data *pl08x = plchan->host;
struct pl08x_txd *txd;
struct pl08x_sg *dsg;
struct scatterlist *sg;
dma_addr_t slave_addr;
int ret, tmp;
dev_dbg(&pl08x->adev->dev, "%s prepare transaction of %d bytes from %s\n",
__func__, sgl->length, plchan->name);
txd = pl08x_get_txd(plchan, flags);
if (!txd) {
dev_err(&pl08x->adev->dev, "%s no txd\n", __func__);
return NULL;
}
if (direction != plchan->runtime_direction)
dev_err(&pl08x->adev->dev, "%s DMA setup does not match "
"the direction configured for the PrimeCell\n",
__func__);
/*
* Set up addresses, the PrimeCell configured address
* will take precedence since this may configure the
* channel target address dynamically at runtime.
*/
txd->direction = direction;
if (direction == DMA_MEM_TO_DEV) {
txd->cctl = plchan->dst_cctl;
slave_addr = plchan->dst_addr;
} else if (direction == DMA_DEV_TO_MEM) {
txd->cctl = plchan->src_cctl;
slave_addr = plchan->src_addr;
} else {
pl08x_free_txd(pl08x, txd);
dev_err(&pl08x->adev->dev,
"%s direction unsupported\n", __func__);
return NULL;
}
if (plchan->device_fc)
tmp = (direction == DMA_MEM_TO_DEV) ? PL080_FLOW_MEM2PER_PER :
PL080_FLOW_PER2MEM_PER;
else
tmp = (direction == DMA_MEM_TO_DEV) ? PL080_FLOW_MEM2PER :
PL080_FLOW_PER2MEM;
txd->ccfg |= tmp << PL080_CONFIG_FLOW_CONTROL_SHIFT;
for_each_sg(sgl, sg, sg_len, tmp) {
dsg = kzalloc(sizeof(struct pl08x_sg), GFP_NOWAIT);
if (!dsg) {
pl08x_free_txd(pl08x, txd);
dev_err(&pl08x->adev->dev, "%s no mem for pl080 sg\n",
__func__);
return NULL;
}
list_add_tail(&dsg->node, &txd->dsg_list);
dsg->len = sg_dma_len(sg);
if (direction == DMA_MEM_TO_DEV) {
dsg->src_addr = sg_phys(sg);
dsg->dst_addr = slave_addr;
} else {
dsg->src_addr = slave_addr;
dsg->dst_addr = sg_phys(sg);
}
}
ret = pl08x_prep_channel_resources(plchan, txd);
if (ret)
return NULL;
return &txd->tx;
}
static int pl08x_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
unsigned long arg)
{
struct pl08x_dma_chan *plchan = to_pl08x_chan(chan);
struct pl08x_driver_data *pl08x = plchan->host;
unsigned long flags;
int ret = 0;
/* Controls applicable to inactive channels */
if (cmd == DMA_SLAVE_CONFIG) {
return dma_set_runtime_config(chan,
(struct dma_slave_config *)arg);
}
/*
* Anything succeeds on channels with no physical allocation and
* no queued transfers.
*/
spin_lock_irqsave(&plchan->lock, flags);
if (!plchan->phychan && !plchan->at) {
spin_unlock_irqrestore(&plchan->lock, flags);
return 0;
}
switch (cmd) {
case DMA_TERMINATE_ALL:
plchan->state = PL08X_CHAN_IDLE;
if (plchan->phychan) {
pl08x_terminate_phy_chan(pl08x, plchan->phychan);
/*
* Mark physical channel as free and free any slave
* signal
*/
release_phy_channel(plchan);
plchan->phychan_hold = 0;
}
/* Dequeue jobs and free LLIs */
if (plchan->at) {
pl08x_free_txd(pl08x, plchan->at);
plchan->at = NULL;
}
/* Dequeue jobs not yet fired as well */
pl08x_free_txd_list(pl08x, plchan);
break;
case DMA_PAUSE:
pl08x_pause_phy_chan(plchan->phychan);
plchan->state = PL08X_CHAN_PAUSED;
break;
case DMA_RESUME:
pl08x_resume_phy_chan(plchan->phychan);
plchan->state = PL08X_CHAN_RUNNING;
break;
default:
/* Unknown command */
ret = -ENXIO;
break;
}
spin_unlock_irqrestore(&plchan->lock, flags);
return ret;
}
bool pl08x_filter_id(struct dma_chan *chan, void *chan_id)
{
struct pl08x_dma_chan *plchan;
char *name = chan_id;
/* Reject channels for devices not bound to this driver */
if (chan->device->dev->driver != &pl08x_amba_driver.drv)
return false;
plchan = to_pl08x_chan(chan);
/* Check that the channel is not taken! */
if (!strcmp(plchan->name, name))
return true;
return false;
}
/*
* Just check that the device is there and active
* TODO: turn this bit on/off depending on the number of physical channels
* actually used, if it is zero... well shut it off. That will save some
* power. Cut the clock at the same time.
*/
static void pl08x_ensure_on(struct pl08x_driver_data *pl08x)
{
writel(PL080_CONFIG_ENABLE, pl08x->base + PL080_CONFIG);
}
static void pl08x_unmap_buffers(struct pl08x_txd *txd)
{
struct device *dev = txd->tx.chan->device->dev;
struct pl08x_sg *dsg;
if (!(txd->tx.flags & DMA_COMPL_SKIP_SRC_UNMAP)) {
if (txd->tx.flags & DMA_COMPL_SRC_UNMAP_SINGLE)
list_for_each_entry(dsg, &txd->dsg_list, node)
dma_unmap_single(dev, dsg->src_addr, dsg->len,
DMA_TO_DEVICE);
else {
list_for_each_entry(dsg, &txd->dsg_list, node)
dma_unmap_page(dev, dsg->src_addr, dsg->len,
DMA_TO_DEVICE);
}
}
if (!(txd->tx.flags & DMA_COMPL_SKIP_DEST_UNMAP)) {
if (txd->tx.flags & DMA_COMPL_DEST_UNMAP_SINGLE)
list_for_each_entry(dsg, &txd->dsg_list, node)
dma_unmap_single(dev, dsg->dst_addr, dsg->len,
DMA_FROM_DEVICE);
else
list_for_each_entry(dsg, &txd->dsg_list, node)
dma_unmap_page(dev, dsg->dst_addr, dsg->len,
DMA_FROM_DEVICE);
}
}
static void pl08x_tasklet(unsigned long data)
{
struct pl08x_dma_chan *plchan = (struct pl08x_dma_chan *) data;
struct pl08x_driver_data *pl08x = plchan->host;
struct pl08x_txd *txd;
unsigned long flags;
spin_lock_irqsave(&plchan->lock, flags);
txd = plchan->at;
plchan->at = NULL;
if (txd) {
/* Update last completed */
dma_cookie_complete(&txd->tx);
}
/* If a new descriptor is queued, set it up plchan->at is NULL here */
if (!list_empty(&plchan->pend_list)) {
struct pl08x_txd *next;
next = list_first_entry(&plchan->pend_list,
struct pl08x_txd,
node);
list_del(&next->node);
pl08x_start_txd(plchan, next);
} else if (plchan->phychan_hold) {
/*
* This channel is still in use - we have a new txd being
* prepared and will soon be queued. Don't give up the
* physical channel.
*/
} else {
struct pl08x_dma_chan *waiting = NULL;
/*
* No more jobs, so free up the physical channel
* Free any allocated signal on slave transfers too
*/
release_phy_channel(plchan);
plchan->state = PL08X_CHAN_IDLE;
/*
* And NOW before anyone else can grab that free:d up
* physical channel, see if there is some memcpy pending
* that seriously needs to start because of being stacked
* up while we were choking the physical channels with data.
*/
list_for_each_entry(waiting, &pl08x->memcpy.channels,
chan.device_node) {
if (waiting->state == PL08X_CHAN_WAITING &&
waiting->waiting != NULL) {
int ret;
/* This should REALLY not fail now */
ret = prep_phy_channel(waiting,
waiting->waiting);
BUG_ON(ret);
waiting->phychan_hold--;
waiting->state = PL08X_CHAN_RUNNING;
waiting->waiting = NULL;
pl08x_issue_pending(&waiting->chan);
break;
}
}
}
spin_unlock_irqrestore(&plchan->lock, flags);
if (txd) {
dma_async_tx_callback callback = txd->tx.callback;
void *callback_param = txd->tx.callback_param;
/* Don't try to unmap buffers on slave channels */
if (!plchan->slave)
pl08x_unmap_buffers(txd);
/* Free the descriptor */
spin_lock_irqsave(&plchan->lock, flags);
pl08x_free_txd(pl08x, txd);
spin_unlock_irqrestore(&plchan->lock, flags);
/* Callback to signal completion */
if (callback)
callback(callback_param);
}
}
static irqreturn_t pl08x_irq(int irq, void *dev)
{
struct pl08x_driver_data *pl08x = dev;
u32 mask = 0, err, tc, i;
/* check & clear - ERR & TC interrupts */
err = readl(pl08x->base + PL080_ERR_STATUS);
if (err) {
dev_err(&pl08x->adev->dev, "%s error interrupt, register value 0x%08x\n",
__func__, err);
writel(err, pl08x->base + PL080_ERR_CLEAR);
}
tc = readl(pl08x->base + PL080_INT_STATUS);
if (tc)
writel(tc, pl08x->base + PL080_TC_CLEAR);
if (!err && !tc)
return IRQ_NONE;
for (i = 0; i < pl08x->vd->channels; i++) {
if (((1 << i) & err) || ((1 << i) & tc)) {
/* Locate physical channel */
struct pl08x_phy_chan *phychan = &pl08x->phy_chans[i];
struct pl08x_dma_chan *plchan = phychan->serving;
if (!plchan) {
dev_err(&pl08x->adev->dev,
"%s Error TC interrupt on unused channel: 0x%08x\n",
__func__, i);
continue;
}
/* Schedule tasklet on this channel */
tasklet_schedule(&plchan->tasklet);
mask |= (1 << i);
}
}
return mask ? IRQ_HANDLED : IRQ_NONE;
}
static void pl08x_dma_slave_init(struct pl08x_dma_chan *chan)
{
u32 cctl = pl08x_cctl(chan->cd->cctl);
chan->slave = true;
chan->name = chan->cd->bus_id;
chan->src_addr = chan->cd->addr;
chan->dst_addr = chan->cd->addr;
chan->src_cctl = cctl | PL080_CONTROL_DST_INCR |
pl08x_select_bus(chan->cd->periph_buses, chan->host->mem_buses);
chan->dst_cctl = cctl | PL080_CONTROL_SRC_INCR |
pl08x_select_bus(chan->host->mem_buses, chan->cd->periph_buses);
}
/*
* Initialise the DMAC memcpy/slave channels.
* Make a local wrapper to hold required data
*/
static int pl08x_dma_init_virtual_channels(struct pl08x_driver_data *pl08x,
struct dma_device *dmadev, unsigned int channels, bool slave)
{
struct pl08x_dma_chan *chan;
int i;
INIT_LIST_HEAD(&dmadev->channels);
/*
* Register as many many memcpy as we have physical channels,
* we won't always be able to use all but the code will have
* to cope with that situation.
*/
for (i = 0; i < channels; i++) {
chan = kzalloc(sizeof(*chan), GFP_KERNEL);
if (!chan) {
dev_err(&pl08x->adev->dev,
"%s no memory for channel\n", __func__);
return -ENOMEM;
}
chan->host = pl08x;
chan->state = PL08X_CHAN_IDLE;
if (slave) {
chan->cd = &pl08x->pd->slave_channels[i];
pl08x_dma_slave_init(chan);
} else {
chan->cd = &pl08x->pd->memcpy_channel;
chan->name = kasprintf(GFP_KERNEL, "memcpy%d", i);
if (!chan->name) {
kfree(chan);
return -ENOMEM;
}
}
if (chan->cd->circular_buffer) {
dev_err(&pl08x->adev->dev,
"channel %s: circular buffers not supported\n",
chan->name);
kfree(chan);
continue;
}
dev_dbg(&pl08x->adev->dev,
"initialize virtual channel \"%s\"\n",
chan->name);
chan->chan.device = dmadev;
dma_cookie_init(&chan->chan);
spin_lock_init(&chan->lock);
INIT_LIST_HEAD(&chan->pend_list);
tasklet_init(&chan->tasklet, pl08x_tasklet,
(unsigned long) chan);
list_add_tail(&chan->chan.device_node, &dmadev->channels);
}
dev_info(&pl08x->adev->dev, "initialized %d virtual %s channels\n",
i, slave ? "slave" : "memcpy");
return i;
}
static void pl08x_free_virtual_channels(struct dma_device *dmadev)
{
struct pl08x_dma_chan *chan = NULL;
struct pl08x_dma_chan *next;
list_for_each_entry_safe(chan,
next, &dmadev->channels, chan.device_node) {
list_del(&chan->chan.device_node);
kfree(chan);
}
}
#ifdef CONFIG_DEBUG_FS
static const char *pl08x_state_str(enum pl08x_dma_chan_state state)
{
switch (state) {
case PL08X_CHAN_IDLE:
return "idle";
case PL08X_CHAN_RUNNING:
return "running";
case PL08X_CHAN_PAUSED:
return "paused";
case PL08X_CHAN_WAITING:
return "waiting";
default:
break;
}
return "UNKNOWN STATE";
}
static int pl08x_debugfs_show(struct seq_file *s, void *data)
{
struct pl08x_driver_data *pl08x = s->private;
struct pl08x_dma_chan *chan;
struct pl08x_phy_chan *ch;
unsigned long flags;
int i;
seq_printf(s, "PL08x physical channels:\n");
seq_printf(s, "CHANNEL:\tUSER:\n");
seq_printf(s, "--------\t-----\n");
for (i = 0; i < pl08x->vd->channels; i++) {
struct pl08x_dma_chan *virt_chan;
ch = &pl08x->phy_chans[i];
spin_lock_irqsave(&ch->lock, flags);
virt_chan = ch->serving;
seq_printf(s, "%d\t\t%s\n",
ch->id, virt_chan ? virt_chan->name : "(none)");
spin_unlock_irqrestore(&ch->lock, flags);
}
seq_printf(s, "\nPL08x virtual memcpy channels:\n");
seq_printf(s, "CHANNEL:\tSTATE:\n");
seq_printf(s, "--------\t------\n");
list_for_each_entry(chan, &pl08x->memcpy.channels, chan.device_node) {
seq_printf(s, "%s\t\t%s\n", chan->name,
pl08x_state_str(chan->state));
}
seq_printf(s, "\nPL08x virtual slave channels:\n");
seq_printf(s, "CHANNEL:\tSTATE:\n");
seq_printf(s, "--------\t------\n");
list_for_each_entry(chan, &pl08x->slave.channels, chan.device_node) {
seq_printf(s, "%s\t\t%s\n", chan->name,
pl08x_state_str(chan->state));
}
return 0;
}
static int pl08x_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, pl08x_debugfs_show, inode->i_private);
}
static const struct file_operations pl08x_debugfs_operations = {
.open = pl08x_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void init_pl08x_debugfs(struct pl08x_driver_data *pl08x)
{
/* Expose a simple debugfs interface to view all clocks */
(void) debugfs_create_file(dev_name(&pl08x->adev->dev),
S_IFREG | S_IRUGO, NULL, pl08x,
&pl08x_debugfs_operations);
}
#else
static inline void init_pl08x_debugfs(struct pl08x_driver_data *pl08x)
{
}
#endif
static int pl08x_probe(struct amba_device *adev, const struct amba_id *id)
{
struct pl08x_driver_data *pl08x;
const struct vendor_data *vd = id->data;
int ret = 0;
int i;
ret = amba_request_regions(adev, NULL);
if (ret)
return ret;
/* Create the driver state holder */
pl08x = kzalloc(sizeof(*pl08x), GFP_KERNEL);
if (!pl08x) {
ret = -ENOMEM;
goto out_no_pl08x;
}
pm_runtime_set_active(&adev->dev);
pm_runtime_enable(&adev->dev);
/* Initialize memcpy engine */
dma_cap_set(DMA_MEMCPY, pl08x->memcpy.cap_mask);
pl08x->memcpy.dev = &adev->dev;
pl08x->memcpy.device_alloc_chan_resources = pl08x_alloc_chan_resources;
pl08x->memcpy.device_free_chan_resources = pl08x_free_chan_resources;
pl08x->memcpy.device_prep_dma_memcpy = pl08x_prep_dma_memcpy;
pl08x->memcpy.device_prep_dma_interrupt = pl08x_prep_dma_interrupt;
pl08x->memcpy.device_tx_status = pl08x_dma_tx_status;
pl08x->memcpy.device_issue_pending = pl08x_issue_pending;
pl08x->memcpy.device_control = pl08x_control;
/* Initialize slave engine */
dma_cap_set(DMA_SLAVE, pl08x->slave.cap_mask);
pl08x->slave.dev = &adev->dev;
pl08x->slave.device_alloc_chan_resources = pl08x_alloc_chan_resources;
pl08x->slave.device_free_chan_resources = pl08x_free_chan_resources;
pl08x->slave.device_prep_dma_interrupt = pl08x_prep_dma_interrupt;
pl08x->slave.device_tx_status = pl08x_dma_tx_status;
pl08x->slave.device_issue_pending = pl08x_issue_pending;
pl08x->slave.device_prep_slave_sg = pl08x_prep_slave_sg;
pl08x->slave.device_control = pl08x_control;
/* Get the platform data */
pl08x->pd = dev_get_platdata(&adev->dev);
if (!pl08x->pd) {
dev_err(&adev->dev, "no platform data supplied\n");
goto out_no_platdata;
}
/* Assign useful pointers to the driver state */
pl08x->adev = adev;
pl08x->vd = vd;
/* By default, AHB1 only. If dualmaster, from platform */
pl08x->lli_buses = PL08X_AHB1;
pl08x->mem_buses = PL08X_AHB1;
if (pl08x->vd->dualmaster) {
pl08x->lli_buses = pl08x->pd->lli_buses;
pl08x->mem_buses = pl08x->pd->mem_buses;
}
/* A DMA memory pool for LLIs, align on 1-byte boundary */
pl08x->pool = dma_pool_create(DRIVER_NAME, &pl08x->adev->dev,
PL08X_LLI_TSFR_SIZE, PL08X_ALIGN, 0);
if (!pl08x->pool) {
ret = -ENOMEM;
goto out_no_lli_pool;
}
spin_lock_init(&pl08x->lock);
pl08x->base = ioremap(adev->res.start, resource_size(&adev->res));
if (!pl08x->base) {
ret = -ENOMEM;
goto out_no_ioremap;
}
/* Turn on the PL08x */
pl08x_ensure_on(pl08x);
/* Attach the interrupt handler */
writel(0x000000FF, pl08x->base + PL080_ERR_CLEAR);
writel(0x000000FF, pl08x->base + PL080_TC_CLEAR);
ret = request_irq(adev->irq[0], pl08x_irq, IRQF_DISABLED,
DRIVER_NAME, pl08x);
if (ret) {
dev_err(&adev->dev, "%s failed to request interrupt %d\n",
__func__, adev->irq[0]);
goto out_no_irq;
}
/* Initialize physical channels */
pl08x->phy_chans = kmalloc((vd->channels * sizeof(*pl08x->phy_chans)),
GFP_KERNEL);
if (!pl08x->phy_chans) {
dev_err(&adev->dev, "%s failed to allocate "
"physical channel holders\n",
__func__);
goto out_no_phychans;
}
for (i = 0; i < vd->channels; i++) {
struct pl08x_phy_chan *ch = &pl08x->phy_chans[i];
ch->id = i;
ch->base = pl08x->base + PL080_Cx_BASE(i);
spin_lock_init(&ch->lock);
ch->serving = NULL;
ch->signal = -1;
dev_dbg(&adev->dev, "physical channel %d is %s\n",
i, pl08x_phy_channel_busy(ch) ? "BUSY" : "FREE");
}
/* Register as many memcpy channels as there are physical channels */
ret = pl08x_dma_init_virtual_channels(pl08x, &pl08x->memcpy,
pl08x->vd->channels, false);
if (ret <= 0) {
dev_warn(&pl08x->adev->dev,
"%s failed to enumerate memcpy channels - %d\n",
__func__, ret);
goto out_no_memcpy;
}
pl08x->memcpy.chancnt = ret;
/* Register slave channels */
ret = pl08x_dma_init_virtual_channels(pl08x, &pl08x->slave,
pl08x->pd->num_slave_channels, true);
if (ret <= 0) {
dev_warn(&pl08x->adev->dev,
"%s failed to enumerate slave channels - %d\n",
__func__, ret);
goto out_no_slave;
}
pl08x->slave.chancnt = ret;
ret = dma_async_device_register(&pl08x->memcpy);
if (ret) {
dev_warn(&pl08x->adev->dev,
"%s failed to register memcpy as an async device - %d\n",
__func__, ret);
goto out_no_memcpy_reg;
}
ret = dma_async_device_register(&pl08x->slave);
if (ret) {
dev_warn(&pl08x->adev->dev,
"%s failed to register slave as an async device - %d\n",
__func__, ret);
goto out_no_slave_reg;
}
amba_set_drvdata(adev, pl08x);
init_pl08x_debugfs(pl08x);
dev_info(&pl08x->adev->dev, "DMA: PL%03x rev%u at 0x%08llx irq %d\n",
amba_part(adev), amba_rev(adev),
(unsigned long long)adev->res.start, adev->irq[0]);
pm_runtime_put(&adev->dev);
return 0;
out_no_slave_reg:
dma_async_device_unregister(&pl08x->memcpy);
out_no_memcpy_reg:
pl08x_free_virtual_channels(&pl08x->slave);
out_no_slave:
pl08x_free_virtual_channels(&pl08x->memcpy);
out_no_memcpy:
kfree(pl08x->phy_chans);
out_no_phychans:
free_irq(adev->irq[0], pl08x);
out_no_irq:
iounmap(pl08x->base);
out_no_ioremap:
dma_pool_destroy(pl08x->pool);
out_no_lli_pool:
out_no_platdata:
pm_runtime_put(&adev->dev);
pm_runtime_disable(&adev->dev);
kfree(pl08x);
out_no_pl08x:
amba_release_regions(adev);
return ret;
}
/* PL080 has 8 channels and the PL080 have just 2 */
static struct vendor_data vendor_pl080 = {
.channels = 8,
.dualmaster = true,
};
static struct vendor_data vendor_pl081 = {
.channels = 2,
.dualmaster = false,
};
static struct amba_id pl08x_ids[] = {
/* PL080 */
{
.id = 0x00041080,
.mask = 0x000fffff,
.data = &vendor_pl080,
},
/* PL081 */
{
.id = 0x00041081,
.mask = 0x000fffff,
.data = &vendor_pl081,
},
/* Nomadik 8815 PL080 variant */
{
.id = 0x00280880,
.mask = 0x00ffffff,
.data = &vendor_pl080,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, pl08x_ids);
static struct amba_driver pl08x_amba_driver = {
.drv.name = DRIVER_NAME,
.id_table = pl08x_ids,
.probe = pl08x_probe,
};
static int __init pl08x_init(void)
{
int retval;
retval = amba_driver_register(&pl08x_amba_driver);
if (retval)
printk(KERN_WARNING DRIVER_NAME
"failed to register as an AMBA device (%d)\n",
retval);
return retval;
}
subsys_initcall(pl08x_init);
| gpl-2.0 |
philozheng/kernel-msm | arch/arm/mach-msm/board-swordfish-panel.c | 5035 | 2652 | /* linux/arch/arm/mach-msm/board-swordfish-panel.c
*
* Copyright (c) 2009 Google Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Author: Dima Zavin <dima@android.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <asm/io.h>
#include <asm/mach-types.h>
#include <mach/msm_fb.h>
#include "board-swordfish.h"
#include "devices.h"
#define CLK_NS_TO_RATE(ns) (1000000000UL / (ns))
int swordfish_panel_blank(struct msm_lcdc_panel_ops *ops)
{
/* TODO: Turn backlight off? */
return 0;
}
int swordfish_panel_unblank(struct msm_lcdc_panel_ops *ops)
{
/* TODO: Turn backlight on? */
return 0;
}
int swordfish_panel_init(struct msm_lcdc_panel_ops *ops)
{
return 0;
}
static struct resource resources_msm_fb[] = {
{
.start = MSM_FB_BASE,
.end = MSM_FB_BASE + MSM_FB_SIZE,
.flags = IORESOURCE_MEM,
},
};
static struct msm_lcdc_timing swordfish_lcdc_timing = {
.clk_rate = CLK_NS_TO_RATE(26),
.hsync_pulse_width = 60,
.hsync_back_porch = 81,
.hsync_front_porch = 81,
.hsync_skew = 0,
.vsync_pulse_width = 2,
.vsync_back_porch = 20,
.vsync_front_porch = 27,
.vsync_act_low = 0,
.hsync_act_low = 0,
.den_act_low = 0,
};
static struct msm_fb_data swordfish_lcdc_fb_data = {
.xres = 800,
.yres = 480,
.width = 94,
.height = 57,
.output_format = 0,
};
static struct msm_lcdc_panel_ops swordfish_lcdc_panel_ops = {
.init = swordfish_panel_init,
.blank = swordfish_panel_blank,
.unblank = swordfish_panel_unblank,
};
static struct msm_lcdc_platform_data swordfish_lcdc_platform_data = {
.panel_ops = &swordfish_lcdc_panel_ops,
.timing = &swordfish_lcdc_timing,
.fb_id = 0,
.fb_data = &swordfish_lcdc_fb_data,
.fb_resource = &resources_msm_fb[0],
};
static struct platform_device swordfish_lcdc_device = {
.name = "msm_mdp_lcdc",
.id = -1,
.dev = {
.platform_data = &swordfish_lcdc_platform_data,
},
};
int __init swordfish_init_panel(void)
{
int rc;
if (!machine_is_swordfish())
return 0;
if ((rc = platform_device_register(&msm_device_mdp)) != 0)
return rc;
if ((rc = platform_device_register(&swordfish_lcdc_device)) != 0)
return rc;
return 0;
}
device_initcall(swordfish_init_panel);
| gpl-2.0 |
Loller79/Solid_Kernel-GEEHRC-LP | drivers/media/dvb/dvb-usb/ec168.c | 5035 | 10404 | /*
* E3C EC168 DVB USB driver
*
* Copyright (C) 2009 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include "ec168.h"
#include "ec100.h"
#include "mxl5005s.h"
/* debug */
static int dvb_usb_ec168_debug;
module_param_named(debug, dvb_usb_ec168_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level" DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static struct ec100_config ec168_ec100_config;
static int ec168_rw_udev(struct usb_device *udev, struct ec168_req *req)
{
int ret;
unsigned int pipe;
u8 request, requesttype;
u8 *buf;
switch (req->cmd) {
case DOWNLOAD_FIRMWARE:
case GPIO:
case WRITE_I2C:
case STREAMING_CTRL:
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
request = req->cmd;
break;
case READ_I2C:
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
request = req->cmd;
break;
case GET_CONFIG:
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
request = CONFIG;
break;
case SET_CONFIG:
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
request = CONFIG;
break;
case WRITE_DEMOD:
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
request = DEMOD_RW;
break;
case READ_DEMOD:
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
request = DEMOD_RW;
break;
default:
err("unknown command:%02x", req->cmd);
ret = -EPERM;
goto error;
}
buf = kmalloc(req->size, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto error;
}
if (requesttype == (USB_TYPE_VENDOR | USB_DIR_OUT)) {
/* write */
memcpy(buf, req->data, req->size);
pipe = usb_sndctrlpipe(udev, 0);
} else {
/* read */
pipe = usb_rcvctrlpipe(udev, 0);
}
msleep(1); /* avoid I2C errors */
ret = usb_control_msg(udev, pipe, request, requesttype, req->value,
req->index, buf, req->size, EC168_USB_TIMEOUT);
ec168_debug_dump(request, requesttype, req->value, req->index, buf,
req->size, deb_xfer);
if (ret < 0)
goto err_dealloc;
else
ret = 0;
/* read request, copy returned data to return buf */
if (!ret && requesttype == (USB_TYPE_VENDOR | USB_DIR_IN))
memcpy(req->data, buf, req->size);
kfree(buf);
return ret;
err_dealloc:
kfree(buf);
error:
deb_info("%s: failed:%d\n", __func__, ret);
return ret;
}
static int ec168_ctrl_msg(struct dvb_usb_device *d, struct ec168_req *req)
{
return ec168_rw_udev(d->udev, req);
}
/* I2C */
static int ec168_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct ec168_req req;
int i = 0;
int ret;
if (num > 2)
return -EINVAL;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
while (i < num) {
if (num > i + 1 && (msg[i+1].flags & I2C_M_RD)) {
if (msg[i].addr == ec168_ec100_config.demod_address) {
req.cmd = READ_DEMOD;
req.value = 0;
req.index = 0xff00 + msg[i].buf[0]; /* reg */
req.size = msg[i+1].len; /* bytes to read */
req.data = &msg[i+1].buf[0];
ret = ec168_ctrl_msg(d, &req);
i += 2;
} else {
err("I2C read not implemented");
ret = -ENOSYS;
i += 2;
}
} else {
if (msg[i].addr == ec168_ec100_config.demod_address) {
req.cmd = WRITE_DEMOD;
req.value = msg[i].buf[1]; /* val */
req.index = 0xff00 + msg[i].buf[0]; /* reg */
req.size = 0;
req.data = NULL;
ret = ec168_ctrl_msg(d, &req);
i += 1;
} else {
req.cmd = WRITE_I2C;
req.value = msg[i].buf[0]; /* val */
req.index = 0x0100 + msg[i].addr; /* I2C addr */
req.size = msg[i].len-1;
req.data = &msg[i].buf[1];
ret = ec168_ctrl_msg(d, &req);
i += 1;
}
}
if (ret)
goto error;
}
ret = i;
error:
mutex_unlock(&d->i2c_mutex);
return i;
}
static u32 ec168_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm ec168_i2c_algo = {
.master_xfer = ec168_i2c_xfer,
.functionality = ec168_i2c_func,
};
/* Callbacks for DVB USB */
static struct ec100_config ec168_ec100_config = {
.demod_address = 0xff, /* not real address, demod is integrated */
};
static int ec168_ec100_frontend_attach(struct dvb_usb_adapter *adap)
{
deb_info("%s:\n", __func__);
adap->fe_adap[0].fe = dvb_attach(ec100_attach, &ec168_ec100_config,
&adap->dev->i2c_adap);
if (adap->fe_adap[0].fe == NULL)
return -ENODEV;
return 0;
}
static struct mxl5005s_config ec168_mxl5003s_config = {
.i2c_address = 0xc6,
.if_freq = IF_FREQ_4570000HZ,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_OFF,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
static int ec168_mxl5003s_tuner_attach(struct dvb_usb_adapter *adap)
{
deb_info("%s:\n", __func__);
return dvb_attach(mxl5005s_attach, adap->fe_adap[0].fe, &adap->dev->i2c_adap,
&ec168_mxl5003s_config) == NULL ? -ENODEV : 0;
}
static int ec168_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
struct ec168_req req = {STREAMING_CTRL, 0x7f01, 0x0202, 0, NULL};
deb_info("%s: onoff:%d\n", __func__, onoff);
if (onoff)
req.index = 0x0102;
return ec168_ctrl_msg(adap->dev, &req);
}
static int ec168_download_firmware(struct usb_device *udev,
const struct firmware *fw)
{
int i, len, packets, remainder, ret;
u16 addr = 0x0000; /* firmware start address */
struct ec168_req req = {DOWNLOAD_FIRMWARE, 0, 0, 0, NULL};
deb_info("%s:\n", __func__);
#define FW_PACKET_MAX_DATA 2048
packets = fw->size / FW_PACKET_MAX_DATA;
remainder = fw->size % FW_PACKET_MAX_DATA;
len = FW_PACKET_MAX_DATA;
for (i = 0; i <= packets; i++) {
if (i == packets) /* set size of the last packet */
len = remainder;
req.size = len;
req.data = (u8 *)(fw->data + i * FW_PACKET_MAX_DATA);
req.index = addr;
addr += FW_PACKET_MAX_DATA;
ret = ec168_rw_udev(udev, &req);
if (ret) {
err("firmware download failed:%d packet:%d", ret, i);
goto error;
}
}
req.size = 0;
/* set "warm"? */
req.cmd = SET_CONFIG;
req.value = 0;
req.index = 0x0001;
ret = ec168_rw_udev(udev, &req);
if (ret)
goto error;
/* really needed - no idea what does */
req.cmd = GPIO;
req.value = 0;
req.index = 0x0206;
ret = ec168_rw_udev(udev, &req);
if (ret)
goto error;
/* activate tuner I2C? */
req.cmd = WRITE_I2C;
req.value = 0;
req.index = 0x00c6;
ret = ec168_rw_udev(udev, &req);
if (ret)
goto error;
return ret;
error:
deb_info("%s: failed:%d\n", __func__, ret);
return ret;
}
static int ec168_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc, int *cold)
{
int ret;
u8 reply;
struct ec168_req req = {GET_CONFIG, 0, 1, sizeof(reply), &reply};
deb_info("%s:\n", __func__);
ret = ec168_rw_udev(udev, &req);
if (ret)
goto error;
deb_info("%s: reply:%02x\n", __func__, reply);
if (reply == 0x01)
*cold = 0;
else
*cold = 1;
return ret;
error:
deb_info("%s: failed:%d\n", __func__, ret);
return ret;
}
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties ec168_properties;
static int ec168_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int ret;
deb_info("%s: interface:%d\n", __func__,
intf->cur_altsetting->desc.bInterfaceNumber);
ret = dvb_usb_device_init(intf, &ec168_properties, THIS_MODULE, NULL,
adapter_nr);
if (ret)
goto error;
return ret;
error:
deb_info("%s: failed:%d\n", __func__, ret);
return ret;
}
#define E3C_EC168_1689 0
#define E3C_EC168_FFFA 1
#define E3C_EC168_FFFB 2
#define E3C_EC168_1001 3
#define E3C_EC168_1002 4
static struct usb_device_id ec168_id[] = {
[E3C_EC168_1689] =
{USB_DEVICE(USB_VID_E3C, USB_PID_E3C_EC168)},
[E3C_EC168_FFFA] =
{USB_DEVICE(USB_VID_E3C, USB_PID_E3C_EC168_2)},
[E3C_EC168_FFFB] =
{USB_DEVICE(USB_VID_E3C, USB_PID_E3C_EC168_3)},
[E3C_EC168_1001] =
{USB_DEVICE(USB_VID_E3C, USB_PID_E3C_EC168_4)},
[E3C_EC168_1002] =
{USB_DEVICE(USB_VID_E3C, USB_PID_E3C_EC168_5)},
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, ec168_id);
static struct dvb_usb_device_properties ec168_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.download_firmware = ec168_download_firmware,
.firmware = "dvb-usb-ec168.fw",
.no_reconnect = 1,
.size_of_priv = 0,
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = ec168_streaming_ctrl,
.frontend_attach = ec168_ec100_frontend_attach,
.tuner_attach = ec168_mxl5003s_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 6,
.endpoint = 0x82,
.u = {
.bulk = {
.buffersize = (32*512),
}
}
},
}},
}
},
.identify_state = ec168_identify_state,
.i2c_algo = &ec168_i2c_algo,
.num_device_descs = 1,
.devices = {
{
.name = "E3C EC168 DVB-T USB2.0 reference design",
.cold_ids = {
&ec168_id[E3C_EC168_1689],
&ec168_id[E3C_EC168_FFFA],
&ec168_id[E3C_EC168_FFFB],
&ec168_id[E3C_EC168_1001],
&ec168_id[E3C_EC168_1002],
NULL},
.warm_ids = {NULL},
},
}
};
static struct usb_driver ec168_driver = {
.name = "dvb_usb_ec168",
.probe = ec168_probe,
.disconnect = dvb_usb_device_exit,
.id_table = ec168_id,
};
module_usb_driver(ec168_driver);
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_DESCRIPTION("E3C EC168 DVB-T USB2.0 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
GustavoRD78/78Kernel-Z3-Kit-Kat | fs/cachefiles/bind.c | 8363 | 7208 | /* Bind and unbind a cache from the filesystem backing it
*
* 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 <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/statfs.h>
#include <linux/ctype.h>
#include "internal.h"
static int cachefiles_daemon_add_cache(struct cachefiles_cache *caches);
/*
* bind a directory as a cache
*/
int cachefiles_daemon_bind(struct cachefiles_cache *cache, char *args)
{
_enter("{%u,%u,%u,%u,%u,%u},%s",
cache->frun_percent,
cache->fcull_percent,
cache->fstop_percent,
cache->brun_percent,
cache->bcull_percent,
cache->bstop_percent,
args);
/* start by checking things over */
ASSERT(cache->fstop_percent >= 0 &&
cache->fstop_percent < cache->fcull_percent &&
cache->fcull_percent < cache->frun_percent &&
cache->frun_percent < 100);
ASSERT(cache->bstop_percent >= 0 &&
cache->bstop_percent < cache->bcull_percent &&
cache->bcull_percent < cache->brun_percent &&
cache->brun_percent < 100);
if (*args) {
kerror("'bind' command doesn't take an argument");
return -EINVAL;
}
if (!cache->rootdirname) {
kerror("No cache directory specified");
return -EINVAL;
}
/* don't permit already bound caches to be re-bound */
if (test_bit(CACHEFILES_READY, &cache->flags)) {
kerror("Cache already bound");
return -EBUSY;
}
/* make sure we have copies of the tag and dirname strings */
if (!cache->tag) {
/* the tag string is released by the fops->release()
* function, so we don't release it on error here */
cache->tag = kstrdup("CacheFiles", GFP_KERNEL);
if (!cache->tag)
return -ENOMEM;
}
/* add the cache */
return cachefiles_daemon_add_cache(cache);
}
/*
* add a cache
*/
static int cachefiles_daemon_add_cache(struct cachefiles_cache *cache)
{
struct cachefiles_object *fsdef;
struct path path;
struct kstatfs stats;
struct dentry *graveyard, *cachedir, *root;
const struct cred *saved_cred;
int ret;
_enter("");
/* we want to work under the module's security ID */
ret = cachefiles_get_security_ID(cache);
if (ret < 0)
return ret;
cachefiles_begin_secure(cache, &saved_cred);
/* allocate the root index object */
ret = -ENOMEM;
fsdef = kmem_cache_alloc(cachefiles_object_jar, GFP_KERNEL);
if (!fsdef)
goto error_root_object;
ASSERTCMP(fsdef->backer, ==, NULL);
atomic_set(&fsdef->usage, 1);
fsdef->type = FSCACHE_COOKIE_TYPE_INDEX;
_debug("- fsdef %p", fsdef);
/* look up the directory at the root of the cache */
ret = kern_path(cache->rootdirname, LOOKUP_DIRECTORY, &path);
if (ret < 0)
goto error_open_root;
cache->mnt = path.mnt;
root = path.dentry;
/* check parameters */
ret = -EOPNOTSUPP;
if (!root->d_inode ||
!root->d_inode->i_op ||
!root->d_inode->i_op->lookup ||
!root->d_inode->i_op->mkdir ||
!root->d_inode->i_op->setxattr ||
!root->d_inode->i_op->getxattr ||
!root->d_sb->s_op->statfs ||
!root->d_sb->s_op->sync_fs)
goto error_unsupported;
ret = -EROFS;
if (root->d_sb->s_flags & MS_RDONLY)
goto error_unsupported;
/* determine the security of the on-disk cache as this governs
* security ID of files we create */
ret = cachefiles_determine_cache_security(cache, root, &saved_cred);
if (ret < 0)
goto error_unsupported;
/* get the cache size and blocksize */
ret = vfs_statfs(&path, &stats);
if (ret < 0)
goto error_unsupported;
ret = -ERANGE;
if (stats.f_bsize <= 0)
goto error_unsupported;
ret = -EOPNOTSUPP;
if (stats.f_bsize > PAGE_SIZE)
goto error_unsupported;
cache->bsize = stats.f_bsize;
cache->bshift = 0;
if (stats.f_bsize < PAGE_SIZE)
cache->bshift = PAGE_SHIFT - ilog2(stats.f_bsize);
_debug("blksize %u (shift %u)",
cache->bsize, cache->bshift);
_debug("size %llu, avail %llu",
(unsigned long long) stats.f_blocks,
(unsigned long long) stats.f_bavail);
/* set up caching limits */
do_div(stats.f_files, 100);
cache->fstop = stats.f_files * cache->fstop_percent;
cache->fcull = stats.f_files * cache->fcull_percent;
cache->frun = stats.f_files * cache->frun_percent;
_debug("limits {%llu,%llu,%llu} files",
(unsigned long long) cache->frun,
(unsigned long long) cache->fcull,
(unsigned long long) cache->fstop);
stats.f_blocks >>= cache->bshift;
do_div(stats.f_blocks, 100);
cache->bstop = stats.f_blocks * cache->bstop_percent;
cache->bcull = stats.f_blocks * cache->bcull_percent;
cache->brun = stats.f_blocks * cache->brun_percent;
_debug("limits {%llu,%llu,%llu} blocks",
(unsigned long long) cache->brun,
(unsigned long long) cache->bcull,
(unsigned long long) cache->bstop);
/* get the cache directory and check its type */
cachedir = cachefiles_get_directory(cache, root, "cache");
if (IS_ERR(cachedir)) {
ret = PTR_ERR(cachedir);
goto error_unsupported;
}
fsdef->dentry = cachedir;
fsdef->fscache.cookie = NULL;
ret = cachefiles_check_object_type(fsdef);
if (ret < 0)
goto error_unsupported;
/* get the graveyard directory */
graveyard = cachefiles_get_directory(cache, root, "graveyard");
if (IS_ERR(graveyard)) {
ret = PTR_ERR(graveyard);
goto error_unsupported;
}
cache->graveyard = graveyard;
/* publish the cache */
fscache_init_cache(&cache->cache,
&cachefiles_cache_ops,
"%s",
fsdef->dentry->d_sb->s_id);
fscache_object_init(&fsdef->fscache, NULL, &cache->cache);
ret = fscache_add_cache(&cache->cache, &fsdef->fscache, cache->tag);
if (ret < 0)
goto error_add_cache;
/* done */
set_bit(CACHEFILES_READY, &cache->flags);
dput(root);
printk(KERN_INFO "CacheFiles:"
" File cache on %s registered\n",
cache->cache.identifier);
/* check how much space the cache has */
cachefiles_has_space(cache, 0, 0);
cachefiles_end_secure(cache, saved_cred);
return 0;
error_add_cache:
dput(cache->graveyard);
cache->graveyard = NULL;
error_unsupported:
mntput(cache->mnt);
cache->mnt = NULL;
dput(fsdef->dentry);
fsdef->dentry = NULL;
dput(root);
error_open_root:
kmem_cache_free(cachefiles_object_jar, fsdef);
error_root_object:
cachefiles_end_secure(cache, saved_cred);
kerror("Failed to register: %d", ret);
return ret;
}
/*
* unbind a cache on fd release
*/
void cachefiles_daemon_unbind(struct cachefiles_cache *cache)
{
_enter("");
if (test_bit(CACHEFILES_READY, &cache->flags)) {
printk(KERN_INFO "CacheFiles:"
" File cache on %s unregistering\n",
cache->cache.identifier);
fscache_withdraw_cache(&cache->cache);
}
dput(cache->graveyard);
mntput(cache->mnt);
kfree(cache->rootdirname);
kfree(cache->secctx);
kfree(cache->tag);
_leave("");
}
| gpl-2.0 |
garwynn/caf_kernel_msm | arch/mn10300/unit-asb2364/irq-fpga.c | 10155 | 2646 | /* ASB2364 FPGA interrupt multiplexing
*
* Copyright (C) 2010 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 <linux/interrupt.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <unit/fpga-regs.h>
/*
* FPGA PIC operations
*/
static void asb2364_fpga_mask(struct irq_data *d)
{
ASB2364_FPGA_REG_MASK(d->irq - NR_CPU_IRQS) = 0x0001;
SyncExBus();
}
static void asb2364_fpga_ack(struct irq_data *d)
{
ASB2364_FPGA_REG_IRQ(d->irq - NR_CPU_IRQS) = 0x0001;
SyncExBus();
}
static void asb2364_fpga_mask_ack(struct irq_data *d)
{
ASB2364_FPGA_REG_MASK(d->irq - NR_CPU_IRQS) = 0x0001;
SyncExBus();
ASB2364_FPGA_REG_IRQ(d->irq - NR_CPU_IRQS) = 0x0001;
SyncExBus();
}
static void asb2364_fpga_unmask(struct irq_data *d)
{
ASB2364_FPGA_REG_MASK(d->irq - NR_CPU_IRQS) = 0x0000;
SyncExBus();
}
static struct irq_chip asb2364_fpga_pic = {
.name = "fpga",
.irq_ack = asb2364_fpga_ack,
.irq_mask = asb2364_fpga_mask,
.irq_mask_ack = asb2364_fpga_mask_ack,
.irq_unmask = asb2364_fpga_unmask,
};
/*
* FPGA PIC interrupt handler
*/
static irqreturn_t fpga_interrupt(int irq, void *_mask)
{
if ((ASB2364_FPGA_REG_IRQ_LAN & 0x0001) != 0x0001)
generic_handle_irq(FPGA_LAN_IRQ);
if ((ASB2364_FPGA_REG_IRQ_UART & 0x0001) != 0x0001)
generic_handle_irq(FPGA_UART_IRQ);
if ((ASB2364_FPGA_REG_IRQ_I2C & 0x0001) != 0x0001)
generic_handle_irq(FPGA_I2C_IRQ);
if ((ASB2364_FPGA_REG_IRQ_USB & 0x0001) != 0x0001)
generic_handle_irq(FPGA_USB_IRQ);
if ((ASB2364_FPGA_REG_IRQ_FPGA & 0x0001) != 0x0001)
generic_handle_irq(FPGA_FPGA_IRQ);
return IRQ_HANDLED;
}
/*
* Define an interrupt action for each FPGA PIC output
*/
static struct irqaction fpga_irq[] = {
[0] = {
.handler = fpga_interrupt,
.flags = IRQF_DISABLED | IRQF_SHARED,
.name = "fpga",
},
};
/*
* Initialise the FPGA's PIC
*/
void __init irq_fpga_init(void)
{
int irq;
ASB2364_FPGA_REG_MASK_LAN = 0x0001;
SyncExBus();
ASB2364_FPGA_REG_MASK_UART = 0x0001;
SyncExBus();
ASB2364_FPGA_REG_MASK_I2C = 0x0001;
SyncExBus();
ASB2364_FPGA_REG_MASK_USB = 0x0001;
SyncExBus();
ASB2364_FPGA_REG_MASK_FPGA = 0x0001;
SyncExBus();
for (irq = NR_CPU_IRQS; irq < NR_IRQS; irq++)
irq_set_chip_and_handler(irq, &asb2364_fpga_pic,
handle_level_irq);
/* the FPGA drives the XIRQ1 input on the CPU PIC */
setup_irq(XIRQ1, &fpga_irq[0]);
}
| gpl-2.0 |
magetron/linux | drivers/acpi/acpica/utmisc.c | 172 | 11760 | /*******************************************************************************
*
* Module Name: utmisc - common utility procedures
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2015, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utmisc")
/*******************************************************************************
*
* FUNCTION: acpi_ut_is_pci_root_bridge
*
* PARAMETERS: id - The HID/CID in string format
*
* RETURN: TRUE if the Id is a match for a PCI/PCI-Express Root Bridge
*
* DESCRIPTION: Determine if the input ID is a PCI Root Bridge ID.
*
******************************************************************************/
u8 acpi_ut_is_pci_root_bridge(char *id)
{
/*
* Check if this is a PCI root bridge.
* ACPI 3.0+: check for a PCI Express root also.
*/
if (!(strcmp(id,
PCI_ROOT_HID_STRING)) ||
!(strcmp(id, PCI_EXPRESS_ROOT_HID_STRING))) {
return (TRUE);
}
return (FALSE);
}
#if (defined ACPI_ASL_COMPILER || defined ACPI_EXEC_APP)
/*******************************************************************************
*
* FUNCTION: acpi_ut_is_aml_table
*
* PARAMETERS: table - An ACPI table
*
* RETURN: TRUE if table contains executable AML; FALSE otherwise
*
* DESCRIPTION: Check ACPI Signature for a table that contains AML code.
* Currently, these are DSDT,SSDT,PSDT. All other table types are
* data tables that do not contain AML code.
*
******************************************************************************/
u8 acpi_ut_is_aml_table(struct acpi_table_header *table)
{
/* These are the only tables that contain executable AML */
if (ACPI_COMPARE_NAME(table->signature, ACPI_SIG_DSDT) ||
ACPI_COMPARE_NAME(table->signature, ACPI_SIG_PSDT) ||
ACPI_COMPARE_NAME(table->signature, ACPI_SIG_SSDT) ||
ACPI_COMPARE_NAME(table->signature, ACPI_SIG_OSDT)) {
return (TRUE);
}
return (FALSE);
}
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ut_dword_byte_swap
*
* PARAMETERS: value - Value to be converted
*
* RETURN: u32 integer with bytes swapped
*
* DESCRIPTION: Convert a 32-bit value to big-endian (swap the bytes)
*
******************************************************************************/
u32 acpi_ut_dword_byte_swap(u32 value)
{
union {
u32 value;
u8 bytes[4];
} out;
union {
u32 value;
u8 bytes[4];
} in;
ACPI_FUNCTION_ENTRY();
in.value = value;
out.bytes[0] = in.bytes[3];
out.bytes[1] = in.bytes[2];
out.bytes[2] = in.bytes[1];
out.bytes[3] = in.bytes[0];
return (out.value);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_set_integer_width
*
* PARAMETERS: Revision From DSDT header
*
* RETURN: None
*
* DESCRIPTION: Set the global integer bit width based upon the revision
* of the DSDT. For Revision 1 and 0, Integers are 32 bits.
* For Revision 2 and above, Integers are 64 bits. Yes, this
* makes a difference.
*
******************************************************************************/
void acpi_ut_set_integer_width(u8 revision)
{
if (revision < 2) {
/* 32-bit case */
acpi_gbl_integer_bit_width = 32;
acpi_gbl_integer_nybble_width = 8;
acpi_gbl_integer_byte_width = 4;
} else {
/* 64-bit case (ACPI 2.0+) */
acpi_gbl_integer_bit_width = 64;
acpi_gbl_integer_nybble_width = 16;
acpi_gbl_integer_byte_width = 8;
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_create_update_state_and_push
*
* PARAMETERS: object - Object to be added to the new state
* action - Increment/Decrement
* state_list - List the state will be added to
*
* RETURN: Status
*
* DESCRIPTION: Create a new state and push it
*
******************************************************************************/
acpi_status
acpi_ut_create_update_state_and_push(union acpi_operand_object *object,
u16 action,
union acpi_generic_state **state_list)
{
union acpi_generic_state *state;
ACPI_FUNCTION_ENTRY();
/* Ignore null objects; these are expected */
if (!object) {
return (AE_OK);
}
state = acpi_ut_create_update_state(object, action);
if (!state) {
return (AE_NO_MEMORY);
}
acpi_ut_push_generic_state(state_list, state);
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_walk_package_tree
*
* PARAMETERS: source_object - The package to walk
* target_object - Target object (if package is being copied)
* walk_callback - Called once for each package element
* context - Passed to the callback function
*
* RETURN: Status
*
* DESCRIPTION: Walk through a package
*
******************************************************************************/
acpi_status
acpi_ut_walk_package_tree(union acpi_operand_object *source_object,
void *target_object,
acpi_pkg_callback walk_callback, void *context)
{
acpi_status status = AE_OK;
union acpi_generic_state *state_list = NULL;
union acpi_generic_state *state;
u32 this_index;
union acpi_operand_object *this_source_obj;
ACPI_FUNCTION_TRACE(ut_walk_package_tree);
state = acpi_ut_create_pkg_state(source_object, target_object, 0);
if (!state) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
while (state) {
/* Get one element of the package */
this_index = state->pkg.index;
this_source_obj = (union acpi_operand_object *)
state->pkg.source_object->package.elements[this_index];
/*
* Check for:
* 1) An uninitialized package element. It is completely
* legal to declare a package and leave it uninitialized
* 2) Not an internal object - can be a namespace node instead
* 3) Any type other than a package. Packages are handled in else
* case below.
*/
if ((!this_source_obj) ||
(ACPI_GET_DESCRIPTOR_TYPE(this_source_obj) !=
ACPI_DESC_TYPE_OPERAND)
|| (this_source_obj->common.type != ACPI_TYPE_PACKAGE)) {
status =
walk_callback(ACPI_COPY_TYPE_SIMPLE,
this_source_obj, state, context);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
state->pkg.index++;
while (state->pkg.index >=
state->pkg.source_object->package.count) {
/*
* We've handled all of the objects at this level, This means
* that we have just completed a package. That package may
* have contained one or more packages itself.
*
* Delete this state and pop the previous state (package).
*/
acpi_ut_delete_generic_state(state);
state = acpi_ut_pop_generic_state(&state_list);
/* Finished when there are no more states */
if (!state) {
/*
* We have handled all of the objects in the top level
* package just add the length of the package objects
* and exit
*/
return_ACPI_STATUS(AE_OK);
}
/*
* Go back up a level and move the index past the just
* completed package object.
*/
state->pkg.index++;
}
} else {
/* This is a subobject of type package */
status =
walk_callback(ACPI_COPY_TYPE_PACKAGE,
this_source_obj, state, context);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Push the current state and create a new one
* The callback above returned a new target package object.
*/
acpi_ut_push_generic_state(&state_list, state);
state = acpi_ut_create_pkg_state(this_source_obj,
state->pkg.
this_target_obj, 0);
if (!state) {
/* Free any stacked Update State objects */
while (state_list) {
state =
acpi_ut_pop_generic_state
(&state_list);
acpi_ut_delete_generic_state(state);
}
return_ACPI_STATUS(AE_NO_MEMORY);
}
}
}
/* We should never get here */
return_ACPI_STATUS(AE_AML_INTERNAL);
}
#ifdef ACPI_DEBUG_OUTPUT
/*******************************************************************************
*
* FUNCTION: acpi_ut_display_init_pathname
*
* PARAMETERS: type - Object type of the node
* obj_handle - Handle whose pathname will be displayed
* path - Additional path string to be appended.
* (NULL if no extra path)
*
* RETURN: acpi_status
*
* DESCRIPTION: Display full pathname of an object, DEBUG ONLY
*
******************************************************************************/
void
acpi_ut_display_init_pathname(u8 type,
struct acpi_namespace_node *obj_handle,
char *path)
{
acpi_status status;
struct acpi_buffer buffer;
ACPI_FUNCTION_ENTRY();
/* Only print the path if the appropriate debug level is enabled */
if (!(acpi_dbg_level & ACPI_LV_INIT_NAMES)) {
return;
}
/* Get the full pathname to the node */
buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
status = acpi_ns_handle_to_pathname(obj_handle, &buffer);
if (ACPI_FAILURE(status)) {
return;
}
/* Print what we're doing */
switch (type) {
case ACPI_TYPE_METHOD:
acpi_os_printf("Executing ");
break;
default:
acpi_os_printf("Initializing ");
break;
}
/* Print the object type and pathname */
acpi_os_printf("%-12s %s",
acpi_ut_get_type_name(type), (char *)buffer.pointer);
/* Extra path is used to append names like _STA, _INI, etc. */
if (path) {
acpi_os_printf(".%s", path);
}
acpi_os_printf("\n");
ACPI_FREE(buffer.pointer);
}
#endif
| gpl-2.0 |
koct9i/linux | drivers/ps3/ps3stor_lib.c | 172 | 9193 | // SPDX-License-Identifier: GPL-2.0-only
/*
* PS3 Storage Library
*
* Copyright (C) 2007 Sony Computer Entertainment Inc.
* Copyright 2007 Sony Corp.
*/
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <asm/lv1call.h>
#include <asm/ps3stor.h>
/*
* A workaround for flash memory I/O errors when the internal hard disk
* has not been formatted for OtherOS use. Delay disk close until flash
* memory is closed.
*/
static struct ps3_flash_workaround {
int flash_open;
int disk_open;
struct ps3_system_bus_device *disk_sbd;
} ps3_flash_workaround;
static int ps3stor_open_hv_device(struct ps3_system_bus_device *sbd)
{
int error = ps3_open_hv_device(sbd);
if (error)
return error;
if (sbd->match_id == PS3_MATCH_ID_STOR_FLASH)
ps3_flash_workaround.flash_open = 1;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK)
ps3_flash_workaround.disk_open = 1;
return 0;
}
static int ps3stor_close_hv_device(struct ps3_system_bus_device *sbd)
{
int error;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK
&& ps3_flash_workaround.disk_open
&& ps3_flash_workaround.flash_open) {
ps3_flash_workaround.disk_sbd = sbd;
return 0;
}
error = ps3_close_hv_device(sbd);
if (error)
return error;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK)
ps3_flash_workaround.disk_open = 0;
if (sbd->match_id == PS3_MATCH_ID_STOR_FLASH) {
ps3_flash_workaround.flash_open = 0;
if (ps3_flash_workaround.disk_sbd) {
ps3_close_hv_device(ps3_flash_workaround.disk_sbd);
ps3_flash_workaround.disk_open = 0;
ps3_flash_workaround.disk_sbd = NULL;
}
}
return 0;
}
static int ps3stor_probe_access(struct ps3_storage_device *dev)
{
int res, error;
unsigned int i;
unsigned long n;
if (dev->sbd.match_id == PS3_MATCH_ID_STOR_ROM) {
/* special case: CD-ROM is assumed always accessible */
dev->accessible_regions = 1;
return 0;
}
error = -EPERM;
for (i = 0; i < dev->num_regions; i++) {
dev_dbg(&dev->sbd.core,
"%s:%u: checking accessibility of region %u\n",
__func__, __LINE__, i);
dev->region_idx = i;
res = ps3stor_read_write_sectors(dev, dev->bounce_lpar, 0, 1,
0);
if (res) {
dev_dbg(&dev->sbd.core, "%s:%u: read failed, "
"region %u is not accessible\n", __func__,
__LINE__, i);
continue;
}
dev_dbg(&dev->sbd.core, "%s:%u: region %u is accessible\n",
__func__, __LINE__, i);
set_bit(i, &dev->accessible_regions);
/* We can access at least one region */
error = 0;
}
if (error)
return error;
n = hweight_long(dev->accessible_regions);
if (n > 1)
dev_info(&dev->sbd.core,
"%s:%u: %lu accessible regions found. Only the first "
"one will be used\n",
__func__, __LINE__, n);
dev->region_idx = __ffs(dev->accessible_regions);
dev_info(&dev->sbd.core,
"First accessible region has index %u start %llu size %llu\n",
dev->region_idx, dev->regions[dev->region_idx].start,
dev->regions[dev->region_idx].size);
return 0;
}
/**
* ps3stor_setup - Setup a storage device before use
* @dev: Pointer to a struct ps3_storage_device
* @handler: Pointer to an interrupt handler
*
* Returns 0 for success, or an error code
*/
int ps3stor_setup(struct ps3_storage_device *dev, irq_handler_t handler)
{
int error, res, alignment;
enum ps3_dma_page_size page_size;
error = ps3stor_open_hv_device(&dev->sbd);
if (error) {
dev_err(&dev->sbd.core,
"%s:%u: ps3_open_hv_device failed %d\n", __func__,
__LINE__, error);
goto fail;
}
error = ps3_sb_event_receive_port_setup(&dev->sbd, PS3_BINDING_CPU_ANY,
&dev->irq);
if (error) {
dev_err(&dev->sbd.core,
"%s:%u: ps3_sb_event_receive_port_setup failed %d\n",
__func__, __LINE__, error);
goto fail_close_device;
}
error = request_irq(dev->irq, handler, 0,
dev->sbd.core.driver->name, dev);
if (error) {
dev_err(&dev->sbd.core, "%s:%u: request_irq failed %d\n",
__func__, __LINE__, error);
goto fail_sb_event_receive_port_destroy;
}
alignment = min(__ffs(dev->bounce_size),
__ffs((unsigned long)dev->bounce_buf));
if (alignment < 12) {
dev_err(&dev->sbd.core,
"%s:%u: bounce buffer not aligned (%lx at 0x%p)\n",
__func__, __LINE__, dev->bounce_size, dev->bounce_buf);
error = -EINVAL;
goto fail_free_irq;
} else if (alignment < 16)
page_size = PS3_DMA_4K;
else
page_size = PS3_DMA_64K;
dev->sbd.d_region = &dev->dma_region;
ps3_dma_region_init(&dev->sbd, &dev->dma_region, page_size,
PS3_DMA_OTHER, dev->bounce_buf, dev->bounce_size);
res = ps3_dma_region_create(&dev->dma_region);
if (res) {
dev_err(&dev->sbd.core, "%s:%u: cannot create DMA region\n",
__func__, __LINE__);
error = -ENOMEM;
goto fail_free_irq;
}
dev->bounce_lpar = ps3_mm_phys_to_lpar(__pa(dev->bounce_buf));
dev->bounce_dma = dma_map_single(&dev->sbd.core, dev->bounce_buf,
dev->bounce_size, DMA_BIDIRECTIONAL);
if (!dev->bounce_dma) {
dev_err(&dev->sbd.core, "%s:%u: map DMA region failed\n",
__func__, __LINE__);
error = -ENODEV;
goto fail_free_dma;
}
error = ps3stor_probe_access(dev);
if (error) {
dev_err(&dev->sbd.core, "%s:%u: No accessible regions found\n",
__func__, __LINE__);
goto fail_unmap_dma;
}
return 0;
fail_unmap_dma:
dma_unmap_single(&dev->sbd.core, dev->bounce_dma, dev->bounce_size,
DMA_BIDIRECTIONAL);
fail_free_dma:
ps3_dma_region_free(&dev->dma_region);
fail_free_irq:
free_irq(dev->irq, dev);
fail_sb_event_receive_port_destroy:
ps3_sb_event_receive_port_destroy(&dev->sbd, dev->irq);
fail_close_device:
ps3stor_close_hv_device(&dev->sbd);
fail:
return error;
}
EXPORT_SYMBOL_GPL(ps3stor_setup);
/**
* ps3stor_teardown - Tear down a storage device after use
* @dev: Pointer to a struct ps3_storage_device
*/
void ps3stor_teardown(struct ps3_storage_device *dev)
{
int error;
dma_unmap_single(&dev->sbd.core, dev->bounce_dma, dev->bounce_size,
DMA_BIDIRECTIONAL);
ps3_dma_region_free(&dev->dma_region);
free_irq(dev->irq, dev);
error = ps3_sb_event_receive_port_destroy(&dev->sbd, dev->irq);
if (error)
dev_err(&dev->sbd.core,
"%s:%u: destroy event receive port failed %d\n",
__func__, __LINE__, error);
error = ps3stor_close_hv_device(&dev->sbd);
if (error)
dev_err(&dev->sbd.core,
"%s:%u: ps3_close_hv_device failed %d\n", __func__,
__LINE__, error);
}
EXPORT_SYMBOL_GPL(ps3stor_teardown);
/**
* ps3stor_read_write_sectors - read/write from/to a storage device
* @dev: Pointer to a struct ps3_storage_device
* @lpar: HV logical partition address
* @start_sector: First sector to read/write
* @sectors: Number of sectors to read/write
* @write: Flag indicating write (non-zero) or read (zero)
*
* Returns 0 for success, -1 in case of failure to submit the command, or
* an LV1 status value in case of other errors
*/
u64 ps3stor_read_write_sectors(struct ps3_storage_device *dev, u64 lpar,
u64 start_sector, u64 sectors, int write)
{
unsigned int region_id = dev->regions[dev->region_idx].id;
const char *op = write ? "write" : "read";
int res;
dev_dbg(&dev->sbd.core, "%s:%u: %s %llu sectors starting at %llu\n",
__func__, __LINE__, op, sectors, start_sector);
init_completion(&dev->done);
res = write ? lv1_storage_write(dev->sbd.dev_id, region_id,
start_sector, sectors, 0, lpar,
&dev->tag)
: lv1_storage_read(dev->sbd.dev_id, region_id,
start_sector, sectors, 0, lpar,
&dev->tag);
if (res) {
dev_dbg(&dev->sbd.core, "%s:%u: %s failed %d\n", __func__,
__LINE__, op, res);
return -1;
}
wait_for_completion(&dev->done);
if (dev->lv1_status) {
dev_dbg(&dev->sbd.core, "%s:%u: %s failed 0x%llx\n", __func__,
__LINE__, op, dev->lv1_status);
return dev->lv1_status;
}
dev_dbg(&dev->sbd.core, "%s:%u: %s completed\n", __func__, __LINE__,
op);
return 0;
}
EXPORT_SYMBOL_GPL(ps3stor_read_write_sectors);
/**
* ps3stor_send_command - send a device command to a storage device
* @dev: Pointer to a struct ps3_storage_device
* @cmd: Command number
* @arg1: First command argument
* @arg2: Second command argument
* @arg3: Third command argument
* @arg4: Fourth command argument
*
* Returns 0 for success, -1 in case of failure to submit the command, or
* an LV1 status value in case of other errors
*/
u64 ps3stor_send_command(struct ps3_storage_device *dev, u64 cmd, u64 arg1,
u64 arg2, u64 arg3, u64 arg4)
{
int res;
dev_dbg(&dev->sbd.core, "%s:%u: send device command 0x%llx\n", __func__,
__LINE__, cmd);
init_completion(&dev->done);
res = lv1_storage_send_device_command(dev->sbd.dev_id, cmd, arg1,
arg2, arg3, arg4, &dev->tag);
if (res) {
dev_err(&dev->sbd.core,
"%s:%u: send_device_command 0x%llx failed %d\n",
__func__, __LINE__, cmd, res);
return -1;
}
wait_for_completion(&dev->done);
if (dev->lv1_status) {
dev_dbg(&dev->sbd.core, "%s:%u: command 0x%llx failed 0x%llx\n",
__func__, __LINE__, cmd, dev->lv1_status);
return dev->lv1_status;
}
dev_dbg(&dev->sbd.core, "%s:%u: command 0x%llx completed\n", __func__,
__LINE__, cmd);
return 0;
}
EXPORT_SYMBOL_GPL(ps3stor_send_command);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PS3 Storage Bus Library");
MODULE_AUTHOR("Sony Corporation");
| gpl-2.0 |
classicsong/Range-Lock | drivers/staging/iio/dds/ad9910.c | 172 | 8552 | /*
* Driver for ADI Direct Digital Synthesis ad9910
*
* Copyright (c) 2010 Analog Devices Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include "../iio.h"
#include "../sysfs.h"
#define DRV_NAME "ad9910"
#define CFR1 0x0
#define CFR2 0x1
#define CFR3 0x2
#define AUXDAC 0x3
#define IOUPD 0x4
#define FTW 0x7
#define POW 0x8
#define ASF 0x9
#define MULTC 0x0A
#define DIG_RAMPL 0x0B
#define DIG_RAMPS 0x0C
#define DIG_RAMPR 0x0D
#define SIN_TONEP0 0x0E
#define SIN_TONEP1 0x0F
#define SIN_TONEP2 0x10
#define SIN_TONEP3 0x11
#define SIN_TONEP4 0x12
#define SIN_TONEP5 0x13
#define SIN_TONEP6 0x14
#define SIN_TONEP7 0x15
#define RAM_ENABLE (1 << 7)
#define MANUAL_OSK (1 << 7)
#define INVSIC (1 << 6)
#define DDS_SINEOP (1)
#define AUTO_OSK (1)
#define OSKEN (1 << 1)
#define LOAD_ARR (1 << 2)
#define CLR_PHA (1 << 3)
#define CLR_DIG (1 << 4)
#define ACLR_PHA (1 << 5)
#define ACLR_DIG (1 << 6)
#define LOAD_LRR (1 << 7)
#define LSB_FST (1)
#define SDIO_IPT (1 << 1)
#define EXT_PWD (1 << 3)
#define ADAC_PWD (1 << 4)
#define REFCLK_PWD (1 << 5)
#define DAC_PWD (1 << 6)
#define DIG_PWD (1 << 7)
#define ENA_AMP (1)
#define READ_FTW (1)
#define DIGR_LOW (1 << 1)
#define DIGR_HIGH (1 << 2)
#define DIGR_ENA (1 << 3)
#define SYNCCLK_ENA (1 << 6)
#define ITER_IOUPD (1 << 7)
#define TX_ENA (1 << 1)
#define PDCLK_INV (1 << 2)
#define PDCLK_ENB (1 << 3)
#define PARA_ENA (1 << 4)
#define SYNC_DIS (1 << 5)
#define DATA_ASS (1 << 6)
#define MATCH_ENA (1 << 7)
#define PLL_ENA (1)
#define PFD_RST (1 << 2)
#define REFCLK_RST (1 << 6)
#define REFCLK_BYP (1 << 7)
/* Register format: 1 byte addr + value */
struct ad9910_config {
u8 auxdac[5];
u8 ioupd[5];
u8 ftw[5];
u8 pow[3];
u8 asf[5];
u8 multc[5];
u8 dig_rampl[9];
u8 dig_ramps[9];
u8 dig_rampr[5];
u8 sin_tonep0[9];
u8 sin_tonep1[9];
u8 sin_tonep2[9];
u8 sin_tonep3[9];
u8 sin_tonep4[9];
u8 sin_tonep5[9];
u8 sin_tonep6[9];
u8 sin_tonep7[9];
};
struct ad9910_state {
struct mutex lock;
struct spi_device *sdev;
};
static ssize_t ad9910_set_parameter(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct spi_message msg;
struct spi_transfer xfer;
int ret;
struct ad9910_config *config = (struct ad9910_config *)buf;
struct iio_dev *idev = dev_get_drvdata(dev);
struct ad9910_state *st = iio_priv(idev);
xfer.len = 5;
xfer.tx_buf = &config->auxdac[0];
mutex_lock(&st->lock);
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->ioupd[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->ftw[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 3;
xfer.tx_buf = &config->pow[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->asf[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->multc[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->dig_rampl[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->dig_ramps[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->dig_rampr[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep0[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep1[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep2[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep3[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep4[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep5[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep6[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
xfer.len = 9;
xfer.tx_buf = &config->sin_tonep7[0];
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
error_ret:
mutex_unlock(&st->lock);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(dds, S_IWUSR, NULL, ad9910_set_parameter, 0);
static void ad9910_init(struct ad9910_state *st)
{
struct spi_message msg;
struct spi_transfer xfer;
int ret;
u8 cfr[5];
cfr[0] = CFR1;
cfr[1] = 0;
cfr[2] = MANUAL_OSK | INVSIC | DDS_SINEOP;
cfr[3] = AUTO_OSK | OSKEN | ACLR_PHA | ACLR_DIG | LOAD_LRR;
cfr[4] = 0;
mutex_lock(&st->lock);
xfer.len = 5;
xfer.tx_buf = 𝔠
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
cfr[0] = CFR2;
cfr[1] = ENA_AMP;
cfr[2] = READ_FTW | DIGR_ENA | ITER_IOUPD;
cfr[3] = TX_ENA | PDCLK_INV | PDCLK_ENB;
cfr[4] = PARA_ENA;
xfer.len = 5;
xfer.tx_buf = 𝔠
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
cfr[0] = CFR3;
cfr[1] = PLL_ENA;
cfr[2] = 0;
cfr[3] = REFCLK_RST | REFCLK_BYP;
cfr[4] = 0;
xfer.len = 5;
xfer.tx_buf = 𝔠
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
error_ret:
mutex_unlock(&st->lock);
}
static struct attribute *ad9910_attributes[] = {
&iio_dev_attr_dds.dev_attr.attr,
NULL,
};
static const struct attribute_group ad9910_attribute_group = {
.attrs = ad9910_attributes,
};
static const struct iio_info ad9910_info = {
.attrs = &ad9910_attribute_group,
.driver_module = THIS_MODULE,
};
static int __devinit ad9910_probe(struct spi_device *spi)
{
struct ad9910_state *st;
struct iio_dev *idev;
int ret = 0;
idev = iio_allocate_device(sizeof(*st));
if (idev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
spi_set_drvdata(spi, idev);
st = iio_priv(idev);
mutex_init(&st->lock);
st->sdev = spi;
idev->dev.parent = &spi->dev;
idev->info = &ad9910_info;
idev->modes = INDIO_DIRECT_MODE;
ret = iio_device_register(idev);
if (ret)
goto error_free_dev;
spi->max_speed_hz = 2000000;
spi->mode = SPI_MODE_3;
spi->bits_per_word = 8;
spi_setup(spi);
ad9910_init(st);
return 0;
error_free_dev:
iio_free_device(idev);
error_ret:
return ret;
}
static int __devexit ad9910_remove(struct spi_device *spi)
{
iio_device_unregister(spi_get_drvdata(spi));
iio_free_device(spi_get_drvdata(spi));
return 0;
}
static struct spi_driver ad9910_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ad9910_probe,
.remove = __devexit_p(ad9910_remove),
};
static __init int ad9910_spi_init(void)
{
return spi_register_driver(&ad9910_driver);
}
module_init(ad9910_spi_init);
static __exit void ad9910_spi_exit(void)
{
spi_unregister_driver(&ad9910_driver);
}
module_exit(ad9910_spi_exit);
MODULE_AUTHOR("Cliff Cai");
MODULE_DESCRIPTION("Analog Devices ad9910 driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
arasilinux/arasievm-kernel | net/tipc/name_distr.c | 172 | 9582 | /*
* net/tipc/name_distr.c: TIPC name distribution code
*
* Copyright (c) 2000-2006, Ericsson AB
* Copyright (c) 2005, 2010-2011, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "link.h"
#include "name_distr.h"
#define ITEM_SIZE sizeof(struct distr_item)
/**
* struct distr_item - publication info distributed to other nodes
* @type: name sequence type
* @lower: name sequence lower bound
* @upper: name sequence upper bound
* @ref: publishing port reference
* @key: publication key
*
* ===> All fields are stored in network byte order. <===
*
* First 3 fields identify (name or) name sequence being published.
* Reference field uniquely identifies port that published name sequence.
* Key field uniquely identifies publication, in the event a port has
* multiple publications of the same name sequence.
*
* Note: There is no field that identifies the publishing node because it is
* the same for all items contained within a publication message.
*/
struct distr_item {
__be32 type;
__be32 lower;
__be32 upper;
__be32 ref;
__be32 key;
};
/**
* List of externally visible publications by this node --
* that is, all publications having scope > TIPC_NODE_SCOPE.
*/
static LIST_HEAD(publ_root);
static u32 publ_cnt;
/**
* publ_to_item - add publication info to a publication message
*/
static void publ_to_item(struct distr_item *i, struct publication *p)
{
i->type = htonl(p->type);
i->lower = htonl(p->lower);
i->upper = htonl(p->upper);
i->ref = htonl(p->ref);
i->key = htonl(p->key);
}
/**
* named_prepare_buf - allocate & initialize a publication message
*/
static struct sk_buff *named_prepare_buf(u32 type, u32 size, u32 dest)
{
struct sk_buff *buf = tipc_buf_acquire(INT_H_SIZE + size);
struct tipc_msg *msg;
if (buf != NULL) {
msg = buf_msg(buf);
tipc_msg_init(msg, NAME_DISTRIBUTOR, type, INT_H_SIZE, dest);
msg_set_size(msg, INT_H_SIZE + size);
}
return buf;
}
static void named_cluster_distribute(struct sk_buff *buf)
{
struct sk_buff *buf_copy;
struct tipc_node *n_ptr;
list_for_each_entry(n_ptr, &tipc_node_list, list) {
if (tipc_node_active_links(n_ptr)) {
buf_copy = skb_copy(buf, GFP_ATOMIC);
if (!buf_copy)
break;
msg_set_destnode(buf_msg(buf_copy), n_ptr->addr);
tipc_link_send(buf_copy, n_ptr->addr, n_ptr->addr);
}
}
buf_discard(buf);
}
/**
* tipc_named_publish - tell other nodes about a new publication by this node
*/
void tipc_named_publish(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_add_tail(&publ->local_list, &publ_root);
publ_cnt++;
buf = named_prepare_buf(PUBLICATION, ITEM_SIZE, 0);
if (!buf) {
warn("Publication distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_withdraw - tell other nodes about a withdrawn publication by this node
*/
void tipc_named_withdraw(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_del(&publ->local_list);
publ_cnt--;
buf = named_prepare_buf(WITHDRAWAL, ITEM_SIZE, 0);
if (!buf) {
warn("Withdrawal distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_node_up - tell specified node about all publications by this node
*/
void tipc_named_node_up(unsigned long nodearg)
{
struct tipc_node *n_ptr;
struct link *l_ptr;
struct publication *publ;
struct distr_item *item = NULL;
struct sk_buff *buf = NULL;
struct list_head message_list;
u32 node = (u32)nodearg;
u32 left = 0;
u32 rest;
u32 max_item_buf = 0;
/* compute maximum amount of publication data to send per message */
read_lock_bh(&tipc_net_lock);
n_ptr = tipc_node_find(node);
if (n_ptr) {
tipc_node_lock(n_ptr);
l_ptr = n_ptr->active_links[0];
if (l_ptr)
max_item_buf = ((l_ptr->max_pkt - INT_H_SIZE) /
ITEM_SIZE) * ITEM_SIZE;
tipc_node_unlock(n_ptr);
}
read_unlock_bh(&tipc_net_lock);
if (!max_item_buf)
return;
/* create list of publication messages, then send them as a unit */
INIT_LIST_HEAD(&message_list);
read_lock_bh(&tipc_nametbl_lock);
rest = publ_cnt * ITEM_SIZE;
list_for_each_entry(publ, &publ_root, local_list) {
if (!buf) {
left = (rest <= max_item_buf) ? rest : max_item_buf;
rest -= left;
buf = named_prepare_buf(PUBLICATION, left, node);
if (!buf) {
warn("Bulk publication distribution failure\n");
goto exit;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
}
publ_to_item(item, publ);
item++;
left -= ITEM_SIZE;
if (!left) {
list_add_tail((struct list_head *)buf, &message_list);
buf = NULL;
}
}
exit:
read_unlock_bh(&tipc_nametbl_lock);
tipc_link_send_names(&message_list, (u32)node);
}
/**
* named_purge_publ - remove publication associated with a failed node
*
* Invoked for each publication issued by a newly failed node.
* Removes publication structure from name table & deletes it.
* In rare cases the link may have come back up again when this
* function is called, and we have two items representing the same
* publication. Nudge this item's key to distinguish it from the other.
*/
static void named_purge_publ(struct publication *publ)
{
struct publication *p;
write_lock_bh(&tipc_nametbl_lock);
publ->key += 1222345;
p = tipc_nametbl_remove_publ(publ->type, publ->lower,
publ->node, publ->ref, publ->key);
if (p)
tipc_nodesub_unsubscribe(&p->subscr);
write_unlock_bh(&tipc_nametbl_lock);
if (p != publ) {
err("Unable to remove publication from failed node\n"
"(type=%u, lower=%u, node=0x%x, ref=%u, key=%u)\n",
publ->type, publ->lower, publ->node, publ->ref, publ->key);
}
kfree(p);
}
/**
* tipc_named_recv - process name table update message sent by another node
*/
void tipc_named_recv(struct sk_buff *buf)
{
struct publication *publ;
struct tipc_msg *msg = buf_msg(buf);
struct distr_item *item = (struct distr_item *)msg_data(msg);
u32 count = msg_data_sz(msg) / ITEM_SIZE;
write_lock_bh(&tipc_nametbl_lock);
while (count--) {
if (msg_type(msg) == PUBLICATION) {
publ = tipc_nametbl_insert_publ(ntohl(item->type),
ntohl(item->lower),
ntohl(item->upper),
TIPC_CLUSTER_SCOPE,
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_subscribe(&publ->subscr,
msg_orignode(msg),
publ,
(net_ev_handler)
named_purge_publ);
}
} else if (msg_type(msg) == WITHDRAWAL) {
publ = tipc_nametbl_remove_publ(ntohl(item->type),
ntohl(item->lower),
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_unsubscribe(&publ->subscr);
kfree(publ);
} else {
err("Unable to remove publication by node 0x%x\n"
"(type=%u, lower=%u, ref=%u, key=%u)\n",
msg_orignode(msg),
ntohl(item->type), ntohl(item->lower),
ntohl(item->ref), ntohl(item->key));
}
} else {
warn("Unrecognized name table message received\n");
}
item++;
}
write_unlock_bh(&tipc_nametbl_lock);
buf_discard(buf);
}
/**
* tipc_named_reinit - re-initialize local publication list
*
* This routine is called whenever TIPC networking is (re)enabled.
* All existing publications by this node that have "cluster" or "zone" scope
* are updated to reflect the node's current network address.
* (If the node's address is unchanged, the update loop terminates immediately.)
*/
void tipc_named_reinit(void)
{
struct publication *publ;
write_lock_bh(&tipc_nametbl_lock);
list_for_each_entry(publ, &publ_root, local_list) {
if (publ->node == tipc_own_addr)
break;
publ->node = tipc_own_addr;
}
write_unlock_bh(&tipc_nametbl_lock);
}
| gpl-2.0 |
u-ra/android_kernel_htc_villec2 | drivers/input/misc/gpio_axis.c | 172 | 6080 | /* drivers/input/misc/gpio_axis.c
*
* Copyright (C) 2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/gpio_event.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <mach/board.h>
struct gpio_axis_state {
int debug_log;
struct gpio_event_input_devs *input_devs;
struct gpio_event_axis_info *info;
uint32_t pos;
};
uint16_t gpio_axis_4bit_gray_map_table[] = {
[0x0] = 0x0, [0x1] = 0x1, /* 0000 0001 */
[0x3] = 0x2, [0x2] = 0x3, /* 0011 0010 */
[0x6] = 0x4, [0x7] = 0x5, /* 0110 0111 */
[0x5] = 0x6, [0x4] = 0x7, /* 0101 0100 */
[0xc] = 0x8, [0xd] = 0x9, /* 1100 1101 */
[0xf] = 0xa, [0xe] = 0xb, /* 1111 1110 */
[0xa] = 0xc, [0xb] = 0xd, /* 1010 1011 */
[0x9] = 0xe, [0x8] = 0xf, /* 1001 1000 */
};
uint16_t gpio_axis_4bit_gray_map(struct gpio_event_axis_info *info, uint16_t in)
{
return gpio_axis_4bit_gray_map_table[in];
}
uint16_t gpio_axis_5bit_singletrack_map_table[] = {
[0x10] = 0x00, [0x14] = 0x01, [0x1c] = 0x02, /* 10000 10100 11100 */
[0x1e] = 0x03, [0x1a] = 0x04, [0x18] = 0x05, /* 11110 11010 11000 */
[0x08] = 0x06, [0x0a] = 0x07, [0x0e] = 0x08, /* 01000 01010 01110 */
[0x0f] = 0x09, [0x0d] = 0x0a, [0x0c] = 0x0b, /* 01111 01101 01100 */
[0x04] = 0x0c, [0x05] = 0x0d, [0x07] = 0x0e, /* 00100 00101 00111 */
[0x17] = 0x0f, [0x16] = 0x10, [0x06] = 0x11, /* 10111 10110 00110 */
[0x02] = 0x12, [0x12] = 0x13, [0x13] = 0x14, /* 00010 10010 10011 */
[0x1b] = 0x15, [0x0b] = 0x16, [0x03] = 0x17, /* 11011 01011 00011 */
[0x01] = 0x18, [0x09] = 0x19, [0x19] = 0x1a, /* 00001 01001 11001 */
[0x1d] = 0x1b, [0x15] = 0x1c, [0x11] = 0x1d, /* 11101 10101 10001 */
};
uint16_t gpio_axis_5bit_singletrack_map(
struct gpio_event_axis_info *info, uint16_t in)
{
return gpio_axis_5bit_singletrack_map_table[in];
}
static void gpio_event_update_axis(struct gpio_axis_state *as, int report)
{
struct gpio_event_axis_info *ai = as->info;
int i;
int change;
uint16_t state = 0;
uint16_t pos;
uint16_t old_pos = as->pos;
for (i = ai->count - 1; i >= 0; i--)
state = (state << 1) | gpio_get_value(ai->gpio[i]);
pos = ai->map(ai, state);
if ((ai->flags & GPIOEAF_PRINT_RAW) && (as->debug_log))
KEY_LOGD("axis %d-%d raw %x, pos %d -> %d\n",
ai->type, ai->code, state, old_pos, pos);
if (report && pos != old_pos) {
if (ai->type == EV_REL) {
change = (ai->decoded_size + pos - old_pos) %
ai->decoded_size;
if (change > ai->decoded_size / 2)
change -= ai->decoded_size;
if (change == ai->decoded_size / 2) {
if ((ai->flags & GPIOEAF_PRINT_EVENT) && (as->debug_log))
KEY_LOGD("axis %d-%d unknown direction, "
"pos %d -> %d\n", ai->type,
ai->code, old_pos, pos);
change = 0; /* no closest direction */
}
if ((ai->flags & GPIOEAF_PRINT_EVENT) && (as->debug_log))
KEY_LOGD("axis %d-%d change %d\n",
ai->type, ai->code, change);
input_report_rel(as->input_devs->dev[ai->dev],
ai->code, change);
} else {
if ((ai->flags & GPIOEAF_PRINT_EVENT) && (as->debug_log))
KEY_LOGD("axis %d-%d now %d\n",
ai->type, ai->code, pos);
input_event(as->input_devs->dev[ai->dev],
ai->type, ai->code, pos);
}
input_sync(as->input_devs->dev[ai->dev]);
}
as->pos = pos;
}
static irqreturn_t gpio_axis_irq_handler(int irq, void *dev_id)
{
struct gpio_axis_state *as = dev_id;
gpio_event_update_axis(as, 1);
return IRQ_HANDLED;
}
int gpio_event_axis_func(struct gpio_event_input_devs *input_devs,
struct gpio_event_info *info, void **data, int func)
{
int ret;
int i;
int irq;
struct gpio_event_axis_info *ai;
struct gpio_axis_state *as;
ai = container_of(info, struct gpio_event_axis_info, info);
if (func == GPIO_EVENT_FUNC_SUSPEND) {
for (i = 0; i < ai->count; i++)
disable_irq(gpio_to_irq(ai->gpio[i]));
return 0;
}
if (func == GPIO_EVENT_FUNC_RESUME) {
for (i = 0; i < ai->count; i++)
enable_irq(gpio_to_irq(ai->gpio[i]));
return 0;
}
if (func == GPIO_EVENT_FUNC_INIT) {
*data = as = kmalloc(sizeof(*as), GFP_KERNEL);
if (as == NULL) {
ret = -ENOMEM;
goto err_alloc_axis_state_failed;
}
if (board_build_flag() == 0)
as->debug_log = 0;
else
as->debug_log = 1;
as->input_devs = input_devs;
as->info = ai;
if (ai->dev >= input_devs->count) {
KEY_LOGE("KEY_ERR: %s: bad device index %d >= %d "
"for %d:%d\n", __func__, ai->dev, input_devs->count,
ai->type, ai->code);
ret = -EINVAL;
goto err_bad_device_index;
}
input_set_capability(input_devs->dev[ai->dev],
ai->type, ai->code);
if (ai->type == EV_ABS) {
input_set_abs_params(input_devs->dev[ai->dev], ai->code,
0, ai->decoded_size - 1, 0, 0);
}
for (i = 0; i < ai->count; i++) {
ret = gpio_request(ai->gpio[i], "gpio_event_axis");
if (ret < 0)
goto err_request_gpio_failed;
ret = gpio_direction_input(ai->gpio[i]);
if (ret < 0)
goto err_gpio_direction_input_failed;
ret = irq = gpio_to_irq(ai->gpio[i]);
if (ret < 0)
goto err_get_irq_num_failed;
ret = request_irq(irq, gpio_axis_irq_handler,
IRQF_TRIGGER_RISING |
IRQF_TRIGGER_FALLING,
"gpio_event_axis", as);
if (ret < 0)
goto err_request_irq_failed;
}
gpio_event_update_axis(as, 0);
return 0;
}
ret = 0;
as = *data;
for (i = ai->count - 1; i >= 0; i--) {
free_irq(gpio_to_irq(ai->gpio[i]), as);
err_request_irq_failed:
err_get_irq_num_failed:
err_gpio_direction_input_failed:
gpio_free(ai->gpio[i]);
err_request_gpio_failed:
;
}
err_bad_device_index:
kfree(as);
*data = NULL;
err_alloc_axis_state_failed:
return ret;
}
| gpl-2.0 |
Dm47021/Holo-a200 | drivers/mfd/tps8003x-gpadc.c | 428 | 17928 | /*
* drivers/mfd/tps8003x-gpadc.c
*
* Gpadc for TI's tps80031
*
* Copyright (c) 2011, NVIDIA 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/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/platform_device.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/hwmon-sysfs.h>
#include <linux/i2c/twl.h>
#include <linux/mfd/tps80031.h>
#include <linux/uaccess.h>
#include <linux/spinlock.h>
#define GPADC_CTRL 0x2e
#define GPSELECT_ISB 0x35
#define GPCH0_LSB 0x3b
#define GPCH0_MSB 0x3c
#define CTRL_P1 0x36
#define TOGGLE1 0x90
#define MISC1 0xe4
#define CTRL_P1_SP1 BIT(3)
#define TOGGLE1_GPADCR BIT(1)
#define GPADC_BUSY (1 << 0)
#define GPADC_EOC_SW (1 << 1)
#define SCALE (1 << 15)
#define TPS80031_GPADC_MAX_CHANNELS 17
#define TPS80031_GPADC_IOC_MAGIC '`'
#define TPS80031_GPADC_IOCX_ADC_RAW_READ _IO(TPS80031_GPADC_IOC_MAGIC, 0)
struct tps80031_gpadc_user_parms {
int channel;
int status;
u16 result;
};
struct tps80031_calibration {
s32 gain_error;
s32 offset_error;
};
struct tps80031_ideal_code {
s16 code1;
s16 code2;
};
struct tps80031_scalar_channel {
uint8_t delta1_addr;
uint8_t delta1_mask;
uint8_t delta2_addr;
uint8_t delta2_mask;
};
static struct tps80031_calibration
tps80031_calib_tbl[TPS80031_GPADC_MAX_CHANNELS];
static const uint32_t calibration_bit_map = 0x47FF;
static const uint32_t scalar_bit_map = 0x4785;
#define TPS80031_GPADC_TRIM1 0xCD
#define TPS80031_GPADC_TRIM2 0xCE
#define TPS80031_GPADC_TRIM3 0xCF
#define TPS80031_GPADC_TRIM4 0xD0
#define TPS80031_GPADC_TRIM5 0xD1
#define TPS80031_GPADC_TRIM6 0xD2
#define TPS80031_GPADC_TRIM7 0xD3
#define TPS80031_GPADC_TRIM8 0xD4
#define TPS80031_GPADC_TRIM9 0xD5
#define TPS80031_GPADC_TRIM10 0xD6
#define TPS80031_GPADC_TRIM11 0xD7
#define TPS80031_GPADC_TRIM12 0xD8
#define TPS80031_GPADC_TRIM13 0xD9
#define TPS80031_GPADC_TRIM14 0xDA
#define TPS80031_GPADC_TRIM15 0xDB
#define TPS80031_GPADC_TRIM16 0xDC
#define TPS80031_GPADC_TRIM19 0xFD
static const struct tps80031_scalar_channel
tps80031_trim[TPS80031_GPADC_MAX_CHANNELS] = {
{ TPS80031_GPADC_TRIM1, 0x7, TPS80031_GPADC_TRIM2, 0x07},
{ 0x00, },
{ TPS80031_GPADC_TRIM3, 0x1F, TPS80031_GPADC_TRIM4, 0x3F},
{ 0x00, },
{ 0x00, },
{ 0x00, },
{ 0x00, },
{ TPS80031_GPADC_TRIM7, 0x1F, TPS80031_GPADC_TRIM8, 0x1F },
{ TPS80031_GPADC_TRIM9, 0x0F, TPS80031_GPADC_TRIM10, 0x1F },
{ TPS80031_GPADC_TRIM11, 0x0F, TPS80031_GPADC_TRIM12, 0x1F },
{ TPS80031_GPADC_TRIM13, 0x0F, TPS80031_GPADC_TRIM14, 0x1F },
{ 0x00, },
{ 0x00, },
{ 0x00, },
{ TPS80031_GPADC_TRIM15, 0x0f, TPS80031_GPADC_TRIM16, 0x1F },
{ 0x00, },
{ 0x00 ,},
};
/*
* actual scaler gain is multiplied by 8 for fixed point operation
* 1.875 * 8 = 15
*/
static const uint16_t tps80031_gain[TPS80031_GPADC_MAX_CHANNELS] = {
1142, /* CHANNEL 0 */
8, /* CHANNEL 1 */
/* 1.875 */
15, /* CHANNEL 2 */
8, /* CHANNEL 3 */
8, /* CHANNEL 4 */
8, /* CHANNEL 5 */
8, /* CHANNEL 6 */
/* 5 */
40, /* CHANNEL 7 */
/* 6.25 */
50, /* CHANNEL 8 */
/* 11.25 */
90, /* CHANNEL 9 */
/* 6.875 */
55, /* CHANNEL 10 */
/* 1.875 */
15, /* CHANNEL 11 */
8, /* CHANNEL 12 */
8, /* CHANNEL 13 */
/* 6.875 */
55, /* CHANNEL 14 */
8, /* CHANNEL 15 */
8, /* CHANNEL 16 */
};
/*
* calibration not needed for channel 11, 12, 13, 15 and 16
* calibration offset is same for channel 1, 3, 4, 5
*/
static const struct tps80031_ideal_code
tps80031_ideal[TPS80031_GPADC_MAX_CHANNELS] = {
{463, 2982}, /* CHANNEL 0 */
{328, 3604}, /* CHANNEL 1 */
{221, 3274}, /* CHANNEL 2 */
{328, 3604}, /* CHANNEL 3 */
{328, 3604}, /* CHANNEL 4 */
{328, 3604}, /* CHANNEL 5 */
{328, 3604}, /* CHANNEL 6 */
{1966, 3013}, /* CHANNEL 7 */
{328, 2754}, /* CHANNEL 8 */
{728, 3275}, /* CHANNEL 9 */
{596, 3274}, /* CHANNEL 10 */
{0, 0}, /* CHANNEL 11 */
{0, 0}, /* CHANNEL 12 */
{0, 0}, /* CHANNEL 13 */
{193, 2859}, /* CHANNEL 14 */
{0, 0}, /* CHANNEL 15 */
{0, 0}, /* CHANNEL 16 */
};
struct tps80031_gpadc_data {
struct device *dev;
struct mutex lock;
};
static struct tps80031_gpadc_data *the_gpadc;
static ssize_t show_gain(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
int value;
int status;
value = tps80031_calib_tbl[attr->index].gain_error;
status = sprintf(buf, "%d\n", value);
return status;
}
static ssize_t set_gain(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
long val;
int status = count;
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
if ((strict_strtol(buf, 10, &val) < 0) || (val < 15000)
|| (val > 60000))
return -EINVAL;
tps80031_calib_tbl[attr->index].gain_error = val;
return status;
}
static ssize_t show_offset(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
int value;
int status;
value = tps80031_calib_tbl[attr->index].offset_error;
status = sprintf(buf, "%d\n", value);
return status;
}
static ssize_t set_offset(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
long val;
int status = count;
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
if ((strict_strtol(buf, 10, &val) < 0) || (val < 15000)
|| (val > 60000))
return -EINVAL;
tps80031_calib_tbl[attr->index].offset_error = val;
return status;
}
static int tps80031_reg_read(struct tps80031_gpadc_data *gpadc, int sid,
int reg, uint8_t *val)
{
int ret;
ret = tps80031_read(gpadc->dev->parent, sid, reg, val);
if (ret < 0)
dev_err(gpadc->dev, "Failed read register 0x%02x\n", reg);
return ret;
}
static int tps80031_reg_write(struct tps80031_gpadc_data *gpadc, int sid,
int reg, uint8_t val)
{
int ret;
ret = tps80031_write(gpadc->dev->parent, sid, reg, val);
if (ret < 0)
dev_err(gpadc->dev, "Failed write register 0x%02x\n", reg);
return ret;
}
static int tps80031_gpadc_channel_raw_read(struct tps80031_gpadc_data *gpadc)
{
uint8_t msb, lsb;
int ret;
ret = tps80031_reg_read(gpadc, SLAVE_ID2, GPCH0_LSB, &lsb);
if (ret < 0)
return ret;
ret = tps80031_reg_read(gpadc, SLAVE_ID2, GPCH0_MSB, &msb);
if (ret < 0)
return ret;
return (int)((msb << 8) | lsb);
}
static int tps80031_gpadc_read_channels(struct tps80031_gpadc_data *gpadc,
uint32_t channel)
{
uint8_t bits;
int gain_error;
int offset_error;
int raw_code;
int corrected_code;
int channel_value;
int raw_channel_value;
/* TPS80031 has 12bit ADC */
bits = 12;
raw_code = tps80031_gpadc_channel_raw_read(gpadc);
if (raw_code < 0)
return raw_code;
/*
* Channels 0,2,7,8,9,10,14 offst and gain cannot
* be fully compensated by software
*/
if (channel == 7)
return raw_code;
/*
* multiply by 1000 to convert the unit to milli
* division by 1024 (>> bits) for 10/12 bit ADC
* division by 8 (>> 3) for actual scaler gain
*/
raw_channel_value =
(raw_code * tps80031_gain[channel] * 1000) >> (bits + 3);
gain_error = tps80031_calib_tbl[channel].gain_error;
offset_error = tps80031_calib_tbl[channel].offset_error;
corrected_code = (raw_code * SCALE - offset_error) / gain_error;
channel_value =
(corrected_code * tps80031_gain[channel] * 1000) >> (bits + 3);
return channel_value;
}
static int tps80031_gpadc_wait_conversion_ready(
struct tps80031_gpadc_data *gpadc,
unsigned int timeout_ms)
{
int ret;
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(timeout_ms);
do {
uint8_t reg;
ret = tps80031_reg_read(gpadc, SLAVE_ID2, CTRL_P1, ®);
if (ret < 0)
return ret;
if (!(reg & GPADC_BUSY) &&
(reg & GPADC_EOC_SW))
return 0;
} while (!time_after(jiffies, timeout));
return -EAGAIN;
}
static inline int tps80031_gpadc_config
(struct tps80031_gpadc_data *gpadc, int channel_no)
{
int ret = 0;
ret = tps80031_reg_write(gpadc, SLAVE_ID2, TOGGLE1, TOGGLE1_GPADCR);
if (ret < 0)
return ret;
ret = tps80031_reg_write(gpadc, SLAVE_ID2, GPSELECT_ISB, channel_no);
if (ret < 0)
return ret;
ret = tps80031_reg_write(gpadc, SLAVE_ID2, GPADC_CTRL, 0xef);
if (ret < 0)
return ret;
ret = tps80031_reg_write(gpadc, SLAVE_ID1, MISC1, 0x02);
if (ret < 0)
return ret;
return ret;
}
int tps80031_gpadc_conversion(int channel_no)
{
int ret = 0;
int read_value;
mutex_lock(&the_gpadc->lock);
ret = tps80031_gpadc_config(the_gpadc, channel_no);
if (ret < 0)
goto err;
/* start ADC conversion */
ret = tps80031_reg_write(the_gpadc, SLAVE_ID2, CTRL_P1, CTRL_P1_SP1);
if (ret < 0)
goto err;
/* Wait until conversion is ready (ctrl register returns EOC) */
ret = tps80031_gpadc_wait_conversion_ready(the_gpadc, 5);
if (ret) {
dev_dbg(the_gpadc->dev, "conversion timeout!\n");
goto err;
}
read_value = tps80031_gpadc_read_channels(the_gpadc, channel_no);
mutex_unlock(&the_gpadc->lock);
return read_value;
err:
mutex_unlock(&the_gpadc->lock);
return ret;
}
EXPORT_SYMBOL_GPL(tps80031_gpadc_conversion);
static SENSOR_DEVICE_ATTR(in0_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 0);
static SENSOR_DEVICE_ATTR(in0_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 0);
static SENSOR_DEVICE_ATTR(in1_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 1);
static SENSOR_DEVICE_ATTR(in1_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 1);
static SENSOR_DEVICE_ATTR(in2_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 2);
static SENSOR_DEVICE_ATTR(in2_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 2);
static SENSOR_DEVICE_ATTR(in3_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 3);
static SENSOR_DEVICE_ATTR(in3_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 3);
static SENSOR_DEVICE_ATTR(in4_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 4);
static SENSOR_DEVICE_ATTR(in4_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 4);
static SENSOR_DEVICE_ATTR(in5_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 5);
static SENSOR_DEVICE_ATTR(in5_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 5);
static SENSOR_DEVICE_ATTR(in6_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 6);
static SENSOR_DEVICE_ATTR(in6_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 6);
static SENSOR_DEVICE_ATTR(in7_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 7);
static SENSOR_DEVICE_ATTR(in7_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 7);
static SENSOR_DEVICE_ATTR(in8_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 8);
static SENSOR_DEVICE_ATTR(in8_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 8);
static SENSOR_DEVICE_ATTR(in9_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 9);
static SENSOR_DEVICE_ATTR(in9_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 9);
static SENSOR_DEVICE_ATTR(in10_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 10);
static SENSOR_DEVICE_ATTR(in10_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 10);
static SENSOR_DEVICE_ATTR(in11_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 11);
static SENSOR_DEVICE_ATTR(in11_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 11);
static SENSOR_DEVICE_ATTR(in12_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 12);
static SENSOR_DEVICE_ATTR(in12_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 12);
static SENSOR_DEVICE_ATTR(in13_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 13);
static SENSOR_DEVICE_ATTR(in13_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 13);
static SENSOR_DEVICE_ATTR(in14_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 14);
static SENSOR_DEVICE_ATTR(in14_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 14);
static SENSOR_DEVICE_ATTR(in15_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 15);
static SENSOR_DEVICE_ATTR(in15_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 15);
static SENSOR_DEVICE_ATTR(in16_gain, S_IRUGO|S_IWUSR, show_gain, set_gain, 16);
static SENSOR_DEVICE_ATTR(in16_offset, S_IRUGO|S_IWUSR,
show_offset, set_offset, 16);
#define IN_ATTRS(X)\
&sensor_dev_attr_in##X##_gain.dev_attr.attr, \
&sensor_dev_attr_in##X##_offset.dev_attr.attr \
static struct attribute *tps80031_gpadc_attributes[] = {
IN_ATTRS(0),
IN_ATTRS(1),
IN_ATTRS(2),
IN_ATTRS(3),
IN_ATTRS(4),
IN_ATTRS(5),
IN_ATTRS(6),
IN_ATTRS(7),
IN_ATTRS(8),
IN_ATTRS(9),
IN_ATTRS(10),
IN_ATTRS(11),
IN_ATTRS(12),
IN_ATTRS(13),
IN_ATTRS(14),
IN_ATTRS(15),
IN_ATTRS(16),
NULL
};
static const struct attribute_group tps80031_gpadc_group = {
.attrs = tps80031_gpadc_attributes,
};
static long tps80031_gpadc_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct tps80031_gpadc_user_parms par;
int val, ret, channel_no;
ret = copy_from_user(&par, (void __user *) arg, sizeof(par));
if (ret) {
dev_dbg(the_gpadc->dev, "copy_from_user: %d\n", ret);
return -EACCES;
}
switch (cmd) {
case TPS80031_GPADC_IOCX_ADC_RAW_READ:
channel_no = par.channel;
val = tps80031_gpadc_conversion(channel_no);
if (likely(val > 0)) {
par.status = 0;
par.result = val;
} else if (val == 0) {
par.status = -ENODATA;
} else {
par.status = val;
}
break;
default:
return -EINVAL;
}
ret = copy_to_user((void __user *) arg, &par, sizeof(par));
if (ret) {
dev_dbg(the_gpadc->dev, "copy_to_user: %d\n", ret);
return -EACCES;
}
return 0;
}
static const struct file_operations tps80031_gpadc_fileops = {
.owner = THIS_MODULE,
.unlocked_ioctl = tps80031_gpadc_ioctl,
};
static struct miscdevice tps80031_gpadc_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "tps80031-gpadc",
.fops = &tps80031_gpadc_fileops
};
static int __devinit tps80031_gpadc_probe(struct platform_device *pdev)
{
struct tps80031_gpadc_data *gpadc;
s16 delta_error1 = 0, delta_error2 = 0;
s16 ideal_code1, ideal_code2;
s16 scalar_delta1 = 0, scalar_delta2 = 0;
s32 gain_error_1;
s32 offset_error;
uint8_t l_delta1, l_delta2, h_delta2;
uint8_t l_scalar1, l_scalar2;
uint8_t sign;
uint8_t index;
int ret;
gpadc = devm_kzalloc(&pdev->dev, sizeof *gpadc, GFP_KERNEL);
if (!gpadc)
return -ENOMEM;
gpadc->dev = &pdev->dev;
ret = misc_register(&tps80031_gpadc_device);
if (ret) {
dev_dbg(&pdev->dev, "could not register misc_device\n");
return ret;
}
platform_set_drvdata(pdev, gpadc);
mutex_init(&gpadc->lock);
for (index = 0; index < TPS80031_GPADC_MAX_CHANNELS; index++) {
if (~calibration_bit_map & (1 << index))
continue;
if (~scalar_bit_map & (1 << index)) {
ret = tps80031_reg_read(gpadc, SLAVE_ID2,
tps80031_trim[index].delta1_addr, &l_scalar1);
if (ret < 0)
goto err;
ret = tps80031_reg_read(gpadc, SLAVE_ID2,
tps80031_trim[index].delta2_addr, &l_scalar2);
if (ret < 0)
goto err;
l_scalar1 &= tps80031_trim[index].delta1_mask;
sign = l_scalar1 & 1;
scalar_delta1 = l_scalar1 >> 1;
if (sign)
scalar_delta1 = 0 - scalar_delta1;
l_scalar2 &= tps80031_trim[index].delta2_mask;
sign = l_scalar2 & 1;
scalar_delta2 = l_scalar2 >> 1;
if (sign)
scalar_delta2 = 0 - scalar_delta2;
} else {
scalar_delta1 = 0;
scalar_delta2 = 0;
}
ret = tps80031_reg_read(gpadc, SLAVE_ID2, TPS80031_GPADC_TRIM5,
&l_delta1);
if (ret < 0)
goto err;
ret = tps80031_reg_read(gpadc, SLAVE_ID2, TPS80031_GPADC_TRIM6,
&l_delta2);
if (ret < 0)
goto err;
ret = tps80031_reg_read(gpadc, SLAVE_ID2, TPS80031_GPADC_TRIM19,
&h_delta2);
if (ret < 0)
goto err;
sign = l_delta1 & 1;
delta_error1 = l_delta1 >> 1;
if (sign)
delta_error1 = (0 - delta_error1);
sign = l_delta2 & 1;
delta_error2 = (l_delta2 >> 1) | (h_delta2 << 7);
if (sign)
delta_error2 = (0 - delta_error2);
ideal_code1 = tps80031_ideal[index].code1 * 4;
ideal_code2 = tps80031_ideal[index].code2 * 4;
gain_error_1 = ((delta_error2 + scalar_delta2) -
(delta_error1 - scalar_delta1)) *
SCALE / (ideal_code2 - ideal_code1);
offset_error = (delta_error1 + scalar_delta1) *
SCALE - gain_error_1 * ideal_code1;
tps80031_calib_tbl[index].gain_error = gain_error_1 + SCALE;
tps80031_calib_tbl[index].offset_error = offset_error;
}
the_gpadc = gpadc;
ret = sysfs_create_group(&pdev->dev.kobj, &tps80031_gpadc_group);
if (ret) {
dev_err(&pdev->dev, "could not create sysfs files\n");
goto err;
}
return 0;
err:
misc_deregister(&tps80031_gpadc_device);
return ret;
}
static int __devexit tps80031_gpadc_remove(struct platform_device *pdev)
{
sysfs_remove_group(&pdev->dev.kobj, &tps80031_gpadc_group);
misc_deregister(&tps80031_gpadc_device);
return 0;
}
static struct platform_driver tps80031_gpadc_driver = {
.probe = tps80031_gpadc_probe,
.remove = __devexit_p(tps80031_gpadc_remove),
.driver = {
.name = "tps80031-gpadc",
.owner = THIS_MODULE,
},
};
static int __init tps80031_gpadc_init(void)
{
return platform_driver_register(&tps80031_gpadc_driver);
}
module_init(tps80031_gpadc_init);
static void __exit tps80031_gpadc_exit(void)
{
platform_driver_unregister(&tps80031_gpadc_driver);
}
module_exit(tps80031_gpadc_exit);
MODULE_ALIAS("platform:tps80031-gpadc");
MODULE_DESCRIPTION("tps80031 ADC driver");
| gpl-2.0 |
ernestj/pitft | arch/tile/kernel/setup.c | 428 | 49446 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mmzone.h>
#include <linux/bootmem.h>
#include <linux/module.h>
#include <linux/node.h>
#include <linux/cpu.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/kexec.h>
#include <linux/pci.h>
#include <linux/swiotlb.h>
#include <linux/initrd.h>
#include <linux/io.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/timex.h>
#include <linux/hugetlb.h>
#include <linux/start_kernel.h>
#include <linux/screen_info.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/cacheflush.h>
#include <asm/pgalloc.h>
#include <asm/mmu_context.h>
#include <hv/hypervisor.h>
#include <arch/interrupts.h>
/* <linux/smp.h> doesn't provide this definition. */
#ifndef CONFIG_SMP
#define setup_max_cpus 1
#endif
static inline int ABS(int x) { return x >= 0 ? x : -x; }
/* Chip information */
char chip_model[64] __write_once;
#ifdef CONFIG_VT
struct screen_info screen_info;
#endif
struct pglist_data node_data[MAX_NUMNODES] __read_mostly;
EXPORT_SYMBOL(node_data);
/* Information on the NUMA nodes that we compute early */
unsigned long node_start_pfn[MAX_NUMNODES];
unsigned long node_end_pfn[MAX_NUMNODES];
unsigned long __initdata node_memmap_pfn[MAX_NUMNODES];
unsigned long __initdata node_percpu_pfn[MAX_NUMNODES];
unsigned long __initdata node_free_pfn[MAX_NUMNODES];
static unsigned long __initdata node_percpu[MAX_NUMNODES];
/*
* per-CPU stack and boot info.
*/
DEFINE_PER_CPU(unsigned long, boot_sp) =
(unsigned long)init_stack + THREAD_SIZE;
#ifdef CONFIG_SMP
DEFINE_PER_CPU(unsigned long, boot_pc) = (unsigned long)start_kernel;
#else
/*
* The variable must be __initdata since it references __init code.
* With CONFIG_SMP it is per-cpu data, which is exempt from validation.
*/
unsigned long __initdata boot_pc = (unsigned long)start_kernel;
#endif
#ifdef CONFIG_HIGHMEM
/* Page frame index of end of lowmem on each controller. */
unsigned long node_lowmem_end_pfn[MAX_NUMNODES];
/* Number of pages that can be mapped into lowmem. */
static unsigned long __initdata mappable_physpages;
#endif
/* Data on which physical memory controller corresponds to which NUMA node */
int node_controller[MAX_NUMNODES] = { [0 ... MAX_NUMNODES-1] = -1 };
#ifdef CONFIG_HIGHMEM
/* Map information from VAs to PAs */
unsigned long pbase_map[1 << (32 - HPAGE_SHIFT)]
__write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(pbase_map);
/* Map information from PAs to VAs */
void *vbase_map[NR_PA_HIGHBIT_VALUES]
__write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(vbase_map);
#endif
/* Node number as a function of the high PA bits */
int highbits_to_node[NR_PA_HIGHBIT_VALUES] __write_once;
EXPORT_SYMBOL(highbits_to_node);
static unsigned int __initdata maxmem_pfn = -1U;
static unsigned int __initdata maxnodemem_pfn[MAX_NUMNODES] = {
[0 ... MAX_NUMNODES-1] = -1U
};
static nodemask_t __initdata isolnodes;
#if defined(CONFIG_PCI) && !defined(__tilegx__)
enum { DEFAULT_PCI_RESERVE_MB = 64 };
static unsigned int __initdata pci_reserve_mb = DEFAULT_PCI_RESERVE_MB;
unsigned long __initdata pci_reserve_start_pfn = -1U;
unsigned long __initdata pci_reserve_end_pfn = -1U;
#endif
static int __init setup_maxmem(char *str)
{
unsigned long long maxmem;
if (str == NULL || (maxmem = memparse(str, NULL)) == 0)
return -EINVAL;
maxmem_pfn = (maxmem >> HPAGE_SHIFT) << (HPAGE_SHIFT - PAGE_SHIFT);
pr_info("Forcing RAM used to no more than %dMB\n",
maxmem_pfn >> (20 - PAGE_SHIFT));
return 0;
}
early_param("maxmem", setup_maxmem);
static int __init setup_maxnodemem(char *str)
{
char *endp;
unsigned long long maxnodemem;
long node;
node = str ? simple_strtoul(str, &endp, 0) : INT_MAX;
if (node >= MAX_NUMNODES || *endp != ':')
return -EINVAL;
maxnodemem = memparse(endp+1, NULL);
maxnodemem_pfn[node] = (maxnodemem >> HPAGE_SHIFT) <<
(HPAGE_SHIFT - PAGE_SHIFT);
pr_info("Forcing RAM used on node %ld to no more than %dMB\n",
node, maxnodemem_pfn[node] >> (20 - PAGE_SHIFT));
return 0;
}
early_param("maxnodemem", setup_maxnodemem);
struct memmap_entry {
u64 addr; /* start of memory segment */
u64 size; /* size of memory segment */
};
static struct memmap_entry memmap_map[64];
static int memmap_nr;
static void add_memmap_region(u64 addr, u64 size)
{
if (memmap_nr >= ARRAY_SIZE(memmap_map)) {
pr_err("Ooops! Too many entries in the memory map!\n");
return;
}
memmap_map[memmap_nr].addr = addr;
memmap_map[memmap_nr].size = size;
memmap_nr++;
}
static int __init setup_memmap(char *p)
{
char *oldp;
u64 start_at, mem_size;
if (!p)
return -EINVAL;
if (!strncmp(p, "exactmap", 8)) {
pr_err("\"memmap=exactmap\" not valid on tile\n");
return 0;
}
oldp = p;
mem_size = memparse(p, &p);
if (p == oldp)
return -EINVAL;
if (*p == '@') {
pr_err("\"memmap=nn@ss\" (force RAM) invalid on tile\n");
} else if (*p == '#') {
pr_err("\"memmap=nn#ss\" (force ACPI data) invalid on tile\n");
} else if (*p == '$') {
start_at = memparse(p+1, &p);
add_memmap_region(start_at, mem_size);
} else {
if (mem_size == 0)
return -EINVAL;
maxmem_pfn = (mem_size >> HPAGE_SHIFT) <<
(HPAGE_SHIFT - PAGE_SHIFT);
}
return *p == '\0' ? 0 : -EINVAL;
}
early_param("memmap", setup_memmap);
static int __init setup_mem(char *str)
{
return setup_maxmem(str);
}
early_param("mem", setup_mem); /* compatibility with x86 */
static int __init setup_isolnodes(char *str)
{
char buf[MAX_NUMNODES * 5];
if (str == NULL || nodelist_parse(str, isolnodes) != 0)
return -EINVAL;
nodelist_scnprintf(buf, sizeof(buf), isolnodes);
pr_info("Set isolnodes value to '%s'\n", buf);
return 0;
}
early_param("isolnodes", setup_isolnodes);
#if defined(CONFIG_PCI) && !defined(__tilegx__)
static int __init setup_pci_reserve(char* str)
{
unsigned long mb;
if (str == NULL || strict_strtoul(str, 0, &mb) != 0 ||
mb > 3 * 1024)
return -EINVAL;
pci_reserve_mb = mb;
pr_info("Reserving %dMB for PCIE root complex mappings\n",
pci_reserve_mb);
return 0;
}
early_param("pci_reserve", setup_pci_reserve);
#endif
#ifndef __tilegx__
/*
* vmalloc=size forces the vmalloc area to be exactly 'size' bytes.
* This can be used to increase (or decrease) the vmalloc area.
*/
static int __init parse_vmalloc(char *arg)
{
if (!arg)
return -EINVAL;
VMALLOC_RESERVE = (memparse(arg, &arg) + PGDIR_SIZE - 1) & PGDIR_MASK;
/* See validate_va() for more on this test. */
if ((long)_VMALLOC_START >= 0)
early_panic("\"vmalloc=%#lx\" value too large: maximum %#lx\n",
VMALLOC_RESERVE, _VMALLOC_END - 0x80000000UL);
return 0;
}
early_param("vmalloc", parse_vmalloc);
#endif
#ifdef CONFIG_HIGHMEM
/*
* Determine for each controller where its lowmem is mapped and how much of
* it is mapped there. On controller zero, the first few megabytes are
* already mapped in as code at MEM_SV_START, so in principle we could
* start our data mappings higher up, but for now we don't bother, to avoid
* additional confusion.
*
* One question is whether, on systems with more than 768 Mb and
* controllers of different sizes, to map in a proportionate amount of
* each one, or to try to map the same amount from each controller.
* (E.g. if we have three controllers with 256MB, 1GB, and 256MB
* respectively, do we map 256MB from each, or do we map 128 MB, 512
* MB, and 128 MB respectively?) For now we use a proportionate
* solution like the latter.
*
* The VA/PA mapping demands that we align our decisions at 16 MB
* boundaries so that we can rapidly convert VA to PA.
*/
static void *__init setup_pa_va_mapping(void)
{
unsigned long curr_pages = 0;
unsigned long vaddr = PAGE_OFFSET;
nodemask_t highonlynodes = isolnodes;
int i, j;
memset(pbase_map, -1, sizeof(pbase_map));
memset(vbase_map, -1, sizeof(vbase_map));
/* Node zero cannot be isolated for LOWMEM purposes. */
node_clear(0, highonlynodes);
/* Count up the number of pages on non-highonlynodes controllers. */
mappable_physpages = 0;
for_each_online_node(i) {
if (!node_isset(i, highonlynodes))
mappable_physpages +=
node_end_pfn[i] - node_start_pfn[i];
}
for_each_online_node(i) {
unsigned long start = node_start_pfn[i];
unsigned long end = node_end_pfn[i];
unsigned long size = end - start;
unsigned long vaddr_end;
if (node_isset(i, highonlynodes)) {
/* Mark this controller as having no lowmem. */
node_lowmem_end_pfn[i] = start;
continue;
}
curr_pages += size;
if (mappable_physpages > MAXMEM_PFN) {
vaddr_end = PAGE_OFFSET +
(((u64)curr_pages * MAXMEM_PFN /
mappable_physpages)
<< PAGE_SHIFT);
} else {
vaddr_end = PAGE_OFFSET + (curr_pages << PAGE_SHIFT);
}
for (j = 0; vaddr < vaddr_end; vaddr += HPAGE_SIZE, ++j) {
unsigned long this_pfn =
start + (j << HUGETLB_PAGE_ORDER);
pbase_map[vaddr >> HPAGE_SHIFT] = this_pfn;
if (vbase_map[__pfn_to_highbits(this_pfn)] ==
(void *)-1)
vbase_map[__pfn_to_highbits(this_pfn)] =
(void *)(vaddr & HPAGE_MASK);
}
node_lowmem_end_pfn[i] = start + (j << HUGETLB_PAGE_ORDER);
BUG_ON(node_lowmem_end_pfn[i] > end);
}
/* Return highest address of any mapped memory. */
return (void *)vaddr;
}
#endif /* CONFIG_HIGHMEM */
/*
* Register our most important memory mappings with the debug stub.
*
* This is up to 4 mappings for lowmem, one mapping per memory
* controller, plus one for our text segment.
*/
static void store_permanent_mappings(void)
{
int i;
for_each_online_node(i) {
HV_PhysAddr pa = ((HV_PhysAddr)node_start_pfn[i]) << PAGE_SHIFT;
#ifdef CONFIG_HIGHMEM
HV_PhysAddr high_mapped_pa = node_lowmem_end_pfn[i];
#else
HV_PhysAddr high_mapped_pa = node_end_pfn[i];
#endif
unsigned long pages = high_mapped_pa - node_start_pfn[i];
HV_VirtAddr addr = (HV_VirtAddr) __va(pa);
hv_store_mapping(addr, pages << PAGE_SHIFT, pa);
}
hv_store_mapping((HV_VirtAddr)_text,
(uint32_t)(_einittext - _text), 0);
}
/*
* Use hv_inquire_physical() to populate node_{start,end}_pfn[]
* and node_online_map, doing suitable sanity-checking.
* Also set min_low_pfn, max_low_pfn, and max_pfn.
*/
static void __init setup_memory(void)
{
int i, j;
int highbits_seen[NR_PA_HIGHBIT_VALUES] = { 0 };
#ifdef CONFIG_HIGHMEM
long highmem_pages;
#endif
#ifndef __tilegx__
int cap;
#endif
#if defined(CONFIG_HIGHMEM) || defined(__tilegx__)
long lowmem_pages;
#endif
unsigned long physpages = 0;
/* We are using a char to hold the cpu_2_node[] mapping */
BUILD_BUG_ON(MAX_NUMNODES > 127);
/* Discover the ranges of memory available to us */
for (i = 0; ; ++i) {
unsigned long start, size, end, highbits;
HV_PhysAddrRange range = hv_inquire_physical(i);
if (range.size == 0)
break;
#ifdef CONFIG_FLATMEM
if (i > 0) {
pr_err("Can't use discontiguous PAs: %#llx..%#llx\n",
range.size, range.start + range.size);
continue;
}
#endif
#ifndef __tilegx__
if ((unsigned long)range.start) {
pr_err("Range not at 4GB multiple: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
#endif
if ((range.start & (HPAGE_SIZE-1)) != 0 ||
(range.size & (HPAGE_SIZE-1)) != 0) {
unsigned long long start_pa = range.start;
unsigned long long orig_size = range.size;
range.start = (start_pa + HPAGE_SIZE - 1) & HPAGE_MASK;
range.size -= (range.start - start_pa);
range.size &= HPAGE_MASK;
pr_err("Range not hugepage-aligned: %#llx..%#llx:"
" now %#llx-%#llx\n",
start_pa, start_pa + orig_size,
range.start, range.start + range.size);
}
highbits = __pa_to_highbits(range.start);
if (highbits >= NR_PA_HIGHBIT_VALUES) {
pr_err("PA high bits too high: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
if (highbits_seen[highbits]) {
pr_err("Range overlaps in high bits: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
highbits_seen[highbits] = 1;
if (PFN_DOWN(range.size) > maxnodemem_pfn[i]) {
int max_size = maxnodemem_pfn[i];
if (max_size > 0) {
pr_err("Maxnodemem reduced node %d to"
" %d pages\n", i, max_size);
range.size = PFN_PHYS(max_size);
} else {
pr_err("Maxnodemem disabled node %d\n", i);
continue;
}
}
if (physpages + PFN_DOWN(range.size) > maxmem_pfn) {
int max_size = maxmem_pfn - physpages;
if (max_size > 0) {
pr_err("Maxmem reduced node %d to %d pages\n",
i, max_size);
range.size = PFN_PHYS(max_size);
} else {
pr_err("Maxmem disabled node %d\n", i);
continue;
}
}
if (i >= MAX_NUMNODES) {
pr_err("Too many PA nodes (#%d): %#llx...%#llx\n",
i, range.size, range.size + range.start);
continue;
}
start = range.start >> PAGE_SHIFT;
size = range.size >> PAGE_SHIFT;
end = start + size;
#ifndef __tilegx__
if (((HV_PhysAddr)end << PAGE_SHIFT) !=
(range.start + range.size)) {
pr_err("PAs too high to represent: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
#endif
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Blocks that overlap the pci reserved region must
* have enough space to hold the maximum percpu data
* region at the top of the range. If there isn't
* enough space above the reserved region, just
* truncate the node.
*/
if (start <= pci_reserve_start_pfn &&
end > pci_reserve_start_pfn) {
unsigned int per_cpu_size =
__per_cpu_end - __per_cpu_start;
unsigned int percpu_pages =
NR_CPUS * (PFN_UP(per_cpu_size) >> PAGE_SHIFT);
if (end < pci_reserve_end_pfn + percpu_pages) {
end = pci_reserve_start_pfn;
pr_err("PCI mapping region reduced node %d to"
" %ld pages\n", i, end - start);
}
}
#endif
for (j = __pfn_to_highbits(start);
j <= __pfn_to_highbits(end - 1); j++)
highbits_to_node[j] = i;
node_start_pfn[i] = start;
node_end_pfn[i] = end;
node_controller[i] = range.controller;
physpages += size;
max_pfn = end;
/* Mark node as online */
node_set(i, node_online_map);
node_set(i, node_possible_map);
}
#ifndef __tilegx__
/*
* For 4KB pages, mem_map "struct page" data is 1% of the size
* of the physical memory, so can be quite big (640 MB for
* four 16G zones). These structures must be mapped in
* lowmem, and since we currently cap out at about 768 MB,
* it's impractical to try to use this much address space.
* For now, arbitrarily cap the amount of physical memory
* we're willing to use at 8 million pages (32GB of 4KB pages).
*/
cap = 8 * 1024 * 1024; /* 8 million pages */
if (physpages > cap) {
int num_nodes = num_online_nodes();
int cap_each = cap / num_nodes;
unsigned long dropped_pages = 0;
for (i = 0; i < num_nodes; ++i) {
int size = node_end_pfn[i] - node_start_pfn[i];
if (size > cap_each) {
dropped_pages += (size - cap_each);
node_end_pfn[i] = node_start_pfn[i] + cap_each;
}
}
physpages -= dropped_pages;
pr_warning("Only using %ldMB memory;"
" ignoring %ldMB.\n",
physpages >> (20 - PAGE_SHIFT),
dropped_pages >> (20 - PAGE_SHIFT));
pr_warning("Consider using a larger page size.\n");
}
#endif
/* Heap starts just above the last loaded address. */
min_low_pfn = PFN_UP((unsigned long)_end - PAGE_OFFSET);
#ifdef CONFIG_HIGHMEM
/* Find where we map lowmem from each controller. */
high_memory = setup_pa_va_mapping();
/* Set max_low_pfn based on what node 0 can directly address. */
max_low_pfn = node_lowmem_end_pfn[0];
lowmem_pages = (mappable_physpages > MAXMEM_PFN) ?
MAXMEM_PFN : mappable_physpages;
highmem_pages = (long) (physpages - lowmem_pages);
pr_notice("%ldMB HIGHMEM available.\n",
pages_to_mb(highmem_pages > 0 ? highmem_pages : 0));
pr_notice("%ldMB LOWMEM available.\n",
pages_to_mb(lowmem_pages));
#else
/* Set max_low_pfn based on what node 0 can directly address. */
max_low_pfn = node_end_pfn[0];
#ifndef __tilegx__
if (node_end_pfn[0] > MAXMEM_PFN) {
pr_warning("Only using %ldMB LOWMEM.\n",
MAXMEM>>20);
pr_warning("Use a HIGHMEM enabled kernel.\n");
max_low_pfn = MAXMEM_PFN;
max_pfn = MAXMEM_PFN;
node_end_pfn[0] = MAXMEM_PFN;
} else {
pr_notice("%ldMB memory available.\n",
pages_to_mb(node_end_pfn[0]));
}
for (i = 1; i < MAX_NUMNODES; ++i) {
node_start_pfn[i] = 0;
node_end_pfn[i] = 0;
}
high_memory = __va(node_end_pfn[0]);
#else
lowmem_pages = 0;
for (i = 0; i < MAX_NUMNODES; ++i) {
int pages = node_end_pfn[i] - node_start_pfn[i];
lowmem_pages += pages;
if (pages)
high_memory = pfn_to_kaddr(node_end_pfn[i]);
}
pr_notice("%ldMB memory available.\n",
pages_to_mb(lowmem_pages));
#endif
#endif
}
/*
* On 32-bit machines, we only put bootmem on the low controller,
* since PAs > 4GB can't be used in bootmem. In principle one could
* imagine, e.g., multiple 1 GB controllers all of which could support
* bootmem, but in practice using controllers this small isn't a
* particularly interesting scenario, so we just keep it simple and
* use only the first controller for bootmem on 32-bit machines.
*/
static inline int node_has_bootmem(int nid)
{
#ifdef CONFIG_64BIT
return 1;
#else
return nid == 0;
#endif
}
static inline unsigned long alloc_bootmem_pfn(int nid,
unsigned long size,
unsigned long goal)
{
void *kva = __alloc_bootmem_node(NODE_DATA(nid), size,
PAGE_SIZE, goal);
unsigned long pfn = kaddr_to_pfn(kva);
BUG_ON(goal && PFN_PHYS(pfn) != goal);
return pfn;
}
static void __init setup_bootmem_allocator_node(int i)
{
unsigned long start, end, mapsize, mapstart;
if (node_has_bootmem(i)) {
NODE_DATA(i)->bdata = &bootmem_node_data[i];
} else {
/* Share controller zero's bdata for now. */
NODE_DATA(i)->bdata = &bootmem_node_data[0];
return;
}
/* Skip up to after the bss in node 0. */
start = (i == 0) ? min_low_pfn : node_start_pfn[i];
/* Only lowmem, if we're a HIGHMEM build. */
#ifdef CONFIG_HIGHMEM
end = node_lowmem_end_pfn[i];
#else
end = node_end_pfn[i];
#endif
/* No memory here. */
if (end == start)
return;
/* Figure out where the bootmem bitmap is located. */
mapsize = bootmem_bootmap_pages(end - start);
if (i == 0) {
/* Use some space right before the heap on node 0. */
mapstart = start;
start += mapsize;
} else {
/* Allocate bitmap on node 0 to avoid page table issues. */
mapstart = alloc_bootmem_pfn(0, PFN_PHYS(mapsize), 0);
}
/* Initialize a node. */
init_bootmem_node(NODE_DATA(i), mapstart, start, end);
/* Free all the space back into the allocator. */
free_bootmem(PFN_PHYS(start), PFN_PHYS(end - start));
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Throw away any memory aliased by the PCI region.
*/
if (pci_reserve_start_pfn < end && pci_reserve_end_pfn > start) {
start = max(pci_reserve_start_pfn, start);
end = min(pci_reserve_end_pfn, end);
reserve_bootmem(PFN_PHYS(start), PFN_PHYS(end - start),
BOOTMEM_EXCLUSIVE);
}
#endif
}
static void __init setup_bootmem_allocator(void)
{
int i;
for (i = 0; i < MAX_NUMNODES; ++i)
setup_bootmem_allocator_node(i);
/* Reserve any memory excluded by "memmap" arguments. */
for (i = 0; i < memmap_nr; ++i) {
struct memmap_entry *m = &memmap_map[i];
reserve_bootmem(m->addr, m->size, 0);
}
#ifdef CONFIG_BLK_DEV_INITRD
if (initrd_start) {
/* Make sure the initrd memory region is not modified. */
if (reserve_bootmem(initrd_start, initrd_end - initrd_start,
BOOTMEM_EXCLUSIVE)) {
pr_crit("The initrd memory region has been polluted. Disabling it.\n");
initrd_start = 0;
initrd_end = 0;
} else {
/*
* Translate initrd_start & initrd_end from PA to VA for
* future access.
*/
initrd_start += PAGE_OFFSET;
initrd_end += PAGE_OFFSET;
}
}
#endif
#ifdef CONFIG_KEXEC
if (crashk_res.start != crashk_res.end)
reserve_bootmem(crashk_res.start, resource_size(&crashk_res), 0);
#endif
}
void *__init alloc_remap(int nid, unsigned long size)
{
int pages = node_end_pfn[nid] - node_start_pfn[nid];
void *map = pfn_to_kaddr(node_memmap_pfn[nid]);
BUG_ON(size != pages * sizeof(struct page));
memset(map, 0, size);
return map;
}
static int __init percpu_size(void)
{
int size = __per_cpu_end - __per_cpu_start;
size += PERCPU_MODULE_RESERVE;
size += PERCPU_DYNAMIC_EARLY_SIZE;
if (size < PCPU_MIN_UNIT_SIZE)
size = PCPU_MIN_UNIT_SIZE;
size = roundup(size, PAGE_SIZE);
/* In several places we assume the per-cpu data fits on a huge page. */
BUG_ON(kdata_huge && size > HPAGE_SIZE);
return size;
}
static void __init zone_sizes_init(void)
{
unsigned long zones_size[MAX_NR_ZONES] = { 0 };
int size = percpu_size();
int num_cpus = smp_height * smp_width;
const unsigned long dma_end = (1UL << (32 - PAGE_SHIFT));
int i;
for (i = 0; i < num_cpus; ++i)
node_percpu[cpu_to_node(i)] += size;
for_each_online_node(i) {
unsigned long start = node_start_pfn[i];
unsigned long end = node_end_pfn[i];
#ifdef CONFIG_HIGHMEM
unsigned long lowmem_end = node_lowmem_end_pfn[i];
#else
unsigned long lowmem_end = end;
#endif
int memmap_size = (end - start) * sizeof(struct page);
node_free_pfn[i] = start;
/*
* Set aside pages for per-cpu data and the mem_map array.
*
* Since the per-cpu data requires special homecaching,
* if we are in kdata_huge mode, we put it at the end of
* the lowmem region. If we're not in kdata_huge mode,
* we take the per-cpu pages from the bottom of the
* controller, since that avoids fragmenting a huge page
* that users might want. We always take the memmap
* from the bottom of the controller, since with
* kdata_huge that lets it be under a huge TLB entry.
*
* If the user has requested isolnodes for a controller,
* though, there'll be no lowmem, so we just alloc_bootmem
* the memmap. There will be no percpu memory either.
*/
if (i != 0 && cpu_isset(i, isolnodes)) {
node_memmap_pfn[i] =
alloc_bootmem_pfn(0, memmap_size, 0);
BUG_ON(node_percpu[i] != 0);
} else if (node_has_bootmem(start)) {
unsigned long goal = 0;
node_memmap_pfn[i] =
alloc_bootmem_pfn(i, memmap_size, 0);
if (kdata_huge)
goal = PFN_PHYS(lowmem_end) - node_percpu[i];
if (node_percpu[i])
node_percpu_pfn[i] =
alloc_bootmem_pfn(i, node_percpu[i],
goal);
} else {
/* In non-bootmem zones, just reserve some pages. */
node_memmap_pfn[i] = node_free_pfn[i];
node_free_pfn[i] += PFN_UP(memmap_size);
if (!kdata_huge) {
node_percpu_pfn[i] = node_free_pfn[i];
node_free_pfn[i] += PFN_UP(node_percpu[i]);
} else {
node_percpu_pfn[i] =
lowmem_end - PFN_UP(node_percpu[i]);
}
}
#ifdef CONFIG_HIGHMEM
if (start > lowmem_end) {
zones_size[ZONE_NORMAL] = 0;
zones_size[ZONE_HIGHMEM] = end - start;
} else {
zones_size[ZONE_NORMAL] = lowmem_end - start;
zones_size[ZONE_HIGHMEM] = end - lowmem_end;
}
#else
zones_size[ZONE_NORMAL] = end - start;
#endif
if (start < dma_end) {
zones_size[ZONE_DMA] = min(zones_size[ZONE_NORMAL],
dma_end - start);
zones_size[ZONE_NORMAL] -= zones_size[ZONE_DMA];
} else {
zones_size[ZONE_DMA] = 0;
}
/* Take zone metadata from controller 0 if we're isolnode. */
if (node_isset(i, isolnodes))
NODE_DATA(i)->bdata = &bootmem_node_data[0];
free_area_init_node(i, zones_size, start, NULL);
printk(KERN_DEBUG " Normal zone: %ld per-cpu pages\n",
PFN_UP(node_percpu[i]));
/* Track the type of memory on each node */
if (zones_size[ZONE_NORMAL] || zones_size[ZONE_DMA])
node_set_state(i, N_NORMAL_MEMORY);
#ifdef CONFIG_HIGHMEM
if (end != start)
node_set_state(i, N_HIGH_MEMORY);
#endif
node_set_online(i);
}
}
#ifdef CONFIG_NUMA
/* which logical CPUs are on which nodes */
struct cpumask node_2_cpu_mask[MAX_NUMNODES] __write_once;
EXPORT_SYMBOL(node_2_cpu_mask);
/* which node each logical CPU is on */
char cpu_2_node[NR_CPUS] __write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(cpu_2_node);
/* Return cpu_to_node() except for cpus not yet assigned, which return -1 */
static int __init cpu_to_bound_node(int cpu, struct cpumask* unbound_cpus)
{
if (!cpu_possible(cpu) || cpumask_test_cpu(cpu, unbound_cpus))
return -1;
else
return cpu_to_node(cpu);
}
/* Return number of immediately-adjacent tiles sharing the same NUMA node. */
static int __init node_neighbors(int node, int cpu,
struct cpumask *unbound_cpus)
{
int neighbors = 0;
int w = smp_width;
int h = smp_height;
int x = cpu % w;
int y = cpu / w;
if (x > 0 && cpu_to_bound_node(cpu-1, unbound_cpus) == node)
++neighbors;
if (x < w-1 && cpu_to_bound_node(cpu+1, unbound_cpus) == node)
++neighbors;
if (y > 0 && cpu_to_bound_node(cpu-w, unbound_cpus) == node)
++neighbors;
if (y < h-1 && cpu_to_bound_node(cpu+w, unbound_cpus) == node)
++neighbors;
return neighbors;
}
static void __init setup_numa_mapping(void)
{
int distance[MAX_NUMNODES][NR_CPUS];
HV_Coord coord;
int cpu, node, cpus, i, x, y;
int num_nodes = num_online_nodes();
struct cpumask unbound_cpus;
nodemask_t default_nodes;
cpumask_clear(&unbound_cpus);
/* Get set of nodes we will use for defaults */
nodes_andnot(default_nodes, node_online_map, isolnodes);
if (nodes_empty(default_nodes)) {
BUG_ON(!node_isset(0, node_online_map));
pr_err("Forcing NUMA node zero available as a default node\n");
node_set(0, default_nodes);
}
/* Populate the distance[] array */
memset(distance, -1, sizeof(distance));
cpu = 0;
for (coord.y = 0; coord.y < smp_height; ++coord.y) {
for (coord.x = 0; coord.x < smp_width;
++coord.x, ++cpu) {
BUG_ON(cpu >= nr_cpu_ids);
if (!cpu_possible(cpu)) {
cpu_2_node[cpu] = -1;
continue;
}
for_each_node_mask(node, default_nodes) {
HV_MemoryControllerInfo info =
hv_inquire_memory_controller(
coord, node_controller[node]);
distance[node][cpu] =
ABS(info.coord.x) + ABS(info.coord.y);
}
cpumask_set_cpu(cpu, &unbound_cpus);
}
}
cpus = cpu;
/*
* Round-robin through the NUMA nodes until all the cpus are
* assigned. We could be more clever here (e.g. create four
* sorted linked lists on the same set of cpu nodes, and pull
* off them in round-robin sequence, removing from all four
* lists each time) but given the relatively small numbers
* involved, O(n^2) seem OK for a one-time cost.
*/
node = first_node(default_nodes);
while (!cpumask_empty(&unbound_cpus)) {
int best_cpu = -1;
int best_distance = INT_MAX;
for (cpu = 0; cpu < cpus; ++cpu) {
if (cpumask_test_cpu(cpu, &unbound_cpus)) {
/*
* Compute metric, which is how much
* closer the cpu is to this memory
* controller than the others, shifted
* up, and then the number of
* neighbors already in the node as an
* epsilon adjustment to try to keep
* the nodes compact.
*/
int d = distance[node][cpu] * num_nodes;
for_each_node_mask(i, default_nodes) {
if (i != node)
d -= distance[i][cpu];
}
d *= 8; /* allow space for epsilon */
d -= node_neighbors(node, cpu, &unbound_cpus);
if (d < best_distance) {
best_cpu = cpu;
best_distance = d;
}
}
}
BUG_ON(best_cpu < 0);
cpumask_set_cpu(best_cpu, &node_2_cpu_mask[node]);
cpu_2_node[best_cpu] = node;
cpumask_clear_cpu(best_cpu, &unbound_cpus);
node = next_node(node, default_nodes);
if (node == MAX_NUMNODES)
node = first_node(default_nodes);
}
/* Print out node assignments and set defaults for disabled cpus */
cpu = 0;
for (y = 0; y < smp_height; ++y) {
printk(KERN_DEBUG "NUMA cpu-to-node row %d:", y);
for (x = 0; x < smp_width; ++x, ++cpu) {
if (cpu_to_node(cpu) < 0) {
pr_cont(" -");
cpu_2_node[cpu] = first_node(default_nodes);
} else {
pr_cont(" %d", cpu_to_node(cpu));
}
}
pr_cont("\n");
}
}
static struct cpu cpu_devices[NR_CPUS];
static int __init topology_init(void)
{
int i;
for_each_online_node(i)
register_one_node(i);
for (i = 0; i < smp_height * smp_width; ++i)
register_cpu(&cpu_devices[i], i);
return 0;
}
subsys_initcall(topology_init);
#else /* !CONFIG_NUMA */
#define setup_numa_mapping() do { } while (0)
#endif /* CONFIG_NUMA */
/*
* Initialize hugepage support on this cpu. We do this on all cores
* early in boot: before argument parsing for the boot cpu, and after
* argument parsing but before the init functions run on the secondaries.
* So the values we set up here in the hypervisor may be overridden on
* the boot cpu as arguments are parsed.
*/
static void init_super_pages(void)
{
#ifdef CONFIG_HUGETLB_SUPER_PAGES
int i;
for (i = 0; i < HUGE_SHIFT_ENTRIES; ++i)
hv_set_pte_super_shift(i, huge_shift[i]);
#endif
}
/**
* setup_cpu() - Do all necessary per-cpu, tile-specific initialization.
* @boot: Is this the boot cpu?
*
* Called from setup_arch() on the boot cpu, or online_secondary().
*/
void setup_cpu(int boot)
{
/* The boot cpu sets up its permanent mappings much earlier. */
if (!boot)
store_permanent_mappings();
/* Allow asynchronous TLB interrupts. */
#if CHIP_HAS_TILE_DMA()
arch_local_irq_unmask(INT_DMATLB_MISS);
arch_local_irq_unmask(INT_DMATLB_ACCESS);
#endif
#ifdef __tilegx__
arch_local_irq_unmask(INT_SINGLE_STEP_K);
#endif
/*
* Allow user access to many generic SPRs, like the cycle
* counter, PASS/FAIL/DONE, INTERRUPT_CRITICAL_SECTION, etc.
*/
__insn_mtspr(SPR_MPL_WORLD_ACCESS_SET_0, 1);
#if CHIP_HAS_SN()
/* Static network is not restricted. */
__insn_mtspr(SPR_MPL_SN_ACCESS_SET_0, 1);
#endif
/*
* Set the MPL for interrupt control 0 & 1 to the corresponding
* values. This includes access to the SYSTEM_SAVE and EX_CONTEXT
* SPRs, as well as the interrupt mask.
*/
__insn_mtspr(SPR_MPL_INTCTRL_0_SET_0, 1);
__insn_mtspr(SPR_MPL_INTCTRL_1_SET_1, 1);
/* Initialize IRQ support for this cpu. */
setup_irq_regs();
#ifdef CONFIG_HARDWALL
/* Reset the network state on this cpu. */
reset_network_state();
#endif
init_super_pages();
}
#ifdef CONFIG_BLK_DEV_INITRD
static int __initdata set_initramfs_file;
static char __initdata initramfs_file[128] = "initramfs";
static int __init setup_initramfs_file(char *str)
{
if (str == NULL)
return -EINVAL;
strncpy(initramfs_file, str, sizeof(initramfs_file) - 1);
set_initramfs_file = 1;
return 0;
}
early_param("initramfs_file", setup_initramfs_file);
/*
* We look for a file called "initramfs" in the hvfs. If there is one, we
* allocate some memory for it and it will be unpacked to the initramfs.
* If it's compressed, the initd code will uncompress it first.
*/
static void __init load_hv_initrd(void)
{
HV_FS_StatInfo stat;
int fd, rc;
void *initrd;
/* If initrd has already been set, skip initramfs file in hvfs. */
if (initrd_start)
return;
fd = hv_fs_findfile((HV_VirtAddr) initramfs_file);
if (fd == HV_ENOENT) {
if (set_initramfs_file) {
pr_warning("No such hvfs initramfs file '%s'\n",
initramfs_file);
return;
} else {
/* Try old backwards-compatible name. */
fd = hv_fs_findfile((HV_VirtAddr)"initramfs.cpio.gz");
if (fd == HV_ENOENT)
return;
}
}
BUG_ON(fd < 0);
stat = hv_fs_fstat(fd);
BUG_ON(stat.size < 0);
if (stat.flags & HV_FS_ISDIR) {
pr_warning("Ignoring hvfs file '%s': it's a directory.\n",
initramfs_file);
return;
}
initrd = alloc_bootmem_pages(stat.size);
rc = hv_fs_pread(fd, (HV_VirtAddr) initrd, stat.size, 0);
if (rc != stat.size) {
pr_err("Error reading %d bytes from hvfs file '%s': %d\n",
stat.size, initramfs_file, rc);
free_initrd_mem((unsigned long) initrd, stat.size);
return;
}
initrd_start = (unsigned long) initrd;
initrd_end = initrd_start + stat.size;
}
void __init free_initrd_mem(unsigned long begin, unsigned long end)
{
free_bootmem(__pa(begin), end - begin);
}
static int __init setup_initrd(char *str)
{
char *endp;
unsigned long initrd_size;
initrd_size = str ? simple_strtoul(str, &endp, 0) : 0;
if (initrd_size == 0 || *endp != '@')
return -EINVAL;
initrd_start = simple_strtoul(endp+1, &endp, 0);
if (initrd_start == 0)
return -EINVAL;
initrd_end = initrd_start + initrd_size;
return 0;
}
early_param("initrd", setup_initrd);
#else
static inline void load_hv_initrd(void) {}
#endif /* CONFIG_BLK_DEV_INITRD */
static void __init validate_hv(void)
{
/*
* It may already be too late, but let's check our built-in
* configuration against what the hypervisor is providing.
*/
unsigned long glue_size = hv_sysconf(HV_SYSCONF_GLUE_SIZE);
int hv_page_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_SMALL);
int hv_hpage_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_LARGE);
HV_ASIDRange asid_range;
#ifndef CONFIG_SMP
HV_Topology topology = hv_inquire_topology();
BUG_ON(topology.coord.x != 0 || topology.coord.y != 0);
if (topology.width != 1 || topology.height != 1) {
pr_warning("Warning: booting UP kernel on %dx%d grid;"
" will ignore all but first tile.\n",
topology.width, topology.height);
}
#endif
if (PAGE_OFFSET + HV_GLUE_START_CPA + glue_size > (unsigned long)_text)
early_panic("Hypervisor glue size %ld is too big!\n",
glue_size);
if (hv_page_size != PAGE_SIZE)
early_panic("Hypervisor page size %#x != our %#lx\n",
hv_page_size, PAGE_SIZE);
if (hv_hpage_size != HPAGE_SIZE)
early_panic("Hypervisor huge page size %#x != our %#lx\n",
hv_hpage_size, HPAGE_SIZE);
#ifdef CONFIG_SMP
/*
* Some hypervisor APIs take a pointer to a bitmap array
* whose size is at least the number of cpus on the chip.
* We use a struct cpumask for this, so it must be big enough.
*/
if ((smp_height * smp_width) > nr_cpu_ids)
early_panic("Hypervisor %d x %d grid too big for Linux"
" NR_CPUS %d\n", smp_height, smp_width,
nr_cpu_ids);
#endif
/*
* Check that we're using allowed ASIDs, and initialize the
* various asid variables to their appropriate initial states.
*/
asid_range = hv_inquire_asid(0);
__get_cpu_var(current_asid) = min_asid = asid_range.start;
max_asid = asid_range.start + asid_range.size - 1;
if (hv_confstr(HV_CONFSTR_CHIP_MODEL, (HV_VirtAddr)chip_model,
sizeof(chip_model)) < 0) {
pr_err("Warning: HV_CONFSTR_CHIP_MODEL not available\n");
strlcpy(chip_model, "unknown", sizeof(chip_model));
}
}
static void __init validate_va(void)
{
#ifndef __tilegx__ /* FIXME: GX: probably some validation relevant here */
/*
* Similarly, make sure we're only using allowed VAs.
* We assume we can contiguously use MEM_USER_INTRPT .. MEM_HV_START,
* and 0 .. KERNEL_HIGH_VADDR.
* In addition, make sure we CAN'T use the end of memory, since
* we use the last chunk of each pgd for the pgd_list.
*/
int i, user_kernel_ok = 0;
unsigned long max_va = 0;
unsigned long list_va =
((PGD_LIST_OFFSET / sizeof(pgd_t)) << PGDIR_SHIFT);
for (i = 0; ; ++i) {
HV_VirtAddrRange range = hv_inquire_virtual(i);
if (range.size == 0)
break;
if (range.start <= MEM_USER_INTRPT &&
range.start + range.size >= MEM_HV_START)
user_kernel_ok = 1;
if (range.start == 0)
max_va = range.size;
BUG_ON(range.start + range.size > list_va);
}
if (!user_kernel_ok)
early_panic("Hypervisor not configured for user/kernel VAs\n");
if (max_va == 0)
early_panic("Hypervisor not configured for low VAs\n");
if (max_va < KERNEL_HIGH_VADDR)
early_panic("Hypervisor max VA %#lx smaller than %#lx\n",
max_va, KERNEL_HIGH_VADDR);
/* Kernel PCs must have their high bit set; see intvec.S. */
if ((long)VMALLOC_START >= 0)
early_panic(
"Linux VMALLOC region below the 2GB line (%#lx)!\n"
"Reconfigure the kernel with smaller VMALLOC_RESERVE.\n",
VMALLOC_START);
#endif
}
/*
* cpu_lotar_map lists all the cpus that are valid for the supervisor
* to cache data on at a page level, i.e. what cpus can be placed in
* the LOTAR field of a PTE. It is equivalent to the set of possible
* cpus plus any other cpus that are willing to share their cache.
* It is set by hv_inquire_tiles(HV_INQ_TILES_LOTAR).
*/
struct cpumask __write_once cpu_lotar_map;
EXPORT_SYMBOL(cpu_lotar_map);
/*
* hash_for_home_map lists all the tiles that hash-for-home data
* will be cached on. Note that this may includes tiles that are not
* valid for this supervisor to use otherwise (e.g. if a hypervisor
* device is being shared between multiple supervisors).
* It is set by hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE).
*/
struct cpumask hash_for_home_map;
EXPORT_SYMBOL(hash_for_home_map);
/*
* cpu_cacheable_map lists all the cpus whose caches the hypervisor can
* flush on our behalf. It is set to cpu_possible_mask OR'ed with
* hash_for_home_map, and it is what should be passed to
* hv_flush_remote() to flush all caches. Note that if there are
* dedicated hypervisor driver tiles that have authorized use of their
* cache, those tiles will only appear in cpu_lotar_map, NOT in
* cpu_cacheable_map, as they are a special case.
*/
struct cpumask __write_once cpu_cacheable_map;
EXPORT_SYMBOL(cpu_cacheable_map);
static __initdata struct cpumask disabled_map;
static int __init disabled_cpus(char *str)
{
int boot_cpu = smp_processor_id();
if (str == NULL || cpulist_parse_crop(str, &disabled_map) != 0)
return -EINVAL;
if (cpumask_test_cpu(boot_cpu, &disabled_map)) {
pr_err("disabled_cpus: can't disable boot cpu %d\n", boot_cpu);
cpumask_clear_cpu(boot_cpu, &disabled_map);
}
return 0;
}
early_param("disabled_cpus", disabled_cpus);
void __init print_disabled_cpus(void)
{
if (!cpumask_empty(&disabled_map)) {
char buf[100];
cpulist_scnprintf(buf, sizeof(buf), &disabled_map);
pr_info("CPUs not available for Linux: %s\n", buf);
}
}
static void __init setup_cpu_maps(void)
{
struct cpumask hv_disabled_map, cpu_possible_init;
int boot_cpu = smp_processor_id();
int cpus, i, rc;
/* Learn which cpus are allowed by the hypervisor. */
rc = hv_inquire_tiles(HV_INQ_TILES_AVAIL,
(HV_VirtAddr) cpumask_bits(&cpu_possible_init),
sizeof(cpu_cacheable_map));
if (rc < 0)
early_panic("hv_inquire_tiles(AVAIL) failed: rc %d\n", rc);
if (!cpumask_test_cpu(boot_cpu, &cpu_possible_init))
early_panic("Boot CPU %d disabled by hypervisor!\n", boot_cpu);
/* Compute the cpus disabled by the hvconfig file. */
cpumask_complement(&hv_disabled_map, &cpu_possible_init);
/* Include them with the cpus disabled by "disabled_cpus". */
cpumask_or(&disabled_map, &disabled_map, &hv_disabled_map);
/*
* Disable every cpu after "setup_max_cpus". But don't mark
* as disabled the cpus that are outside of our initial rectangle,
* since that turns out to be confusing.
*/
cpus = 1; /* this cpu */
cpumask_set_cpu(boot_cpu, &disabled_map); /* ignore this cpu */
for (i = 0; cpus < setup_max_cpus; ++i)
if (!cpumask_test_cpu(i, &disabled_map))
++cpus;
for (; i < smp_height * smp_width; ++i)
cpumask_set_cpu(i, &disabled_map);
cpumask_clear_cpu(boot_cpu, &disabled_map); /* reset this cpu */
for (i = smp_height * smp_width; i < NR_CPUS; ++i)
cpumask_clear_cpu(i, &disabled_map);
/*
* Setup cpu_possible map as every cpu allocated to us, minus
* the results of any "disabled_cpus" settings.
*/
cpumask_andnot(&cpu_possible_init, &cpu_possible_init, &disabled_map);
init_cpu_possible(&cpu_possible_init);
/* Learn which cpus are valid for LOTAR caching. */
rc = hv_inquire_tiles(HV_INQ_TILES_LOTAR,
(HV_VirtAddr) cpumask_bits(&cpu_lotar_map),
sizeof(cpu_lotar_map));
if (rc < 0) {
pr_err("warning: no HV_INQ_TILES_LOTAR; using AVAIL\n");
cpu_lotar_map = *cpu_possible_mask;
}
/* Retrieve set of CPUs used for hash-for-home caching */
rc = hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE,
(HV_VirtAddr) hash_for_home_map.bits,
sizeof(hash_for_home_map));
if (rc < 0)
early_panic("hv_inquire_tiles(HFH_CACHE) failed: rc %d\n", rc);
cpumask_or(&cpu_cacheable_map, cpu_possible_mask, &hash_for_home_map);
}
static int __init dataplane(char *str)
{
pr_warning("WARNING: dataplane support disabled in this kernel\n");
return 0;
}
early_param("dataplane", dataplane);
#ifdef CONFIG_CMDLINE_BOOL
static char __initdata builtin_cmdline[COMMAND_LINE_SIZE] = CONFIG_CMDLINE;
#endif
void __init setup_arch(char **cmdline_p)
{
int len;
#if defined(CONFIG_CMDLINE_BOOL) && defined(CONFIG_CMDLINE_OVERRIDE)
len = hv_get_command_line((HV_VirtAddr) boot_command_line,
COMMAND_LINE_SIZE);
if (boot_command_line[0])
pr_warning("WARNING: ignoring dynamic command line \"%s\"\n",
boot_command_line);
strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE);
#else
char *hv_cmdline;
#if defined(CONFIG_CMDLINE_BOOL)
if (builtin_cmdline[0]) {
int builtin_len = strlcpy(boot_command_line, builtin_cmdline,
COMMAND_LINE_SIZE);
if (builtin_len < COMMAND_LINE_SIZE-1)
boot_command_line[builtin_len++] = ' ';
hv_cmdline = &boot_command_line[builtin_len];
len = COMMAND_LINE_SIZE - builtin_len;
} else
#endif
{
hv_cmdline = boot_command_line;
len = COMMAND_LINE_SIZE;
}
len = hv_get_command_line((HV_VirtAddr) hv_cmdline, len);
if (len < 0 || len > COMMAND_LINE_SIZE)
early_panic("hv_get_command_line failed: %d\n", len);
#endif
*cmdline_p = boot_command_line;
/* Set disabled_map and setup_max_cpus very early */
parse_early_param();
/* Make sure the kernel is compatible with the hypervisor. */
validate_hv();
validate_va();
setup_cpu_maps();
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Initialize the PCI structures. This is done before memory
* setup so that we know whether or not a pci_reserve region
* is necessary.
*/
if (tile_pci_init() == 0)
pci_reserve_mb = 0;
/* PCI systems reserve a region just below 4GB for mapping iomem. */
pci_reserve_end_pfn = (1 << (32 - PAGE_SHIFT));
pci_reserve_start_pfn = pci_reserve_end_pfn -
(pci_reserve_mb << (20 - PAGE_SHIFT));
#endif
init_mm.start_code = (unsigned long) _text;
init_mm.end_code = (unsigned long) _etext;
init_mm.end_data = (unsigned long) _edata;
init_mm.brk = (unsigned long) _end;
setup_memory();
store_permanent_mappings();
setup_bootmem_allocator();
/*
* NOTE: before this point _nobody_ is allowed to allocate
* any memory using the bootmem allocator.
*/
#ifdef CONFIG_SWIOTLB
swiotlb_init(0);
#endif
paging_init();
setup_numa_mapping();
zone_sizes_init();
set_page_homes();
setup_cpu(1);
setup_clock();
load_hv_initrd();
}
/*
* Set up per-cpu memory.
*/
unsigned long __per_cpu_offset[NR_CPUS] __write_once;
EXPORT_SYMBOL(__per_cpu_offset);
static size_t __initdata pfn_offset[MAX_NUMNODES] = { 0 };
static unsigned long __initdata percpu_pfn[NR_CPUS] = { 0 };
/*
* As the percpu code allocates pages, we return the pages from the
* end of the node for the specified cpu.
*/
static void *__init pcpu_fc_alloc(unsigned int cpu, size_t size, size_t align)
{
int nid = cpu_to_node(cpu);
unsigned long pfn = node_percpu_pfn[nid] + pfn_offset[nid];
BUG_ON(size % PAGE_SIZE != 0);
pfn_offset[nid] += size / PAGE_SIZE;
BUG_ON(node_percpu[nid] < size);
node_percpu[nid] -= size;
if (percpu_pfn[cpu] == 0)
percpu_pfn[cpu] = pfn;
return pfn_to_kaddr(pfn);
}
/*
* Pages reserved for percpu memory are not freeable, and in any case we are
* on a short path to panic() in setup_per_cpu_area() at this point anyway.
*/
static void __init pcpu_fc_free(void *ptr, size_t size)
{
}
/*
* Set up vmalloc page tables using bootmem for the percpu code.
*/
static void __init pcpu_fc_populate_pte(unsigned long addr)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
BUG_ON(pgd_addr_invalid(addr));
if (addr < VMALLOC_START || addr >= VMALLOC_END)
panic("PCPU addr %#lx outside vmalloc range %#lx..%#lx;"
" try increasing CONFIG_VMALLOC_RESERVE\n",
addr, VMALLOC_START, VMALLOC_END);
pgd = swapper_pg_dir + pgd_index(addr);
pud = pud_offset(pgd, addr);
BUG_ON(!pud_present(*pud));
pmd = pmd_offset(pud, addr);
if (pmd_present(*pmd)) {
BUG_ON(pmd_huge_page(*pmd));
} else {
pte = __alloc_bootmem(L2_KERNEL_PGTABLE_SIZE,
HV_PAGE_TABLE_ALIGN, 0);
pmd_populate_kernel(&init_mm, pmd, pte);
}
}
void __init setup_per_cpu_areas(void)
{
struct page *pg;
unsigned long delta, pfn, lowmem_va;
unsigned long size = percpu_size();
char *ptr;
int rc, cpu, i;
rc = pcpu_page_first_chunk(PERCPU_MODULE_RESERVE, pcpu_fc_alloc,
pcpu_fc_free, pcpu_fc_populate_pte);
if (rc < 0)
panic("Cannot initialize percpu area (err=%d)", rc);
delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
for_each_possible_cpu(cpu) {
__per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
/* finv the copy out of cache so we can change homecache */
ptr = pcpu_base_addr + pcpu_unit_offsets[cpu];
__finv_buffer(ptr, size);
pfn = percpu_pfn[cpu];
/* Rewrite the page tables to cache on that cpu */
pg = pfn_to_page(pfn);
for (i = 0; i < size; i += PAGE_SIZE, ++pfn, ++pg) {
/* Update the vmalloc mapping and page home. */
unsigned long addr = (unsigned long)ptr + i;
pte_t *ptep = virt_to_kpte(addr);
pte_t pte = *ptep;
BUG_ON(pfn != pte_pfn(pte));
pte = hv_pte_set_mode(pte, HV_PTE_MODE_CACHE_TILE_L3);
pte = set_remote_cache_cpu(pte, cpu);
set_pte_at(&init_mm, addr, ptep, pte);
/* Update the lowmem mapping for consistency. */
lowmem_va = (unsigned long)pfn_to_kaddr(pfn);
ptep = virt_to_kpte(lowmem_va);
if (pte_huge(*ptep)) {
printk(KERN_DEBUG "early shatter of huge page"
" at %#lx\n", lowmem_va);
shatter_pmd((pmd_t *)ptep);
ptep = virt_to_kpte(lowmem_va);
BUG_ON(pte_huge(*ptep));
}
BUG_ON(pfn != pte_pfn(*ptep));
set_pte_at(&init_mm, lowmem_va, ptep, pte);
}
}
/* Set our thread pointer appropriately. */
set_my_cpu_offset(__per_cpu_offset[smp_processor_id()]);
/* Make sure the finv's have completed. */
mb_incoherent();
/* Flush the TLB so we reference it properly from here on out. */
local_flush_tlb_all();
}
static struct resource data_resource = {
.name = "Kernel data",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource code_resource = {
.name = "Kernel code",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
/*
* On Pro, we reserve all resources above 4GB so that PCI won't try to put
* mappings above 4GB.
*/
#if defined(CONFIG_PCI) && !defined(__tilegx__)
static struct resource* __init
insert_non_bus_resource(void)
{
struct resource *res =
kzalloc(sizeof(struct resource), GFP_ATOMIC);
if (!res)
return NULL;
res->name = "Non-Bus Physical Address Space";
res->start = (1ULL << 32);
res->end = -1LL;
res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
if (insert_resource(&iomem_resource, res)) {
kfree(res);
return NULL;
}
return res;
}
#endif
static struct resource* __init
insert_ram_resource(u64 start_pfn, u64 end_pfn, bool reserved)
{
struct resource *res =
kzalloc(sizeof(struct resource), GFP_ATOMIC);
if (!res)
return NULL;
res->name = reserved ? "Reserved" : "System RAM";
res->start = start_pfn << PAGE_SHIFT;
res->end = (end_pfn << PAGE_SHIFT) - 1;
res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
if (insert_resource(&iomem_resource, res)) {
kfree(res);
return NULL;
}
return res;
}
/*
* Request address space for all standard resources
*
* If the system includes PCI root complex drivers, we need to create
* a window just below 4GB where PCI BARs can be mapped.
*/
static int __init request_standard_resources(void)
{
int i;
enum { CODE_DELTA = MEM_SV_START - PAGE_OFFSET };
#if defined(CONFIG_PCI) && !defined(__tilegx__)
insert_non_bus_resource();
#endif
for_each_online_node(i) {
u64 start_pfn = node_start_pfn[i];
u64 end_pfn = node_end_pfn[i];
#if defined(CONFIG_PCI) && !defined(__tilegx__)
if (start_pfn <= pci_reserve_start_pfn &&
end_pfn > pci_reserve_start_pfn) {
if (end_pfn > pci_reserve_end_pfn)
insert_ram_resource(pci_reserve_end_pfn,
end_pfn, 0);
end_pfn = pci_reserve_start_pfn;
}
#endif
insert_ram_resource(start_pfn, end_pfn, 0);
}
code_resource.start = __pa(_text - CODE_DELTA);
code_resource.end = __pa(_etext - CODE_DELTA)-1;
data_resource.start = __pa(_sdata);
data_resource.end = __pa(_end)-1;
insert_resource(&iomem_resource, &code_resource);
insert_resource(&iomem_resource, &data_resource);
/* Mark any "memmap" regions busy for the resource manager. */
for (i = 0; i < memmap_nr; ++i) {
struct memmap_entry *m = &memmap_map[i];
insert_ram_resource(PFN_DOWN(m->addr),
PFN_UP(m->addr + m->size - 1), 1);
}
#ifdef CONFIG_KEXEC
insert_resource(&iomem_resource, &crashk_res);
#endif
return 0;
}
subsys_initcall(request_standard_resources);
| gpl-2.0 |
Amperific/kernel_tuna_4.3 | drivers/net/wan/ixp4xx_hss.c | 940 | 37915 | /*
* Intel IXP4xx HSS (synchronous serial port) driver for Linux
*
* Copyright (C) 2007-2008 Krzysztof Hałasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/cdev.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/fs.h>
#include <linux/hdlc.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <mach/npe.h>
#include <mach/qmgr.h>
#define DEBUG_DESC 0
#define DEBUG_RX 0
#define DEBUG_TX 0
#define DEBUG_PKT_BYTES 0
#define DEBUG_CLOSE 0
#define DRV_NAME "ixp4xx_hss"
#define PKT_EXTRA_FLAGS 0 /* orig 1 */
#define PKT_NUM_PIPES 1 /* 1, 2 or 4 */
#define PKT_PIPE_FIFO_SIZEW 4 /* total 4 dwords per HSS */
#define RX_DESCS 16 /* also length of all RX queues */
#define TX_DESCS 16 /* also length of all TX queues */
#define POOL_ALLOC_SIZE (sizeof(struct desc) * (RX_DESCS + TX_DESCS))
#define RX_SIZE (HDLC_MAX_MRU + 4) /* NPE needs more space */
#define MAX_CLOSE_WAIT 1000 /* microseconds */
#define HSS_COUNT 2
#define FRAME_SIZE 256 /* doesn't matter at this point */
#define FRAME_OFFSET 0
#define MAX_CHANNELS (FRAME_SIZE / 8)
#define NAPI_WEIGHT 16
/* Queue IDs */
#define HSS0_CHL_RXTRIG_QUEUE 12 /* orig size = 32 dwords */
#define HSS0_PKT_RX_QUEUE 13 /* orig size = 32 dwords */
#define HSS0_PKT_TX0_QUEUE 14 /* orig size = 16 dwords */
#define HSS0_PKT_TX1_QUEUE 15
#define HSS0_PKT_TX2_QUEUE 16
#define HSS0_PKT_TX3_QUEUE 17
#define HSS0_PKT_RXFREE0_QUEUE 18 /* orig size = 16 dwords */
#define HSS0_PKT_RXFREE1_QUEUE 19
#define HSS0_PKT_RXFREE2_QUEUE 20
#define HSS0_PKT_RXFREE3_QUEUE 21
#define HSS0_PKT_TXDONE_QUEUE 22 /* orig size = 64 dwords */
#define HSS1_CHL_RXTRIG_QUEUE 10
#define HSS1_PKT_RX_QUEUE 0
#define HSS1_PKT_TX0_QUEUE 5
#define HSS1_PKT_TX1_QUEUE 6
#define HSS1_PKT_TX2_QUEUE 7
#define HSS1_PKT_TX3_QUEUE 8
#define HSS1_PKT_RXFREE0_QUEUE 1
#define HSS1_PKT_RXFREE1_QUEUE 2
#define HSS1_PKT_RXFREE2_QUEUE 3
#define HSS1_PKT_RXFREE3_QUEUE 4
#define HSS1_PKT_TXDONE_QUEUE 9
#define NPE_PKT_MODE_HDLC 0
#define NPE_PKT_MODE_RAW 1
#define NPE_PKT_MODE_56KMODE 2
#define NPE_PKT_MODE_56KENDIAN_MSB 4
/* PKT_PIPE_HDLC_CFG_WRITE flags */
#define PKT_HDLC_IDLE_ONES 0x1 /* default = flags */
#define PKT_HDLC_CRC_32 0x2 /* default = CRC-16 */
#define PKT_HDLC_MSB_ENDIAN 0x4 /* default = LE */
/* hss_config, PCRs */
/* Frame sync sampling, default = active low */
#define PCR_FRM_SYNC_ACTIVE_HIGH 0x40000000
#define PCR_FRM_SYNC_FALLINGEDGE 0x80000000
#define PCR_FRM_SYNC_RISINGEDGE 0xC0000000
/* Frame sync pin: input (default) or output generated off a given clk edge */
#define PCR_FRM_SYNC_OUTPUT_FALLING 0x20000000
#define PCR_FRM_SYNC_OUTPUT_RISING 0x30000000
/* Frame and data clock sampling on edge, default = falling */
#define PCR_FCLK_EDGE_RISING 0x08000000
#define PCR_DCLK_EDGE_RISING 0x04000000
/* Clock direction, default = input */
#define PCR_SYNC_CLK_DIR_OUTPUT 0x02000000
/* Generate/Receive frame pulses, default = enabled */
#define PCR_FRM_PULSE_DISABLED 0x01000000
/* Data rate is full (default) or half the configured clk speed */
#define PCR_HALF_CLK_RATE 0x00200000
/* Invert data between NPE and HSS FIFOs? (default = no) */
#define PCR_DATA_POLARITY_INVERT 0x00100000
/* TX/RX endianness, default = LSB */
#define PCR_MSB_ENDIAN 0x00080000
/* Normal (default) / open drain mode (TX only) */
#define PCR_TX_PINS_OPEN_DRAIN 0x00040000
/* No framing bit transmitted and expected on RX? (default = framing bit) */
#define PCR_SOF_NO_FBIT 0x00020000
/* Drive data pins? */
#define PCR_TX_DATA_ENABLE 0x00010000
/* Voice 56k type: drive the data pins low (default), high, high Z */
#define PCR_TX_V56K_HIGH 0x00002000
#define PCR_TX_V56K_HIGH_IMP 0x00004000
/* Unassigned type: drive the data pins low (default), high, high Z */
#define PCR_TX_UNASS_HIGH 0x00000800
#define PCR_TX_UNASS_HIGH_IMP 0x00001000
/* T1 @ 1.544MHz only: Fbit dictated in FIFO (default) or high Z */
#define PCR_TX_FB_HIGH_IMP 0x00000400
/* 56k data endiannes - which bit unused: high (default) or low */
#define PCR_TX_56KE_BIT_0_UNUSED 0x00000200
/* 56k data transmission type: 32/8 bit data (default) or 56K data */
#define PCR_TX_56KS_56K_DATA 0x00000100
/* hss_config, cCR */
/* Number of packetized clients, default = 1 */
#define CCR_NPE_HFIFO_2_HDLC 0x04000000
#define CCR_NPE_HFIFO_3_OR_4HDLC 0x08000000
/* default = no loopback */
#define CCR_LOOPBACK 0x02000000
/* HSS number, default = 0 (first) */
#define CCR_SECOND_HSS 0x01000000
/* hss_config, clkCR: main:10, num:10, denom:12 */
#define CLK42X_SPEED_EXP ((0x3FF << 22) | ( 2 << 12) | 15) /*65 KHz*/
#define CLK42X_SPEED_512KHZ (( 130 << 22) | ( 2 << 12) | 15)
#define CLK42X_SPEED_1536KHZ (( 43 << 22) | ( 18 << 12) | 47)
#define CLK42X_SPEED_1544KHZ (( 43 << 22) | ( 33 << 12) | 192)
#define CLK42X_SPEED_2048KHZ (( 32 << 22) | ( 34 << 12) | 63)
#define CLK42X_SPEED_4096KHZ (( 16 << 22) | ( 34 << 12) | 127)
#define CLK42X_SPEED_8192KHZ (( 8 << 22) | ( 34 << 12) | 255)
#define CLK46X_SPEED_512KHZ (( 130 << 22) | ( 24 << 12) | 127)
#define CLK46X_SPEED_1536KHZ (( 43 << 22) | (152 << 12) | 383)
#define CLK46X_SPEED_1544KHZ (( 43 << 22) | ( 66 << 12) | 385)
#define CLK46X_SPEED_2048KHZ (( 32 << 22) | (280 << 12) | 511)
#define CLK46X_SPEED_4096KHZ (( 16 << 22) | (280 << 12) | 1023)
#define CLK46X_SPEED_8192KHZ (( 8 << 22) | (280 << 12) | 2047)
/*
* HSS_CONFIG_CLOCK_CR register consists of 3 parts:
* A (10 bits), B (10 bits) and C (12 bits).
* IXP42x HSS clock generator operation (verified with an oscilloscope):
* Each clock bit takes 7.5 ns (1 / 133.xx MHz).
* The clock sequence consists of (C - B) states of 0s and 1s, each state is
* A bits wide. It's followed by (B + 1) states of 0s and 1s, each state is
* (A + 1) bits wide.
*
* The resulting average clock frequency (assuming 33.333 MHz oscillator) is:
* freq = 66.666 MHz / (A + (B + 1) / (C + 1))
* minimum freq = 66.666 MHz / (A + 1)
* maximum freq = 66.666 MHz / A
*
* Example: A = 2, B = 2, C = 7, CLOCK_CR register = 2 << 22 | 2 << 12 | 7
* freq = 66.666 MHz / (2 + (2 + 1) / (7 + 1)) = 28.07 MHz (Mb/s).
* The clock sequence is: 1100110011 (5 doubles) 000111000 (3 triples).
* The sequence takes (C - B) * A + (B + 1) * (A + 1) = 5 * 2 + 3 * 3 bits
* = 19 bits (each 7.5 ns long) = 142.5 ns (then the sequence repeats).
* The sequence consists of 4 complete clock periods, thus the average
* frequency (= clock rate) is 4 / 142.5 ns = 28.07 MHz (Mb/s).
* (max specified clock rate for IXP42x HSS is 8.192 Mb/s).
*/
/* hss_config, LUT entries */
#define TDMMAP_UNASSIGNED 0
#define TDMMAP_HDLC 1 /* HDLC - packetized */
#define TDMMAP_VOICE56K 2 /* Voice56K - 7-bit channelized */
#define TDMMAP_VOICE64K 3 /* Voice64K - 8-bit channelized */
/* offsets into HSS config */
#define HSS_CONFIG_TX_PCR 0x00 /* port configuration registers */
#define HSS_CONFIG_RX_PCR 0x04
#define HSS_CONFIG_CORE_CR 0x08 /* loopback control, HSS# */
#define HSS_CONFIG_CLOCK_CR 0x0C /* clock generator control */
#define HSS_CONFIG_TX_FCR 0x10 /* frame configuration registers */
#define HSS_CONFIG_RX_FCR 0x14
#define HSS_CONFIG_TX_LUT 0x18 /* channel look-up tables */
#define HSS_CONFIG_RX_LUT 0x38
/* NPE command codes */
/* writes the ConfigWord value to the location specified by offset */
#define PORT_CONFIG_WRITE 0x40
/* triggers the NPE to load the contents of the configuration table */
#define PORT_CONFIG_LOAD 0x41
/* triggers the NPE to return an HssErrorReadResponse message */
#define PORT_ERROR_READ 0x42
/* triggers the NPE to reset internal status and enable the HssPacketized
operation for the flow specified by pPipe */
#define PKT_PIPE_FLOW_ENABLE 0x50
#define PKT_PIPE_FLOW_DISABLE 0x51
#define PKT_NUM_PIPES_WRITE 0x52
#define PKT_PIPE_FIFO_SIZEW_WRITE 0x53
#define PKT_PIPE_HDLC_CFG_WRITE 0x54
#define PKT_PIPE_IDLE_PATTERN_WRITE 0x55
#define PKT_PIPE_RX_SIZE_WRITE 0x56
#define PKT_PIPE_MODE_WRITE 0x57
/* HDLC packet status values - desc->status */
#define ERR_SHUTDOWN 1 /* stop or shutdown occurrence */
#define ERR_HDLC_ALIGN 2 /* HDLC alignment error */
#define ERR_HDLC_FCS 3 /* HDLC Frame Check Sum error */
#define ERR_RXFREE_Q_EMPTY 4 /* RX-free queue became empty while receiving
this packet (if buf_len < pkt_len) */
#define ERR_HDLC_TOO_LONG 5 /* HDLC frame size too long */
#define ERR_HDLC_ABORT 6 /* abort sequence received */
#define ERR_DISCONNECTING 7 /* disconnect is in progress */
#ifdef __ARMEB__
typedef struct sk_buff buffer_t;
#define free_buffer dev_kfree_skb
#define free_buffer_irq dev_kfree_skb_irq
#else
typedef void buffer_t;
#define free_buffer kfree
#define free_buffer_irq kfree
#endif
struct port {
struct device *dev;
struct npe *npe;
struct net_device *netdev;
struct napi_struct napi;
struct hss_plat_info *plat;
buffer_t *rx_buff_tab[RX_DESCS], *tx_buff_tab[TX_DESCS];
struct desc *desc_tab; /* coherent */
u32 desc_tab_phys;
unsigned int id;
unsigned int clock_type, clock_rate, loopback;
unsigned int initialized, carrier;
u8 hdlc_cfg;
u32 clock_reg;
};
/* NPE message structure */
struct msg {
#ifdef __ARMEB__
u8 cmd, unused, hss_port, index;
union {
struct { u8 data8a, data8b, data8c, data8d; };
struct { u16 data16a, data16b; };
struct { u32 data32; };
};
#else
u8 index, hss_port, unused, cmd;
union {
struct { u8 data8d, data8c, data8b, data8a; };
struct { u16 data16b, data16a; };
struct { u32 data32; };
};
#endif
};
/* HDLC packet descriptor */
struct desc {
u32 next; /* pointer to next buffer, unused */
#ifdef __ARMEB__
u16 buf_len; /* buffer length */
u16 pkt_len; /* packet length */
u32 data; /* pointer to data buffer in RAM */
u8 status;
u8 error_count;
u16 __reserved;
#else
u16 pkt_len; /* packet length */
u16 buf_len; /* buffer length */
u32 data; /* pointer to data buffer in RAM */
u16 __reserved;
u8 error_count;
u8 status;
#endif
u32 __reserved1[4];
};
#define rx_desc_phys(port, n) ((port)->desc_tab_phys + \
(n) * sizeof(struct desc))
#define rx_desc_ptr(port, n) (&(port)->desc_tab[n])
#define tx_desc_phys(port, n) ((port)->desc_tab_phys + \
((n) + RX_DESCS) * sizeof(struct desc))
#define tx_desc_ptr(port, n) (&(port)->desc_tab[(n) + RX_DESCS])
/*****************************************************************************
* global variables
****************************************************************************/
static int ports_open;
static struct dma_pool *dma_pool;
static spinlock_t npe_lock;
static const struct {
int tx, txdone, rx, rxfree;
}queue_ids[2] = {{HSS0_PKT_TX0_QUEUE, HSS0_PKT_TXDONE_QUEUE, HSS0_PKT_RX_QUEUE,
HSS0_PKT_RXFREE0_QUEUE},
{HSS1_PKT_TX0_QUEUE, HSS1_PKT_TXDONE_QUEUE, HSS1_PKT_RX_QUEUE,
HSS1_PKT_RXFREE0_QUEUE},
};
/*****************************************************************************
* utility functions
****************************************************************************/
static inline struct port* dev_to_port(struct net_device *dev)
{
return dev_to_hdlc(dev)->priv;
}
#ifndef __ARMEB__
static inline void memcpy_swab32(u32 *dest, u32 *src, int cnt)
{
int i;
for (i = 0; i < cnt; i++)
dest[i] = swab32(src[i]);
}
#endif
/*****************************************************************************
* HSS access
****************************************************************************/
static void hss_npe_send(struct port *port, struct msg *msg, const char* what)
{
u32 *val = (u32*)msg;
if (npe_send_message(port->npe, msg, what)) {
printk(KERN_CRIT "HSS-%i: unable to send command [%08X:%08X]"
" to %s\n", port->id, val[0], val[1],
npe_name(port->npe));
BUG();
}
}
static void hss_config_set_lut(struct port *port)
{
struct msg msg;
int ch;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
for (ch = 0; ch < MAX_CHANNELS; ch++) {
msg.data32 >>= 2;
msg.data32 |= TDMMAP_HDLC << 30;
if (ch % 16 == 15) {
msg.index = HSS_CONFIG_TX_LUT + ((ch / 4) & ~3);
hss_npe_send(port, &msg, "HSS_SET_TX_LUT");
msg.index += HSS_CONFIG_RX_LUT - HSS_CONFIG_TX_LUT;
hss_npe_send(port, &msg, "HSS_SET_RX_LUT");
}
}
}
static void hss_config(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_TX_PCR;
msg.data32 = PCR_FRM_PULSE_DISABLED | PCR_MSB_ENDIAN |
PCR_TX_DATA_ENABLE | PCR_SOF_NO_FBIT;
if (port->clock_type == CLOCK_INT)
msg.data32 |= PCR_SYNC_CLK_DIR_OUTPUT;
hss_npe_send(port, &msg, "HSS_SET_TX_PCR");
msg.index = HSS_CONFIG_RX_PCR;
msg.data32 ^= PCR_TX_DATA_ENABLE | PCR_DCLK_EDGE_RISING;
hss_npe_send(port, &msg, "HSS_SET_RX_PCR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_CORE_CR;
msg.data32 = (port->loopback ? CCR_LOOPBACK : 0) |
(port->id ? CCR_SECOND_HSS : 0);
hss_npe_send(port, &msg, "HSS_SET_CORE_CR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_CLOCK_CR;
msg.data32 = port->clock_reg;
hss_npe_send(port, &msg, "HSS_SET_CLOCK_CR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_TX_FCR;
msg.data16a = FRAME_OFFSET;
msg.data16b = FRAME_SIZE - 1;
hss_npe_send(port, &msg, "HSS_SET_TX_FCR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_RX_FCR;
msg.data16a = FRAME_OFFSET;
msg.data16b = FRAME_SIZE - 1;
hss_npe_send(port, &msg, "HSS_SET_RX_FCR");
hss_config_set_lut(port);
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_LOAD;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "HSS_LOAD_CONFIG");
if (npe_recv_message(port->npe, &msg, "HSS_LOAD_CONFIG") ||
/* HSS_LOAD_CONFIG for port #1 returns port_id = #4 */
msg.cmd != PORT_CONFIG_LOAD || msg.data32) {
printk(KERN_CRIT "HSS-%i: HSS_LOAD_CONFIG failed\n",
port->id);
BUG();
}
/* HDLC may stop working without this - check FIXME */
npe_recv_message(port->npe, &msg, "FLUSH_IT");
}
static void hss_set_hdlc_cfg(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_HDLC_CFG_WRITE;
msg.hss_port = port->id;
msg.data8a = port->hdlc_cfg; /* rx_cfg */
msg.data8b = port->hdlc_cfg | (PKT_EXTRA_FLAGS << 3); /* tx_cfg */
hss_npe_send(port, &msg, "HSS_SET_HDLC_CFG");
}
static u32 hss_get_status(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_ERROR_READ;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "PORT_ERROR_READ");
if (npe_recv_message(port->npe, &msg, "PORT_ERROR_READ")) {
printk(KERN_CRIT "HSS-%i: unable to read HSS status\n",
port->id);
BUG();
}
return msg.data32;
}
static void hss_start_hdlc(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_FLOW_ENABLE;
msg.hss_port = port->id;
msg.data32 = 0;
hss_npe_send(port, &msg, "HSS_ENABLE_PKT_PIPE");
}
static void hss_stop_hdlc(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_FLOW_DISABLE;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "HSS_DISABLE_PKT_PIPE");
hss_get_status(port); /* make sure it's halted */
}
static int hss_load_firmware(struct port *port)
{
struct msg msg;
int err;
if (port->initialized)
return 0;
if (!npe_running(port->npe) &&
(err = npe_load_firmware(port->npe, npe_name(port->npe),
port->dev)))
return err;
/* HDLC mode configuration */
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_NUM_PIPES_WRITE;
msg.hss_port = port->id;
msg.data8a = PKT_NUM_PIPES;
hss_npe_send(port, &msg, "HSS_SET_PKT_PIPES");
msg.cmd = PKT_PIPE_FIFO_SIZEW_WRITE;
msg.data8a = PKT_PIPE_FIFO_SIZEW;
hss_npe_send(port, &msg, "HSS_SET_PKT_FIFO");
msg.cmd = PKT_PIPE_MODE_WRITE;
msg.data8a = NPE_PKT_MODE_HDLC;
/* msg.data8b = inv_mask */
/* msg.data8c = or_mask */
hss_npe_send(port, &msg, "HSS_SET_PKT_MODE");
msg.cmd = PKT_PIPE_RX_SIZE_WRITE;
msg.data16a = HDLC_MAX_MRU; /* including CRC */
hss_npe_send(port, &msg, "HSS_SET_PKT_RX_SIZE");
msg.cmd = PKT_PIPE_IDLE_PATTERN_WRITE;
msg.data32 = 0x7F7F7F7F; /* ??? FIXME */
hss_npe_send(port, &msg, "HSS_SET_PKT_IDLE");
port->initialized = 1;
return 0;
}
/*****************************************************************************
* packetized (HDLC) operation
****************************************************************************/
static inline void debug_pkt(struct net_device *dev, const char *func,
u8 *data, int len)
{
#if DEBUG_PKT_BYTES
int i;
printk(KERN_DEBUG "%s: %s(%i)", dev->name, func, len);
for (i = 0; i < len; i++) {
if (i >= DEBUG_PKT_BYTES)
break;
printk("%s%02X", !(i % 4) ? " " : "", data[i]);
}
printk("\n");
#endif
}
static inline void debug_desc(u32 phys, struct desc *desc)
{
#if DEBUG_DESC
printk(KERN_DEBUG "%X: %X %3X %3X %08X %X %X\n",
phys, desc->next, desc->buf_len, desc->pkt_len,
desc->data, desc->status, desc->error_count);
#endif
}
static inline int queue_get_desc(unsigned int queue, struct port *port,
int is_tx)
{
u32 phys, tab_phys, n_desc;
struct desc *tab;
if (!(phys = qmgr_get_entry(queue)))
return -1;
BUG_ON(phys & 0x1F);
tab_phys = is_tx ? tx_desc_phys(port, 0) : rx_desc_phys(port, 0);
tab = is_tx ? tx_desc_ptr(port, 0) : rx_desc_ptr(port, 0);
n_desc = (phys - tab_phys) / sizeof(struct desc);
BUG_ON(n_desc >= (is_tx ? TX_DESCS : RX_DESCS));
debug_desc(phys, &tab[n_desc]);
BUG_ON(tab[n_desc].next);
return n_desc;
}
static inline void queue_put_desc(unsigned int queue, u32 phys,
struct desc *desc)
{
debug_desc(phys, desc);
BUG_ON(phys & 0x1F);
qmgr_put_entry(queue, phys);
/* Don't check for queue overflow here, we've allocated sufficient
length and queues >= 32 don't support this check anyway. */
}
static inline void dma_unmap_tx(struct port *port, struct desc *desc)
{
#ifdef __ARMEB__
dma_unmap_single(&port->netdev->dev, desc->data,
desc->buf_len, DMA_TO_DEVICE);
#else
dma_unmap_single(&port->netdev->dev, desc->data & ~3,
ALIGN((desc->data & 3) + desc->buf_len, 4),
DMA_TO_DEVICE);
#endif
}
static void hss_hdlc_set_carrier(void *pdev, int carrier)
{
struct net_device *netdev = pdev;
struct port *port = dev_to_port(netdev);
unsigned long flags;
spin_lock_irqsave(&npe_lock, flags);
port->carrier = carrier;
if (!port->loopback) {
if (carrier)
netif_carrier_on(netdev);
else
netif_carrier_off(netdev);
}
spin_unlock_irqrestore(&npe_lock, flags);
}
static void hss_hdlc_rx_irq(void *pdev)
{
struct net_device *dev = pdev;
struct port *port = dev_to_port(dev);
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_rx_irq\n", dev->name);
#endif
qmgr_disable_irq(queue_ids[port->id].rx);
napi_schedule(&port->napi);
}
static int hss_hdlc_poll(struct napi_struct *napi, int budget)
{
struct port *port = container_of(napi, struct port, napi);
struct net_device *dev = port->netdev;
unsigned int rxq = queue_ids[port->id].rx;
unsigned int rxfreeq = queue_ids[port->id].rxfree;
int received = 0;
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll\n", dev->name);
#endif
while (received < budget) {
struct sk_buff *skb;
struct desc *desc;
int n;
#ifdef __ARMEB__
struct sk_buff *temp;
u32 phys;
#endif
if ((n = queue_get_desc(rxq, port, 0)) < 0) {
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll"
" napi_complete\n", dev->name);
#endif
napi_complete(napi);
qmgr_enable_irq(rxq);
if (!qmgr_stat_empty(rxq) &&
napi_reschedule(napi)) {
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll"
" napi_reschedule succeeded\n",
dev->name);
#endif
qmgr_disable_irq(rxq);
continue;
}
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll all done\n",
dev->name);
#endif
return received; /* all work done */
}
desc = rx_desc_ptr(port, n);
#if 0 /* FIXME - error_count counts modulo 256, perhaps we should use it */
if (desc->error_count)
printk(KERN_DEBUG "%s: hss_hdlc_poll status 0x%02X"
" errors %u\n", dev->name, desc->status,
desc->error_count);
#endif
skb = NULL;
switch (desc->status) {
case 0:
#ifdef __ARMEB__
if ((skb = netdev_alloc_skb(dev, RX_SIZE)) != NULL) {
phys = dma_map_single(&dev->dev, skb->data,
RX_SIZE,
DMA_FROM_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
dev_kfree_skb(skb);
skb = NULL;
}
}
#else
skb = netdev_alloc_skb(dev, desc->pkt_len);
#endif
if (!skb)
dev->stats.rx_dropped++;
break;
case ERR_HDLC_ALIGN:
case ERR_HDLC_ABORT:
dev->stats.rx_frame_errors++;
dev->stats.rx_errors++;
break;
case ERR_HDLC_FCS:
dev->stats.rx_crc_errors++;
dev->stats.rx_errors++;
break;
case ERR_HDLC_TOO_LONG:
dev->stats.rx_length_errors++;
dev->stats.rx_errors++;
break;
default: /* FIXME - remove printk */
printk(KERN_ERR "%s: hss_hdlc_poll: status 0x%02X"
" errors %u\n", dev->name, desc->status,
desc->error_count);
dev->stats.rx_errors++;
}
if (!skb) {
/* put the desc back on RX-ready queue */
desc->buf_len = RX_SIZE;
desc->pkt_len = desc->status = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
continue;
}
/* process received frame */
#ifdef __ARMEB__
temp = skb;
skb = port->rx_buff_tab[n];
dma_unmap_single(&dev->dev, desc->data,
RX_SIZE, DMA_FROM_DEVICE);
#else
dma_sync_single_for_cpu(&dev->dev, desc->data,
RX_SIZE, DMA_FROM_DEVICE);
memcpy_swab32((u32 *)skb->data, (u32 *)port->rx_buff_tab[n],
ALIGN(desc->pkt_len, 4) / 4);
#endif
skb_put(skb, desc->pkt_len);
debug_pkt(dev, "hss_hdlc_poll", skb->data, skb->len);
skb->protocol = hdlc_type_trans(skb, dev);
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
/* put the new buffer on RX-free queue */
#ifdef __ARMEB__
port->rx_buff_tab[n] = temp;
desc->data = phys;
#endif
desc->buf_len = RX_SIZE;
desc->pkt_len = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
received++;
}
#if DEBUG_RX
printk(KERN_DEBUG "hss_hdlc_poll: end, not all work done\n");
#endif
return received; /* not all work done */
}
static void hss_hdlc_txdone_irq(void *pdev)
{
struct net_device *dev = pdev;
struct port *port = dev_to_port(dev);
int n_desc;
#if DEBUG_TX
printk(KERN_DEBUG DRV_NAME ": hss_hdlc_txdone_irq\n");
#endif
while ((n_desc = queue_get_desc(queue_ids[port->id].txdone,
port, 1)) >= 0) {
struct desc *desc;
int start;
desc = tx_desc_ptr(port, n_desc);
dev->stats.tx_packets++;
dev->stats.tx_bytes += desc->pkt_len;
dma_unmap_tx(port, desc);
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_txdone_irq free %p\n",
dev->name, port->tx_buff_tab[n_desc]);
#endif
free_buffer_irq(port->tx_buff_tab[n_desc]);
port->tx_buff_tab[n_desc] = NULL;
start = qmgr_stat_below_low_watermark(port->plat->txreadyq);
queue_put_desc(port->plat->txreadyq,
tx_desc_phys(port, n_desc), desc);
if (start) { /* TX-ready queue was empty */
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_txdone_irq xmit"
" ready\n", dev->name);
#endif
netif_wake_queue(dev);
}
}
}
static int hss_hdlc_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned int txreadyq = port->plat->txreadyq;
int len, offset, bytes, n;
void *mem;
u32 phys;
struct desc *desc;
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit\n", dev->name);
#endif
if (unlikely(skb->len > HDLC_MAX_MRU)) {
dev_kfree_skb(skb);
dev->stats.tx_errors++;
return NETDEV_TX_OK;
}
debug_pkt(dev, "hss_hdlc_xmit", skb->data, skb->len);
len = skb->len;
#ifdef __ARMEB__
offset = 0; /* no need to keep alignment */
bytes = len;
mem = skb->data;
#else
offset = (int)skb->data & 3; /* keep 32-bit alignment */
bytes = ALIGN(offset + len, 4);
if (!(mem = kmalloc(bytes, GFP_ATOMIC))) {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
memcpy_swab32(mem, (u32 *)((int)skb->data & ~3), bytes / 4);
dev_kfree_skb(skb);
#endif
phys = dma_map_single(&dev->dev, mem, bytes, DMA_TO_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
#ifdef __ARMEB__
dev_kfree_skb(skb);
#else
kfree(mem);
#endif
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
n = queue_get_desc(txreadyq, port, 1);
BUG_ON(n < 0);
desc = tx_desc_ptr(port, n);
#ifdef __ARMEB__
port->tx_buff_tab[n] = skb;
#else
port->tx_buff_tab[n] = mem;
#endif
desc->data = phys + offset;
desc->buf_len = desc->pkt_len = len;
wmb();
queue_put_desc(queue_ids[port->id].tx, tx_desc_phys(port, n), desc);
if (qmgr_stat_below_low_watermark(txreadyq)) { /* empty */
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit queue full\n", dev->name);
#endif
netif_stop_queue(dev);
/* we could miss TX ready interrupt */
if (!qmgr_stat_below_low_watermark(txreadyq)) {
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit ready again\n",
dev->name);
#endif
netif_wake_queue(dev);
}
}
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit end\n", dev->name);
#endif
return NETDEV_TX_OK;
}
static int request_hdlc_queues(struct port *port)
{
int err;
err = qmgr_request_queue(queue_ids[port->id].rxfree, RX_DESCS, 0, 0,
"%s:RX-free", port->netdev->name);
if (err)
return err;
err = qmgr_request_queue(queue_ids[port->id].rx, RX_DESCS, 0, 0,
"%s:RX", port->netdev->name);
if (err)
goto rel_rxfree;
err = qmgr_request_queue(queue_ids[port->id].tx, TX_DESCS, 0, 0,
"%s:TX", port->netdev->name);
if (err)
goto rel_rx;
err = qmgr_request_queue(port->plat->txreadyq, TX_DESCS, 0, 0,
"%s:TX-ready", port->netdev->name);
if (err)
goto rel_tx;
err = qmgr_request_queue(queue_ids[port->id].txdone, TX_DESCS, 0, 0,
"%s:TX-done", port->netdev->name);
if (err)
goto rel_txready;
return 0;
rel_txready:
qmgr_release_queue(port->plat->txreadyq);
rel_tx:
qmgr_release_queue(queue_ids[port->id].tx);
rel_rx:
qmgr_release_queue(queue_ids[port->id].rx);
rel_rxfree:
qmgr_release_queue(queue_ids[port->id].rxfree);
printk(KERN_DEBUG "%s: unable to request hardware queues\n",
port->netdev->name);
return err;
}
static void release_hdlc_queues(struct port *port)
{
qmgr_release_queue(queue_ids[port->id].rxfree);
qmgr_release_queue(queue_ids[port->id].rx);
qmgr_release_queue(queue_ids[port->id].txdone);
qmgr_release_queue(queue_ids[port->id].tx);
qmgr_release_queue(port->plat->txreadyq);
}
static int init_hdlc_queues(struct port *port)
{
int i;
if (!ports_open)
if (!(dma_pool = dma_pool_create(DRV_NAME, NULL,
POOL_ALLOC_SIZE, 32, 0)))
return -ENOMEM;
if (!(port->desc_tab = dma_pool_alloc(dma_pool, GFP_KERNEL,
&port->desc_tab_phys)))
return -ENOMEM;
memset(port->desc_tab, 0, POOL_ALLOC_SIZE);
memset(port->rx_buff_tab, 0, sizeof(port->rx_buff_tab)); /* tables */
memset(port->tx_buff_tab, 0, sizeof(port->tx_buff_tab));
/* Setup RX buffers */
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff;
void *data;
#ifdef __ARMEB__
if (!(buff = netdev_alloc_skb(port->netdev, RX_SIZE)))
return -ENOMEM;
data = buff->data;
#else
if (!(buff = kmalloc(RX_SIZE, GFP_KERNEL)))
return -ENOMEM;
data = buff;
#endif
desc->buf_len = RX_SIZE;
desc->data = dma_map_single(&port->netdev->dev, data,
RX_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(&port->netdev->dev, desc->data)) {
free_buffer(buff);
return -EIO;
}
port->rx_buff_tab[i] = buff;
}
return 0;
}
static void destroy_hdlc_queues(struct port *port)
{
int i;
if (port->desc_tab) {
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff = port->rx_buff_tab[i];
if (buff) {
dma_unmap_single(&port->netdev->dev,
desc->data, RX_SIZE,
DMA_FROM_DEVICE);
free_buffer(buff);
}
}
for (i = 0; i < TX_DESCS; i++) {
struct desc *desc = tx_desc_ptr(port, i);
buffer_t *buff = port->tx_buff_tab[i];
if (buff) {
dma_unmap_tx(port, desc);
free_buffer(buff);
}
}
dma_pool_free(dma_pool, port->desc_tab, port->desc_tab_phys);
port->desc_tab = NULL;
}
if (!ports_open && dma_pool) {
dma_pool_destroy(dma_pool);
dma_pool = NULL;
}
}
static int hss_hdlc_open(struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned long flags;
int i, err = 0;
if ((err = hdlc_open(dev)))
return err;
if ((err = hss_load_firmware(port)))
goto err_hdlc_close;
if ((err = request_hdlc_queues(port)))
goto err_hdlc_close;
if ((err = init_hdlc_queues(port)))
goto err_destroy_queues;
spin_lock_irqsave(&npe_lock, flags);
if (port->plat->open)
if ((err = port->plat->open(port->id, dev,
hss_hdlc_set_carrier)))
goto err_unlock;
spin_unlock_irqrestore(&npe_lock, flags);
/* Populate queues with buffers, no failure after this point */
for (i = 0; i < TX_DESCS; i++)
queue_put_desc(port->plat->txreadyq,
tx_desc_phys(port, i), tx_desc_ptr(port, i));
for (i = 0; i < RX_DESCS; i++)
queue_put_desc(queue_ids[port->id].rxfree,
rx_desc_phys(port, i), rx_desc_ptr(port, i));
napi_enable(&port->napi);
netif_start_queue(dev);
qmgr_set_irq(queue_ids[port->id].rx, QUEUE_IRQ_SRC_NOT_EMPTY,
hss_hdlc_rx_irq, dev);
qmgr_set_irq(queue_ids[port->id].txdone, QUEUE_IRQ_SRC_NOT_EMPTY,
hss_hdlc_txdone_irq, dev);
qmgr_enable_irq(queue_ids[port->id].txdone);
ports_open++;
hss_set_hdlc_cfg(port);
hss_config(port);
hss_start_hdlc(port);
/* we may already have RX data, enables IRQ */
napi_schedule(&port->napi);
return 0;
err_unlock:
spin_unlock_irqrestore(&npe_lock, flags);
err_destroy_queues:
destroy_hdlc_queues(port);
release_hdlc_queues(port);
err_hdlc_close:
hdlc_close(dev);
return err;
}
static int hss_hdlc_close(struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned long flags;
int i, buffs = RX_DESCS; /* allocated RX buffers */
spin_lock_irqsave(&npe_lock, flags);
ports_open--;
qmgr_disable_irq(queue_ids[port->id].rx);
netif_stop_queue(dev);
napi_disable(&port->napi);
hss_stop_hdlc(port);
while (queue_get_desc(queue_ids[port->id].rxfree, port, 0) >= 0)
buffs--;
while (queue_get_desc(queue_ids[port->id].rx, port, 0) >= 0)
buffs--;
if (buffs)
printk(KERN_CRIT "%s: unable to drain RX queue, %i buffer(s)"
" left in NPE\n", dev->name, buffs);
buffs = TX_DESCS;
while (queue_get_desc(queue_ids[port->id].tx, port, 1) >= 0)
buffs--; /* cancel TX */
i = 0;
do {
while (queue_get_desc(port->plat->txreadyq, port, 1) >= 0)
buffs--;
if (!buffs)
break;
} while (++i < MAX_CLOSE_WAIT);
if (buffs)
printk(KERN_CRIT "%s: unable to drain TX queue, %i buffer(s) "
"left in NPE\n", dev->name, buffs);
#if DEBUG_CLOSE
if (!buffs)
printk(KERN_DEBUG "Draining TX queues took %i cycles\n", i);
#endif
qmgr_disable_irq(queue_ids[port->id].txdone);
if (port->plat->close)
port->plat->close(port->id, dev);
spin_unlock_irqrestore(&npe_lock, flags);
destroy_hdlc_queues(port);
release_hdlc_queues(port);
hdlc_close(dev);
return 0;
}
static int hss_hdlc_attach(struct net_device *dev, unsigned short encoding,
unsigned short parity)
{
struct port *port = dev_to_port(dev);
if (encoding != ENCODING_NRZ)
return -EINVAL;
switch(parity) {
case PARITY_CRC16_PR1_CCITT:
port->hdlc_cfg = 0;
return 0;
case PARITY_CRC32_PR1_CCITT:
port->hdlc_cfg = PKT_HDLC_CRC_32;
return 0;
default:
return -EINVAL;
}
}
static u32 check_clock(u32 rate, u32 a, u32 b, u32 c,
u32 *best, u32 *best_diff, u32 *reg)
{
/* a is 10-bit, b is 10-bit, c is 12-bit */
u64 new_rate;
u32 new_diff;
new_rate = ixp4xx_timer_freq * (u64)(c + 1);
do_div(new_rate, a * (c + 1) + b + 1);
new_diff = abs((u32)new_rate - rate);
if (new_diff < *best_diff) {
*best = new_rate;
*best_diff = new_diff;
*reg = (a << 22) | (b << 12) | c;
}
return new_diff;
}
static void find_best_clock(u32 rate, u32 *best, u32 *reg)
{
u32 a, b, diff = 0xFFFFFFFF;
a = ixp4xx_timer_freq / rate;
if (a > 0x3FF) { /* 10-bit value - we can go as slow as ca. 65 kb/s */
check_clock(rate, 0x3FF, 1, 1, best, &diff, reg);
return;
}
if (a == 0) { /* > 66.666 MHz */
a = 1; /* minimum divider is 1 (a = 0, b = 1, c = 1) */
rate = ixp4xx_timer_freq;
}
if (rate * a == ixp4xx_timer_freq) { /* don't divide by 0 later */
check_clock(rate, a - 1, 1, 1, best, &diff, reg);
return;
}
for (b = 0; b < 0x400; b++) {
u64 c = (b + 1) * (u64)rate;
do_div(c, ixp4xx_timer_freq - rate * a);
c--;
if (c >= 0xFFF) { /* 12-bit - no need to check more 'b's */
if (b == 0 && /* also try a bit higher rate */
!check_clock(rate, a - 1, 1, 1, best, &diff, reg))
return;
check_clock(rate, a, b, 0xFFF, best, &diff, reg);
return;
}
if (!check_clock(rate, a, b, c, best, &diff, reg))
return;
if (!check_clock(rate, a, b, c + 1, best, &diff, reg))
return;
}
}
static int hss_hdlc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
const size_t size = sizeof(sync_serial_settings);
sync_serial_settings new_line;
sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
struct port *port = dev_to_port(dev);
unsigned long flags;
int clk;
if (cmd != SIOCWANDEV)
return hdlc_ioctl(dev, ifr, cmd);
switch(ifr->ifr_settings.type) {
case IF_GET_IFACE:
ifr->ifr_settings.type = IF_IFACE_V35;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
memset(&new_line, 0, sizeof(new_line));
new_line.clock_type = port->clock_type;
new_line.clock_rate = port->clock_rate;
new_line.loopback = port->loopback;
if (copy_to_user(line, &new_line, size))
return -EFAULT;
return 0;
case IF_IFACE_SYNC_SERIAL:
case IF_IFACE_V35:
if(!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&new_line, line, size))
return -EFAULT;
clk = new_line.clock_type;
if (port->plat->set_clock)
clk = port->plat->set_clock(port->id, clk);
if (clk != CLOCK_EXT && clk != CLOCK_INT)
return -EINVAL; /* No such clock setting */
if (new_line.loopback != 0 && new_line.loopback != 1)
return -EINVAL;
port->clock_type = clk; /* Update settings */
if (clk == CLOCK_INT)
find_best_clock(new_line.clock_rate, &port->clock_rate,
&port->clock_reg);
else {
port->clock_rate = 0;
port->clock_reg = CLK42X_SPEED_2048KHZ;
}
port->loopback = new_line.loopback;
spin_lock_irqsave(&npe_lock, flags);
if (dev->flags & IFF_UP)
hss_config(port);
if (port->loopback || port->carrier)
netif_carrier_on(port->netdev);
else
netif_carrier_off(port->netdev);
spin_unlock_irqrestore(&npe_lock, flags);
return 0;
default:
return hdlc_ioctl(dev, ifr, cmd);
}
}
/*****************************************************************************
* initialization
****************************************************************************/
static const struct net_device_ops hss_hdlc_ops = {
.ndo_open = hss_hdlc_open,
.ndo_stop = hss_hdlc_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = hss_hdlc_ioctl,
};
static int __devinit hss_init_one(struct platform_device *pdev)
{
struct port *port;
struct net_device *dev;
hdlc_device *hdlc;
int err;
if ((port = kzalloc(sizeof(*port), GFP_KERNEL)) == NULL)
return -ENOMEM;
if ((port->npe = npe_request(0)) == NULL) {
err = -ENODEV;
goto err_free;
}
if ((port->netdev = dev = alloc_hdlcdev(port)) == NULL) {
err = -ENOMEM;
goto err_plat;
}
SET_NETDEV_DEV(dev, &pdev->dev);
hdlc = dev_to_hdlc(dev);
hdlc->attach = hss_hdlc_attach;
hdlc->xmit = hss_hdlc_xmit;
dev->netdev_ops = &hss_hdlc_ops;
dev->tx_queue_len = 100;
port->clock_type = CLOCK_EXT;
port->clock_rate = 0;
port->clock_reg = CLK42X_SPEED_2048KHZ;
port->id = pdev->id;
port->dev = &pdev->dev;
port->plat = pdev->dev.platform_data;
netif_napi_add(dev, &port->napi, hss_hdlc_poll, NAPI_WEIGHT);
if ((err = register_hdlc_device(dev)))
goto err_free_netdev;
platform_set_drvdata(pdev, port);
printk(KERN_INFO "%s: HSS-%i\n", dev->name, port->id);
return 0;
err_free_netdev:
free_netdev(dev);
err_plat:
npe_release(port->npe);
err_free:
kfree(port);
return err;
}
static int __devexit hss_remove_one(struct platform_device *pdev)
{
struct port *port = platform_get_drvdata(pdev);
unregister_hdlc_device(port->netdev);
free_netdev(port->netdev);
npe_release(port->npe);
platform_set_drvdata(pdev, NULL);
kfree(port);
return 0;
}
static struct platform_driver ixp4xx_hss_driver = {
.driver.name = DRV_NAME,
.probe = hss_init_one,
.remove = hss_remove_one,
};
static int __init hss_init_module(void)
{
if ((ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_HDLC | IXP4XX_FEATURE_HSS)) !=
(IXP4XX_FEATURE_HDLC | IXP4XX_FEATURE_HSS))
return -ENODEV;
spin_lock_init(&npe_lock);
return platform_driver_register(&ixp4xx_hss_driver);
}
static void __exit hss_cleanup_module(void)
{
platform_driver_unregister(&ixp4xx_hss_driver);
}
MODULE_AUTHOR("Krzysztof Halasa");
MODULE_DESCRIPTION("Intel IXP4xx HSS driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ixp4xx_hss");
module_init(hss_init_module);
module_exit(hss_cleanup_module);
| gpl-2.0 |
burstlam/zte-kernel-gb | net/bluetooth/cmtp/sock.c | 1196 | 5554 | /*
CMTP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002-2003 Marcel Holtmann <marcel@holtmann.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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/ioctl.h>
#include <linux/file.h>
#include <linux/compat.h>
#include <linux/gfp.h>
#include <net/sock.h>
#include <linux/isdn/capilli.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "cmtp.h"
static int cmtp_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int cmtp_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct cmtp_connadd_req ca;
struct cmtp_conndel_req cd;
struct cmtp_connlist_req cl;
struct cmtp_conninfo ci;
struct socket *nsock;
void __user *argp = (void __user *)arg;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
switch (cmd) {
case CMTPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
nsock = sockfd_lookup(ca.sock, &err);
if (!nsock)
return err;
if (nsock->sk->sk_state != BT_CONNECTED) {
sockfd_put(nsock);
return -EBADFD;
}
err = cmtp_add_connection(&ca, nsock);
if (!err) {
if (copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
} else
sockfd_put(nsock);
return err;
case CMTPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return cmtp_del_connection(&cd);
case CMTPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = cmtp_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case CMTPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = cmtp_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
}
return -EINVAL;
}
#ifdef CONFIG_COMPAT
static int cmtp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
if (cmd == CMTPGETCONNLIST) {
struct cmtp_connlist_req cl;
uint32_t uci;
int err;
if (get_user(cl.cnum, (uint32_t __user *) arg) ||
get_user(uci, (u32 __user *) (arg + 4)))
return -EFAULT;
cl.ci = compat_ptr(uci);
if (cl.cnum <= 0)
return -EINVAL;
err = cmtp_get_connlist(&cl);
if (!err && put_user(cl.cnum, (uint32_t __user *) arg))
err = -EFAULT;
return err;
}
return cmtp_sock_ioctl(sock, cmd, arg);
}
#endif
static const struct proto_ops cmtp_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = cmtp_sock_release,
.ioctl = cmtp_sock_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = cmtp_sock_compat_ioctl,
#endif
.bind = sock_no_bind,
.getname = sock_no_getname,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto cmtp_proto = {
.name = "CMTP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct bt_sock)
};
static int cmtp_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &cmtp_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &cmtp_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = BT_OPEN;
return 0;
}
static const struct net_proto_family cmtp_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = cmtp_sock_create
};
int cmtp_init_sockets(void)
{
int err;
err = proto_register(&cmtp_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_CMTP, &cmtp_sock_family_ops);
if (err < 0)
goto error;
return 0;
error:
BT_ERR("Can't register CMTP socket");
proto_unregister(&cmtp_proto);
return err;
}
void cmtp_cleanup_sockets(void)
{
if (bt_sock_unregister(BTPROTO_CMTP) < 0)
BT_ERR("Can't unregister CMTP socket");
proto_unregister(&cmtp_proto);
}
| gpl-2.0 |
jthornber/linux-2.6 | arch/arm/mach-axxia/platsmp.c | 1452 | 2189 | /*
* linux/arch/arm/mach-axxia/platsmp.c
*
* Copyright (C) 2012 LSI Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/smp.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <asm/cacheflush.h>
/* Syscon register offsets for releasing cores from reset */
#define SC_CRIT_WRITE_KEY 0x1000
#define SC_RST_CPU_HOLD 0x1010
/*
* Write the kernel entry point for secondary CPUs to the specified address
*/
static void write_release_addr(u32 release_phys)
{
u32 *virt = (u32 *) phys_to_virt(release_phys);
writel_relaxed(virt_to_phys(secondary_startup), virt);
/* Make sure this store is visible to other CPUs */
smp_wmb();
__cpuc_flush_dcache_area(virt, sizeof(u32));
}
static int axxia_boot_secondary(unsigned int cpu, struct task_struct *idle)
{
struct device_node *syscon_np;
void __iomem *syscon;
u32 tmp;
syscon_np = of_find_compatible_node(NULL, NULL, "lsi,axxia-syscon");
if (!syscon_np)
return -ENOENT;
syscon = of_iomap(syscon_np, 0);
if (!syscon)
return -ENOMEM;
tmp = readl(syscon + SC_RST_CPU_HOLD);
writel(0xab, syscon + SC_CRIT_WRITE_KEY);
tmp &= ~(1 << cpu);
writel(tmp, syscon + SC_RST_CPU_HOLD);
return 0;
}
static void __init axxia_smp_prepare_cpus(unsigned int max_cpus)
{
int cpu_count = 0;
int cpu;
/*
* Initialise the present map, which describes the set of CPUs actually
* populated at the present time.
*/
for_each_possible_cpu(cpu) {
struct device_node *np;
u32 release_phys;
np = of_get_cpu_node(cpu, NULL);
if (!np)
continue;
if (of_property_read_u32(np, "cpu-release-addr", &release_phys))
continue;
if (cpu_count < max_cpus) {
set_cpu_present(cpu, true);
cpu_count++;
}
if (release_phys != 0)
write_release_addr(release_phys);
}
}
static struct smp_operations axxia_smp_ops __initdata = {
.smp_prepare_cpus = axxia_smp_prepare_cpus,
.smp_boot_secondary = axxia_boot_secondary,
};
CPU_METHOD_OF_DECLARE(axxia_smp, "lsi,syscon-release", &axxia_smp_ops);
| gpl-2.0 |
eskyuu/linux | drivers/media/radio/radio-cadet.c | 1708 | 16987 | /* radio-cadet.c - A video4linux driver for the ADS Cadet AM/FM Radio Card
*
* by Fred Gleason <fredg@wava.com>
* Version 0.3.3
*
* (Loosely) based on code for the Aztech radio card by
*
* Russell Kroll (rkroll@exploits.org)
* Quay Ly
* Donald Song
* Jason Lewis (jlewis@twilight.vtc.vsc.edu)
* Scott McGrath (smcgrath@twilight.vtc.vsc.edu)
* William McGrath (wmcgrath@twilight.vtc.vsc.edu)
*
* History:
* 2000-04-29 Russell Kroll <rkroll@exploits.org>
* Added ISAPnP detection for Linux 2.3/2.4
*
* 2001-01-10 Russell Kroll <rkroll@exploits.org>
* Removed dead CONFIG_RADIO_CADET_PORT code
* PnP detection on load is now default (no args necessary)
*
* 2002-01-17 Adam Belay <ambx1@neo.rr.com>
* Updated to latest pnp code
*
* 2003-01-31 Alan Cox <alan@lxorguk.ukuu.org.uk>
* Cleaned up locking, delay code, general odds and ends
*
* 2006-07-30 Hans J. Koch <koch@hjk-az.de>
* Changed API to V4L2
*/
#include <linux/module.h> /* Modules */
#include <linux/init.h> /* Initdata */
#include <linux/ioport.h> /* request_region */
#include <linux/delay.h> /* udelay */
#include <linux/videodev2.h> /* V4L2 API defs */
#include <linux/param.h>
#include <linux/pnp.h>
#include <linux/sched.h>
#include <linux/io.h> /* outb, outb_p */
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
MODULE_AUTHOR("Fred Gleason, Russell Kroll, Quay Lu, Donald Song, Jason Lewis, Scott McGrath, William McGrath");
MODULE_DESCRIPTION("A driver for the ADS Cadet AM/FM/RDS radio card.");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.3.4");
static int io = -1; /* default to isapnp activation */
static int radio_nr = -1;
module_param(io, int, 0);
MODULE_PARM_DESC(io, "I/O address of Cadet card (0x330,0x332,0x334,0x336,0x338,0x33a,0x33c,0x33e)");
module_param(radio_nr, int, 0);
#define RDS_BUFFER 256
#define RDS_RX_FLAG 1
#define MBS_RX_FLAG 2
struct cadet {
struct v4l2_device v4l2_dev;
struct video_device vdev;
struct v4l2_ctrl_handler ctrl_handler;
int io;
bool is_fm_band;
u32 curfreq;
int tunestat;
int sigstrength;
wait_queue_head_t read_queue;
struct timer_list readtimer;
u8 rdsin, rdsout, rdsstat;
unsigned char rdsbuf[RDS_BUFFER];
struct mutex lock;
int reading;
};
static struct cadet cadet_card;
/*
* Signal Strength Threshold Values
* The V4L API spec does not define any particular unit for the signal
* strength value. These values are in microvolts of RF at the tuner's input.
*/
static u16 sigtable[2][4] = {
{ 1835, 2621, 4128, 65535 },
{ 2185, 4369, 13107, 65535 },
};
static const struct v4l2_frequency_band bands[] = {
{
.index = 0,
.type = V4L2_TUNER_RADIO,
.capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 8320, /* 520 kHz */
.rangehigh = 26400, /* 1650 kHz */
.modulation = V4L2_BAND_MODULATION_AM,
}, {
.index = 1,
.type = V4L2_TUNER_RADIO,
.capability = V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_RDS |
V4L2_TUNER_CAP_RDS_BLOCK_IO | V4L2_TUNER_CAP_LOW |
V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 1400000, /* 87.5 MHz */
.rangehigh = 1728000, /* 108.0 MHz */
.modulation = V4L2_BAND_MODULATION_FM,
},
};
static int cadet_getstereo(struct cadet *dev)
{
int ret = V4L2_TUNER_SUB_MONO;
if (!dev->is_fm_band) /* Only FM has stereo capability! */
return V4L2_TUNER_SUB_MONO;
outb(7, dev->io); /* Select tuner control */
if ((inb(dev->io + 1) & 0x40) == 0)
ret = V4L2_TUNER_SUB_STEREO;
return ret;
}
static unsigned cadet_gettune(struct cadet *dev)
{
int curvol, i;
unsigned fifo = 0;
/*
* Prepare for read
*/
outb(7, dev->io); /* Select tuner control */
curvol = inb(dev->io + 1); /* Save current volume/mute setting */
outb(0x00, dev->io + 1); /* Ensure WRITE-ENABLE is LOW */
dev->tunestat = 0xffff;
/*
* Read the shift register
*/
for (i = 0; i < 25; i++) {
fifo = (fifo << 1) | ((inb(dev->io + 1) >> 7) & 0x01);
if (i < 24) {
outb(0x01, dev->io + 1);
dev->tunestat &= inb(dev->io + 1);
outb(0x00, dev->io + 1);
}
}
/*
* Restore volume/mute setting
*/
outb(curvol, dev->io + 1);
return fifo;
}
static unsigned cadet_getfreq(struct cadet *dev)
{
int i;
unsigned freq = 0, test, fifo = 0;
/*
* Read current tuning
*/
fifo = cadet_gettune(dev);
/*
* Convert to actual frequency
*/
if (!dev->is_fm_band) /* AM */
return ((fifo & 0x7fff) - 450) * 16;
test = 12500;
for (i = 0; i < 14; i++) {
if ((fifo & 0x01) != 0)
freq += test;
test = test << 1;
fifo = fifo >> 1;
}
freq -= 10700000; /* IF frequency is 10.7 MHz */
freq = (freq * 16) / 1000; /* Make it 1/16 kHz */
return freq;
}
static void cadet_settune(struct cadet *dev, unsigned fifo)
{
int i;
unsigned test;
outb(7, dev->io); /* Select tuner control */
/*
* Write the shift register
*/
test = 0;
test = (fifo >> 23) & 0x02; /* Align data for SDO */
test |= 0x1c; /* SDM=1, SWE=1, SEN=1, SCK=0 */
outb(7, dev->io); /* Select tuner control */
outb(test, dev->io + 1); /* Initialize for write */
for (i = 0; i < 25; i++) {
test |= 0x01; /* Toggle SCK High */
outb(test, dev->io + 1);
test &= 0xfe; /* Toggle SCK Low */
outb(test, dev->io + 1);
fifo = fifo << 1; /* Prepare the next bit */
test = 0x1c | ((fifo >> 23) & 0x02);
outb(test, dev->io + 1);
}
}
static void cadet_setfreq(struct cadet *dev, unsigned freq)
{
unsigned fifo;
int i, j, test;
int curvol;
freq = clamp(freq, bands[dev->is_fm_band].rangelow,
bands[dev->is_fm_band].rangehigh);
dev->curfreq = freq;
/*
* Formulate a fifo command
*/
fifo = 0;
if (dev->is_fm_band) { /* FM */
test = 102400;
freq = freq / 16; /* Make it kHz */
freq += 10700; /* IF is 10700 kHz */
for (i = 0; i < 14; i++) {
fifo = fifo << 1;
if (freq >= test) {
fifo |= 0x01;
freq -= test;
}
test = test >> 1;
}
} else { /* AM */
fifo = (freq / 16) + 450; /* Make it kHz */
fifo |= 0x100000; /* Select AM Band */
}
/*
* Save current volume/mute setting
*/
outb(7, dev->io); /* Select tuner control */
curvol = inb(dev->io + 1);
/*
* Tune the card
*/
for (j = 3; j > -1; j--) {
cadet_settune(dev, fifo | (j << 16));
outb(7, dev->io); /* Select tuner control */
outb(curvol, dev->io + 1);
msleep(100);
cadet_gettune(dev);
if ((dev->tunestat & 0x40) == 0) { /* Tuned */
dev->sigstrength = sigtable[dev->is_fm_band][j];
goto reset_rds;
}
}
dev->sigstrength = 0;
reset_rds:
outb(3, dev->io);
outb(inb(dev->io + 1) & 0x7f, dev->io + 1);
}
static bool cadet_has_rds_data(struct cadet *dev)
{
bool result;
mutex_lock(&dev->lock);
result = dev->rdsin != dev->rdsout;
mutex_unlock(&dev->lock);
return result;
}
static void cadet_handler(unsigned long data)
{
struct cadet *dev = (void *)data;
/* Service the RDS fifo */
if (mutex_trylock(&dev->lock)) {
outb(0x3, dev->io); /* Select RDS Decoder Control */
if ((inb(dev->io + 1) & 0x20) != 0)
pr_err("cadet: RDS fifo overflow\n");
outb(0x80, dev->io); /* Select RDS fifo */
while ((inb(dev->io) & 0x80) != 0) {
dev->rdsbuf[dev->rdsin] = inb(dev->io + 1);
if (dev->rdsin + 1 != dev->rdsout)
dev->rdsin++;
}
mutex_unlock(&dev->lock);
}
/*
* Service pending read
*/
if (cadet_has_rds_data(dev))
wake_up_interruptible(&dev->read_queue);
/*
* Clean up and exit
*/
init_timer(&dev->readtimer);
dev->readtimer.function = cadet_handler;
dev->readtimer.data = data;
dev->readtimer.expires = jiffies + msecs_to_jiffies(50);
add_timer(&dev->readtimer);
}
static void cadet_start_rds(struct cadet *dev)
{
dev->rdsstat = 1;
outb(0x80, dev->io); /* Select RDS fifo */
init_timer(&dev->readtimer);
dev->readtimer.function = cadet_handler;
dev->readtimer.data = (unsigned long)dev;
dev->readtimer.expires = jiffies + msecs_to_jiffies(50);
add_timer(&dev->readtimer);
}
static ssize_t cadet_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
{
struct cadet *dev = video_drvdata(file);
unsigned char readbuf[RDS_BUFFER];
int i = 0;
mutex_lock(&dev->lock);
if (dev->rdsstat == 0)
cadet_start_rds(dev);
mutex_unlock(&dev->lock);
if (!cadet_has_rds_data(dev) && (file->f_flags & O_NONBLOCK))
return -EWOULDBLOCK;
i = wait_event_interruptible(dev->read_queue, cadet_has_rds_data(dev));
if (i)
return i;
mutex_lock(&dev->lock);
while (i < count && dev->rdsin != dev->rdsout)
readbuf[i++] = dev->rdsbuf[dev->rdsout++];
mutex_unlock(&dev->lock);
if (i && copy_to_user(data, readbuf, i))
return -EFAULT;
return i;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
strlcpy(v->driver, "ADS Cadet", sizeof(v->driver));
strlcpy(v->card, "ADS Cadet", sizeof(v->card));
strlcpy(v->bus_info, "ISA:radio-cadet", sizeof(v->bus_info));
v->device_caps = V4L2_CAP_TUNER | V4L2_CAP_RADIO |
V4L2_CAP_READWRITE | V4L2_CAP_RDS_CAPTURE;
v->capabilities = v->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct cadet *dev = video_drvdata(file);
if (v->index)
return -EINVAL;
v->type = V4L2_TUNER_RADIO;
strlcpy(v->name, "Radio", sizeof(v->name));
v->capability = bands[0].capability | bands[1].capability;
v->rangelow = bands[0].rangelow; /* 520 kHz (start of AM band) */
v->rangehigh = bands[1].rangehigh; /* 108.0 MHz (end of FM band) */
if (dev->is_fm_band) {
v->rxsubchans = cadet_getstereo(dev);
outb(3, dev->io);
outb(inb(dev->io + 1) & 0x7f, dev->io + 1);
mdelay(100);
outb(3, dev->io);
if (inb(dev->io + 1) & 0x80)
v->rxsubchans |= V4L2_TUNER_SUB_RDS;
} else {
v->rangelow = 8320; /* 520 kHz */
v->rangehigh = 26400; /* 1650 kHz */
v->rxsubchans = V4L2_TUNER_SUB_MONO;
}
v->audmode = V4L2_TUNER_MODE_STEREO;
v->signal = dev->sigstrength; /* We might need to modify scaling of this */
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
const struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int vidioc_enum_freq_bands(struct file *file, void *priv,
struct v4l2_frequency_band *band)
{
if (band->tuner)
return -EINVAL;
if (band->index >= ARRAY_SIZE(bands))
return -EINVAL;
*band = bands[band->index];
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct cadet *dev = video_drvdata(file);
if (f->tuner)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = dev->curfreq;
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
const struct v4l2_frequency *f)
{
struct cadet *dev = video_drvdata(file);
if (f->tuner)
return -EINVAL;
dev->is_fm_band =
f->frequency >= (bands[0].rangehigh + bands[1].rangelow) / 2;
cadet_setfreq(dev, f->frequency);
return 0;
}
static int cadet_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct cadet *dev = container_of(ctrl->handler, struct cadet, ctrl_handler);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
outb(7, dev->io); /* Select tuner control */
if (ctrl->val)
outb(0x00, dev->io + 1);
else
outb(0x20, dev->io + 1);
return 0;
}
return -EINVAL;
}
static int cadet_open(struct file *file)
{
struct cadet *dev = video_drvdata(file);
int err;
mutex_lock(&dev->lock);
err = v4l2_fh_open(file);
if (err)
goto fail;
if (v4l2_fh_is_singular_file(file))
init_waitqueue_head(&dev->read_queue);
fail:
mutex_unlock(&dev->lock);
return err;
}
static int cadet_release(struct file *file)
{
struct cadet *dev = video_drvdata(file);
mutex_lock(&dev->lock);
if (v4l2_fh_is_singular_file(file) && dev->rdsstat) {
del_timer_sync(&dev->readtimer);
dev->rdsstat = 0;
}
v4l2_fh_release(file);
mutex_unlock(&dev->lock);
return 0;
}
static unsigned int cadet_poll(struct file *file, struct poll_table_struct *wait)
{
struct cadet *dev = video_drvdata(file);
unsigned long req_events = poll_requested_events(wait);
unsigned int res = v4l2_ctrl_poll(file, wait);
poll_wait(file, &dev->read_queue, wait);
if (dev->rdsstat == 0 && (req_events & (POLLIN | POLLRDNORM))) {
mutex_lock(&dev->lock);
if (dev->rdsstat == 0)
cadet_start_rds(dev);
mutex_unlock(&dev->lock);
}
if (cadet_has_rds_data(dev))
res |= POLLIN | POLLRDNORM;
return res;
}
static const struct v4l2_file_operations cadet_fops = {
.owner = THIS_MODULE,
.open = cadet_open,
.release = cadet_release,
.read = cadet_read,
.unlocked_ioctl = video_ioctl2,
.poll = cadet_poll,
};
static const struct v4l2_ioctl_ops cadet_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_enum_freq_bands = vidioc_enum_freq_bands,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static const struct v4l2_ctrl_ops cadet_ctrl_ops = {
.s_ctrl = cadet_s_ctrl,
};
#ifdef CONFIG_PNP
static struct pnp_device_id cadet_pnp_devices[] = {
/* ADS Cadet AM/FM Radio Card */
{.id = "MSM0c24", .driver_data = 0},
{.id = ""}
};
MODULE_DEVICE_TABLE(pnp, cadet_pnp_devices);
static int cadet_pnp_probe(struct pnp_dev *dev, const struct pnp_device_id *dev_id)
{
if (!dev)
return -ENODEV;
/* only support one device */
if (io > 0)
return -EBUSY;
if (!pnp_port_valid(dev, 0))
return -ENODEV;
io = pnp_port_start(dev, 0);
printk(KERN_INFO "radio-cadet: PnP reports device at %#x\n", io);
return io;
}
static struct pnp_driver cadet_pnp_driver = {
.name = "radio-cadet",
.id_table = cadet_pnp_devices,
.probe = cadet_pnp_probe,
.remove = NULL,
};
#else
static struct pnp_driver cadet_pnp_driver;
#endif
static void cadet_probe(struct cadet *dev)
{
static int iovals[8] = { 0x330, 0x332, 0x334, 0x336, 0x338, 0x33a, 0x33c, 0x33e };
int i;
for (i = 0; i < 8; i++) {
dev->io = iovals[i];
if (request_region(dev->io, 2, "cadet-probe")) {
cadet_setfreq(dev, bands[1].rangelow);
if (cadet_getfreq(dev) == bands[1].rangelow) {
release_region(dev->io, 2);
return;
}
release_region(dev->io, 2);
}
}
dev->io = -1;
}
/*
* io should only be set if the user has used something like
* isapnp (the userspace program) to initialize this card for us
*/
static int __init cadet_init(void)
{
struct cadet *dev = &cadet_card;
struct v4l2_device *v4l2_dev = &dev->v4l2_dev;
struct v4l2_ctrl_handler *hdl;
int res = -ENODEV;
strlcpy(v4l2_dev->name, "cadet", sizeof(v4l2_dev->name));
mutex_init(&dev->lock);
/* If a probe was requested then probe ISAPnP first (safest) */
if (io < 0)
pnp_register_driver(&cadet_pnp_driver);
dev->io = io;
/* If that fails then probe unsafely if probe is requested */
if (dev->io < 0)
cadet_probe(dev);
/* Else we bail out */
if (dev->io < 0) {
#ifdef MODULE
v4l2_err(v4l2_dev, "you must set an I/O address with io=0x330, 0x332, 0x334,\n");
v4l2_err(v4l2_dev, "0x336, 0x338, 0x33a, 0x33c or 0x33e\n");
#endif
goto fail;
}
if (!request_region(dev->io, 2, "cadet"))
goto fail;
res = v4l2_device_register(NULL, v4l2_dev);
if (res < 0) {
release_region(dev->io, 2);
v4l2_err(v4l2_dev, "could not register v4l2_device\n");
goto fail;
}
hdl = &dev->ctrl_handler;
v4l2_ctrl_handler_init(hdl, 2);
v4l2_ctrl_new_std(hdl, &cadet_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
v4l2_dev->ctrl_handler = hdl;
if (hdl->error) {
res = hdl->error;
v4l2_err(v4l2_dev, "Could not register controls\n");
goto err_hdl;
}
dev->is_fm_band = true;
dev->curfreq = bands[dev->is_fm_band].rangelow;
cadet_setfreq(dev, dev->curfreq);
strlcpy(dev->vdev.name, v4l2_dev->name, sizeof(dev->vdev.name));
dev->vdev.v4l2_dev = v4l2_dev;
dev->vdev.fops = &cadet_fops;
dev->vdev.ioctl_ops = &cadet_ioctl_ops;
dev->vdev.release = video_device_release_empty;
dev->vdev.lock = &dev->lock;
video_set_drvdata(&dev->vdev, dev);
res = video_register_device(&dev->vdev, VFL_TYPE_RADIO, radio_nr);
if (res < 0)
goto err_hdl;
v4l2_info(v4l2_dev, "ADS Cadet Radio Card at 0x%x\n", dev->io);
return 0;
err_hdl:
v4l2_ctrl_handler_free(hdl);
v4l2_device_unregister(v4l2_dev);
release_region(dev->io, 2);
fail:
pnp_unregister_driver(&cadet_pnp_driver);
return res;
}
static void __exit cadet_exit(void)
{
struct cadet *dev = &cadet_card;
video_unregister_device(&dev->vdev);
v4l2_ctrl_handler_free(&dev->ctrl_handler);
v4l2_device_unregister(&dev->v4l2_dev);
outb(7, dev->io); /* Mute */
outb(0x00, dev->io + 1);
release_region(dev->io, 2);
pnp_unregister_driver(&cadet_pnp_driver);
}
module_init(cadet_init);
module_exit(cadet_exit);
| gpl-2.0 |
hypnos-android/Hypnos | drivers/video/backlight/jornada720_lcd.c | 1708 | 3436 | /*
*
* LCD driver for HP Jornada 700 series (710/720/728)
* Copyright (C) 2006-2009 Kristoffer Ericson <kristoffer.ericson@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 or any later version as published by the Free Software Foundation.
*
*/
#include <linux/device.h>
#include <linux/fb.h>
#include <linux/kernel.h>
#include <linux/lcd.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <mach/jornada720.h>
#include <mach/hardware.h>
#include <video/s1d13xxxfb.h>
#define LCD_MAX_CONTRAST 0xff
#define LCD_DEF_CONTRAST 0x80
static int jornada_lcd_get_power(struct lcd_device *dev)
{
/* LDD2 in PPC = LCD POWER */
if (PPSR & PPC_LDD2)
return FB_BLANK_UNBLANK; /* PW ON */
else
return FB_BLANK_POWERDOWN; /* PW OFF */
}
static int jornada_lcd_get_contrast(struct lcd_device *dev)
{
int ret;
if (jornada_lcd_get_power(dev) != FB_BLANK_UNBLANK)
return 0;
jornada_ssp_start();
if (jornada_ssp_byte(GETCONTRAST) != TXDUMMY) {
printk(KERN_ERR "lcd: get contrast failed\n");
jornada_ssp_end();
return -ETIMEDOUT;
} else {
ret = jornada_ssp_byte(TXDUMMY);
jornada_ssp_end();
return ret;
}
}
static int jornada_lcd_set_contrast(struct lcd_device *dev, int value)
{
int ret;
jornada_ssp_start();
/* start by sending our set contrast cmd to mcu */
ret = jornada_ssp_byte(SETCONTRAST);
/* push the new value */
if (jornada_ssp_byte(value) != TXDUMMY) {
printk(KERN_ERR "lcd : set contrast failed\n");
jornada_ssp_end();
return -ETIMEDOUT;
}
/* if we get here we can assume everything went well */
jornada_ssp_end();
return 0;
}
static int jornada_lcd_set_power(struct lcd_device *dev, int power)
{
if (power != FB_BLANK_UNBLANK) {
PPSR &= ~PPC_LDD2;
PPDR |= PPC_LDD2;
} else
PPSR |= PPC_LDD2;
return 0;
}
static struct lcd_ops jornada_lcd_props = {
.get_contrast = jornada_lcd_get_contrast,
.set_contrast = jornada_lcd_set_contrast,
.get_power = jornada_lcd_get_power,
.set_power = jornada_lcd_set_power,
};
static int jornada_lcd_probe(struct platform_device *pdev)
{
struct lcd_device *lcd_device;
int ret;
lcd_device = lcd_device_register(S1D_DEVICENAME, &pdev->dev, NULL, &jornada_lcd_props);
if (IS_ERR(lcd_device)) {
ret = PTR_ERR(lcd_device);
printk(KERN_ERR "lcd : failed to register device\n");
return ret;
}
platform_set_drvdata(pdev, lcd_device);
/* lets set our default values */
jornada_lcd_set_contrast(lcd_device, LCD_DEF_CONTRAST);
jornada_lcd_set_power(lcd_device, FB_BLANK_UNBLANK);
/* give it some time to startup */
msleep(100);
return 0;
}
static int jornada_lcd_remove(struct platform_device *pdev)
{
struct lcd_device *lcd_device = platform_get_drvdata(pdev);
lcd_device_unregister(lcd_device);
return 0;
}
static struct platform_driver jornada_lcd_driver = {
.probe = jornada_lcd_probe,
.remove = jornada_lcd_remove,
.driver = {
.name = "jornada_lcd",
},
};
int __init jornada_lcd_init(void)
{
return platform_driver_register(&jornada_lcd_driver);
}
void __exit jornada_lcd_exit(void)
{
platform_driver_unregister(&jornada_lcd_driver);
}
MODULE_AUTHOR("Kristoffer Ericson <kristoffer.ericson@gmail.com>");
MODULE_DESCRIPTION("HP Jornada 710/720/728 LCD driver");
MODULE_LICENSE("GPL");
module_init(jornada_lcd_init);
module_exit(jornada_lcd_exit);
| gpl-2.0 |
nychitman1/android_kernel_htc_flounder | drivers/input/misc/pcap_keys.c | 2476 | 3197 | /*
* Input driver for PCAP events:
* * Power key
* * Headphone button
*
* Copyright (c) 2008,2009 Ilya Petrov <ilya.muromec@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/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/mfd/ezx-pcap.h>
#include <linux/slab.h>
struct pcap_keys {
struct pcap_chip *pcap;
struct input_dev *input;
};
/* PCAP2 interrupts us on keypress */
static irqreturn_t pcap_keys_handler(int irq, void *_pcap_keys)
{
struct pcap_keys *pcap_keys = _pcap_keys;
int pirq = irq_to_pcap(pcap_keys->pcap, irq);
u32 pstat;
ezx_pcap_read(pcap_keys->pcap, PCAP_REG_PSTAT, &pstat);
pstat &= 1 << pirq;
switch (pirq) {
case PCAP_IRQ_ONOFF:
input_report_key(pcap_keys->input, KEY_POWER, !pstat);
break;
case PCAP_IRQ_MIC:
input_report_key(pcap_keys->input, KEY_HP, !pstat);
break;
}
input_sync(pcap_keys->input);
return IRQ_HANDLED;
}
static int pcap_keys_probe(struct platform_device *pdev)
{
int err = -ENOMEM;
struct pcap_keys *pcap_keys;
struct input_dev *input_dev;
pcap_keys = kmalloc(sizeof(struct pcap_keys), GFP_KERNEL);
if (!pcap_keys)
return err;
pcap_keys->pcap = dev_get_drvdata(pdev->dev.parent);
input_dev = input_allocate_device();
if (!input_dev)
goto fail;
pcap_keys->input = input_dev;
platform_set_drvdata(pdev, pcap_keys);
input_dev->name = pdev->name;
input_dev->phys = "pcap-keys/input0";
input_dev->id.bustype = BUS_HOST;
input_dev->dev.parent = &pdev->dev;
__set_bit(EV_KEY, input_dev->evbit);
__set_bit(KEY_POWER, input_dev->keybit);
__set_bit(KEY_HP, input_dev->keybit);
err = input_register_device(input_dev);
if (err)
goto fail_allocate;
err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF),
pcap_keys_handler, 0, "Power key", pcap_keys);
if (err)
goto fail_register;
err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC),
pcap_keys_handler, 0, "Headphone button", pcap_keys);
if (err)
goto fail_pwrkey;
return 0;
fail_pwrkey:
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys);
fail_register:
input_unregister_device(input_dev);
goto fail;
fail_allocate:
input_free_device(input_dev);
fail:
kfree(pcap_keys);
return err;
}
static int pcap_keys_remove(struct platform_device *pdev)
{
struct pcap_keys *pcap_keys = platform_get_drvdata(pdev);
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys);
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC), pcap_keys);
input_unregister_device(pcap_keys->input);
kfree(pcap_keys);
return 0;
}
static struct platform_driver pcap_keys_device_driver = {
.probe = pcap_keys_probe,
.remove = pcap_keys_remove,
.driver = {
.name = "pcap-keys",
.owner = THIS_MODULE,
}
};
module_platform_driver(pcap_keys_device_driver);
MODULE_DESCRIPTION("Motorola PCAP2 input events driver");
MODULE_AUTHOR("Ilya Petrov <ilya.muromec@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pcap_keys");
| gpl-2.0 |
playfulgod/kernel_lge-m695 | arch/um/drivers/chan_kern.c | 2732 | 13210 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include "chan_kern.h"
#include "os.h"
#ifdef CONFIG_NOCONFIG_CHAN
static void *not_configged_init(char *str, int device,
const struct chan_opts *opts)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return NULL;
}
static int not_configged_open(int input, int output, int primary, void *data,
char **dev_out)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -ENODEV;
}
static void not_configged_close(int fd, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
}
static int not_configged_read(int fd, char *c_out, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_write(int fd, const char *buf, int len, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_console_write(int fd, const char *buf, int len)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_window_size(int fd, void *data, unsigned short *rows,
unsigned short *cols)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -ENODEV;
}
static void not_configged_free(void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
}
static const struct chan_ops not_configged_ops = {
.init = not_configged_init,
.open = not_configged_open,
.close = not_configged_close,
.read = not_configged_read,
.write = not_configged_write,
.console_write = not_configged_console_write,
.window_size = not_configged_window_size,
.free = not_configged_free,
.winch = 0,
};
#endif /* CONFIG_NOCONFIG_CHAN */
static void tty_receive_char(struct tty_struct *tty, char ch)
{
if (tty == NULL)
return;
if (I_IXON(tty) && !I_IXOFF(tty) && !tty->raw) {
if (ch == STOP_CHAR(tty)) {
stop_tty(tty);
return;
}
else if (ch == START_CHAR(tty)) {
start_tty(tty);
return;
}
}
tty_insert_flip_char(tty, ch, TTY_NORMAL);
}
static int open_one_chan(struct chan *chan)
{
int fd, err;
if (chan->opened)
return 0;
if (chan->ops->open == NULL)
fd = 0;
else fd = (*chan->ops->open)(chan->input, chan->output, chan->primary,
chan->data, &chan->dev);
if (fd < 0)
return fd;
err = os_set_fd_block(fd, 0);
if (err) {
(*chan->ops->close)(fd, chan->data);
return err;
}
chan->fd = fd;
chan->opened = 1;
return 0;
}
static int open_chan(struct list_head *chans)
{
struct list_head *ele;
struct chan *chan;
int ret, err = 0;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
ret = open_one_chan(chan);
if (chan->primary)
err = ret;
}
return err;
}
void chan_enable_winch(struct list_head *chans, struct tty_struct *tty)
{
struct list_head *ele;
struct chan *chan;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (chan->primary && chan->output && chan->ops->winch) {
register_winch(chan->fd, tty);
return;
}
}
}
int enable_chan(struct line *line)
{
struct list_head *ele;
struct chan *chan;
int err;
list_for_each(ele, &line->chan_list) {
chan = list_entry(ele, struct chan, list);
err = open_one_chan(chan);
if (err) {
if (chan->primary)
goto out_close;
continue;
}
if (chan->enabled)
continue;
err = line_setup_irq(chan->fd, chan->input, chan->output, line,
chan);
if (err)
goto out_close;
chan->enabled = 1;
}
return 0;
out_close:
close_chan(&line->chan_list, 0);
return err;
}
/* Items are added in IRQ context, when free_irq can't be called, and
* removed in process context, when it can.
* This handles interrupt sources which disappear, and which need to
* be permanently disabled. This is discovered in IRQ context, but
* the freeing of the IRQ must be done later.
*/
static DEFINE_SPINLOCK(irqs_to_free_lock);
static LIST_HEAD(irqs_to_free);
void free_irqs(void)
{
struct chan *chan;
LIST_HEAD(list);
struct list_head *ele;
unsigned long flags;
spin_lock_irqsave(&irqs_to_free_lock, flags);
list_splice_init(&irqs_to_free, &list);
spin_unlock_irqrestore(&irqs_to_free_lock, flags);
list_for_each(ele, &list) {
chan = list_entry(ele, struct chan, free_list);
if (chan->input && chan->enabled)
free_irq(chan->line->driver->read_irq, chan);
if (chan->output && chan->enabled)
free_irq(chan->line->driver->write_irq, chan);
chan->enabled = 0;
}
}
static void close_one_chan(struct chan *chan, int delay_free_irq)
{
unsigned long flags;
if (!chan->opened)
return;
if (delay_free_irq) {
spin_lock_irqsave(&irqs_to_free_lock, flags);
list_add(&chan->free_list, &irqs_to_free);
spin_unlock_irqrestore(&irqs_to_free_lock, flags);
}
else {
if (chan->input && chan->enabled)
free_irq(chan->line->driver->read_irq, chan);
if (chan->output && chan->enabled)
free_irq(chan->line->driver->write_irq, chan);
chan->enabled = 0;
}
if (chan->ops->close != NULL)
(*chan->ops->close)(chan->fd, chan->data);
chan->opened = 0;
chan->fd = -1;
}
void close_chan(struct list_head *chans, int delay_free_irq)
{
struct chan *chan;
/* Close in reverse order as open in case more than one of them
* refers to the same device and they save and restore that device's
* state. Then, the first one opened will have the original state,
* so it must be the last closed.
*/
list_for_each_entry_reverse(chan, chans, list) {
close_one_chan(chan, delay_free_irq);
}
}
void deactivate_chan(struct list_head *chans, int irq)
{
struct list_head *ele;
struct chan *chan;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (chan->enabled && chan->input)
deactivate_fd(chan->fd, irq);
}
}
void reactivate_chan(struct list_head *chans, int irq)
{
struct list_head *ele;
struct chan *chan;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (chan->enabled && chan->input)
reactivate_fd(chan->fd, irq);
}
}
int write_chan(struct list_head *chans, const char *buf, int len,
int write_irq)
{
struct list_head *ele;
struct chan *chan = NULL;
int n, ret = 0;
if (len == 0)
return 0;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (!chan->output || (chan->ops->write == NULL))
continue;
n = chan->ops->write(chan->fd, buf, len, chan->data);
if (chan->primary) {
ret = n;
if ((ret == -EAGAIN) || ((ret >= 0) && (ret < len)))
reactivate_fd(chan->fd, write_irq);
}
}
return ret;
}
int console_write_chan(struct list_head *chans, const char *buf, int len)
{
struct list_head *ele;
struct chan *chan;
int n, ret = 0;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (!chan->output || (chan->ops->console_write == NULL))
continue;
n = chan->ops->console_write(chan->fd, buf, len);
if (chan->primary)
ret = n;
}
return ret;
}
int console_open_chan(struct line *line, struct console *co)
{
int err;
err = open_chan(&line->chan_list);
if (err)
return err;
printk(KERN_INFO "Console initialized on /dev/%s%d\n", co->name,
co->index);
return 0;
}
int chan_window_size(struct list_head *chans, unsigned short *rows_out,
unsigned short *cols_out)
{
struct list_head *ele;
struct chan *chan;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (chan->primary) {
if (chan->ops->window_size == NULL)
return 0;
return chan->ops->window_size(chan->fd, chan->data,
rows_out, cols_out);
}
}
return 0;
}
static void free_one_chan(struct chan *chan, int delay_free_irq)
{
list_del(&chan->list);
close_one_chan(chan, delay_free_irq);
if (chan->ops->free != NULL)
(*chan->ops->free)(chan->data);
if (chan->primary && chan->output)
ignore_sigio_fd(chan->fd);
kfree(chan);
}
static void free_chan(struct list_head *chans, int delay_free_irq)
{
struct list_head *ele, *next;
struct chan *chan;
list_for_each_safe(ele, next, chans) {
chan = list_entry(ele, struct chan, list);
free_one_chan(chan, delay_free_irq);
}
}
static int one_chan_config_string(struct chan *chan, char *str, int size,
char **error_out)
{
int n = 0;
if (chan == NULL) {
CONFIG_CHUNK(str, size, n, "none", 1);
return n;
}
CONFIG_CHUNK(str, size, n, chan->ops->type, 0);
if (chan->dev == NULL) {
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
CONFIG_CHUNK(str, size, n, ":", 0);
CONFIG_CHUNK(str, size, n, chan->dev, 0);
return n;
}
static int chan_pair_config_string(struct chan *in, struct chan *out,
char *str, int size, char **error_out)
{
int n;
n = one_chan_config_string(in, str, size, error_out);
str += n;
size -= n;
if (in == out) {
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
CONFIG_CHUNK(str, size, n, ",", 1);
n = one_chan_config_string(out, str, size, error_out);
str += n;
size -= n;
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
int chan_config_string(struct list_head *chans, char *str, int size,
char **error_out)
{
struct list_head *ele;
struct chan *chan, *in = NULL, *out = NULL;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
if (!chan->primary)
continue;
if (chan->input)
in = chan;
if (chan->output)
out = chan;
}
return chan_pair_config_string(in, out, str, size, error_out);
}
struct chan_type {
char *key;
const struct chan_ops *ops;
};
static const struct chan_type chan_table[] = {
{ "fd", &fd_ops },
#ifdef CONFIG_NULL_CHAN
{ "null", &null_ops },
#else
{ "null", ¬_configged_ops },
#endif
#ifdef CONFIG_PORT_CHAN
{ "port", &port_ops },
#else
{ "port", ¬_configged_ops },
#endif
#ifdef CONFIG_PTY_CHAN
{ "pty", &pty_ops },
{ "pts", &pts_ops },
#else
{ "pty", ¬_configged_ops },
{ "pts", ¬_configged_ops },
#endif
#ifdef CONFIG_TTY_CHAN
{ "tty", &tty_ops },
#else
{ "tty", ¬_configged_ops },
#endif
#ifdef CONFIG_XTERM_CHAN
{ "xterm", &xterm_ops },
#else
{ "xterm", ¬_configged_ops },
#endif
};
static struct chan *parse_chan(struct line *line, char *str, int device,
const struct chan_opts *opts, char **error_out)
{
const struct chan_type *entry;
const struct chan_ops *ops;
struct chan *chan;
void *data;
int i;
ops = NULL;
data = NULL;
for(i = 0; i < ARRAY_SIZE(chan_table); i++) {
entry = &chan_table[i];
if (!strncmp(str, entry->key, strlen(entry->key))) {
ops = entry->ops;
str += strlen(entry->key);
break;
}
}
if (ops == NULL) {
*error_out = "No match for configured backends";
return NULL;
}
data = (*ops->init)(str, device, opts);
if (data == NULL) {
*error_out = "Configuration failed";
return NULL;
}
chan = kmalloc(sizeof(*chan), GFP_ATOMIC);
if (chan == NULL) {
*error_out = "Memory allocation failed";
return NULL;
}
*chan = ((struct chan) { .list = LIST_HEAD_INIT(chan->list),
.free_list =
LIST_HEAD_INIT(chan->free_list),
.line = line,
.primary = 1,
.input = 0,
.output = 0,
.opened = 0,
.enabled = 0,
.fd = -1,
.ops = ops,
.data = data });
return chan;
}
int parse_chan_pair(char *str, struct line *line, int device,
const struct chan_opts *opts, char **error_out)
{
struct list_head *chans = &line->chan_list;
struct chan *new, *chan;
char *in, *out;
if (!list_empty(chans)) {
chan = list_entry(chans->next, struct chan, list);
free_chan(chans, 0);
INIT_LIST_HEAD(chans);
}
out = strchr(str, ',');
if (out != NULL) {
in = str;
*out = '\0';
out++;
new = parse_chan(line, in, device, opts, error_out);
if (new == NULL)
return -1;
new->input = 1;
list_add(&new->list, chans);
new = parse_chan(line, out, device, opts, error_out);
if (new == NULL)
return -1;
list_add(&new->list, chans);
new->output = 1;
}
else {
new = parse_chan(line, str, device, opts, error_out);
if (new == NULL)
return -1;
list_add(&new->list, chans);
new->input = 1;
new->output = 1;
}
return 0;
}
void chan_interrupt(struct list_head *chans, struct delayed_work *task,
struct tty_struct *tty, int irq)
{
struct list_head *ele, *next;
struct chan *chan;
int err;
char c;
list_for_each_safe(ele, next, chans) {
chan = list_entry(ele, struct chan, list);
if (!chan->input || (chan->ops->read == NULL))
continue;
do {
if (tty && !tty_buffer_request_room(tty, 1)) {
schedule_delayed_work(task, 1);
goto out;
}
err = chan->ops->read(chan->fd, &c, chan->data);
if (err > 0)
tty_receive_char(tty, c);
} while (err > 0);
if (err == 0)
reactivate_fd(chan->fd, irq);
if (err == -EIO) {
if (chan->primary) {
if (tty != NULL)
tty_hangup(tty);
close_chan(chans, 1);
return;
}
else close_one_chan(chan, 1);
}
}
out:
if (tty)
tty_flip_buffer_push(tty);
}
| gpl-2.0 |
CyanideDevices/android_kernel_samsung_smdk4412 | arch/alpha/kernel/sys_miata.c | 4012 | 8202 | /*
* linux/arch/alpha/kernel/sys_miata.c
*
* Copyright (C) 1995 David A Rusling
* Copyright (C) 1996 Jay A Estabrook
* Copyright (C) 1998, 1999, 2000 Richard Henderson
*
* Code supporting the MIATA (EV56+PYXIS).
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/reboot.h>
#include <asm/ptrace.h>
#include <asm/system.h>
#include <asm/dma.h>
#include <asm/irq.h>
#include <asm/mmu_context.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/core_cia.h>
#include <asm/tlbflush.h>
#include "proto.h"
#include "irq_impl.h"
#include "pci_impl.h"
#include "machvec_impl.h"
static void
miata_srm_device_interrupt(unsigned long vector)
{
int irq;
irq = (vector - 0x800) >> 4;
/*
* I really hate to do this, but the MIATA SRM console ignores the
* low 8 bits in the interrupt summary register, and reports the
* vector 0x80 *lower* than I expected from the bit numbering in
* the documentation.
* This was done because the low 8 summary bits really aren't used
* for reporting any interrupts (the PCI-ISA bridge, bit 7, isn't
* used for this purpose, as PIC interrupts are delivered as the
* vectors 0x800-0x8f0).
* But I really don't want to change the fixup code for allocation
* of IRQs, nor the alpha_irq_mask maintenance stuff, both of which
* look nice and clean now.
* So, here's this grotty hack... :-(
*/
if (irq >= 16)
irq = irq + 8;
handle_irq(irq);
}
static void __init
miata_init_irq(void)
{
if (alpha_using_srm)
alpha_mv.device_interrupt = miata_srm_device_interrupt;
#if 0
/* These break on MiataGL so we'll try not to do it at all. */
*(vulp)PYXIS_INT_HILO = 0x000000B2UL; mb(); /* ISA/NMI HI */
*(vulp)PYXIS_RT_COUNT = 0UL; mb(); /* clear count */
#endif
init_i8259a_irqs();
/* Not interested in the bogus interrupts (3,10), Fan Fault (0),
NMI (1), or EIDE (9).
We also disable the risers (4,5), since we don't know how to
route the interrupts behind the bridge. */
init_pyxis_irqs(0x63b0000);
common_init_isa_dma();
setup_irq(16+2, &halt_switch_irqaction); /* SRM only? */
setup_irq(16+6, &timer_cascade_irqaction);
}
/*
* PCI Fixup configuration.
*
* Summary @ PYXIS_INT_REQ:
* Bit Meaning
* 0 Fan Fault
* 1 NMI
* 2 Halt/Reset switch
* 3 none
* 4 CID0 (Riser ID)
* 5 CID1 (Riser ID)
* 6 Interval timer
* 7 PCI-ISA Bridge
* 8 Ethernet
* 9 EIDE (deprecated, ISA 14/15 used)
*10 none
*11 USB
*12 Interrupt Line A from slot 4
*13 Interrupt Line B from slot 4
*14 Interrupt Line C from slot 4
*15 Interrupt Line D from slot 4
*16 Interrupt Line A from slot 5
*17 Interrupt line B from slot 5
*18 Interrupt Line C from slot 5
*19 Interrupt Line D from slot 5
*20 Interrupt Line A from slot 1
*21 Interrupt Line B from slot 1
*22 Interrupt Line C from slot 1
*23 Interrupt Line D from slot 1
*24 Interrupt Line A from slot 2
*25 Interrupt Line B from slot 2
*26 Interrupt Line C from slot 2
*27 Interrupt Line D from slot 2
*27 Interrupt Line A from slot 3
*29 Interrupt Line B from slot 3
*30 Interrupt Line C from slot 3
*31 Interrupt Line D from slot 3
*
* The device to slot mapping looks like:
*
* Slot Device
* 3 DC21142 Ethernet
* 4 EIDE CMD646
* 5 none
* 6 USB
* 7 PCI-ISA bridge
* 8 PCI-PCI Bridge (SBU Riser)
* 9 none
* 10 none
* 11 PCI on board slot 4 (SBU Riser)
* 12 PCI on board slot 5 (SBU Riser)
*
* These are behind the bridge, so I'm not sure what to do...
*
* 13 PCI on board slot 1 (SBU Riser)
* 14 PCI on board slot 2 (SBU Riser)
* 15 PCI on board slot 3 (SBU Riser)
*
*
* This two layered interrupt approach means that we allocate IRQ 16 and
* above for PCI interrupts. The IRQ relates to which bit the interrupt
* comes in on. This makes interrupt processing much easier.
*/
static int __init
miata_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
static char irq_tab[18][5] __initdata = {
/*INT INTA INTB INTC INTD */
{16+ 8, 16+ 8, 16+ 8, 16+ 8, 16+ 8}, /* IdSel 14, DC21142 */
{ -1, -1, -1, -1, -1}, /* IdSel 15, EIDE */
{ -1, -1, -1, -1, -1}, /* IdSel 16, none */
{ -1, -1, -1, -1, -1}, /* IdSel 17, none */
{ -1, -1, -1, -1, -1}, /* IdSel 18, PCI-ISA */
{ -1, -1, -1, -1, -1}, /* IdSel 19, PCI-PCI */
{ -1, -1, -1, -1, -1}, /* IdSel 20, none */
{ -1, -1, -1, -1, -1}, /* IdSel 21, none */
{16+12, 16+12, 16+13, 16+14, 16+15}, /* IdSel 22, slot 4 */
{16+16, 16+16, 16+17, 16+18, 16+19}, /* IdSel 23, slot 5 */
/* the next 7 are actually on PCI bus 1, across the bridge */
{16+11, 16+11, 16+11, 16+11, 16+11}, /* IdSel 24, QLISP/GL*/
{ -1, -1, -1, -1, -1}, /* IdSel 25, none */
{ -1, -1, -1, -1, -1}, /* IdSel 26, none */
{ -1, -1, -1, -1, -1}, /* IdSel 27, none */
{16+20, 16+20, 16+21, 16+22, 16+23}, /* IdSel 28, slot 1 */
{16+24, 16+24, 16+25, 16+26, 16+27}, /* IdSel 29, slot 2 */
{16+28, 16+28, 16+29, 16+30, 16+31}, /* IdSel 30, slot 3 */
/* This bridge is on the main bus of the later orig MIATA */
{ -1, -1, -1, -1, -1}, /* IdSel 31, PCI-PCI */
};
const long min_idsel = 3, max_idsel = 20, irqs_per_slot = 5;
/* the USB function of the 82c693 has it's interrupt connected to
the 2nd 8259 controller. So we have to check for it first. */
if((slot == 7) && (PCI_FUNC(dev->devfn) == 3)) {
u8 irq=0;
struct pci_dev *pdev = pci_get_slot(dev->bus, dev->devfn & ~7);
if(pdev == NULL || pci_read_config_byte(pdev, 0x40,&irq) != PCIBIOS_SUCCESSFUL) {
pci_dev_put(pdev);
return -1;
}
else {
pci_dev_put(pdev);
return irq;
}
}
return COMMON_TABLE_LOOKUP;
}
static u8 __init
miata_swizzle(struct pci_dev *dev, u8 *pinp)
{
int slot, pin = *pinp;
if (dev->bus->number == 0) {
slot = PCI_SLOT(dev->devfn);
}
/* Check for the built-in bridge. */
else if ((PCI_SLOT(dev->bus->self->devfn) == 8) ||
(PCI_SLOT(dev->bus->self->devfn) == 20)) {
slot = PCI_SLOT(dev->devfn) + 9;
}
else
{
/* Must be a card-based bridge. */
do {
if ((PCI_SLOT(dev->bus->self->devfn) == 8) ||
(PCI_SLOT(dev->bus->self->devfn) == 20)) {
slot = PCI_SLOT(dev->devfn) + 9;
break;
}
pin = pci_swizzle_interrupt_pin(dev, pin);
/* Move up the chain of bridges. */
dev = dev->bus->self;
/* Slot of the next bridge. */
slot = PCI_SLOT(dev->devfn);
} while (dev->bus->self);
}
*pinp = pin;
return slot;
}
static void __init
miata_init_pci(void)
{
cia_init_pci();
SMC669_Init(0); /* it might be a GL (fails harmlessly if not) */
es1888_init();
}
static void
miata_kill_arch(int mode)
{
cia_kill_arch(mode);
#ifndef ALPHA_RESTORE_SRM_SETUP
switch(mode) {
case LINUX_REBOOT_CMD_RESTART:
/* Who said DEC engineers have no sense of humor? ;-) */
if (alpha_using_srm) {
*(vuip) PYXIS_RESET = 0x0000dead;
mb();
}
break;
case LINUX_REBOOT_CMD_HALT:
break;
case LINUX_REBOOT_CMD_POWER_OFF:
break;
}
halt();
#endif
}
/*
* The System Vector
*/
struct alpha_machine_vector miata_mv __initmv = {
.vector_name = "Miata",
DO_EV5_MMU,
DO_DEFAULT_RTC,
DO_PYXIS_IO,
.machine_check = cia_machine_check,
.max_isa_dma_address = ALPHA_MAX_ISA_DMA_ADDRESS,
.min_io_address = DEFAULT_IO_BASE,
.min_mem_address = DEFAULT_MEM_BASE,
.pci_dac_offset = PYXIS_DAC_OFFSET,
.nr_irqs = 48,
.device_interrupt = pyxis_device_interrupt,
.init_arch = pyxis_init_arch,
.init_irq = miata_init_irq,
.init_rtc = common_init_rtc,
.init_pci = miata_init_pci,
.kill_arch = miata_kill_arch,
.pci_map_irq = miata_map_irq,
.pci_swizzle = miata_swizzle,
};
ALIAS_MV(miata)
| gpl-2.0 |
ChiefzReloaded/lge-kernel-startablet-new | sound/core/seq/oss/seq_oss_synth.c | 4012 | 15027 | /*
* OSS compatible sequencer driver
*
* synth device handlers
*
* Copyright (C) 1998,99 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "seq_oss_synth.h"
#include "seq_oss_midi.h"
#include "../seq_lock.h"
#include <linux/init.h>
#include <linux/slab.h>
/*
* constants
*/
#define SNDRV_SEQ_OSS_MAX_SYNTH_NAME 30
#define MAX_SYSEX_BUFLEN 128
/*
* definition of synth info records
*/
/* sysex buffer */
struct seq_oss_synth_sysex {
int len;
int skip;
unsigned char buf[MAX_SYSEX_BUFLEN];
};
/* synth info */
struct seq_oss_synth {
int seq_device;
/* for synth_info */
int synth_type;
int synth_subtype;
int nr_voices;
char name[SNDRV_SEQ_OSS_MAX_SYNTH_NAME];
struct snd_seq_oss_callback oper;
int opened;
void *private_data;
snd_use_lock_t use_lock;
};
/*
* device table
*/
static int max_synth_devs;
static struct seq_oss_synth *synth_devs[SNDRV_SEQ_OSS_MAX_SYNTH_DEVS];
static struct seq_oss_synth midi_synth_dev = {
-1, /* seq_device */
SYNTH_TYPE_MIDI, /* synth_type */
0, /* synth_subtype */
16, /* nr_voices */
"MIDI", /* name */
};
static DEFINE_SPINLOCK(register_lock);
/*
* prototypes
*/
static struct seq_oss_synth *get_synthdev(struct seq_oss_devinfo *dp, int dev);
static void reset_channels(struct seq_oss_synthinfo *info);
/*
* global initialization
*/
void __init
snd_seq_oss_synth_init(void)
{
snd_use_lock_init(&midi_synth_dev.use_lock);
}
/*
* registration of the synth device
*/
int
snd_seq_oss_synth_register(struct snd_seq_device *dev)
{
int i;
struct seq_oss_synth *rec;
struct snd_seq_oss_reg *reg = SNDRV_SEQ_DEVICE_ARGPTR(dev);
unsigned long flags;
if ((rec = kzalloc(sizeof(*rec), GFP_KERNEL)) == NULL) {
snd_printk(KERN_ERR "can't malloc synth info\n");
return -ENOMEM;
}
rec->seq_device = -1;
rec->synth_type = reg->type;
rec->synth_subtype = reg->subtype;
rec->nr_voices = reg->nvoices;
rec->oper = reg->oper;
rec->private_data = reg->private_data;
rec->opened = 0;
snd_use_lock_init(&rec->use_lock);
/* copy and truncate the name of synth device */
strlcpy(rec->name, dev->name, sizeof(rec->name));
/* registration */
spin_lock_irqsave(®ister_lock, flags);
for (i = 0; i < max_synth_devs; i++) {
if (synth_devs[i] == NULL)
break;
}
if (i >= max_synth_devs) {
if (max_synth_devs >= SNDRV_SEQ_OSS_MAX_SYNTH_DEVS) {
spin_unlock_irqrestore(®ister_lock, flags);
snd_printk(KERN_ERR "no more synth slot\n");
kfree(rec);
return -ENOMEM;
}
max_synth_devs++;
}
rec->seq_device = i;
synth_devs[i] = rec;
debug_printk(("synth %s registered %d\n", rec->name, i));
spin_unlock_irqrestore(®ister_lock, flags);
dev->driver_data = rec;
#ifdef SNDRV_OSS_INFO_DEV_SYNTH
if (i < SNDRV_CARDS)
snd_oss_info_register(SNDRV_OSS_INFO_DEV_SYNTH, i, rec->name);
#endif
return 0;
}
int
snd_seq_oss_synth_unregister(struct snd_seq_device *dev)
{
int index;
struct seq_oss_synth *rec = dev->driver_data;
unsigned long flags;
spin_lock_irqsave(®ister_lock, flags);
for (index = 0; index < max_synth_devs; index++) {
if (synth_devs[index] == rec)
break;
}
if (index >= max_synth_devs) {
spin_unlock_irqrestore(®ister_lock, flags);
snd_printk(KERN_ERR "can't unregister synth\n");
return -EINVAL;
}
synth_devs[index] = NULL;
if (index == max_synth_devs - 1) {
for (index--; index >= 0; index--) {
if (synth_devs[index])
break;
}
max_synth_devs = index + 1;
}
spin_unlock_irqrestore(®ister_lock, flags);
#ifdef SNDRV_OSS_INFO_DEV_SYNTH
if (rec->seq_device < SNDRV_CARDS)
snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_SYNTH, rec->seq_device);
#endif
snd_use_lock_sync(&rec->use_lock);
kfree(rec);
return 0;
}
/*
*/
static struct seq_oss_synth *
get_sdev(int dev)
{
struct seq_oss_synth *rec;
unsigned long flags;
spin_lock_irqsave(®ister_lock, flags);
rec = synth_devs[dev];
if (rec)
snd_use_lock_use(&rec->use_lock);
spin_unlock_irqrestore(®ister_lock, flags);
return rec;
}
/*
* set up synth tables
*/
void
snd_seq_oss_synth_setup(struct seq_oss_devinfo *dp)
{
int i;
struct seq_oss_synth *rec;
struct seq_oss_synthinfo *info;
dp->max_synthdev = max_synth_devs;
dp->synth_opened = 0;
memset(dp->synths, 0, sizeof(dp->synths));
for (i = 0; i < dp->max_synthdev; i++) {
rec = get_sdev(i);
if (rec == NULL)
continue;
if (rec->oper.open == NULL || rec->oper.close == NULL) {
snd_use_lock_free(&rec->use_lock);
continue;
}
info = &dp->synths[i];
info->arg.app_index = dp->port;
info->arg.file_mode = dp->file_mode;
info->arg.seq_mode = dp->seq_mode;
if (dp->seq_mode == SNDRV_SEQ_OSS_MODE_SYNTH)
info->arg.event_passing = SNDRV_SEQ_OSS_PROCESS_EVENTS;
else
info->arg.event_passing = SNDRV_SEQ_OSS_PASS_EVENTS;
info->opened = 0;
if (!try_module_get(rec->oper.owner)) {
snd_use_lock_free(&rec->use_lock);
continue;
}
if (rec->oper.open(&info->arg, rec->private_data) < 0) {
module_put(rec->oper.owner);
snd_use_lock_free(&rec->use_lock);
continue;
}
info->nr_voices = rec->nr_voices;
if (info->nr_voices > 0) {
info->ch = kcalloc(info->nr_voices, sizeof(struct seq_oss_chinfo), GFP_KERNEL);
if (!info->ch) {
snd_printk(KERN_ERR "Cannot malloc\n");
rec->oper.close(&info->arg);
module_put(rec->oper.owner);
snd_use_lock_free(&rec->use_lock);
continue;
}
reset_channels(info);
}
debug_printk(("synth %d assigned\n", i));
info->opened++;
rec->opened++;
dp->synth_opened++;
snd_use_lock_free(&rec->use_lock);
}
}
/*
* set up synth tables for MIDI emulation - /dev/music mode only
*/
void
snd_seq_oss_synth_setup_midi(struct seq_oss_devinfo *dp)
{
int i;
if (dp->max_synthdev >= SNDRV_SEQ_OSS_MAX_SYNTH_DEVS)
return;
for (i = 0; i < dp->max_mididev; i++) {
struct seq_oss_synthinfo *info;
info = &dp->synths[dp->max_synthdev];
if (snd_seq_oss_midi_open(dp, i, dp->file_mode) < 0)
continue;
info->arg.app_index = dp->port;
info->arg.file_mode = dp->file_mode;
info->arg.seq_mode = dp->seq_mode;
info->arg.private_data = info;
info->is_midi = 1;
info->midi_mapped = i;
info->arg.event_passing = SNDRV_SEQ_OSS_PASS_EVENTS;
snd_seq_oss_midi_get_addr(dp, i, &info->arg.addr);
info->opened = 1;
midi_synth_dev.opened++;
dp->max_synthdev++;
if (dp->max_synthdev >= SNDRV_SEQ_OSS_MAX_SYNTH_DEVS)
break;
}
}
/*
* clean up synth tables
*/
void
snd_seq_oss_synth_cleanup(struct seq_oss_devinfo *dp)
{
int i;
struct seq_oss_synth *rec;
struct seq_oss_synthinfo *info;
if (snd_BUG_ON(dp->max_synthdev >= SNDRV_SEQ_OSS_MAX_SYNTH_DEVS))
return;
for (i = 0; i < dp->max_synthdev; i++) {
info = &dp->synths[i];
if (! info->opened)
continue;
if (info->is_midi) {
if (midi_synth_dev.opened > 0) {
snd_seq_oss_midi_close(dp, info->midi_mapped);
midi_synth_dev.opened--;
}
} else {
rec = get_sdev(i);
if (rec == NULL)
continue;
if (rec->opened > 0) {
debug_printk(("synth %d closed\n", i));
rec->oper.close(&info->arg);
module_put(rec->oper.owner);
rec->opened = 0;
}
snd_use_lock_free(&rec->use_lock);
}
kfree(info->sysex);
info->sysex = NULL;
kfree(info->ch);
info->ch = NULL;
}
dp->synth_opened = 0;
dp->max_synthdev = 0;
}
/*
* check if the specified device is MIDI mapped device
*/
static int
is_midi_dev(struct seq_oss_devinfo *dp, int dev)
{
if (dev < 0 || dev >= dp->max_synthdev)
return 0;
if (dp->synths[dev].is_midi)
return 1;
return 0;
}
/*
* return synth device information pointer
*/
static struct seq_oss_synth *
get_synthdev(struct seq_oss_devinfo *dp, int dev)
{
struct seq_oss_synth *rec;
if (dev < 0 || dev >= dp->max_synthdev)
return NULL;
if (! dp->synths[dev].opened)
return NULL;
if (dp->synths[dev].is_midi)
return &midi_synth_dev;
if ((rec = get_sdev(dev)) == NULL)
return NULL;
if (! rec->opened) {
snd_use_lock_free(&rec->use_lock);
return NULL;
}
return rec;
}
/*
* reset note and velocity on each channel.
*/
static void
reset_channels(struct seq_oss_synthinfo *info)
{
int i;
if (info->ch == NULL || ! info->nr_voices)
return;
for (i = 0; i < info->nr_voices; i++) {
info->ch[i].note = -1;
info->ch[i].vel = 0;
}
}
/*
* reset synth device:
* call reset callback. if no callback is defined, send a heartbeat
* event to the corresponding port.
*/
void
snd_seq_oss_synth_reset(struct seq_oss_devinfo *dp, int dev)
{
struct seq_oss_synth *rec;
struct seq_oss_synthinfo *info;
if (snd_BUG_ON(dev < 0 || dev >= dp->max_synthdev))
return;
info = &dp->synths[dev];
if (! info->opened)
return;
if (info->sysex)
info->sysex->len = 0; /* reset sysex */
reset_channels(info);
if (info->is_midi) {
if (midi_synth_dev.opened <= 0)
return;
snd_seq_oss_midi_reset(dp, info->midi_mapped);
/* reopen the device */
snd_seq_oss_midi_close(dp, dev);
if (snd_seq_oss_midi_open(dp, info->midi_mapped,
dp->file_mode) < 0) {
midi_synth_dev.opened--;
info->opened = 0;
kfree(info->sysex);
info->sysex = NULL;
kfree(info->ch);
info->ch = NULL;
}
return;
}
rec = get_sdev(dev);
if (rec == NULL)
return;
if (rec->oper.reset) {
rec->oper.reset(&info->arg);
} else {
struct snd_seq_event ev;
memset(&ev, 0, sizeof(ev));
snd_seq_oss_fill_addr(dp, &ev, info->arg.addr.client,
info->arg.addr.port);
ev.type = SNDRV_SEQ_EVENT_RESET;
snd_seq_oss_dispatch(dp, &ev, 0, 0);
}
snd_use_lock_free(&rec->use_lock);
}
/*
* load a patch record:
* call load_patch callback function
*/
int
snd_seq_oss_synth_load_patch(struct seq_oss_devinfo *dp, int dev, int fmt,
const char __user *buf, int p, int c)
{
struct seq_oss_synth *rec;
int rc;
if (dev < 0 || dev >= dp->max_synthdev)
return -ENXIO;
if (is_midi_dev(dp, dev))
return 0;
if ((rec = get_synthdev(dp, dev)) == NULL)
return -ENXIO;
if (rec->oper.load_patch == NULL)
rc = -ENXIO;
else
rc = rec->oper.load_patch(&dp->synths[dev].arg, fmt, buf, p, c);
snd_use_lock_free(&rec->use_lock);
return rc;
}
/*
* check if the device is valid synth device
*/
int
snd_seq_oss_synth_is_valid(struct seq_oss_devinfo *dp, int dev)
{
struct seq_oss_synth *rec;
rec = get_synthdev(dp, dev);
if (rec) {
snd_use_lock_free(&rec->use_lock);
return 1;
}
return 0;
}
/*
* receive OSS 6 byte sysex packet:
* the full sysex message will be sent if it reaches to the end of data
* (0xff).
*/
int
snd_seq_oss_synth_sysex(struct seq_oss_devinfo *dp, int dev, unsigned char *buf, struct snd_seq_event *ev)
{
int i, send;
unsigned char *dest;
struct seq_oss_synth_sysex *sysex;
if (! snd_seq_oss_synth_is_valid(dp, dev))
return -ENXIO;
sysex = dp->synths[dev].sysex;
if (sysex == NULL) {
sysex = kzalloc(sizeof(*sysex), GFP_KERNEL);
if (sysex == NULL)
return -ENOMEM;
dp->synths[dev].sysex = sysex;
}
send = 0;
dest = sysex->buf + sysex->len;
/* copy 6 byte packet to the buffer */
for (i = 0; i < 6; i++) {
if (buf[i] == 0xff) {
send = 1;
break;
}
dest[i] = buf[i];
sysex->len++;
if (sysex->len >= MAX_SYSEX_BUFLEN) {
sysex->len = 0;
sysex->skip = 1;
break;
}
}
if (sysex->len && send) {
if (sysex->skip) {
sysex->skip = 0;
sysex->len = 0;
return -EINVAL; /* skip */
}
/* copy the data to event record and send it */
ev->flags = SNDRV_SEQ_EVENT_LENGTH_VARIABLE;
if (snd_seq_oss_synth_addr(dp, dev, ev))
return -EINVAL;
ev->data.ext.len = sysex->len;
ev->data.ext.ptr = sysex->buf;
sysex->len = 0;
return 0;
}
return -EINVAL; /* skip */
}
/*
* fill the event source/destination addresses
*/
int
snd_seq_oss_synth_addr(struct seq_oss_devinfo *dp, int dev, struct snd_seq_event *ev)
{
if (! snd_seq_oss_synth_is_valid(dp, dev))
return -EINVAL;
snd_seq_oss_fill_addr(dp, ev, dp->synths[dev].arg.addr.client,
dp->synths[dev].arg.addr.port);
return 0;
}
/*
* OSS compatible ioctl
*/
int
snd_seq_oss_synth_ioctl(struct seq_oss_devinfo *dp, int dev, unsigned int cmd, unsigned long addr)
{
struct seq_oss_synth *rec;
int rc;
if (is_midi_dev(dp, dev))
return -ENXIO;
if ((rec = get_synthdev(dp, dev)) == NULL)
return -ENXIO;
if (rec->oper.ioctl == NULL)
rc = -ENXIO;
else
rc = rec->oper.ioctl(&dp->synths[dev].arg, cmd, addr);
snd_use_lock_free(&rec->use_lock);
return rc;
}
/*
* send OSS raw events - SEQ_PRIVATE and SEQ_VOLUME
*/
int
snd_seq_oss_synth_raw_event(struct seq_oss_devinfo *dp, int dev, unsigned char *data, struct snd_seq_event *ev)
{
if (! snd_seq_oss_synth_is_valid(dp, dev) || is_midi_dev(dp, dev))
return -ENXIO;
ev->type = SNDRV_SEQ_EVENT_OSS;
memcpy(ev->data.raw8.d, data, 8);
return snd_seq_oss_synth_addr(dp, dev, ev);
}
/*
* create OSS compatible synth_info record
*/
int
snd_seq_oss_synth_make_info(struct seq_oss_devinfo *dp, int dev, struct synth_info *inf)
{
struct seq_oss_synth *rec;
if (dev < 0 || dev >= dp->max_synthdev)
return -ENXIO;
if (dp->synths[dev].is_midi) {
struct midi_info minf;
snd_seq_oss_midi_make_info(dp, dp->synths[dev].midi_mapped, &minf);
inf->synth_type = SYNTH_TYPE_MIDI;
inf->synth_subtype = 0;
inf->nr_voices = 16;
inf->device = dev;
strlcpy(inf->name, minf.name, sizeof(inf->name));
} else {
if ((rec = get_synthdev(dp, dev)) == NULL)
return -ENXIO;
inf->synth_type = rec->synth_type;
inf->synth_subtype = rec->synth_subtype;
inf->nr_voices = rec->nr_voices;
inf->device = dev;
strlcpy(inf->name, rec->name, sizeof(inf->name));
snd_use_lock_free(&rec->use_lock);
}
return 0;
}
#ifdef CONFIG_PROC_FS
/*
* proc interface
*/
void
snd_seq_oss_synth_info_read(struct snd_info_buffer *buf)
{
int i;
struct seq_oss_synth *rec;
snd_iprintf(buf, "\nNumber of synth devices: %d\n", max_synth_devs);
for (i = 0; i < max_synth_devs; i++) {
snd_iprintf(buf, "\nsynth %d: ", i);
rec = get_sdev(i);
if (rec == NULL) {
snd_iprintf(buf, "*empty*\n");
continue;
}
snd_iprintf(buf, "[%s]\n", rec->name);
snd_iprintf(buf, " type 0x%x : subtype 0x%x : voices %d\n",
rec->synth_type, rec->synth_subtype,
rec->nr_voices);
snd_iprintf(buf, " capabilities : ioctl %s / load_patch %s\n",
enabled_str((long)rec->oper.ioctl),
enabled_str((long)rec->oper.load_patch));
snd_use_lock_free(&rec->use_lock);
}
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
Fox-Mc-Cloud/android_kernel_samsung_smdk4412 | drivers/usb/serial/symbolserial.c | 4012 | 8249 | /*
* Symbol USB barcode to serial driver
*
* Copyright (C) 2009 Greg Kroah-Hartman <gregkh@suse.de>
* Copyright (C) 2009 Novell 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/tty.h>
#include <linux/slab.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/uaccess.h>
static int debug;
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(0x05e0, 0x0600) },
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
/* This structure holds all of the individual device information */
struct symbol_private {
struct usb_device *udev;
struct usb_serial *serial;
struct usb_serial_port *port;
unsigned char *int_buffer;
struct urb *int_urb;
int buffer_size;
u8 bInterval;
u8 int_address;
spinlock_t lock; /* protects the following flags */
bool throttled;
bool actually_throttled;
bool rts;
};
static void symbol_int_callback(struct urb *urb)
{
struct symbol_private *priv = urb->context;
unsigned char *data = urb->transfer_buffer;
struct usb_serial_port *port = priv->port;
int status = urb->status;
struct tty_struct *tty;
int result;
int data_length;
dbg("%s - port %d", __func__, port->number);
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dbg("%s - nonzero urb status received: %d",
__func__, status);
goto exit;
}
usb_serial_debug_data(debug, &port->dev, __func__, urb->actual_length,
data);
if (urb->actual_length > 1) {
data_length = urb->actual_length - 1;
/*
* Data from the device comes with a 1 byte header:
*
* <size of data>data...
* This is real data to be sent to the tty layer
* we pretty much just ignore the size and send everything
* else to the tty layer.
*/
tty = tty_port_tty_get(&port->port);
if (tty) {
tty_insert_flip_string(tty, &data[1], data_length);
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
} else {
dev_dbg(&priv->udev->dev,
"Improper amount of data received from the device, "
"%d bytes", urb->actual_length);
}
exit:
spin_lock(&priv->lock);
/* Continue trying to always read if we should */
if (!priv->throttled) {
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev,
priv->int_address),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
result = usb_submit_urb(priv->int_urb, GFP_ATOMIC);
if (result)
dev_err(&port->dev,
"%s - failed resubmitting read urb, error %d\n",
__func__, result);
} else
priv->actually_throttled = true;
spin_unlock(&priv->lock);
}
static int symbol_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct symbol_private *priv = usb_get_serial_data(port->serial);
unsigned long flags;
int result = 0;
dbg("%s - port %d", __func__, port->number);
spin_lock_irqsave(&priv->lock, flags);
priv->throttled = false;
priv->actually_throttled = false;
priv->port = port;
spin_unlock_irqrestore(&priv->lock, flags);
/* Start reading from the device */
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev, priv->int_address),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
result = usb_submit_urb(priv->int_urb, GFP_KERNEL);
if (result)
dev_err(&port->dev,
"%s - failed resubmitting read urb, error %d\n",
__func__, result);
return result;
}
static void symbol_close(struct usb_serial_port *port)
{
struct symbol_private *priv = usb_get_serial_data(port->serial);
dbg("%s - port %d", __func__, port->number);
/* shutdown our urbs */
usb_kill_urb(priv->int_urb);
}
static void symbol_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct symbol_private *priv = usb_get_serial_data(port->serial);
dbg("%s - port %d", __func__, port->number);
spin_lock_irq(&priv->lock);
priv->throttled = true;
spin_unlock_irq(&priv->lock);
}
static void symbol_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct symbol_private *priv = usb_get_serial_data(port->serial);
int result;
bool was_throttled;
dbg("%s - port %d", __func__, port->number);
spin_lock_irq(&priv->lock);
priv->throttled = false;
was_throttled = priv->actually_throttled;
priv->actually_throttled = false;
spin_unlock_irq(&priv->lock);
priv->int_urb->dev = port->serial->dev;
if (was_throttled) {
result = usb_submit_urb(priv->int_urb, GFP_KERNEL);
if (result)
dev_err(&port->dev,
"%s - failed submitting read urb, error %d\n",
__func__, result);
}
}
static int symbol_startup(struct usb_serial *serial)
{
struct symbol_private *priv;
struct usb_host_interface *intf;
int i;
int retval = -ENOMEM;
bool int_in_found = false;
/* create our private serial structure */
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
dev_err(&serial->dev->dev, "%s - Out of memory\n", __func__);
return -ENOMEM;
}
spin_lock_init(&priv->lock);
priv->serial = serial;
priv->port = serial->port[0];
priv->udev = serial->dev;
/* find our interrupt endpoint */
intf = serial->interface->altsetting;
for (i = 0; i < intf->desc.bNumEndpoints; ++i) {
struct usb_endpoint_descriptor *endpoint;
endpoint = &intf->endpoint[i].desc;
if (!usb_endpoint_is_int_in(endpoint))
continue;
priv->int_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!priv->int_urb) {
dev_err(&priv->udev->dev, "out of memory\n");
goto error;
}
priv->buffer_size = le16_to_cpu(endpoint->wMaxPacketSize) * 2;
priv->int_buffer = kmalloc(priv->buffer_size, GFP_KERNEL);
if (!priv->int_buffer) {
dev_err(&priv->udev->dev, "out of memory\n");
goto error;
}
priv->int_address = endpoint->bEndpointAddress;
priv->bInterval = endpoint->bInterval;
/* set up our int urb */
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev,
endpoint->bEndpointAddress),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
int_in_found = true;
break;
}
if (!int_in_found) {
dev_err(&priv->udev->dev,
"Error - the proper endpoints were not found!\n");
goto error;
}
usb_set_serial_data(serial, priv);
return 0;
error:
usb_free_urb(priv->int_urb);
kfree(priv->int_buffer);
kfree(priv);
return retval;
}
static void symbol_disconnect(struct usb_serial *serial)
{
struct symbol_private *priv = usb_get_serial_data(serial);
dbg("%s", __func__);
usb_kill_urb(priv->int_urb);
usb_free_urb(priv->int_urb);
}
static void symbol_release(struct usb_serial *serial)
{
struct symbol_private *priv = usb_get_serial_data(serial);
dbg("%s", __func__);
kfree(priv->int_buffer);
kfree(priv);
}
static struct usb_driver symbol_driver = {
.name = "symbol",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
.no_dynamic_id = 1,
};
static struct usb_serial_driver symbol_device = {
.driver = {
.owner = THIS_MODULE,
.name = "symbol",
},
.id_table = id_table,
.usb_driver = &symbol_driver,
.num_ports = 1,
.attach = symbol_startup,
.open = symbol_open,
.close = symbol_close,
.disconnect = symbol_disconnect,
.release = symbol_release,
.throttle = symbol_throttle,
.unthrottle = symbol_unthrottle,
};
static int __init symbol_init(void)
{
int retval;
retval = usb_serial_register(&symbol_device);
if (retval)
return retval;
retval = usb_register(&symbol_driver);
if (retval)
usb_serial_deregister(&symbol_device);
return retval;
}
static void __exit symbol_exit(void)
{
usb_deregister(&symbol_driver);
usb_serial_deregister(&symbol_device);
}
module_init(symbol_init);
module_exit(symbol_exit);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
craigacgomez/android_kernel_samsung_manta | arch/mips/cavium-octeon/executive/cvmx-spi.c | 4780 | 22409 | /***********************license start***************
* Author: Cavium Networks
*
* Contact: support@caviumnetworks.com
* This file is part of the OCTEON SDK
*
* Copyright (c) 2003-2008 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
***********************license end**************************************/
/*
*
* Support library for the SPI
*/
#include <asm/octeon/octeon.h>
#include <asm/octeon/cvmx-config.h>
#include <asm/octeon/cvmx-pko.h>
#include <asm/octeon/cvmx-spi.h>
#include <asm/octeon/cvmx-spxx-defs.h>
#include <asm/octeon/cvmx-stxx-defs.h>
#include <asm/octeon/cvmx-srxx-defs.h>
#define INVOKE_CB(function_p, args...) \
do { \
if (function_p) { \
res = function_p(args); \
if (res) \
return res; \
} \
} while (0)
#if CVMX_ENABLE_DEBUG_PRINTS
static const char *modes[] =
{ "UNKNOWN", "TX Halfplex", "Rx Halfplex", "Duplex" };
#endif
/* Default callbacks, can be overridden
* using cvmx_spi_get_callbacks/cvmx_spi_set_callbacks
*/
static cvmx_spi_callbacks_t cvmx_spi_callbacks = {
.reset_cb = cvmx_spi_reset_cb,
.calendar_setup_cb = cvmx_spi_calendar_setup_cb,
.clock_detect_cb = cvmx_spi_clock_detect_cb,
.training_cb = cvmx_spi_training_cb,
.calendar_sync_cb = cvmx_spi_calendar_sync_cb,
.interface_up_cb = cvmx_spi_interface_up_cb
};
/**
* Get current SPI4 initialization callbacks
*
* @callbacks: Pointer to the callbacks structure.to fill
*
* Returns Pointer to cvmx_spi_callbacks_t structure.
*/
void cvmx_spi_get_callbacks(cvmx_spi_callbacks_t *callbacks)
{
memcpy(callbacks, &cvmx_spi_callbacks, sizeof(cvmx_spi_callbacks));
}
/**
* Set new SPI4 initialization callbacks
*
* @new_callbacks: Pointer to an updated callbacks structure.
*/
void cvmx_spi_set_callbacks(cvmx_spi_callbacks_t *new_callbacks)
{
memcpy(&cvmx_spi_callbacks, new_callbacks, sizeof(cvmx_spi_callbacks));
}
/**
* Initialize and start the SPI interface.
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @timeout: Timeout to wait for clock synchronization in seconds
* @num_ports: Number of SPI ports to configure
*
* Returns Zero on success, negative of failure.
*/
int cvmx_spi_start_interface(int interface, cvmx_spi_mode_t mode, int timeout,
int num_ports)
{
int res = -1;
if (!(OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)))
return res;
/* Callback to perform SPI4 reset */
INVOKE_CB(cvmx_spi_callbacks.reset_cb, interface, mode);
/* Callback to perform calendar setup */
INVOKE_CB(cvmx_spi_callbacks.calendar_setup_cb, interface, mode,
num_ports);
/* Callback to perform clock detection */
INVOKE_CB(cvmx_spi_callbacks.clock_detect_cb, interface, mode, timeout);
/* Callback to perform SPI4 link training */
INVOKE_CB(cvmx_spi_callbacks.training_cb, interface, mode, timeout);
/* Callback to perform calendar sync */
INVOKE_CB(cvmx_spi_callbacks.calendar_sync_cb, interface, mode,
timeout);
/* Callback to handle interface coming up */
INVOKE_CB(cvmx_spi_callbacks.interface_up_cb, interface, mode);
return res;
}
/**
* This routine restarts the SPI interface after it has lost synchronization
* with its correspondent system.
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @timeout: Timeout to wait for clock synchronization in seconds
*
* Returns Zero on success, negative of failure.
*/
int cvmx_spi_restart_interface(int interface, cvmx_spi_mode_t mode, int timeout)
{
int res = -1;
if (!(OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)))
return res;
cvmx_dprintf("SPI%d: Restart %s\n", interface, modes[mode]);
/* Callback to perform SPI4 reset */
INVOKE_CB(cvmx_spi_callbacks.reset_cb, interface, mode);
/* NOTE: Calendar setup is not performed during restart */
/* Refer to cvmx_spi_start_interface() for the full sequence */
/* Callback to perform clock detection */
INVOKE_CB(cvmx_spi_callbacks.clock_detect_cb, interface, mode, timeout);
/* Callback to perform SPI4 link training */
INVOKE_CB(cvmx_spi_callbacks.training_cb, interface, mode, timeout);
/* Callback to perform calendar sync */
INVOKE_CB(cvmx_spi_callbacks.calendar_sync_cb, interface, mode,
timeout);
/* Callback to handle interface coming up */
INVOKE_CB(cvmx_spi_callbacks.interface_up_cb, interface, mode);
return res;
}
/**
* Callback to perform SPI4 reset
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_reset_cb(int interface, cvmx_spi_mode_t mode)
{
union cvmx_spxx_dbg_deskew_ctl spxx_dbg_deskew_ctl;
union cvmx_spxx_clk_ctl spxx_clk_ctl;
union cvmx_spxx_bist_stat spxx_bist_stat;
union cvmx_spxx_int_msk spxx_int_msk;
union cvmx_stxx_int_msk stxx_int_msk;
union cvmx_spxx_trn4_ctl spxx_trn4_ctl;
int index;
uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
/* Disable SPI error events while we run BIST */
spxx_int_msk.u64 = cvmx_read_csr(CVMX_SPXX_INT_MSK(interface));
cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), 0);
stxx_int_msk.u64 = cvmx_read_csr(CVMX_STXX_INT_MSK(interface));
cvmx_write_csr(CVMX_STXX_INT_MSK(interface), 0);
/* Run BIST in the SPI interface */
cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), 0);
cvmx_write_csr(CVMX_STXX_COM_CTL(interface), 0);
spxx_clk_ctl.u64 = 0;
spxx_clk_ctl.s.runbist = 1;
cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
cvmx_wait(10 * MS);
spxx_bist_stat.u64 = cvmx_read_csr(CVMX_SPXX_BIST_STAT(interface));
if (spxx_bist_stat.s.stat0)
cvmx_dprintf
("ERROR SPI%d: BIST failed on receive datapath FIFO\n",
interface);
if (spxx_bist_stat.s.stat1)
cvmx_dprintf("ERROR SPI%d: BIST failed on RX calendar table\n",
interface);
if (spxx_bist_stat.s.stat2)
cvmx_dprintf("ERROR SPI%d: BIST failed on TX calendar table\n",
interface);
/* Clear the calendar table after BIST to fix parity errors */
for (index = 0; index < 32; index++) {
union cvmx_srxx_spi4_calx srxx_spi4_calx;
union cvmx_stxx_spi4_calx stxx_spi4_calx;
srxx_spi4_calx.u64 = 0;
srxx_spi4_calx.s.oddpar = 1;
cvmx_write_csr(CVMX_SRXX_SPI4_CALX(index, interface),
srxx_spi4_calx.u64);
stxx_spi4_calx.u64 = 0;
stxx_spi4_calx.s.oddpar = 1;
cvmx_write_csr(CVMX_STXX_SPI4_CALX(index, interface),
stxx_spi4_calx.u64);
}
/* Re enable reporting of error interrupts */
cvmx_write_csr(CVMX_SPXX_INT_REG(interface),
cvmx_read_csr(CVMX_SPXX_INT_REG(interface)));
cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), spxx_int_msk.u64);
cvmx_write_csr(CVMX_STXX_INT_REG(interface),
cvmx_read_csr(CVMX_STXX_INT_REG(interface)));
cvmx_write_csr(CVMX_STXX_INT_MSK(interface), stxx_int_msk.u64);
/* Setup the CLKDLY right in the middle */
spxx_clk_ctl.u64 = 0;
spxx_clk_ctl.s.seetrn = 0;
spxx_clk_ctl.s.clkdly = 0x10;
spxx_clk_ctl.s.runbist = 0;
spxx_clk_ctl.s.statdrv = 0;
/* This should always be on the opposite edge as statdrv */
spxx_clk_ctl.s.statrcv = 1;
spxx_clk_ctl.s.sndtrn = 0;
spxx_clk_ctl.s.drptrn = 0;
spxx_clk_ctl.s.rcvtrn = 0;
spxx_clk_ctl.s.srxdlck = 0;
cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
cvmx_wait(100 * MS);
/* Reset SRX0 DLL */
spxx_clk_ctl.s.srxdlck = 1;
cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
/* Waiting for Inf0 Spi4 RX DLL to lock */
cvmx_wait(100 * MS);
/* Enable dynamic alignment */
spxx_trn4_ctl.s.trntest = 0;
spxx_trn4_ctl.s.jitter = 1;
spxx_trn4_ctl.s.clr_boot = 1;
spxx_trn4_ctl.s.set_boot = 0;
if (OCTEON_IS_MODEL(OCTEON_CN58XX))
spxx_trn4_ctl.s.maxdist = 3;
else
spxx_trn4_ctl.s.maxdist = 8;
spxx_trn4_ctl.s.macro_en = 1;
spxx_trn4_ctl.s.mux_en = 1;
cvmx_write_csr(CVMX_SPXX_TRN4_CTL(interface), spxx_trn4_ctl.u64);
spxx_dbg_deskew_ctl.u64 = 0;
cvmx_write_csr(CVMX_SPXX_DBG_DESKEW_CTL(interface),
spxx_dbg_deskew_ctl.u64);
return 0;
}
/**
* Callback to setup calendar and miscellaneous settings before clock detection
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @num_ports: Number of ports to configure on SPI
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_calendar_setup_cb(int interface, cvmx_spi_mode_t mode,
int num_ports)
{
int port;
int index;
if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
union cvmx_srxx_com_ctl srxx_com_ctl;
union cvmx_srxx_spi4_stat srxx_spi4_stat;
/* SRX0 number of Ports */
srxx_com_ctl.u64 = 0;
srxx_com_ctl.s.prts = num_ports - 1;
srxx_com_ctl.s.st_en = 0;
srxx_com_ctl.s.inf_en = 0;
cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
/* SRX0 Calendar Table. This round robbins through all ports */
port = 0;
index = 0;
while (port < num_ports) {
union cvmx_srxx_spi4_calx srxx_spi4_calx;
srxx_spi4_calx.u64 = 0;
srxx_spi4_calx.s.prt0 = port++;
srxx_spi4_calx.s.prt1 = port++;
srxx_spi4_calx.s.prt2 = port++;
srxx_spi4_calx.s.prt3 = port++;
srxx_spi4_calx.s.oddpar =
~(cvmx_dpop(srxx_spi4_calx.u64) & 1);
cvmx_write_csr(CVMX_SRXX_SPI4_CALX(index, interface),
srxx_spi4_calx.u64);
index++;
}
srxx_spi4_stat.u64 = 0;
srxx_spi4_stat.s.len = num_ports;
srxx_spi4_stat.s.m = 1;
cvmx_write_csr(CVMX_SRXX_SPI4_STAT(interface),
srxx_spi4_stat.u64);
}
if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
union cvmx_stxx_arb_ctl stxx_arb_ctl;
union cvmx_gmxx_tx_spi_max gmxx_tx_spi_max;
union cvmx_gmxx_tx_spi_thresh gmxx_tx_spi_thresh;
union cvmx_gmxx_tx_spi_ctl gmxx_tx_spi_ctl;
union cvmx_stxx_spi4_stat stxx_spi4_stat;
union cvmx_stxx_spi4_dat stxx_spi4_dat;
/* STX0 Config */
stxx_arb_ctl.u64 = 0;
stxx_arb_ctl.s.igntpa = 0;
stxx_arb_ctl.s.mintrn = 0;
cvmx_write_csr(CVMX_STXX_ARB_CTL(interface), stxx_arb_ctl.u64);
gmxx_tx_spi_max.u64 = 0;
gmxx_tx_spi_max.s.max1 = 8;
gmxx_tx_spi_max.s.max2 = 4;
gmxx_tx_spi_max.s.slice = 0;
cvmx_write_csr(CVMX_GMXX_TX_SPI_MAX(interface),
gmxx_tx_spi_max.u64);
gmxx_tx_spi_thresh.u64 = 0;
gmxx_tx_spi_thresh.s.thresh = 4;
cvmx_write_csr(CVMX_GMXX_TX_SPI_THRESH(interface),
gmxx_tx_spi_thresh.u64);
gmxx_tx_spi_ctl.u64 = 0;
gmxx_tx_spi_ctl.s.tpa_clr = 0;
gmxx_tx_spi_ctl.s.cont_pkt = 0;
cvmx_write_csr(CVMX_GMXX_TX_SPI_CTL(interface),
gmxx_tx_spi_ctl.u64);
/* STX0 Training Control */
stxx_spi4_dat.u64 = 0;
/*Minimum needed by dynamic alignment */
stxx_spi4_dat.s.alpha = 32;
stxx_spi4_dat.s.max_t = 0xFFFF; /*Minimum interval is 0x20 */
cvmx_write_csr(CVMX_STXX_SPI4_DAT(interface),
stxx_spi4_dat.u64);
/* STX0 Calendar Table. This round robbins through all ports */
port = 0;
index = 0;
while (port < num_ports) {
union cvmx_stxx_spi4_calx stxx_spi4_calx;
stxx_spi4_calx.u64 = 0;
stxx_spi4_calx.s.prt0 = port++;
stxx_spi4_calx.s.prt1 = port++;
stxx_spi4_calx.s.prt2 = port++;
stxx_spi4_calx.s.prt3 = port++;
stxx_spi4_calx.s.oddpar =
~(cvmx_dpop(stxx_spi4_calx.u64) & 1);
cvmx_write_csr(CVMX_STXX_SPI4_CALX(index, interface),
stxx_spi4_calx.u64);
index++;
}
stxx_spi4_stat.u64 = 0;
stxx_spi4_stat.s.len = num_ports;
stxx_spi4_stat.s.m = 1;
cvmx_write_csr(CVMX_STXX_SPI4_STAT(interface),
stxx_spi4_stat.u64);
}
return 0;
}
/**
* Callback to perform clock detection
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @timeout: Timeout to wait for clock synchronization in seconds
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_clock_detect_cb(int interface, cvmx_spi_mode_t mode, int timeout)
{
int clock_transitions;
union cvmx_spxx_clk_stat stat;
uint64_t timeout_time;
uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
/*
* Regardless of operating mode, both Tx and Rx clocks must be
* present for the SPI interface to operate.
*/
cvmx_dprintf("SPI%d: Waiting to see TsClk...\n", interface);
timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
/*
* Require 100 clock transitions in order to avoid any noise
* in the beginning.
*/
clock_transitions = 100;
do {
stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
if (stat.s.s4clk0 && stat.s.s4clk1 && clock_transitions) {
/*
* We've seen a clock transition, so decrement
* the number we still need.
*/
clock_transitions--;
cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
stat.s.s4clk0 = 0;
stat.s.s4clk1 = 0;
}
if (cvmx_get_cycle() > timeout_time) {
cvmx_dprintf("SPI%d: Timeout\n", interface);
return -1;
}
} while (stat.s.s4clk0 == 0 || stat.s.s4clk1 == 0);
cvmx_dprintf("SPI%d: Waiting to see RsClk...\n", interface);
timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
/*
* Require 100 clock transitions in order to avoid any noise in the
* beginning.
*/
clock_transitions = 100;
do {
stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
if (stat.s.d4clk0 && stat.s.d4clk1 && clock_transitions) {
/*
* We've seen a clock transition, so decrement
* the number we still need
*/
clock_transitions--;
cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
stat.s.d4clk0 = 0;
stat.s.d4clk1 = 0;
}
if (cvmx_get_cycle() > timeout_time) {
cvmx_dprintf("SPI%d: Timeout\n", interface);
return -1;
}
} while (stat.s.d4clk0 == 0 || stat.s.d4clk1 == 0);
return 0;
}
/**
* Callback to perform link training
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @timeout: Timeout to wait for link to be trained (in seconds)
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_training_cb(int interface, cvmx_spi_mode_t mode, int timeout)
{
union cvmx_spxx_trn4_ctl spxx_trn4_ctl;
union cvmx_spxx_clk_stat stat;
uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
uint64_t timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
int rx_training_needed;
/* SRX0 & STX0 Inf0 Links are configured - begin training */
union cvmx_spxx_clk_ctl spxx_clk_ctl;
spxx_clk_ctl.u64 = 0;
spxx_clk_ctl.s.seetrn = 0;
spxx_clk_ctl.s.clkdly = 0x10;
spxx_clk_ctl.s.runbist = 0;
spxx_clk_ctl.s.statdrv = 0;
/* This should always be on the opposite edge as statdrv */
spxx_clk_ctl.s.statrcv = 1;
spxx_clk_ctl.s.sndtrn = 1;
spxx_clk_ctl.s.drptrn = 1;
spxx_clk_ctl.s.rcvtrn = 1;
spxx_clk_ctl.s.srxdlck = 1;
cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
cvmx_wait(1000 * MS);
/* SRX0 clear the boot bit */
spxx_trn4_ctl.u64 = cvmx_read_csr(CVMX_SPXX_TRN4_CTL(interface));
spxx_trn4_ctl.s.clr_boot = 1;
cvmx_write_csr(CVMX_SPXX_TRN4_CTL(interface), spxx_trn4_ctl.u64);
/* Wait for the training sequence to complete */
cvmx_dprintf("SPI%d: Waiting for training\n", interface);
cvmx_wait(1000 * MS);
/* Wait a really long time here */
timeout_time = cvmx_get_cycle() + 1000ull * MS * 600;
/*
* The HRM says we must wait for 34 + 16 * MAXDIST training sequences.
* We'll be pessimistic and wait for a lot more.
*/
rx_training_needed = 500;
do {
stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
if (stat.s.srxtrn && rx_training_needed) {
rx_training_needed--;
cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
stat.s.srxtrn = 0;
}
if (cvmx_get_cycle() > timeout_time) {
cvmx_dprintf("SPI%d: Timeout\n", interface);
return -1;
}
} while (stat.s.srxtrn == 0);
return 0;
}
/**
* Callback to perform calendar data synchronization
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
* @timeout: Timeout to wait for calendar data in seconds
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_calendar_sync_cb(int interface, cvmx_spi_mode_t mode, int timeout)
{
uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
/* SRX0 interface should be good, send calendar data */
union cvmx_srxx_com_ctl srxx_com_ctl;
cvmx_dprintf
("SPI%d: Rx is synchronized, start sending calendar data\n",
interface);
srxx_com_ctl.u64 = cvmx_read_csr(CVMX_SRXX_COM_CTL(interface));
srxx_com_ctl.s.inf_en = 1;
srxx_com_ctl.s.st_en = 1;
cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
}
if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
/* STX0 has achieved sync */
/* The corespondant board should be sending calendar data */
/* Enable the STX0 STAT receiver. */
union cvmx_spxx_clk_stat stat;
uint64_t timeout_time;
union cvmx_stxx_com_ctl stxx_com_ctl;
stxx_com_ctl.u64 = 0;
stxx_com_ctl.s.st_en = 1;
cvmx_write_csr(CVMX_STXX_COM_CTL(interface), stxx_com_ctl.u64);
/* Waiting for calendar sync on STX0 STAT */
cvmx_dprintf("SPI%d: Waiting to sync on STX[%d] STAT\n",
interface, interface);
timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
/* SPX0_CLK_STAT - SPX0_CLK_STAT[STXCAL] should be 1 (bit10) */
do {
stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
if (cvmx_get_cycle() > timeout_time) {
cvmx_dprintf("SPI%d: Timeout\n", interface);
return -1;
}
} while (stat.s.stxcal == 0);
}
return 0;
}
/**
* Callback to handle interface up
*
* @interface: The identifier of the packet interface to configure and
* use as a SPI interface.
* @mode: The operating mode for the SPI interface. The interface
* can operate as a full duplex (both Tx and Rx data paths
* active) or as a halfplex (either the Tx data path is
* active or the Rx data path is active, but not both).
*
* Returns Zero on success, non-zero error code on failure (will cause
* SPI initialization to abort)
*/
int cvmx_spi_interface_up_cb(int interface, cvmx_spi_mode_t mode)
{
union cvmx_gmxx_rxx_frm_min gmxx_rxx_frm_min;
union cvmx_gmxx_rxx_frm_max gmxx_rxx_frm_max;
union cvmx_gmxx_rxx_jabber gmxx_rxx_jabber;
if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
union cvmx_srxx_com_ctl srxx_com_ctl;
srxx_com_ctl.u64 = cvmx_read_csr(CVMX_SRXX_COM_CTL(interface));
srxx_com_ctl.s.inf_en = 1;
cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
cvmx_dprintf("SPI%d: Rx is now up\n", interface);
}
if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
union cvmx_stxx_com_ctl stxx_com_ctl;
stxx_com_ctl.u64 = cvmx_read_csr(CVMX_STXX_COM_CTL(interface));
stxx_com_ctl.s.inf_en = 1;
cvmx_write_csr(CVMX_STXX_COM_CTL(interface), stxx_com_ctl.u64);
cvmx_dprintf("SPI%d: Tx is now up\n", interface);
}
gmxx_rxx_frm_min.u64 = 0;
gmxx_rxx_frm_min.s.len = 64;
cvmx_write_csr(CVMX_GMXX_RXX_FRM_MIN(0, interface),
gmxx_rxx_frm_min.u64);
gmxx_rxx_frm_max.u64 = 0;
gmxx_rxx_frm_max.s.len = 64 * 1024 - 4;
cvmx_write_csr(CVMX_GMXX_RXX_FRM_MAX(0, interface),
gmxx_rxx_frm_max.u64);
gmxx_rxx_jabber.u64 = 0;
gmxx_rxx_jabber.s.cnt = 64 * 1024 - 4;
cvmx_write_csr(CVMX_GMXX_RXX_JABBER(0, interface), gmxx_rxx_jabber.u64);
return 0;
}
| gpl-2.0 |
raden/melati-kernel | drivers/media/dvb/dvb-usb/au6610.c | 5036 | 5910 | /*
* DVB USB Linux driver for Alcor Micro AU6610 DVB-T USB2.0.
*
* Copyright (C) 2006 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "au6610.h"
#include "zl10353.h"
#include "qt1010.h"
/* debug */
static int dvb_usb_au6610_debug;
module_param_named(debug, dvb_usb_au6610_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level" DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static int au6610_usb_msg(struct dvb_usb_device *d, u8 operation, u8 addr,
u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen)
{
int ret;
u16 index;
u8 *usb_buf;
/*
* allocate enough for all known requests,
* read returns 5 and write 6 bytes
*/
usb_buf = kmalloc(6, GFP_KERNEL);
if (!usb_buf)
return -ENOMEM;
switch (wlen) {
case 1:
index = wbuf[0] << 8;
break;
case 2:
index = wbuf[0] << 8;
index += wbuf[1];
break;
default:
warn("wlen = %x, aborting.", wlen);
ret = -EINVAL;
goto error;
}
ret = usb_control_msg(d->udev, usb_rcvctrlpipe(d->udev, 0), operation,
USB_TYPE_VENDOR|USB_DIR_IN, addr << 1, index,
usb_buf, 6, AU6610_USB_TIMEOUT);
if (ret < 0)
goto error;
switch (operation) {
case AU6610_REQ_I2C_READ:
case AU6610_REQ_USB_READ:
/* requested value is always 5th byte in buffer */
rbuf[0] = usb_buf[4];
}
error:
kfree(usb_buf);
return ret;
}
static int au6610_i2c_msg(struct dvb_usb_device *d, u8 addr,
u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen)
{
u8 request;
u8 wo = (rbuf == NULL || rlen == 0); /* write-only */
if (wo) {
request = AU6610_REQ_I2C_WRITE;
} else { /* rw */
request = AU6610_REQ_I2C_READ;
}
return au6610_usb_msg(d, request, addr, wbuf, wlen, rbuf, rlen);
}
/* I2C */
static int au6610_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i;
if (num > 2)
return -EINVAL;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
/* write/read request */
if (i+1 < num && (msg[i+1].flags & I2C_M_RD)) {
if (au6610_i2c_msg(d, msg[i].addr, msg[i].buf,
msg[i].len, msg[i+1].buf,
msg[i+1].len) < 0)
break;
i++;
} else if (au6610_i2c_msg(d, msg[i].addr, msg[i].buf,
msg[i].len, NULL, 0) < 0)
break;
}
mutex_unlock(&d->i2c_mutex);
return i;
}
static u32 au6610_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm au6610_i2c_algo = {
.master_xfer = au6610_i2c_xfer,
.functionality = au6610_i2c_func,
};
/* Callbacks for DVB USB */
static struct zl10353_config au6610_zl10353_config = {
.demod_address = 0x0f,
.no_tuner = 1,
.parallel_ts = 1,
};
static int au6610_zl10353_frontend_attach(struct dvb_usb_adapter *adap)
{
adap->fe_adap[0].fe = dvb_attach(zl10353_attach, &au6610_zl10353_config,
&adap->dev->i2c_adap);
if (adap->fe_adap[0].fe == NULL)
return -ENODEV;
return 0;
}
static struct qt1010_config au6610_qt1010_config = {
.i2c_address = 0x62
};
static int au6610_qt1010_tuner_attach(struct dvb_usb_adapter *adap)
{
return dvb_attach(qt1010_attach,
adap->fe_adap[0].fe, &adap->dev->i2c_adap,
&au6610_qt1010_config) == NULL ? -ENODEV : 0;
}
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties au6610_properties;
static int au6610_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct dvb_usb_device *d;
struct usb_host_interface *alt;
int ret;
if (intf->num_altsetting < AU6610_ALTSETTING_COUNT)
return -ENODEV;
ret = dvb_usb_device_init(intf, &au6610_properties, THIS_MODULE, &d,
adapter_nr);
if (ret == 0) {
alt = usb_altnum_to_altsetting(intf, AU6610_ALTSETTING);
if (alt == NULL) {
deb_info("%s: no alt found!\n", __func__);
return -ENODEV;
}
ret = usb_set_interface(d->udev, alt->desc.bInterfaceNumber,
alt->desc.bAlternateSetting);
}
return ret;
}
static struct usb_device_id au6610_table [] = {
{ USB_DEVICE(USB_VID_ALCOR_MICRO, USB_PID_SIGMATEK_DVB_110) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, au6610_table);
static struct dvb_usb_device_properties au6610_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = 0,
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.frontend_attach = au6610_zl10353_frontend_attach,
.tuner_attach = au6610_qt1010_tuner_attach,
.stream = {
.type = USB_ISOC,
.count = 5,
.endpoint = 0x82,
.u = {
.isoc = {
.framesperurb = 40,
.framesize = 942,
.interval = 1,
}
}
},
}},
}
},
.i2c_algo = &au6610_i2c_algo,
.num_device_descs = 1,
.devices = {
{
.name = "Sigmatek DVB-110 DVB-T USB2.0",
.cold_ids = {NULL},
.warm_ids = {&au6610_table[0], NULL},
},
}
};
static struct usb_driver au6610_driver = {
.name = "dvb_usb_au6610",
.probe = au6610_probe,
.disconnect = dvb_usb_device_exit,
.id_table = au6610_table,
};
module_usb_driver(au6610_driver);
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_DESCRIPTION("Driver for Alcor Micro AU6610 DVB-T USB2.0");
MODULE_VERSION("0.1");
MODULE_LICENSE("GPL");
| gpl-2.0 |
EPDCenter/android_kernel_rockchip_mk908 | drivers/zorro/zorro.c | 7852 | 5272 | /*
* Zorro Bus Services
*
* Copyright (C) 1995-2003 Geert Uytterhoeven
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/zorro.h>
#include <linux/bitops.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/setup.h>
#include <asm/amigahw.h>
#include "zorro.h"
/*
* Zorro Expansion Devices
*/
unsigned int zorro_num_autocon;
struct zorro_dev zorro_autocon[ZORRO_NUM_AUTO];
/*
* Zorro bus
*/
struct zorro_bus {
struct list_head devices; /* list of devices on this bus */
struct device dev;
};
/*
* Find Zorro Devices
*/
struct zorro_dev *zorro_find_device(zorro_id id, struct zorro_dev *from)
{
struct zorro_dev *z;
if (!zorro_num_autocon)
return NULL;
for (z = from ? from+1 : &zorro_autocon[0];
z < zorro_autocon+zorro_num_autocon;
z++)
if (id == ZORRO_WILDCARD || id == z->id)
return z;
return NULL;
}
EXPORT_SYMBOL(zorro_find_device);
/*
* Bitmask indicating portions of available Zorro II RAM that are unused
* by the system. Every bit represents a 64K chunk, for a maximum of 8MB
* (128 chunks, physical 0x00200000-0x009fffff).
*
* If you want to use (= allocate) portions of this RAM, you should clear
* the corresponding bits.
*
* Possible uses:
* - z2ram device
* - SCSI DMA bounce buffers
*
* FIXME: use the normal resource management
*/
DECLARE_BITMAP(zorro_unused_z2ram, 128);
EXPORT_SYMBOL(zorro_unused_z2ram);
static void __init mark_region(unsigned long start, unsigned long end,
int flag)
{
if (flag)
start += Z2RAM_CHUNKMASK;
else
end += Z2RAM_CHUNKMASK;
start &= ~Z2RAM_CHUNKMASK;
end &= ~Z2RAM_CHUNKMASK;
if (end <= Z2RAM_START || start >= Z2RAM_END)
return;
start = start < Z2RAM_START ? 0x00000000 : start-Z2RAM_START;
end = end > Z2RAM_END ? Z2RAM_SIZE : end-Z2RAM_START;
while (start < end) {
u32 chunk = start>>Z2RAM_CHUNKSHIFT;
if (flag)
set_bit(chunk, zorro_unused_z2ram);
else
clear_bit(chunk, zorro_unused_z2ram);
start += Z2RAM_CHUNKSIZE;
}
}
static struct resource __init *zorro_find_parent_resource(
struct platform_device *bridge, struct zorro_dev *z)
{
int i;
for (i = 0; i < bridge->num_resources; i++) {
struct resource *r = &bridge->resource[i];
if (zorro_resource_start(z) >= r->start &&
zorro_resource_end(z) <= r->end)
return r;
}
return &iomem_resource;
}
static int __init amiga_zorro_probe(struct platform_device *pdev)
{
struct zorro_bus *bus;
struct zorro_dev *z;
struct resource *r;
unsigned int i;
int error;
/* Initialize the Zorro bus */
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus)
return -ENOMEM;
INIT_LIST_HEAD(&bus->devices);
bus->dev.parent = &pdev->dev;
dev_set_name(&bus->dev, "zorro");
error = device_register(&bus->dev);
if (error) {
pr_err("Zorro: Error registering zorro_bus\n");
put_device(&bus->dev);
kfree(bus);
return error;
}
platform_set_drvdata(pdev, bus);
pr_info("Zorro: Probing AutoConfig expansion devices: %u device%s\n",
zorro_num_autocon, zorro_num_autocon == 1 ? "" : "s");
/* First identify all devices ... */
for (i = 0; i < zorro_num_autocon; i++) {
z = &zorro_autocon[i];
z->id = (z->rom.er_Manufacturer<<16) | (z->rom.er_Product<<8);
if (z->id == ZORRO_PROD_GVP_EPC_BASE) {
/* GVP quirk */
unsigned long magic = zorro_resource_start(z)+0x8000;
z->id |= *(u16 *)ZTWO_VADDR(magic) & GVP_PRODMASK;
}
sprintf(z->name, "Zorro device %08x", z->id);
zorro_name_device(z);
z->resource.name = z->name;
r = zorro_find_parent_resource(pdev, z);
error = request_resource(r, &z->resource);
if (error)
dev_err(&bus->dev,
"Address space collision on device %s %pR\n",
z->name, &z->resource);
dev_set_name(&z->dev, "%02x", i);
z->dev.parent = &bus->dev;
z->dev.bus = &zorro_bus_type;
}
/* ... then register them */
for (i = 0; i < zorro_num_autocon; i++) {
z = &zorro_autocon[i];
error = device_register(&z->dev);
if (error) {
dev_err(&bus->dev, "Error registering device %s\n",
z->name);
put_device(&z->dev);
continue;
}
error = zorro_create_sysfs_dev_files(z);
if (error)
dev_err(&z->dev, "Error creating sysfs files\n");
}
/* Mark all available Zorro II memory */
zorro_for_each_dev(z) {
if (z->rom.er_Type & ERTF_MEMLIST)
mark_region(zorro_resource_start(z),
zorro_resource_end(z)+1, 1);
}
/* Unmark all used Zorro II memory */
for (i = 0; i < m68k_num_memory; i++)
if (m68k_memory[i].addr < 16*1024*1024)
mark_region(m68k_memory[i].addr,
m68k_memory[i].addr+m68k_memory[i].size,
0);
return 0;
}
static struct platform_driver amiga_zorro_driver = {
.driver = {
.name = "amiga-zorro",
.owner = THIS_MODULE,
},
};
static int __init amiga_zorro_init(void)
{
return platform_driver_probe(&amiga_zorro_driver, amiga_zorro_probe);
}
module_init(amiga_zorro_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Snuzzo/ermahgerd_kernel_vigor | fs/nfs/objlayout/pnfs_osd_xdr_cli.c | 10924 | 11268 | /*
* Object-Based pNFS Layout XDR layer
*
* Copyright (C) 2007 Panasas Inc. [year of first publication]
* All rights reserved.
*
* Benny Halevy <bhalevy@panasas.com>
* Boaz Harrosh <bharrosh@panasas.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
* See the file COPYING included with this distribution for more details.
*
* 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 Panasas company 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/pnfs_osd_xdr.h>
#define NFSDBG_FACILITY NFSDBG_PNFS_LD
/*
* The following implementation is based on RFC5664
*/
/*
* struct pnfs_osd_objid {
* struct nfs4_deviceid oid_device_id;
* u64 oid_partition_id;
* u64 oid_object_id;
* }; // xdr size 32 bytes
*/
static __be32 *
_osd_xdr_decode_objid(__be32 *p, struct pnfs_osd_objid *objid)
{
p = xdr_decode_opaque_fixed(p, objid->oid_device_id.data,
sizeof(objid->oid_device_id.data));
p = xdr_decode_hyper(p, &objid->oid_partition_id);
p = xdr_decode_hyper(p, &objid->oid_object_id);
return p;
}
/*
* struct pnfs_osd_opaque_cred {
* u32 cred_len;
* void *cred;
* }; // xdr size [variable]
* The return pointers are from the xdr buffer
*/
static int
_osd_xdr_decode_opaque_cred(struct pnfs_osd_opaque_cred *opaque_cred,
struct xdr_stream *xdr)
{
__be32 *p = xdr_inline_decode(xdr, 1);
if (!p)
return -EINVAL;
opaque_cred->cred_len = be32_to_cpu(*p++);
p = xdr_inline_decode(xdr, opaque_cred->cred_len);
if (!p)
return -EINVAL;
opaque_cred->cred = p;
return 0;
}
/*
* struct pnfs_osd_object_cred {
* struct pnfs_osd_objid oc_object_id;
* u32 oc_osd_version;
* u32 oc_cap_key_sec;
* struct pnfs_osd_opaque_cred oc_cap_key
* struct pnfs_osd_opaque_cred oc_cap;
* }; // xdr size 32 + 4 + 4 + [variable] + [variable]
*/
static int
_osd_xdr_decode_object_cred(struct pnfs_osd_object_cred *comp,
struct xdr_stream *xdr)
{
__be32 *p = xdr_inline_decode(xdr, 32 + 4 + 4);
int ret;
if (!p)
return -EIO;
p = _osd_xdr_decode_objid(p, &comp->oc_object_id);
comp->oc_osd_version = be32_to_cpup(p++);
comp->oc_cap_key_sec = be32_to_cpup(p);
ret = _osd_xdr_decode_opaque_cred(&comp->oc_cap_key, xdr);
if (unlikely(ret))
return ret;
ret = _osd_xdr_decode_opaque_cred(&comp->oc_cap, xdr);
return ret;
}
/*
* struct pnfs_osd_data_map {
* u32 odm_num_comps;
* u64 odm_stripe_unit;
* u32 odm_group_width;
* u32 odm_group_depth;
* u32 odm_mirror_cnt;
* u32 odm_raid_algorithm;
* }; // xdr size 4 + 8 + 4 + 4 + 4 + 4
*/
static inline int
_osd_data_map_xdr_sz(void)
{
return 4 + 8 + 4 + 4 + 4 + 4;
}
static __be32 *
_osd_xdr_decode_data_map(__be32 *p, struct pnfs_osd_data_map *data_map)
{
data_map->odm_num_comps = be32_to_cpup(p++);
p = xdr_decode_hyper(p, &data_map->odm_stripe_unit);
data_map->odm_group_width = be32_to_cpup(p++);
data_map->odm_group_depth = be32_to_cpup(p++);
data_map->odm_mirror_cnt = be32_to_cpup(p++);
data_map->odm_raid_algorithm = be32_to_cpup(p++);
dprintk("%s: odm_num_comps=%u odm_stripe_unit=%llu odm_group_width=%u "
"odm_group_depth=%u odm_mirror_cnt=%u odm_raid_algorithm=%u\n",
__func__,
data_map->odm_num_comps,
(unsigned long long)data_map->odm_stripe_unit,
data_map->odm_group_width,
data_map->odm_group_depth,
data_map->odm_mirror_cnt,
data_map->odm_raid_algorithm);
return p;
}
int pnfs_osd_xdr_decode_layout_map(struct pnfs_osd_layout *layout,
struct pnfs_osd_xdr_decode_layout_iter *iter, struct xdr_stream *xdr)
{
__be32 *p;
memset(iter, 0, sizeof(*iter));
p = xdr_inline_decode(xdr, _osd_data_map_xdr_sz() + 4 + 4);
if (unlikely(!p))
return -EINVAL;
p = _osd_xdr_decode_data_map(p, &layout->olo_map);
layout->olo_comps_index = be32_to_cpup(p++);
layout->olo_num_comps = be32_to_cpup(p++);
dprintk("%s: olo_comps_index=%d olo_num_comps=%d\n", __func__,
layout->olo_comps_index, layout->olo_num_comps);
iter->total_comps = layout->olo_num_comps;
return 0;
}
bool pnfs_osd_xdr_decode_layout_comp(struct pnfs_osd_object_cred *comp,
struct pnfs_osd_xdr_decode_layout_iter *iter, struct xdr_stream *xdr,
int *err)
{
BUG_ON(iter->decoded_comps > iter->total_comps);
if (iter->decoded_comps == iter->total_comps)
return false;
*err = _osd_xdr_decode_object_cred(comp, xdr);
if (unlikely(*err)) {
dprintk("%s: _osd_xdr_decode_object_cred=>%d decoded_comps=%d "
"total_comps=%d\n", __func__, *err,
iter->decoded_comps, iter->total_comps);
return false; /* stop the loop */
}
dprintk("%s: dev(%llx:%llx) par=0x%llx obj=0x%llx "
"key_len=%u cap_len=%u\n",
__func__,
_DEVID_LO(&comp->oc_object_id.oid_device_id),
_DEVID_HI(&comp->oc_object_id.oid_device_id),
comp->oc_object_id.oid_partition_id,
comp->oc_object_id.oid_object_id,
comp->oc_cap_key.cred_len, comp->oc_cap.cred_len);
iter->decoded_comps++;
return true;
}
/*
* Get Device Information Decoding
*
* Note: since Device Information is currently done synchronously, all
* variable strings fields are left inside the rpc buffer and are only
* pointed to by the pnfs_osd_deviceaddr members. So the read buffer
* should not be freed while the returned information is in use.
*/
/*
*struct nfs4_string {
* unsigned int len;
* char *data;
*}; // size [variable]
* NOTE: Returned string points to inside the XDR buffer
*/
static __be32 *
__read_u8_opaque(__be32 *p, struct nfs4_string *str)
{
str->len = be32_to_cpup(p++);
str->data = (char *)p;
p += XDR_QUADLEN(str->len);
return p;
}
/*
* struct pnfs_osd_targetid {
* u32 oti_type;
* struct nfs4_string oti_scsi_device_id;
* };// size 4 + [variable]
*/
static __be32 *
__read_targetid(__be32 *p, struct pnfs_osd_targetid* targetid)
{
u32 oti_type;
oti_type = be32_to_cpup(p++);
targetid->oti_type = oti_type;
switch (oti_type) {
case OBJ_TARGET_SCSI_NAME:
case OBJ_TARGET_SCSI_DEVICE_ID:
p = __read_u8_opaque(p, &targetid->oti_scsi_device_id);
}
return p;
}
/*
* struct pnfs_osd_net_addr {
* struct nfs4_string r_netid;
* struct nfs4_string r_addr;
* };
*/
static __be32 *
__read_net_addr(__be32 *p, struct pnfs_osd_net_addr* netaddr)
{
p = __read_u8_opaque(p, &netaddr->r_netid);
p = __read_u8_opaque(p, &netaddr->r_addr);
return p;
}
/*
* struct pnfs_osd_targetaddr {
* u32 ota_available;
* struct pnfs_osd_net_addr ota_netaddr;
* };
*/
static __be32 *
__read_targetaddr(__be32 *p, struct pnfs_osd_targetaddr *targetaddr)
{
u32 ota_available;
ota_available = be32_to_cpup(p++);
targetaddr->ota_available = ota_available;
if (ota_available)
p = __read_net_addr(p, &targetaddr->ota_netaddr);
return p;
}
/*
* struct pnfs_osd_deviceaddr {
* struct pnfs_osd_targetid oda_targetid;
* struct pnfs_osd_targetaddr oda_targetaddr;
* u8 oda_lun[8];
* struct nfs4_string oda_systemid;
* struct pnfs_osd_object_cred oda_root_obj_cred;
* struct nfs4_string oda_osdname;
* };
*/
/* We need this version for the pnfs_osd_xdr_decode_deviceaddr which does
* not have an xdr_stream
*/
static __be32 *
__read_opaque_cred(__be32 *p,
struct pnfs_osd_opaque_cred *opaque_cred)
{
opaque_cred->cred_len = be32_to_cpu(*p++);
opaque_cred->cred = p;
return p + XDR_QUADLEN(opaque_cred->cred_len);
}
static __be32 *
__read_object_cred(__be32 *p, struct pnfs_osd_object_cred *comp)
{
p = _osd_xdr_decode_objid(p, &comp->oc_object_id);
comp->oc_osd_version = be32_to_cpup(p++);
comp->oc_cap_key_sec = be32_to_cpup(p++);
p = __read_opaque_cred(p, &comp->oc_cap_key);
p = __read_opaque_cred(p, &comp->oc_cap);
return p;
}
void pnfs_osd_xdr_decode_deviceaddr(
struct pnfs_osd_deviceaddr *deviceaddr, __be32 *p)
{
p = __read_targetid(p, &deviceaddr->oda_targetid);
p = __read_targetaddr(p, &deviceaddr->oda_targetaddr);
p = xdr_decode_opaque_fixed(p, deviceaddr->oda_lun,
sizeof(deviceaddr->oda_lun));
p = __read_u8_opaque(p, &deviceaddr->oda_systemid);
p = __read_object_cred(p, &deviceaddr->oda_root_obj_cred);
p = __read_u8_opaque(p, &deviceaddr->oda_osdname);
/* libosd likes this terminated in dbg. It's last, so no problems */
deviceaddr->oda_osdname.data[deviceaddr->oda_osdname.len] = 0;
}
/*
* struct pnfs_osd_layoutupdate {
* u32 dsu_valid;
* s64 dsu_delta;
* u32 olu_ioerr_flag;
* }; xdr size 4 + 8 + 4
*/
int
pnfs_osd_xdr_encode_layoutupdate(struct xdr_stream *xdr,
struct pnfs_osd_layoutupdate *lou)
{
__be32 *p = xdr_reserve_space(xdr, 4 + 8 + 4);
if (!p)
return -E2BIG;
*p++ = cpu_to_be32(lou->dsu_valid);
if (lou->dsu_valid)
p = xdr_encode_hyper(p, lou->dsu_delta);
*p++ = cpu_to_be32(lou->olu_ioerr_flag);
return 0;
}
/*
* struct pnfs_osd_objid {
* struct nfs4_deviceid oid_device_id;
* u64 oid_partition_id;
* u64 oid_object_id;
* }; // xdr size 32 bytes
*/
static inline __be32 *
pnfs_osd_xdr_encode_objid(__be32 *p, struct pnfs_osd_objid *object_id)
{
p = xdr_encode_opaque_fixed(p, &object_id->oid_device_id.data,
sizeof(object_id->oid_device_id.data));
p = xdr_encode_hyper(p, object_id->oid_partition_id);
p = xdr_encode_hyper(p, object_id->oid_object_id);
return p;
}
/*
* struct pnfs_osd_ioerr {
* struct pnfs_osd_objid oer_component;
* u64 oer_comp_offset;
* u64 oer_comp_length;
* u32 oer_iswrite;
* u32 oer_errno;
* }; // xdr size 32 + 24 bytes
*/
void pnfs_osd_xdr_encode_ioerr(__be32 *p, struct pnfs_osd_ioerr *ioerr)
{
p = pnfs_osd_xdr_encode_objid(p, &ioerr->oer_component);
p = xdr_encode_hyper(p, ioerr->oer_comp_offset);
p = xdr_encode_hyper(p, ioerr->oer_comp_length);
*p++ = cpu_to_be32(ioerr->oer_iswrite);
*p = cpu_to_be32(ioerr->oer_errno);
}
__be32 *pnfs_osd_xdr_ioerr_reserve_space(struct xdr_stream *xdr)
{
__be32 *p;
p = xdr_reserve_space(xdr, 32 + 24);
if (unlikely(!p))
dprintk("%s: out of xdr space\n", __func__);
return p;
}
| gpl-2.0 |
cmenard/android_kernel_samsung_espresso10 | arch/parisc/math-emu/dfsub.c | 12204 | 15898 | /*
* Linux/PA-RISC Project (http://www.parisc-linux.org/)
*
* Floating-point emulation code
* Copyright (C) 2001 Hewlett-Packard (Paul Bame) <bame@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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
*/
/*
* BEGIN_DESC
*
* File:
* @(#) pa/spmath/dfsub.c $Revision: 1.1 $
*
* Purpose:
* Double_subtract: subtract two double precision values.
*
* External Interfaces:
* dbl_fsub(leftptr, rightptr, dstptr, status)
*
* Internal Interfaces:
*
* Theory:
* <<please update with a overview of the operation of this file>>
*
* END_DESC
*/
#include "float.h"
#include "dbl_float.h"
/*
* Double_subtract: subtract two double precision values.
*/
int
dbl_fsub(
dbl_floating_point *leftptr,
dbl_floating_point *rightptr,
dbl_floating_point *dstptr,
unsigned int *status)
{
register unsigned int signless_upper_left, signless_upper_right, save;
register unsigned int leftp1, leftp2, rightp1, rightp2, extent;
register unsigned int resultp1 = 0, resultp2 = 0;
register int result_exponent, right_exponent, diff_exponent;
register int sign_save, jumpsize;
register boolean inexact = FALSE, underflowtrap;
/* Create local copies of the numbers */
Dbl_copyfromptr(leftptr,leftp1,leftp2);
Dbl_copyfromptr(rightptr,rightp1,rightp2);
/* A zero "save" helps discover equal operands (for later), *
* and is used in swapping operands (if needed). */
Dbl_xortointp1(leftp1,rightp1,/*to*/save);
/*
* check first operand for NaN's or infinity
*/
if ((result_exponent = Dbl_exponent(leftp1)) == DBL_INFINITY_EXPONENT)
{
if (Dbl_iszero_mantissa(leftp1,leftp2))
{
if (Dbl_isnotnan(rightp1,rightp2))
{
if (Dbl_isinfinity(rightp1,rightp2) && save==0)
{
/*
* invalid since operands are same signed infinity's
*/
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
Set_invalidflag();
Dbl_makequietnan(resultp1,resultp2);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
/*
* return infinity
*/
Dbl_copytoptr(leftp1,leftp2,dstptr);
return(NOEXCEPTION);
}
}
else
{
/*
* is NaN; signaling or quiet?
*/
if (Dbl_isone_signaling(leftp1))
{
/* trap if INVALIDTRAP enabled */
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
/* make NaN quiet */
Set_invalidflag();
Dbl_set_quiet(leftp1);
}
/*
* is second operand a signaling NaN?
*/
else if (Dbl_is_signalingnan(rightp1))
{
/* trap if INVALIDTRAP enabled */
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
/* make NaN quiet */
Set_invalidflag();
Dbl_set_quiet(rightp1);
Dbl_copytoptr(rightp1,rightp2,dstptr);
return(NOEXCEPTION);
}
/*
* return quiet NaN
*/
Dbl_copytoptr(leftp1,leftp2,dstptr);
return(NOEXCEPTION);
}
} /* End left NaN or Infinity processing */
/*
* check second operand for NaN's or infinity
*/
if (Dbl_isinfinity_exponent(rightp1))
{
if (Dbl_iszero_mantissa(rightp1,rightp2))
{
/* return infinity */
Dbl_invert_sign(rightp1);
Dbl_copytoptr(rightp1,rightp2,dstptr);
return(NOEXCEPTION);
}
/*
* is NaN; signaling or quiet?
*/
if (Dbl_isone_signaling(rightp1))
{
/* trap if INVALIDTRAP enabled */
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
/* make NaN quiet */
Set_invalidflag();
Dbl_set_quiet(rightp1);
}
/*
* return quiet NaN
*/
Dbl_copytoptr(rightp1,rightp2,dstptr);
return(NOEXCEPTION);
} /* End right NaN or Infinity processing */
/* Invariant: Must be dealing with finite numbers */
/* Compare operands by removing the sign */
Dbl_copytoint_exponentmantissap1(leftp1,signless_upper_left);
Dbl_copytoint_exponentmantissap1(rightp1,signless_upper_right);
/* sign difference selects add or sub operation. */
if(Dbl_ismagnitudeless(leftp2,rightp2,signless_upper_left,signless_upper_right))
{
/* Set the left operand to the larger one by XOR swap *
* First finish the first word using "save" */
Dbl_xorfromintp1(save,rightp1,/*to*/rightp1);
Dbl_xorfromintp1(save,leftp1,/*to*/leftp1);
Dbl_swap_lower(leftp2,rightp2);
result_exponent = Dbl_exponent(leftp1);
Dbl_invert_sign(leftp1);
}
/* Invariant: left is not smaller than right. */
if((right_exponent = Dbl_exponent(rightp1)) == 0)
{
/* Denormalized operands. First look for zeroes */
if(Dbl_iszero_mantissa(rightp1,rightp2))
{
/* right is zero */
if(Dbl_iszero_exponentmantissa(leftp1,leftp2))
{
/* Both operands are zeros */
Dbl_invert_sign(rightp1);
if(Is_rounding_mode(ROUNDMINUS))
{
Dbl_or_signs(leftp1,/*with*/rightp1);
}
else
{
Dbl_and_signs(leftp1,/*with*/rightp1);
}
}
else
{
/* Left is not a zero and must be the result. Trapped
* underflows are signaled if left is denormalized. Result
* is always exact. */
if( (result_exponent == 0) && Is_underflowtrap_enabled() )
{
/* need to normalize results mantissa */
sign_save = Dbl_signextendedsign(leftp1);
Dbl_leftshiftby1(leftp1,leftp2);
Dbl_normalize(leftp1,leftp2,result_exponent);
Dbl_set_sign(leftp1,/*using*/sign_save);
Dbl_setwrapped_exponent(leftp1,result_exponent,unfl);
Dbl_copytoptr(leftp1,leftp2,dstptr);
/* inexact = FALSE */
return(UNDERFLOWEXCEPTION);
}
}
Dbl_copytoptr(leftp1,leftp2,dstptr);
return(NOEXCEPTION);
}
/* Neither are zeroes */
Dbl_clear_sign(rightp1); /* Exponent is already cleared */
if(result_exponent == 0 )
{
/* Both operands are denormalized. The result must be exact
* and is simply calculated. A sum could become normalized and a
* difference could cancel to a true zero. */
if( (/*signed*/int) save >= 0 )
{
Dbl_subtract(leftp1,leftp2,/*minus*/rightp1,rightp2,
/*into*/resultp1,resultp2);
if(Dbl_iszero_mantissa(resultp1,resultp2))
{
if(Is_rounding_mode(ROUNDMINUS))
{
Dbl_setone_sign(resultp1);
}
else
{
Dbl_setzero_sign(resultp1);
}
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
}
else
{
Dbl_addition(leftp1,leftp2,rightp1,rightp2,
/*into*/resultp1,resultp2);
if(Dbl_isone_hidden(resultp1))
{
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
}
if(Is_underflowtrap_enabled())
{
/* need to normalize result */
sign_save = Dbl_signextendedsign(resultp1);
Dbl_leftshiftby1(resultp1,resultp2);
Dbl_normalize(resultp1,resultp2,result_exponent);
Dbl_set_sign(resultp1,/*using*/sign_save);
Dbl_setwrapped_exponent(resultp1,result_exponent,unfl);
Dbl_copytoptr(resultp1,resultp2,dstptr);
/* inexact = FALSE */
return(UNDERFLOWEXCEPTION);
}
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
right_exponent = 1; /* Set exponent to reflect different bias
* with denomalized numbers. */
}
else
{
Dbl_clear_signexponent_set_hidden(rightp1);
}
Dbl_clear_exponent_set_hidden(leftp1);
diff_exponent = result_exponent - right_exponent;
/*
* Special case alignment of operands that would force alignment
* beyond the extent of the extension. A further optimization
* could special case this but only reduces the path length for this
* infrequent case.
*/
if(diff_exponent > DBL_THRESHOLD)
{
diff_exponent = DBL_THRESHOLD;
}
/* Align right operand by shifting to right */
Dbl_right_align(/*operand*/rightp1,rightp2,/*shifted by*/diff_exponent,
/*and lower to*/extent);
/* Treat sum and difference of the operands separately. */
if( (/*signed*/int) save >= 0 )
{
/*
* Difference of the two operands. Their can be no overflow. A
* borrow can occur out of the hidden bit and force a post
* normalization phase.
*/
Dbl_subtract_withextension(leftp1,leftp2,/*minus*/rightp1,rightp2,
/*with*/extent,/*into*/resultp1,resultp2);
if(Dbl_iszero_hidden(resultp1))
{
/* Handle normalization */
/* A straight forward algorithm would now shift the result
* and extension left until the hidden bit becomes one. Not
* all of the extension bits need participate in the shift.
* Only the two most significant bits (round and guard) are
* needed. If only a single shift is needed then the guard
* bit becomes a significant low order bit and the extension
* must participate in the rounding. If more than a single
* shift is needed, then all bits to the right of the guard
* bit are zeros, and the guard bit may or may not be zero. */
sign_save = Dbl_signextendedsign(resultp1);
Dbl_leftshiftby1_withextent(resultp1,resultp2,extent,resultp1,resultp2);
/* Need to check for a zero result. The sign and exponent
* fields have already been zeroed. The more efficient test
* of the full object can be used.
*/
if(Dbl_iszero(resultp1,resultp2))
/* Must have been "x-x" or "x+(-x)". */
{
if(Is_rounding_mode(ROUNDMINUS)) Dbl_setone_sign(resultp1);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
result_exponent--;
/* Look to see if normalization is finished. */
if(Dbl_isone_hidden(resultp1))
{
if(result_exponent==0)
{
/* Denormalized, exponent should be zero. Left operand *
* was normalized, so extent (guard, round) was zero */
goto underflow;
}
else
{
/* No further normalization is needed. */
Dbl_set_sign(resultp1,/*using*/sign_save);
Ext_leftshiftby1(extent);
goto round;
}
}
/* Check for denormalized, exponent should be zero. Left *
* operand was normalized, so extent (guard, round) was zero */
if(!(underflowtrap = Is_underflowtrap_enabled()) &&
result_exponent==0) goto underflow;
/* Shift extension to complete one bit of normalization and
* update exponent. */
Ext_leftshiftby1(extent);
/* Discover first one bit to determine shift amount. Use a
* modified binary search. We have already shifted the result
* one position right and still not found a one so the remainder
* of the extension must be zero and simplifies rounding. */
/* Scan bytes */
while(Dbl_iszero_hiddenhigh7mantissa(resultp1))
{
Dbl_leftshiftby8(resultp1,resultp2);
if((result_exponent -= 8) <= 0 && !underflowtrap)
goto underflow;
}
/* Now narrow it down to the nibble */
if(Dbl_iszero_hiddenhigh3mantissa(resultp1))
{
/* The lower nibble contains the normalizing one */
Dbl_leftshiftby4(resultp1,resultp2);
if((result_exponent -= 4) <= 0 && !underflowtrap)
goto underflow;
}
/* Select case were first bit is set (already normalized)
* otherwise select the proper shift. */
if((jumpsize = Dbl_hiddenhigh3mantissa(resultp1)) > 7)
{
/* Already normalized */
if(result_exponent <= 0) goto underflow;
Dbl_set_sign(resultp1,/*using*/sign_save);
Dbl_set_exponent(resultp1,/*using*/result_exponent);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
Dbl_sethigh4bits(resultp1,/*using*/sign_save);
switch(jumpsize)
{
case 1:
{
Dbl_leftshiftby3(resultp1,resultp2);
result_exponent -= 3;
break;
}
case 2:
case 3:
{
Dbl_leftshiftby2(resultp1,resultp2);
result_exponent -= 2;
break;
}
case 4:
case 5:
case 6:
case 7:
{
Dbl_leftshiftby1(resultp1,resultp2);
result_exponent -= 1;
break;
}
}
if(result_exponent > 0)
{
Dbl_set_exponent(resultp1,/*using*/result_exponent);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION); /* Sign bit is already set */
}
/* Fixup potential underflows */
underflow:
if(Is_underflowtrap_enabled())
{
Dbl_set_sign(resultp1,sign_save);
Dbl_setwrapped_exponent(resultp1,result_exponent,unfl);
Dbl_copytoptr(resultp1,resultp2,dstptr);
/* inexact = FALSE */
return(UNDERFLOWEXCEPTION);
}
/*
* Since we cannot get an inexact denormalized result,
* we can now return.
*/
Dbl_fix_overshift(resultp1,resultp2,(1-result_exponent),extent);
Dbl_clear_signexponent(resultp1);
Dbl_set_sign(resultp1,sign_save);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
} /* end if(hidden...)... */
/* Fall through and round */
} /* end if(save >= 0)... */
else
{
/* Subtract magnitudes */
Dbl_addition(leftp1,leftp2,rightp1,rightp2,/*to*/resultp1,resultp2);
if(Dbl_isone_hiddenoverflow(resultp1))
{
/* Prenormalization required. */
Dbl_rightshiftby1_withextent(resultp2,extent,extent);
Dbl_arithrightshiftby1(resultp1,resultp2);
result_exponent++;
} /* end if hiddenoverflow... */
} /* end else ...subtract magnitudes... */
/* Round the result. If the extension is all zeros,then the result is
* exact. Otherwise round in the correct direction. No underflow is
* possible. If a postnormalization is necessary, then the mantissa is
* all zeros so no shift is needed. */
round:
if(Ext_isnotzero(extent))
{
inexact = TRUE;
switch(Rounding_mode())
{
case ROUNDNEAREST: /* The default. */
if(Ext_isone_sign(extent))
{
/* at least 1/2 ulp */
if(Ext_isnotzero_lower(extent) ||
Dbl_isone_lowmantissap2(resultp2))
{
/* either exactly half way and odd or more than 1/2ulp */
Dbl_increment(resultp1,resultp2);
}
}
break;
case ROUNDPLUS:
if(Dbl_iszero_sign(resultp1))
{
/* Round up positive results */
Dbl_increment(resultp1,resultp2);
}
break;
case ROUNDMINUS:
if(Dbl_isone_sign(resultp1))
{
/* Round down negative results */
Dbl_increment(resultp1,resultp2);
}
case ROUNDZERO:;
/* truncate is simple */
} /* end switch... */
if(Dbl_isone_hiddenoverflow(resultp1)) result_exponent++;
}
if(result_exponent == DBL_INFINITY_EXPONENT)
{
/* Overflow */
if(Is_overflowtrap_enabled())
{
Dbl_setwrapped_exponent(resultp1,result_exponent,ovfl);
Dbl_copytoptr(resultp1,resultp2,dstptr);
if (inexact)
if (Is_inexacttrap_enabled())
return(OVERFLOWEXCEPTION | INEXACTEXCEPTION);
else Set_inexactflag();
return(OVERFLOWEXCEPTION);
}
else
{
inexact = TRUE;
Set_overflowflag();
Dbl_setoverflow(resultp1,resultp2);
}
}
else Dbl_set_exponent(resultp1,result_exponent);
Dbl_copytoptr(resultp1,resultp2,dstptr);
if(inexact)
if(Is_inexacttrap_enabled()) return(INEXACTEXCEPTION);
else Set_inexactflag();
return(NOEXCEPTION);
}
| gpl-2.0 |
Jackeagle/kernel_samsung_exynos5260 | net/ipv4/netfilter/ipt_ah.c | 12972 | 2333 | /* Kernel module to match AH parameters. */
/* (C) 1999-2000 Yon Uriarte <yon@astaro.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter_ipv4/ipt_ah.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yon Uriarte <yon@astaro.de>");
MODULE_DESCRIPTION("Xtables: IPv4 IPsec-AH SPI match");
/* Returns 1 if the spi is matched by the range, 0 otherwise */
static inline bool
spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert)
{
bool r;
pr_debug("spi_match:%c 0x%x <= 0x%x <= 0x%x\n",
invert ? '!' : ' ', min, spi, max);
r=(spi >= min && spi <= max) ^ invert;
pr_debug(" result %s\n", r ? "PASS" : "FAILED");
return r;
}
static bool ah_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct ip_auth_hdr _ahdr;
const struct ip_auth_hdr *ah;
const struct ipt_ah *ahinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ah = skb_header_pointer(skb, par->thoff, sizeof(_ahdr), &_ahdr);
if (ah == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
pr_debug("Dropping evil AH tinygram.\n");
par->hotdrop = true;
return 0;
}
return spi_match(ahinfo->spis[0], ahinfo->spis[1],
ntohl(ah->spi),
!!(ahinfo->invflags & IPT_AH_INV_SPI));
}
static int ah_mt_check(const struct xt_mtchk_param *par)
{
const struct ipt_ah *ahinfo = par->matchinfo;
/* Must specify no unknown invflags */
if (ahinfo->invflags & ~IPT_AH_INV_MASK) {
pr_debug("unknown flags %X\n", ahinfo->invflags);
return -EINVAL;
}
return 0;
}
static struct xt_match ah_mt_reg __read_mostly = {
.name = "ah",
.family = NFPROTO_IPV4,
.match = ah_mt,
.matchsize = sizeof(struct ipt_ah),
.proto = IPPROTO_AH,
.checkentry = ah_mt_check,
.me = THIS_MODULE,
};
static int __init ah_mt_init(void)
{
return xt_register_match(&ah_mt_reg);
}
static void __exit ah_mt_exit(void)
{
xt_unregister_match(&ah_mt_reg);
}
module_init(ah_mt_init);
module_exit(ah_mt_exit);
| gpl-2.0 |
5victor/linux | net/ipv4/netfilter/ipt_ah.c | 12972 | 2333 | /* Kernel module to match AH parameters. */
/* (C) 1999-2000 Yon Uriarte <yon@astaro.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter_ipv4/ipt_ah.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yon Uriarte <yon@astaro.de>");
MODULE_DESCRIPTION("Xtables: IPv4 IPsec-AH SPI match");
/* Returns 1 if the spi is matched by the range, 0 otherwise */
static inline bool
spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert)
{
bool r;
pr_debug("spi_match:%c 0x%x <= 0x%x <= 0x%x\n",
invert ? '!' : ' ', min, spi, max);
r=(spi >= min && spi <= max) ^ invert;
pr_debug(" result %s\n", r ? "PASS" : "FAILED");
return r;
}
static bool ah_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct ip_auth_hdr _ahdr;
const struct ip_auth_hdr *ah;
const struct ipt_ah *ahinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ah = skb_header_pointer(skb, par->thoff, sizeof(_ahdr), &_ahdr);
if (ah == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
pr_debug("Dropping evil AH tinygram.\n");
par->hotdrop = true;
return 0;
}
return spi_match(ahinfo->spis[0], ahinfo->spis[1],
ntohl(ah->spi),
!!(ahinfo->invflags & IPT_AH_INV_SPI));
}
static int ah_mt_check(const struct xt_mtchk_param *par)
{
const struct ipt_ah *ahinfo = par->matchinfo;
/* Must specify no unknown invflags */
if (ahinfo->invflags & ~IPT_AH_INV_MASK) {
pr_debug("unknown flags %X\n", ahinfo->invflags);
return -EINVAL;
}
return 0;
}
static struct xt_match ah_mt_reg __read_mostly = {
.name = "ah",
.family = NFPROTO_IPV4,
.match = ah_mt,
.matchsize = sizeof(struct ipt_ah),
.proto = IPPROTO_AH,
.checkentry = ah_mt_check,
.me = THIS_MODULE,
};
static int __init ah_mt_init(void)
{
return xt_register_match(&ah_mt_reg);
}
static void __exit ah_mt_exit(void)
{
xt_unregister_match(&ah_mt_reg);
}
module_init(ah_mt_init);
module_exit(ah_mt_exit);
| gpl-2.0 |
anasanzari/Cowcopy | drivers/iio/accel/stk8312.c | 173 | 9159 | /**
* Sensortek STK8312 3-Axis Accelerometer
*
* Copyright (c) 2015, Intel Corporation.
*
* This file is subject to the terms and conditions of version 2 of
* the GNU General Public License. See the file COPYING in the main
* directory of this archive for more details.
*
* IIO driver for STK8312; 7-bit I2C address: 0x3D.
*/
#include <linux/acpi.h>
#include <linux/i2c.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#define STK8312_REG_XOUT 0x00
#define STK8312_REG_YOUT 0x01
#define STK8312_REG_ZOUT 0x02
#define STK8312_REG_MODE 0x07
#define STK8312_REG_STH 0x13
#define STK8312_REG_RESET 0x20
#define STK8312_REG_AFECTRL 0x24
#define STK8312_REG_OTPADDR 0x3D
#define STK8312_REG_OTPDATA 0x3E
#define STK8312_REG_OTPCTRL 0x3F
#define STK8312_MODE_ACTIVE 1
#define STK8312_MODE_STANDBY 0
#define STK8312_MODE_MASK 0x01
#define STK8312_RNG_MASK 0xC0
#define STK8312_RNG_SHIFT 6
#define STK8312_READ_RETRIES 16
#define STK8312_DRIVER_NAME "stk8312"
/*
* The accelerometer has two measurement ranges:
*
* -6g - +6g (8-bit, signed)
* -16g - +16g (8-bit, signed)
*
* scale1 = (6 + 6) * 9.81 / (2^8 - 1) = 0.4616
* scale2 = (16 + 16) * 9.81 / (2^8 - 1) = 1.2311
*/
#define STK8312_SCALE_AVAIL "0.4616 1.2311"
static const int stk8312_scale_table[][2] = {
{0, 461600}, {1, 231100}
};
#define STK8312_ACCEL_CHANNEL(reg, axis) { \
.type = IIO_ACCEL, \
.address = reg, \
.modified = 1, \
.channel2 = IIO_MOD_##axis, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
}
static const struct iio_chan_spec stk8312_channels[] = {
STK8312_ACCEL_CHANNEL(STK8312_REG_XOUT, X),
STK8312_ACCEL_CHANNEL(STK8312_REG_YOUT, Y),
STK8312_ACCEL_CHANNEL(STK8312_REG_ZOUT, Z),
};
struct stk8312_data {
struct i2c_client *client;
struct mutex lock;
int range;
u8 mode;
};
static IIO_CONST_ATTR(in_accel_scale_available, STK8312_SCALE_AVAIL);
static struct attribute *stk8312_attributes[] = {
&iio_const_attr_in_accel_scale_available.dev_attr.attr,
NULL,
};
static const struct attribute_group stk8312_attribute_group = {
.attrs = stk8312_attributes
};
static int stk8312_otp_init(struct stk8312_data *data)
{
int ret;
int count = 10;
struct i2c_client *client = data->client;
ret = i2c_smbus_write_byte_data(client, STK8312_REG_OTPADDR, 0x70);
if (ret < 0)
goto exit_err;
ret = i2c_smbus_write_byte_data(client, STK8312_REG_OTPCTRL, 0x02);
if (ret < 0)
goto exit_err;
do {
usleep_range(1000, 5000);
ret = i2c_smbus_read_byte_data(client, STK8312_REG_OTPCTRL);
if (ret < 0)
goto exit_err;
count--;
} while (!(ret & 0x80) && count > 0);
if (count == 0)
goto exit_err;
ret = i2c_smbus_read_byte_data(client, STK8312_REG_OTPDATA);
if (ret < 0)
goto exit_err;
ret = i2c_smbus_write_byte_data(data->client,
STK8312_REG_AFECTRL, ret);
if (ret < 0)
goto exit_err;
msleep(150);
return ret;
exit_err:
dev_err(&client->dev, "failed to initialize sensor\n");
return ret;
}
static int stk8312_set_mode(struct stk8312_data *data, u8 mode)
{
int ret;
u8 masked_reg;
struct i2c_client *client = data->client;
if (mode > 1)
return -EINVAL;
else if (mode == data->mode)
return 0;
ret = i2c_smbus_read_byte_data(client, STK8312_REG_MODE);
if (ret < 0) {
dev_err(&client->dev, "failed to change sensor mode\n");
return ret;
}
masked_reg = ret & (~STK8312_MODE_MASK);
masked_reg |= mode;
ret = i2c_smbus_write_byte_data(client,
STK8312_REG_MODE, masked_reg);
if (ret < 0) {
dev_err(&client->dev, "failed to change sensor mode\n");
return ret;
}
data->mode = mode;
if (mode == STK8312_MODE_ACTIVE) {
/* Need to run OTP sequence before entering active mode */
usleep_range(1000, 5000);
ret = stk8312_otp_init(data);
}
return ret;
}
static int stk8312_set_range(struct stk8312_data *data, u8 range)
{
int ret;
u8 masked_reg;
u8 mode;
struct i2c_client *client = data->client;
if (range != 1 && range != 2)
return -EINVAL;
else if (range == data->range)
return 0;
mode = data->mode;
/* We need to go in standby mode to modify registers */
ret = stk8312_set_mode(data, STK8312_MODE_STANDBY);
if (ret < 0)
return ret;
ret = i2c_smbus_read_byte_data(client, STK8312_REG_STH);
if (ret < 0) {
dev_err(&client->dev, "failed to change sensor range\n");
return ret;
}
masked_reg = ret & (~STK8312_RNG_MASK);
masked_reg |= range << STK8312_RNG_SHIFT;
ret = i2c_smbus_write_byte_data(client, STK8312_REG_STH, masked_reg);
if (ret < 0)
dev_err(&client->dev, "failed to change sensor range\n");
else
data->range = range;
return stk8312_set_mode(data, mode);
}
static int stk8312_read_accel(struct stk8312_data *data, u8 address)
{
int ret;
struct i2c_client *client = data->client;
if (address > 2)
return -EINVAL;
ret = i2c_smbus_read_byte_data(client, address);
if (ret < 0) {
dev_err(&client->dev, "register read failed\n");
return ret;
}
return sign_extend32(ret, 7);
}
static int stk8312_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct stk8312_data *data = iio_priv(indio_dev);
if (chan->type != IIO_ACCEL)
return -EINVAL;
switch (mask) {
case IIO_CHAN_INFO_RAW:
mutex_lock(&data->lock);
*val = stk8312_read_accel(data, chan->address);
mutex_unlock(&data->lock);
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
*val = stk8312_scale_table[data->range - 1][0];
*val2 = stk8312_scale_table[data->range - 1][1];
return IIO_VAL_INT_PLUS_MICRO;
}
return -EINVAL;
}
static int stk8312_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
int i;
int index = -1;
int ret;
struct stk8312_data *data = iio_priv(indio_dev);
switch (mask) {
case IIO_CHAN_INFO_SCALE:
for (i = 0; i < ARRAY_SIZE(stk8312_scale_table); i++)
if (val == stk8312_scale_table[i][0] &&
val2 == stk8312_scale_table[i][1]) {
index = i + 1;
break;
}
if (index < 0)
return -EINVAL;
mutex_lock(&data->lock);
ret = stk8312_set_range(data, index);
mutex_unlock(&data->lock);
return ret;
}
return -EINVAL;
}
static const struct iio_info stk8312_info = {
.driver_module = THIS_MODULE,
.read_raw = stk8312_read_raw,
.write_raw = stk8312_write_raw,
.attrs = &stk8312_attribute_group,
};
static int stk8312_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret;
struct iio_dev *indio_dev;
struct stk8312_data *data;
indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
if (!indio_dev) {
dev_err(&client->dev, "iio allocation failed!\n");
return -ENOMEM;
}
data = iio_priv(indio_dev);
data->client = client;
i2c_set_clientdata(client, indio_dev);
mutex_init(&data->lock);
indio_dev->dev.parent = &client->dev;
indio_dev->info = &stk8312_info;
indio_dev->name = STK8312_DRIVER_NAME;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = stk8312_channels;
indio_dev->num_channels = ARRAY_SIZE(stk8312_channels);
/* A software reset is recommended at power-on */
ret = i2c_smbus_write_byte_data(data->client, STK8312_REG_RESET, 0x00);
if (ret < 0) {
dev_err(&client->dev, "failed to reset sensor\n");
return ret;
}
ret = stk8312_set_range(data, 1);
if (ret < 0)
return ret;
ret = stk8312_set_mode(data, STK8312_MODE_ACTIVE);
if (ret < 0)
return ret;
ret = iio_device_register(indio_dev);
if (ret < 0) {
dev_err(&client->dev, "device_register failed\n");
stk8312_set_mode(data, STK8312_MODE_STANDBY);
}
return ret;
}
static int stk8312_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
iio_device_unregister(indio_dev);
return stk8312_set_mode(iio_priv(indio_dev), STK8312_MODE_STANDBY);
}
#ifdef CONFIG_PM_SLEEP
static int stk8312_suspend(struct device *dev)
{
struct stk8312_data *data;
data = iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
return stk8312_set_mode(data, STK8312_MODE_STANDBY);
}
static int stk8312_resume(struct device *dev)
{
struct stk8312_data *data;
data = iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
return stk8312_set_mode(data, STK8312_MODE_ACTIVE);
}
static SIMPLE_DEV_PM_OPS(stk8312_pm_ops, stk8312_suspend, stk8312_resume);
#define STK8312_PM_OPS (&stk8312_pm_ops)
#else
#define STK8312_PM_OPS NULL
#endif
static const struct i2c_device_id stk8312_i2c_id[] = {
{"STK8312", 0},
{}
};
static const struct acpi_device_id stk8312_acpi_id[] = {
{"STK8312", 0},
{}
};
MODULE_DEVICE_TABLE(acpi, stk8312_acpi_id);
static struct i2c_driver stk8312_driver = {
.driver = {
.name = "stk8312",
.pm = STK8312_PM_OPS,
.acpi_match_table = ACPI_PTR(stk8312_acpi_id),
},
.probe = stk8312_probe,
.remove = stk8312_remove,
.id_table = stk8312_i2c_id,
};
module_i2c_driver(stk8312_driver);
MODULE_AUTHOR("Tiberiu Breana <tiberiu.a.breana@intel.com>");
MODULE_DESCRIPTION("STK8312 3-Axis Accelerometer driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
MikeC84/jet-3.4.10-gdd05a11 | arch/powerpc/kernel/time.c | 429 | 26701 | /*
* Common time routines among all ppc machines.
*
* Written by Cort Dougan (cort@cs.nmt.edu) to merge
* Paul Mackerras' version and mine for PReP and Pmac.
* MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
* Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
*
* First round of bugfixes by Gabriel Paubert (paubert@iram.es)
* to make clock more stable (2.4.0-test5). The only thing
* that this code assumes is that the timebases have been synchronized
* by firmware on SMP and are never stopped (never do sleep
* on SMP then, nap and doze are OK).
*
* Speeded up do_gettimeofday by getting rid of references to
* xtime (which required locks for consistency). (mikejc@us.ibm.com)
*
* TODO (not necessarily in this file):
* - improve precision and reproducibility of timebase frequency
* measurement at boot time.
* - for astronomical applications: add a new function to get
* non ambiguous timestamps even around leap seconds. This needs
* a new timestamp format and a good name.
*
* 1997-09-10 Updated NTP code according to technical memorandum Jan '96
* "A Kernel Model for Precision Timekeeping" by Dave Mills
*
* 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/errno.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/timex.h>
#include <linux/kernel_stat.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/profile.h>
#include <linux/cpu.h>
#include <linux/security.h>
#include <linux/percpu.h>
#include <linux/rtc.h>
#include <linux/jiffies.h>
#include <linux/posix-timers.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/irq_work.h>
#include <asm/trace.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/nvram.h>
#include <asm/cache.h>
#include <asm/machdep.h>
#include <asm/uaccess.h>
#include <asm/time.h>
#include <asm/prom.h>
#include <asm/irq.h>
#include <asm/div64.h>
#include <asm/smp.h>
#include <asm/vdso_datapage.h>
#include <asm/firmware.h>
#include <asm/cputime.h>
/* powerpc clocksource/clockevent code */
#include <linux/clockchips.h>
#include <linux/clocksource.h>
static cycle_t rtc_read(struct clocksource *);
static struct clocksource clocksource_rtc = {
.name = "rtc",
.rating = 400,
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
.mask = CLOCKSOURCE_MASK(64),
.read = rtc_read,
};
static cycle_t timebase_read(struct clocksource *);
static struct clocksource clocksource_timebase = {
.name = "timebase",
.rating = 400,
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
.mask = CLOCKSOURCE_MASK(64),
.read = timebase_read,
};
#define DECREMENTER_MAX 0x7fffffff
static int decrementer_set_next_event(unsigned long evt,
struct clock_event_device *dev);
static void decrementer_set_mode(enum clock_event_mode mode,
struct clock_event_device *dev);
static struct clock_event_device decrementer_clockevent = {
.name = "decrementer",
.rating = 200,
.irq = 0,
.set_next_event = decrementer_set_next_event,
.set_mode = decrementer_set_mode,
.features = CLOCK_EVT_FEAT_ONESHOT,
};
DEFINE_PER_CPU(u64, decrementers_next_tb);
static DEFINE_PER_CPU(struct clock_event_device, decrementers);
#define XSEC_PER_SEC (1024*1024)
#ifdef CONFIG_PPC64
#define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
#else
/* compute ((xsec << 12) * max) >> 32 */
#define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
#endif
unsigned long tb_ticks_per_jiffy;
unsigned long tb_ticks_per_usec = 100; /* sane default */
EXPORT_SYMBOL(tb_ticks_per_usec);
unsigned long tb_ticks_per_sec;
EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
DEFINE_SPINLOCK(rtc_lock);
EXPORT_SYMBOL_GPL(rtc_lock);
static u64 tb_to_ns_scale __read_mostly;
static unsigned tb_to_ns_shift __read_mostly;
static u64 boot_tb __read_mostly;
extern struct timezone sys_tz;
static long timezone_offset;
unsigned long ppc_proc_freq;
EXPORT_SYMBOL_GPL(ppc_proc_freq);
unsigned long ppc_tb_freq;
EXPORT_SYMBOL_GPL(ppc_tb_freq);
#ifdef CONFIG_VIRT_CPU_ACCOUNTING
/*
* Factors for converting from cputime_t (timebase ticks) to
* jiffies, microseconds, seconds, and clock_t (1/USER_HZ seconds).
* These are all stored as 0.64 fixed-point binary fractions.
*/
u64 __cputime_jiffies_factor;
EXPORT_SYMBOL(__cputime_jiffies_factor);
u64 __cputime_usec_factor;
EXPORT_SYMBOL(__cputime_usec_factor);
u64 __cputime_sec_factor;
EXPORT_SYMBOL(__cputime_sec_factor);
u64 __cputime_clockt_factor;
EXPORT_SYMBOL(__cputime_clockt_factor);
DEFINE_PER_CPU(unsigned long, cputime_last_delta);
DEFINE_PER_CPU(unsigned long, cputime_scaled_last_delta);
cputime_t cputime_one_jiffy;
void (*dtl_consumer)(struct dtl_entry *, u64);
static void calc_cputime_factors(void)
{
struct div_result res;
div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
__cputime_jiffies_factor = res.result_low;
div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
__cputime_usec_factor = res.result_low;
div128_by_32(1, 0, tb_ticks_per_sec, &res);
__cputime_sec_factor = res.result_low;
div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
__cputime_clockt_factor = res.result_low;
}
/*
* Read the SPURR on systems that have it, otherwise the PURR,
* or if that doesn't exist return the timebase value passed in.
*/
static u64 read_spurr(u64 tb)
{
if (cpu_has_feature(CPU_FTR_SPURR))
return mfspr(SPRN_SPURR);
if (cpu_has_feature(CPU_FTR_PURR))
return mfspr(SPRN_PURR);
return tb;
}
#ifdef CONFIG_PPC_SPLPAR
/*
* Scan the dispatch trace log and count up the stolen time.
* Should be called with interrupts disabled.
*/
static u64 scan_dispatch_log(u64 stop_tb)
{
u64 i = local_paca->dtl_ridx;
struct dtl_entry *dtl = local_paca->dtl_curr;
struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
struct lppaca *vpa = local_paca->lppaca_ptr;
u64 tb_delta;
u64 stolen = 0;
u64 dtb;
if (!dtl)
return 0;
if (i == vpa->dtl_idx)
return 0;
while (i < vpa->dtl_idx) {
if (dtl_consumer)
dtl_consumer(dtl, i);
dtb = dtl->timebase;
tb_delta = dtl->enqueue_to_dispatch_time +
dtl->ready_to_enqueue_time;
barrier();
if (i + N_DISPATCH_LOG < vpa->dtl_idx) {
/* buffer has overflowed */
i = vpa->dtl_idx - N_DISPATCH_LOG;
dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
continue;
}
if (dtb > stop_tb)
break;
stolen += tb_delta;
++i;
++dtl;
if (dtl == dtl_end)
dtl = local_paca->dispatch_log;
}
local_paca->dtl_ridx = i;
local_paca->dtl_curr = dtl;
return stolen;
}
/*
* Accumulate stolen time by scanning the dispatch trace log.
* Called on entry from user mode.
*/
void accumulate_stolen_time(void)
{
u64 sst, ust;
u8 save_soft_enabled = local_paca->soft_enabled;
/* We are called early in the exception entry, before
* soft/hard_enabled are sync'ed to the expected state
* for the exception. We are hard disabled but the PACA
* needs to reflect that so various debug stuff doesn't
* complain
*/
local_paca->soft_enabled = 0;
sst = scan_dispatch_log(local_paca->starttime_user);
ust = scan_dispatch_log(local_paca->starttime);
local_paca->system_time -= sst;
local_paca->user_time -= ust;
local_paca->stolen_time += ust + sst;
local_paca->soft_enabled = save_soft_enabled;
}
static inline u64 calculate_stolen_time(u64 stop_tb)
{
u64 stolen = 0;
if (get_paca()->dtl_ridx != get_paca()->lppaca_ptr->dtl_idx) {
stolen = scan_dispatch_log(stop_tb);
get_paca()->system_time -= stolen;
}
stolen += get_paca()->stolen_time;
get_paca()->stolen_time = 0;
return stolen;
}
#else /* CONFIG_PPC_SPLPAR */
static inline u64 calculate_stolen_time(u64 stop_tb)
{
return 0;
}
#endif /* CONFIG_PPC_SPLPAR */
/*
* Account time for a transition between system, hard irq
* or soft irq state.
*/
void account_system_vtime(struct task_struct *tsk)
{
u64 now, nowscaled, delta, deltascaled;
unsigned long flags;
u64 stolen, udelta, sys_scaled, user_scaled;
local_irq_save(flags);
now = mftb();
nowscaled = read_spurr(now);
get_paca()->system_time += now - get_paca()->starttime;
get_paca()->starttime = now;
deltascaled = nowscaled - get_paca()->startspurr;
get_paca()->startspurr = nowscaled;
stolen = calculate_stolen_time(now);
delta = get_paca()->system_time;
get_paca()->system_time = 0;
udelta = get_paca()->user_time - get_paca()->utime_sspurr;
get_paca()->utime_sspurr = get_paca()->user_time;
/*
* Because we don't read the SPURR on every kernel entry/exit,
* deltascaled includes both user and system SPURR ticks.
* Apportion these ticks to system SPURR ticks and user
* SPURR ticks in the same ratio as the system time (delta)
* and user time (udelta) values obtained from the timebase
* over the same interval. The system ticks get accounted here;
* the user ticks get saved up in paca->user_time_scaled to be
* used by account_process_tick.
*/
sys_scaled = delta;
user_scaled = udelta;
if (deltascaled != delta + udelta) {
if (udelta) {
sys_scaled = deltascaled * delta / (delta + udelta);
user_scaled = deltascaled - sys_scaled;
} else {
sys_scaled = deltascaled;
}
}
get_paca()->user_time_scaled += user_scaled;
if (in_interrupt() || idle_task(smp_processor_id()) != tsk) {
account_system_time(tsk, 0, delta, sys_scaled);
if (stolen)
account_steal_time(stolen);
} else {
account_idle_time(delta + stolen);
}
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(account_system_vtime);
/*
* Transfer the user and system times accumulated in the paca
* by the exception entry and exit code to the generic process
* user and system time records.
* Must be called with interrupts disabled.
* Assumes that account_system_vtime() has been called recently
* (i.e. since the last entry from usermode) so that
* get_paca()->user_time_scaled is up to date.
*/
void account_process_tick(struct task_struct *tsk, int user_tick)
{
cputime_t utime, utimescaled;
utime = get_paca()->user_time;
utimescaled = get_paca()->user_time_scaled;
get_paca()->user_time = 0;
get_paca()->user_time_scaled = 0;
get_paca()->utime_sspurr = 0;
account_user_time(tsk, utime, utimescaled);
}
#else /* ! CONFIG_VIRT_CPU_ACCOUNTING */
#define calc_cputime_factors()
#endif
void __delay(unsigned long loops)
{
unsigned long start;
int diff;
if (__USE_RTC()) {
start = get_rtcl();
do {
/* the RTCL register wraps at 1000000000 */
diff = get_rtcl() - start;
if (diff < 0)
diff += 1000000000;
} while (diff < loops);
} else {
start = get_tbl();
while (get_tbl() - start < loops)
HMT_low();
HMT_medium();
}
}
EXPORT_SYMBOL(__delay);
void udelay(unsigned long usecs)
{
__delay(tb_ticks_per_usec * usecs);
}
EXPORT_SYMBOL(udelay);
#ifdef CONFIG_SMP
unsigned long profile_pc(struct pt_regs *regs)
{
unsigned long pc = instruction_pointer(regs);
if (in_lock_functions(pc))
return regs->link;
return pc;
}
EXPORT_SYMBOL(profile_pc);
#endif
#ifdef CONFIG_IRQ_WORK
/*
* 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
*/
#ifdef CONFIG_PPC64
static inline unsigned long test_irq_work_pending(void)
{
unsigned long x;
asm volatile("lbz %0,%1(13)"
: "=r" (x)
: "i" (offsetof(struct paca_struct, irq_work_pending)));
return x;
}
static inline void set_irq_work_pending_flag(void)
{
asm volatile("stb %0,%1(13)" : :
"r" (1),
"i" (offsetof(struct paca_struct, irq_work_pending)));
}
static inline void clear_irq_work_pending(void)
{
asm volatile("stb %0,%1(13)" : :
"r" (0),
"i" (offsetof(struct paca_struct, irq_work_pending)));
}
#else /* 32-bit */
DEFINE_PER_CPU(u8, irq_work_pending);
#define set_irq_work_pending_flag() __get_cpu_var(irq_work_pending) = 1
#define test_irq_work_pending() __get_cpu_var(irq_work_pending)
#define clear_irq_work_pending() __get_cpu_var(irq_work_pending) = 0
#endif /* 32 vs 64 bit */
void arch_irq_work_raise(void)
{
preempt_disable();
set_irq_work_pending_flag();
set_dec(1);
preempt_enable();
}
#else /* CONFIG_IRQ_WORK */
#define test_irq_work_pending() 0
#define clear_irq_work_pending()
#endif /* CONFIG_IRQ_WORK */
/*
* timer_interrupt - gets called when the decrementer overflows,
* with interrupts disabled.
*/
void timer_interrupt(struct pt_regs * regs)
{
struct pt_regs *old_regs;
u64 *next_tb = &__get_cpu_var(decrementers_next_tb);
struct clock_event_device *evt = &__get_cpu_var(decrementers);
u64 now;
/* Ensure a positive value is written to the decrementer, or else
* some CPUs will continue to take decrementer exceptions.
*/
set_dec(DECREMENTER_MAX);
/* Some implementations of hotplug will get timer interrupts while
* offline, just ignore these
*/
if (!cpu_online(smp_processor_id()))
return;
/* Conditionally hard-enable interrupts now that the DEC has been
* bumped to its maximum value
*/
may_hard_irq_enable();
trace_timer_interrupt_entry(regs);
__get_cpu_var(irq_stat).timer_irqs++;
#if defined(CONFIG_PPC32) && defined(CONFIG_PMAC)
if (atomic_read(&ppc_n_lost_interrupts) != 0)
do_IRQ(regs);
#endif
old_regs = set_irq_regs(regs);
irq_enter();
if (test_irq_work_pending()) {
clear_irq_work_pending();
irq_work_run();
}
now = get_tb_or_rtc();
if (now >= *next_tb) {
*next_tb = ~(u64)0;
if (evt->event_handler)
evt->event_handler(evt);
} else {
now = *next_tb - now;
if (now <= DECREMENTER_MAX)
set_dec((int)now);
}
#ifdef CONFIG_PPC64
/* collect purr register values often, for accurate calculations */
if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
cu->current_tb = mfspr(SPRN_PURR);
}
#endif
irq_exit();
set_irq_regs(old_regs);
trace_timer_interrupt_exit(regs);
}
#ifdef CONFIG_SUSPEND
static void generic_suspend_disable_irqs(void)
{
/* Disable the decrementer, so that it doesn't interfere
* with suspending.
*/
set_dec(DECREMENTER_MAX);
local_irq_disable();
set_dec(DECREMENTER_MAX);
}
static void generic_suspend_enable_irqs(void)
{
local_irq_enable();
}
/* Overrides the weak version in kernel/power/main.c */
void arch_suspend_disable_irqs(void)
{
if (ppc_md.suspend_disable_irqs)
ppc_md.suspend_disable_irqs();
generic_suspend_disable_irqs();
}
/* Overrides the weak version in kernel/power/main.c */
void arch_suspend_enable_irqs(void)
{
generic_suspend_enable_irqs();
if (ppc_md.suspend_enable_irqs)
ppc_md.suspend_enable_irqs();
}
#endif
/*
* Scheduler clock - returns current time in nanosec units.
*
* Note: mulhdu(a, b) (multiply high double unsigned) returns
* the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
* are 64-bit unsigned numbers.
*/
unsigned long long sched_clock(void)
{
if (__USE_RTC())
return get_rtc();
return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
}
static int __init get_freq(char *name, int cells, unsigned long *val)
{
struct device_node *cpu;
const unsigned int *fp;
int found = 0;
/* The cpu node should have timebase and clock frequency properties */
cpu = of_find_node_by_type(NULL, "cpu");
if (cpu) {
fp = of_get_property(cpu, name, NULL);
if (fp) {
found = 1;
*val = of_read_ulong(fp, cells);
}
of_node_put(cpu);
}
return found;
}
/* should become __cpuinit when secondary_cpu_time_init also is */
void start_cpu_decrementer(void)
{
#if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
/* Clear any pending timer interrupts */
mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
/* Enable decrementer interrupt */
mtspr(SPRN_TCR, TCR_DIE);
#endif /* defined(CONFIG_BOOKE) || defined(CONFIG_40x) */
}
void __init generic_calibrate_decr(void)
{
ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
!get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
printk(KERN_ERR "WARNING: Estimating decrementer frequency "
"(not found)\n");
}
ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
!get_freq("clock-frequency", 1, &ppc_proc_freq)) {
printk(KERN_ERR "WARNING: Estimating processor frequency "
"(not found)\n");
}
}
int update_persistent_clock(struct timespec now)
{
struct rtc_time tm;
if (!ppc_md.set_rtc_time)
return 0;
to_tm(now.tv_sec + 1 + timezone_offset, &tm);
tm.tm_year -= 1900;
tm.tm_mon -= 1;
return ppc_md.set_rtc_time(&tm);
}
static void __read_persistent_clock(struct timespec *ts)
{
struct rtc_time tm;
static int first = 1;
ts->tv_nsec = 0;
/* XXX this is a litle fragile but will work okay in the short term */
if (first) {
first = 0;
if (ppc_md.time_init)
timezone_offset = ppc_md.time_init();
/* get_boot_time() isn't guaranteed to be safe to call late */
if (ppc_md.get_boot_time) {
ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
return;
}
}
if (!ppc_md.get_rtc_time) {
ts->tv_sec = 0;
return;
}
ppc_md.get_rtc_time(&tm);
ts->tv_sec = mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
void read_persistent_clock(struct timespec *ts)
{
__read_persistent_clock(ts);
/* Sanitize it in case real time clock is set below EPOCH */
if (ts->tv_sec < 0) {
ts->tv_sec = 0;
ts->tv_nsec = 0;
}
}
/* clocksource code */
static cycle_t rtc_read(struct clocksource *cs)
{
return (cycle_t)get_rtc();
}
static cycle_t timebase_read(struct clocksource *cs)
{
return (cycle_t)get_tb();
}
void update_vsyscall(struct timespec *wall_time, struct timespec *wtm,
struct clocksource *clock, u32 mult)
{
u64 new_tb_to_xs, new_stamp_xsec;
u32 frac_sec;
if (clock != &clocksource_timebase)
return;
/* Make userspace gettimeofday spin until we're done. */
++vdso_data->tb_update_count;
smp_mb();
/* 19342813113834067 ~= 2^(20+64) / 1e9 */
new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
new_stamp_xsec = (u64) wall_time->tv_nsec * XSEC_PER_SEC;
do_div(new_stamp_xsec, 1000000000);
new_stamp_xsec += (u64) wall_time->tv_sec * XSEC_PER_SEC;
BUG_ON(wall_time->tv_nsec >= NSEC_PER_SEC);
/* this is tv_nsec / 1e9 as a 0.32 fraction */
frac_sec = ((u64) wall_time->tv_nsec * 18446744073ULL) >> 32;
/*
* tb_update_count is used to allow the userspace gettimeofday code
* to assure itself that it sees a consistent view of the tb_to_xs and
* stamp_xsec variables. It reads the tb_update_count, then reads
* tb_to_xs and stamp_xsec and then reads tb_update_count again. If
* the two values of tb_update_count match and are even then the
* tb_to_xs and stamp_xsec values are consistent. If not, then it
* loops back and reads them again until this criteria is met.
* We expect the caller to have done the first increment of
* vdso_data->tb_update_count already.
*/
vdso_data->tb_orig_stamp = clock->cycle_last;
vdso_data->stamp_xsec = new_stamp_xsec;
vdso_data->tb_to_xs = new_tb_to_xs;
vdso_data->wtom_clock_sec = wtm->tv_sec;
vdso_data->wtom_clock_nsec = wtm->tv_nsec;
vdso_data->stamp_xtime = *wall_time;
vdso_data->stamp_sec_fraction = frac_sec;
smp_wmb();
++(vdso_data->tb_update_count);
}
void update_vsyscall_tz(void)
{
/* Make userspace gettimeofday spin until we're done. */
++vdso_data->tb_update_count;
smp_mb();
vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
vdso_data->tz_dsttime = sys_tz.tz_dsttime;
smp_mb();
++vdso_data->tb_update_count;
}
static void __init clocksource_init(void)
{
struct clocksource *clock;
if (__USE_RTC())
clock = &clocksource_rtc;
else
clock = &clocksource_timebase;
if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
printk(KERN_ERR "clocksource: %s is already registered\n",
clock->name);
return;
}
printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
clock->name, clock->mult, clock->shift);
}
static int decrementer_set_next_event(unsigned long evt,
struct clock_event_device *dev)
{
__get_cpu_var(decrementers_next_tb) = get_tb_or_rtc() + evt;
set_dec(evt);
return 0;
}
static void decrementer_set_mode(enum clock_event_mode mode,
struct clock_event_device *dev)
{
if (mode != CLOCK_EVT_MODE_ONESHOT)
decrementer_set_next_event(DECREMENTER_MAX, dev);
}
static void register_decrementer_clockevent(int cpu)
{
struct clock_event_device *dec = &per_cpu(decrementers, cpu);
*dec = decrementer_clockevent;
dec->cpumask = cpumask_of(cpu);
printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
dec->name, dec->mult, dec->shift, cpu);
clockevents_register_device(dec);
}
static void __init init_decrementer_clockevent(void)
{
int cpu = smp_processor_id();
clockevents_calc_mult_shift(&decrementer_clockevent, ppc_tb_freq, 4);
decrementer_clockevent.max_delta_ns =
clockevent_delta2ns(DECREMENTER_MAX, &decrementer_clockevent);
decrementer_clockevent.min_delta_ns =
clockevent_delta2ns(2, &decrementer_clockevent);
register_decrementer_clockevent(cpu);
}
void secondary_cpu_time_init(void)
{
/* Start the decrementer on CPUs that have manual control
* such as BookE
*/
start_cpu_decrementer();
/* FIME: Should make unrelatred change to move snapshot_timebase
* call here ! */
register_decrementer_clockevent(smp_processor_id());
}
/* This function is only called on the boot processor */
void __init time_init(void)
{
struct div_result res;
u64 scale;
unsigned shift;
if (__USE_RTC()) {
/* 601 processor: dec counts down by 128 every 128ns */
ppc_tb_freq = 1000000000;
} else {
/* Normal PowerPC with timebase register */
ppc_md.calibrate_decr();
printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
}
tb_ticks_per_jiffy = ppc_tb_freq / HZ;
tb_ticks_per_sec = ppc_tb_freq;
tb_ticks_per_usec = ppc_tb_freq / 1000000;
calc_cputime_factors();
setup_cputime_one_jiffy();
/*
* Compute scale factor for sched_clock.
* The calibrate_decr() function has set tb_ticks_per_sec,
* which is the timebase frequency.
* We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
* the 128-bit result as a 64.64 fixed-point number.
* We then shift that number right until it is less than 1.0,
* giving us the scale factor and shift count to use in
* sched_clock().
*/
div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
scale = res.result_low;
for (shift = 0; res.result_high != 0; ++shift) {
scale = (scale >> 1) | (res.result_high << 63);
res.result_high >>= 1;
}
tb_to_ns_scale = scale;
tb_to_ns_shift = shift;
/* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
boot_tb = get_tb_or_rtc();
/* If platform provided a timezone (pmac), we correct the time */
if (timezone_offset) {
sys_tz.tz_minuteswest = -timezone_offset / 60;
sys_tz.tz_dsttime = 0;
}
vdso_data->tb_update_count = 0;
vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
/* Start the decrementer on CPUs that have manual control
* such as BookE
*/
start_cpu_decrementer();
/* Register the clocksource */
clocksource_init();
init_decrementer_clockevent();
}
#define FEBRUARY 2
#define STARTOFTIME 1970
#define SECDAY 86400L
#define SECYR (SECDAY * 365)
#define leapyear(year) ((year) % 4 == 0 && \
((year) % 100 != 0 || (year) % 400 == 0))
#define days_in_year(a) (leapyear(a) ? 366 : 365)
#define days_in_month(a) (month_days[(a) - 1])
static int month_days[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
/*
* This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
*/
void GregorianDay(struct rtc_time * tm)
{
int leapsToDate;
int lastYear;
int day;
int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
lastYear = tm->tm_year - 1;
/*
* Number of leap corrections to apply up to end of last year
*/
leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
/*
* This year is a leap year if it is divisible by 4 except when it is
* divisible by 100 unless it is divisible by 400
*
* e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
*/
day = tm->tm_mon > 2 && leapyear(tm->tm_year);
day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
tm->tm_mday;
tm->tm_wday = day % 7;
}
void to_tm(int tim, struct rtc_time * tm)
{
register int i;
register long hms, day;
day = tim / SECDAY;
hms = tim % SECDAY;
/* Hours, minutes, seconds are easy */
tm->tm_hour = hms / 3600;
tm->tm_min = (hms % 3600) / 60;
tm->tm_sec = (hms % 3600) % 60;
/* Number of years in days */
for (i = STARTOFTIME; day >= days_in_year(i); i++)
day -= days_in_year(i);
tm->tm_year = i;
/* Number of months in days left */
if (leapyear(tm->tm_year))
days_in_month(FEBRUARY) = 29;
for (i = 1; day >= days_in_month(i); i++)
day -= days_in_month(i);
days_in_month(FEBRUARY) = 28;
tm->tm_mon = i;
/* Days are what is left over (+1) from all that. */
tm->tm_mday = day + 1;
/*
* Determine the day of week
*/
GregorianDay(tm);
}
/*
* Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
* result.
*/
void div128_by_32(u64 dividend_high, u64 dividend_low,
unsigned divisor, struct div_result *dr)
{
unsigned long a, b, c, d;
unsigned long w, x, y, z;
u64 ra, rb, rc;
a = dividend_high >> 32;
b = dividend_high & 0xffffffff;
c = dividend_low >> 32;
d = dividend_low & 0xffffffff;
w = a / divisor;
ra = ((u64)(a - (w * divisor)) << 32) + b;
rb = ((u64) do_div(ra, divisor) << 32) + c;
x = ra;
rc = ((u64) do_div(rb, divisor) << 32) + d;
y = rb;
do_div(rc, divisor);
z = rc;
dr->result_high = ((u64)w << 32) + x;
dr->result_low = ((u64)y << 32) + z;
}
/* We don't need to calibrate delay, we use the CPU timebase for that */
void calibrate_delay(void)
{
/* Some generic code (such as spinlock debug) use loops_per_jiffy
* as the number of __delay(1) in a jiffy, so make it so
*/
loops_per_jiffy = tb_ticks_per_jiffy;
}
static int __init rtc_init(void)
{
struct platform_device *pdev;
if (!ppc_md.get_rtc_time)
return -ENODEV;
pdev = platform_device_register_simple("rtc-generic", -1, NULL, 0);
if (IS_ERR(pdev))
return PTR_ERR(pdev);
return 0;
}
module_init(rtc_init);
| gpl-2.0 |
DoriKal/linux | arch/mips/ath25/ar2315.c | 429 | 9645 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2003 Atheros Communications, Inc., All Rights Reserved.
* Copyright (C) 2006 FON Technology, SL.
* Copyright (C) 2006 Imre Kaloz <kaloz@openwrt.org>
* Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
* Copyright (C) 2012 Alexandros C. Couloumbis <alex@ozo.com>
*/
/*
* Platform devices for Atheros AR2315 SoCs
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/irqdomain.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/reboot.h>
#include <asm/bootinfo.h>
#include <asm/reboot.h>
#include <asm/time.h>
#include <ath25_platform.h>
#include "devices.h"
#include "ar2315.h"
#include "ar2315_regs.h"
static void __iomem *ar2315_rst_base;
static struct irq_domain *ar2315_misc_irq_domain;
static inline u32 ar2315_rst_reg_read(u32 reg)
{
return __raw_readl(ar2315_rst_base + reg);
}
static inline void ar2315_rst_reg_write(u32 reg, u32 val)
{
__raw_writel(val, ar2315_rst_base + reg);
}
static inline void ar2315_rst_reg_mask(u32 reg, u32 mask, u32 val)
{
u32 ret = ar2315_rst_reg_read(reg);
ret &= ~mask;
ret |= val;
ar2315_rst_reg_write(reg, ret);
}
static irqreturn_t ar2315_ahb_err_handler(int cpl, void *dev_id)
{
ar2315_rst_reg_write(AR2315_AHB_ERR0, AR2315_AHB_ERROR_DET);
ar2315_rst_reg_read(AR2315_AHB_ERR1);
pr_emerg("AHB fatal error\n");
machine_restart("AHB error"); /* Catastrophic failure */
return IRQ_HANDLED;
}
static struct irqaction ar2315_ahb_err_interrupt = {
.handler = ar2315_ahb_err_handler,
.name = "ar2315-ahb-error",
};
static void ar2315_misc_irq_handler(unsigned irq, struct irq_desc *desc)
{
u32 pending = ar2315_rst_reg_read(AR2315_ISR) &
ar2315_rst_reg_read(AR2315_IMR);
unsigned nr, misc_irq = 0;
if (pending) {
struct irq_domain *domain = irq_get_handler_data(irq);
nr = __ffs(pending);
misc_irq = irq_find_mapping(domain, nr);
}
if (misc_irq) {
if (nr == AR2315_MISC_IRQ_GPIO)
ar2315_rst_reg_write(AR2315_ISR, AR2315_ISR_GPIO);
else if (nr == AR2315_MISC_IRQ_WATCHDOG)
ar2315_rst_reg_write(AR2315_ISR, AR2315_ISR_WD);
generic_handle_irq(misc_irq);
} else {
spurious_interrupt();
}
}
static void ar2315_misc_irq_unmask(struct irq_data *d)
{
ar2315_rst_reg_mask(AR2315_IMR, 0, BIT(d->hwirq));
}
static void ar2315_misc_irq_mask(struct irq_data *d)
{
ar2315_rst_reg_mask(AR2315_IMR, BIT(d->hwirq), 0);
}
static struct irq_chip ar2315_misc_irq_chip = {
.name = "ar2315-misc",
.irq_unmask = ar2315_misc_irq_unmask,
.irq_mask = ar2315_misc_irq_mask,
};
static int ar2315_misc_irq_map(struct irq_domain *d, unsigned irq,
irq_hw_number_t hw)
{
irq_set_chip_and_handler(irq, &ar2315_misc_irq_chip, handle_level_irq);
return 0;
}
static struct irq_domain_ops ar2315_misc_irq_domain_ops = {
.map = ar2315_misc_irq_map,
};
/*
* Called when an interrupt is received, this function
* determines exactly which interrupt it was, and it
* invokes the appropriate handler.
*
* Implicitly, we also define interrupt priority by
* choosing which to dispatch first.
*/
static void ar2315_irq_dispatch(void)
{
u32 pending = read_c0_status() & read_c0_cause();
if (pending & CAUSEF_IP3)
do_IRQ(AR2315_IRQ_WLAN0);
#ifdef CONFIG_PCI_AR2315
else if (pending & CAUSEF_IP5)
do_IRQ(AR2315_IRQ_LCBUS_PCI);
#endif
else if (pending & CAUSEF_IP2)
do_IRQ(AR2315_IRQ_MISC);
else if (pending & CAUSEF_IP7)
do_IRQ(ATH25_IRQ_CPU_CLOCK);
else
spurious_interrupt();
}
void __init ar2315_arch_init_irq(void)
{
struct irq_domain *domain;
unsigned irq;
ath25_irq_dispatch = ar2315_irq_dispatch;
domain = irq_domain_add_linear(NULL, AR2315_MISC_IRQ_COUNT,
&ar2315_misc_irq_domain_ops, NULL);
if (!domain)
panic("Failed to add IRQ domain");
irq = irq_create_mapping(domain, AR2315_MISC_IRQ_AHB);
setup_irq(irq, &ar2315_ahb_err_interrupt);
irq_set_chained_handler(AR2315_IRQ_MISC, ar2315_misc_irq_handler);
irq_set_handler_data(AR2315_IRQ_MISC, domain);
ar2315_misc_irq_domain = domain;
}
void __init ar2315_init_devices(void)
{
/* Find board configuration */
ath25_find_config(AR2315_SPI_READ_BASE, AR2315_SPI_READ_SIZE);
ath25_add_wmac(0, AR2315_WLAN0_BASE, AR2315_IRQ_WLAN0);
}
static void ar2315_restart(char *command)
{
void (*mips_reset_vec)(void) = (void *)0xbfc00000;
local_irq_disable();
/* try reset the system via reset control */
ar2315_rst_reg_write(AR2315_COLD_RESET, AR2317_RESET_SYSTEM);
/* Cold reset does not work on the AR2315/6, use the GPIO reset bits
* a workaround. Give it some time to attempt a gpio based hardware
* reset (atheros reference design workaround) */
/* TODO: implement the GPIO reset workaround */
/* Some boards (e.g. Senao EOC-2610) don't implement the reset logic
* workaround. Attempt to jump to the mips reset location -
* the boot loader itself might be able to recover the system */
mips_reset_vec();
}
/*
* This table is indexed by bits 5..4 of the CLOCKCTL1 register
* to determine the predevisor value.
*/
static int clockctl1_predivide_table[4] __initdata = { 1, 2, 4, 5 };
static int pllc_divide_table[5] __initdata = { 2, 3, 4, 6, 3 };
static unsigned __init ar2315_sys_clk(u32 clock_ctl)
{
unsigned int pllc_ctrl, cpu_div;
unsigned int pllc_out, refdiv, fdiv, divby2;
unsigned int clk_div;
pllc_ctrl = ar2315_rst_reg_read(AR2315_PLLC_CTL);
refdiv = ATH25_REG_MS(pllc_ctrl, AR2315_PLLC_REF_DIV);
refdiv = clockctl1_predivide_table[refdiv];
fdiv = ATH25_REG_MS(pllc_ctrl, AR2315_PLLC_FDBACK_DIV);
divby2 = ATH25_REG_MS(pllc_ctrl, AR2315_PLLC_ADD_FDBACK_DIV) + 1;
pllc_out = (40000000 / refdiv) * (2 * divby2) * fdiv;
/* clkm input selected */
switch (clock_ctl & AR2315_CPUCLK_CLK_SEL_M) {
case 0:
case 1:
clk_div = ATH25_REG_MS(pllc_ctrl, AR2315_PLLC_CLKM_DIV);
clk_div = pllc_divide_table[clk_div];
break;
case 2:
clk_div = ATH25_REG_MS(pllc_ctrl, AR2315_PLLC_CLKC_DIV);
clk_div = pllc_divide_table[clk_div];
break;
default:
pllc_out = 40000000;
clk_div = 1;
break;
}
cpu_div = ATH25_REG_MS(clock_ctl, AR2315_CPUCLK_CLK_DIV);
cpu_div = cpu_div * 2 ?: 1;
return pllc_out / (clk_div * cpu_div);
}
static inline unsigned ar2315_cpu_frequency(void)
{
return ar2315_sys_clk(ar2315_rst_reg_read(AR2315_CPUCLK));
}
static inline unsigned ar2315_apb_frequency(void)
{
return ar2315_sys_clk(ar2315_rst_reg_read(AR2315_AMBACLK));
}
void __init ar2315_plat_time_init(void)
{
mips_hpt_frequency = ar2315_cpu_frequency() / 2;
}
void __init ar2315_plat_mem_setup(void)
{
void __iomem *sdram_base;
u32 memsize, memcfg;
u32 devid;
u32 config;
/* Detect memory size */
sdram_base = ioremap_nocache(AR2315_SDRAMCTL_BASE,
AR2315_SDRAMCTL_SIZE);
memcfg = __raw_readl(sdram_base + AR2315_MEM_CFG);
memsize = 1 + ATH25_REG_MS(memcfg, AR2315_MEM_CFG_DATA_WIDTH);
memsize <<= 1 + ATH25_REG_MS(memcfg, AR2315_MEM_CFG_COL_WIDTH);
memsize <<= 1 + ATH25_REG_MS(memcfg, AR2315_MEM_CFG_ROW_WIDTH);
memsize <<= 3;
add_memory_region(0, memsize, BOOT_MEM_RAM);
iounmap(sdram_base);
ar2315_rst_base = ioremap_nocache(AR2315_RST_BASE, AR2315_RST_SIZE);
/* Detect the hardware based on the device ID */
devid = ar2315_rst_reg_read(AR2315_SREV) & AR2315_REV_CHIP;
switch (devid) {
case 0x91: /* Need to check */
ath25_soc = ATH25_SOC_AR2318;
break;
case 0x90:
ath25_soc = ATH25_SOC_AR2317;
break;
case 0x87:
ath25_soc = ATH25_SOC_AR2316;
break;
case 0x86:
default:
ath25_soc = ATH25_SOC_AR2315;
break;
}
ath25_board.devid = devid;
/* Clear any lingering AHB errors */
config = read_c0_config();
write_c0_config(config & ~0x3);
ar2315_rst_reg_write(AR2315_AHB_ERR0, AR2315_AHB_ERROR_DET);
ar2315_rst_reg_read(AR2315_AHB_ERR1);
ar2315_rst_reg_write(AR2315_WDT_CTRL, AR2315_WDT_CTRL_IGNORE);
_machine_restart = ar2315_restart;
}
#ifdef CONFIG_PCI_AR2315
static struct resource ar2315_pci_res[] = {
{
.name = "ar2315-pci-ctrl",
.flags = IORESOURCE_MEM,
.start = AR2315_PCI_BASE,
.end = AR2315_PCI_BASE + AR2315_PCI_SIZE - 1,
},
{
.name = "ar2315-pci-ext",
.flags = IORESOURCE_MEM,
.start = AR2315_PCI_EXT_BASE,
.end = AR2315_PCI_EXT_BASE + AR2315_PCI_EXT_SIZE - 1,
},
{
.name = "ar2315-pci",
.flags = IORESOURCE_IRQ,
.start = AR2315_IRQ_LCBUS_PCI,
.end = AR2315_IRQ_LCBUS_PCI,
},
};
#endif
void __init ar2315_arch_init(void)
{
unsigned irq = irq_create_mapping(ar2315_misc_irq_domain,
AR2315_MISC_IRQ_UART0);
ath25_serial_setup(AR2315_UART0_BASE, irq, ar2315_apb_frequency());
#ifdef CONFIG_PCI_AR2315
if (ath25_soc == ATH25_SOC_AR2315) {
/* Reset PCI DMA logic */
ar2315_rst_reg_mask(AR2315_RESET, 0, AR2315_RESET_PCIDMA);
msleep(20);
ar2315_rst_reg_mask(AR2315_RESET, AR2315_RESET_PCIDMA, 0);
msleep(20);
/* Configure endians */
ar2315_rst_reg_mask(AR2315_ENDIAN_CTL, 0, AR2315_CONFIG_PCIAHB |
AR2315_CONFIG_PCIAHB_BRIDGE);
/* Configure as PCI host with DMA */
ar2315_rst_reg_write(AR2315_PCICLK, AR2315_PCICLK_PLLC_CLKM |
(AR2315_PCICLK_IN_FREQ_DIV_6 <<
AR2315_PCICLK_DIV_S));
ar2315_rst_reg_mask(AR2315_AHB_ARB_CTL, 0, AR2315_ARB_PCI);
ar2315_rst_reg_mask(AR2315_IF_CTL, AR2315_IF_PCI_CLK_MASK |
AR2315_IF_MASK, AR2315_IF_PCI |
AR2315_IF_PCI_HOST | AR2315_IF_PCI_INTR |
(AR2315_IF_PCI_CLK_OUTPUT_CLK <<
AR2315_IF_PCI_CLK_SHIFT));
platform_device_register_simple("ar2315-pci", -1,
ar2315_pci_res,
ARRAY_SIZE(ar2315_pci_res));
}
#endif
}
| gpl-2.0 |
calonso-conabio/linux | drivers/video/fbdev/omap2/dss/hdmi5_core.c | 685 | 28398 | /*
* OMAP5 HDMI CORE IP driver library
*
* Copyright (C) 2014 Texas Instruments Incorporated
*
* Authors:
* Yong Zhi
* Mythri pk
* Archit Taneja <archit@ti.com>
* Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <drm/drm_edid.h>
#include <sound/asound.h>
#include <sound/asoundef.h>
#include "hdmi5_core.h"
/* only 24 bit color depth used for now */
static const struct csc_table csc_table_deepcolor[] = {
/* HDMI_DEEP_COLOR_24BIT */
[0] = { 7036, 0, 0, 32, 0, 7036, 0, 32, 0, 0, 7036, 32, },
/* HDMI_DEEP_COLOR_30BIT */
[1] = { 7015, 0, 0, 128, 0, 7015, 0, 128, 0, 0, 7015, 128, },
/* HDMI_DEEP_COLOR_36BIT */
[2] = { 7010, 0, 0, 512, 0, 7010, 0, 512, 0, 0, 7010, 512, },
/* FULL RANGE */
[3] = { 8192, 0, 0, 0, 0, 8192, 0, 0, 0, 0, 8192, 0, },
};
static void hdmi_core_ddc_init(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
const unsigned long long iclk = 266000000; /* DSS L3 ICLK */
const unsigned ss_scl_high = 4000; /* ns */
const unsigned ss_scl_low = 4700; /* ns */
const unsigned fs_scl_high = 600; /* ns */
const unsigned fs_scl_low = 1300; /* ns */
const unsigned sda_hold = 1000; /* ns */
const unsigned sfr_div = 10;
unsigned long long sfr;
unsigned v;
sfr = iclk / sfr_div; /* SFR_DIV */
sfr /= 1000; /* SFR clock in kHz */
/* Reset */
REG_FLD_MOD(base, HDMI_CORE_I2CM_SOFTRSTZ, 0, 0, 0);
if (hdmi_wait_for_bit_change(base, HDMI_CORE_I2CM_SOFTRSTZ,
0, 0, 1) != 1)
DSSERR("HDMI I2CM reset failed\n");
/* Standard (0) or Fast (1) Mode */
REG_FLD_MOD(base, HDMI_CORE_I2CM_DIV, 0, 3, 3);
/* Standard Mode SCL High counter */
v = DIV_ROUND_UP_ULL(ss_scl_high * sfr, 1000000);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SS_SCL_HCNT_1_ADDR,
(v >> 8) & 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SS_SCL_HCNT_0_ADDR,
v & 0xff, 7, 0);
/* Standard Mode SCL Low counter */
v = DIV_ROUND_UP_ULL(ss_scl_low * sfr, 1000000);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SS_SCL_LCNT_1_ADDR,
(v >> 8) & 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SS_SCL_LCNT_0_ADDR,
v & 0xff, 7, 0);
/* Fast Mode SCL High Counter */
v = DIV_ROUND_UP_ULL(fs_scl_high * sfr, 1000000);
REG_FLD_MOD(base, HDMI_CORE_I2CM_FS_SCL_HCNT_1_ADDR,
(v >> 8) & 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_FS_SCL_HCNT_0_ADDR,
v & 0xff, 7, 0);
/* Fast Mode SCL Low Counter */
v = DIV_ROUND_UP_ULL(fs_scl_low * sfr, 1000000);
REG_FLD_MOD(base, HDMI_CORE_I2CM_FS_SCL_LCNT_1_ADDR,
(v >> 8) & 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_FS_SCL_LCNT_0_ADDR,
v & 0xff, 7, 0);
/* SDA Hold Time */
v = DIV_ROUND_UP_ULL(sda_hold * sfr, 1000000);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SDA_HOLD_ADDR, v & 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SLAVE, 0x50, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SEGADDR, 0x30, 6, 0);
/* NACK_POL to high */
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 7, 7);
/* NACK_MASK to unmasked */
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x0, 6, 6);
/* ARBITRATION_POL to high */
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 3, 3);
/* ARBITRATION_MASK to unmasked */
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x0, 2, 2);
/* DONE_POL to high */
REG_FLD_MOD(base, HDMI_CORE_I2CM_INT, 0x1, 3, 3);
/* DONE_MASK to unmasked */
REG_FLD_MOD(base, HDMI_CORE_I2CM_INT, 0x0, 2, 2);
}
static void hdmi_core_ddc_uninit(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
/* Mask I2C interrupts */
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 6, 6);
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 2, 2);
REG_FLD_MOD(base, HDMI_CORE_I2CM_INT, 0x1, 2, 2);
}
static int hdmi_core_ddc_edid(struct hdmi_core_data *core, u8 *pedid, u8 ext)
{
void __iomem *base = core->base;
u8 cur_addr;
char checksum = 0;
const int retries = 1000;
u8 seg_ptr = ext / 2;
u8 edidbase = ((ext % 2) * 0x80);
REG_FLD_MOD(base, HDMI_CORE_I2CM_SEGPTR, seg_ptr, 7, 0);
/*
* TODO: We use polling here, although we probably should use proper
* interrupts.
*/
for (cur_addr = 0; cur_addr < 128; ++cur_addr) {
int i;
/* clear ERROR and DONE */
REG_FLD_MOD(base, HDMI_CORE_IH_I2CM_STAT0, 0x3, 1, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_ADDRESS,
edidbase + cur_addr, 7, 0);
if (seg_ptr)
REG_FLD_MOD(base, HDMI_CORE_I2CM_OPERATION, 1, 1, 1);
else
REG_FLD_MOD(base, HDMI_CORE_I2CM_OPERATION, 1, 0, 0);
for (i = 0; i < retries; ++i) {
u32 stat;
stat = REG_GET(base, HDMI_CORE_IH_I2CM_STAT0, 1, 0);
/* I2CM_ERROR */
if (stat & 1) {
DSSERR("HDMI I2C Master Error\n");
return -EIO;
}
/* I2CM_DONE */
if (stat & (1 << 1))
break;
usleep_range(250, 1000);
}
if (i == retries) {
DSSERR("HDMI I2C timeout reading EDID\n");
return -EIO;
}
pedid[cur_addr] = REG_GET(base, HDMI_CORE_I2CM_DATAI, 7, 0);
checksum += pedid[cur_addr];
}
return 0;
}
int hdmi5_read_edid(struct hdmi_core_data *core, u8 *edid, int len)
{
int r, n, i;
int max_ext_blocks = (len / 128) - 1;
if (len < 128)
return -EINVAL;
hdmi_core_ddc_init(core);
r = hdmi_core_ddc_edid(core, edid, 0);
if (r)
goto out;
n = edid[0x7e];
if (n > max_ext_blocks)
n = max_ext_blocks;
for (i = 1; i <= n; i++) {
r = hdmi_core_ddc_edid(core, edid + i * EDID_LENGTH, i);
if (r)
goto out;
}
out:
hdmi_core_ddc_uninit(core);
return r ? r : len;
}
void hdmi5_core_dump(struct hdmi_core_data *core, struct seq_file *s)
{
#define DUMPCORE(r) seq_printf(s, "%-35s %08x\n", #r,\
hdmi_read_reg(core->base, r))
DUMPCORE(HDMI_CORE_FC_INVIDCONF);
DUMPCORE(HDMI_CORE_FC_INHACTIV0);
DUMPCORE(HDMI_CORE_FC_INHACTIV1);
DUMPCORE(HDMI_CORE_FC_INHBLANK0);
DUMPCORE(HDMI_CORE_FC_INHBLANK1);
DUMPCORE(HDMI_CORE_FC_INVACTIV0);
DUMPCORE(HDMI_CORE_FC_INVACTIV1);
DUMPCORE(HDMI_CORE_FC_INVBLANK);
DUMPCORE(HDMI_CORE_FC_HSYNCINDELAY0);
DUMPCORE(HDMI_CORE_FC_HSYNCINDELAY1);
DUMPCORE(HDMI_CORE_FC_HSYNCINWIDTH0);
DUMPCORE(HDMI_CORE_FC_HSYNCINWIDTH1);
DUMPCORE(HDMI_CORE_FC_VSYNCINDELAY);
DUMPCORE(HDMI_CORE_FC_VSYNCINWIDTH);
DUMPCORE(HDMI_CORE_FC_CTRLDUR);
DUMPCORE(HDMI_CORE_FC_EXCTRLDUR);
DUMPCORE(HDMI_CORE_FC_EXCTRLSPAC);
DUMPCORE(HDMI_CORE_FC_CH0PREAM);
DUMPCORE(HDMI_CORE_FC_CH1PREAM);
DUMPCORE(HDMI_CORE_FC_CH2PREAM);
DUMPCORE(HDMI_CORE_FC_AVICONF0);
DUMPCORE(HDMI_CORE_FC_AVICONF1);
DUMPCORE(HDMI_CORE_FC_AVICONF2);
DUMPCORE(HDMI_CORE_FC_AVIVID);
DUMPCORE(HDMI_CORE_FC_PRCONF);
DUMPCORE(HDMI_CORE_MC_CLKDIS);
DUMPCORE(HDMI_CORE_MC_SWRSTZREQ);
DUMPCORE(HDMI_CORE_MC_FLOWCTRL);
DUMPCORE(HDMI_CORE_MC_PHYRSTZ);
DUMPCORE(HDMI_CORE_MC_LOCKONCLOCK);
DUMPCORE(HDMI_CORE_I2CM_SLAVE);
DUMPCORE(HDMI_CORE_I2CM_ADDRESS);
DUMPCORE(HDMI_CORE_I2CM_DATAO);
DUMPCORE(HDMI_CORE_I2CM_DATAI);
DUMPCORE(HDMI_CORE_I2CM_OPERATION);
DUMPCORE(HDMI_CORE_I2CM_INT);
DUMPCORE(HDMI_CORE_I2CM_CTLINT);
DUMPCORE(HDMI_CORE_I2CM_DIV);
DUMPCORE(HDMI_CORE_I2CM_SEGADDR);
DUMPCORE(HDMI_CORE_I2CM_SOFTRSTZ);
DUMPCORE(HDMI_CORE_I2CM_SEGPTR);
DUMPCORE(HDMI_CORE_I2CM_SS_SCL_HCNT_1_ADDR);
DUMPCORE(HDMI_CORE_I2CM_SS_SCL_HCNT_0_ADDR);
DUMPCORE(HDMI_CORE_I2CM_SS_SCL_LCNT_1_ADDR);
DUMPCORE(HDMI_CORE_I2CM_SS_SCL_LCNT_0_ADDR);
DUMPCORE(HDMI_CORE_I2CM_FS_SCL_HCNT_1_ADDR);
DUMPCORE(HDMI_CORE_I2CM_FS_SCL_HCNT_0_ADDR);
DUMPCORE(HDMI_CORE_I2CM_FS_SCL_LCNT_1_ADDR);
DUMPCORE(HDMI_CORE_I2CM_FS_SCL_LCNT_0_ADDR);
DUMPCORE(HDMI_CORE_I2CM_SDA_HOLD_ADDR);
}
static void hdmi_core_init(struct hdmi_core_vid_config *video_cfg,
struct hdmi_config *cfg)
{
DSSDBG("hdmi_core_init\n");
/* video core */
video_cfg->data_enable_pol = 1; /* It is always 1*/
video_cfg->v_fc_config.timings.hsync_level = cfg->timings.hsync_level;
video_cfg->v_fc_config.timings.x_res = cfg->timings.x_res;
video_cfg->v_fc_config.timings.hsw = cfg->timings.hsw - 1;
video_cfg->v_fc_config.timings.hbp = cfg->timings.hbp;
video_cfg->v_fc_config.timings.hfp = cfg->timings.hfp;
video_cfg->hblank = cfg->timings.hfp +
cfg->timings.hbp + cfg->timings.hsw - 1;
video_cfg->v_fc_config.timings.vsync_level = cfg->timings.vsync_level;
video_cfg->v_fc_config.timings.y_res = cfg->timings.y_res;
video_cfg->v_fc_config.timings.vsw = cfg->timings.vsw;
video_cfg->v_fc_config.timings.vfp = cfg->timings.vfp;
video_cfg->v_fc_config.timings.vbp = cfg->timings.vbp;
video_cfg->vblank_osc = 0; /* Always 0 - need to confirm */
video_cfg->vblank = cfg->timings.vsw +
cfg->timings.vfp + cfg->timings.vbp;
video_cfg->v_fc_config.hdmi_dvi_mode = cfg->hdmi_dvi_mode;
video_cfg->v_fc_config.timings.interlace = cfg->timings.interlace;
}
/* DSS_HDMI_CORE_VIDEO_CONFIG */
static void hdmi_core_video_config(struct hdmi_core_data *core,
struct hdmi_core_vid_config *cfg)
{
void __iomem *base = core->base;
unsigned char r = 0;
bool vsync_pol, hsync_pol;
vsync_pol =
cfg->v_fc_config.timings.vsync_level == OMAPDSS_SIG_ACTIVE_HIGH;
hsync_pol =
cfg->v_fc_config.timings.hsync_level == OMAPDSS_SIG_ACTIVE_HIGH;
/* Set hsync, vsync and data-enable polarity */
r = hdmi_read_reg(base, HDMI_CORE_FC_INVIDCONF);
r = FLD_MOD(r, vsync_pol, 6, 6);
r = FLD_MOD(r, hsync_pol, 5, 5);
r = FLD_MOD(r, cfg->data_enable_pol, 4, 4);
r = FLD_MOD(r, cfg->vblank_osc, 1, 1);
r = FLD_MOD(r, cfg->v_fc_config.timings.interlace, 0, 0);
hdmi_write_reg(base, HDMI_CORE_FC_INVIDCONF, r);
/* set x resolution */
REG_FLD_MOD(base, HDMI_CORE_FC_INHACTIV1,
cfg->v_fc_config.timings.x_res >> 8, 4, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_INHACTIV0,
cfg->v_fc_config.timings.x_res & 0xFF, 7, 0);
/* set y resolution */
REG_FLD_MOD(base, HDMI_CORE_FC_INVACTIV1,
cfg->v_fc_config.timings.y_res >> 8, 4, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_INVACTIV0,
cfg->v_fc_config.timings.y_res & 0xFF, 7, 0);
/* set horizontal blanking pixels */
REG_FLD_MOD(base, HDMI_CORE_FC_INHBLANK1, cfg->hblank >> 8, 4, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_INHBLANK0, cfg->hblank & 0xFF, 7, 0);
/* set vertial blanking pixels */
REG_FLD_MOD(base, HDMI_CORE_FC_INVBLANK, cfg->vblank, 7, 0);
/* set horizontal sync offset */
REG_FLD_MOD(base, HDMI_CORE_FC_HSYNCINDELAY1,
cfg->v_fc_config.timings.hfp >> 8, 4, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_HSYNCINDELAY0,
cfg->v_fc_config.timings.hfp & 0xFF, 7, 0);
/* set vertical sync offset */
REG_FLD_MOD(base, HDMI_CORE_FC_VSYNCINDELAY,
cfg->v_fc_config.timings.vfp, 7, 0);
/* set horizontal sync pulse width */
REG_FLD_MOD(base, HDMI_CORE_FC_HSYNCINWIDTH1,
(cfg->v_fc_config.timings.hsw >> 8), 1, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_HSYNCINWIDTH0,
cfg->v_fc_config.timings.hsw & 0xFF, 7, 0);
/* set vertical sync pulse width */
REG_FLD_MOD(base, HDMI_CORE_FC_VSYNCINWIDTH,
cfg->v_fc_config.timings.vsw, 5, 0);
/* select DVI mode */
REG_FLD_MOD(base, HDMI_CORE_FC_INVIDCONF,
cfg->v_fc_config.hdmi_dvi_mode, 3, 3);
}
static void hdmi_core_config_video_packetizer(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
int clr_depth = 0; /* 24 bit color depth */
/* COLOR_DEPTH */
REG_FLD_MOD(base, HDMI_CORE_VP_PR_CD, clr_depth, 7, 4);
/* BYPASS_EN */
REG_FLD_MOD(base, HDMI_CORE_VP_CONF, clr_depth ? 0 : 1, 6, 6);
/* PP_EN */
REG_FLD_MOD(base, HDMI_CORE_VP_CONF, clr_depth ? 1 : 0, 5, 5);
/* YCC422_EN */
REG_FLD_MOD(base, HDMI_CORE_VP_CONF, 0, 3, 3);
/* PP_STUFFING */
REG_FLD_MOD(base, HDMI_CORE_VP_STUFF, clr_depth ? 1 : 0, 1, 1);
/* YCC422_STUFFING */
REG_FLD_MOD(base, HDMI_CORE_VP_STUFF, 1, 2, 2);
/* OUTPUT_SELECTOR */
REG_FLD_MOD(base, HDMI_CORE_VP_CONF, clr_depth ? 0 : 2, 1, 0);
}
static void hdmi_core_config_csc(struct hdmi_core_data *core)
{
int clr_depth = 0; /* 24 bit color depth */
/* CSC_COLORDEPTH */
REG_FLD_MOD(core->base, HDMI_CORE_CSC_SCALE, clr_depth, 7, 4);
}
static void hdmi_core_config_video_sampler(struct hdmi_core_data *core)
{
int video_mapping = 1; /* for 24 bit color depth */
/* VIDEO_MAPPING */
REG_FLD_MOD(core->base, HDMI_CORE_TX_INVID0, video_mapping, 4, 0);
}
static void hdmi_core_write_avi_infoframe(struct hdmi_core_data *core,
struct hdmi_avi_infoframe *frame)
{
void __iomem *base = core->base;
u8 data[HDMI_INFOFRAME_SIZE(AVI)];
u8 *ptr;
unsigned y, a, b, s;
unsigned c, m, r;
unsigned itc, ec, q, sc;
unsigned vic;
unsigned yq, cn, pr;
hdmi_avi_infoframe_pack(frame, data, sizeof(data));
print_hex_dump_debug("AVI: ", DUMP_PREFIX_NONE, 16, 1, data,
HDMI_INFOFRAME_SIZE(AVI), false);
ptr = data + HDMI_INFOFRAME_HEADER_SIZE;
y = (ptr[0] >> 5) & 0x3;
a = (ptr[0] >> 4) & 0x1;
b = (ptr[0] >> 2) & 0x3;
s = (ptr[0] >> 0) & 0x3;
c = (ptr[1] >> 6) & 0x3;
m = (ptr[1] >> 4) & 0x3;
r = (ptr[1] >> 0) & 0x3;
itc = (ptr[2] >> 7) & 0x1;
ec = (ptr[2] >> 4) & 0x7;
q = (ptr[2] >> 2) & 0x3;
sc = (ptr[2] >> 0) & 0x3;
vic = ptr[3];
yq = (ptr[4] >> 6) & 0x3;
cn = (ptr[4] >> 4) & 0x3;
pr = (ptr[4] >> 0) & 0xf;
hdmi_write_reg(base, HDMI_CORE_FC_AVICONF0,
(a << 6) | (s << 4) | (b << 2) | (y << 0));
hdmi_write_reg(base, HDMI_CORE_FC_AVICONF1,
(c << 6) | (m << 4) | (r << 0));
hdmi_write_reg(base, HDMI_CORE_FC_AVICONF2,
(itc << 7) | (ec << 4) | (q << 2) | (sc << 0));
hdmi_write_reg(base, HDMI_CORE_FC_AVIVID, vic);
hdmi_write_reg(base, HDMI_CORE_FC_AVICONF3,
(yq << 2) | (cn << 0));
REG_FLD_MOD(base, HDMI_CORE_FC_PRCONF, pr, 3, 0);
}
static void hdmi_core_csc_config(struct hdmi_core_data *core,
struct csc_table csc_coeff)
{
void __iomem *base = core->base;
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A1_MSB, csc_coeff.a1 >> 8 , 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A1_LSB, csc_coeff.a1, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A2_MSB, csc_coeff.a2 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A2_LSB, csc_coeff.a2, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A3_MSB, csc_coeff.a3 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A3_LSB, csc_coeff.a3, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A4_MSB, csc_coeff.a4 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_A4_LSB, csc_coeff.a4, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B1_MSB, csc_coeff.b1 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B1_LSB, csc_coeff.b1, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B2_MSB, csc_coeff.b2 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B2_LSB, csc_coeff.b2, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B3_MSB, csc_coeff.b3 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B3_LSB, csc_coeff.b3, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B4_MSB, csc_coeff.b4 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_B4_LSB, csc_coeff.b4, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C1_MSB, csc_coeff.c1 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C1_LSB, csc_coeff.c1, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C2_MSB, csc_coeff.c2 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C2_LSB, csc_coeff.c2, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C3_MSB, csc_coeff.c3 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C3_LSB, csc_coeff.c3, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C4_MSB, csc_coeff.c4 >> 8, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_CSC_COEF_C4_LSB, csc_coeff.c4, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_MC_FLOWCTRL, 0x1, 0, 0);
}
static void hdmi_core_configure_range(struct hdmi_core_data *core)
{
struct csc_table csc_coeff = { 0 };
/* support limited range with 24 bit color depth for now */
csc_coeff = csc_table_deepcolor[0];
hdmi_core_csc_config(core, csc_coeff);
}
static void hdmi_core_enable_video_path(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
DSSDBG("hdmi_core_enable_video_path\n");
REG_FLD_MOD(base, HDMI_CORE_FC_CTRLDUR, 0x0C, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_EXCTRLDUR, 0x20, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_EXCTRLSPAC, 0x01, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_CH0PREAM, 0x0B, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_CH1PREAM, 0x16, 5, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_CH2PREAM, 0x21, 5, 0);
REG_FLD_MOD(base, HDMI_CORE_MC_CLKDIS, 0x00, 0, 0);
REG_FLD_MOD(base, HDMI_CORE_MC_CLKDIS, 0x00, 1, 1);
}
static void hdmi_core_mask_interrupts(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
/* Master IRQ mask */
REG_FLD_MOD(base, HDMI_CORE_IH_MUTE, 0x3, 1, 0);
/* Mask all the interrupts in HDMI core */
REG_FLD_MOD(base, HDMI_CORE_VP_MASK, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_MASK0, 0xe7, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_MASK1, 0xfb, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_MASK2, 0x3, 1, 0);
REG_FLD_MOD(base, HDMI_CORE_AUD_INT, 0x3, 3, 2);
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_MASK, 0x3, 1, 0);
REG_FLD_MOD(base, HDMI_CORE_CEC_MASK, 0x7f, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 6, 6);
REG_FLD_MOD(base, HDMI_CORE_I2CM_CTLINT, 0x1, 2, 2);
REG_FLD_MOD(base, HDMI_CORE_I2CM_INT, 0x1, 2, 2);
REG_FLD_MOD(base, HDMI_CORE_PHY_MASK0, 0xf3, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_PHY_STAT0, 0xff, 7, 0);
/* Clear all the current interrupt bits */
REG_FLD_MOD(base, HDMI_CORE_IH_VP_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT0, 0xe7, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT1, 0xfb, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT2, 0x3, 1, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_AS_STAT0, 0x7, 2, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_CEC_STAT0, 0x7f, 6, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_I2CM_STAT0, 0x3, 1, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_PHY_STAT0, 0xff, 7, 0);
}
static void hdmi_core_enable_interrupts(struct hdmi_core_data *core)
{
/* Unmute interrupts */
REG_FLD_MOD(core->base, HDMI_CORE_IH_MUTE, 0x0, 1, 0);
}
int hdmi5_core_handle_irqs(struct hdmi_core_data *core)
{
void __iomem *base = core->base;
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT1, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_FC_STAT2, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_AS_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_PHY_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_I2CM_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_CEC_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_VP_STAT0, 0xff, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_IH_I2CMPHY_STAT0, 0xff, 7, 0);
return 0;
}
void hdmi5_configure(struct hdmi_core_data *core, struct hdmi_wp_data *wp,
struct hdmi_config *cfg)
{
struct omap_video_timings video_timing;
struct hdmi_video_format video_format;
struct hdmi_core_vid_config v_core_cfg;
hdmi_core_mask_interrupts(core);
hdmi_core_init(&v_core_cfg, cfg);
hdmi_wp_init_vid_fmt_timings(&video_format, &video_timing, cfg);
hdmi_wp_video_config_timing(wp, &video_timing);
/* video config */
video_format.packing_mode = HDMI_PACK_24b_RGB_YUV444_YUV422;
hdmi_wp_video_config_format(wp, &video_format);
hdmi_wp_video_config_interface(wp, &video_timing);
/* support limited range with 24 bit color depth for now */
hdmi_core_configure_range(core);
cfg->infoframe.quantization_range = HDMI_QUANTIZATION_RANGE_LIMITED;
/*
* configure core video part, set software reset in the core
*/
v_core_cfg.packet_mode = HDMI_PACKETMODE24BITPERPIXEL;
hdmi_core_video_config(core, &v_core_cfg);
hdmi_core_config_video_packetizer(core);
hdmi_core_config_csc(core);
hdmi_core_config_video_sampler(core);
if (cfg->hdmi_dvi_mode == HDMI_HDMI)
hdmi_core_write_avi_infoframe(core, &cfg->infoframe);
hdmi_core_enable_video_path(core);
hdmi_core_enable_interrupts(core);
}
static void hdmi5_core_audio_config(struct hdmi_core_data *core,
struct hdmi_core_audio_config *cfg)
{
void __iomem *base = core->base;
u8 val;
/* Mute audio before configuring */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCONF, 0xf, 7, 4);
/* Set the N parameter */
REG_FLD_MOD(base, HDMI_CORE_AUD_N1, cfg->n, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_AUD_N2, cfg->n >> 8, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_AUD_N3, cfg->n >> 16, 3, 0);
/*
* CTS manual mode. Automatic mode is not supported when using audio
* parallel interface.
*/
REG_FLD_MOD(base, HDMI_CORE_AUD_CTS3, 1, 4, 4);
REG_FLD_MOD(base, HDMI_CORE_AUD_CTS1, cfg->cts, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_AUD_CTS2, cfg->cts >> 8, 7, 0);
REG_FLD_MOD(base, HDMI_CORE_AUD_CTS3, cfg->cts >> 16, 3, 0);
/* Layout of Audio Sample Packets: 2-channel or multichannels */
if (cfg->layout == HDMI_AUDIO_LAYOUT_2CH)
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCONF, 0, 0, 0);
else
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCONF, 1, 0, 0);
/* Configure IEC-609580 Validity bits */
/* Channel 0 is valid */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, 0, 0, 0);
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, 0, 4, 4);
if (cfg->layout == HDMI_AUDIO_LAYOUT_2CH)
val = 1;
else
val = 0;
/* Channels 1, 2 setting */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 1, 1);
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 5, 5);
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 2, 2);
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 6, 6);
/* Channel 3 setting */
if (cfg->layout == HDMI_AUDIO_LAYOUT_6CH)
val = 1;
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 3, 3);
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSV, val, 7, 7);
/* Configure IEC-60958 User bits */
/* TODO: should be set by user. */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSU, 0, 7, 0);
/* Configure IEC-60958 Channel Status word */
/* CGMSA */
val = cfg->iec60958_cfg->status[5] & IEC958_AES5_CON_CGMSA;
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(0), val, 5, 4);
/* Copyright */
val = (cfg->iec60958_cfg->status[0] &
IEC958_AES0_CON_NOT_COPYRIGHT) >> 2;
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(0), val, 0, 0);
/* Category */
hdmi_write_reg(base, HDMI_CORE_FC_AUDSCHNLS(1),
cfg->iec60958_cfg->status[1]);
/* PCM audio mode */
val = (cfg->iec60958_cfg->status[0] & IEC958_AES0_CON_MODE) >> 6;
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(2), val, 6, 4);
/* Source number */
val = cfg->iec60958_cfg->status[2] & IEC958_AES2_CON_SOURCE;
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(2), val, 3, 0);
/* Channel number right 0 */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(3), 2, 3, 0);
/* Channel number right 1*/
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(3), 4, 7, 4);
/* Channel number right 2 */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(4), 6, 3, 0);
/* Channel number right 3*/
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(4), 8, 7, 4);
/* Channel number left 0 */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(5), 1, 3, 0);
/* Channel number left 1*/
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(5), 3, 7, 4);
/* Channel number left 2 */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(6), 5, 3, 0);
/* Channel number left 3*/
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCHNLS(6), 7, 7, 4);
/* Clock accuracy and sample rate */
hdmi_write_reg(base, HDMI_CORE_FC_AUDSCHNLS(7),
cfg->iec60958_cfg->status[3]);
/* Original sample rate and word length */
hdmi_write_reg(base, HDMI_CORE_FC_AUDSCHNLS(8),
cfg->iec60958_cfg->status[4]);
/* Enable FIFO empty and full interrupts */
REG_FLD_MOD(base, HDMI_CORE_AUD_INT, 3, 3, 2);
/* Configure GPA */
/* select HBR/SPDIF interfaces */
if (cfg->layout == HDMI_AUDIO_LAYOUT_2CH) {
/* select HBR/SPDIF interfaces */
REG_FLD_MOD(base, HDMI_CORE_AUD_CONF0, 0, 5, 5);
/* enable two channels in GPA */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_CONF1, 3, 7, 0);
} else if (cfg->layout == HDMI_AUDIO_LAYOUT_6CH) {
/* select HBR/SPDIF interfaces */
REG_FLD_MOD(base, HDMI_CORE_AUD_CONF0, 0, 5, 5);
/* enable six channels in GPA */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_CONF1, 0x3F, 7, 0);
} else {
/* select HBR/SPDIF interfaces */
REG_FLD_MOD(base, HDMI_CORE_AUD_CONF0, 0, 5, 5);
/* enable eight channels in GPA */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_CONF1, 0xFF, 7, 0);
}
/* disable HBR */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_CONF2, 0, 0, 0);
/* enable PCUV */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_CONF2, 1, 1, 1);
/* enable GPA FIFO full and empty mask */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_MASK, 3, 1, 0);
/* set polarity of GPA FIFO empty interrupts */
REG_FLD_MOD(base, HDMI_CORE_AUD_GP_POL, 1, 0, 0);
/* unmute audio */
REG_FLD_MOD(base, HDMI_CORE_FC_AUDSCONF, 0, 7, 4);
}
static void hdmi5_core_audio_infoframe_cfg(struct hdmi_core_data *core,
struct snd_cea_861_aud_if *info_aud)
{
void __iomem *base = core->base;
/* channel count and coding type fields in AUDICONF0 are swapped */
hdmi_write_reg(base, HDMI_CORE_FC_AUDICONF0,
(info_aud->db1_ct_cc & CEA861_AUDIO_INFOFRAME_DB1CC) << 4 |
(info_aud->db1_ct_cc & CEA861_AUDIO_INFOFRAME_DB1CT) >> 4);
hdmi_write_reg(base, HDMI_CORE_FC_AUDICONF1, info_aud->db2_sf_ss);
hdmi_write_reg(base, HDMI_CORE_FC_AUDICONF2, info_aud->db4_ca);
hdmi_write_reg(base, HDMI_CORE_FC_AUDICONF3,
(info_aud->db5_dminh_lsv & CEA861_AUDIO_INFOFRAME_DB5_DM_INH) >> 3 |
(info_aud->db5_dminh_lsv & CEA861_AUDIO_INFOFRAME_DB5_LSV));
}
int hdmi5_audio_config(struct hdmi_core_data *core, struct hdmi_wp_data *wp,
struct omap_dss_audio *audio, u32 pclk)
{
struct hdmi_audio_format audio_format;
struct hdmi_audio_dma audio_dma;
struct hdmi_core_audio_config core_cfg;
int err, n, cts, channel_count;
unsigned int fs_nr;
bool word_length_16b = false;
if (!audio || !audio->iec || !audio->cea || !core)
return -EINVAL;
core_cfg.iec60958_cfg = audio->iec;
if (!(audio->iec->status[4] & IEC958_AES4_CON_MAX_WORDLEN_24) &&
(audio->iec->status[4] & IEC958_AES4_CON_WORDLEN_20_16))
word_length_16b = true;
/* only 16-bit word length supported atm */
if (!word_length_16b)
return -EINVAL;
switch (audio->iec->status[3] & IEC958_AES3_CON_FS) {
case IEC958_AES3_CON_FS_32000:
fs_nr = 32000;
break;
case IEC958_AES3_CON_FS_44100:
fs_nr = 44100;
break;
case IEC958_AES3_CON_FS_48000:
fs_nr = 48000;
break;
case IEC958_AES3_CON_FS_88200:
fs_nr = 88200;
break;
case IEC958_AES3_CON_FS_96000:
fs_nr = 96000;
break;
case IEC958_AES3_CON_FS_176400:
fs_nr = 176400;
break;
case IEC958_AES3_CON_FS_192000:
fs_nr = 192000;
break;
default:
return -EINVAL;
}
err = hdmi_compute_acr(pclk, fs_nr, &n, &cts);
core_cfg.n = n;
core_cfg.cts = cts;
/* Audio channels settings */
channel_count = (audio->cea->db1_ct_cc & CEA861_AUDIO_INFOFRAME_DB1CC)
+ 1;
if (channel_count == 2)
core_cfg.layout = HDMI_AUDIO_LAYOUT_2CH;
else if (channel_count == 6)
core_cfg.layout = HDMI_AUDIO_LAYOUT_6CH;
else
core_cfg.layout = HDMI_AUDIO_LAYOUT_8CH;
/* DMA settings */
if (word_length_16b)
audio_dma.transfer_size = 0x10;
else
audio_dma.transfer_size = 0x20;
audio_dma.block_size = 0xC0;
audio_dma.mode = HDMI_AUDIO_TRANSF_DMA;
audio_dma.fifo_threshold = 0x20; /* in number of samples */
/* audio FIFO format settings for 16-bit samples*/
audio_format.samples_per_word = HDMI_AUDIO_ONEWORD_TWOSAMPLES;
audio_format.sample_size = HDMI_AUDIO_SAMPLE_16BITS;
audio_format.justification = HDMI_AUDIO_JUSTIFY_LEFT;
audio_format.sample_order = HDMI_AUDIO_SAMPLE_LEFT_FIRST;
/* only LPCM atm */
audio_format.type = HDMI_AUDIO_TYPE_LPCM;
/* only allowed option */
audio_format.sample_order = HDMI_AUDIO_SAMPLE_LEFT_FIRST;
/* disable start/stop signals of IEC 60958 blocks */
audio_format.en_sig_blk_strt_end = HDMI_AUDIO_BLOCK_SIG_STARTEND_ON;
/* configure DMA and audio FIFO format*/
hdmi_wp_audio_config_dma(wp, &audio_dma);
hdmi_wp_audio_config_format(wp, &audio_format);
/* configure the core */
hdmi5_core_audio_config(core, &core_cfg);
/* configure CEA 861 audio infoframe */
hdmi5_core_audio_infoframe_cfg(core, audio->cea);
return 0;
}
int hdmi5_core_init(struct platform_device *pdev, struct hdmi_core_data *core)
{
struct resource *res;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "core");
if (!res) {
DSSERR("can't get CORE IORESOURCE_MEM HDMI\n");
return -EINVAL;
}
core->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(core->base)) {
DSSERR("can't ioremap HDMI core\n");
return PTR_ERR(core->base);
}
return 0;
}
| gpl-2.0 |
coreos/linux-deprecated | arch/mips/math-emu/dp_sub.c | 685 | 4798 | /* IEEE754 floating point arithmetic
* double precision: common utilities
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ieee754dp.h"
union ieee754dp ieee754dp_sub(union ieee754dp x, union ieee754dp y)
{
int s;
COMPXDP;
COMPYDP;
EXPLODEXDP;
EXPLODEYDP;
ieee754_clearcx();
FLUSHXDP;
FLUSHYDP;
switch (CLPAIR(xc, yc)) {
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_INF):
ieee754_setcx(IEEE754_INVALID_OPERATION);
return ieee754dp_nanxcpt(ieee754dp_indef());
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_QNAN):
return y;
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_INF):
return x;
/*
* Infinity handling
*/
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_INF):
if (xs != ys)
return x;
ieee754_setcx(IEEE754_INVALID_OPERATION);
return ieee754dp_indef();
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_INF):
return ieee754dp_inf(ys ^ 1);
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_DNORM):
return x;
/*
* Zero handling
*/
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_ZERO):
if (xs != ys)
return x;
else
return ieee754dp_zero(ieee754_csr.rm == FPU_CSR_RD);
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_ZERO):
return x;
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_DNORM):
/* quick fix up */
DPSIGN(y) ^= 1;
return y;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_DNORM):
DPDNORMX;
/* FALL THROUGH */
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_DNORM):
/* normalize ym,ye */
DPDNORMY;
break;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_NORM):
/* normalize xm,xe */
DPDNORMX;
break;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_NORM):
break;
}
/* flip sign of y and handle as add */
ys ^= 1;
assert(xm & DP_HIDDEN_BIT);
assert(ym & DP_HIDDEN_BIT);
/* provide guard,round and stick bit dpace */
xm <<= 3;
ym <<= 3;
if (xe > ye) {
/*
* Have to shift y fraction right to align
*/
s = xe - ye;
ym = XDPSRS(ym, s);
ye += s;
} else if (ye > xe) {
/*
* Have to shift x fraction right to align
*/
s = ye - xe;
xm = XDPSRS(xm, s);
xe += s;
}
assert(xe == ye);
assert(xe <= DP_EMAX);
if (xs == ys) {
/* generate 28 bit result of adding two 27 bit numbers
*/
xm = xm + ym;
xe = xe;
xs = xs;
if (xm >> (DP_FBITS + 1 + 3)) { /* carry out */
xm = XDPSRS1(xm); /* shift preserving sticky */
xe++;
}
} else {
if (xm >= ym) {
xm = xm - ym;
xe = xe;
xs = xs;
} else {
xm = ym - xm;
xe = xe;
xs = ys;
}
if (xm == 0) {
if (ieee754_csr.rm == FPU_CSR_RD)
return ieee754dp_zero(1); /* round negative inf. => sign = -1 */
else
return ieee754dp_zero(0); /* other round modes => sign = 1 */
}
/* normalize to rounding precision
*/
while ((xm >> (DP_FBITS + 3)) == 0) {
xm <<= 1;
xe--;
}
}
return ieee754dp_format(xs, xe, xm);
}
| gpl-2.0 |
akiradeveloper/linux | drivers/clk/ux500/u8540_clk.c | 1453 | 20133 | /*
* Clock definitions for u8540 platform.
*
* Copyright (C) 2012 ST-Ericsson SA
* Author: Ulf Hansson <ulf.hansson@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/clk-provider.h>
#include <linux/mfd/dbx500-prcmu.h>
#include <linux/platform_data/clk-ux500.h>
#include "clk.h"
void u8540_clk_init(u32 clkrst1_base, u32 clkrst2_base, u32 clkrst3_base,
u32 clkrst5_base, u32 clkrst6_base)
{
struct clk *clk;
/* Clock sources. */
/* Fixed ClockGen */
clk = clk_reg_prcmu_gate("soc0_pll", NULL, PRCMU_PLLSOC0,
CLK_IS_ROOT|CLK_IGNORE_UNUSED);
clk_register_clkdev(clk, "soc0_pll", NULL);
clk = clk_reg_prcmu_gate("soc1_pll", NULL, PRCMU_PLLSOC1,
CLK_IS_ROOT|CLK_IGNORE_UNUSED);
clk_register_clkdev(clk, "soc1_pll", NULL);
clk = clk_reg_prcmu_gate("ddr_pll", NULL, PRCMU_PLLDDR,
CLK_IS_ROOT|CLK_IGNORE_UNUSED);
clk_register_clkdev(clk, "ddr_pll", NULL);
clk = clk_register_fixed_rate(NULL, "rtc32k", NULL,
CLK_IS_ROOT|CLK_IGNORE_UNUSED,
32768);
clk_register_clkdev(clk, "clk32k", NULL);
clk_register_clkdev(clk, "apb_pclk", "rtc-pl031");
clk = clk_register_fixed_rate(NULL, "ulp38m4", NULL,
CLK_IS_ROOT|CLK_IGNORE_UNUSED,
38400000);
clk = clk_reg_prcmu_gate("uartclk", NULL, PRCMU_UARTCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "UART");
/* msp02clk needs a abx500 clk as parent. Handle by abx500 clk driver */
clk = clk_reg_prcmu_gate("msp02clk", "ab9540_sysclk12_b1",
PRCMU_MSP02CLK, 0);
clk_register_clkdev(clk, NULL, "MSP02");
clk = clk_reg_prcmu_gate("msp1clk", NULL, PRCMU_MSP1CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "MSP1");
clk = clk_reg_prcmu_gate("i2cclk", NULL, PRCMU_I2CCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "I2C");
clk = clk_reg_prcmu_gate("slimclk", NULL, PRCMU_SLIMCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "slim");
clk = clk_reg_prcmu_gate("per1clk", NULL, PRCMU_PER1CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH1");
clk = clk_reg_prcmu_gate("per2clk", NULL, PRCMU_PER2CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH2");
clk = clk_reg_prcmu_gate("per3clk", NULL, PRCMU_PER3CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH3");
clk = clk_reg_prcmu_gate("per5clk", NULL, PRCMU_PER5CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH5");
clk = clk_reg_prcmu_gate("per6clk", NULL, PRCMU_PER6CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH6");
clk = clk_reg_prcmu_gate("per7clk", NULL, PRCMU_PER7CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "PERIPH7");
clk = clk_reg_prcmu_scalable("lcdclk", NULL, PRCMU_LCDCLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "lcd");
clk_register_clkdev(clk, "lcd", "mcde");
clk = clk_reg_prcmu_opp_gate("bmlclk", NULL, PRCMU_BMLCLK,
CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "bml");
clk = clk_reg_prcmu_scalable("hsitxclk", NULL, PRCMU_HSITXCLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk = clk_reg_prcmu_scalable("hsirxclk", NULL, PRCMU_HSIRXCLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk = clk_reg_prcmu_scalable("hdmiclk", NULL, PRCMU_HDMICLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "hdmi");
clk_register_clkdev(clk, "hdmi", "mcde");
clk = clk_reg_prcmu_gate("apeatclk", NULL, PRCMU_APEATCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "apeat");
clk = clk_reg_prcmu_gate("apetraceclk", NULL, PRCMU_APETRACECLK,
CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "apetrace");
clk = clk_reg_prcmu_gate("mcdeclk", NULL, PRCMU_MCDECLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "mcde");
clk_register_clkdev(clk, "mcde", "mcde");
clk_register_clkdev(clk, NULL, "dsilink.0");
clk_register_clkdev(clk, NULL, "dsilink.1");
clk_register_clkdev(clk, NULL, "dsilink.2");
clk = clk_reg_prcmu_opp_gate("ipi2cclk", NULL, PRCMU_IPI2CCLK,
CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "ipi2");
clk = clk_reg_prcmu_gate("dsialtclk", NULL, PRCMU_DSIALTCLK,
CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "dsialt");
clk = clk_reg_prcmu_gate("dmaclk", NULL, PRCMU_DMACLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "dma40.0");
clk = clk_reg_prcmu_gate("b2r2clk", NULL, PRCMU_B2R2CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "b2r2");
clk_register_clkdev(clk, NULL, "b2r2_core");
clk_register_clkdev(clk, NULL, "U8500-B2R2.0");
clk_register_clkdev(clk, NULL, "b2r2_1_core");
clk = clk_reg_prcmu_scalable("tvclk", NULL, PRCMU_TVCLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "tv");
clk_register_clkdev(clk, "tv", "mcde");
clk = clk_reg_prcmu_gate("sspclk", NULL, PRCMU_SSPCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "SSP");
clk = clk_reg_prcmu_gate("rngclk", NULL, PRCMU_RNGCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "rngclk");
clk = clk_reg_prcmu_gate("uiccclk", NULL, PRCMU_UICCCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "uicc");
clk = clk_reg_prcmu_gate("timclk", NULL, PRCMU_TIMCLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "mtu0");
clk_register_clkdev(clk, NULL, "mtu1");
clk = clk_reg_prcmu_opp_volt_scalable("sdmmcclk", NULL,
PRCMU_SDMMCCLK, 100000000,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdmmc");
clk = clk_reg_prcmu_opp_volt_scalable("sdmmchclk", NULL,
PRCMU_SDMMCHCLK, 400000000,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdmmchclk");
clk = clk_reg_prcmu_gate("hvaclk", NULL, PRCMU_HVACLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "hva");
clk = clk_reg_prcmu_gate("g1clk", NULL, PRCMU_G1CLK, CLK_IS_ROOT);
clk_register_clkdev(clk, NULL, "g1");
clk = clk_reg_prcmu_scalable("spare1clk", NULL, PRCMU_SPARE1CLK, 0,
CLK_IS_ROOT|CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsilcd", "mcde");
clk = clk_reg_prcmu_scalable("dsi_pll", "hdmiclk",
PRCMU_PLLDSI, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsihs2", "mcde");
clk_register_clkdev(clk, "hs_clk", "dsilink.2");
clk = clk_reg_prcmu_scalable("dsilcd_pll", "spare1clk",
PRCMU_PLLDSI_LCD, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsilcd_pll", "mcde");
clk = clk_reg_prcmu_scalable("dsi0clk", "dsi_pll",
PRCMU_DSI0CLK, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsihs0", "mcde");
clk = clk_reg_prcmu_scalable("dsi0lcdclk", "dsilcd_pll",
PRCMU_DSI0CLK_LCD, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsihs0", "mcde");
clk_register_clkdev(clk, "hs_clk", "dsilink.0");
clk = clk_reg_prcmu_scalable("dsi1clk", "dsi_pll",
PRCMU_DSI1CLK, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsihs1", "mcde");
clk = clk_reg_prcmu_scalable("dsi1lcdclk", "dsilcd_pll",
PRCMU_DSI1CLK_LCD, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "dsihs1", "mcde");
clk_register_clkdev(clk, "hs_clk", "dsilink.1");
clk = clk_reg_prcmu_scalable("dsi0escclk", "tvclk",
PRCMU_DSI0ESCCLK, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "lp_clk", "dsilink.0");
clk_register_clkdev(clk, "dsilp0", "mcde");
clk = clk_reg_prcmu_scalable("dsi1escclk", "tvclk",
PRCMU_DSI1ESCCLK, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "lp_clk", "dsilink.1");
clk_register_clkdev(clk, "dsilp1", "mcde");
clk = clk_reg_prcmu_scalable("dsi2escclk", "tvclk",
PRCMU_DSI2ESCCLK, 0, CLK_SET_RATE_GATE);
clk_register_clkdev(clk, "lp_clk", "dsilink.2");
clk_register_clkdev(clk, "dsilp2", "mcde");
clk = clk_reg_prcmu_scalable_rate("armss", NULL,
PRCMU_ARMSS, 0, CLK_IS_ROOT|CLK_IGNORE_UNUSED);
clk_register_clkdev(clk, "armss", NULL);
clk = clk_register_fixed_factor(NULL, "smp_twd", "armss",
CLK_IGNORE_UNUSED, 1, 2);
clk_register_clkdev(clk, NULL, "smp_twd");
/* PRCC P-clocks */
/* Peripheral 1 : PRCC P-clocks */
clk = clk_reg_prcc_pclk("p1_pclk0", "per1clk", clkrst1_base,
BIT(0), 0);
clk_register_clkdev(clk, "apb_pclk", "uart0");
clk = clk_reg_prcc_pclk("p1_pclk1", "per1clk", clkrst1_base,
BIT(1), 0);
clk_register_clkdev(clk, "apb_pclk", "uart1");
clk = clk_reg_prcc_pclk("p1_pclk2", "per1clk", clkrst1_base,
BIT(2), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.1");
clk = clk_reg_prcc_pclk("p1_pclk3", "per1clk", clkrst1_base,
BIT(3), 0);
clk_register_clkdev(clk, "apb_pclk", "msp0");
clk_register_clkdev(clk, "apb_pclk", "dbx5x0-msp-i2s.0");
clk = clk_reg_prcc_pclk("p1_pclk4", "per1clk", clkrst1_base,
BIT(4), 0);
clk_register_clkdev(clk, "apb_pclk", "msp1");
clk_register_clkdev(clk, "apb_pclk", "dbx5x0-msp-i2s.1");
clk = clk_reg_prcc_pclk("p1_pclk5", "per1clk", clkrst1_base,
BIT(5), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi0");
clk = clk_reg_prcc_pclk("p1_pclk6", "per1clk", clkrst1_base,
BIT(6), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.2");
clk = clk_reg_prcc_pclk("p1_pclk7", "per1clk", clkrst1_base,
BIT(7), 0);
clk_register_clkdev(clk, NULL, "spi3");
clk = clk_reg_prcc_pclk("p1_pclk8", "per1clk", clkrst1_base,
BIT(8), 0);
clk_register_clkdev(clk, "apb_pclk", "slimbus0");
clk = clk_reg_prcc_pclk("p1_pclk9", "per1clk", clkrst1_base,
BIT(9), 0);
clk_register_clkdev(clk, NULL, "gpio.0");
clk_register_clkdev(clk, NULL, "gpio.1");
clk_register_clkdev(clk, NULL, "gpioblock0");
clk_register_clkdev(clk, "apb_pclk", "ab85xx-codec.0");
clk = clk_reg_prcc_pclk("p1_pclk10", "per1clk", clkrst1_base,
BIT(10), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.4");
clk = clk_reg_prcc_pclk("p1_pclk11", "per1clk", clkrst1_base,
BIT(11), 0);
clk_register_clkdev(clk, "apb_pclk", "msp3");
clk_register_clkdev(clk, "apb_pclk", "dbx5x0-msp-i2s.3");
/* Peripheral 2 : PRCC P-clocks */
clk = clk_reg_prcc_pclk("p2_pclk0", "per2clk", clkrst2_base,
BIT(0), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.3");
clk = clk_reg_prcc_pclk("p2_pclk1", "per2clk", clkrst2_base,
BIT(1), 0);
clk_register_clkdev(clk, NULL, "spi2");
clk = clk_reg_prcc_pclk("p2_pclk2", "per2clk", clkrst2_base,
BIT(2), 0);
clk_register_clkdev(clk, NULL, "spi1");
clk = clk_reg_prcc_pclk("p2_pclk3", "per2clk", clkrst2_base,
BIT(3), 0);
clk_register_clkdev(clk, NULL, "pwl");
clk = clk_reg_prcc_pclk("p2_pclk4", "per2clk", clkrst2_base,
BIT(4), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi4");
clk = clk_reg_prcc_pclk("p2_pclk5", "per2clk", clkrst2_base,
BIT(5), 0);
clk_register_clkdev(clk, "apb_pclk", "msp2");
clk_register_clkdev(clk, "apb_pclk", "dbx5x0-msp-i2s.2");
clk = clk_reg_prcc_pclk("p2_pclk6", "per2clk", clkrst2_base,
BIT(6), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi1");
clk = clk_reg_prcc_pclk("p2_pclk7", "per2clk", clkrst2_base,
BIT(7), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi3");
clk = clk_reg_prcc_pclk("p2_pclk8", "per2clk", clkrst2_base,
BIT(8), 0);
clk_register_clkdev(clk, NULL, "spi0");
clk = clk_reg_prcc_pclk("p2_pclk9", "per2clk", clkrst2_base,
BIT(9), 0);
clk_register_clkdev(clk, "hsir_hclk", "ste_hsi.0");
clk = clk_reg_prcc_pclk("p2_pclk10", "per2clk", clkrst2_base,
BIT(10), 0);
clk_register_clkdev(clk, "hsit_hclk", "ste_hsi.0");
clk = clk_reg_prcc_pclk("p2_pclk11", "per2clk", clkrst2_base,
BIT(11), 0);
clk_register_clkdev(clk, NULL, "gpio.6");
clk_register_clkdev(clk, NULL, "gpio.7");
clk_register_clkdev(clk, NULL, "gpioblock1");
clk = clk_reg_prcc_pclk("p2_pclk12", "per2clk", clkrst2_base,
BIT(12), 0);
clk_register_clkdev(clk, "msp4-pclk", "ab85xx-codec.0");
/* Peripheral 3 : PRCC P-clocks */
clk = clk_reg_prcc_pclk("p3_pclk0", "per3clk", clkrst3_base,
BIT(0), 0);
clk_register_clkdev(clk, NULL, "fsmc");
clk = clk_reg_prcc_pclk("p3_pclk1", "per3clk", clkrst3_base,
BIT(1), 0);
clk_register_clkdev(clk, "apb_pclk", "ssp0");
clk = clk_reg_prcc_pclk("p3_pclk2", "per3clk", clkrst3_base,
BIT(2), 0);
clk_register_clkdev(clk, "apb_pclk", "ssp1");
clk = clk_reg_prcc_pclk("p3_pclk3", "per3clk", clkrst3_base,
BIT(3), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.0");
clk = clk_reg_prcc_pclk("p3_pclk4", "per3clk", clkrst3_base,
BIT(4), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi2");
clk = clk_reg_prcc_pclk("p3_pclk5", "per3clk", clkrst3_base,
BIT(5), 0);
clk_register_clkdev(clk, "apb_pclk", "ske");
clk_register_clkdev(clk, "apb_pclk", "nmk-ske-keypad");
clk = clk_reg_prcc_pclk("p3_pclk6", "per3clk", clkrst3_base,
BIT(6), 0);
clk_register_clkdev(clk, "apb_pclk", "uart2");
clk = clk_reg_prcc_pclk("p3_pclk7", "per3clk", clkrst3_base,
BIT(7), 0);
clk_register_clkdev(clk, "apb_pclk", "sdi5");
clk = clk_reg_prcc_pclk("p3_pclk8", "per3clk", clkrst3_base,
BIT(8), 0);
clk_register_clkdev(clk, NULL, "gpio.2");
clk_register_clkdev(clk, NULL, "gpio.3");
clk_register_clkdev(clk, NULL, "gpio.4");
clk_register_clkdev(clk, NULL, "gpio.5");
clk_register_clkdev(clk, NULL, "gpioblock2");
clk = clk_reg_prcc_pclk("p3_pclk9", "per3clk", clkrst3_base,
BIT(9), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.5");
clk = clk_reg_prcc_pclk("p3_pclk10", "per3clk", clkrst3_base,
BIT(10), 0);
clk_register_clkdev(clk, "apb_pclk", "nmk-i2c.6");
clk = clk_reg_prcc_pclk("p3_pclk11", "per3clk", clkrst3_base,
BIT(11), 0);
clk_register_clkdev(clk, "apb_pclk", "uart3");
clk = clk_reg_prcc_pclk("p3_pclk12", "per3clk", clkrst3_base,
BIT(12), 0);
clk_register_clkdev(clk, "apb_pclk", "uart4");
/* Peripheral 5 : PRCC P-clocks */
clk = clk_reg_prcc_pclk("p5_pclk0", "per5clk", clkrst5_base,
BIT(0), 0);
clk_register_clkdev(clk, "usb", "musb-ux500.0");
clk_register_clkdev(clk, "usbclk", "ab-iddet.0");
clk = clk_reg_prcc_pclk("p5_pclk1", "per5clk", clkrst5_base,
BIT(1), 0);
clk_register_clkdev(clk, NULL, "gpio.8");
clk_register_clkdev(clk, NULL, "gpioblock3");
/* Peripheral 6 : PRCC P-clocks */
clk = clk_reg_prcc_pclk("p6_pclk0", "per6clk", clkrst6_base,
BIT(0), 0);
clk_register_clkdev(clk, "apb_pclk", "rng");
clk = clk_reg_prcc_pclk("p6_pclk1", "per6clk", clkrst6_base,
BIT(1), 0);
clk_register_clkdev(clk, NULL, "cryp0");
clk_register_clkdev(clk, NULL, "cryp1");
clk = clk_reg_prcc_pclk("p6_pclk2", "per6clk", clkrst6_base,
BIT(2), 0);
clk_register_clkdev(clk, NULL, "hash0");
clk = clk_reg_prcc_pclk("p6_pclk3", "per6clk", clkrst6_base,
BIT(3), 0);
clk_register_clkdev(clk, NULL, "pka");
clk = clk_reg_prcc_pclk("p6_pclk4", "per6clk", clkrst6_base,
BIT(4), 0);
clk_register_clkdev(clk, NULL, "db8540-hash1");
clk = clk_reg_prcc_pclk("p6_pclk5", "per6clk", clkrst6_base,
BIT(5), 0);
clk_register_clkdev(clk, NULL, "cfgreg");
clk = clk_reg_prcc_pclk("p6_pclk6", "per6clk", clkrst6_base,
BIT(6), 0);
clk_register_clkdev(clk, "apb_pclk", "mtu0");
clk = clk_reg_prcc_pclk("p6_pclk7", "per6clk", clkrst6_base,
BIT(7), 0);
clk_register_clkdev(clk, "apb_pclk", "mtu1");
/*
* PRCC K-clocks ==> see table PRCC_PCKEN/PRCC_KCKEN
* This differs from the internal implementation:
* We don't use the PERPIH[n| clock as parent, since those _should_
* only be used as parents for the P-clocks.
* TODO: "parentjoin" with corresponding P-clocks for all K-clocks.
*/
/* Peripheral 1 : PRCC K-clocks */
clk = clk_reg_prcc_kclk("p1_uart0_kclk", "uartclk",
clkrst1_base, BIT(0), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "uart0");
clk = clk_reg_prcc_kclk("p1_uart1_kclk", "uartclk",
clkrst1_base, BIT(1), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "uart1");
clk = clk_reg_prcc_kclk("p1_i2c1_kclk", "i2cclk",
clkrst1_base, BIT(2), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.1");
clk = clk_reg_prcc_kclk("p1_msp0_kclk", "msp02clk",
clkrst1_base, BIT(3), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "msp0");
clk_register_clkdev(clk, NULL, "dbx5x0-msp-i2s.0");
clk = clk_reg_prcc_kclk("p1_msp1_kclk", "msp1clk",
clkrst1_base, BIT(4), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "msp1");
clk_register_clkdev(clk, NULL, "dbx5x0-msp-i2s.1");
clk = clk_reg_prcc_kclk("p1_sdi0_kclk", "sdmmchclk",
clkrst1_base, BIT(5), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi0");
clk = clk_reg_prcc_kclk("p1_i2c2_kclk", "i2cclk",
clkrst1_base, BIT(6), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.2");
clk = clk_reg_prcc_kclk("p1_slimbus0_kclk", "slimclk",
clkrst1_base, BIT(8), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "slimbus0");
clk = clk_reg_prcc_kclk("p1_i2c4_kclk", "i2cclk",
clkrst1_base, BIT(9), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.4");
clk = clk_reg_prcc_kclk("p1_msp3_kclk", "msp1clk",
clkrst1_base, BIT(10), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "msp3");
clk_register_clkdev(clk, NULL, "dbx5x0-msp-i2s.3");
/* Peripheral 2 : PRCC K-clocks */
clk = clk_reg_prcc_kclk("p2_i2c3_kclk", "i2cclk",
clkrst2_base, BIT(0), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.3");
clk = clk_reg_prcc_kclk("p2_pwl_kclk", "rtc32k",
clkrst2_base, BIT(1), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "pwl");
clk = clk_reg_prcc_kclk("p2_sdi4_kclk", "sdmmchclk",
clkrst2_base, BIT(2), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi4");
clk = clk_reg_prcc_kclk("p2_msp2_kclk", "msp02clk",
clkrst2_base, BIT(3), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "msp2");
clk_register_clkdev(clk, NULL, "dbx5x0-msp-i2s.2");
clk = clk_reg_prcc_kclk("p2_sdi1_kclk", "sdmmchclk",
clkrst2_base, BIT(4), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi1");
clk = clk_reg_prcc_kclk("p2_sdi3_kclk", "sdmmcclk",
clkrst2_base, BIT(5), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi3");
clk = clk_reg_prcc_kclk("p2_ssirx_kclk", "hsirxclk",
clkrst2_base, BIT(6),
CLK_SET_RATE_GATE|CLK_SET_RATE_PARENT);
clk_register_clkdev(clk, "hsir_hsirxclk", "ste_hsi.0");
clk = clk_reg_prcc_kclk("p2_ssitx_kclk", "hsitxclk",
clkrst2_base, BIT(7),
CLK_SET_RATE_GATE|CLK_SET_RATE_PARENT);
clk_register_clkdev(clk, "hsit_hsitxclk", "ste_hsi.0");
/* Should only be 9540, but might be added for 85xx as well */
clk = clk_reg_prcc_kclk("p2_msp4_kclk", "msp02clk",
clkrst2_base, BIT(9), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "msp4");
clk_register_clkdev(clk, "msp4", "ab85xx-codec.0");
/* Peripheral 3 : PRCC K-clocks */
clk = clk_reg_prcc_kclk("p3_ssp0_kclk", "sspclk",
clkrst3_base, BIT(1), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "ssp0");
clk = clk_reg_prcc_kclk("p3_ssp1_kclk", "sspclk",
clkrst3_base, BIT(2), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "ssp1");
clk = clk_reg_prcc_kclk("p3_i2c0_kclk", "i2cclk",
clkrst3_base, BIT(3), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.0");
clk = clk_reg_prcc_kclk("p3_sdi2_kclk", "sdmmchclk",
clkrst3_base, BIT(4), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi2");
clk = clk_reg_prcc_kclk("p3_ske_kclk", "rtc32k",
clkrst3_base, BIT(5), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "ske");
clk_register_clkdev(clk, NULL, "nmk-ske-keypad");
clk = clk_reg_prcc_kclk("p3_uart2_kclk", "uartclk",
clkrst3_base, BIT(6), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "uart2");
clk = clk_reg_prcc_kclk("p3_sdi5_kclk", "sdmmcclk",
clkrst3_base, BIT(7), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "sdi5");
clk = clk_reg_prcc_kclk("p3_i2c5_kclk", "i2cclk",
clkrst3_base, BIT(8), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.5");
clk = clk_reg_prcc_kclk("p3_i2c6_kclk", "i2cclk",
clkrst3_base, BIT(9), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "nmk-i2c.6");
clk = clk_reg_prcc_kclk("p3_uart3_kclk", "uartclk",
clkrst3_base, BIT(10), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "uart3");
clk = clk_reg_prcc_kclk("p3_uart4_kclk", "uartclk",
clkrst3_base, BIT(11), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "uart4");
/* Peripheral 6 : PRCC K-clocks */
clk = clk_reg_prcc_kclk("p6_rng_kclk", "rngclk",
clkrst6_base, BIT(0), CLK_SET_RATE_GATE);
clk_register_clkdev(clk, NULL, "rng");
}
| gpl-2.0 |
olafdietsche/linux-accessfs | arch/mips/alchemy/devboards/db1550.c | 2477 | 15991 | /*
* Alchemy Db1550/Pb1550 board support
*
* (c) 2011 Manuel Lauss <manuel.lauss@googlemail.com>
*/
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <asm/bootinfo.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-au1x00/au1xxx_eth.h>
#include <asm/mach-au1x00/au1xxx_dbdma.h>
#include <asm/mach-au1x00/au1xxx_psc.h>
#include <asm/mach-au1x00/au1550_spi.h>
#include <asm/mach-au1x00/au1550nd.h>
#include <asm/mach-db1x00/bcsr.h>
#include <prom.h>
#include "platform.h"
static void __init db1550_hw_setup(void)
{
void __iomem *base;
/* complete SPI setup: link psc0_intclk to a 48MHz source,
* and assign GPIO16 to PSC0_SYNC1 (SPI cs# line) as well as PSC1_SYNC
* for AC97 on PB1550.
*/
base = (void __iomem *)SYS_CLKSRC;
__raw_writel(__raw_readl(base) | 0x000001e0, base);
base = (void __iomem *)SYS_PINFUNC;
__raw_writel(__raw_readl(base) | 1 | SYS_PF_PSC1_S1, base);
wmb();
/* reset the AC97 codec now, the reset time in the psc-ac97 driver
* is apparently too short although it's ridiculous as it is.
*/
base = (void __iomem *)KSEG1ADDR(AU1550_PSC1_PHYS_ADDR);
__raw_writel(PSC_SEL_CLK_SERCLK | PSC_SEL_PS_AC97MODE,
base + PSC_SEL_OFFSET);
__raw_writel(PSC_CTRL_DISABLE, base + PSC_CTRL_OFFSET);
wmb();
__raw_writel(PSC_AC97RST_RST, base + PSC_AC97RST_OFFSET);
wmb();
}
int __init db1550_board_setup(void)
{
unsigned short whoami;
bcsr_init(DB1550_BCSR_PHYS_ADDR,
DB1550_BCSR_PHYS_ADDR + DB1550_BCSR_HEXLED_OFS);
whoami = bcsr_read(BCSR_WHOAMI); /* PB1550 hexled offset differs */
if ((BCSR_WHOAMI_BOARD(whoami) == BCSR_WHOAMI_PB1550_SDR) ||
(BCSR_WHOAMI_BOARD(whoami) == BCSR_WHOAMI_PB1550_DDR))
bcsr_init(PB1550_BCSR_PHYS_ADDR,
PB1550_BCSR_PHYS_ADDR + PB1550_BCSR_HEXLED_OFS);
pr_info("Alchemy/AMD %s Board, CPLD Rev %d Board-ID %d " \
"Daughtercard ID %d\n", get_system_type(),
(whoami >> 4) & 0xf, (whoami >> 8) & 0xf, whoami & 0xf);
db1550_hw_setup();
return 0;
}
/*****************************************************************************/
static struct mtd_partition db1550_spiflash_parts[] = {
{
.name = "spi_flash",
.offset = 0,
.size = MTDPART_SIZ_FULL,
},
};
static struct flash_platform_data db1550_spiflash_data = {
.name = "s25fl010",
.parts = db1550_spiflash_parts,
.nr_parts = ARRAY_SIZE(db1550_spiflash_parts),
.type = "m25p10",
};
static struct spi_board_info db1550_spi_devs[] __initdata = {
{
/* TI TMP121AIDBVR temp sensor */
.modalias = "tmp121",
.max_speed_hz = 2400000,
.bus_num = 0,
.chip_select = 0,
.mode = SPI_MODE_0,
},
{
/* Spansion S25FL001D0FMA SPI flash */
.modalias = "m25p80",
.max_speed_hz = 2400000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_0,
.platform_data = &db1550_spiflash_data,
},
};
static struct i2c_board_info db1550_i2c_devs[] __initdata = {
{ I2C_BOARD_INFO("24c04", 0x52),}, /* AT24C04-10 I2C eeprom */
{ I2C_BOARD_INFO("ne1619", 0x2d),}, /* adm1025-compat hwmon */
{ I2C_BOARD_INFO("wm8731", 0x1b),}, /* I2S audio codec WM8731 */
};
/**********************************************************************/
static void au1550_nand_cmd_ctrl(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct nand_chip *this = mtd->priv;
unsigned long ioaddr = (unsigned long)this->IO_ADDR_W;
ioaddr &= 0xffffff00;
if (ctrl & NAND_CLE) {
ioaddr += MEM_STNAND_CMD;
} else if (ctrl & NAND_ALE) {
ioaddr += MEM_STNAND_ADDR;
} else {
/* assume we want to r/w real data by default */
ioaddr += MEM_STNAND_DATA;
}
this->IO_ADDR_R = this->IO_ADDR_W = (void __iomem *)ioaddr;
if (cmd != NAND_CMD_NONE) {
__raw_writeb(cmd, this->IO_ADDR_W);
wmb();
}
}
static int au1550_nand_device_ready(struct mtd_info *mtd)
{
return __raw_readl((void __iomem *)MEM_STSTAT) & 1;
}
static struct mtd_partition db1550_nand_parts[] = {
{
.name = "NAND FS 0",
.offset = 0,
.size = 8 * 1024 * 1024,
},
{
.name = "NAND FS 1",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL
},
};
struct platform_nand_data db1550_nand_platdata = {
.chip = {
.nr_chips = 1,
.chip_offset = 0,
.nr_partitions = ARRAY_SIZE(db1550_nand_parts),
.partitions = db1550_nand_parts,
.chip_delay = 20,
},
.ctrl = {
.dev_ready = au1550_nand_device_ready,
.cmd_ctrl = au1550_nand_cmd_ctrl,
},
};
static struct resource db1550_nand_res[] = {
[0] = {
.start = 0x20000000,
.end = 0x200000ff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device db1550_nand_dev = {
.name = "gen_nand",
.num_resources = ARRAY_SIZE(db1550_nand_res),
.resource = db1550_nand_res,
.id = -1,
.dev = {
.platform_data = &db1550_nand_platdata,
}
};
static struct au1550nd_platdata pb1550_nand_pd = {
.parts = db1550_nand_parts,
.num_parts = ARRAY_SIZE(db1550_nand_parts),
.devwidth = 0, /* x8 NAND default, needs fixing up */
};
static struct platform_device pb1550_nand_dev = {
.name = "au1550-nand",
.id = -1,
.resource = db1550_nand_res,
.num_resources = ARRAY_SIZE(db1550_nand_res),
.dev = {
.platform_data = &pb1550_nand_pd,
},
};
static void __init pb1550_nand_setup(void)
{
int boot_swapboot = (au_readl(MEM_STSTAT) & (0x7 << 1)) |
((bcsr_read(BCSR_STATUS) >> 6) & 0x1);
gpio_direction_input(206); /* de-assert NAND CS# */
switch (boot_swapboot) {
case 0: case 2: case 8: case 0xC: case 0xD:
/* x16 NAND Flash */
pb1550_nand_pd.devwidth = 1;
/* fallthrough */
case 1: case 3: case 9: case 0xE: case 0xF:
/* x8 NAND, already set up */
platform_device_register(&pb1550_nand_dev);
}
}
/**********************************************************************/
static struct resource au1550_psc0_res[] = {
[0] = {
.start = AU1550_PSC0_PHYS_ADDR,
.end = AU1550_PSC0_PHYS_ADDR + 0xfff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AU1550_PSC0_INT,
.end = AU1550_PSC0_INT,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AU1550_DSCR_CMD0_PSC0_TX,
.end = AU1550_DSCR_CMD0_PSC0_TX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = AU1550_DSCR_CMD0_PSC0_RX,
.end = AU1550_DSCR_CMD0_PSC0_RX,
.flags = IORESOURCE_DMA,
},
};
static void db1550_spi_cs_en(struct au1550_spi_info *spi, int cs, int pol)
{
if (cs)
bcsr_mod(BCSR_BOARD, 0, BCSR_BOARD_SPISEL);
else
bcsr_mod(BCSR_BOARD, BCSR_BOARD_SPISEL, 0);
}
static struct au1550_spi_info db1550_spi_platdata = {
.mainclk_hz = 48000000, /* PSC0 clock: max. 2.4MHz SPI clk */
.num_chipselect = 2,
.activate_cs = db1550_spi_cs_en,
};
static u64 spi_dmamask = DMA_BIT_MASK(32);
static struct platform_device db1550_spi_dev = {
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &db1550_spi_platdata,
},
.name = "au1550-spi",
.id = 0, /* bus number */
.num_resources = ARRAY_SIZE(au1550_psc0_res),
.resource = au1550_psc0_res,
};
/**********************************************************************/
static struct resource au1550_psc1_res[] = {
[0] = {
.start = AU1550_PSC1_PHYS_ADDR,
.end = AU1550_PSC1_PHYS_ADDR + 0xfff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AU1550_PSC1_INT,
.end = AU1550_PSC1_INT,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AU1550_DSCR_CMD0_PSC1_TX,
.end = AU1550_DSCR_CMD0_PSC1_TX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = AU1550_DSCR_CMD0_PSC1_RX,
.end = AU1550_DSCR_CMD0_PSC1_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device db1550_ac97_dev = {
.name = "au1xpsc_ac97",
.id = 1, /* PSC ID */
.num_resources = ARRAY_SIZE(au1550_psc1_res),
.resource = au1550_psc1_res,
};
static struct resource au1550_psc2_res[] = {
[0] = {
.start = AU1550_PSC2_PHYS_ADDR,
.end = AU1550_PSC2_PHYS_ADDR + 0xfff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AU1550_PSC2_INT,
.end = AU1550_PSC2_INT,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AU1550_DSCR_CMD0_PSC2_TX,
.end = AU1550_DSCR_CMD0_PSC2_TX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = AU1550_DSCR_CMD0_PSC2_RX,
.end = AU1550_DSCR_CMD0_PSC2_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device db1550_i2c_dev = {
.name = "au1xpsc_smbus",
.id = 0, /* bus number */
.num_resources = ARRAY_SIZE(au1550_psc2_res),
.resource = au1550_psc2_res,
};
/**********************************************************************/
static struct resource au1550_psc3_res[] = {
[0] = {
.start = AU1550_PSC3_PHYS_ADDR,
.end = AU1550_PSC3_PHYS_ADDR + 0xfff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AU1550_PSC3_INT,
.end = AU1550_PSC3_INT,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AU1550_DSCR_CMD0_PSC3_TX,
.end = AU1550_DSCR_CMD0_PSC3_TX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = AU1550_DSCR_CMD0_PSC3_RX,
.end = AU1550_DSCR_CMD0_PSC3_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device db1550_i2s_dev = {
.name = "au1xpsc_i2s",
.id = 3, /* PSC ID */
.num_resources = ARRAY_SIZE(au1550_psc3_res),
.resource = au1550_psc3_res,
};
/**********************************************************************/
static struct platform_device db1550_stac_dev = {
.name = "ac97-codec",
.id = 1, /* on PSC1 */
};
static struct platform_device db1550_ac97dma_dev = {
.name = "au1xpsc-pcm",
.id = 1, /* on PSC3 */
};
static struct platform_device db1550_i2sdma_dev = {
.name = "au1xpsc-pcm",
.id = 3, /* on PSC3 */
};
static struct platform_device db1550_sndac97_dev = {
.name = "db1550-ac97",
};
static struct platform_device db1550_sndi2s_dev = {
.name = "db1550-i2s",
};
/**********************************************************************/
static int db1550_map_pci_irq(const struct pci_dev *d, u8 slot, u8 pin)
{
if ((slot < 11) || (slot > 13) || pin == 0)
return -1;
if (slot == 11)
return (pin == 1) ? AU1550_PCI_INTC : 0xff;
if (slot == 12) {
switch (pin) {
case 1: return AU1550_PCI_INTB;
case 2: return AU1550_PCI_INTC;
case 3: return AU1550_PCI_INTD;
case 4: return AU1550_PCI_INTA;
}
}
if (slot == 13) {
switch (pin) {
case 1: return AU1550_PCI_INTA;
case 2: return AU1550_PCI_INTB;
case 3: return AU1550_PCI_INTC;
case 4: return AU1550_PCI_INTD;
}
}
return -1;
}
static int pb1550_map_pci_irq(const struct pci_dev *d, u8 slot, u8 pin)
{
if ((slot < 12) || (slot > 13) || pin == 0)
return -1;
if (slot == 12) {
switch (pin) {
case 1: return AU1500_PCI_INTB;
case 2: return AU1500_PCI_INTC;
case 3: return AU1500_PCI_INTD;
case 4: return AU1500_PCI_INTA;
}
}
if (slot == 13) {
switch (pin) {
case 1: return AU1500_PCI_INTA;
case 2: return AU1500_PCI_INTB;
case 3: return AU1500_PCI_INTC;
case 4: return AU1500_PCI_INTD;
}
}
return -1;
}
static struct resource alchemy_pci_host_res[] = {
[0] = {
.start = AU1500_PCI_PHYS_ADDR,
.end = AU1500_PCI_PHYS_ADDR + 0xfff,
.flags = IORESOURCE_MEM,
},
};
static struct alchemy_pci_platdata db1550_pci_pd = {
.board_map_irq = db1550_map_pci_irq,
};
static struct platform_device db1550_pci_host_dev = {
.dev.platform_data = &db1550_pci_pd,
.name = "alchemy-pci",
.id = 0,
.num_resources = ARRAY_SIZE(alchemy_pci_host_res),
.resource = alchemy_pci_host_res,
};
/**********************************************************************/
static struct platform_device *db1550_devs[] __initdata = {
&db1550_i2c_dev,
&db1550_ac97_dev,
&db1550_spi_dev,
&db1550_i2s_dev,
&db1550_stac_dev,
&db1550_ac97dma_dev,
&db1550_i2sdma_dev,
&db1550_sndac97_dev,
&db1550_sndi2s_dev,
};
/* must be arch_initcall; MIPS PCI scans busses in a subsys_initcall */
int __init db1550_pci_setup(int id)
{
if (id)
db1550_pci_pd.board_map_irq = pb1550_map_pci_irq;
return platform_device_register(&db1550_pci_host_dev);
}
static void __init db1550_devices(void)
{
alchemy_gpio_direction_output(203, 0); /* red led on */
irq_set_irq_type(AU1550_GPIO0_INT, IRQ_TYPE_EDGE_BOTH); /* CD0# */
irq_set_irq_type(AU1550_GPIO1_INT, IRQ_TYPE_EDGE_BOTH); /* CD1# */
irq_set_irq_type(AU1550_GPIO3_INT, IRQ_TYPE_LEVEL_LOW); /* CARD0# */
irq_set_irq_type(AU1550_GPIO5_INT, IRQ_TYPE_LEVEL_LOW); /* CARD1# */
irq_set_irq_type(AU1550_GPIO21_INT, IRQ_TYPE_LEVEL_LOW); /* STSCHG0# */
irq_set_irq_type(AU1550_GPIO22_INT, IRQ_TYPE_LEVEL_LOW); /* STSCHG1# */
db1x_register_pcmcia_socket(
AU1000_PCMCIA_ATTR_PHYS_ADDR,
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x000400000 - 1,
AU1000_PCMCIA_MEM_PHYS_ADDR,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x000400000 - 1,
AU1000_PCMCIA_IO_PHYS_ADDR,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x000010000 - 1,
AU1550_GPIO3_INT, AU1550_GPIO0_INT,
/*AU1550_GPIO21_INT*/0, 0, 0);
db1x_register_pcmcia_socket(
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x004000000,
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x004400000 - 1,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x004000000,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x004400000 - 1,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x004000000,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x004010000 - 1,
AU1550_GPIO5_INT, AU1550_GPIO1_INT,
/*AU1550_GPIO22_INT*/0, 0, 1);
platform_device_register(&db1550_nand_dev);
alchemy_gpio_direction_output(202, 0); /* green led on */
}
static void __init pb1550_devices(void)
{
irq_set_irq_type(AU1550_GPIO0_INT, IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(AU1550_GPIO1_INT, IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(AU1550_GPIO201_205_INT, IRQ_TYPE_LEVEL_HIGH);
/* enable both PCMCIA card irqs in the shared line */
alchemy_gpio2_enable_int(201); /* socket 0 card irq */
alchemy_gpio2_enable_int(202); /* socket 1 card irq */
/* Pb1550, like all others, also has statuschange irqs; however they're
* wired up on one of the Au1550's shared GPIO201_205 line, which also
* services the PCMCIA card interrupts. So we ignore statuschange and
* use the GPIO201_205 exclusively for card interrupts, since a) pcmcia
* drivers are used to shared irqs and b) statuschange isn't really use-
* ful anyway.
*/
db1x_register_pcmcia_socket(
AU1000_PCMCIA_ATTR_PHYS_ADDR,
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x000400000 - 1,
AU1000_PCMCIA_MEM_PHYS_ADDR,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x000400000 - 1,
AU1000_PCMCIA_IO_PHYS_ADDR,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x000010000 - 1,
AU1550_GPIO201_205_INT, AU1550_GPIO0_INT, 0, 0, 0);
db1x_register_pcmcia_socket(
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x008000000,
AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x008400000 - 1,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x008000000,
AU1000_PCMCIA_MEM_PHYS_ADDR + 0x008400000 - 1,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x008000000,
AU1000_PCMCIA_IO_PHYS_ADDR + 0x008010000 - 1,
AU1550_GPIO201_205_INT, AU1550_GPIO1_INT, 0, 0, 1);
pb1550_nand_setup();
}
int __init db1550_dev_setup(void)
{
int swapped, id;
id = (BCSR_WHOAMI_BOARD(bcsr_read(BCSR_WHOAMI)) != BCSR_WHOAMI_DB1550);
i2c_register_board_info(0, db1550_i2c_devs,
ARRAY_SIZE(db1550_i2c_devs));
spi_register_board_info(db1550_spi_devs,
ARRAY_SIZE(db1550_i2c_devs));
/* Audio PSC clock is supplied by codecs (PSC1, 3) FIXME: platdata!! */
__raw_writel(PSC_SEL_CLK_SERCLK,
(void __iomem *)KSEG1ADDR(AU1550_PSC1_PHYS_ADDR) + PSC_SEL_OFFSET);
wmb();
__raw_writel(PSC_SEL_CLK_SERCLK,
(void __iomem *)KSEG1ADDR(AU1550_PSC3_PHYS_ADDR) + PSC_SEL_OFFSET);
wmb();
/* SPI/I2C use internally supplied 50MHz source */
__raw_writel(PSC_SEL_CLK_INTCLK,
(void __iomem *)KSEG1ADDR(AU1550_PSC0_PHYS_ADDR) + PSC_SEL_OFFSET);
wmb();
__raw_writel(PSC_SEL_CLK_INTCLK,
(void __iomem *)KSEG1ADDR(AU1550_PSC2_PHYS_ADDR) + PSC_SEL_OFFSET);
wmb();
id ? pb1550_devices() : db1550_devices();
swapped = bcsr_read(BCSR_STATUS) &
(id ? BCSR_STATUS_PB1550_SWAPBOOT : BCSR_STATUS_DB1000_SWAPBOOT);
db1x_register_norflash(128 << 20, 4, swapped);
return platform_add_devices(db1550_devs, ARRAY_SIZE(db1550_devs));
}
| gpl-2.0 |
Split-Screen/android_kernel_motorola_msm8939 | arch/arm/mach-imx/clk-imx1.c | 2733 | 4688 | /*
* Copyright (C) 2008 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <linux/err.h>
#include "clk.h"
#include "common.h"
#include "hardware.h"
/* CCM register addresses */
#define IO_ADDR_CCM(off) (MX1_IO_ADDRESS(MX1_CCM_BASE_ADDR + (off)))
#define CCM_CSCR IO_ADDR_CCM(0x0)
#define CCM_MPCTL0 IO_ADDR_CCM(0x4)
#define CCM_SPCTL0 IO_ADDR_CCM(0xc)
#define CCM_PCDR IO_ADDR_CCM(0x20)
/* SCM register addresses */
#define IO_ADDR_SCM(off) (MX1_IO_ADDRESS(MX1_SCM_BASE_ADDR + (off)))
#define SCM_GCCR IO_ADDR_SCM(0xc)
static const char *prem_sel_clks[] = { "clk32_premult", "clk16m", };
static const char *clko_sel_clks[] = { "per1", "hclk", "clk48m", "clk16m", "prem",
"fclk", };
enum imx1_clks {
dummy, clk32, clk16m_ext, clk16m, clk32_premult, prem, mpll, spll, mcu,
fclk, hclk, clk48m, per1, per2, per3, clko, dma_gate, csi_gate,
mma_gate, usbd_gate, clk_max
};
static struct clk *clk[clk_max];
int __init mx1_clocks_init(unsigned long fref)
{
int i;
clk[dummy] = imx_clk_fixed("dummy", 0);
clk[clk32] = imx_clk_fixed("clk32", fref);
clk[clk16m_ext] = imx_clk_fixed("clk16m_ext", 16000000);
clk[clk16m] = imx_clk_gate("clk16m", "clk16m_ext", CCM_CSCR, 17);
clk[clk32_premult] = imx_clk_fixed_factor("clk32_premult", "clk32", 512, 1);
clk[prem] = imx_clk_mux("prem", CCM_CSCR, 16, 1, prem_sel_clks,
ARRAY_SIZE(prem_sel_clks));
clk[mpll] = imx_clk_pllv1("mpll", "clk32_premult", CCM_MPCTL0);
clk[spll] = imx_clk_pllv1("spll", "prem", CCM_SPCTL0);
clk[mcu] = imx_clk_divider("mcu", "clk32_premult", CCM_CSCR, 15, 1);
clk[fclk] = imx_clk_divider("fclk", "mpll", CCM_CSCR, 15, 1);
clk[hclk] = imx_clk_divider("hclk", "spll", CCM_CSCR, 10, 4);
clk[clk48m] = imx_clk_divider("clk48m", "spll", CCM_CSCR, 26, 3);
clk[per1] = imx_clk_divider("per1", "spll", CCM_PCDR, 0, 4);
clk[per2] = imx_clk_divider("per2", "spll", CCM_PCDR, 4, 4);
clk[per3] = imx_clk_divider("per3", "spll", CCM_PCDR, 16, 7);
clk[clko] = imx_clk_mux("clko", CCM_CSCR, 29, 3, clko_sel_clks,
ARRAY_SIZE(clko_sel_clks));
clk[dma_gate] = imx_clk_gate("dma_gate", "hclk", SCM_GCCR, 4);
clk[csi_gate] = imx_clk_gate("csi_gate", "hclk", SCM_GCCR, 2);
clk[mma_gate] = imx_clk_gate("mma_gate", "hclk", SCM_GCCR, 1);
clk[usbd_gate] = imx_clk_gate("usbd_gate", "clk48m", SCM_GCCR, 0);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("imx1 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
clk_register_clkdev(clk[dma_gate], "ahb", "imx1-dma");
clk_register_clkdev(clk[hclk], "ipg", "imx1-dma");
clk_register_clkdev(clk[csi_gate], NULL, "mx1-camera.0");
clk_register_clkdev(clk[mma_gate], "mma", NULL);
clk_register_clkdev(clk[usbd_gate], NULL, "imx_udc.0");
clk_register_clkdev(clk[per1], "per", "imx-gpt.0");
clk_register_clkdev(clk[hclk], "ipg", "imx-gpt.0");
clk_register_clkdev(clk[per1], "per", "imx1-uart.0");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.0");
clk_register_clkdev(clk[per1], "per", "imx1-uart.1");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.1");
clk_register_clkdev(clk[per1], "per", "imx1-uart.2");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.2");
clk_register_clkdev(clk[hclk], NULL, "imx1-i2c.0");
clk_register_clkdev(clk[per2], "per", "imx1-cspi.0");
clk_register_clkdev(clk[dummy], "ipg", "imx1-cspi.0");
clk_register_clkdev(clk[per2], "per", "imx1-cspi.1");
clk_register_clkdev(clk[dummy], "ipg", "imx1-cspi.1");
clk_register_clkdev(clk[per2], NULL, "imx-mmc.0");
clk_register_clkdev(clk[per2], "per", "imx1-fb.0");
clk_register_clkdev(clk[dummy], "ipg", "imx1-fb.0");
clk_register_clkdev(clk[dummy], "ahb", "imx1-fb.0");
clk_register_clkdev(clk[hclk], "mshc", NULL);
clk_register_clkdev(clk[per3], "ssi", NULL);
clk_register_clkdev(clk[clk32], NULL, "imx1-rtc.0");
clk_register_clkdev(clk[clko], "clko", NULL);
mxc_timer_init(MX1_IO_ADDRESS(MX1_TIM1_BASE_ADDR), MX1_TIM1_INT);
return 0;
}
| gpl-2.0 |
kozmikkick/flounder | arch/arm/mach-imx/clk-imx1.c | 2733 | 4688 | /*
* Copyright (C) 2008 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <linux/err.h>
#include "clk.h"
#include "common.h"
#include "hardware.h"
/* CCM register addresses */
#define IO_ADDR_CCM(off) (MX1_IO_ADDRESS(MX1_CCM_BASE_ADDR + (off)))
#define CCM_CSCR IO_ADDR_CCM(0x0)
#define CCM_MPCTL0 IO_ADDR_CCM(0x4)
#define CCM_SPCTL0 IO_ADDR_CCM(0xc)
#define CCM_PCDR IO_ADDR_CCM(0x20)
/* SCM register addresses */
#define IO_ADDR_SCM(off) (MX1_IO_ADDRESS(MX1_SCM_BASE_ADDR + (off)))
#define SCM_GCCR IO_ADDR_SCM(0xc)
static const char *prem_sel_clks[] = { "clk32_premult", "clk16m", };
static const char *clko_sel_clks[] = { "per1", "hclk", "clk48m", "clk16m", "prem",
"fclk", };
enum imx1_clks {
dummy, clk32, clk16m_ext, clk16m, clk32_premult, prem, mpll, spll, mcu,
fclk, hclk, clk48m, per1, per2, per3, clko, dma_gate, csi_gate,
mma_gate, usbd_gate, clk_max
};
static struct clk *clk[clk_max];
int __init mx1_clocks_init(unsigned long fref)
{
int i;
clk[dummy] = imx_clk_fixed("dummy", 0);
clk[clk32] = imx_clk_fixed("clk32", fref);
clk[clk16m_ext] = imx_clk_fixed("clk16m_ext", 16000000);
clk[clk16m] = imx_clk_gate("clk16m", "clk16m_ext", CCM_CSCR, 17);
clk[clk32_premult] = imx_clk_fixed_factor("clk32_premult", "clk32", 512, 1);
clk[prem] = imx_clk_mux("prem", CCM_CSCR, 16, 1, prem_sel_clks,
ARRAY_SIZE(prem_sel_clks));
clk[mpll] = imx_clk_pllv1("mpll", "clk32_premult", CCM_MPCTL0);
clk[spll] = imx_clk_pllv1("spll", "prem", CCM_SPCTL0);
clk[mcu] = imx_clk_divider("mcu", "clk32_premult", CCM_CSCR, 15, 1);
clk[fclk] = imx_clk_divider("fclk", "mpll", CCM_CSCR, 15, 1);
clk[hclk] = imx_clk_divider("hclk", "spll", CCM_CSCR, 10, 4);
clk[clk48m] = imx_clk_divider("clk48m", "spll", CCM_CSCR, 26, 3);
clk[per1] = imx_clk_divider("per1", "spll", CCM_PCDR, 0, 4);
clk[per2] = imx_clk_divider("per2", "spll", CCM_PCDR, 4, 4);
clk[per3] = imx_clk_divider("per3", "spll", CCM_PCDR, 16, 7);
clk[clko] = imx_clk_mux("clko", CCM_CSCR, 29, 3, clko_sel_clks,
ARRAY_SIZE(clko_sel_clks));
clk[dma_gate] = imx_clk_gate("dma_gate", "hclk", SCM_GCCR, 4);
clk[csi_gate] = imx_clk_gate("csi_gate", "hclk", SCM_GCCR, 2);
clk[mma_gate] = imx_clk_gate("mma_gate", "hclk", SCM_GCCR, 1);
clk[usbd_gate] = imx_clk_gate("usbd_gate", "clk48m", SCM_GCCR, 0);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("imx1 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
clk_register_clkdev(clk[dma_gate], "ahb", "imx1-dma");
clk_register_clkdev(clk[hclk], "ipg", "imx1-dma");
clk_register_clkdev(clk[csi_gate], NULL, "mx1-camera.0");
clk_register_clkdev(clk[mma_gate], "mma", NULL);
clk_register_clkdev(clk[usbd_gate], NULL, "imx_udc.0");
clk_register_clkdev(clk[per1], "per", "imx-gpt.0");
clk_register_clkdev(clk[hclk], "ipg", "imx-gpt.0");
clk_register_clkdev(clk[per1], "per", "imx1-uart.0");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.0");
clk_register_clkdev(clk[per1], "per", "imx1-uart.1");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.1");
clk_register_clkdev(clk[per1], "per", "imx1-uart.2");
clk_register_clkdev(clk[hclk], "ipg", "imx1-uart.2");
clk_register_clkdev(clk[hclk], NULL, "imx1-i2c.0");
clk_register_clkdev(clk[per2], "per", "imx1-cspi.0");
clk_register_clkdev(clk[dummy], "ipg", "imx1-cspi.0");
clk_register_clkdev(clk[per2], "per", "imx1-cspi.1");
clk_register_clkdev(clk[dummy], "ipg", "imx1-cspi.1");
clk_register_clkdev(clk[per2], NULL, "imx-mmc.0");
clk_register_clkdev(clk[per2], "per", "imx1-fb.0");
clk_register_clkdev(clk[dummy], "ipg", "imx1-fb.0");
clk_register_clkdev(clk[dummy], "ahb", "imx1-fb.0");
clk_register_clkdev(clk[hclk], "mshc", NULL);
clk_register_clkdev(clk[per3], "ssi", NULL);
clk_register_clkdev(clk[clk32], NULL, "imx1-rtc.0");
clk_register_clkdev(clk[clko], "clko", NULL);
mxc_timer_init(MX1_IO_ADDRESS(MX1_TIM1_BASE_ADDR), MX1_TIM1_INT);
return 0;
}
| gpl-2.0 |
omnirom/android_kernel_htc_msm8960 | drivers/staging/android/alarm-dev.c | 3757 | 9796 | /* drivers/rtc/alarm-dev.c
*
* Copyright (C) 2007-2009 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/time.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/alarmtimer.h>
#include <linux/wakelock.h>
#include "android_alarm.h"
#define ANDROID_ALARM_PRINT_INFO (1U << 0)
#define ANDROID_ALARM_PRINT_IO (1U << 1)
#define ANDROID_ALARM_PRINT_INT (1U << 2)
static int debug_mask = ANDROID_ALARM_PRINT_INFO;
module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
#define pr_alarm(debug_level_mask, args...) \
do { \
if (debug_mask & ANDROID_ALARM_PRINT_##debug_level_mask) { \
pr_info(args); \
} \
} while (0)
#define ANDROID_ALARM_WAKEUP_MASK ( \
ANDROID_ALARM_RTC_WAKEUP_MASK | \
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP_MASK)
/* support old usespace code */
#define ANDROID_ALARM_SET_OLD _IOW('a', 2, time_t) /* set alarm */
#define ANDROID_ALARM_SET_AND_WAIT_OLD _IOW('a', 3, time_t)
static int alarm_opened;
static DEFINE_SPINLOCK(alarm_slock);
static struct wake_lock alarm_wake_lock;
static DECLARE_WAIT_QUEUE_HEAD(alarm_wait_queue);
static uint32_t alarm_pending;
static uint32_t alarm_enabled;
static uint32_t wait_pending;
struct devalarm {
union {
struct hrtimer hrt;
struct alarm alrm;
} u;
enum android_alarm_type type;
};
static struct devalarm alarms[ANDROID_ALARM_TYPE_COUNT];
static int is_wakeup(enum android_alarm_type type)
{
if (type == ANDROID_ALARM_RTC_WAKEUP ||
type == ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP)
return 1;
return 0;
}
static void devalarm_start(struct devalarm *alrm, ktime_t exp)
{
if (is_wakeup(alrm->type))
alarm_start(&alrm->u.alrm, exp);
else
hrtimer_start(&alrm->u.hrt, exp, HRTIMER_MODE_ABS);
}
static int devalarm_try_to_cancel(struct devalarm *alrm)
{
int ret;
if (is_wakeup(alrm->type))
ret = alarm_try_to_cancel(&alrm->u.alrm);
else
ret = hrtimer_try_to_cancel(&alrm->u.hrt);
return ret;
}
static void devalarm_cancel(struct devalarm *alrm)
{
if (is_wakeup(alrm->type))
alarm_cancel(&alrm->u.alrm);
else
hrtimer_cancel(&alrm->u.hrt);
}
static long alarm_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int rv = 0;
unsigned long flags;
struct timespec new_alarm_time;
struct timespec new_rtc_time;
struct timespec tmp_time;
struct rtc_time new_rtc_tm;
struct rtc_device *rtc_dev;
enum android_alarm_type alarm_type = ANDROID_ALARM_IOCTL_TO_TYPE(cmd);
uint32_t alarm_type_mask = 1U << alarm_type;
if (alarm_type >= ANDROID_ALARM_TYPE_COUNT)
return -EINVAL;
if (ANDROID_ALARM_BASE_CMD(cmd) != ANDROID_ALARM_GET_TIME(0)) {
if ((file->f_flags & O_ACCMODE) == O_RDONLY)
return -EPERM;
if (file->private_data == NULL &&
cmd != ANDROID_ALARM_SET_RTC) {
spin_lock_irqsave(&alarm_slock, flags);
if (alarm_opened) {
spin_unlock_irqrestore(&alarm_slock, flags);
return -EBUSY;
}
alarm_opened = 1;
file->private_data = (void *)1;
spin_unlock_irqrestore(&alarm_slock, flags);
}
}
switch (ANDROID_ALARM_BASE_CMD(cmd)) {
case ANDROID_ALARM_CLEAR(0):
spin_lock_irqsave(&alarm_slock, flags);
pr_alarm(IO, "alarm %d clear\n", alarm_type);
devalarm_try_to_cancel(&alarms[alarm_type]);
if (alarm_pending) {
alarm_pending &= ~alarm_type_mask;
if (!alarm_pending && !wait_pending)
wake_unlock(&alarm_wake_lock);
}
alarm_enabled &= ~alarm_type_mask;
spin_unlock_irqrestore(&alarm_slock, flags);
break;
case ANDROID_ALARM_SET_OLD:
case ANDROID_ALARM_SET_AND_WAIT_OLD:
if (get_user(new_alarm_time.tv_sec, (int __user *)arg)) {
rv = -EFAULT;
goto err1;
}
new_alarm_time.tv_nsec = 0;
goto from_old_alarm_set;
case ANDROID_ALARM_SET_AND_WAIT(0):
case ANDROID_ALARM_SET(0):
if (copy_from_user(&new_alarm_time, (void __user *)arg,
sizeof(new_alarm_time))) {
rv = -EFAULT;
goto err1;
}
from_old_alarm_set:
spin_lock_irqsave(&alarm_slock, flags);
pr_alarm(IO, "alarm %d set %ld.%09ld\n", alarm_type,
new_alarm_time.tv_sec, new_alarm_time.tv_nsec);
alarm_enabled |= alarm_type_mask;
devalarm_start(&alarms[alarm_type],
timespec_to_ktime(new_alarm_time));
spin_unlock_irqrestore(&alarm_slock, flags);
if (ANDROID_ALARM_BASE_CMD(cmd) != ANDROID_ALARM_SET_AND_WAIT(0)
&& cmd != ANDROID_ALARM_SET_AND_WAIT_OLD)
break;
/* fall though */
case ANDROID_ALARM_WAIT:
spin_lock_irqsave(&alarm_slock, flags);
pr_alarm(IO, "alarm wait\n");
if (!alarm_pending && wait_pending) {
wake_unlock(&alarm_wake_lock);
wait_pending = 0;
}
spin_unlock_irqrestore(&alarm_slock, flags);
rv = wait_event_interruptible(alarm_wait_queue, alarm_pending);
if (rv)
goto err1;
spin_lock_irqsave(&alarm_slock, flags);
rv = alarm_pending;
wait_pending = 1;
alarm_pending = 0;
spin_unlock_irqrestore(&alarm_slock, flags);
break;
case ANDROID_ALARM_SET_RTC:
if (copy_from_user(&new_rtc_time, (void __user *)arg,
sizeof(new_rtc_time))) {
rv = -EFAULT;
goto err1;
}
rtc_time_to_tm(new_rtc_time.tv_sec, &new_rtc_tm);
rtc_dev = alarmtimer_get_rtcdev();
rv = do_settimeofday(&new_rtc_time);
if (rv < 0)
goto err1;
if (rtc_dev)
rv = rtc_set_time(rtc_dev, &new_rtc_tm);
spin_lock_irqsave(&alarm_slock, flags);
alarm_pending |= ANDROID_ALARM_TIME_CHANGE_MASK;
wake_up(&alarm_wait_queue);
spin_unlock_irqrestore(&alarm_slock, flags);
if (rv < 0)
goto err1;
break;
case ANDROID_ALARM_GET_TIME(0):
switch (alarm_type) {
case ANDROID_ALARM_RTC_WAKEUP:
case ANDROID_ALARM_RTC:
getnstimeofday(&tmp_time);
break;
case ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP:
case ANDROID_ALARM_ELAPSED_REALTIME:
get_monotonic_boottime(&tmp_time);
break;
case ANDROID_ALARM_TYPE_COUNT:
case ANDROID_ALARM_SYSTEMTIME:
ktime_get_ts(&tmp_time);
break;
}
if (copy_to_user((void __user *)arg, &tmp_time,
sizeof(tmp_time))) {
rv = -EFAULT;
goto err1;
}
break;
default:
rv = -EINVAL;
goto err1;
}
err1:
return rv;
}
static int alarm_open(struct inode *inode, struct file *file)
{
file->private_data = NULL;
return 0;
}
static int alarm_release(struct inode *inode, struct file *file)
{
int i;
unsigned long flags;
spin_lock_irqsave(&alarm_slock, flags);
if (file->private_data != 0) {
for (i = 0; i < ANDROID_ALARM_TYPE_COUNT; i++) {
uint32_t alarm_type_mask = 1U << i;
if (alarm_enabled & alarm_type_mask) {
pr_alarm(INFO, "alarm_release: clear alarm, "
"pending %d\n",
!!(alarm_pending & alarm_type_mask));
alarm_enabled &= ~alarm_type_mask;
}
spin_unlock_irqrestore(&alarm_slock, flags);
devalarm_cancel(&alarms[i]);
spin_lock_irqsave(&alarm_slock, flags);
}
if (alarm_pending | wait_pending) {
if (alarm_pending)
pr_alarm(INFO, "alarm_release: clear "
"pending alarms %x\n", alarm_pending);
wake_unlock(&alarm_wake_lock);
wait_pending = 0;
alarm_pending = 0;
}
alarm_opened = 0;
}
spin_unlock_irqrestore(&alarm_slock, flags);
return 0;
}
static void devalarm_triggered(struct devalarm *alarm)
{
unsigned long flags;
uint32_t alarm_type_mask = 1U << alarm->type;
pr_alarm(INT, "devalarm_triggered type %d\n", alarm->type);
spin_lock_irqsave(&alarm_slock, flags);
if (alarm_enabled & alarm_type_mask) {
wake_lock_timeout(&alarm_wake_lock, 5 * HZ);
alarm_enabled &= ~alarm_type_mask;
alarm_pending |= alarm_type_mask;
wake_up(&alarm_wait_queue);
}
spin_unlock_irqrestore(&alarm_slock, flags);
}
static enum hrtimer_restart devalarm_hrthandler(struct hrtimer *hrt)
{
struct devalarm *devalrm = container_of(hrt, struct devalarm, u.hrt);
devalarm_triggered(devalrm);
return HRTIMER_NORESTART;
}
static enum alarmtimer_restart devalarm_alarmhandler(struct alarm *alrm,
ktime_t now)
{
struct devalarm *devalrm = container_of(alrm, struct devalarm, u.alrm);
devalarm_triggered(devalrm);
return ALARMTIMER_NORESTART;
}
static const struct file_operations alarm_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = alarm_ioctl,
.open = alarm_open,
.release = alarm_release,
};
static struct miscdevice alarm_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "alarm",
.fops = &alarm_fops,
};
static int __init alarm_dev_init(void)
{
int err;
int i;
err = misc_register(&alarm_device);
if (err)
return err;
alarm_init(&alarms[ANDROID_ALARM_RTC_WAKEUP].u.alrm,
ALARM_REALTIME, devalarm_alarmhandler);
hrtimer_init(&alarms[ANDROID_ALARM_RTC].u.hrt,
CLOCK_REALTIME, HRTIMER_MODE_ABS);
alarm_init(&alarms[ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP].u.alrm,
ALARM_BOOTTIME, devalarm_alarmhandler);
hrtimer_init(&alarms[ANDROID_ALARM_ELAPSED_REALTIME].u.hrt,
CLOCK_BOOTTIME, HRTIMER_MODE_ABS);
hrtimer_init(&alarms[ANDROID_ALARM_SYSTEMTIME].u.hrt,
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
for (i = 0; i < ANDROID_ALARM_TYPE_COUNT; i++) {
alarms[i].type = i;
if (!is_wakeup(i))
alarms[i].u.hrt.function = devalarm_hrthandler;
}
wake_lock_init(&alarm_wake_lock, WAKE_LOCK_SUSPEND, "alarm");
return 0;
}
static void __exit alarm_dev_exit(void)
{
misc_deregister(&alarm_device);
wake_lock_destroy(&alarm_wake_lock);
}
module_init(alarm_dev_init);
module_exit(alarm_dev_exit);
| gpl-2.0 |
Abhinav1997/android_kernel_riogrande | fs/xfs/xfs_log.c | 4781 | 101972 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_error.h"
#include "xfs_log_priv.h"
#include "xfs_buf_item.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_log_recover.h"
#include "xfs_trans_priv.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_rw.h"
#include "xfs_trace.h"
kmem_zone_t *xfs_log_ticket_zone;
/* Local miscellaneous function prototypes */
STATIC int xlog_commit_record(struct log *log, struct xlog_ticket *ticket,
xlog_in_core_t **, xfs_lsn_t *);
STATIC xlog_t * xlog_alloc_log(xfs_mount_t *mp,
xfs_buftarg_t *log_target,
xfs_daddr_t blk_offset,
int num_bblks);
STATIC int xlog_space_left(struct log *log, atomic64_t *head);
STATIC int xlog_sync(xlog_t *log, xlog_in_core_t *iclog);
STATIC void xlog_dealloc_log(xlog_t *log);
/* local state machine functions */
STATIC void xlog_state_done_syncing(xlog_in_core_t *iclog, int);
STATIC void xlog_state_do_callback(xlog_t *log,int aborted, xlog_in_core_t *iclog);
STATIC int xlog_state_get_iclog_space(xlog_t *log,
int len,
xlog_in_core_t **iclog,
xlog_ticket_t *ticket,
int *continued_write,
int *logoffsetp);
STATIC int xlog_state_release_iclog(xlog_t *log,
xlog_in_core_t *iclog);
STATIC void xlog_state_switch_iclogs(xlog_t *log,
xlog_in_core_t *iclog,
int eventual_size);
STATIC void xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog);
STATIC void xlog_grant_push_ail(struct log *log,
int need_bytes);
STATIC void xlog_regrant_reserve_log_space(xlog_t *log,
xlog_ticket_t *ticket);
STATIC void xlog_ungrant_log_space(xlog_t *log,
xlog_ticket_t *ticket);
#if defined(DEBUG)
STATIC void xlog_verify_dest_ptr(xlog_t *log, char *ptr);
STATIC void xlog_verify_grant_tail(struct log *log);
STATIC void xlog_verify_iclog(xlog_t *log, xlog_in_core_t *iclog,
int count, boolean_t syncing);
STATIC void xlog_verify_tail_lsn(xlog_t *log, xlog_in_core_t *iclog,
xfs_lsn_t tail_lsn);
#else
#define xlog_verify_dest_ptr(a,b)
#define xlog_verify_grant_tail(a)
#define xlog_verify_iclog(a,b,c,d)
#define xlog_verify_tail_lsn(a,b,c)
#endif
STATIC int xlog_iclogs_empty(xlog_t *log);
static void
xlog_grant_sub_space(
struct log *log,
atomic64_t *head,
int bytes)
{
int64_t head_val = atomic64_read(head);
int64_t new, old;
do {
int cycle, space;
xlog_crack_grant_head_val(head_val, &cycle, &space);
space -= bytes;
if (space < 0) {
space += log->l_logsize;
cycle--;
}
old = head_val;
new = xlog_assign_grant_head_val(cycle, space);
head_val = atomic64_cmpxchg(head, old, new);
} while (head_val != old);
}
static void
xlog_grant_add_space(
struct log *log,
atomic64_t *head,
int bytes)
{
int64_t head_val = atomic64_read(head);
int64_t new, old;
do {
int tmp;
int cycle, space;
xlog_crack_grant_head_val(head_val, &cycle, &space);
tmp = log->l_logsize - space;
if (tmp > bytes)
space += bytes;
else {
space = bytes - tmp;
cycle++;
}
old = head_val;
new = xlog_assign_grant_head_val(cycle, space);
head_val = atomic64_cmpxchg(head, old, new);
} while (head_val != old);
}
STATIC void
xlog_grant_head_init(
struct xlog_grant_head *head)
{
xlog_assign_grant_head(&head->grant, 1, 0);
INIT_LIST_HEAD(&head->waiters);
spin_lock_init(&head->lock);
}
STATIC void
xlog_grant_head_wake_all(
struct xlog_grant_head *head)
{
struct xlog_ticket *tic;
spin_lock(&head->lock);
list_for_each_entry(tic, &head->waiters, t_queue)
wake_up_process(tic->t_task);
spin_unlock(&head->lock);
}
static inline int
xlog_ticket_reservation(
struct log *log,
struct xlog_grant_head *head,
struct xlog_ticket *tic)
{
if (head == &log->l_write_head) {
ASSERT(tic->t_flags & XLOG_TIC_PERM_RESERV);
return tic->t_unit_res;
} else {
if (tic->t_flags & XLOG_TIC_PERM_RESERV)
return tic->t_unit_res * tic->t_cnt;
else
return tic->t_unit_res;
}
}
STATIC bool
xlog_grant_head_wake(
struct log *log,
struct xlog_grant_head *head,
int *free_bytes)
{
struct xlog_ticket *tic;
int need_bytes;
list_for_each_entry(tic, &head->waiters, t_queue) {
need_bytes = xlog_ticket_reservation(log, head, tic);
if (*free_bytes < need_bytes)
return false;
*free_bytes -= need_bytes;
trace_xfs_log_grant_wake_up(log, tic);
wake_up_process(tic->t_task);
}
return true;
}
STATIC int
xlog_grant_head_wait(
struct log *log,
struct xlog_grant_head *head,
struct xlog_ticket *tic,
int need_bytes)
{
list_add_tail(&tic->t_queue, &head->waiters);
do {
if (XLOG_FORCED_SHUTDOWN(log))
goto shutdown;
xlog_grant_push_ail(log, need_bytes);
__set_current_state(TASK_UNINTERRUPTIBLE);
spin_unlock(&head->lock);
XFS_STATS_INC(xs_sleep_logspace);
trace_xfs_log_grant_sleep(log, tic);
schedule();
trace_xfs_log_grant_wake(log, tic);
spin_lock(&head->lock);
if (XLOG_FORCED_SHUTDOWN(log))
goto shutdown;
} while (xlog_space_left(log, &head->grant) < need_bytes);
list_del_init(&tic->t_queue);
return 0;
shutdown:
list_del_init(&tic->t_queue);
return XFS_ERROR(EIO);
}
/*
* Atomically get the log space required for a log ticket.
*
* Once a ticket gets put onto head->waiters, it will only return after the
* needed reservation is satisfied.
*
* This function is structured so that it has a lock free fast path. This is
* necessary because every new transaction reservation will come through this
* path. Hence any lock will be globally hot if we take it unconditionally on
* every pass.
*
* As tickets are only ever moved on and off head->waiters under head->lock, we
* only need to take that lock if we are going to add the ticket to the queue
* and sleep. We can avoid taking the lock if the ticket was never added to
* head->waiters because the t_queue list head will be empty and we hold the
* only reference to it so it can safely be checked unlocked.
*/
STATIC int
xlog_grant_head_check(
struct log *log,
struct xlog_grant_head *head,
struct xlog_ticket *tic,
int *need_bytes)
{
int free_bytes;
int error = 0;
ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY));
/*
* If there are other waiters on the queue then give them a chance at
* logspace before us. Wake up the first waiters, if we do not wake
* up all the waiters then go to sleep waiting for more free space,
* otherwise try to get some space for this transaction.
*/
*need_bytes = xlog_ticket_reservation(log, head, tic);
free_bytes = xlog_space_left(log, &head->grant);
if (!list_empty_careful(&head->waiters)) {
spin_lock(&head->lock);
if (!xlog_grant_head_wake(log, head, &free_bytes) ||
free_bytes < *need_bytes) {
error = xlog_grant_head_wait(log, head, tic,
*need_bytes);
}
spin_unlock(&head->lock);
} else if (free_bytes < *need_bytes) {
spin_lock(&head->lock);
error = xlog_grant_head_wait(log, head, tic, *need_bytes);
spin_unlock(&head->lock);
}
return error;
}
static void
xlog_tic_reset_res(xlog_ticket_t *tic)
{
tic->t_res_num = 0;
tic->t_res_arr_sum = 0;
tic->t_res_num_ophdrs = 0;
}
static void
xlog_tic_add_region(xlog_ticket_t *tic, uint len, uint type)
{
if (tic->t_res_num == XLOG_TIC_LEN_MAX) {
/* add to overflow and start again */
tic->t_res_o_flow += tic->t_res_arr_sum;
tic->t_res_num = 0;
tic->t_res_arr_sum = 0;
}
tic->t_res_arr[tic->t_res_num].r_len = len;
tic->t_res_arr[tic->t_res_num].r_type = type;
tic->t_res_arr_sum += len;
tic->t_res_num++;
}
/*
* Replenish the byte reservation required by moving the grant write head.
*/
int
xfs_log_regrant(
struct xfs_mount *mp,
struct xlog_ticket *tic)
{
struct log *log = mp->m_log;
int need_bytes;
int error = 0;
if (XLOG_FORCED_SHUTDOWN(log))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_try_logspace);
/*
* This is a new transaction on the ticket, so we need to change the
* transaction ID so that the next transaction has a different TID in
* the log. Just add one to the existing tid so that we can see chains
* of rolling transactions in the log easily.
*/
tic->t_tid++;
xlog_grant_push_ail(log, tic->t_unit_res);
tic->t_curr_res = tic->t_unit_res;
xlog_tic_reset_res(tic);
if (tic->t_cnt > 0)
return 0;
trace_xfs_log_regrant(log, tic);
error = xlog_grant_head_check(log, &log->l_write_head, tic,
&need_bytes);
if (error)
goto out_error;
xlog_grant_add_space(log, &log->l_write_head.grant, need_bytes);
trace_xfs_log_regrant_exit(log, tic);
xlog_verify_grant_tail(log);
return 0;
out_error:
/*
* If we are failing, make sure the ticket doesn't have any current
* reservations. We don't want to add this back when the ticket/
* transaction gets cancelled.
*/
tic->t_curr_res = 0;
tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
return error;
}
/*
* Reserve log space and return a ticket corresponding the reservation.
*
* Each reservation is going to reserve extra space for a log record header.
* When writes happen to the on-disk log, we don't subtract the length of the
* log record header from any reservation. By wasting space in each
* reservation, we prevent over allocation problems.
*/
int
xfs_log_reserve(
struct xfs_mount *mp,
int unit_bytes,
int cnt,
struct xlog_ticket **ticp,
__uint8_t client,
bool permanent,
uint t_type)
{
struct log *log = mp->m_log;
struct xlog_ticket *tic;
int need_bytes;
int error = 0;
ASSERT(client == XFS_TRANSACTION || client == XFS_LOG);
if (XLOG_FORCED_SHUTDOWN(log))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_try_logspace);
ASSERT(*ticp == NULL);
tic = xlog_ticket_alloc(log, unit_bytes, cnt, client, permanent,
KM_SLEEP | KM_MAYFAIL);
if (!tic)
return XFS_ERROR(ENOMEM);
tic->t_trans_type = t_type;
*ticp = tic;
xlog_grant_push_ail(log, tic->t_unit_res * tic->t_cnt);
trace_xfs_log_reserve(log, tic);
error = xlog_grant_head_check(log, &log->l_reserve_head, tic,
&need_bytes);
if (error)
goto out_error;
xlog_grant_add_space(log, &log->l_reserve_head.grant, need_bytes);
xlog_grant_add_space(log, &log->l_write_head.grant, need_bytes);
trace_xfs_log_reserve_exit(log, tic);
xlog_verify_grant_tail(log);
return 0;
out_error:
/*
* If we are failing, make sure the ticket doesn't have any current
* reservations. We don't want to add this back when the ticket/
* transaction gets cancelled.
*/
tic->t_curr_res = 0;
tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
return error;
}
/*
* NOTES:
*
* 1. currblock field gets updated at startup and after in-core logs
* marked as with WANT_SYNC.
*/
/*
* This routine is called when a user of a log manager ticket is done with
* the reservation. If the ticket was ever used, then a commit record for
* the associated transaction is written out as a log operation header with
* no data. The flag XLOG_TIC_INITED is set when the first write occurs with
* a given ticket. If the ticket was one with a permanent reservation, then
* a few operations are done differently. Permanent reservation tickets by
* default don't release the reservation. They just commit the current
* transaction with the belief that the reservation is still needed. A flag
* must be passed in before permanent reservations are actually released.
* When these type of tickets are not released, they need to be set into
* the inited state again. By doing this, a start record will be written
* out when the next write occurs.
*/
xfs_lsn_t
xfs_log_done(
struct xfs_mount *mp,
struct xlog_ticket *ticket,
struct xlog_in_core **iclog,
uint flags)
{
struct log *log = mp->m_log;
xfs_lsn_t lsn = 0;
if (XLOG_FORCED_SHUTDOWN(log) ||
/*
* If nothing was ever written, don't write out commit record.
* If we get an error, just continue and give back the log ticket.
*/
(((ticket->t_flags & XLOG_TIC_INITED) == 0) &&
(xlog_commit_record(log, ticket, iclog, &lsn)))) {
lsn = (xfs_lsn_t) -1;
if (ticket->t_flags & XLOG_TIC_PERM_RESERV) {
flags |= XFS_LOG_REL_PERM_RESERV;
}
}
if ((ticket->t_flags & XLOG_TIC_PERM_RESERV) == 0 ||
(flags & XFS_LOG_REL_PERM_RESERV)) {
trace_xfs_log_done_nonperm(log, ticket);
/*
* Release ticket if not permanent reservation or a specific
* request has been made to release a permanent reservation.
*/
xlog_ungrant_log_space(log, ticket);
xfs_log_ticket_put(ticket);
} else {
trace_xfs_log_done_perm(log, ticket);
xlog_regrant_reserve_log_space(log, ticket);
/* If this ticket was a permanent reservation and we aren't
* trying to release it, reset the inited flags; so next time
* we write, a start record will be written out.
*/
ticket->t_flags |= XLOG_TIC_INITED;
}
return lsn;
}
/*
* Attaches a new iclog I/O completion callback routine during
* transaction commit. If the log is in error state, a non-zero
* return code is handed back and the caller is responsible for
* executing the callback at an appropriate time.
*/
int
xfs_log_notify(
struct xfs_mount *mp,
struct xlog_in_core *iclog,
xfs_log_callback_t *cb)
{
int abortflg;
spin_lock(&iclog->ic_callback_lock);
abortflg = (iclog->ic_state & XLOG_STATE_IOERROR);
if (!abortflg) {
ASSERT_ALWAYS((iclog->ic_state == XLOG_STATE_ACTIVE) ||
(iclog->ic_state == XLOG_STATE_WANT_SYNC));
cb->cb_next = NULL;
*(iclog->ic_callback_tail) = cb;
iclog->ic_callback_tail = &(cb->cb_next);
}
spin_unlock(&iclog->ic_callback_lock);
return abortflg;
}
int
xfs_log_release_iclog(
struct xfs_mount *mp,
struct xlog_in_core *iclog)
{
if (xlog_state_release_iclog(mp->m_log, iclog)) {
xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
return EIO;
}
return 0;
}
/*
* Mount a log filesystem
*
* mp - ubiquitous xfs mount point structure
* log_target - buftarg of on-disk log device
* blk_offset - Start block # where block size is 512 bytes (BBSIZE)
* num_bblocks - Number of BBSIZE blocks in on-disk log
*
* Return error or zero.
*/
int
xfs_log_mount(
xfs_mount_t *mp,
xfs_buftarg_t *log_target,
xfs_daddr_t blk_offset,
int num_bblks)
{
int error;
if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
xfs_notice(mp, "Mounting Filesystem");
else {
xfs_notice(mp,
"Mounting filesystem in no-recovery mode. Filesystem will be inconsistent.");
ASSERT(mp->m_flags & XFS_MOUNT_RDONLY);
}
mp->m_log = xlog_alloc_log(mp, log_target, blk_offset, num_bblks);
if (IS_ERR(mp->m_log)) {
error = -PTR_ERR(mp->m_log);
goto out;
}
/*
* Initialize the AIL now we have a log.
*/
error = xfs_trans_ail_init(mp);
if (error) {
xfs_warn(mp, "AIL initialisation failed: error %d", error);
goto out_free_log;
}
mp->m_log->l_ailp = mp->m_ail;
/*
* skip log recovery on a norecovery mount. pretend it all
* just worked.
*/
if (!(mp->m_flags & XFS_MOUNT_NORECOVERY)) {
int readonly = (mp->m_flags & XFS_MOUNT_RDONLY);
if (readonly)
mp->m_flags &= ~XFS_MOUNT_RDONLY;
error = xlog_recover(mp->m_log);
if (readonly)
mp->m_flags |= XFS_MOUNT_RDONLY;
if (error) {
xfs_warn(mp, "log mount/recovery failed: error %d",
error);
goto out_destroy_ail;
}
}
/* Normal transactions can now occur */
mp->m_log->l_flags &= ~XLOG_ACTIVE_RECOVERY;
/*
* Now the log has been fully initialised and we know were our
* space grant counters are, we can initialise the permanent ticket
* needed for delayed logging to work.
*/
xlog_cil_init_post_recovery(mp->m_log);
return 0;
out_destroy_ail:
xfs_trans_ail_destroy(mp);
out_free_log:
xlog_dealloc_log(mp->m_log);
out:
return error;
}
/*
* Finish the recovery of the file system. This is separate from
* the xfs_log_mount() call, because it depends on the code in
* xfs_mountfs() to read in the root and real-time bitmap inodes
* between calling xfs_log_mount() and here.
*
* mp - ubiquitous xfs mount point structure
*/
int
xfs_log_mount_finish(xfs_mount_t *mp)
{
int error;
if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
error = xlog_recover_finish(mp->m_log);
else {
error = 0;
ASSERT(mp->m_flags & XFS_MOUNT_RDONLY);
}
return error;
}
/*
* Final log writes as part of unmount.
*
* Mark the filesystem clean as unmount happens. Note that during relocation
* this routine needs to be executed as part of source-bag while the
* deallocation must not be done until source-end.
*/
/*
* Unmount record used to have a string "Unmount filesystem--" in the
* data section where the "Un" was really a magic number (XLOG_UNMOUNT_TYPE).
* We just write the magic number now since that particular field isn't
* currently architecture converted and "nUmount" is a bit foo.
* As far as I know, there weren't any dependencies on the old behaviour.
*/
int
xfs_log_unmount_write(xfs_mount_t *mp)
{
xlog_t *log = mp->m_log;
xlog_in_core_t *iclog;
#ifdef DEBUG
xlog_in_core_t *first_iclog;
#endif
xlog_ticket_t *tic = NULL;
xfs_lsn_t lsn;
int error;
/*
* Don't write out unmount record on read-only mounts.
* Or, if we are doing a forced umount (typically because of IO errors).
*/
if (mp->m_flags & XFS_MOUNT_RDONLY)
return 0;
error = _xfs_log_force(mp, XFS_LOG_SYNC, NULL);
ASSERT(error || !(XLOG_FORCED_SHUTDOWN(log)));
#ifdef DEBUG
first_iclog = iclog = log->l_iclog;
do {
if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
ASSERT(iclog->ic_state & XLOG_STATE_ACTIVE);
ASSERT(iclog->ic_offset == 0);
}
iclog = iclog->ic_next;
} while (iclog != first_iclog);
#endif
if (! (XLOG_FORCED_SHUTDOWN(log))) {
error = xfs_log_reserve(mp, 600, 1, &tic,
XFS_LOG, 0, XLOG_UNMOUNT_REC_TYPE);
if (!error) {
/* the data section must be 32 bit size aligned */
struct {
__uint16_t magic;
__uint16_t pad1;
__uint32_t pad2; /* may as well make it 64 bits */
} magic = {
.magic = XLOG_UNMOUNT_TYPE,
};
struct xfs_log_iovec reg = {
.i_addr = &magic,
.i_len = sizeof(magic),
.i_type = XLOG_REG_TYPE_UNMOUNT,
};
struct xfs_log_vec vec = {
.lv_niovecs = 1,
.lv_iovecp = ®,
};
/* remove inited flag, and account for space used */
tic->t_flags = 0;
tic->t_curr_res -= sizeof(magic);
error = xlog_write(log, &vec, tic, &lsn,
NULL, XLOG_UNMOUNT_TRANS);
/*
* At this point, we're umounting anyway,
* so there's no point in transitioning log state
* to IOERROR. Just continue...
*/
}
if (error)
xfs_alert(mp, "%s: unmount record failed", __func__);
spin_lock(&log->l_icloglock);
iclog = log->l_iclog;
atomic_inc(&iclog->ic_refcnt);
xlog_state_want_sync(log, iclog);
spin_unlock(&log->l_icloglock);
error = xlog_state_release_iclog(log, iclog);
spin_lock(&log->l_icloglock);
if (!(iclog->ic_state == XLOG_STATE_ACTIVE ||
iclog->ic_state == XLOG_STATE_DIRTY)) {
if (!XLOG_FORCED_SHUTDOWN(log)) {
xlog_wait(&iclog->ic_force_wait,
&log->l_icloglock);
} else {
spin_unlock(&log->l_icloglock);
}
} else {
spin_unlock(&log->l_icloglock);
}
if (tic) {
trace_xfs_log_umount_write(log, tic);
xlog_ungrant_log_space(log, tic);
xfs_log_ticket_put(tic);
}
} else {
/*
* We're already in forced_shutdown mode, couldn't
* even attempt to write out the unmount transaction.
*
* Go through the motions of sync'ing and releasing
* the iclog, even though no I/O will actually happen,
* we need to wait for other log I/Os that may already
* be in progress. Do this as a separate section of
* code so we'll know if we ever get stuck here that
* we're in this odd situation of trying to unmount
* a file system that went into forced_shutdown as
* the result of an unmount..
*/
spin_lock(&log->l_icloglock);
iclog = log->l_iclog;
atomic_inc(&iclog->ic_refcnt);
xlog_state_want_sync(log, iclog);
spin_unlock(&log->l_icloglock);
error = xlog_state_release_iclog(log, iclog);
spin_lock(&log->l_icloglock);
if ( ! ( iclog->ic_state == XLOG_STATE_ACTIVE
|| iclog->ic_state == XLOG_STATE_DIRTY
|| iclog->ic_state == XLOG_STATE_IOERROR) ) {
xlog_wait(&iclog->ic_force_wait,
&log->l_icloglock);
} else {
spin_unlock(&log->l_icloglock);
}
}
return error;
} /* xfs_log_unmount_write */
/*
* Deallocate log structures for unmount/relocation.
*
* We need to stop the aild from running before we destroy
* and deallocate the log as the aild references the log.
*/
void
xfs_log_unmount(xfs_mount_t *mp)
{
xfs_trans_ail_destroy(mp);
xlog_dealloc_log(mp->m_log);
}
void
xfs_log_item_init(
struct xfs_mount *mp,
struct xfs_log_item *item,
int type,
const struct xfs_item_ops *ops)
{
item->li_mountp = mp;
item->li_ailp = mp->m_ail;
item->li_type = type;
item->li_ops = ops;
item->li_lv = NULL;
INIT_LIST_HEAD(&item->li_ail);
INIT_LIST_HEAD(&item->li_cil);
}
/*
* Wake up processes waiting for log space after we have moved the log tail.
*/
void
xfs_log_space_wake(
struct xfs_mount *mp)
{
struct log *log = mp->m_log;
int free_bytes;
if (XLOG_FORCED_SHUTDOWN(log))
return;
if (!list_empty_careful(&log->l_write_head.waiters)) {
ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY));
spin_lock(&log->l_write_head.lock);
free_bytes = xlog_space_left(log, &log->l_write_head.grant);
xlog_grant_head_wake(log, &log->l_write_head, &free_bytes);
spin_unlock(&log->l_write_head.lock);
}
if (!list_empty_careful(&log->l_reserve_head.waiters)) {
ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY));
spin_lock(&log->l_reserve_head.lock);
free_bytes = xlog_space_left(log, &log->l_reserve_head.grant);
xlog_grant_head_wake(log, &log->l_reserve_head, &free_bytes);
spin_unlock(&log->l_reserve_head.lock);
}
}
/*
* Determine if we have a transaction that has gone to disk
* that needs to be covered. To begin the transition to the idle state
* firstly the log needs to be idle (no AIL and nothing in the iclogs).
* If we are then in a state where covering is needed, the caller is informed
* that dummy transactions are required to move the log into the idle state.
*
* Because this is called as part of the sync process, we should also indicate
* that dummy transactions should be issued in anything but the covered or
* idle states. This ensures that the log tail is accurately reflected in
* the log at the end of the sync, hence if a crash occurrs avoids replay
* of transactions where the metadata is already on disk.
*/
int
xfs_log_need_covered(xfs_mount_t *mp)
{
int needed = 0;
xlog_t *log = mp->m_log;
if (!xfs_fs_writable(mp))
return 0;
spin_lock(&log->l_icloglock);
switch (log->l_covered_state) {
case XLOG_STATE_COVER_DONE:
case XLOG_STATE_COVER_DONE2:
case XLOG_STATE_COVER_IDLE:
break;
case XLOG_STATE_COVER_NEED:
case XLOG_STATE_COVER_NEED2:
if (!xfs_ail_min_lsn(log->l_ailp) &&
xlog_iclogs_empty(log)) {
if (log->l_covered_state == XLOG_STATE_COVER_NEED)
log->l_covered_state = XLOG_STATE_COVER_DONE;
else
log->l_covered_state = XLOG_STATE_COVER_DONE2;
}
/* FALLTHRU */
default:
needed = 1;
break;
}
spin_unlock(&log->l_icloglock);
return needed;
}
/*
* We may be holding the log iclog lock upon entering this routine.
*/
xfs_lsn_t
xlog_assign_tail_lsn(
struct xfs_mount *mp)
{
xfs_lsn_t tail_lsn;
struct log *log = mp->m_log;
/*
* To make sure we always have a valid LSN for the log tail we keep
* track of the last LSN which was committed in log->l_last_sync_lsn,
* and use that when the AIL was empty and xfs_ail_min_lsn returns 0.
*
* If the AIL has been emptied we also need to wake any process
* waiting for this condition.
*/
tail_lsn = xfs_ail_min_lsn(mp->m_ail);
if (!tail_lsn)
tail_lsn = atomic64_read(&log->l_last_sync_lsn);
atomic64_set(&log->l_tail_lsn, tail_lsn);
return tail_lsn;
}
/*
* Return the space in the log between the tail and the head. The head
* is passed in the cycle/bytes formal parms. In the special case where
* the reserve head has wrapped passed the tail, this calculation is no
* longer valid. In this case, just return 0 which means there is no space
* in the log. This works for all places where this function is called
* with the reserve head. Of course, if the write head were to ever
* wrap the tail, we should blow up. Rather than catch this case here,
* we depend on other ASSERTions in other parts of the code. XXXmiken
*
* This code also handles the case where the reservation head is behind
* the tail. The details of this case are described below, but the end
* result is that we return the size of the log as the amount of space left.
*/
STATIC int
xlog_space_left(
struct log *log,
atomic64_t *head)
{
int free_bytes;
int tail_bytes;
int tail_cycle;
int head_cycle;
int head_bytes;
xlog_crack_grant_head(head, &head_cycle, &head_bytes);
xlog_crack_atomic_lsn(&log->l_tail_lsn, &tail_cycle, &tail_bytes);
tail_bytes = BBTOB(tail_bytes);
if (tail_cycle == head_cycle && head_bytes >= tail_bytes)
free_bytes = log->l_logsize - (head_bytes - tail_bytes);
else if (tail_cycle + 1 < head_cycle)
return 0;
else if (tail_cycle < head_cycle) {
ASSERT(tail_cycle == (head_cycle - 1));
free_bytes = tail_bytes - head_bytes;
} else {
/*
* The reservation head is behind the tail.
* In this case we just want to return the size of the
* log as the amount of space left.
*/
xfs_alert(log->l_mp,
"xlog_space_left: head behind tail\n"
" tail_cycle = %d, tail_bytes = %d\n"
" GH cycle = %d, GH bytes = %d",
tail_cycle, tail_bytes, head_cycle, head_bytes);
ASSERT(0);
free_bytes = log->l_logsize;
}
return free_bytes;
}
/*
* Log function which is called when an io completes.
*
* The log manager needs its own routine, in order to control what
* happens with the buffer after the write completes.
*/
void
xlog_iodone(xfs_buf_t *bp)
{
xlog_in_core_t *iclog = bp->b_fspriv;
xlog_t *l = iclog->ic_log;
int aborted = 0;
/*
* Race to shutdown the filesystem if we see an error.
*/
if (XFS_TEST_ERROR((xfs_buf_geterror(bp)), l->l_mp,
XFS_ERRTAG_IODONE_IOERR, XFS_RANDOM_IODONE_IOERR)) {
xfs_buf_ioerror_alert(bp, __func__);
xfs_buf_stale(bp);
xfs_force_shutdown(l->l_mp, SHUTDOWN_LOG_IO_ERROR);
/*
* This flag will be propagated to the trans-committed
* callback routines to let them know that the log-commit
* didn't succeed.
*/
aborted = XFS_LI_ABORTED;
} else if (iclog->ic_state & XLOG_STATE_IOERROR) {
aborted = XFS_LI_ABORTED;
}
/* log I/O is always issued ASYNC */
ASSERT(XFS_BUF_ISASYNC(bp));
xlog_state_done_syncing(iclog, aborted);
/*
* do not reference the buffer (bp) here as we could race
* with it being freed after writing the unmount record to the
* log.
*/
} /* xlog_iodone */
/*
* Return size of each in-core log record buffer.
*
* All machines get 8 x 32kB buffers by default, unless tuned otherwise.
*
* If the filesystem blocksize is too large, we may need to choose a
* larger size since the directory code currently logs entire blocks.
*/
STATIC void
xlog_get_iclog_buffer_size(xfs_mount_t *mp,
xlog_t *log)
{
int size;
int xhdrs;
if (mp->m_logbufs <= 0)
log->l_iclog_bufs = XLOG_MAX_ICLOGS;
else
log->l_iclog_bufs = mp->m_logbufs;
/*
* Buffer size passed in from mount system call.
*/
if (mp->m_logbsize > 0) {
size = log->l_iclog_size = mp->m_logbsize;
log->l_iclog_size_log = 0;
while (size != 1) {
log->l_iclog_size_log++;
size >>= 1;
}
if (xfs_sb_version_haslogv2(&mp->m_sb)) {
/* # headers = size / 32k
* one header holds cycles from 32k of data
*/
xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE;
if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE)
xhdrs++;
log->l_iclog_hsize = xhdrs << BBSHIFT;
log->l_iclog_heads = xhdrs;
} else {
ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE);
log->l_iclog_hsize = BBSIZE;
log->l_iclog_heads = 1;
}
goto done;
}
/* All machines use 32kB buffers by default. */
log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
/* the default log size is 16k or 32k which is one header sector */
log->l_iclog_hsize = BBSIZE;
log->l_iclog_heads = 1;
done:
/* are we being asked to make the sizes selected above visible? */
if (mp->m_logbufs == 0)
mp->m_logbufs = log->l_iclog_bufs;
if (mp->m_logbsize == 0)
mp->m_logbsize = log->l_iclog_size;
} /* xlog_get_iclog_buffer_size */
/*
* This routine initializes some of the log structure for a given mount point.
* Its primary purpose is to fill in enough, so recovery can occur. However,
* some other stuff may be filled in too.
*/
STATIC xlog_t *
xlog_alloc_log(xfs_mount_t *mp,
xfs_buftarg_t *log_target,
xfs_daddr_t blk_offset,
int num_bblks)
{
xlog_t *log;
xlog_rec_header_t *head;
xlog_in_core_t **iclogp;
xlog_in_core_t *iclog, *prev_iclog=NULL;
xfs_buf_t *bp;
int i;
int error = ENOMEM;
uint log2_size = 0;
log = kmem_zalloc(sizeof(xlog_t), KM_MAYFAIL);
if (!log) {
xfs_warn(mp, "Log allocation failed: No memory!");
goto out;
}
log->l_mp = mp;
log->l_targ = log_target;
log->l_logsize = BBTOB(num_bblks);
log->l_logBBstart = blk_offset;
log->l_logBBsize = num_bblks;
log->l_covered_state = XLOG_STATE_COVER_IDLE;
log->l_flags |= XLOG_ACTIVE_RECOVERY;
log->l_prev_block = -1;
/* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
xlog_assign_atomic_lsn(&log->l_tail_lsn, 1, 0);
xlog_assign_atomic_lsn(&log->l_last_sync_lsn, 1, 0);
log->l_curr_cycle = 1; /* 0 is bad since this is initial value */
xlog_grant_head_init(&log->l_reserve_head);
xlog_grant_head_init(&log->l_write_head);
error = EFSCORRUPTED;
if (xfs_sb_version_hassector(&mp->m_sb)) {
log2_size = mp->m_sb.sb_logsectlog;
if (log2_size < BBSHIFT) {
xfs_warn(mp, "Log sector size too small (0x%x < 0x%x)",
log2_size, BBSHIFT);
goto out_free_log;
}
log2_size -= BBSHIFT;
if (log2_size > mp->m_sectbb_log) {
xfs_warn(mp, "Log sector size too large (0x%x > 0x%x)",
log2_size, mp->m_sectbb_log);
goto out_free_log;
}
/* for larger sector sizes, must have v2 or external log */
if (log2_size && log->l_logBBstart > 0 &&
!xfs_sb_version_haslogv2(&mp->m_sb)) {
xfs_warn(mp,
"log sector size (0x%x) invalid for configuration.",
log2_size);
goto out_free_log;
}
}
log->l_sectBBsize = 1 << log2_size;
xlog_get_iclog_buffer_size(mp, log);
error = ENOMEM;
bp = xfs_buf_alloc(mp->m_logdev_targp, 0, log->l_iclog_size, 0);
if (!bp)
goto out_free_log;
bp->b_iodone = xlog_iodone;
ASSERT(xfs_buf_islocked(bp));
log->l_xbuf = bp;
spin_lock_init(&log->l_icloglock);
init_waitqueue_head(&log->l_flush_wait);
/* log record size must be multiple of BBSIZE; see xlog_rec_header_t */
ASSERT((XFS_BUF_SIZE(bp) & BBMASK) == 0);
iclogp = &log->l_iclog;
/*
* The amount of memory to allocate for the iclog structure is
* rather funky due to the way the structure is defined. It is
* done this way so that we can use different sizes for machines
* with different amounts of memory. See the definition of
* xlog_in_core_t in xfs_log_priv.h for details.
*/
ASSERT(log->l_iclog_size >= 4096);
for (i=0; i < log->l_iclog_bufs; i++) {
*iclogp = kmem_zalloc(sizeof(xlog_in_core_t), KM_MAYFAIL);
if (!*iclogp)
goto out_free_iclog;
iclog = *iclogp;
iclog->ic_prev = prev_iclog;
prev_iclog = iclog;
bp = xfs_buf_get_uncached(mp->m_logdev_targp,
log->l_iclog_size, 0);
if (!bp)
goto out_free_iclog;
bp->b_iodone = xlog_iodone;
iclog->ic_bp = bp;
iclog->ic_data = bp->b_addr;
#ifdef DEBUG
log->l_iclog_bak[i] = (xfs_caddr_t)&(iclog->ic_header);
#endif
head = &iclog->ic_header;
memset(head, 0, sizeof(xlog_rec_header_t));
head->h_magicno = cpu_to_be32(XLOG_HEADER_MAGIC_NUM);
head->h_version = cpu_to_be32(
xfs_sb_version_haslogv2(&log->l_mp->m_sb) ? 2 : 1);
head->h_size = cpu_to_be32(log->l_iclog_size);
/* new fields */
head->h_fmt = cpu_to_be32(XLOG_FMT);
memcpy(&head->h_fs_uuid, &mp->m_sb.sb_uuid, sizeof(uuid_t));
iclog->ic_size = XFS_BUF_SIZE(bp) - log->l_iclog_hsize;
iclog->ic_state = XLOG_STATE_ACTIVE;
iclog->ic_log = log;
atomic_set(&iclog->ic_refcnt, 0);
spin_lock_init(&iclog->ic_callback_lock);
iclog->ic_callback_tail = &(iclog->ic_callback);
iclog->ic_datap = (char *)iclog->ic_data + log->l_iclog_hsize;
ASSERT(xfs_buf_islocked(iclog->ic_bp));
init_waitqueue_head(&iclog->ic_force_wait);
init_waitqueue_head(&iclog->ic_write_wait);
iclogp = &iclog->ic_next;
}
*iclogp = log->l_iclog; /* complete ring */
log->l_iclog->ic_prev = prev_iclog; /* re-write 1st prev ptr */
error = xlog_cil_init(log);
if (error)
goto out_free_iclog;
return log;
out_free_iclog:
for (iclog = log->l_iclog; iclog; iclog = prev_iclog) {
prev_iclog = iclog->ic_next;
if (iclog->ic_bp)
xfs_buf_free(iclog->ic_bp);
kmem_free(iclog);
}
spinlock_destroy(&log->l_icloglock);
xfs_buf_free(log->l_xbuf);
out_free_log:
kmem_free(log);
out:
return ERR_PTR(-error);
} /* xlog_alloc_log */
/*
* Write out the commit record of a transaction associated with the given
* ticket. Return the lsn of the commit record.
*/
STATIC int
xlog_commit_record(
struct log *log,
struct xlog_ticket *ticket,
struct xlog_in_core **iclog,
xfs_lsn_t *commitlsnp)
{
struct xfs_mount *mp = log->l_mp;
int error;
struct xfs_log_iovec reg = {
.i_addr = NULL,
.i_len = 0,
.i_type = XLOG_REG_TYPE_COMMIT,
};
struct xfs_log_vec vec = {
.lv_niovecs = 1,
.lv_iovecp = ®,
};
ASSERT_ALWAYS(iclog);
error = xlog_write(log, &vec, ticket, commitlsnp, iclog,
XLOG_COMMIT_TRANS);
if (error)
xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
return error;
}
/*
* Push on the buffer cache code if we ever use more than 75% of the on-disk
* log space. This code pushes on the lsn which would supposedly free up
* the 25% which we want to leave free. We may need to adopt a policy which
* pushes on an lsn which is further along in the log once we reach the high
* water mark. In this manner, we would be creating a low water mark.
*/
STATIC void
xlog_grant_push_ail(
struct log *log,
int need_bytes)
{
xfs_lsn_t threshold_lsn = 0;
xfs_lsn_t last_sync_lsn;
int free_blocks;
int free_bytes;
int threshold_block;
int threshold_cycle;
int free_threshold;
ASSERT(BTOBB(need_bytes) < log->l_logBBsize);
free_bytes = xlog_space_left(log, &log->l_reserve_head.grant);
free_blocks = BTOBBT(free_bytes);
/*
* Set the threshold for the minimum number of free blocks in the
* log to the maximum of what the caller needs, one quarter of the
* log, and 256 blocks.
*/
free_threshold = BTOBB(need_bytes);
free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2));
free_threshold = MAX(free_threshold, 256);
if (free_blocks >= free_threshold)
return;
xlog_crack_atomic_lsn(&log->l_tail_lsn, &threshold_cycle,
&threshold_block);
threshold_block += free_threshold;
if (threshold_block >= log->l_logBBsize) {
threshold_block -= log->l_logBBsize;
threshold_cycle += 1;
}
threshold_lsn = xlog_assign_lsn(threshold_cycle,
threshold_block);
/*
* Don't pass in an lsn greater than the lsn of the last
* log record known to be on disk. Use a snapshot of the last sync lsn
* so that it doesn't change between the compare and the set.
*/
last_sync_lsn = atomic64_read(&log->l_last_sync_lsn);
if (XFS_LSN_CMP(threshold_lsn, last_sync_lsn) > 0)
threshold_lsn = last_sync_lsn;
/*
* Get the transaction layer to kick the dirty buffers out to
* disk asynchronously. No point in trying to do this if
* the filesystem is shutting down.
*/
if (!XLOG_FORCED_SHUTDOWN(log))
xfs_ail_push(log->l_ailp, threshold_lsn);
}
/*
* The bdstrat callback function for log bufs. This gives us a central
* place to trap bufs in case we get hit by a log I/O error and need to
* shutdown. Actually, in practice, even when we didn't get a log error,
* we transition the iclogs to IOERROR state *after* flushing all existing
* iclogs to disk. This is because we don't want anymore new transactions to be
* started or completed afterwards.
*/
STATIC int
xlog_bdstrat(
struct xfs_buf *bp)
{
struct xlog_in_core *iclog = bp->b_fspriv;
if (iclog->ic_state & XLOG_STATE_IOERROR) {
xfs_buf_ioerror(bp, EIO);
xfs_buf_stale(bp);
xfs_buf_ioend(bp, 0);
/*
* It would seem logical to return EIO here, but we rely on
* the log state machine to propagate I/O errors instead of
* doing it here.
*/
return 0;
}
xfs_buf_iorequest(bp);
return 0;
}
/*
* Flush out the in-core log (iclog) to the on-disk log in an asynchronous
* fashion. Previously, we should have moved the current iclog
* ptr in the log to point to the next available iclog. This allows further
* write to continue while this code syncs out an iclog ready to go.
* Before an in-core log can be written out, the data section must be scanned
* to save away the 1st word of each BBSIZE block into the header. We replace
* it with the current cycle count. Each BBSIZE block is tagged with the
* cycle count because there in an implicit assumption that drives will
* guarantee that entire 512 byte blocks get written at once. In other words,
* we can't have part of a 512 byte block written and part not written. By
* tagging each block, we will know which blocks are valid when recovering
* after an unclean shutdown.
*
* This routine is single threaded on the iclog. No other thread can be in
* this routine with the same iclog. Changing contents of iclog can there-
* fore be done without grabbing the state machine lock. Updating the global
* log will require grabbing the lock though.
*
* The entire log manager uses a logical block numbering scheme. Only
* log_sync (and then only bwrite()) know about the fact that the log may
* not start with block zero on a given device. The log block start offset
* is added immediately before calling bwrite().
*/
STATIC int
xlog_sync(xlog_t *log,
xlog_in_core_t *iclog)
{
xfs_caddr_t dptr; /* pointer to byte sized element */
xfs_buf_t *bp;
int i;
uint count; /* byte count of bwrite */
uint count_init; /* initial count before roundup */
int roundoff; /* roundoff to BB or stripe */
int split = 0; /* split write into two regions */
int error;
int v2 = xfs_sb_version_haslogv2(&log->l_mp->m_sb);
XFS_STATS_INC(xs_log_writes);
ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
/* Add for LR header */
count_init = log->l_iclog_hsize + iclog->ic_offset;
/* Round out the log write size */
if (v2 && log->l_mp->m_sb.sb_logsunit > 1) {
/* we have a v2 stripe unit to use */
count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init));
} else {
count = BBTOB(BTOBB(count_init));
}
roundoff = count - count_init;
ASSERT(roundoff >= 0);
ASSERT((v2 && log->l_mp->m_sb.sb_logsunit > 1 &&
roundoff < log->l_mp->m_sb.sb_logsunit)
||
(log->l_mp->m_sb.sb_logsunit <= 1 &&
roundoff < BBTOB(1)));
/* move grant heads by roundoff in sync */
xlog_grant_add_space(log, &log->l_reserve_head.grant, roundoff);
xlog_grant_add_space(log, &log->l_write_head.grant, roundoff);
/* put cycle number in every block */
xlog_pack_data(log, iclog, roundoff);
/* real byte length */
if (v2) {
iclog->ic_header.h_len =
cpu_to_be32(iclog->ic_offset + roundoff);
} else {
iclog->ic_header.h_len =
cpu_to_be32(iclog->ic_offset);
}
bp = iclog->ic_bp;
XFS_BUF_SET_ADDR(bp, BLOCK_LSN(be64_to_cpu(iclog->ic_header.h_lsn)));
XFS_STATS_ADD(xs_log_blocks, BTOBB(count));
/* Do we need to split this write into 2 parts? */
if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) {
split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)));
count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp));
iclog->ic_bwritecnt = 2; /* split into 2 writes */
} else {
iclog->ic_bwritecnt = 1;
}
XFS_BUF_SET_COUNT(bp, count);
bp->b_fspriv = iclog;
XFS_BUF_ZEROFLAGS(bp);
XFS_BUF_ASYNC(bp);
bp->b_flags |= XBF_SYNCIO;
if (log->l_mp->m_flags & XFS_MOUNT_BARRIER) {
bp->b_flags |= XBF_FUA;
/*
* Flush the data device before flushing the log to make
* sure all meta data written back from the AIL actually made
* it to disk before stamping the new log tail LSN into the
* log buffer. For an external log we need to issue the
* flush explicitly, and unfortunately synchronously here;
* for an internal log we can simply use the block layer
* state machine for preflushes.
*/
if (log->l_mp->m_logdev_targp != log->l_mp->m_ddev_targp)
xfs_blkdev_issue_flush(log->l_mp->m_ddev_targp);
else
bp->b_flags |= XBF_FLUSH;
}
ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
xlog_verify_iclog(log, iclog, count, B_TRUE);
/* account for log which doesn't start at block #0 */
XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
/*
* Don't call xfs_bwrite here. We do log-syncs even when the filesystem
* is shutting down.
*/
XFS_BUF_WRITE(bp);
error = xlog_bdstrat(bp);
if (error) {
xfs_buf_ioerror_alert(bp, "xlog_sync");
return error;
}
if (split) {
bp = iclog->ic_log->l_xbuf;
XFS_BUF_SET_ADDR(bp, 0); /* logical 0 */
xfs_buf_associate_memory(bp,
(char *)&iclog->ic_header + count, split);
bp->b_fspriv = iclog;
XFS_BUF_ZEROFLAGS(bp);
XFS_BUF_ASYNC(bp);
bp->b_flags |= XBF_SYNCIO;
if (log->l_mp->m_flags & XFS_MOUNT_BARRIER)
bp->b_flags |= XBF_FUA;
dptr = bp->b_addr;
/*
* Bump the cycle numbers at the start of each block
* since this part of the buffer is at the start of
* a new cycle. Watch out for the header magic number
* case, though.
*/
for (i = 0; i < split; i += BBSIZE) {
be32_add_cpu((__be32 *)dptr, 1);
if (be32_to_cpu(*(__be32 *)dptr) == XLOG_HEADER_MAGIC_NUM)
be32_add_cpu((__be32 *)dptr, 1);
dptr += BBSIZE;
}
ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
/* account for internal log which doesn't start at block #0 */
XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
XFS_BUF_WRITE(bp);
error = xlog_bdstrat(bp);
if (error) {
xfs_buf_ioerror_alert(bp, "xlog_sync (split)");
return error;
}
}
return 0;
} /* xlog_sync */
/*
* Deallocate a log structure
*/
STATIC void
xlog_dealloc_log(xlog_t *log)
{
xlog_in_core_t *iclog, *next_iclog;
int i;
xlog_cil_destroy(log);
/*
* always need to ensure that the extra buffer does not point to memory
* owned by another log buffer before we free it.
*/
xfs_buf_set_empty(log->l_xbuf, log->l_iclog_size);
xfs_buf_free(log->l_xbuf);
iclog = log->l_iclog;
for (i=0; i<log->l_iclog_bufs; i++) {
xfs_buf_free(iclog->ic_bp);
next_iclog = iclog->ic_next;
kmem_free(iclog);
iclog = next_iclog;
}
spinlock_destroy(&log->l_icloglock);
log->l_mp->m_log = NULL;
kmem_free(log);
} /* xlog_dealloc_log */
/*
* Update counters atomically now that memcpy is done.
*/
/* ARGSUSED */
static inline void
xlog_state_finish_copy(xlog_t *log,
xlog_in_core_t *iclog,
int record_cnt,
int copy_bytes)
{
spin_lock(&log->l_icloglock);
be32_add_cpu(&iclog->ic_header.h_num_logops, record_cnt);
iclog->ic_offset += copy_bytes;
spin_unlock(&log->l_icloglock);
} /* xlog_state_finish_copy */
/*
* print out info relating to regions written which consume
* the reservation
*/
void
xlog_print_tic_res(
struct xfs_mount *mp,
struct xlog_ticket *ticket)
{
uint i;
uint ophdr_spc = ticket->t_res_num_ophdrs * (uint)sizeof(xlog_op_header_t);
/* match with XLOG_REG_TYPE_* in xfs_log.h */
static char *res_type_str[XLOG_REG_TYPE_MAX] = {
"bformat",
"bchunk",
"efi_format",
"efd_format",
"iformat",
"icore",
"iext",
"ibroot",
"ilocal",
"iattr_ext",
"iattr_broot",
"iattr_local",
"qformat",
"dquot",
"quotaoff",
"LR header",
"unmount",
"commit",
"trans header"
};
static char *trans_type_str[XFS_TRANS_TYPE_MAX] = {
"SETATTR_NOT_SIZE",
"SETATTR_SIZE",
"INACTIVE",
"CREATE",
"CREATE_TRUNC",
"TRUNCATE_FILE",
"REMOVE",
"LINK",
"RENAME",
"MKDIR",
"RMDIR",
"SYMLINK",
"SET_DMATTRS",
"GROWFS",
"STRAT_WRITE",
"DIOSTRAT",
"WRITE_SYNC",
"WRITEID",
"ADDAFORK",
"ATTRINVAL",
"ATRUNCATE",
"ATTR_SET",
"ATTR_RM",
"ATTR_FLAG",
"CLEAR_AGI_BUCKET",
"QM_SBCHANGE",
"DUMMY1",
"DUMMY2",
"QM_QUOTAOFF",
"QM_DQALLOC",
"QM_SETQLIM",
"QM_DQCLUSTER",
"QM_QINOCREATE",
"QM_QUOTAOFF_END",
"SB_UNIT",
"FSYNC_TS",
"GROWFSRT_ALLOC",
"GROWFSRT_ZERO",
"GROWFSRT_FREE",
"SWAPEXT"
};
xfs_warn(mp,
"xlog_write: reservation summary:\n"
" trans type = %s (%u)\n"
" unit res = %d bytes\n"
" current res = %d bytes\n"
" total reg = %u bytes (o/flow = %u bytes)\n"
" ophdrs = %u (ophdr space = %u bytes)\n"
" ophdr + reg = %u bytes\n"
" num regions = %u\n",
((ticket->t_trans_type <= 0 ||
ticket->t_trans_type > XFS_TRANS_TYPE_MAX) ?
"bad-trans-type" : trans_type_str[ticket->t_trans_type-1]),
ticket->t_trans_type,
ticket->t_unit_res,
ticket->t_curr_res,
ticket->t_res_arr_sum, ticket->t_res_o_flow,
ticket->t_res_num_ophdrs, ophdr_spc,
ticket->t_res_arr_sum +
ticket->t_res_o_flow + ophdr_spc,
ticket->t_res_num);
for (i = 0; i < ticket->t_res_num; i++) {
uint r_type = ticket->t_res_arr[i].r_type;
xfs_warn(mp, "region[%u]: %s - %u bytes\n", i,
((r_type <= 0 || r_type > XLOG_REG_TYPE_MAX) ?
"bad-rtype" : res_type_str[r_type-1]),
ticket->t_res_arr[i].r_len);
}
xfs_alert_tag(mp, XFS_PTAG_LOGRES,
"xlog_write: reservation ran out. Need to up reservation");
xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
}
/*
* Calculate the potential space needed by the log vector. Each region gets
* its own xlog_op_header_t and may need to be double word aligned.
*/
static int
xlog_write_calc_vec_length(
struct xlog_ticket *ticket,
struct xfs_log_vec *log_vector)
{
struct xfs_log_vec *lv;
int headers = 0;
int len = 0;
int i;
/* acct for start rec of xact */
if (ticket->t_flags & XLOG_TIC_INITED)
headers++;
for (lv = log_vector; lv; lv = lv->lv_next) {
headers += lv->lv_niovecs;
for (i = 0; i < lv->lv_niovecs; i++) {
struct xfs_log_iovec *vecp = &lv->lv_iovecp[i];
len += vecp->i_len;
xlog_tic_add_region(ticket, vecp->i_len, vecp->i_type);
}
}
ticket->t_res_num_ophdrs += headers;
len += headers * sizeof(struct xlog_op_header);
return len;
}
/*
* If first write for transaction, insert start record We can't be trying to
* commit if we are inited. We can't have any "partial_copy" if we are inited.
*/
static int
xlog_write_start_rec(
struct xlog_op_header *ophdr,
struct xlog_ticket *ticket)
{
if (!(ticket->t_flags & XLOG_TIC_INITED))
return 0;
ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
ophdr->oh_clientid = ticket->t_clientid;
ophdr->oh_len = 0;
ophdr->oh_flags = XLOG_START_TRANS;
ophdr->oh_res2 = 0;
ticket->t_flags &= ~XLOG_TIC_INITED;
return sizeof(struct xlog_op_header);
}
static xlog_op_header_t *
xlog_write_setup_ophdr(
struct log *log,
struct xlog_op_header *ophdr,
struct xlog_ticket *ticket,
uint flags)
{
ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
ophdr->oh_clientid = ticket->t_clientid;
ophdr->oh_res2 = 0;
/* are we copying a commit or unmount record? */
ophdr->oh_flags = flags;
/*
* We've seen logs corrupted with bad transaction client ids. This
* makes sure that XFS doesn't generate them on. Turn this into an EIO
* and shut down the filesystem.
*/
switch (ophdr->oh_clientid) {
case XFS_TRANSACTION:
case XFS_VOLUME:
case XFS_LOG:
break;
default:
xfs_warn(log->l_mp,
"Bad XFS transaction clientid 0x%x in ticket 0x%p",
ophdr->oh_clientid, ticket);
return NULL;
}
return ophdr;
}
/*
* Set up the parameters of the region copy into the log. This has
* to handle region write split across multiple log buffers - this
* state is kept external to this function so that this code can
* can be written in an obvious, self documenting manner.
*/
static int
xlog_write_setup_copy(
struct xlog_ticket *ticket,
struct xlog_op_header *ophdr,
int space_available,
int space_required,
int *copy_off,
int *copy_len,
int *last_was_partial_copy,
int *bytes_consumed)
{
int still_to_copy;
still_to_copy = space_required - *bytes_consumed;
*copy_off = *bytes_consumed;
if (still_to_copy <= space_available) {
/* write of region completes here */
*copy_len = still_to_copy;
ophdr->oh_len = cpu_to_be32(*copy_len);
if (*last_was_partial_copy)
ophdr->oh_flags |= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS);
*last_was_partial_copy = 0;
*bytes_consumed = 0;
return 0;
}
/* partial write of region, needs extra log op header reservation */
*copy_len = space_available;
ophdr->oh_len = cpu_to_be32(*copy_len);
ophdr->oh_flags |= XLOG_CONTINUE_TRANS;
if (*last_was_partial_copy)
ophdr->oh_flags |= XLOG_WAS_CONT_TRANS;
*bytes_consumed += *copy_len;
(*last_was_partial_copy)++;
/* account for new log op header */
ticket->t_curr_res -= sizeof(struct xlog_op_header);
ticket->t_res_num_ophdrs++;
return sizeof(struct xlog_op_header);
}
static int
xlog_write_copy_finish(
struct log *log,
struct xlog_in_core *iclog,
uint flags,
int *record_cnt,
int *data_cnt,
int *partial_copy,
int *partial_copy_len,
int log_offset,
struct xlog_in_core **commit_iclog)
{
if (*partial_copy) {
/*
* This iclog has already been marked WANT_SYNC by
* xlog_state_get_iclog_space.
*/
xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt);
*record_cnt = 0;
*data_cnt = 0;
return xlog_state_release_iclog(log, iclog);
}
*partial_copy = 0;
*partial_copy_len = 0;
if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) {
/* no more space in this iclog - push it. */
xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt);
*record_cnt = 0;
*data_cnt = 0;
spin_lock(&log->l_icloglock);
xlog_state_want_sync(log, iclog);
spin_unlock(&log->l_icloglock);
if (!commit_iclog)
return xlog_state_release_iclog(log, iclog);
ASSERT(flags & XLOG_COMMIT_TRANS);
*commit_iclog = iclog;
}
return 0;
}
/*
* Write some region out to in-core log
*
* This will be called when writing externally provided regions or when
* writing out a commit record for a given transaction.
*
* General algorithm:
* 1. Find total length of this write. This may include adding to the
* lengths passed in.
* 2. Check whether we violate the tickets reservation.
* 3. While writing to this iclog
* A. Reserve as much space in this iclog as can get
* B. If this is first write, save away start lsn
* C. While writing this region:
* 1. If first write of transaction, write start record
* 2. Write log operation header (header per region)
* 3. Find out if we can fit entire region into this iclog
* 4. Potentially, verify destination memcpy ptr
* 5. Memcpy (partial) region
* 6. If partial copy, release iclog; otherwise, continue
* copying more regions into current iclog
* 4. Mark want sync bit (in simulation mode)
* 5. Release iclog for potential flush to on-disk log.
*
* ERRORS:
* 1. Panic if reservation is overrun. This should never happen since
* reservation amounts are generated internal to the filesystem.
* NOTES:
* 1. Tickets are single threaded data structures.
* 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
* syncing routine. When a single log_write region needs to span
* multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
* on all log operation writes which don't contain the end of the
* region. The XLOG_END_TRANS bit is used for the in-core log
* operation which contains the end of the continued log_write region.
* 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
* we don't really know exactly how much space will be used. As a result,
* we don't update ic_offset until the end when we know exactly how many
* bytes have been written out.
*/
int
xlog_write(
struct log *log,
struct xfs_log_vec *log_vector,
struct xlog_ticket *ticket,
xfs_lsn_t *start_lsn,
struct xlog_in_core **commit_iclog,
uint flags)
{
struct xlog_in_core *iclog = NULL;
struct xfs_log_iovec *vecp;
struct xfs_log_vec *lv;
int len;
int index;
int partial_copy = 0;
int partial_copy_len = 0;
int contwr = 0;
int record_cnt = 0;
int data_cnt = 0;
int error;
*start_lsn = 0;
len = xlog_write_calc_vec_length(ticket, log_vector);
/*
* Region headers and bytes are already accounted for.
* We only need to take into account start records and
* split regions in this function.
*/
if (ticket->t_flags & XLOG_TIC_INITED)
ticket->t_curr_res -= sizeof(xlog_op_header_t);
/*
* Commit record headers need to be accounted for. These
* come in as separate writes so are easy to detect.
*/
if (flags & (XLOG_COMMIT_TRANS | XLOG_UNMOUNT_TRANS))
ticket->t_curr_res -= sizeof(xlog_op_header_t);
if (ticket->t_curr_res < 0)
xlog_print_tic_res(log->l_mp, ticket);
index = 0;
lv = log_vector;
vecp = lv->lv_iovecp;
while (lv && index < lv->lv_niovecs) {
void *ptr;
int log_offset;
error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
&contwr, &log_offset);
if (error)
return error;
ASSERT(log_offset <= iclog->ic_size - 1);
ptr = iclog->ic_datap + log_offset;
/* start_lsn is the first lsn written to. That's all we need. */
if (!*start_lsn)
*start_lsn = be64_to_cpu(iclog->ic_header.h_lsn);
/*
* This loop writes out as many regions as can fit in the amount
* of space which was allocated by xlog_state_get_iclog_space().
*/
while (lv && index < lv->lv_niovecs) {
struct xfs_log_iovec *reg = &vecp[index];
struct xlog_op_header *ophdr;
int start_rec_copy;
int copy_len;
int copy_off;
ASSERT(reg->i_len % sizeof(__int32_t) == 0);
ASSERT((unsigned long)ptr % sizeof(__int32_t) == 0);
start_rec_copy = xlog_write_start_rec(ptr, ticket);
if (start_rec_copy) {
record_cnt++;
xlog_write_adv_cnt(&ptr, &len, &log_offset,
start_rec_copy);
}
ophdr = xlog_write_setup_ophdr(log, ptr, ticket, flags);
if (!ophdr)
return XFS_ERROR(EIO);
xlog_write_adv_cnt(&ptr, &len, &log_offset,
sizeof(struct xlog_op_header));
len += xlog_write_setup_copy(ticket, ophdr,
iclog->ic_size-log_offset,
reg->i_len,
©_off, ©_len,
&partial_copy,
&partial_copy_len);
xlog_verify_dest_ptr(log, ptr);
/* copy region */
ASSERT(copy_len >= 0);
memcpy(ptr, reg->i_addr + copy_off, copy_len);
xlog_write_adv_cnt(&ptr, &len, &log_offset, copy_len);
copy_len += start_rec_copy + sizeof(xlog_op_header_t);
record_cnt++;
data_cnt += contwr ? copy_len : 0;
error = xlog_write_copy_finish(log, iclog, flags,
&record_cnt, &data_cnt,
&partial_copy,
&partial_copy_len,
log_offset,
commit_iclog);
if (error)
return error;
/*
* if we had a partial copy, we need to get more iclog
* space but we don't want to increment the region
* index because there is still more is this region to
* write.
*
* If we completed writing this region, and we flushed
* the iclog (indicated by resetting of the record
* count), then we also need to get more log space. If
* this was the last record, though, we are done and
* can just return.
*/
if (partial_copy)
break;
if (++index == lv->lv_niovecs) {
lv = lv->lv_next;
index = 0;
if (lv)
vecp = lv->lv_iovecp;
}
if (record_cnt == 0) {
if (!lv)
return 0;
break;
}
}
}
ASSERT(len == 0);
xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
if (!commit_iclog)
return xlog_state_release_iclog(log, iclog);
ASSERT(flags & XLOG_COMMIT_TRANS);
*commit_iclog = iclog;
return 0;
}
/*****************************************************************************
*
* State Machine functions
*
*****************************************************************************
*/
/* Clean iclogs starting from the head. This ordering must be
* maintained, so an iclog doesn't become ACTIVE beyond one that
* is SYNCING. This is also required to maintain the notion that we use
* a ordered wait queue to hold off would be writers to the log when every
* iclog is trying to sync to disk.
*
* State Change: DIRTY -> ACTIVE
*/
STATIC void
xlog_state_clean_log(xlog_t *log)
{
xlog_in_core_t *iclog;
int changed = 0;
iclog = log->l_iclog;
do {
if (iclog->ic_state == XLOG_STATE_DIRTY) {
iclog->ic_state = XLOG_STATE_ACTIVE;
iclog->ic_offset = 0;
ASSERT(iclog->ic_callback == NULL);
/*
* If the number of ops in this iclog indicate it just
* contains the dummy transaction, we can
* change state into IDLE (the second time around).
* Otherwise we should change the state into
* NEED a dummy.
* We don't need to cover the dummy.
*/
if (!changed &&
(be32_to_cpu(iclog->ic_header.h_num_logops) ==
XLOG_COVER_OPS)) {
changed = 1;
} else {
/*
* We have two dirty iclogs so start over
* This could also be num of ops indicates
* this is not the dummy going out.
*/
changed = 2;
}
iclog->ic_header.h_num_logops = 0;
memset(iclog->ic_header.h_cycle_data, 0,
sizeof(iclog->ic_header.h_cycle_data));
iclog->ic_header.h_lsn = 0;
} else if (iclog->ic_state == XLOG_STATE_ACTIVE)
/* do nothing */;
else
break; /* stop cleaning */
iclog = iclog->ic_next;
} while (iclog != log->l_iclog);
/* log is locked when we are called */
/*
* Change state for the dummy log recording.
* We usually go to NEED. But we go to NEED2 if the changed indicates
* we are done writing the dummy record.
* If we are done with the second dummy recored (DONE2), then
* we go to IDLE.
*/
if (changed) {
switch (log->l_covered_state) {
case XLOG_STATE_COVER_IDLE:
case XLOG_STATE_COVER_NEED:
case XLOG_STATE_COVER_NEED2:
log->l_covered_state = XLOG_STATE_COVER_NEED;
break;
case XLOG_STATE_COVER_DONE:
if (changed == 1)
log->l_covered_state = XLOG_STATE_COVER_NEED2;
else
log->l_covered_state = XLOG_STATE_COVER_NEED;
break;
case XLOG_STATE_COVER_DONE2:
if (changed == 1)
log->l_covered_state = XLOG_STATE_COVER_IDLE;
else
log->l_covered_state = XLOG_STATE_COVER_NEED;
break;
default:
ASSERT(0);
}
}
} /* xlog_state_clean_log */
STATIC xfs_lsn_t
xlog_get_lowest_lsn(
xlog_t *log)
{
xlog_in_core_t *lsn_log;
xfs_lsn_t lowest_lsn, lsn;
lsn_log = log->l_iclog;
lowest_lsn = 0;
do {
if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) {
lsn = be64_to_cpu(lsn_log->ic_header.h_lsn);
if ((lsn && !lowest_lsn) ||
(XFS_LSN_CMP(lsn, lowest_lsn) < 0)) {
lowest_lsn = lsn;
}
}
lsn_log = lsn_log->ic_next;
} while (lsn_log != log->l_iclog);
return lowest_lsn;
}
STATIC void
xlog_state_do_callback(
xlog_t *log,
int aborted,
xlog_in_core_t *ciclog)
{
xlog_in_core_t *iclog;
xlog_in_core_t *first_iclog; /* used to know when we've
* processed all iclogs once */
xfs_log_callback_t *cb, *cb_next;
int flushcnt = 0;
xfs_lsn_t lowest_lsn;
int ioerrors; /* counter: iclogs with errors */
int loopdidcallbacks; /* flag: inner loop did callbacks*/
int funcdidcallbacks; /* flag: function did callbacks */
int repeats; /* for issuing console warnings if
* looping too many times */
int wake = 0;
spin_lock(&log->l_icloglock);
first_iclog = iclog = log->l_iclog;
ioerrors = 0;
funcdidcallbacks = 0;
repeats = 0;
do {
/*
* Scan all iclogs starting with the one pointed to by the
* log. Reset this starting point each time the log is
* unlocked (during callbacks).
*
* Keep looping through iclogs until one full pass is made
* without running any callbacks.
*/
first_iclog = log->l_iclog;
iclog = log->l_iclog;
loopdidcallbacks = 0;
repeats++;
do {
/* skip all iclogs in the ACTIVE & DIRTY states */
if (iclog->ic_state &
(XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) {
iclog = iclog->ic_next;
continue;
}
/*
* Between marking a filesystem SHUTDOWN and stopping
* the log, we do flush all iclogs to disk (if there
* wasn't a log I/O error). So, we do want things to
* go smoothly in case of just a SHUTDOWN w/o a
* LOG_IO_ERROR.
*/
if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
/*
* Can only perform callbacks in order. Since
* this iclog is not in the DONE_SYNC/
* DO_CALLBACK state, we skip the rest and
* just try to clean up. If we set our iclog
* to DO_CALLBACK, we will not process it when
* we retry since a previous iclog is in the
* CALLBACK and the state cannot change since
* we are holding the l_icloglock.
*/
if (!(iclog->ic_state &
(XLOG_STATE_DONE_SYNC |
XLOG_STATE_DO_CALLBACK))) {
if (ciclog && (ciclog->ic_state ==
XLOG_STATE_DONE_SYNC)) {
ciclog->ic_state = XLOG_STATE_DO_CALLBACK;
}
break;
}
/*
* We now have an iclog that is in either the
* DO_CALLBACK or DONE_SYNC states. The other
* states (WANT_SYNC, SYNCING, or CALLBACK were
* caught by the above if and are going to
* clean (i.e. we aren't doing their callbacks)
* see the above if.
*/
/*
* We will do one more check here to see if we
* have chased our tail around.
*/
lowest_lsn = xlog_get_lowest_lsn(log);
if (lowest_lsn &&
XFS_LSN_CMP(lowest_lsn,
be64_to_cpu(iclog->ic_header.h_lsn)) < 0) {
iclog = iclog->ic_next;
continue; /* Leave this iclog for
* another thread */
}
iclog->ic_state = XLOG_STATE_CALLBACK;
/*
* update the last_sync_lsn before we drop the
* icloglock to ensure we are the only one that
* can update it.
*/
ASSERT(XFS_LSN_CMP(atomic64_read(&log->l_last_sync_lsn),
be64_to_cpu(iclog->ic_header.h_lsn)) <= 0);
atomic64_set(&log->l_last_sync_lsn,
be64_to_cpu(iclog->ic_header.h_lsn));
} else
ioerrors++;
spin_unlock(&log->l_icloglock);
/*
* Keep processing entries in the callback list until
* we come around and it is empty. We need to
* atomically see that the list is empty and change the
* state to DIRTY so that we don't miss any more
* callbacks being added.
*/
spin_lock(&iclog->ic_callback_lock);
cb = iclog->ic_callback;
while (cb) {
iclog->ic_callback_tail = &(iclog->ic_callback);
iclog->ic_callback = NULL;
spin_unlock(&iclog->ic_callback_lock);
/* perform callbacks in the order given */
for (; cb; cb = cb_next) {
cb_next = cb->cb_next;
cb->cb_func(cb->cb_arg, aborted);
}
spin_lock(&iclog->ic_callback_lock);
cb = iclog->ic_callback;
}
loopdidcallbacks++;
funcdidcallbacks++;
spin_lock(&log->l_icloglock);
ASSERT(iclog->ic_callback == NULL);
spin_unlock(&iclog->ic_callback_lock);
if (!(iclog->ic_state & XLOG_STATE_IOERROR))
iclog->ic_state = XLOG_STATE_DIRTY;
/*
* Transition from DIRTY to ACTIVE if applicable.
* NOP if STATE_IOERROR.
*/
xlog_state_clean_log(log);
/* wake up threads waiting in xfs_log_force() */
wake_up_all(&iclog->ic_force_wait);
iclog = iclog->ic_next;
} while (first_iclog != iclog);
if (repeats > 5000) {
flushcnt += repeats;
repeats = 0;
xfs_warn(log->l_mp,
"%s: possible infinite loop (%d iterations)",
__func__, flushcnt);
}
} while (!ioerrors && loopdidcallbacks);
/*
* make one last gasp attempt to see if iclogs are being left in
* limbo..
*/
#ifdef DEBUG
if (funcdidcallbacks) {
first_iclog = iclog = log->l_iclog;
do {
ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK);
/*
* Terminate the loop if iclogs are found in states
* which will cause other threads to clean up iclogs.
*
* SYNCING - i/o completion will go through logs
* DONE_SYNC - interrupt thread should be waiting for
* l_icloglock
* IOERROR - give up hope all ye who enter here
*/
if (iclog->ic_state == XLOG_STATE_WANT_SYNC ||
iclog->ic_state == XLOG_STATE_SYNCING ||
iclog->ic_state == XLOG_STATE_DONE_SYNC ||
iclog->ic_state == XLOG_STATE_IOERROR )
break;
iclog = iclog->ic_next;
} while (first_iclog != iclog);
}
#endif
if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR))
wake = 1;
spin_unlock(&log->l_icloglock);
if (wake)
wake_up_all(&log->l_flush_wait);
}
/*
* Finish transitioning this iclog to the dirty state.
*
* Make sure that we completely execute this routine only when this is
* the last call to the iclog. There is a good chance that iclog flushes,
* when we reach the end of the physical log, get turned into 2 separate
* calls to bwrite. Hence, one iclog flush could generate two calls to this
* routine. By using the reference count bwritecnt, we guarantee that only
* the second completion goes through.
*
* Callbacks could take time, so they are done outside the scope of the
* global state machine log lock.
*/
STATIC void
xlog_state_done_syncing(
xlog_in_core_t *iclog,
int aborted)
{
xlog_t *log = iclog->ic_log;
spin_lock(&log->l_icloglock);
ASSERT(iclog->ic_state == XLOG_STATE_SYNCING ||
iclog->ic_state == XLOG_STATE_IOERROR);
ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2);
/*
* If we got an error, either on the first buffer, or in the case of
* split log writes, on the second, we mark ALL iclogs STATE_IOERROR,
* and none should ever be attempted to be written to disk
* again.
*/
if (iclog->ic_state != XLOG_STATE_IOERROR) {
if (--iclog->ic_bwritecnt == 1) {
spin_unlock(&log->l_icloglock);
return;
}
iclog->ic_state = XLOG_STATE_DONE_SYNC;
}
/*
* Someone could be sleeping prior to writing out the next
* iclog buffer, we wake them all, one will get to do the
* I/O, the others get to wait for the result.
*/
wake_up_all(&iclog->ic_write_wait);
spin_unlock(&log->l_icloglock);
xlog_state_do_callback(log, aborted, iclog); /* also cleans log */
} /* xlog_state_done_syncing */
/*
* If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
* sleep. We wait on the flush queue on the head iclog as that should be
* the first iclog to complete flushing. Hence if all iclogs are syncing,
* we will wait here and all new writes will sleep until a sync completes.
*
* The in-core logs are used in a circular fashion. They are not used
* out-of-order even when an iclog past the head is free.
*
* return:
* * log_offset where xlog_write() can start writing into the in-core
* log's data space.
* * in-core log pointer to which xlog_write() should write.
* * boolean indicating this is a continued write to an in-core log.
* If this is the last write, then the in-core log's offset field
* needs to be incremented, depending on the amount of data which
* is copied.
*/
STATIC int
xlog_state_get_iclog_space(xlog_t *log,
int len,
xlog_in_core_t **iclogp,
xlog_ticket_t *ticket,
int *continued_write,
int *logoffsetp)
{
int log_offset;
xlog_rec_header_t *head;
xlog_in_core_t *iclog;
int error;
restart:
spin_lock(&log->l_icloglock);
if (XLOG_FORCED_SHUTDOWN(log)) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
iclog = log->l_iclog;
if (iclog->ic_state != XLOG_STATE_ACTIVE) {
XFS_STATS_INC(xs_log_noiclogs);
/* Wait for log writes to have flushed */
xlog_wait(&log->l_flush_wait, &log->l_icloglock);
goto restart;
}
head = &iclog->ic_header;
atomic_inc(&iclog->ic_refcnt); /* prevents sync */
log_offset = iclog->ic_offset;
/* On the 1st write to an iclog, figure out lsn. This works
* if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
* committing to. If the offset is set, that's how many blocks
* must be written.
*/
if (log_offset == 0) {
ticket->t_curr_res -= log->l_iclog_hsize;
xlog_tic_add_region(ticket,
log->l_iclog_hsize,
XLOG_REG_TYPE_LRHEADER);
head->h_cycle = cpu_to_be32(log->l_curr_cycle);
head->h_lsn = cpu_to_be64(
xlog_assign_lsn(log->l_curr_cycle, log->l_curr_block));
ASSERT(log->l_curr_block >= 0);
}
/* If there is enough room to write everything, then do it. Otherwise,
* claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
* bit is on, so this will get flushed out. Don't update ic_offset
* until you know exactly how many bytes get copied. Therefore, wait
* until later to update ic_offset.
*
* xlog_write() algorithm assumes that at least 2 xlog_op_header_t's
* can fit into remaining data section.
*/
if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) {
xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
/*
* If I'm the only one writing to this iclog, sync it to disk.
* We need to do an atomic compare and decrement here to avoid
* racing with concurrent atomic_dec_and_lock() calls in
* xlog_state_release_iclog() when there is more than one
* reference to the iclog.
*/
if (!atomic_add_unless(&iclog->ic_refcnt, -1, 1)) {
/* we are the only one */
spin_unlock(&log->l_icloglock);
error = xlog_state_release_iclog(log, iclog);
if (error)
return error;
} else {
spin_unlock(&log->l_icloglock);
}
goto restart;
}
/* Do we have enough room to write the full amount in the remainder
* of this iclog? Or must we continue a write on the next iclog and
* mark this iclog as completely taken? In the case where we switch
* iclogs (to mark it taken), this particular iclog will release/sync
* to disk in xlog_write().
*/
if (len <= iclog->ic_size - iclog->ic_offset) {
*continued_write = 0;
iclog->ic_offset += len;
} else {
*continued_write = 1;
xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
}
*iclogp = iclog;
ASSERT(iclog->ic_offset <= iclog->ic_size);
spin_unlock(&log->l_icloglock);
*logoffsetp = log_offset;
return 0;
} /* xlog_state_get_iclog_space */
/* The first cnt-1 times through here we don't need to
* move the grant write head because the permanent
* reservation has reserved cnt times the unit amount.
* Release part of current permanent unit reservation and
* reset current reservation to be one units worth. Also
* move grant reservation head forward.
*/
STATIC void
xlog_regrant_reserve_log_space(xlog_t *log,
xlog_ticket_t *ticket)
{
trace_xfs_log_regrant_reserve_enter(log, ticket);
if (ticket->t_cnt > 0)
ticket->t_cnt--;
xlog_grant_sub_space(log, &log->l_reserve_head.grant,
ticket->t_curr_res);
xlog_grant_sub_space(log, &log->l_write_head.grant,
ticket->t_curr_res);
ticket->t_curr_res = ticket->t_unit_res;
xlog_tic_reset_res(ticket);
trace_xfs_log_regrant_reserve_sub(log, ticket);
/* just return if we still have some of the pre-reserved space */
if (ticket->t_cnt > 0)
return;
xlog_grant_add_space(log, &log->l_reserve_head.grant,
ticket->t_unit_res);
trace_xfs_log_regrant_reserve_exit(log, ticket);
ticket->t_curr_res = ticket->t_unit_res;
xlog_tic_reset_res(ticket);
} /* xlog_regrant_reserve_log_space */
/*
* Give back the space left from a reservation.
*
* All the information we need to make a correct determination of space left
* is present. For non-permanent reservations, things are quite easy. The
* count should have been decremented to zero. We only need to deal with the
* space remaining in the current reservation part of the ticket. If the
* ticket contains a permanent reservation, there may be left over space which
* needs to be released. A count of N means that N-1 refills of the current
* reservation can be done before we need to ask for more space. The first
* one goes to fill up the first current reservation. Once we run out of
* space, the count will stay at zero and the only space remaining will be
* in the current reservation field.
*/
STATIC void
xlog_ungrant_log_space(xlog_t *log,
xlog_ticket_t *ticket)
{
int bytes;
if (ticket->t_cnt > 0)
ticket->t_cnt--;
trace_xfs_log_ungrant_enter(log, ticket);
trace_xfs_log_ungrant_sub(log, ticket);
/*
* If this is a permanent reservation ticket, we may be able to free
* up more space based on the remaining count.
*/
bytes = ticket->t_curr_res;
if (ticket->t_cnt > 0) {
ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
bytes += ticket->t_unit_res*ticket->t_cnt;
}
xlog_grant_sub_space(log, &log->l_reserve_head.grant, bytes);
xlog_grant_sub_space(log, &log->l_write_head.grant, bytes);
trace_xfs_log_ungrant_exit(log, ticket);
xfs_log_space_wake(log->l_mp);
}
/*
* Flush iclog to disk if this is the last reference to the given iclog and
* the WANT_SYNC bit is set.
*
* When this function is entered, the iclog is not necessarily in the
* WANT_SYNC state. It may be sitting around waiting to get filled.
*
*
*/
STATIC int
xlog_state_release_iclog(
xlog_t *log,
xlog_in_core_t *iclog)
{
int sync = 0; /* do we sync? */
if (iclog->ic_state & XLOG_STATE_IOERROR)
return XFS_ERROR(EIO);
ASSERT(atomic_read(&iclog->ic_refcnt) > 0);
if (!atomic_dec_and_lock(&iclog->ic_refcnt, &log->l_icloglock))
return 0;
if (iclog->ic_state & XLOG_STATE_IOERROR) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE ||
iclog->ic_state == XLOG_STATE_WANT_SYNC);
if (iclog->ic_state == XLOG_STATE_WANT_SYNC) {
/* update tail before writing to iclog */
xfs_lsn_t tail_lsn = xlog_assign_tail_lsn(log->l_mp);
sync++;
iclog->ic_state = XLOG_STATE_SYNCING;
iclog->ic_header.h_tail_lsn = cpu_to_be64(tail_lsn);
xlog_verify_tail_lsn(log, iclog, tail_lsn);
/* cycle incremented when incrementing curr_block */
}
spin_unlock(&log->l_icloglock);
/*
* We let the log lock go, so it's possible that we hit a log I/O
* error or some other SHUTDOWN condition that marks the iclog
* as XLOG_STATE_IOERROR before the bwrite. However, we know that
* this iclog has consistent data, so we ignore IOERROR
* flags after this point.
*/
if (sync)
return xlog_sync(log, iclog);
return 0;
} /* xlog_state_release_iclog */
/*
* This routine will mark the current iclog in the ring as WANT_SYNC
* and move the current iclog pointer to the next iclog in the ring.
* When this routine is called from xlog_state_get_iclog_space(), the
* exact size of the iclog has not yet been determined. All we know is
* that every data block. We have run out of space in this log record.
*/
STATIC void
xlog_state_switch_iclogs(xlog_t *log,
xlog_in_core_t *iclog,
int eventual_size)
{
ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
if (!eventual_size)
eventual_size = iclog->ic_offset;
iclog->ic_state = XLOG_STATE_WANT_SYNC;
iclog->ic_header.h_prev_block = cpu_to_be32(log->l_prev_block);
log->l_prev_block = log->l_curr_block;
log->l_prev_cycle = log->l_curr_cycle;
/* roll log?: ic_offset changed later */
log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
/* Round up to next log-sunit */
if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
log->l_mp->m_sb.sb_logsunit > 1) {
__uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit);
log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
}
if (log->l_curr_block >= log->l_logBBsize) {
log->l_curr_cycle++;
if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
log->l_curr_cycle++;
log->l_curr_block -= log->l_logBBsize;
ASSERT(log->l_curr_block >= 0);
}
ASSERT(iclog == log->l_iclog);
log->l_iclog = iclog->ic_next;
} /* xlog_state_switch_iclogs */
/*
* Write out all data in the in-core log as of this exact moment in time.
*
* Data may be written to the in-core log during this call. However,
* we don't guarantee this data will be written out. A change from past
* implementation means this routine will *not* write out zero length LRs.
*
* Basically, we try and perform an intelligent scan of the in-core logs.
* If we determine there is no flushable data, we just return. There is no
* flushable data if:
*
* 1. the current iclog is active and has no data; the previous iclog
* is in the active or dirty state.
* 2. the current iclog is drity, and the previous iclog is in the
* active or dirty state.
*
* We may sleep if:
*
* 1. the current iclog is not in the active nor dirty state.
* 2. the current iclog dirty, and the previous iclog is not in the
* active nor dirty state.
* 3. the current iclog is active, and there is another thread writing
* to this particular iclog.
* 4. a) the current iclog is active and has no other writers
* b) when we return from flushing out this iclog, it is still
* not in the active nor dirty state.
*/
int
_xfs_log_force(
struct xfs_mount *mp,
uint flags,
int *log_flushed)
{
struct log *log = mp->m_log;
struct xlog_in_core *iclog;
xfs_lsn_t lsn;
XFS_STATS_INC(xs_log_force);
xlog_cil_force(log);
spin_lock(&log->l_icloglock);
iclog = log->l_iclog;
if (iclog->ic_state & XLOG_STATE_IOERROR) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
/* If the head iclog is not active nor dirty, we just attach
* ourselves to the head and go to sleep.
*/
if (iclog->ic_state == XLOG_STATE_ACTIVE ||
iclog->ic_state == XLOG_STATE_DIRTY) {
/*
* If the head is dirty or (active and empty), then
* we need to look at the previous iclog. If the previous
* iclog is active or dirty we are done. There is nothing
* to sync out. Otherwise, we attach ourselves to the
* previous iclog and go to sleep.
*/
if (iclog->ic_state == XLOG_STATE_DIRTY ||
(atomic_read(&iclog->ic_refcnt) == 0
&& iclog->ic_offset == 0)) {
iclog = iclog->ic_prev;
if (iclog->ic_state == XLOG_STATE_ACTIVE ||
iclog->ic_state == XLOG_STATE_DIRTY)
goto no_sleep;
else
goto maybe_sleep;
} else {
if (atomic_read(&iclog->ic_refcnt) == 0) {
/* We are the only one with access to this
* iclog. Flush it out now. There should
* be a roundoff of zero to show that someone
* has already taken care of the roundoff from
* the previous sync.
*/
atomic_inc(&iclog->ic_refcnt);
lsn = be64_to_cpu(iclog->ic_header.h_lsn);
xlog_state_switch_iclogs(log, iclog, 0);
spin_unlock(&log->l_icloglock);
if (xlog_state_release_iclog(log, iclog))
return XFS_ERROR(EIO);
if (log_flushed)
*log_flushed = 1;
spin_lock(&log->l_icloglock);
if (be64_to_cpu(iclog->ic_header.h_lsn) == lsn &&
iclog->ic_state != XLOG_STATE_DIRTY)
goto maybe_sleep;
else
goto no_sleep;
} else {
/* Someone else is writing to this iclog.
* Use its call to flush out the data. However,
* the other thread may not force out this LR,
* so we mark it WANT_SYNC.
*/
xlog_state_switch_iclogs(log, iclog, 0);
goto maybe_sleep;
}
}
}
/* By the time we come around again, the iclog could've been filled
* which would give it another lsn. If we have a new lsn, just
* return because the relevant data has been flushed.
*/
maybe_sleep:
if (flags & XFS_LOG_SYNC) {
/*
* We must check if we're shutting down here, before
* we wait, while we're holding the l_icloglock.
* Then we check again after waking up, in case our
* sleep was disturbed by a bad news.
*/
if (iclog->ic_state & XLOG_STATE_IOERROR) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
XFS_STATS_INC(xs_log_force_sleep);
xlog_wait(&iclog->ic_force_wait, &log->l_icloglock);
/*
* No need to grab the log lock here since we're
* only deciding whether or not to return EIO
* and the memory read should be atomic.
*/
if (iclog->ic_state & XLOG_STATE_IOERROR)
return XFS_ERROR(EIO);
if (log_flushed)
*log_flushed = 1;
} else {
no_sleep:
spin_unlock(&log->l_icloglock);
}
return 0;
}
/*
* Wrapper for _xfs_log_force(), to be used when caller doesn't care
* about errors or whether the log was flushed or not. This is the normal
* interface to use when trying to unpin items or move the log forward.
*/
void
xfs_log_force(
xfs_mount_t *mp,
uint flags)
{
int error;
error = _xfs_log_force(mp, flags, NULL);
if (error)
xfs_warn(mp, "%s: error %d returned.", __func__, error);
}
/*
* Force the in-core log to disk for a specific LSN.
*
* Find in-core log with lsn.
* If it is in the DIRTY state, just return.
* If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
* state and go to sleep or return.
* If it is in any other state, go to sleep or return.
*
* Synchronous forces are implemented with a signal variable. All callers
* to force a given lsn to disk will wait on a the sv attached to the
* specific in-core log. When given in-core log finally completes its
* write to disk, that thread will wake up all threads waiting on the
* sv.
*/
int
_xfs_log_force_lsn(
struct xfs_mount *mp,
xfs_lsn_t lsn,
uint flags,
int *log_flushed)
{
struct log *log = mp->m_log;
struct xlog_in_core *iclog;
int already_slept = 0;
ASSERT(lsn != 0);
XFS_STATS_INC(xs_log_force);
lsn = xlog_cil_force_lsn(log, lsn);
if (lsn == NULLCOMMITLSN)
return 0;
try_again:
spin_lock(&log->l_icloglock);
iclog = log->l_iclog;
if (iclog->ic_state & XLOG_STATE_IOERROR) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
do {
if (be64_to_cpu(iclog->ic_header.h_lsn) != lsn) {
iclog = iclog->ic_next;
continue;
}
if (iclog->ic_state == XLOG_STATE_DIRTY) {
spin_unlock(&log->l_icloglock);
return 0;
}
if (iclog->ic_state == XLOG_STATE_ACTIVE) {
/*
* We sleep here if we haven't already slept (e.g.
* this is the first time we've looked at the correct
* iclog buf) and the buffer before us is going to
* be sync'ed. The reason for this is that if we
* are doing sync transactions here, by waiting for
* the previous I/O to complete, we can allow a few
* more transactions into this iclog before we close
* it down.
*
* Otherwise, we mark the buffer WANT_SYNC, and bump
* up the refcnt so we can release the log (which
* drops the ref count). The state switch keeps new
* transaction commits from using this buffer. When
* the current commits finish writing into the buffer,
* the refcount will drop to zero and the buffer will
* go out then.
*/
if (!already_slept &&
(iclog->ic_prev->ic_state &
(XLOG_STATE_WANT_SYNC | XLOG_STATE_SYNCING))) {
ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR));
XFS_STATS_INC(xs_log_force_sleep);
xlog_wait(&iclog->ic_prev->ic_write_wait,
&log->l_icloglock);
if (log_flushed)
*log_flushed = 1;
already_slept = 1;
goto try_again;
}
atomic_inc(&iclog->ic_refcnt);
xlog_state_switch_iclogs(log, iclog, 0);
spin_unlock(&log->l_icloglock);
if (xlog_state_release_iclog(log, iclog))
return XFS_ERROR(EIO);
if (log_flushed)
*log_flushed = 1;
spin_lock(&log->l_icloglock);
}
if ((flags & XFS_LOG_SYNC) && /* sleep */
!(iclog->ic_state &
(XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) {
/*
* Don't wait on completion if we know that we've
* gotten a log write error.
*/
if (iclog->ic_state & XLOG_STATE_IOERROR) {
spin_unlock(&log->l_icloglock);
return XFS_ERROR(EIO);
}
XFS_STATS_INC(xs_log_force_sleep);
xlog_wait(&iclog->ic_force_wait, &log->l_icloglock);
/*
* No need to grab the log lock here since we're
* only deciding whether or not to return EIO
* and the memory read should be atomic.
*/
if (iclog->ic_state & XLOG_STATE_IOERROR)
return XFS_ERROR(EIO);
if (log_flushed)
*log_flushed = 1;
} else { /* just return */
spin_unlock(&log->l_icloglock);
}
return 0;
} while (iclog != log->l_iclog);
spin_unlock(&log->l_icloglock);
return 0;
}
/*
* Wrapper for _xfs_log_force_lsn(), to be used when caller doesn't care
* about errors or whether the log was flushed or not. This is the normal
* interface to use when trying to unpin items or move the log forward.
*/
void
xfs_log_force_lsn(
xfs_mount_t *mp,
xfs_lsn_t lsn,
uint flags)
{
int error;
error = _xfs_log_force_lsn(mp, lsn, flags, NULL);
if (error)
xfs_warn(mp, "%s: error %d returned.", __func__, error);
}
/*
* Called when we want to mark the current iclog as being ready to sync to
* disk.
*/
STATIC void
xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog)
{
assert_spin_locked(&log->l_icloglock);
if (iclog->ic_state == XLOG_STATE_ACTIVE) {
xlog_state_switch_iclogs(log, iclog, 0);
} else {
ASSERT(iclog->ic_state &
(XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR));
}
}
/*****************************************************************************
*
* TICKET functions
*
*****************************************************************************
*/
/*
* Free a used ticket when its refcount falls to zero.
*/
void
xfs_log_ticket_put(
xlog_ticket_t *ticket)
{
ASSERT(atomic_read(&ticket->t_ref) > 0);
if (atomic_dec_and_test(&ticket->t_ref))
kmem_zone_free(xfs_log_ticket_zone, ticket);
}
xlog_ticket_t *
xfs_log_ticket_get(
xlog_ticket_t *ticket)
{
ASSERT(atomic_read(&ticket->t_ref) > 0);
atomic_inc(&ticket->t_ref);
return ticket;
}
/*
* Allocate and initialise a new log ticket.
*/
xlog_ticket_t *
xlog_ticket_alloc(
struct log *log,
int unit_bytes,
int cnt,
char client,
bool permanent,
int alloc_flags)
{
struct xlog_ticket *tic;
uint num_headers;
int iclog_space;
tic = kmem_zone_zalloc(xfs_log_ticket_zone, alloc_flags);
if (!tic)
return NULL;
/*
* Permanent reservations have up to 'cnt'-1 active log operations
* in the log. A unit in this case is the amount of space for one
* of these log operations. Normal reservations have a cnt of 1
* and their unit amount is the total amount of space required.
*
* The following lines of code account for non-transaction data
* which occupy space in the on-disk log.
*
* Normal form of a transaction is:
* <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph>
* and then there are LR hdrs, split-recs and roundoff at end of syncs.
*
* We need to account for all the leadup data and trailer data
* around the transaction data.
* And then we need to account for the worst case in terms of using
* more space.
* The worst case will happen if:
* - the placement of the transaction happens to be such that the
* roundoff is at its maximum
* - the transaction data is synced before the commit record is synced
* i.e. <transaction-data><roundoff> | <commit-rec><roundoff>
* Therefore the commit record is in its own Log Record.
* This can happen as the commit record is called with its
* own region to xlog_write().
* This then means that in the worst case, roundoff can happen for
* the commit-rec as well.
* The commit-rec is smaller than padding in this scenario and so it is
* not added separately.
*/
/* for trans header */
unit_bytes += sizeof(xlog_op_header_t);
unit_bytes += sizeof(xfs_trans_header_t);
/* for start-rec */
unit_bytes += sizeof(xlog_op_header_t);
/*
* for LR headers - the space for data in an iclog is the size minus
* the space used for the headers. If we use the iclog size, then we
* undercalculate the number of headers required.
*
* Furthermore - the addition of op headers for split-recs might
* increase the space required enough to require more log and op
* headers, so take that into account too.
*
* IMPORTANT: This reservation makes the assumption that if this
* transaction is the first in an iclog and hence has the LR headers
* accounted to it, then the remaining space in the iclog is
* exclusively for this transaction. i.e. if the transaction is larger
* than the iclog, it will be the only thing in that iclog.
* Fundamentally, this means we must pass the entire log vector to
* xlog_write to guarantee this.
*/
iclog_space = log->l_iclog_size - log->l_iclog_hsize;
num_headers = howmany(unit_bytes, iclog_space);
/* for split-recs - ophdrs added when data split over LRs */
unit_bytes += sizeof(xlog_op_header_t) * num_headers;
/* add extra header reservations if we overrun */
while (!num_headers ||
howmany(unit_bytes, iclog_space) > num_headers) {
unit_bytes += sizeof(xlog_op_header_t);
num_headers++;
}
unit_bytes += log->l_iclog_hsize * num_headers;
/* for commit-rec LR header - note: padding will subsume the ophdr */
unit_bytes += log->l_iclog_hsize;
/* for roundoff padding for transaction data and one for commit record */
if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
log->l_mp->m_sb.sb_logsunit > 1) {
/* log su roundoff */
unit_bytes += 2*log->l_mp->m_sb.sb_logsunit;
} else {
/* BB roundoff */
unit_bytes += 2*BBSIZE;
}
atomic_set(&tic->t_ref, 1);
tic->t_task = current;
INIT_LIST_HEAD(&tic->t_queue);
tic->t_unit_res = unit_bytes;
tic->t_curr_res = unit_bytes;
tic->t_cnt = cnt;
tic->t_ocnt = cnt;
tic->t_tid = random32();
tic->t_clientid = client;
tic->t_flags = XLOG_TIC_INITED;
tic->t_trans_type = 0;
if (permanent)
tic->t_flags |= XLOG_TIC_PERM_RESERV;
xlog_tic_reset_res(tic);
return tic;
}
/******************************************************************************
*
* Log debug routines
*
******************************************************************************
*/
#if defined(DEBUG)
/*
* Make sure that the destination ptr is within the valid data region of
* one of the iclogs. This uses backup pointers stored in a different
* part of the log in case we trash the log structure.
*/
void
xlog_verify_dest_ptr(
struct log *log,
char *ptr)
{
int i;
int good_ptr = 0;
for (i = 0; i < log->l_iclog_bufs; i++) {
if (ptr >= log->l_iclog_bak[i] &&
ptr <= log->l_iclog_bak[i] + log->l_iclog_size)
good_ptr++;
}
if (!good_ptr)
xfs_emerg(log->l_mp, "%s: invalid ptr", __func__);
}
/*
* Check to make sure the grant write head didn't just over lap the tail. If
* the cycles are the same, we can't be overlapping. Otherwise, make sure that
* the cycles differ by exactly one and check the byte count.
*
* This check is run unlocked, so can give false positives. Rather than assert
* on failures, use a warn-once flag and a panic tag to allow the admin to
* determine if they want to panic the machine when such an error occurs. For
* debug kernels this will have the same effect as using an assert but, unlinke
* an assert, it can be turned off at runtime.
*/
STATIC void
xlog_verify_grant_tail(
struct log *log)
{
int tail_cycle, tail_blocks;
int cycle, space;
xlog_crack_grant_head(&log->l_write_head.grant, &cycle, &space);
xlog_crack_atomic_lsn(&log->l_tail_lsn, &tail_cycle, &tail_blocks);
if (tail_cycle != cycle) {
if (cycle - 1 != tail_cycle &&
!(log->l_flags & XLOG_TAIL_WARN)) {
xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES,
"%s: cycle - 1 != tail_cycle", __func__);
log->l_flags |= XLOG_TAIL_WARN;
}
if (space > BBTOB(tail_blocks) &&
!(log->l_flags & XLOG_TAIL_WARN)) {
xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES,
"%s: space > BBTOB(tail_blocks)", __func__);
log->l_flags |= XLOG_TAIL_WARN;
}
}
}
/* check if it will fit */
STATIC void
xlog_verify_tail_lsn(xlog_t *log,
xlog_in_core_t *iclog,
xfs_lsn_t tail_lsn)
{
int blocks;
if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) {
blocks =
log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn));
if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize))
xfs_emerg(log->l_mp, "%s: ran out of log space", __func__);
} else {
ASSERT(CYCLE_LSN(tail_lsn)+1 == log->l_prev_cycle);
if (BLOCK_LSN(tail_lsn) == log->l_prev_block)
xfs_emerg(log->l_mp, "%s: tail wrapped", __func__);
blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block;
if (blocks < BTOBB(iclog->ic_offset) + 1)
xfs_emerg(log->l_mp, "%s: ran out of log space", __func__);
}
} /* xlog_verify_tail_lsn */
/*
* Perform a number of checks on the iclog before writing to disk.
*
* 1. Make sure the iclogs are still circular
* 2. Make sure we have a good magic number
* 3. Make sure we don't have magic numbers in the data
* 4. Check fields of each log operation header for:
* A. Valid client identifier
* B. tid ptr value falls in valid ptr space (user space code)
* C. Length in log record header is correct according to the
* individual operation headers within record.
* 5. When a bwrite will occur within 5 blocks of the front of the physical
* log, check the preceding blocks of the physical log to make sure all
* the cycle numbers agree with the current cycle number.
*/
STATIC void
xlog_verify_iclog(xlog_t *log,
xlog_in_core_t *iclog,
int count,
boolean_t syncing)
{
xlog_op_header_t *ophead;
xlog_in_core_t *icptr;
xlog_in_core_2_t *xhdr;
xfs_caddr_t ptr;
xfs_caddr_t base_ptr;
__psint_t field_offset;
__uint8_t clientid;
int len, i, j, k, op_len;
int idx;
/* check validity of iclog pointers */
spin_lock(&log->l_icloglock);
icptr = log->l_iclog;
for (i=0; i < log->l_iclog_bufs; i++) {
if (icptr == NULL)
xfs_emerg(log->l_mp, "%s: invalid ptr", __func__);
icptr = icptr->ic_next;
}
if (icptr != log->l_iclog)
xfs_emerg(log->l_mp, "%s: corrupt iclog ring", __func__);
spin_unlock(&log->l_icloglock);
/* check log magic numbers */
if (iclog->ic_header.h_magicno != cpu_to_be32(XLOG_HEADER_MAGIC_NUM))
xfs_emerg(log->l_mp, "%s: invalid magic num", __func__);
ptr = (xfs_caddr_t) &iclog->ic_header;
for (ptr += BBSIZE; ptr < ((xfs_caddr_t)&iclog->ic_header) + count;
ptr += BBSIZE) {
if (*(__be32 *)ptr == cpu_to_be32(XLOG_HEADER_MAGIC_NUM))
xfs_emerg(log->l_mp, "%s: unexpected magic num",
__func__);
}
/* check fields */
len = be32_to_cpu(iclog->ic_header.h_num_logops);
ptr = iclog->ic_datap;
base_ptr = ptr;
ophead = (xlog_op_header_t *)ptr;
xhdr = iclog->ic_data;
for (i = 0; i < len; i++) {
ophead = (xlog_op_header_t *)ptr;
/* clientid is only 1 byte */
field_offset = (__psint_t)
((xfs_caddr_t)&(ophead->oh_clientid) - base_ptr);
if (syncing == B_FALSE || (field_offset & 0x1ff)) {
clientid = ophead->oh_clientid;
} else {
idx = BTOBBT((xfs_caddr_t)&(ophead->oh_clientid) - iclog->ic_datap);
if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
clientid = xlog_get_client_id(
xhdr[j].hic_xheader.xh_cycle_data[k]);
} else {
clientid = xlog_get_client_id(
iclog->ic_header.h_cycle_data[idx]);
}
}
if (clientid != XFS_TRANSACTION && clientid != XFS_LOG)
xfs_warn(log->l_mp,
"%s: invalid clientid %d op 0x%p offset 0x%lx",
__func__, clientid, ophead,
(unsigned long)field_offset);
/* check length */
field_offset = (__psint_t)
((xfs_caddr_t)&(ophead->oh_len) - base_ptr);
if (syncing == B_FALSE || (field_offset & 0x1ff)) {
op_len = be32_to_cpu(ophead->oh_len);
} else {
idx = BTOBBT((__psint_t)&ophead->oh_len -
(__psint_t)iclog->ic_datap);
if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
op_len = be32_to_cpu(xhdr[j].hic_xheader.xh_cycle_data[k]);
} else {
op_len = be32_to_cpu(iclog->ic_header.h_cycle_data[idx]);
}
}
ptr += sizeof(xlog_op_header_t) + op_len;
}
} /* xlog_verify_iclog */
#endif
/*
* Mark all iclogs IOERROR. l_icloglock is held by the caller.
*/
STATIC int
xlog_state_ioerror(
xlog_t *log)
{
xlog_in_core_t *iclog, *ic;
iclog = log->l_iclog;
if (! (iclog->ic_state & XLOG_STATE_IOERROR)) {
/*
* Mark all the incore logs IOERROR.
* From now on, no log flushes will result.
*/
ic = iclog;
do {
ic->ic_state = XLOG_STATE_IOERROR;
ic = ic->ic_next;
} while (ic != iclog);
return 0;
}
/*
* Return non-zero, if state transition has already happened.
*/
return 1;
}
/*
* This is called from xfs_force_shutdown, when we're forcibly
* shutting down the filesystem, typically because of an IO error.
* Our main objectives here are to make sure that:
* a. the filesystem gets marked 'SHUTDOWN' for all interested
* parties to find out, 'atomically'.
* b. those who're sleeping on log reservations, pinned objects and
* other resources get woken up, and be told the bad news.
* c. nothing new gets queued up after (a) and (b) are done.
* d. if !logerror, flush the iclogs to disk, then seal them off
* for business.
*
* Note: for delayed logging the !logerror case needs to flush the regions
* held in memory out to the iclogs before flushing them to disk. This needs
* to be done before the log is marked as shutdown, otherwise the flush to the
* iclogs will fail.
*/
int
xfs_log_force_umount(
struct xfs_mount *mp,
int logerror)
{
xlog_t *log;
int retval;
log = mp->m_log;
/*
* If this happens during log recovery, don't worry about
* locking; the log isn't open for business yet.
*/
if (!log ||
log->l_flags & XLOG_ACTIVE_RECOVERY) {
mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
if (mp->m_sb_bp)
XFS_BUF_DONE(mp->m_sb_bp);
return 0;
}
/*
* Somebody could've already done the hard work for us.
* No need to get locks for this.
*/
if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) {
ASSERT(XLOG_FORCED_SHUTDOWN(log));
return 1;
}
retval = 0;
/*
* Flush the in memory commit item list before marking the log as
* being shut down. We need to do it in this order to ensure all the
* completed transactions are flushed to disk with the xfs_log_force()
* call below.
*/
if (!logerror)
xlog_cil_force(log);
/*
* mark the filesystem and the as in a shutdown state and wake
* everybody up to tell them the bad news.
*/
spin_lock(&log->l_icloglock);
mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
if (mp->m_sb_bp)
XFS_BUF_DONE(mp->m_sb_bp);
/*
* This flag is sort of redundant because of the mount flag, but
* it's good to maintain the separation between the log and the rest
* of XFS.
*/
log->l_flags |= XLOG_IO_ERROR;
/*
* If we hit a log error, we want to mark all the iclogs IOERROR
* while we're still holding the loglock.
*/
if (logerror)
retval = xlog_state_ioerror(log);
spin_unlock(&log->l_icloglock);
/*
* We don't want anybody waiting for log reservations after this. That
* means we have to wake up everybody queued up on reserveq as well as
* writeq. In addition, we make sure in xlog_{re}grant_log_space that
* we don't enqueue anything once the SHUTDOWN flag is set, and this
* action is protected by the grant locks.
*/
xlog_grant_head_wake_all(&log->l_reserve_head);
xlog_grant_head_wake_all(&log->l_write_head);
if (!(log->l_iclog->ic_state & XLOG_STATE_IOERROR)) {
ASSERT(!logerror);
/*
* Force the incore logs to disk before shutting the
* log down completely.
*/
_xfs_log_force(mp, XFS_LOG_SYNC, NULL);
spin_lock(&log->l_icloglock);
retval = xlog_state_ioerror(log);
spin_unlock(&log->l_icloglock);
}
/*
* Wake up everybody waiting on xfs_log_force.
* Callback all log item committed functions as if the
* log writes were completed.
*/
xlog_state_do_callback(log, XFS_LI_ABORTED, NULL);
#ifdef XFSERRORDEBUG
{
xlog_in_core_t *iclog;
spin_lock(&log->l_icloglock);
iclog = log->l_iclog;
do {
ASSERT(iclog->ic_callback == 0);
iclog = iclog->ic_next;
} while (iclog != log->l_iclog);
spin_unlock(&log->l_icloglock);
}
#endif
/* return non-zero if log IOERROR transition had already happened */
return retval;
}
STATIC int
xlog_iclogs_empty(xlog_t *log)
{
xlog_in_core_t *iclog;
iclog = log->l_iclog;
do {
/* endianness does not matter here, zero is zero in
* any language.
*/
if (iclog->ic_header.h_num_logops)
return 0;
iclog = iclog->ic_next;
} while (iclog != log->l_iclog);
return 1;
}
| gpl-2.0 |
crpalmer/htc_kernel_m7 | drivers/scsi/osst.c | 7597 | 187197 | /*
SCSI Tape Driver for Linux version 1.1 and newer. See the accompanying
file Documentation/scsi/st.txt for more information.
History:
OnStream SCSI Tape support (osst) cloned from st.c by
Willem Riede (osst@riede.org) Feb 2000
Fixes ... Kurt Garloff <garloff@suse.de> Mar 2000
Rewritten from Dwayne Forsyth's SCSI tape driver by Kai Makisara.
Contribution and ideas from several people including (in alphabetical
order) Klaus Ehrenfried, Wolfgang Denk, Steve Hirsch, Andreas Koppenh"ofer,
Michael Leodolter, Eyal Lebedinsky, J"org Weule, and Eric Youngdale.
Copyright 1992 - 2002 Kai Makisara / 2000 - 2006 Willem Riede
email osst@riede.org
$Header: /cvsroot/osst/Driver/osst.c,v 1.73 2005/01/01 21:13:34 wriede Exp $
Microscopic alterations - Rik Ling, 2000/12/21
Last st.c sync: Tue Oct 15 22:01:04 2002 by makisara
Some small formal changes - aeb, 950809
*/
static const char * cvsid = "$Id: osst.c,v 1.73 2005/01/01 21:13:34 wriede Exp $";
static const char * osst_version = "0.99.4";
/* The "failure to reconnect" firmware bug */
#define OSST_FW_NEED_POLL_MIN 10601 /*(107A)*/
#define OSST_FW_NEED_POLL_MAX 10704 /*(108D)*/
#define OSST_FW_NEED_POLL(x,d) ((x) >= OSST_FW_NEED_POLL_MIN && (x) <= OSST_FW_NEED_POLL_MAX && d->host->this_id != 7)
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/proc_fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/mtio.h>
#include <linux/ioctl.h>
#include <linux/fcntl.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/moduleparam.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <asm/dma.h>
/* The driver prints some debugging information on the console if DEBUG
is defined and non-zero. */
#define DEBUG 0
/* The message level for the debug messages is currently set to KERN_NOTICE
so that people can easily see the messages. Later when the debugging messages
in the drivers are more widely classified, this may be changed to KERN_DEBUG. */
#define OSST_DEB_MSG KERN_NOTICE
#include <scsi/scsi.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_ioctl.h>
#define ST_KILOBYTE 1024
#include "st.h"
#include "osst.h"
#include "osst_options.h"
#include "osst_detect.h"
static DEFINE_MUTEX(osst_int_mutex);
static int max_dev = 0;
static int write_threshold_kbs = 0;
static int max_sg_segs = 0;
#ifdef MODULE
MODULE_AUTHOR("Willem Riede");
MODULE_DESCRIPTION("OnStream {DI-|FW-|SC-|USB}{30|50} Tape Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(OSST_MAJOR);
MODULE_ALIAS_SCSI_DEVICE(TYPE_TAPE);
module_param(max_dev, int, 0444);
MODULE_PARM_DESC(max_dev, "Maximum number of OnStream Tape Drives to attach (4)");
module_param(write_threshold_kbs, int, 0644);
MODULE_PARM_DESC(write_threshold_kbs, "Asynchronous write threshold (KB; 32)");
module_param(max_sg_segs, int, 0644);
MODULE_PARM_DESC(max_sg_segs, "Maximum number of scatter/gather segments to use (9)");
#else
static struct osst_dev_parm {
char *name;
int *val;
} parms[] __initdata = {
{ "max_dev", &max_dev },
{ "write_threshold_kbs", &write_threshold_kbs },
{ "max_sg_segs", &max_sg_segs }
};
#endif
/* Some default definitions have been moved to osst_options.h */
#define OSST_BUFFER_SIZE (OSST_BUFFER_BLOCKS * ST_KILOBYTE)
#define OSST_WRITE_THRESHOLD (OSST_WRITE_THRESHOLD_BLOCKS * ST_KILOBYTE)
/* The buffer size should fit into the 24 bits for length in the
6-byte SCSI read and write commands. */
#if OSST_BUFFER_SIZE >= (2 << 24 - 1)
#error "Buffer size should not exceed (2 << 24 - 1) bytes!"
#endif
#if DEBUG
static int debugging = 1;
/* uncomment define below to test error recovery */
// #define OSST_INJECT_ERRORS 1
#endif
/* Do not retry! The drive firmware already retries when appropriate,
and when it tries to tell us something, we had better listen... */
#define MAX_RETRIES 0
#define NO_TAPE NOT_READY
#define OSST_WAIT_POSITION_COMPLETE (HZ > 200 ? HZ / 200 : 1)
#define OSST_WAIT_WRITE_COMPLETE (HZ / 12)
#define OSST_WAIT_LONG_WRITE_COMPLETE (HZ / 2)
#define OSST_TIMEOUT (200 * HZ)
#define OSST_LONG_TIMEOUT (1800 * HZ)
#define TAPE_NR(x) (iminor(x) & ~(-1 << ST_MODE_SHIFT))
#define TAPE_MODE(x) ((iminor(x) & ST_MODE_MASK) >> ST_MODE_SHIFT)
#define TAPE_REWIND(x) ((iminor(x) & 0x80) == 0)
#define TAPE_IS_RAW(x) (TAPE_MODE(x) & (ST_NBR_MODES >> 1))
/* Internal ioctl to set both density (uppermost 8 bits) and blocksize (lower
24 bits) */
#define SET_DENS_AND_BLK 0x10001
static int osst_buffer_size = OSST_BUFFER_SIZE;
static int osst_write_threshold = OSST_WRITE_THRESHOLD;
static int osst_max_sg_segs = OSST_MAX_SG;
static int osst_max_dev = OSST_MAX_TAPES;
static int osst_nr_dev;
static struct osst_tape **os_scsi_tapes = NULL;
static DEFINE_RWLOCK(os_scsi_tapes_lock);
static int modes_defined = 0;
static struct osst_buffer *new_tape_buffer(int, int, int);
static int enlarge_buffer(struct osst_buffer *, int);
static void normalize_buffer(struct osst_buffer *);
static int append_to_buffer(const char __user *, struct osst_buffer *, int);
static int from_buffer(struct osst_buffer *, char __user *, int);
static int osst_zero_buffer_tail(struct osst_buffer *);
static int osst_copy_to_buffer(struct osst_buffer *, unsigned char *);
static int osst_copy_from_buffer(struct osst_buffer *, unsigned char *);
static int osst_probe(struct device *);
static int osst_remove(struct device *);
static struct scsi_driver osst_template = {
.owner = THIS_MODULE,
.gendrv = {
.name = "osst",
.probe = osst_probe,
.remove = osst_remove,
}
};
static int osst_int_ioctl(struct osst_tape *STp, struct osst_request ** aSRpnt,
unsigned int cmd_in, unsigned long arg);
static int osst_set_frame_position(struct osst_tape *STp, struct osst_request ** aSRpnt, int frame, int skip);
static int osst_get_frame_position(struct osst_tape *STp, struct osst_request ** aSRpnt);
static int osst_flush_write_buffer(struct osst_tape *STp, struct osst_request ** aSRpnt);
static int osst_write_error_recovery(struct osst_tape * STp, struct osst_request ** aSRpnt, int pending);
static inline char *tape_name(struct osst_tape *tape)
{
return tape->drive->disk_name;
}
/* Routines that handle the interaction with mid-layer SCSI routines */
/* Normalize Sense */
static void osst_analyze_sense(struct osst_request *SRpnt, struct st_cmdstatus *s)
{
const u8 *ucp;
const u8 *sense = SRpnt->sense;
s->have_sense = scsi_normalize_sense(SRpnt->sense,
SCSI_SENSE_BUFFERSIZE, &s->sense_hdr);
s->flags = 0;
if (s->have_sense) {
s->deferred = 0;
s->remainder_valid =
scsi_get_sense_info_fld(sense, SCSI_SENSE_BUFFERSIZE, &s->uremainder64);
switch (sense[0] & 0x7f) {
case 0x71:
s->deferred = 1;
case 0x70:
s->fixed_format = 1;
s->flags = sense[2] & 0xe0;
break;
case 0x73:
s->deferred = 1;
case 0x72:
s->fixed_format = 0;
ucp = scsi_sense_desc_find(sense, SCSI_SENSE_BUFFERSIZE, 4);
s->flags = ucp ? (ucp[3] & 0xe0) : 0;
break;
}
}
}
/* Convert the result to success code */
static int osst_chk_result(struct osst_tape * STp, struct osst_request * SRpnt)
{
char *name = tape_name(STp);
int result = SRpnt->result;
u8 * sense = SRpnt->sense, scode;
#if DEBUG
const char *stp;
#endif
struct st_cmdstatus *cmdstatp;
if (!result)
return 0;
cmdstatp = &STp->buffer->cmdstat;
osst_analyze_sense(SRpnt, cmdstatp);
if (cmdstatp->have_sense)
scode = STp->buffer->cmdstat.sense_hdr.sense_key;
else
scode = 0;
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Error: %x, cmd: %x %x %x %x %x %x\n",
name, result,
SRpnt->cmd[0], SRpnt->cmd[1], SRpnt->cmd[2],
SRpnt->cmd[3], SRpnt->cmd[4], SRpnt->cmd[5]);
if (scode) printk(OSST_DEB_MSG "%s:D: Sense: %02x, ASC: %02x, ASCQ: %02x\n",
name, scode, sense[12], sense[13]);
if (cmdstatp->have_sense)
__scsi_print_sense("osst ", SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
}
else
#endif
if (cmdstatp->have_sense && (
scode != NO_SENSE &&
scode != RECOVERED_ERROR &&
/* scode != UNIT_ATTENTION && */
scode != BLANK_CHECK &&
scode != VOLUME_OVERFLOW &&
SRpnt->cmd[0] != MODE_SENSE &&
SRpnt->cmd[0] != TEST_UNIT_READY)) { /* Abnormal conditions for tape */
if (cmdstatp->have_sense) {
printk(KERN_WARNING "%s:W: Command with sense data:\n", name);
__scsi_print_sense("osst ", SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
}
else {
static int notyetprinted = 1;
printk(KERN_WARNING
"%s:W: Warning %x (driver bt 0x%x, host bt 0x%x).\n",
name, result, driver_byte(result),
host_byte(result));
if (notyetprinted) {
notyetprinted = 0;
printk(KERN_INFO
"%s:I: This warning may be caused by your scsi controller,\n", name);
printk(KERN_INFO
"%s:I: it has been reported with some Buslogic cards.\n", name);
}
}
}
STp->pos_unknown |= STp->device->was_reset;
if (cmdstatp->have_sense && scode == RECOVERED_ERROR) {
STp->recover_count++;
STp->recover_erreg++;
#if DEBUG
if (debugging) {
if (SRpnt->cmd[0] == READ_6)
stp = "read";
else if (SRpnt->cmd[0] == WRITE_6)
stp = "write";
else
stp = "ioctl";
printk(OSST_DEB_MSG "%s:D: Recovered %s error (%d).\n", name, stp,
STp->recover_count);
}
#endif
if ((sense[2] & 0xe0) == 0)
return 0;
}
return (-EIO);
}
/* Wakeup from interrupt */
static void osst_end_async(struct request *req, int update)
{
struct osst_request *SRpnt = req->end_io_data;
struct osst_tape *STp = SRpnt->stp;
struct rq_map_data *mdata = &SRpnt->stp->buffer->map_data;
STp->buffer->cmdstat.midlevel_result = SRpnt->result = req->errors;
#if DEBUG
STp->write_pending = 0;
#endif
if (SRpnt->waiting)
complete(SRpnt->waiting);
if (SRpnt->bio) {
kfree(mdata->pages);
blk_rq_unmap_user(SRpnt->bio);
}
__blk_put_request(req->q, req);
}
/* osst_request memory management */
static struct osst_request *osst_allocate_request(void)
{
return kzalloc(sizeof(struct osst_request), GFP_KERNEL);
}
static void osst_release_request(struct osst_request *streq)
{
kfree(streq);
}
static int osst_execute(struct osst_request *SRpnt, const unsigned char *cmd,
int cmd_len, int data_direction, void *buffer, unsigned bufflen,
int use_sg, int timeout, int retries)
{
struct request *req;
struct page **pages = NULL;
struct rq_map_data *mdata = &SRpnt->stp->buffer->map_data;
int err = 0;
int write = (data_direction == DMA_TO_DEVICE);
req = blk_get_request(SRpnt->stp->device->request_queue, write, GFP_KERNEL);
if (!req)
return DRIVER_ERROR << 24;
req->cmd_type = REQ_TYPE_BLOCK_PC;
req->cmd_flags |= REQ_QUIET;
SRpnt->bio = NULL;
if (use_sg) {
struct scatterlist *sg, *sgl = (struct scatterlist *)buffer;
int i;
pages = kzalloc(use_sg * sizeof(struct page *), GFP_KERNEL);
if (!pages)
goto free_req;
for_each_sg(sgl, sg, use_sg, i)
pages[i] = sg_page(sg);
mdata->null_mapped = 1;
mdata->page_order = get_order(sgl[0].length);
mdata->nr_entries =
DIV_ROUND_UP(bufflen, PAGE_SIZE << mdata->page_order);
mdata->offset = 0;
err = blk_rq_map_user(req->q, req, mdata, NULL, bufflen, GFP_KERNEL);
if (err) {
kfree(pages);
goto free_req;
}
SRpnt->bio = req->bio;
mdata->pages = pages;
} else if (bufflen) {
err = blk_rq_map_kern(req->q, req, buffer, bufflen, GFP_KERNEL);
if (err)
goto free_req;
}
req->cmd_len = cmd_len;
memset(req->cmd, 0, BLK_MAX_CDB); /* ATAPI hates garbage after CDB */
memcpy(req->cmd, cmd, req->cmd_len);
req->sense = SRpnt->sense;
req->sense_len = 0;
req->timeout = timeout;
req->retries = retries;
req->end_io_data = SRpnt;
blk_execute_rq_nowait(req->q, NULL, req, 1, osst_end_async);
return 0;
free_req:
blk_put_request(req);
return DRIVER_ERROR << 24;
}
/* Do the scsi command. Waits until command performed if do_wait is true.
Otherwise osst_write_behind_check() is used to check that the command
has finished. */
static struct osst_request * osst_do_scsi(struct osst_request *SRpnt, struct osst_tape *STp,
unsigned char *cmd, int bytes, int direction, int timeout, int retries, int do_wait)
{
unsigned char *bp;
unsigned short use_sg;
#ifdef OSST_INJECT_ERRORS
static int inject = 0;
static int repeat = 0;
#endif
struct completion *waiting;
/* if async, make sure there's no command outstanding */
if (!do_wait && ((STp->buffer)->last_SRpnt)) {
printk(KERN_ERR "%s: Async command already active.\n",
tape_name(STp));
if (signal_pending(current))
(STp->buffer)->syscall_result = (-EINTR);
else
(STp->buffer)->syscall_result = (-EBUSY);
return NULL;
}
if (SRpnt == NULL) {
SRpnt = osst_allocate_request();
if (SRpnt == NULL) {
printk(KERN_ERR "%s: Can't allocate SCSI request.\n",
tape_name(STp));
if (signal_pending(current))
(STp->buffer)->syscall_result = (-EINTR);
else
(STp->buffer)->syscall_result = (-EBUSY);
return NULL;
}
SRpnt->stp = STp;
}
/* If async IO, set last_SRpnt. This ptr tells write_behind_check
which IO is outstanding. It's nulled out when the IO completes. */
if (!do_wait)
(STp->buffer)->last_SRpnt = SRpnt;
waiting = &STp->wait;
init_completion(waiting);
SRpnt->waiting = waiting;
use_sg = (bytes > STp->buffer->sg[0].length) ? STp->buffer->use_sg : 0;
if (use_sg) {
bp = (char *)&(STp->buffer->sg[0]);
if (STp->buffer->sg_segs < use_sg)
use_sg = STp->buffer->sg_segs;
}
else
bp = (STp->buffer)->b_data;
memcpy(SRpnt->cmd, cmd, sizeof(SRpnt->cmd));
STp->buffer->cmdstat.have_sense = 0;
STp->buffer->syscall_result = 0;
if (osst_execute(SRpnt, cmd, COMMAND_SIZE(cmd[0]), direction, bp, bytes,
use_sg, timeout, retries))
/* could not allocate the buffer or request was too large */
(STp->buffer)->syscall_result = (-EBUSY);
else if (do_wait) {
wait_for_completion(waiting);
SRpnt->waiting = NULL;
STp->buffer->syscall_result = osst_chk_result(STp, SRpnt);
#ifdef OSST_INJECT_ERRORS
if (STp->buffer->syscall_result == 0 &&
cmd[0] == READ_6 &&
cmd[4] &&
( (++ inject % 83) == 29 ||
(STp->first_frame_position == 240
/* or STp->read_error_frame to fail again on the block calculated above */ &&
++repeat < 3))) {
printk(OSST_DEB_MSG "%s:D: Injecting read error\n", tape_name(STp));
STp->buffer->last_result_fatal = 1;
}
#endif
}
return SRpnt;
}
/* Handle the write-behind checking (downs the semaphore) */
static void osst_write_behind_check(struct osst_tape *STp)
{
struct osst_buffer * STbuffer;
STbuffer = STp->buffer;
#if DEBUG
if (STp->write_pending)
STp->nbr_waits++;
else
STp->nbr_finished++;
#endif
wait_for_completion(&(STp->wait));
STp->buffer->last_SRpnt->waiting = NULL;
STp->buffer->syscall_result = osst_chk_result(STp, STp->buffer->last_SRpnt);
if (STp->buffer->syscall_result)
STp->buffer->syscall_result =
osst_write_error_recovery(STp, &(STp->buffer->last_SRpnt), 1);
else
STp->first_frame_position++;
osst_release_request(STp->buffer->last_SRpnt);
if (STbuffer->writing < STbuffer->buffer_bytes)
printk(KERN_WARNING "osst :A: write_behind_check: something left in buffer!\n");
STbuffer->last_SRpnt = NULL;
STbuffer->buffer_bytes -= STbuffer->writing;
STbuffer->writing = 0;
return;
}
/* Onstream specific Routines */
/*
* Initialize the OnStream AUX
*/
static void osst_init_aux(struct osst_tape * STp, int frame_type, int frame_seq_number,
int logical_blk_num, int blk_sz, int blk_cnt)
{
os_aux_t *aux = STp->buffer->aux;
os_partition_t *par = &aux->partition;
os_dat_t *dat = &aux->dat;
if (STp->raw) return;
memset(aux, 0, sizeof(*aux));
aux->format_id = htonl(0);
memcpy(aux->application_sig, "LIN4", 4);
aux->hdwr = htonl(0);
aux->frame_type = frame_type;
switch (frame_type) {
case OS_FRAME_TYPE_HEADER:
aux->update_frame_cntr = htonl(STp->update_frame_cntr);
par->partition_num = OS_CONFIG_PARTITION;
par->par_desc_ver = OS_PARTITION_VERSION;
par->wrt_pass_cntr = htons(0xffff);
/* 0-4 = reserved, 5-9 = header, 2990-2994 = header, 2995-2999 = reserved */
par->first_frame_ppos = htonl(0);
par->last_frame_ppos = htonl(0xbb7);
aux->frame_seq_num = htonl(0);
aux->logical_blk_num_high = htonl(0);
aux->logical_blk_num = htonl(0);
aux->next_mark_ppos = htonl(STp->first_mark_ppos);
break;
case OS_FRAME_TYPE_DATA:
case OS_FRAME_TYPE_MARKER:
dat->dat_sz = 8;
dat->reserved1 = 0;
dat->entry_cnt = 1;
dat->reserved3 = 0;
dat->dat_list[0].blk_sz = htonl(blk_sz);
dat->dat_list[0].blk_cnt = htons(blk_cnt);
dat->dat_list[0].flags = frame_type==OS_FRAME_TYPE_MARKER?
OS_DAT_FLAGS_MARK:OS_DAT_FLAGS_DATA;
dat->dat_list[0].reserved = 0;
case OS_FRAME_TYPE_EOD:
aux->update_frame_cntr = htonl(0);
par->partition_num = OS_DATA_PARTITION;
par->par_desc_ver = OS_PARTITION_VERSION;
par->wrt_pass_cntr = htons(STp->wrt_pass_cntr);
par->first_frame_ppos = htonl(STp->first_data_ppos);
par->last_frame_ppos = htonl(STp->capacity);
aux->frame_seq_num = htonl(frame_seq_number);
aux->logical_blk_num_high = htonl(0);
aux->logical_blk_num = htonl(logical_blk_num);
break;
default: ; /* probably FILL */
}
aux->filemark_cnt = htonl(STp->filemark_cnt);
aux->phys_fm = htonl(0xffffffff);
aux->last_mark_ppos = htonl(STp->last_mark_ppos);
aux->last_mark_lbn = htonl(STp->last_mark_lbn);
}
/*
* Verify that we have the correct tape frame
*/
static int osst_verify_frame(struct osst_tape * STp, int frame_seq_number, int quiet)
{
char * name = tape_name(STp);
os_aux_t * aux = STp->buffer->aux;
os_partition_t * par = &(aux->partition);
struct st_partstat * STps = &(STp->ps[STp->partition]);
int blk_cnt, blk_sz, i;
if (STp->raw) {
if (STp->buffer->syscall_result) {
for (i=0; i < STp->buffer->sg_segs; i++)
memset(page_address(sg_page(&STp->buffer->sg[i])),
0, STp->buffer->sg[i].length);
strcpy(STp->buffer->b_data, "READ ERROR ON FRAME");
} else
STp->buffer->buffer_bytes = OS_FRAME_SIZE;
return 1;
}
if (STp->buffer->syscall_result) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, read error\n", name);
#endif
return 0;
}
if (ntohl(aux->format_id) != 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, format_id %u\n", name, ntohl(aux->format_id));
#endif
goto err_out;
}
if (memcmp(aux->application_sig, STp->application_sig, 4) != 0 &&
(memcmp(aux->application_sig, "LIN3", 4) != 0 || STp->linux_media_version != 4)) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, incorrect application signature\n", name);
#endif
goto err_out;
}
if (par->partition_num != OS_DATA_PARTITION) {
if (!STp->linux_media || STp->linux_media_version != 2) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, partition num %d\n",
name, par->partition_num);
#endif
goto err_out;
}
}
if (par->par_desc_ver != OS_PARTITION_VERSION) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, partition version %d\n", name, par->par_desc_ver);
#endif
goto err_out;
}
if (ntohs(par->wrt_pass_cntr) != STp->wrt_pass_cntr) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, wrt_pass_cntr %d (expected %d)\n",
name, ntohs(par->wrt_pass_cntr), STp->wrt_pass_cntr);
#endif
goto err_out;
}
if (aux->frame_type != OS_FRAME_TYPE_DATA &&
aux->frame_type != OS_FRAME_TYPE_EOD &&
aux->frame_type != OS_FRAME_TYPE_MARKER) {
if (!quiet) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, frame type %x\n", name, aux->frame_type);
#endif
}
goto err_out;
}
if (aux->frame_type == OS_FRAME_TYPE_EOD &&
STp->first_frame_position < STp->eod_frame_ppos) {
printk(KERN_INFO "%s:I: Skipping premature EOD frame %d\n", name,
STp->first_frame_position);
goto err_out;
}
if (frame_seq_number != -1 && ntohl(aux->frame_seq_num) != frame_seq_number) {
if (!quiet) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame, sequence number %u (expected %d)\n",
name, ntohl(aux->frame_seq_num), frame_seq_number);
#endif
}
goto err_out;
}
if (aux->frame_type == OS_FRAME_TYPE_MARKER) {
STps->eof = ST_FM_HIT;
i = ntohl(aux->filemark_cnt);
if (STp->header_cache != NULL && i < OS_FM_TAB_MAX && (i > STp->filemark_cnt ||
STp->first_frame_position - 1 != ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[i]))) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: %s filemark %d at frame pos %d\n", name,
STp->header_cache->dat_fm_tab.fm_tab_ent[i] == 0?"Learned":"Corrected",
i, STp->first_frame_position - 1);
#endif
STp->header_cache->dat_fm_tab.fm_tab_ent[i] = htonl(STp->first_frame_position - 1);
if (i >= STp->filemark_cnt)
STp->filemark_cnt = i+1;
}
}
if (aux->frame_type == OS_FRAME_TYPE_EOD) {
STps->eof = ST_EOD_1;
STp->frame_in_buffer = 1;
}
if (aux->frame_type == OS_FRAME_TYPE_DATA) {
blk_cnt = ntohs(aux->dat.dat_list[0].blk_cnt);
blk_sz = ntohl(aux->dat.dat_list[0].blk_sz);
STp->buffer->buffer_bytes = blk_cnt * blk_sz;
STp->buffer->read_pointer = 0;
STp->frame_in_buffer = 1;
/* See what block size was used to write file */
if (STp->block_size != blk_sz && blk_sz > 0) {
printk(KERN_INFO
"%s:I: File was written with block size %d%c, currently %d%c, adjusted to match.\n",
name, blk_sz<1024?blk_sz:blk_sz/1024,blk_sz<1024?'b':'k',
STp->block_size<1024?STp->block_size:STp->block_size/1024,
STp->block_size<1024?'b':'k');
STp->block_size = blk_sz;
STp->buffer->buffer_blocks = OS_DATA_SIZE / blk_sz;
}
STps->eof = ST_NOEOF;
}
STp->frame_seq_number = ntohl(aux->frame_seq_num);
STp->logical_blk_num = ntohl(aux->logical_blk_num);
return 1;
err_out:
if (STp->read_error_frame == 0)
STp->read_error_frame = STp->first_frame_position - 1;
return 0;
}
/*
* Wait for the unit to become Ready
*/
static int osst_wait_ready(struct osst_tape * STp, struct osst_request ** aSRpnt,
unsigned timeout, int initial_delay)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
unsigned long startwait = jiffies;
#if DEBUG
int dbg = debugging;
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Reached onstream wait ready\n", name);
#endif
if (initial_delay > 0)
msleep(jiffies_to_msecs(initial_delay));
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (!SRpnt) return (-EBUSY);
while ( STp->buffer->syscall_result && time_before(jiffies, startwait + timeout*HZ) &&
(( SRpnt->sense[2] == 2 && SRpnt->sense[12] == 4 &&
(SRpnt->sense[13] == 1 || SRpnt->sense[13] == 8) ) ||
( SRpnt->sense[2] == 6 && SRpnt->sense[12] == 0x28 &&
SRpnt->sense[13] == 0 ) )) {
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Sleeping in onstream wait ready\n", name);
printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
debugging = 0;
}
#endif
msleep(100);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
}
*aSRpnt = SRpnt;
#if DEBUG
debugging = dbg;
#endif
if ( STp->buffer->syscall_result &&
osst_write_error_recovery(STp, aSRpnt, 0) ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Abnormal exit from onstream wait ready\n", name);
printk(OSST_DEB_MSG "%s:D: Result = %d, Sense: 0=%02x, 2=%02x, 12=%02x, 13=%02x\n", name,
STp->buffer->syscall_result, SRpnt->sense[0], SRpnt->sense[2],
SRpnt->sense[12], SRpnt->sense[13]);
#endif
return (-EIO);
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Normal exit from onstream wait ready\n", name);
#endif
return 0;
}
/*
* Wait for a tape to be inserted in the unit
*/
static int osst_wait_for_medium(struct osst_tape * STp, struct osst_request ** aSRpnt, unsigned timeout)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
unsigned long startwait = jiffies;
#if DEBUG
int dbg = debugging;
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Reached onstream wait for medium\n", name);
#endif
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (!SRpnt) return (-EBUSY);
while ( STp->buffer->syscall_result && time_before(jiffies, startwait + timeout*HZ) &&
SRpnt->sense[2] == 2 && SRpnt->sense[12] == 0x3a && SRpnt->sense[13] == 0 ) {
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Sleeping in onstream wait medium\n", name);
printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
debugging = 0;
}
#endif
msleep(100);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
}
*aSRpnt = SRpnt;
#if DEBUG
debugging = dbg;
#endif
if ( STp->buffer->syscall_result && SRpnt->sense[2] != 2 &&
SRpnt->sense[12] != 4 && SRpnt->sense[13] == 1) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Abnormal exit from onstream wait medium\n", name);
printk(OSST_DEB_MSG "%s:D: Result = %d, Sense: 0=%02x, 2=%02x, 12=%02x, 13=%02x\n", name,
STp->buffer->syscall_result, SRpnt->sense[0], SRpnt->sense[2],
SRpnt->sense[12], SRpnt->sense[13]);
#endif
return 0;
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Normal exit from onstream wait medium\n", name);
#endif
return 1;
}
static int osst_position_tape_and_confirm(struct osst_tape * STp, struct osst_request ** aSRpnt, int frame)
{
int retval;
osst_wait_ready(STp, aSRpnt, 15 * 60, 0); /* TODO - can this catch a write error? */
retval = osst_set_frame_position(STp, aSRpnt, frame, 0);
if (retval) return (retval);
osst_wait_ready(STp, aSRpnt, 15 * 60, OSST_WAIT_POSITION_COMPLETE);
return (osst_get_frame_position(STp, aSRpnt));
}
/*
* Wait for write(s) to complete
*/
static int osst_flush_drive_buffer(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
int result = 0;
int delay = OSST_WAIT_WRITE_COMPLETE;
#if DEBUG
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Reached onstream flush drive buffer (write filemark)\n", name);
#endif
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_FILEMARKS;
cmd[1] = 1;
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (!SRpnt) return (-EBUSY);
if (STp->buffer->syscall_result) {
if ((SRpnt->sense[2] & 0x0f) == 2 && SRpnt->sense[12] == 4) {
if (SRpnt->sense[13] == 8) {
delay = OSST_WAIT_LONG_WRITE_COMPLETE;
}
} else
result = osst_write_error_recovery(STp, aSRpnt, 0);
}
result |= osst_wait_ready(STp, aSRpnt, 5 * 60, delay);
STp->ps[STp->partition].rw = OS_WRITING_COMPLETE;
return (result);
}
#define OSST_POLL_PER_SEC 10
static int osst_wait_frame(struct osst_tape * STp, struct osst_request ** aSRpnt, int curr, int minlast, int to)
{
unsigned long startwait = jiffies;
char * name = tape_name(STp);
#if DEBUG
char notyetprinted = 1;
#endif
if (minlast >= 0 && STp->ps[STp->partition].rw != ST_READING)
printk(KERN_ERR "%s:A: Waiting for frame without having initialized read!\n", name);
while (time_before (jiffies, startwait + to*HZ))
{
int result;
result = osst_get_frame_position(STp, aSRpnt);
if (result == -EIO)
if ((result = osst_write_error_recovery(STp, aSRpnt, 0)) == 0)
return 0; /* successful recovery leaves drive ready for frame */
if (result < 0) break;
if (STp->first_frame_position == curr &&
((minlast < 0 &&
(signed)STp->last_frame_position > (signed)curr + minlast) ||
(minlast >= 0 && STp->cur_frames > minlast)
) && result >= 0)
{
#if DEBUG
if (debugging || time_after_eq(jiffies, startwait + 2*HZ/OSST_POLL_PER_SEC))
printk (OSST_DEB_MSG
"%s:D: Succ wait f fr %i (>%i): %i-%i %i (%i): %3li.%li s\n",
name, curr, curr+minlast, STp->first_frame_position,
STp->last_frame_position, STp->cur_frames,
result, (jiffies-startwait)/HZ,
(((jiffies-startwait)%HZ)*10)/HZ);
#endif
return 0;
}
#if DEBUG
if (time_after_eq(jiffies, startwait + 2*HZ/OSST_POLL_PER_SEC) && notyetprinted)
{
printk (OSST_DEB_MSG "%s:D: Wait for frame %i (>%i): %i-%i %i (%i)\n",
name, curr, curr+minlast, STp->first_frame_position,
STp->last_frame_position, STp->cur_frames, result);
notyetprinted--;
}
#endif
msleep(1000 / OSST_POLL_PER_SEC);
}
#if DEBUG
printk (OSST_DEB_MSG "%s:D: Fail wait f fr %i (>%i): %i-%i %i: %3li.%li s\n",
name, curr, curr+minlast, STp->first_frame_position,
STp->last_frame_position, STp->cur_frames,
(jiffies-startwait)/HZ, (((jiffies-startwait)%HZ)*10)/HZ);
#endif
return -EBUSY;
}
static int osst_recover_wait_frame(struct osst_tape * STp, struct osst_request ** aSRpnt, int writing)
{
struct osst_request * SRpnt;
unsigned char cmd[MAX_COMMAND_SIZE];
unsigned long startwait = jiffies;
int retval = 1;
char * name = tape_name(STp);
if (writing) {
char mybuf[24];
char * olddata = STp->buffer->b_data;
int oldsize = STp->buffer->buffer_size;
/* write zero fm then read pos - if shows write error, try to recover - if no progress, wait */
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_FILEMARKS;
cmd[1] = 1;
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout,
MAX_RETRIES, 1);
while (retval && time_before (jiffies, startwait + 5*60*HZ)) {
if (STp->buffer->syscall_result && (SRpnt->sense[2] & 0x0f) != 2) {
/* some failure - not just not-ready */
retval = osst_write_error_recovery(STp, aSRpnt, 0);
break;
}
schedule_timeout_interruptible(HZ / OSST_POLL_PER_SEC);
STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = READ_POSITION;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 20, DMA_FROM_DEVICE, STp->timeout,
MAX_RETRIES, 1);
retval = ( STp->buffer->syscall_result || (STp->buffer)->b_data[15] > 25 );
STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;
}
if (retval)
printk(KERN_ERR "%s:E: Device did not succeed to write buffered data\n", name);
} else
/* TODO - figure out which error conditions can be handled */
if (STp->buffer->syscall_result)
printk(KERN_WARNING
"%s:W: Recover_wait_frame(read) cannot handle %02x:%02x:%02x\n", name,
(*aSRpnt)->sense[ 2] & 0x0f,
(*aSRpnt)->sense[12],
(*aSRpnt)->sense[13]);
return retval;
}
/*
* Read the next OnStream tape frame at the current location
*/
static int osst_read_frame(struct osst_tape * STp, struct osst_request ** aSRpnt, int timeout)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
int retval = 0;
#if DEBUG
os_aux_t * aux = STp->buffer->aux;
char * name = tape_name(STp);
#endif
if (STp->poll)
if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, 0, timeout))
retval = osst_recover_wait_frame(STp, aSRpnt, 0);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = READ_6;
cmd[1] = 1;
cmd[4] = 1;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Reading frame from OnStream tape\n", name);
#endif
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_FROM_DEVICE,
STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (!SRpnt)
return (-EBUSY);
if ((STp->buffer)->syscall_result) {
retval = 1;
if (STp->read_error_frame == 0) {
STp->read_error_frame = STp->first_frame_position;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Recording read error at %d\n", name, STp->read_error_frame);
#endif
}
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
name,
SRpnt->sense[0], SRpnt->sense[1],
SRpnt->sense[2], SRpnt->sense[3],
SRpnt->sense[4], SRpnt->sense[5],
SRpnt->sense[6], SRpnt->sense[7]);
#endif
}
else
STp->first_frame_position++;
#if DEBUG
if (debugging) {
char sig[8]; int i;
for (i=0;i<4;i++)
sig[i] = aux->application_sig[i]<32?'^':aux->application_sig[i];
sig[4] = '\0';
printk(OSST_DEB_MSG
"%s:D: AUX: %s UpdFrCt#%d Wpass#%d %s FrSeq#%d LogBlk#%d Qty=%d Sz=%d\n", name, sig,
ntohl(aux->update_frame_cntr), ntohs(aux->partition.wrt_pass_cntr),
aux->frame_type==1?"EOD":aux->frame_type==2?"MARK":
aux->frame_type==8?"HEADR":aux->frame_type==0x80?"DATA":"FILL",
ntohl(aux->frame_seq_num), ntohl(aux->logical_blk_num),
ntohs(aux->dat.dat_list[0].blk_cnt), ntohl(aux->dat.dat_list[0].blk_sz) );
if (aux->frame_type==2)
printk(OSST_DEB_MSG "%s:D: mark_cnt=%d, last_mark_ppos=%d, last_mark_lbn=%d\n", name,
ntohl(aux->filemark_cnt), ntohl(aux->last_mark_ppos), ntohl(aux->last_mark_lbn));
printk(OSST_DEB_MSG "%s:D: Exit read frame from OnStream tape with code %d\n", name, retval);
}
#endif
return (retval);
}
static int osst_initiate_read(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
struct st_partstat * STps = &(STp->ps[STp->partition]);
struct osst_request * SRpnt ;
unsigned char cmd[MAX_COMMAND_SIZE];
int retval = 0;
char * name = tape_name(STp);
if (STps->rw != ST_READING) { /* Initialize read operation */
if (STps->rw == ST_WRITING || STp->dirty) {
STp->write_type = OS_WRITE_DATA;
osst_flush_write_buffer(STp, aSRpnt);
osst_flush_drive_buffer(STp, aSRpnt);
}
STps->rw = ST_READING;
STp->frame_in_buffer = 0;
/*
* Issue a read 0 command to get the OnStream drive
* read frames into its buffer.
*/
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = READ_6;
cmd[1] = 1;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Start Read Ahead on OnStream tape\n", name);
#endif
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if ((retval = STp->buffer->syscall_result))
printk(KERN_WARNING "%s:W: Error starting read ahead\n", name);
}
return retval;
}
static int osst_get_logical_frame(struct osst_tape * STp, struct osst_request ** aSRpnt,
int frame_seq_number, int quiet)
{
struct st_partstat * STps = &(STp->ps[STp->partition]);
char * name = tape_name(STp);
int cnt = 0,
bad = 0,
past = 0,
x,
position;
/*
* If we want just any frame (-1) and there is a frame in the buffer, return it
*/
if (frame_seq_number == -1 && STp->frame_in_buffer) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Frame %d still in buffer\n", name, STp->frame_seq_number);
#endif
return (STps->eof);
}
/*
* Search and wait for the next logical tape frame
*/
while (1) {
if (cnt++ > 400) {
printk(KERN_ERR "%s:E: Couldn't find logical frame %d, aborting\n",
name, frame_seq_number);
if (STp->read_error_frame) {
osst_set_frame_position(STp, aSRpnt, STp->read_error_frame, 0);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Repositioning tape to bad frame %d\n",
name, STp->read_error_frame);
#endif
STp->read_error_frame = 0;
STp->abort_count++;
}
return (-EIO);
}
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Looking for frame %d, attempt %d\n",
name, frame_seq_number, cnt);
#endif
if ( osst_initiate_read(STp, aSRpnt)
|| ( (!STp->frame_in_buffer) && osst_read_frame(STp, aSRpnt, 30) ) ) {
if (STp->raw)
return (-EIO);
position = osst_get_frame_position(STp, aSRpnt);
if (position >= 0xbae && position < 0xbb8)
position = 0xbb8;
else if (position > STp->eod_frame_ppos || ++bad == 10) {
position = STp->read_error_frame - 1;
bad = 0;
}
else {
position += 29;
cnt += 19;
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Bad frame detected, positioning tape to block %d\n",
name, position);
#endif
osst_set_frame_position(STp, aSRpnt, position, 0);
continue;
}
if (osst_verify_frame(STp, frame_seq_number, quiet))
break;
if (osst_verify_frame(STp, -1, quiet)) {
x = ntohl(STp->buffer->aux->frame_seq_num);
if (STp->fast_open) {
printk(KERN_WARNING
"%s:W: Found logical frame %d instead of %d after fast open\n",
name, x, frame_seq_number);
STp->header_ok = 0;
STp->read_error_frame = 0;
return (-EIO);
}
if (x > frame_seq_number) {
if (++past > 3) {
/* positioning backwards did not bring us to the desired frame */
position = STp->read_error_frame - 1;
}
else {
position = osst_get_frame_position(STp, aSRpnt)
+ frame_seq_number - x - 1;
if (STp->first_frame_position >= 3000 && position < 3000)
position -= 10;
}
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Found logical frame %d while looking for %d: back up %d\n",
name, x, frame_seq_number,
STp->first_frame_position - position);
#endif
osst_set_frame_position(STp, aSRpnt, position, 0);
cnt += 10;
}
else
past = 0;
}
if (osst_get_frame_position(STp, aSRpnt) == 0xbaf) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping config partition\n", name);
#endif
osst_set_frame_position(STp, aSRpnt, 0xbb8, 0);
cnt--;
}
STp->frame_in_buffer = 0;
}
if (cnt > 1) {
STp->recover_count++;
STp->recover_erreg++;
printk(KERN_WARNING "%s:I: Don't worry, Read error at position %d recovered\n",
name, STp->read_error_frame);
}
STp->read_count++;
#if DEBUG
if (debugging || STps->eof)
printk(OSST_DEB_MSG
"%s:D: Exit get logical frame (%d=>%d) from OnStream tape with code %d\n",
name, frame_seq_number, STp->frame_seq_number, STps->eof);
#endif
STp->fast_open = 0;
STp->read_error_frame = 0;
return (STps->eof);
}
static int osst_seek_logical_blk(struct osst_tape * STp, struct osst_request ** aSRpnt, int logical_blk_num)
{
struct st_partstat * STps = &(STp->ps[STp->partition]);
char * name = tape_name(STp);
int retries = 0;
int frame_seq_estimate, ppos_estimate, move;
if (logical_blk_num < 0) logical_blk_num = 0;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Seeking logical block %d (now at %d, size %d%c)\n",
name, logical_blk_num, STp->logical_blk_num,
STp->block_size<1024?STp->block_size:STp->block_size/1024,
STp->block_size<1024?'b':'k');
#endif
/* Do we know where we are? */
if (STps->drv_block >= 0) {
move = logical_blk_num - STp->logical_blk_num;
if (move < 0) move -= (OS_DATA_SIZE / STp->block_size) - 1;
move /= (OS_DATA_SIZE / STp->block_size);
frame_seq_estimate = STp->frame_seq_number + move;
} else
frame_seq_estimate = logical_blk_num * STp->block_size / OS_DATA_SIZE;
if (frame_seq_estimate < 2980) ppos_estimate = frame_seq_estimate + 10;
else ppos_estimate = frame_seq_estimate + 20;
while (++retries < 10) {
if (ppos_estimate > STp->eod_frame_ppos-2) {
frame_seq_estimate += STp->eod_frame_ppos - 2 - ppos_estimate;
ppos_estimate = STp->eod_frame_ppos - 2;
}
if (frame_seq_estimate < 0) {
frame_seq_estimate = 0;
ppos_estimate = 10;
}
osst_set_frame_position(STp, aSRpnt, ppos_estimate, 0);
if (osst_get_logical_frame(STp, aSRpnt, frame_seq_estimate, 1) >= 0) {
/* we've located the estimated frame, now does it have our block? */
if (logical_blk_num < STp->logical_blk_num ||
logical_blk_num >= STp->logical_blk_num + ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt)) {
if (STps->eof == ST_FM_HIT)
move = logical_blk_num < STp->logical_blk_num? -2 : 1;
else {
move = logical_blk_num - STp->logical_blk_num;
if (move < 0) move -= (OS_DATA_SIZE / STp->block_size) - 1;
move /= (OS_DATA_SIZE / STp->block_size);
}
if (!move) move = logical_blk_num > STp->logical_blk_num ? 1 : -1;
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Seek retry %d at ppos %d fsq %d (est %d) lbn %d (need %d) move %d\n",
name, retries, ppos_estimate, STp->frame_seq_number, frame_seq_estimate,
STp->logical_blk_num, logical_blk_num, move);
#endif
frame_seq_estimate += move;
ppos_estimate += move;
continue;
} else {
STp->buffer->read_pointer = (logical_blk_num - STp->logical_blk_num) * STp->block_size;
STp->buffer->buffer_bytes -= STp->buffer->read_pointer;
STp->logical_blk_num = logical_blk_num;
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Seek success at ppos %d fsq %d in_buf %d, bytes %d, ptr %d*%d\n",
name, ppos_estimate, STp->frame_seq_number, STp->frame_in_buffer,
STp->buffer->buffer_bytes, STp->buffer->read_pointer / STp->block_size,
STp->block_size);
#endif
STps->drv_file = ntohl(STp->buffer->aux->filemark_cnt);
if (STps->eof == ST_FM_HIT) {
STps->drv_file++;
STps->drv_block = 0;
} else {
STps->drv_block = ntohl(STp->buffer->aux->last_mark_lbn)?
STp->logical_blk_num -
(STps->drv_file ? ntohl(STp->buffer->aux->last_mark_lbn) + 1 : 0):
-1;
}
STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_NOEOF;
return 0;
}
}
if (osst_get_logical_frame(STp, aSRpnt, -1, 1) < 0)
goto error;
/* we are not yet at the estimated frame, adjust our estimate of its physical position */
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Seek retry %d at ppos %d fsq %d (est %d) lbn %d (need %d)\n",
name, retries, ppos_estimate, STp->frame_seq_number, frame_seq_estimate,
STp->logical_blk_num, logical_blk_num);
#endif
if (frame_seq_estimate != STp->frame_seq_number)
ppos_estimate += frame_seq_estimate - STp->frame_seq_number;
else
break;
}
error:
printk(KERN_ERR "%s:E: Couldn't seek to logical block %d (at %d), %d retries\n",
name, logical_blk_num, STp->logical_blk_num, retries);
return (-EIO);
}
/* The values below are based on the OnStream frame payload size of 32K == 2**15,
* that is, OSST_FRAME_SHIFT + OSST_SECTOR_SHIFT must be 15. With a minimum block
* size of 512 bytes, we need to be able to resolve 32K/512 == 64 == 2**6 positions
* inside each frame. Finally, OSST_SECTOR_MASK == 2**OSST_FRAME_SHIFT - 1.
*/
#define OSST_FRAME_SHIFT 6
#define OSST_SECTOR_SHIFT 9
#define OSST_SECTOR_MASK 0x03F
static int osst_get_sector(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
int sector;
#if DEBUG
char * name = tape_name(STp);
printk(OSST_DEB_MSG
"%s:D: Positioned at ppos %d, frame %d, lbn %d, file %d, blk %d, %cptr %d, eof %d\n",
name, STp->first_frame_position, STp->frame_seq_number, STp->logical_blk_num,
STp->ps[STp->partition].drv_file, STp->ps[STp->partition].drv_block,
STp->ps[STp->partition].rw == ST_WRITING?'w':'r',
STp->ps[STp->partition].rw == ST_WRITING?STp->buffer->buffer_bytes:
STp->buffer->read_pointer, STp->ps[STp->partition].eof);
#endif
/* do we know where we are inside a file? */
if (STp->ps[STp->partition].drv_block >= 0) {
sector = (STp->frame_in_buffer ? STp->first_frame_position-1 :
STp->first_frame_position) << OSST_FRAME_SHIFT;
if (STp->ps[STp->partition].rw == ST_WRITING)
sector |= (STp->buffer->buffer_bytes >> OSST_SECTOR_SHIFT) & OSST_SECTOR_MASK;
else
sector |= (STp->buffer->read_pointer >> OSST_SECTOR_SHIFT) & OSST_SECTOR_MASK;
} else {
sector = osst_get_frame_position(STp, aSRpnt);
if (sector > 0)
sector <<= OSST_FRAME_SHIFT;
}
return sector;
}
static int osst_seek_sector(struct osst_tape * STp, struct osst_request ** aSRpnt, int sector)
{
struct st_partstat * STps = &(STp->ps[STp->partition]);
int frame = sector >> OSST_FRAME_SHIFT,
offset = (sector & OSST_SECTOR_MASK) << OSST_SECTOR_SHIFT,
r;
#if DEBUG
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Seeking sector %d in frame %d at offset %d\n",
name, sector, frame, offset);
#endif
if (frame < 0 || frame >= STp->capacity) return (-ENXIO);
if (frame <= STp->first_data_ppos) {
STp->frame_seq_number = STp->logical_blk_num = STps->drv_file = STps->drv_block = 0;
return (osst_set_frame_position(STp, aSRpnt, frame, 0));
}
r = osst_set_frame_position(STp, aSRpnt, offset?frame:frame-1, 0);
if (r < 0) return r;
r = osst_get_logical_frame(STp, aSRpnt, -1, 1);
if (r < 0) return r;
if (osst_get_frame_position(STp, aSRpnt) != (offset?frame+1:frame)) return (-EIO);
if (offset) {
STp->logical_blk_num += offset / STp->block_size;
STp->buffer->read_pointer = offset;
STp->buffer->buffer_bytes -= offset;
} else {
STp->frame_seq_number++;
STp->frame_in_buffer = 0;
STp->logical_blk_num += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
STp->buffer->buffer_bytes = STp->buffer->read_pointer = 0;
}
STps->drv_file = ntohl(STp->buffer->aux->filemark_cnt);
if (STps->eof == ST_FM_HIT) {
STps->drv_file++;
STps->drv_block = 0;
} else {
STps->drv_block = ntohl(STp->buffer->aux->last_mark_lbn)?
STp->logical_blk_num -
(STps->drv_file ? ntohl(STp->buffer->aux->last_mark_lbn) + 1 : 0):
-1;
}
STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_NOEOF;
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Now positioned at ppos %d, frame %d, lbn %d, file %d, blk %d, rptr %d, eof %d\n",
name, STp->first_frame_position, STp->frame_seq_number, STp->logical_blk_num,
STps->drv_file, STps->drv_block, STp->buffer->read_pointer, STps->eof);
#endif
return 0;
}
/*
* Read back the drive's internal buffer contents, as a part
* of the write error recovery mechanism for old OnStream
* firmware revisions.
* Precondition for this function to work: all frames in the
* drive's buffer must be of one type (DATA, MARK or EOD)!
*/
static int osst_read_back_buffer_and_rewrite(struct osst_tape * STp, struct osst_request ** aSRpnt,
unsigned int frame, unsigned int skip, int pending)
{
struct osst_request * SRpnt = * aSRpnt;
unsigned char * buffer, * p;
unsigned char cmd[MAX_COMMAND_SIZE];
int flag, new_frame, i;
int nframes = STp->cur_frames;
int blks_per_frame = ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
int frame_seq_number = ntohl(STp->buffer->aux->frame_seq_num)
- (nframes + pending - 1);
int logical_blk_num = ntohl(STp->buffer->aux->logical_blk_num)
- (nframes + pending - 1) * blks_per_frame;
char * name = tape_name(STp);
unsigned long startwait = jiffies;
#if DEBUG
int dbg = debugging;
#endif
if ((buffer = vmalloc((nframes + 1) * OS_DATA_SIZE)) == NULL)
return (-EIO);
printk(KERN_INFO "%s:I: Reading back %d frames from drive buffer%s\n",
name, nframes, pending?" and one that was pending":"");
osst_copy_from_buffer(STp->buffer, (p = &buffer[nframes * OS_DATA_SIZE]));
#if DEBUG
if (pending && debugging)
printk(OSST_DEB_MSG "%s:D: Pending frame %d (lblk %d), data %02x %02x %02x %02x\n",
name, frame_seq_number + nframes,
logical_blk_num + nframes * blks_per_frame,
p[0], p[1], p[2], p[3]);
#endif
for (i = 0, p = buffer; i < nframes; i++, p += OS_DATA_SIZE) {
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = 0x3C; /* Buffer Read */
cmd[1] = 6; /* Retrieve Faulty Block */
cmd[7] = 32768 >> 8;
cmd[8] = 32768 & 0xff;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, OS_FRAME_SIZE, DMA_FROM_DEVICE,
STp->timeout, MAX_RETRIES, 1);
if ((STp->buffer)->syscall_result || !SRpnt) {
printk(KERN_ERR "%s:E: Failed to read frame back from OnStream buffer\n", name);
vfree(buffer);
*aSRpnt = SRpnt;
return (-EIO);
}
osst_copy_from_buffer(STp->buffer, p);
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Read back logical frame %d, data %02x %02x %02x %02x\n",
name, frame_seq_number + i, p[0], p[1], p[2], p[3]);
#endif
}
*aSRpnt = SRpnt;
osst_get_frame_position(STp, aSRpnt);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Frames left in buffer: %d\n", name, STp->cur_frames);
#endif
/* Write synchronously so we can be sure we're OK again and don't have to recover recursively */
/* In the header we don't actually re-write the frames that fail, just the ones after them */
for (flag=1, new_frame=frame, p=buffer, i=0; i < nframes + pending; ) {
if (flag) {
if (STp->write_type == OS_WRITE_HEADER) {
i += skip;
p += skip * OS_DATA_SIZE;
}
else if (new_frame < 2990 && new_frame+skip+nframes+pending >= 2990)
new_frame = 3000-i;
else
new_frame += skip;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Position to frame %d, write fseq %d\n",
name, new_frame+i, frame_seq_number+i);
#endif
osst_set_frame_position(STp, aSRpnt, new_frame + i, 0);
osst_wait_ready(STp, aSRpnt, 60, OSST_WAIT_POSITION_COMPLETE);
osst_get_frame_position(STp, aSRpnt);
SRpnt = * aSRpnt;
if (new_frame > frame + 1000) {
printk(KERN_ERR "%s:E: Failed to find writable tape media\n", name);
vfree(buffer);
return (-EIO);
}
if ( i >= nframes + pending ) break;
flag = 0;
}
osst_copy_to_buffer(STp->buffer, p);
/*
* IMPORTANT: for error recovery to work, _never_ queue frames with mixed frame type!
*/
osst_init_aux(STp, STp->buffer->aux->frame_type, frame_seq_number+i,
logical_blk_num + i*blks_per_frame,
ntohl(STp->buffer->aux->dat.dat_list[0].blk_sz), blks_per_frame);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = 1;
cmd[4] = 1;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG
"%s:D: About to write frame %d, seq %d, lbn %d, data %02x %02x %02x %02x\n",
name, new_frame+i, frame_seq_number+i, logical_blk_num + i*blks_per_frame,
p[0], p[1], p[2], p[3]);
#endif
SRpnt = osst_do_scsi(SRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE,
STp->timeout, MAX_RETRIES, 1);
if (STp->buffer->syscall_result)
flag = 1;
else {
p += OS_DATA_SIZE; i++;
/* if we just sent the last frame, wait till all successfully written */
if ( i == nframes + pending ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Check re-write successful\n", name);
#endif
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_FILEMARKS;
cmd[1] = 1;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
STp->timeout, MAX_RETRIES, 1);
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Sleeping in re-write wait ready\n", name);
printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
debugging = 0;
}
#endif
flag = STp->buffer->syscall_result;
while ( !flag && time_before(jiffies, startwait + 60*HZ) ) {
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout,
MAX_RETRIES, 1);
if (SRpnt->sense[2] == 2 && SRpnt->sense[12] == 4 &&
(SRpnt->sense[13] == 1 || SRpnt->sense[13] == 8)) {
/* in the process of becoming ready */
msleep(100);
continue;
}
if (STp->buffer->syscall_result)
flag = 1;
break;
}
#if DEBUG
debugging = dbg;
printk(OSST_DEB_MSG "%s:D: Wait re-write finished\n", name);
#endif
}
}
*aSRpnt = SRpnt;
if (flag) {
if ((SRpnt->sense[ 2] & 0x0f) == 13 &&
SRpnt->sense[12] == 0 &&
SRpnt->sense[13] == 2) {
printk(KERN_ERR "%s:E: Volume overflow in write error recovery\n", name);
vfree(buffer);
return (-EIO); /* hit end of tape = fail */
}
i = ((SRpnt->sense[3] << 24) |
(SRpnt->sense[4] << 16) |
(SRpnt->sense[5] << 8) |
SRpnt->sense[6] ) - new_frame;
p = &buffer[i * OS_DATA_SIZE];
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Additional write error at %d\n", name, new_frame+i);
#endif
osst_get_frame_position(STp, aSRpnt);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: reported frame positions: host = %d, tape = %d, buffer = %d\n",
name, STp->first_frame_position, STp->last_frame_position, STp->cur_frames);
#endif
}
}
if (flag) {
/* error recovery did not successfully complete */
printk(KERN_ERR "%s:D: Write error recovery failed in %s\n", name,
STp->write_type == OS_WRITE_HEADER?"header":"body");
}
if (!pending)
osst_copy_to_buffer(STp->buffer, p); /* so buffer content == at entry in all cases */
vfree(buffer);
return 0;
}
static int osst_reposition_and_retry(struct osst_tape * STp, struct osst_request ** aSRpnt,
unsigned int frame, unsigned int skip, int pending)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
char * name = tape_name(STp);
int expected = 0;
int attempts = 1000 / skip;
int flag = 1;
unsigned long startwait = jiffies;
#if DEBUG
int dbg = debugging;
#endif
while (attempts && time_before(jiffies, startwait + 60*HZ)) {
if (flag) {
#if DEBUG
debugging = dbg;
#endif
if (frame < 2990 && frame+skip+STp->cur_frames+pending >= 2990)
frame = 3000-skip;
expected = frame+skip+STp->cur_frames+pending;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Position to fppos %d, re-write from fseq %d\n",
name, frame+skip, STp->frame_seq_number-STp->cur_frames-pending);
#endif
osst_set_frame_position(STp, aSRpnt, frame + skip, 1);
flag = 0;
attempts--;
schedule_timeout_interruptible(msecs_to_jiffies(100));
}
if (osst_get_frame_position(STp, aSRpnt) < 0) { /* additional write error */
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Addl error, host %d, tape %d, buffer %d\n",
name, STp->first_frame_position,
STp->last_frame_position, STp->cur_frames);
#endif
frame = STp->last_frame_position;
flag = 1;
continue;
}
if (pending && STp->cur_frames < 50) {
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = 1;
cmd[4] = 1;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: About to write pending fseq %d at fppos %d\n",
name, STp->frame_seq_number-1, STp->first_frame_position);
#endif
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE,
STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (STp->buffer->syscall_result) { /* additional write error */
if ((SRpnt->sense[ 2] & 0x0f) == 13 &&
SRpnt->sense[12] == 0 &&
SRpnt->sense[13] == 2) {
printk(KERN_ERR
"%s:E: Volume overflow in write error recovery\n",
name);
break; /* hit end of tape = fail */
}
flag = 1;
}
else
pending = 0;
continue;
}
if (STp->cur_frames == 0) {
#if DEBUG
debugging = dbg;
printk(OSST_DEB_MSG "%s:D: Wait re-write finished\n", name);
#endif
if (STp->first_frame_position != expected) {
printk(KERN_ERR "%s:A: Actual position %d - expected %d\n",
name, STp->first_frame_position, expected);
return (-EIO);
}
return 0;
}
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Sleeping in re-write wait ready\n", name);
printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
debugging = 0;
}
#endif
schedule_timeout_interruptible(msecs_to_jiffies(100));
}
printk(KERN_ERR "%s:E: Failed to find valid tape media\n", name);
#if DEBUG
debugging = dbg;
#endif
return (-EIO);
}
/*
* Error recovery algorithm for the OnStream tape.
*/
static int osst_write_error_recovery(struct osst_tape * STp, struct osst_request ** aSRpnt, int pending)
{
struct osst_request * SRpnt = * aSRpnt;
struct st_partstat * STps = & STp->ps[STp->partition];
char * name = tape_name(STp);
int retval = 0;
int rw_state;
unsigned int frame, skip;
rw_state = STps->rw;
if ((SRpnt->sense[ 2] & 0x0f) != 3
|| SRpnt->sense[12] != 12
|| SRpnt->sense[13] != 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Write error recovery cannot handle %02x:%02x:%02x\n", name,
SRpnt->sense[2], SRpnt->sense[12], SRpnt->sense[13]);
#endif
return (-EIO);
}
frame = (SRpnt->sense[3] << 24) |
(SRpnt->sense[4] << 16) |
(SRpnt->sense[5] << 8) |
SRpnt->sense[6];
skip = SRpnt->sense[9];
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Detected physical bad frame at %u, advised to skip %d\n", name, frame, skip);
#endif
osst_get_frame_position(STp, aSRpnt);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: reported frame positions: host = %d, tape = %d\n",
name, STp->first_frame_position, STp->last_frame_position);
#endif
switch (STp->write_type) {
case OS_WRITE_DATA:
case OS_WRITE_EOD:
case OS_WRITE_NEW_MARK:
printk(KERN_WARNING
"%s:I: Relocating %d buffered logical frames from position %u to %u\n",
name, STp->cur_frames, frame, (frame + skip > 3000 && frame < 3000)?3000:frame + skip);
if (STp->os_fw_rev >= 10600)
retval = osst_reposition_and_retry(STp, aSRpnt, frame, skip, pending);
else
retval = osst_read_back_buffer_and_rewrite(STp, aSRpnt, frame, skip, pending);
printk(KERN_WARNING "%s:%s: %sWrite error%srecovered\n", name,
retval?"E" :"I",
retval?"" :"Don't worry, ",
retval?" not ":" ");
break;
case OS_WRITE_LAST_MARK:
printk(KERN_ERR "%s:E: Bad frame in update last marker, fatal\n", name);
osst_set_frame_position(STp, aSRpnt, frame + STp->cur_frames + pending, 0);
retval = -EIO;
break;
case OS_WRITE_HEADER:
printk(KERN_WARNING "%s:I: Bad frame in header partition, skipped\n", name);
retval = osst_read_back_buffer_and_rewrite(STp, aSRpnt, frame, 1, pending);
break;
default:
printk(KERN_INFO "%s:I: Bad frame in filler, ignored\n", name);
osst_set_frame_position(STp, aSRpnt, frame + STp->cur_frames + pending, 0);
}
osst_get_frame_position(STp, aSRpnt);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Positioning complete, cur_frames %d, pos %d, tape pos %d\n",
name, STp->cur_frames, STp->first_frame_position, STp->last_frame_position);
printk(OSST_DEB_MSG "%s:D: next logical frame to write: %d\n", name, STp->logical_blk_num);
#endif
if (retval == 0) {
STp->recover_count++;
STp->recover_erreg++;
} else
STp->abort_count++;
STps->rw = rw_state;
return retval;
}
static int osst_space_over_filemarks_backward(struct osst_tape * STp, struct osst_request ** aSRpnt,
int mt_op, int mt_count)
{
char * name = tape_name(STp);
int cnt;
int last_mark_ppos = -1;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_backwards %d %d\n", name, mt_op, mt_count);
#endif
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_bwd\n", name);
#endif
return -EIO;
}
if (STp->linux_media_version >= 4) {
/*
* direct lookup in header filemark list
*/
cnt = ntohl(STp->buffer->aux->filemark_cnt);
if (STp->header_ok &&
STp->header_cache != NULL &&
(cnt - mt_count) >= 0 &&
(cnt - mt_count) < OS_FM_TAB_MAX &&
(cnt - mt_count) < STp->filemark_cnt &&
STp->header_cache->dat_fm_tab.fm_tab_ent[cnt-1] == STp->buffer->aux->last_mark_ppos)
last_mark_ppos = ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt - mt_count]);
#if DEBUG
if (STp->header_cache == NULL || (cnt - mt_count) < 0 || (cnt - mt_count) >= OS_FM_TAB_MAX)
printk(OSST_DEB_MSG "%s:D: Filemark lookup fail due to %s\n", name,
STp->header_cache == NULL?"lack of header cache":"count out of range");
else
printk(OSST_DEB_MSG "%s:D: Filemark lookup: prev mark %d (%s), skip %d to %d\n",
name, cnt,
((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt-1] ==
STp->buffer->aux->last_mark_ppos))?"match":"error",
mt_count, last_mark_ppos);
#endif
if (last_mark_ppos > 10 && last_mark_ppos < STp->eod_frame_ppos) {
osst_position_tape_and_confirm(STp, aSRpnt, last_mark_ppos);
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
name, last_mark_ppos);
return (-EIO);
}
goto found;
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reverting to scan filemark backwards\n", name);
#endif
}
cnt = 0;
while (cnt != mt_count) {
last_mark_ppos = ntohl(STp->buffer->aux->last_mark_ppos);
if (last_mark_ppos == -1)
return (-EIO);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Positioning to last mark at %d\n", name, last_mark_ppos);
#endif
osst_position_tape_and_confirm(STp, aSRpnt, last_mark_ppos);
cnt++;
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
name, last_mark_ppos);
return (-EIO);
}
}
found:
if (mt_op == MTBSFM) {
STp->frame_seq_number++;
STp->frame_in_buffer = 0;
STp->buffer->buffer_bytes = 0;
STp->buffer->read_pointer = 0;
STp->logical_blk_num += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
}
return 0;
}
/*
* ADRL 1.1 compatible "slow" space filemarks fwd version
*
* Just scans for the filemark sequentially.
*/
static int osst_space_over_filemarks_forward_slow(struct osst_tape * STp, struct osst_request ** aSRpnt,
int mt_op, int mt_count)
{
int cnt = 0;
#if DEBUG
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_forward_slow %d %d\n", name, mt_op, mt_count);
#endif
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_fwd\n", name);
#endif
return (-EIO);
}
while (1) {
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER)
cnt++;
if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_EOD) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: space_fwd: EOD reached\n", name);
#endif
if (STp->first_frame_position > STp->eod_frame_ppos+1) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: EOD position corrected (%d=>%d)\n",
name, STp->eod_frame_ppos, STp->first_frame_position-1);
#endif
STp->eod_frame_ppos = STp->first_frame_position-1;
}
return (-EIO);
}
if (cnt == mt_count)
break;
STp->frame_in_buffer = 0;
}
if (mt_op == MTFSF) {
STp->frame_seq_number++;
STp->frame_in_buffer = 0;
STp->buffer->buffer_bytes = 0;
STp->buffer->read_pointer = 0;
STp->logical_blk_num += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
}
return 0;
}
/*
* Fast linux specific version of OnStream FSF
*/
static int osst_space_over_filemarks_forward_fast(struct osst_tape * STp, struct osst_request ** aSRpnt,
int mt_op, int mt_count)
{
char * name = tape_name(STp);
int cnt = 0,
next_mark_ppos = -1;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_forward_fast %d %d\n", name, mt_op, mt_count);
#endif
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_fwd\n", name);
#endif
return (-EIO);
}
if (STp->linux_media_version >= 4) {
/*
* direct lookup in header filemark list
*/
cnt = ntohl(STp->buffer->aux->filemark_cnt) - 1;
if (STp->header_ok &&
STp->header_cache != NULL &&
(cnt + mt_count) < OS_FM_TAB_MAX &&
(cnt + mt_count) < STp->filemark_cnt &&
((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt] == STp->buffer->aux->last_mark_ppos)))
next_mark_ppos = ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt + mt_count]);
#if DEBUG
if (STp->header_cache == NULL || (cnt + mt_count) >= OS_FM_TAB_MAX)
printk(OSST_DEB_MSG "%s:D: Filemark lookup fail due to %s\n", name,
STp->header_cache == NULL?"lack of header cache":"count out of range");
else
printk(OSST_DEB_MSG "%s:D: Filemark lookup: prev mark %d (%s), skip %d to %d\n",
name, cnt,
((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt] ==
STp->buffer->aux->last_mark_ppos))?"match":"error",
mt_count, next_mark_ppos);
#endif
if (next_mark_ppos <= 10 || next_mark_ppos > STp->eod_frame_ppos) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count);
} else {
osst_position_tape_and_confirm(STp, aSRpnt, next_mark_ppos);
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n",
name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
name, next_mark_ppos);
return (-EIO);
}
if (ntohl(STp->buffer->aux->filemark_cnt) != cnt + mt_count) {
printk(KERN_WARNING "%s:W: Expected to find marker %d at ppos %d, not %d\n",
name, cnt+mt_count, next_mark_ppos,
ntohl(STp->buffer->aux->filemark_cnt));
return (-EIO);
}
}
} else {
/*
* Find nearest (usually previous) marker, then jump from marker to marker
*/
while (1) {
if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER)
break;
if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_EOD) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: space_fwd: EOD reached\n", name);
#endif
return (-EIO);
}
if (ntohl(STp->buffer->aux->filemark_cnt) == 0) {
if (STp->first_mark_ppos == -1) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count);
}
osst_position_tape_and_confirm(STp, aSRpnt, STp->first_mark_ppos);
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Couldn't get logical blk num in space_filemarks_fwd_fast\n",
name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
printk(KERN_WARNING "%s:W: Expected to find filemark at %d\n",
name, STp->first_mark_ppos);
return (-EIO);
}
} else {
if (osst_space_over_filemarks_backward(STp, aSRpnt, MTBSF, 1) < 0)
return (-EIO);
mt_count++;
}
}
cnt++;
while (cnt != mt_count) {
next_mark_ppos = ntohl(STp->buffer->aux->next_mark_ppos);
if (!next_mark_ppos || next_mark_ppos > STp->eod_frame_ppos) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count - cnt);
}
#if DEBUG
else printk(OSST_DEB_MSG "%s:D: Positioning to next mark at %d\n", name, next_mark_ppos);
#endif
osst_position_tape_and_confirm(STp, aSRpnt, next_mark_ppos);
cnt++;
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n",
name);
#endif
return (-EIO);
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
name, next_mark_ppos);
return (-EIO);
}
}
}
if (mt_op == MTFSF) {
STp->frame_seq_number++;
STp->frame_in_buffer = 0;
STp->buffer->buffer_bytes = 0;
STp->buffer->read_pointer = 0;
STp->logical_blk_num += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
}
return 0;
}
/*
* In debug mode, we want to see as many errors as possible
* to test the error recovery mechanism.
*/
#if DEBUG
static void osst_set_retries(struct osst_tape * STp, struct osst_request ** aSRpnt, int retries)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt = * aSRpnt;
char * name = tape_name(STp);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SELECT;
cmd[1] = 0x10;
cmd[4] = NUMBER_RETRIES_PAGE_LENGTH + MODE_HEADER_LENGTH;
(STp->buffer)->b_data[0] = cmd[4] - 1;
(STp->buffer)->b_data[1] = 0; /* Medium Type - ignoring */
(STp->buffer)->b_data[2] = 0; /* Reserved */
(STp->buffer)->b_data[3] = 0; /* Block Descriptor Length */
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = NUMBER_RETRIES_PAGE | (1 << 7);
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 2;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 4;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = retries;
if (debugging)
printk(OSST_DEB_MSG "%s:D: Setting number of retries on OnStream tape to %d\n", name, retries);
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result)
printk (KERN_ERR "%s:D: Couldn't set retries to %d\n", name, retries);
}
#endif
static int osst_write_filemark(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
int result;
int this_mark_ppos = STp->first_frame_position;
int this_mark_lbn = STp->logical_blk_num;
#if DEBUG
char * name = tape_name(STp);
#endif
if (STp->raw) return 0;
STp->write_type = OS_WRITE_NEW_MARK;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Writing Filemark %i at fppos %d (fseq %d, lblk %d)\n",
name, STp->filemark_cnt, this_mark_ppos, STp->frame_seq_number, this_mark_lbn);
#endif
STp->dirty = 1;
result = osst_flush_write_buffer(STp, aSRpnt);
result |= osst_flush_drive_buffer(STp, aSRpnt);
STp->last_mark_ppos = this_mark_ppos;
STp->last_mark_lbn = this_mark_lbn;
if (STp->header_cache != NULL && STp->filemark_cnt < OS_FM_TAB_MAX)
STp->header_cache->dat_fm_tab.fm_tab_ent[STp->filemark_cnt] = htonl(this_mark_ppos);
if (STp->filemark_cnt++ == 0)
STp->first_mark_ppos = this_mark_ppos;
return result;
}
static int osst_write_eod(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
int result;
#if DEBUG
char * name = tape_name(STp);
#endif
if (STp->raw) return 0;
STp->write_type = OS_WRITE_EOD;
STp->eod_frame_ppos = STp->first_frame_position;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Writing EOD at fppos %d (fseq %d, lblk %d)\n", name,
STp->eod_frame_ppos, STp->frame_seq_number, STp->logical_blk_num);
#endif
STp->dirty = 1;
result = osst_flush_write_buffer(STp, aSRpnt);
result |= osst_flush_drive_buffer(STp, aSRpnt);
STp->eod_frame_lfa = --(STp->frame_seq_number);
return result;
}
static int osst_write_filler(struct osst_tape * STp, struct osst_request ** aSRpnt, int where, int count)
{
char * name = tape_name(STp);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reached onstream write filler group %d\n", name, where);
#endif
osst_wait_ready(STp, aSRpnt, 60 * 5, 0);
osst_set_frame_position(STp, aSRpnt, where, 0);
STp->write_type = OS_WRITE_FILLER;
while (count--) {
memcpy(STp->buffer->b_data, "Filler", 6);
STp->buffer->buffer_bytes = 6;
STp->dirty = 1;
if (osst_flush_write_buffer(STp, aSRpnt)) {
printk(KERN_INFO "%s:I: Couldn't write filler frame\n", name);
return (-EIO);
}
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Exiting onstream write filler group\n", name);
#endif
return osst_flush_drive_buffer(STp, aSRpnt);
}
static int __osst_write_header(struct osst_tape * STp, struct osst_request ** aSRpnt, int where, int count)
{
char * name = tape_name(STp);
int result;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reached onstream write header group %d\n", name, where);
#endif
osst_wait_ready(STp, aSRpnt, 60 * 5, 0);
osst_set_frame_position(STp, aSRpnt, where, 0);
STp->write_type = OS_WRITE_HEADER;
while (count--) {
osst_copy_to_buffer(STp->buffer, (unsigned char *)STp->header_cache);
STp->buffer->buffer_bytes = sizeof(os_header_t);
STp->dirty = 1;
if (osst_flush_write_buffer(STp, aSRpnt)) {
printk(KERN_INFO "%s:I: Couldn't write header frame\n", name);
return (-EIO);
}
}
result = osst_flush_drive_buffer(STp, aSRpnt);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Write onstream header group %s\n", name, result?"failed":"done");
#endif
return result;
}
static int osst_write_header(struct osst_tape * STp, struct osst_request ** aSRpnt, int locate_eod)
{
os_header_t * header;
int result;
char * name = tape_name(STp);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Writing tape header\n", name);
#endif
if (STp->raw) return 0;
if (STp->header_cache == NULL) {
if ((STp->header_cache = vmalloc(sizeof(os_header_t))) == NULL) {
printk(KERN_ERR "%s:E: Failed to allocate header cache\n", name);
return (-ENOMEM);
}
memset(STp->header_cache, 0, sizeof(os_header_t));
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Allocated and cleared memory for header cache\n", name);
#endif
}
if (STp->header_ok) STp->update_frame_cntr++;
else STp->update_frame_cntr = 0;
header = STp->header_cache;
strcpy(header->ident_str, "ADR_SEQ");
header->major_rev = 1;
header->minor_rev = 4;
header->ext_trk_tb_off = htons(17192);
header->pt_par_num = 1;
header->partition[0].partition_num = OS_DATA_PARTITION;
header->partition[0].par_desc_ver = OS_PARTITION_VERSION;
header->partition[0].wrt_pass_cntr = htons(STp->wrt_pass_cntr);
header->partition[0].first_frame_ppos = htonl(STp->first_data_ppos);
header->partition[0].last_frame_ppos = htonl(STp->capacity);
header->partition[0].eod_frame_ppos = htonl(STp->eod_frame_ppos);
header->cfg_col_width = htonl(20);
header->dat_col_width = htonl(1500);
header->qfa_col_width = htonl(0);
header->ext_track_tb.nr_stream_part = 1;
header->ext_track_tb.et_ent_sz = 32;
header->ext_track_tb.dat_ext_trk_ey.et_part_num = 0;
header->ext_track_tb.dat_ext_trk_ey.fmt = 1;
header->ext_track_tb.dat_ext_trk_ey.fm_tab_off = htons(17736);
header->ext_track_tb.dat_ext_trk_ey.last_hlb_hi = 0;
header->ext_track_tb.dat_ext_trk_ey.last_hlb = htonl(STp->eod_frame_lfa);
header->ext_track_tb.dat_ext_trk_ey.last_pp = htonl(STp->eod_frame_ppos);
header->dat_fm_tab.fm_part_num = 0;
header->dat_fm_tab.fm_tab_ent_sz = 4;
header->dat_fm_tab.fm_tab_ent_cnt = htons(STp->filemark_cnt<OS_FM_TAB_MAX?
STp->filemark_cnt:OS_FM_TAB_MAX);
result = __osst_write_header(STp, aSRpnt, 0xbae, 5);
if (STp->update_frame_cntr == 0)
osst_write_filler(STp, aSRpnt, 0xbb3, 5);
result &= __osst_write_header(STp, aSRpnt, 5, 5);
if (locate_eod) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Locating back to eod frame addr %d\n", name, STp->eod_frame_ppos);
#endif
osst_set_frame_position(STp, aSRpnt, STp->eod_frame_ppos, 0);
}
if (result)
printk(KERN_ERR "%s:E: Write header failed\n", name);
else {
memcpy(STp->application_sig, "LIN4", 4);
STp->linux_media = 1;
STp->linux_media_version = 4;
STp->header_ok = 1;
}
return result;
}
static int osst_reset_header(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
if (STp->header_cache != NULL)
memset(STp->header_cache, 0, sizeof(os_header_t));
STp->logical_blk_num = STp->frame_seq_number = 0;
STp->frame_in_buffer = 0;
STp->eod_frame_ppos = STp->first_data_ppos = 0x0000000A;
STp->filemark_cnt = 0;
STp->first_mark_ppos = STp->last_mark_ppos = STp->last_mark_lbn = -1;
return osst_write_header(STp, aSRpnt, 1);
}
static int __osst_analyze_headers(struct osst_tape * STp, struct osst_request ** aSRpnt, int ppos)
{
char * name = tape_name(STp);
os_header_t * header;
os_aux_t * aux;
char id_string[8];
int linux_media_version,
update_frame_cntr;
if (STp->raw)
return 1;
if (ppos == 5 || ppos == 0xbae || STp->buffer->syscall_result) {
if (osst_set_frame_position(STp, aSRpnt, ppos, 0))
printk(KERN_WARNING "%s:W: Couldn't position tape\n", name);
osst_wait_ready(STp, aSRpnt, 60 * 15, 0);
if (osst_initiate_read (STp, aSRpnt)) {
printk(KERN_WARNING "%s:W: Couldn't initiate read\n", name);
return 0;
}
}
if (osst_read_frame(STp, aSRpnt, 180)) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't read header frame\n", name);
#endif
return 0;
}
header = (os_header_t *) STp->buffer->b_data; /* warning: only first segment addressable */
aux = STp->buffer->aux;
if (aux->frame_type != OS_FRAME_TYPE_HEADER) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping non-header frame (%d)\n", name, ppos);
#endif
return 0;
}
if (ntohl(aux->frame_seq_num) != 0 ||
ntohl(aux->logical_blk_num) != 0 ||
aux->partition.partition_num != OS_CONFIG_PARTITION ||
ntohl(aux->partition.first_frame_ppos) != 0 ||
ntohl(aux->partition.last_frame_ppos) != 0xbb7 ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Invalid header frame (%d,%d,%d,%d,%d)\n", name,
ntohl(aux->frame_seq_num), ntohl(aux->logical_blk_num),
aux->partition.partition_num, ntohl(aux->partition.first_frame_ppos),
ntohl(aux->partition.last_frame_ppos));
#endif
return 0;
}
if (strncmp(header->ident_str, "ADR_SEQ", 7) != 0 &&
strncmp(header->ident_str, "ADR-SEQ", 7) != 0) {
strlcpy(id_string, header->ident_str, 8);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Invalid header identification string %s\n", name, id_string);
#endif
return 0;
}
update_frame_cntr = ntohl(aux->update_frame_cntr);
if (update_frame_cntr < STp->update_frame_cntr) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame %d with update_frame_counter %d<%d\n",
name, ppos, update_frame_cntr, STp->update_frame_cntr);
#endif
return 0;
}
if (header->major_rev != 1 || header->minor_rev != 4 ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: %s revision %d.%d detected (1.4 supported)\n",
name, (header->major_rev != 1 || header->minor_rev < 2 ||
header->minor_rev > 4 )? "Invalid" : "Warning:",
header->major_rev, header->minor_rev);
#endif
if (header->major_rev != 1 || header->minor_rev < 2 || header->minor_rev > 4)
return 0;
}
#if DEBUG
if (header->pt_par_num != 1)
printk(KERN_INFO "%s:W: %d partitions defined, only one supported\n",
name, header->pt_par_num);
#endif
memcpy(id_string, aux->application_sig, 4);
id_string[4] = 0;
if (memcmp(id_string, "LIN", 3) == 0) {
STp->linux_media = 1;
linux_media_version = id_string[3] - '0';
if (linux_media_version != 4)
printk(KERN_INFO "%s:I: Linux media version %d detected (current 4)\n",
name, linux_media_version);
} else {
printk(KERN_WARNING "%s:W: Non Linux media detected (%s)\n", name, id_string);
return 0;
}
if (linux_media_version < STp->linux_media_version) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping frame %d with linux_media_version %d\n",
name, ppos, linux_media_version);
#endif
return 0;
}
if (linux_media_version > STp->linux_media_version) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Frame %d sets linux_media_version to %d\n",
name, ppos, linux_media_version);
#endif
memcpy(STp->application_sig, id_string, 5);
STp->linux_media_version = linux_media_version;
STp->update_frame_cntr = -1;
}
if (update_frame_cntr > STp->update_frame_cntr) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Frame %d sets update_frame_counter to %d\n",
name, ppos, update_frame_cntr);
#endif
if (STp->header_cache == NULL) {
if ((STp->header_cache = vmalloc(sizeof(os_header_t))) == NULL) {
printk(KERN_ERR "%s:E: Failed to allocate header cache\n", name);
return 0;
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Allocated memory for header cache\n", name);
#endif
}
osst_copy_from_buffer(STp->buffer, (unsigned char *)STp->header_cache);
header = STp->header_cache; /* further accesses from cached (full) copy */
STp->wrt_pass_cntr = ntohs(header->partition[0].wrt_pass_cntr);
STp->first_data_ppos = ntohl(header->partition[0].first_frame_ppos);
STp->eod_frame_ppos = ntohl(header->partition[0].eod_frame_ppos);
STp->eod_frame_lfa = ntohl(header->ext_track_tb.dat_ext_trk_ey.last_hlb);
STp->filemark_cnt = ntohl(aux->filemark_cnt);
STp->first_mark_ppos = ntohl(aux->next_mark_ppos);
STp->last_mark_ppos = ntohl(aux->last_mark_ppos);
STp->last_mark_lbn = ntohl(aux->last_mark_lbn);
STp->update_frame_cntr = update_frame_cntr;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Detected write pass %d, update frame counter %d, filemark counter %d\n",
name, STp->wrt_pass_cntr, STp->update_frame_cntr, STp->filemark_cnt);
printk(OSST_DEB_MSG "%s:D: first data frame on tape = %d, last = %d, eod frame = %d\n", name,
STp->first_data_ppos,
ntohl(header->partition[0].last_frame_ppos),
ntohl(header->partition[0].eod_frame_ppos));
printk(OSST_DEB_MSG "%s:D: first mark on tape = %d, last = %d, eod frame = %d\n",
name, STp->first_mark_ppos, STp->last_mark_ppos, STp->eod_frame_ppos);
#endif
if (header->minor_rev < 4 && STp->linux_media_version == 4) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Moving filemark list to ADR 1.4 location\n", name);
#endif
memcpy((void *)header->dat_fm_tab.fm_tab_ent,
(void *)header->old_filemark_list, sizeof(header->dat_fm_tab.fm_tab_ent));
memset((void *)header->old_filemark_list, 0, sizeof(header->old_filemark_list));
}
if (header->minor_rev == 4 &&
(header->ext_trk_tb_off != htons(17192) ||
header->partition[0].partition_num != OS_DATA_PARTITION ||
header->partition[0].par_desc_ver != OS_PARTITION_VERSION ||
header->partition[0].last_frame_ppos != htonl(STp->capacity) ||
header->cfg_col_width != htonl(20) ||
header->dat_col_width != htonl(1500) ||
header->qfa_col_width != htonl(0) ||
header->ext_track_tb.nr_stream_part != 1 ||
header->ext_track_tb.et_ent_sz != 32 ||
header->ext_track_tb.dat_ext_trk_ey.et_part_num != OS_DATA_PARTITION ||
header->ext_track_tb.dat_ext_trk_ey.fmt != 1 ||
header->ext_track_tb.dat_ext_trk_ey.fm_tab_off != htons(17736) ||
header->ext_track_tb.dat_ext_trk_ey.last_hlb_hi != 0 ||
header->ext_track_tb.dat_ext_trk_ey.last_pp != htonl(STp->eod_frame_ppos) ||
header->dat_fm_tab.fm_part_num != OS_DATA_PARTITION ||
header->dat_fm_tab.fm_tab_ent_sz != 4 ||
header->dat_fm_tab.fm_tab_ent_cnt !=
htons(STp->filemark_cnt<OS_FM_TAB_MAX?STp->filemark_cnt:OS_FM_TAB_MAX)))
printk(KERN_WARNING "%s:W: Failed consistency check ADR 1.4 format\n", name);
}
return 1;
}
static int osst_analyze_headers(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
int position, ppos;
int first, last;
int valid = 0;
char * name = tape_name(STp);
position = osst_get_frame_position(STp, aSRpnt);
if (STp->raw) {
STp->header_ok = STp->linux_media = 1;
STp->linux_media_version = 0;
return 1;
}
STp->header_ok = STp->linux_media = STp->linux_media_version = 0;
STp->wrt_pass_cntr = STp->update_frame_cntr = -1;
STp->eod_frame_ppos = STp->first_data_ppos = -1;
STp->first_mark_ppos = STp->last_mark_ppos = STp->last_mark_lbn = -1;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reading header\n", name);
#endif
/* optimization for speed - if we are positioned at ppos 10, read second group first */
/* TODO try the ADR 1.1 locations for the second group if we have no valid one yet... */
first = position==10?0xbae: 5;
last = position==10?0xbb3:10;
for (ppos = first; ppos < last; ppos++)
if (__osst_analyze_headers(STp, aSRpnt, ppos))
valid = 1;
first = position==10? 5:0xbae;
last = position==10?10:0xbb3;
for (ppos = first; ppos < last; ppos++)
if (__osst_analyze_headers(STp, aSRpnt, ppos))
valid = 1;
if (!valid) {
printk(KERN_ERR "%s:E: Failed to find valid ADRL header, new media?\n", name);
STp->eod_frame_ppos = STp->first_data_ppos = 0;
osst_set_frame_position(STp, aSRpnt, 10, 0);
return 0;
}
if (position <= STp->first_data_ppos) {
position = STp->first_data_ppos;
STp->ps[0].drv_file = STp->ps[0].drv_block = STp->frame_seq_number = STp->logical_blk_num = 0;
}
osst_set_frame_position(STp, aSRpnt, position, 0);
STp->header_ok = 1;
return 1;
}
static int osst_verify_position(struct osst_tape * STp, struct osst_request ** aSRpnt)
{
int frame_position = STp->first_frame_position;
int frame_seq_numbr = STp->frame_seq_number;
int logical_blk_num = STp->logical_blk_num;
int halfway_frame = STp->frame_in_buffer;
int read_pointer = STp->buffer->read_pointer;
int prev_mark_ppos = -1;
int actual_mark_ppos, i, n;
#if DEBUG
char * name = tape_name(STp);
printk(OSST_DEB_MSG "%s:D: Verify that the tape is really the one we think before writing\n", name);
#endif
osst_set_frame_position(STp, aSRpnt, frame_position - 1, 0);
if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in verify_position\n", name);
#endif
return (-EIO);
}
if (STp->linux_media_version >= 4) {
for (i=0; i<STp->filemark_cnt; i++)
if ((n=ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[i])) < frame_position)
prev_mark_ppos = n;
} else
prev_mark_ppos = frame_position - 1; /* usually - we don't really know */
actual_mark_ppos = STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER ?
frame_position - 1 : ntohl(STp->buffer->aux->last_mark_ppos);
if (frame_position != STp->first_frame_position ||
frame_seq_numbr != STp->frame_seq_number + (halfway_frame?0:1) ||
prev_mark_ppos != actual_mark_ppos ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Block mismatch: fppos %d-%d, fseq %d-%d, mark %d-%d\n", name,
STp->first_frame_position, frame_position,
STp->frame_seq_number + (halfway_frame?0:1),
frame_seq_numbr, actual_mark_ppos, prev_mark_ppos);
#endif
return (-EIO);
}
if (halfway_frame) {
/* prepare buffer for append and rewrite on top of original */
osst_set_frame_position(STp, aSRpnt, frame_position - 1, 0);
STp->buffer->buffer_bytes = read_pointer;
STp->ps[STp->partition].rw = ST_WRITING;
STp->dirty = 1;
}
STp->frame_in_buffer = halfway_frame;
STp->frame_seq_number = frame_seq_numbr;
STp->logical_blk_num = logical_blk_num;
return 0;
}
/* Acc. to OnStream, the vers. numbering is the following:
* X.XX for released versions (X=digit),
* XXXY for unreleased versions (Y=letter)
* Ordering 1.05 < 106A < 106B < ... < 106a < ... < 1.06
* This fn makes monoton numbers out of this scheme ...
*/
static unsigned int osst_parse_firmware_rev (const char * str)
{
if (str[1] == '.') {
return (str[0]-'0')*10000
+(str[2]-'0')*1000
+(str[3]-'0')*100;
} else {
return (str[0]-'0')*10000
+(str[1]-'0')*1000
+(str[2]-'0')*100 - 100
+(str[3]-'@');
}
}
/*
* Configure the OnStream SCII tape drive for default operation
*/
static int osst_configure_onstream(struct osst_tape *STp, struct osst_request ** aSRpnt)
{
unsigned char cmd[MAX_COMMAND_SIZE];
char * name = tape_name(STp);
struct osst_request * SRpnt = * aSRpnt;
osst_mode_parameter_header_t * header;
osst_block_size_page_t * bs;
osst_capabilities_page_t * cp;
osst_tape_paramtr_page_t * prm;
int drive_buffer_size;
if (STp->ready != ST_READY) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Not Ready\n", name);
#endif
return (-EIO);
}
if (STp->os_fw_rev < 10600) {
printk(KERN_INFO "%s:I: Old OnStream firmware revision detected (%s),\n", name, STp->device->rev);
printk(KERN_INFO "%s:I: an upgrade to version 1.06 or above is recommended\n", name);
}
/*
* Configure 32.5KB (data+aux) frame size.
* Get the current frame size from the block size mode page
*/
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
cmd[1] = 8;
cmd[2] = BLOCK_SIZE_PAGE;
cmd[4] = BLOCK_SIZE_PAGE_LENGTH + MODE_HEADER_LENGTH;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
if (SRpnt == NULL) {
#if DEBUG
printk(OSST_DEB_MSG "osst :D: Busy\n");
#endif
return (-EBUSY);
}
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
printk (KERN_ERR "%s:E: Can't get tape block size mode page\n", name);
return (-EIO);
}
header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
bs = (osst_block_size_page_t *) ((STp->buffer)->b_data + sizeof(osst_mode_parameter_header_t) + header->bdl);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: 32KB play back: %s\n", name, bs->play32 ? "Yes" : "No");
printk(OSST_DEB_MSG "%s:D: 32.5KB play back: %s\n", name, bs->play32_5 ? "Yes" : "No");
printk(OSST_DEB_MSG "%s:D: 32KB record: %s\n", name, bs->record32 ? "Yes" : "No");
printk(OSST_DEB_MSG "%s:D: 32.5KB record: %s\n", name, bs->record32_5 ? "Yes" : "No");
#endif
/*
* Configure default auto columns mode, 32.5KB transfer mode
*/
bs->one = 1;
bs->play32 = 0;
bs->play32_5 = 1;
bs->record32 = 0;
bs->record32_5 = 1;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SELECT;
cmd[1] = 0x10;
cmd[4] = BLOCK_SIZE_PAGE_LENGTH + MODE_HEADER_LENGTH;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
printk (KERN_ERR "%s:E: Couldn't set tape block size mode page\n", name);
return (-EIO);
}
#if DEBUG
printk(KERN_INFO "%s:D: Drive Block Size changed to 32.5K\n", name);
/*
* In debug mode, we want to see as many errors as possible
* to test the error recovery mechanism.
*/
osst_set_retries(STp, aSRpnt, 0);
SRpnt = * aSRpnt;
#endif
/*
* Set vendor name to 'LIN4' for "Linux support version 4".
*/
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SELECT;
cmd[1] = 0x10;
cmd[4] = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH;
header->mode_data_length = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH - 1;
header->medium_type = 0; /* Medium Type - ignoring */
header->dsp = 0; /* Reserved */
header->bdl = 0; /* Block Descriptor Length */
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = VENDOR_IDENT_PAGE | (1 << 7);
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 6;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 'L';
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = 'I';
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 4] = 'N';
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 5] = '4';
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 6] = 0;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 7] = 0;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
printk (KERN_ERR "%s:E: Couldn't set vendor name to %s\n", name,
(char *) ((STp->buffer)->b_data + MODE_HEADER_LENGTH + 2));
return (-EIO);
}
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
cmd[1] = 8;
cmd[2] = CAPABILITIES_PAGE;
cmd[4] = CAPABILITIES_PAGE_LENGTH + MODE_HEADER_LENGTH;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
printk (KERN_ERR "%s:E: Can't get capabilities page\n", name);
return (-EIO);
}
header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
cp = (osst_capabilities_page_t *) ((STp->buffer)->b_data +
sizeof(osst_mode_parameter_header_t) + header->bdl);
drive_buffer_size = ntohs(cp->buffer_size) / 2;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
cmd[1] = 8;
cmd[2] = TAPE_PARAMTR_PAGE;
cmd[4] = TAPE_PARAMTR_PAGE_LENGTH + MODE_HEADER_LENGTH;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
printk (KERN_ERR "%s:E: Can't get tape parameter page\n", name);
return (-EIO);
}
header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
prm = (osst_tape_paramtr_page_t *) ((STp->buffer)->b_data +
sizeof(osst_mode_parameter_header_t) + header->bdl);
STp->density = prm->density;
STp->capacity = ntohs(prm->segtrk) * ntohs(prm->trks);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Density %d, tape length: %dMB, drive buffer size: %dKB\n",
name, STp->density, STp->capacity / 32, drive_buffer_size);
#endif
return 0;
}
/* Step over EOF if it has been inadvertently crossed (ioctl not used because
it messes up the block number). */
static int cross_eof(struct osst_tape *STp, struct osst_request ** aSRpnt, int forward)
{
int result;
char * name = tape_name(STp);
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Stepping over filemark %s.\n",
name, forward ? "forward" : "backward");
#endif
if (forward) {
/* assumes that the filemark is already read by the drive, so this is low cost */
result = osst_space_over_filemarks_forward_slow(STp, aSRpnt, MTFSF, 1);
}
else
/* assumes this is only called if we just read the filemark! */
result = osst_seek_logical_blk(STp, aSRpnt, STp->logical_blk_num - 1);
if (result < 0)
printk(KERN_WARNING "%s:W: Stepping over filemark %s failed.\n",
name, forward ? "forward" : "backward");
return result;
}
/* Get the tape position. */
static int osst_get_frame_position(struct osst_tape *STp, struct osst_request ** aSRpnt)
{
unsigned char scmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
int result = 0;
char * name = tape_name(STp);
/* KG: We want to be able to use it for checking Write Buffer availability
* and thus don't want to risk to overwrite anything. Exchange buffers ... */
char mybuf[24];
char * olddata = STp->buffer->b_data;
int oldsize = STp->buffer->buffer_size;
if (STp->ready != ST_READY) return (-EIO);
memset (scmd, 0, MAX_COMMAND_SIZE);
scmd[0] = READ_POSITION;
STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
SRpnt = osst_do_scsi(*aSRpnt, STp, scmd, 20, DMA_FROM_DEVICE,
STp->timeout, MAX_RETRIES, 1);
if (!SRpnt) {
STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;
return (-EBUSY);
}
*aSRpnt = SRpnt;
if (STp->buffer->syscall_result)
result = ((SRpnt->sense[2] & 0x0f) == 3) ? -EIO : -EINVAL; /* 3: Write Error */
if (result == -EINVAL)
printk(KERN_ERR "%s:E: Can't read tape position.\n", name);
else {
if (result == -EIO) { /* re-read position - this needs to preserve media errors */
unsigned char mysense[16];
memcpy (mysense, SRpnt->sense, 16);
memset (scmd, 0, MAX_COMMAND_SIZE);
scmd[0] = READ_POSITION;
STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
SRpnt = osst_do_scsi(SRpnt, STp, scmd, 20, DMA_FROM_DEVICE,
STp->timeout, MAX_RETRIES, 1);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reread position, reason=[%02x:%02x:%02x], result=[%s%02x:%02x:%02x]\n",
name, mysense[2], mysense[12], mysense[13], STp->buffer->syscall_result?"":"ok:",
SRpnt->sense[2],SRpnt->sense[12],SRpnt->sense[13]);
#endif
if (!STp->buffer->syscall_result)
memcpy (SRpnt->sense, mysense, 16);
else
printk(KERN_WARNING "%s:W: Double error in get position\n", name);
}
STp->first_frame_position = ((STp->buffer)->b_data[4] << 24)
+ ((STp->buffer)->b_data[5] << 16)
+ ((STp->buffer)->b_data[6] << 8)
+ (STp->buffer)->b_data[7];
STp->last_frame_position = ((STp->buffer)->b_data[ 8] << 24)
+ ((STp->buffer)->b_data[ 9] << 16)
+ ((STp->buffer)->b_data[10] << 8)
+ (STp->buffer)->b_data[11];
STp->cur_frames = (STp->buffer)->b_data[15];
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: Drive Positions: host %d, tape %d%s, buffer %d\n", name,
STp->first_frame_position, STp->last_frame_position,
((STp->buffer)->b_data[0]&0x80)?" (BOP)":
((STp->buffer)->b_data[0]&0x40)?" (EOP)":"",
STp->cur_frames);
}
#endif
if (STp->cur_frames == 0 && STp->first_frame_position != STp->last_frame_position) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Correcting read position %d, %d, %d\n", name,
STp->first_frame_position, STp->last_frame_position, STp->cur_frames);
#endif
STp->first_frame_position = STp->last_frame_position;
}
}
STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;
return (result == 0 ? STp->first_frame_position : result);
}
/* Set the tape block */
static int osst_set_frame_position(struct osst_tape *STp, struct osst_request ** aSRpnt, int ppos, int skip)
{
unsigned char scmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
struct st_partstat * STps;
int result = 0;
int pp = (ppos == 3000 && !skip)? 0 : ppos;
char * name = tape_name(STp);
if (STp->ready != ST_READY) return (-EIO);
STps = &(STp->ps[STp->partition]);
if (ppos < 0 || ppos > STp->capacity) {
printk(KERN_WARNING "%s:W: Reposition request %d out of range\n", name, ppos);
pp = ppos = ppos < 0 ? 0 : (STp->capacity - 1);
result = (-EINVAL);
}
do {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Setting ppos to %d.\n", name, pp);
#endif
memset (scmd, 0, MAX_COMMAND_SIZE);
scmd[0] = SEEK_10;
scmd[1] = 1;
scmd[3] = (pp >> 24);
scmd[4] = (pp >> 16);
scmd[5] = (pp >> 8);
scmd[6] = pp;
if (skip)
scmd[9] = 0x80;
SRpnt = osst_do_scsi(*aSRpnt, STp, scmd, 0, DMA_NONE, STp->long_timeout,
MAX_RETRIES, 1);
if (!SRpnt)
return (-EBUSY);
*aSRpnt = SRpnt;
if ((STp->buffer)->syscall_result != 0) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: SEEK command from %d to %d failed.\n",
name, STp->first_frame_position, pp);
#endif
result = (-EIO);
}
if (pp != ppos)
osst_wait_ready(STp, aSRpnt, 5 * 60, OSST_WAIT_POSITION_COMPLETE);
} while ((pp != ppos) && (pp = ppos));
STp->first_frame_position = STp->last_frame_position = ppos;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->rw = ST_IDLE;
STp->frame_in_buffer = 0;
return result;
}
static int osst_write_trailer(struct osst_tape *STp, struct osst_request ** aSRpnt, int leave_at_EOT)
{
struct st_partstat * STps = &(STp->ps[STp->partition]);
int result = 0;
if (STp->write_type != OS_WRITE_NEW_MARK) {
/* true unless the user wrote the filemark for us */
result = osst_flush_drive_buffer(STp, aSRpnt);
if (result < 0) goto out;
result = osst_write_filemark(STp, aSRpnt);
if (result < 0) goto out;
if (STps->drv_file >= 0)
STps->drv_file++ ;
STps->drv_block = 0;
}
result = osst_write_eod(STp, aSRpnt);
osst_write_header(STp, aSRpnt, leave_at_EOT);
STps->eof = ST_FM;
out:
return result;
}
/* osst versions of st functions - augmented and stripped to suit OnStream only */
/* Flush the write buffer (never need to write if variable blocksize). */
static int osst_flush_write_buffer(struct osst_tape *STp, struct osst_request ** aSRpnt)
{
int offset, transfer, blks = 0;
int result = 0;
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt = *aSRpnt;
struct st_partstat * STps;
char * name = tape_name(STp);
if ((STp->buffer)->writing) {
if (SRpnt == (STp->buffer)->last_SRpnt)
#if DEBUG
{ printk(OSST_DEB_MSG
"%s:D: aSRpnt points to osst_request that write_behind_check will release -- cleared\n", name);
#endif
*aSRpnt = SRpnt = NULL;
#if DEBUG
} else if (SRpnt)
printk(OSST_DEB_MSG
"%s:D: aSRpnt does not point to osst_request that write_behind_check will release -- strange\n", name);
#endif
osst_write_behind_check(STp);
if ((STp->buffer)->syscall_result) {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Async write error (flush) %x.\n",
name, (STp->buffer)->midlevel_result);
#endif
if ((STp->buffer)->midlevel_result == INT_MAX)
return (-ENOSPC);
return (-EIO);
}
}
result = 0;
if (STp->dirty == 1) {
STp->write_count++;
STps = &(STp->ps[STp->partition]);
STps->rw = ST_WRITING;
offset = STp->buffer->buffer_bytes;
blks = (offset + STp->block_size - 1) / STp->block_size;
transfer = OS_FRAME_SIZE;
if (offset < OS_DATA_SIZE)
osst_zero_buffer_tail(STp->buffer);
if (STp->poll)
if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, -50, 120))
result = osst_recover_wait_frame(STp, aSRpnt, 1);
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = 1;
cmd[4] = 1;
switch (STp->write_type) {
case OS_WRITE_DATA:
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Writing %d blocks to frame %d, lblks %d-%d\n",
name, blks, STp->frame_seq_number,
STp->logical_blk_num - blks, STp->logical_blk_num - 1);
#endif
osst_init_aux(STp, OS_FRAME_TYPE_DATA, STp->frame_seq_number++,
STp->logical_blk_num - blks, STp->block_size, blks);
break;
case OS_WRITE_EOD:
osst_init_aux(STp, OS_FRAME_TYPE_EOD, STp->frame_seq_number++,
STp->logical_blk_num, 0, 0);
break;
case OS_WRITE_NEW_MARK:
osst_init_aux(STp, OS_FRAME_TYPE_MARKER, STp->frame_seq_number++,
STp->logical_blk_num++, 0, blks=1);
break;
case OS_WRITE_HEADER:
osst_init_aux(STp, OS_FRAME_TYPE_HEADER, 0, 0, 0, blks=0);
break;
default: /* probably FILLER */
osst_init_aux(STp, OS_FRAME_TYPE_FILL, 0, 0, 0, 0);
}
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Flushing %d bytes, Transferring %d bytes in %d lblocks.\n",
name, offset, transfer, blks);
#endif
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, transfer, DMA_TO_DEVICE,
STp->timeout, MAX_RETRIES, 1);
*aSRpnt = SRpnt;
if (!SRpnt)
return (-EBUSY);
if ((STp->buffer)->syscall_result != 0) {
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: write sense [0]=0x%02x [2]=%02x [12]=%02x [13]=%02x\n",
name, SRpnt->sense[0], SRpnt->sense[2],
SRpnt->sense[12], SRpnt->sense[13]);
#endif
if ((SRpnt->sense[0] & 0x70) == 0x70 &&
(SRpnt->sense[2] & 0x40) && /* FIXME - SC-30 drive doesn't assert EOM bit */
(SRpnt->sense[2] & 0x0f) == NO_SENSE) {
STp->dirty = 0;
(STp->buffer)->buffer_bytes = 0;
result = (-ENOSPC);
}
else {
if (osst_write_error_recovery(STp, aSRpnt, 1)) {
printk(KERN_ERR "%s:E: Error on flush write.\n", name);
result = (-EIO);
}
}
STps->drv_block = (-1); /* FIXME - even if write recovery succeeds? */
}
else {
STp->first_frame_position++;
STp->dirty = 0;
(STp->buffer)->buffer_bytes = 0;
}
}
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Exit flush write buffer with code %d\n", name, result);
#endif
return result;
}
/* Flush the tape buffer. The tape will be positioned correctly unless
seek_next is true. */
static int osst_flush_buffer(struct osst_tape * STp, struct osst_request ** aSRpnt, int seek_next)
{
struct st_partstat * STps;
int backspace = 0, result = 0;
#if DEBUG
char * name = tape_name(STp);
#endif
/*
* If there was a bus reset, block further access
* to this device.
*/
if( STp->pos_unknown)
return (-EIO);
if (STp->ready != ST_READY)
return 0;
STps = &(STp->ps[STp->partition]);
if (STps->rw == ST_WRITING || STp->dirty) { /* Writing */
STp->write_type = OS_WRITE_DATA;
return osst_flush_write_buffer(STp, aSRpnt);
}
if (STp->block_size == 0)
return 0;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reached flush (read) buffer\n", name);
#endif
if (!STp->can_bsr) {
backspace = ((STp->buffer)->buffer_bytes + (STp->buffer)->read_pointer) / STp->block_size -
((STp->buffer)->read_pointer + STp->block_size - 1 ) / STp->block_size ;
(STp->buffer)->buffer_bytes = 0;
(STp->buffer)->read_pointer = 0;
STp->frame_in_buffer = 0; /* FIXME is this relevant w. OSST? */
}
if (!seek_next) {
if (STps->eof == ST_FM_HIT) {
result = cross_eof(STp, aSRpnt, 0); /* Back over the EOF hit */
if (!result)
STps->eof = ST_NOEOF;
else {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
}
}
if (!result && backspace > 0) /* TODO -- design and run a test case for this */
result = osst_seek_logical_blk(STp, aSRpnt, STp->logical_blk_num - backspace);
}
else if (STps->eof == ST_FM_HIT) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_NOEOF;
}
return result;
}
static int osst_write_frame(struct osst_tape * STp, struct osst_request ** aSRpnt, int synchronous)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt;
int blks;
#if DEBUG
char * name = tape_name(STp);
#endif
if ((!STp-> raw) && (STp->first_frame_position == 0xbae)) { /* _must_ preserve buffer! */
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Reaching config partition.\n", name);
#endif
if (osst_flush_drive_buffer(STp, aSRpnt) < 0) {
return (-EIO);
}
/* error recovery may have bumped us past the header partition */
if (osst_get_frame_position(STp, aSRpnt) < 0xbb8) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Skipping over config partition.\n", name);
#endif
osst_position_tape_and_confirm(STp, aSRpnt, 0xbb8);
}
}
if (STp->poll)
if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, -48, 120))
if (osst_recover_wait_frame(STp, aSRpnt, 1))
return (-EIO);
// osst_build_stats(STp, &SRpnt);
STp->ps[STp->partition].rw = ST_WRITING;
STp->write_type = OS_WRITE_DATA;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = 1;
cmd[4] = 1; /* one frame at a time... */
blks = STp->buffer->buffer_bytes / STp->block_size;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Writing %d blocks to frame %d, lblks %d-%d\n", name, blks,
STp->frame_seq_number, STp->logical_blk_num - blks, STp->logical_blk_num - 1);
#endif
osst_init_aux(STp, OS_FRAME_TYPE_DATA, STp->frame_seq_number++,
STp->logical_blk_num - blks, STp->block_size, blks);
#if DEBUG
if (!synchronous)
STp->write_pending = 1;
#endif
SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE, STp->timeout,
MAX_RETRIES, synchronous);
if (!SRpnt)
return (-EBUSY);
*aSRpnt = SRpnt;
if (synchronous) {
if (STp->buffer->syscall_result != 0) {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Error on write:\n", name);
#endif
if ((SRpnt->sense[0] & 0x70) == 0x70 &&
(SRpnt->sense[2] & 0x40)) {
if ((SRpnt->sense[2] & 0x0f) == VOLUME_OVERFLOW)
return (-ENOSPC);
}
else {
if (osst_write_error_recovery(STp, aSRpnt, 1))
return (-EIO);
}
}
else
STp->first_frame_position++;
}
STp->write_count++;
return 0;
}
/* Lock or unlock the drive door. Don't use when struct osst_request allocated. */
static int do_door_lock(struct osst_tape * STp, int do_lock)
{
int retval, cmd;
cmd = do_lock ? SCSI_IOCTL_DOORLOCK : SCSI_IOCTL_DOORUNLOCK;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: %socking drive door.\n", tape_name(STp), do_lock ? "L" : "Unl");
#endif
retval = scsi_ioctl(STp->device, cmd, NULL);
if (!retval) {
STp->door_locked = do_lock ? ST_LOCKED_EXPLICIT : ST_UNLOCKED;
}
else {
STp->door_locked = ST_LOCK_FAILS;
}
return retval;
}
/* Set the internal state after reset */
static void reset_state(struct osst_tape *STp)
{
int i;
struct st_partstat *STps;
STp->pos_unknown = 0;
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = -1;
STps->drv_file = -1;
}
}
/* Entry points to osst */
/* Write command */
static ssize_t osst_write(struct file * filp, const char __user * buf, size_t count, loff_t *ppos)
{
ssize_t total, retval = 0;
ssize_t i, do_count, blks, transfer;
int write_threshold;
int doing_write = 0;
const char __user * b_point;
struct osst_request * SRpnt = NULL;
struct st_modedef * STm;
struct st_partstat * STps;
struct osst_tape * STp = filp->private_data;
char * name = tape_name(STp);
if (mutex_lock_interruptible(&STp->lock))
return (-ERESTARTSYS);
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
if( !scsi_block_when_processing_errors(STp->device) ) {
retval = (-ENXIO);
goto out;
}
if (STp->ready != ST_READY) {
if (STp->ready == ST_NO_TAPE)
retval = (-ENOMEDIUM);
else
retval = (-EIO);
goto out;
}
STm = &(STp->modes[STp->current_mode]);
if (!STm->defined) {
retval = (-ENXIO);
goto out;
}
if (count == 0)
goto out;
/*
* If there was a bus reset, block further access
* to this device.
*/
if (STp->pos_unknown) {
retval = (-EIO);
goto out;
}
#if DEBUG
if (!STp->in_use) {
printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
retval = (-EIO);
goto out;
}
#endif
if (STp->write_prot) {
retval = (-EACCES);
goto out;
}
/* Write must be integral number of blocks */
if (STp->block_size != 0 && (count % STp->block_size) != 0) {
printk(KERN_ERR "%s:E: Write (%Zd bytes) not multiple of tape block size (%d%c).\n",
name, count, STp->block_size<1024?
STp->block_size:STp->block_size/1024, STp->block_size<1024?'b':'k');
retval = (-EINVAL);
goto out;
}
if (STp->first_frame_position >= STp->capacity - OSST_EOM_RESERVE) {
printk(KERN_ERR "%s:E: Write truncated at EOM early warning (frame %d).\n",
name, STp->first_frame_position);
retval = (-ENOSPC);
goto out;
}
if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED && !do_door_lock(STp, 1))
STp->door_locked = ST_LOCKED_AUTO;
STps = &(STp->ps[STp->partition]);
if (STps->rw == ST_READING) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Switching from read to write at file %d, block %d\n", name,
STps->drv_file, STps->drv_block);
#endif
retval = osst_flush_buffer(STp, &SRpnt, 0);
if (retval)
goto out;
STps->rw = ST_IDLE;
}
if (STps->rw != ST_WRITING) {
/* Are we totally rewriting this tape? */
if (!STp->header_ok ||
(STp->first_frame_position == STp->first_data_ppos && STps->drv_block < 0) ||
(STps->drv_file == 0 && STps->drv_block == 0)) {
STp->wrt_pass_cntr++;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Allocating next write pass counter: %d\n",
name, STp->wrt_pass_cntr);
#endif
osst_reset_header(STp, &SRpnt);
STps->drv_file = STps->drv_block = 0;
}
/* Do we know where we'll be writing on the tape? */
else {
if ((STp->fast_open && osst_verify_position(STp, &SRpnt)) ||
STps->drv_file < 0 || STps->drv_block < 0) {
if (STp->first_frame_position == STp->eod_frame_ppos) { /* at EOD */
STps->drv_file = STp->filemark_cnt;
STps->drv_block = 0;
}
else {
/* We have no idea where the tape is positioned - give up */
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: Cannot write at indeterminate position.\n", name);
#endif
retval = (-EIO);
goto out;
}
}
if ((STps->drv_file + STps->drv_block) > 0 && STps->drv_file < STp->filemark_cnt) {
STp->filemark_cnt = STps->drv_file;
STp->last_mark_ppos =
ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[STp->filemark_cnt-1]);
printk(KERN_WARNING
"%s:W: Overwriting file %d with old write pass counter %d\n",
name, STps->drv_file, STp->wrt_pass_cntr);
printk(KERN_WARNING
"%s:W: may lead to stale data being accepted on reading back!\n",
name);
#if DEBUG
printk(OSST_DEB_MSG
"%s:D: resetting filemark count to %d and last mark ppos,lbn to %d,%d\n",
name, STp->filemark_cnt, STp->last_mark_ppos, STp->last_mark_lbn);
#endif
}
}
STp->fast_open = 0;
}
if (!STp->header_ok) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Write cannot proceed without valid headers\n", name);
#endif
retval = (-EIO);
goto out;
}
if ((STp->buffer)->writing) {
if (SRpnt) printk(KERN_ERR "%s:A: Not supposed to have SRpnt at line %d\n", name, __LINE__);
osst_write_behind_check(STp);
if ((STp->buffer)->syscall_result) {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Async write error (write) %x.\n", name,
(STp->buffer)->midlevel_result);
#endif
if ((STp->buffer)->midlevel_result == INT_MAX)
STps->eof = ST_EOM_OK;
else
STps->eof = ST_EOM_ERROR;
}
}
if (STps->eof == ST_EOM_OK) {
retval = (-ENOSPC);
goto out;
}
else if (STps->eof == ST_EOM_ERROR) {
retval = (-EIO);
goto out;
}
/* Check the buffer readability in cases where copy_user might catch
the problems after some tape movement. */
if ((copy_from_user(&i, buf, 1) != 0 ||
copy_from_user(&i, buf + count - 1, 1) != 0)) {
retval = (-EFAULT);
goto out;
}
if (!STm->do_buffer_writes) {
write_threshold = 1;
}
else
write_threshold = (STp->buffer)->buffer_blocks * STp->block_size;
if (!STm->do_async_writes)
write_threshold--;
total = count;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Writing %d bytes to file %d block %d lblk %d fseq %d fppos %d\n",
name, (int) count, STps->drv_file, STps->drv_block,
STp->logical_blk_num, STp->frame_seq_number, STp->first_frame_position);
#endif
b_point = buf;
while ((STp->buffer)->buffer_bytes + count > write_threshold)
{
doing_write = 1;
do_count = (STp->buffer)->buffer_blocks * STp->block_size -
(STp->buffer)->buffer_bytes;
if (do_count > count)
do_count = count;
i = append_to_buffer(b_point, STp->buffer, do_count);
if (i) {
retval = i;
goto out;
}
blks = do_count / STp->block_size;
STp->logical_blk_num += blks; /* logical_blk_num is incremented as data is moved from user */
i = osst_write_frame(STp, &SRpnt, 1);
if (i == (-ENOSPC)) {
transfer = STp->buffer->writing; /* FIXME -- check this logic */
if (transfer <= do_count) {
*ppos += do_count - transfer;
count -= do_count - transfer;
if (STps->drv_block >= 0) {
STps->drv_block += (do_count - transfer) / STp->block_size;
}
STps->eof = ST_EOM_OK;
retval = (-ENOSPC); /* EOM within current request */
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: EOM with %d bytes unwritten.\n",
name, (int) transfer);
#endif
}
else {
STps->eof = ST_EOM_ERROR;
STps->drv_block = (-1); /* Too cautious? */
retval = (-EIO); /* EOM for old data */
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: EOM with lost data.\n", name);
#endif
}
}
else
retval = i;
if (retval < 0) {
if (SRpnt != NULL) {
osst_release_request(SRpnt);
SRpnt = NULL;
}
STp->buffer->buffer_bytes = 0;
STp->dirty = 0;
if (count < total)
retval = total - count;
goto out;
}
*ppos += do_count;
b_point += do_count;
count -= do_count;
if (STps->drv_block >= 0) {
STps->drv_block += blks;
}
STp->buffer->buffer_bytes = 0;
STp->dirty = 0;
} /* end while write threshold exceeded */
if (count != 0) {
STp->dirty = 1;
i = append_to_buffer(b_point, STp->buffer, count);
if (i) {
retval = i;
goto out;
}
blks = count / STp->block_size;
STp->logical_blk_num += blks;
if (STps->drv_block >= 0) {
STps->drv_block += blks;
}
*ppos += count;
count = 0;
}
if (doing_write && (STp->buffer)->syscall_result != 0) {
retval = (STp->buffer)->syscall_result;
goto out;
}
if (STm->do_async_writes && ((STp->buffer)->buffer_bytes >= STp->write_threshold)) {
/* Schedule an asynchronous write */
(STp->buffer)->writing = ((STp->buffer)->buffer_bytes /
STp->block_size) * STp->block_size;
STp->dirty = !((STp->buffer)->writing ==
(STp->buffer)->buffer_bytes);
i = osst_write_frame(STp, &SRpnt, 0);
if (i < 0) {
retval = (-EIO);
goto out;
}
SRpnt = NULL; /* Prevent releasing this request! */
}
STps->at_sm &= (total == 0);
if (total > 0)
STps->eof = ST_NOEOF;
retval = total;
out:
if (SRpnt != NULL) osst_release_request(SRpnt);
mutex_unlock(&STp->lock);
return retval;
}
/* Read command */
static ssize_t osst_read(struct file * filp, char __user * buf, size_t count, loff_t *ppos)
{
ssize_t total, retval = 0;
ssize_t i, transfer;
int special;
struct st_modedef * STm;
struct st_partstat * STps;
struct osst_request * SRpnt = NULL;
struct osst_tape * STp = filp->private_data;
char * name = tape_name(STp);
if (mutex_lock_interruptible(&STp->lock))
return (-ERESTARTSYS);
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
if( !scsi_block_when_processing_errors(STp->device) ) {
retval = (-ENXIO);
goto out;
}
if (STp->ready != ST_READY) {
if (STp->ready == ST_NO_TAPE)
retval = (-ENOMEDIUM);
else
retval = (-EIO);
goto out;
}
STm = &(STp->modes[STp->current_mode]);
if (!STm->defined) {
retval = (-ENXIO);
goto out;
}
#if DEBUG
if (!STp->in_use) {
printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
retval = (-EIO);
goto out;
}
#endif
/* Must have initialized medium */
if (!STp->header_ok) {
retval = (-EIO);
goto out;
}
if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED && !do_door_lock(STp, 1))
STp->door_locked = ST_LOCKED_AUTO;
STps = &(STp->ps[STp->partition]);
if (STps->rw == ST_WRITING) {
retval = osst_flush_buffer(STp, &SRpnt, 0);
if (retval)
goto out;
STps->rw = ST_IDLE;
/* FIXME -- this may leave the tape without EOD and up2date headers */
}
if ((count % STp->block_size) != 0) {
printk(KERN_WARNING
"%s:W: Read (%Zd bytes) not multiple of tape block size (%d%c).\n", name, count,
STp->block_size<1024?STp->block_size:STp->block_size/1024, STp->block_size<1024?'b':'k');
}
#if DEBUG
if (debugging && STps->eof != ST_NOEOF)
printk(OSST_DEB_MSG "%s:D: EOF/EOM flag up (%d). Bytes %d\n", name,
STps->eof, (STp->buffer)->buffer_bytes);
#endif
if ((STp->buffer)->buffer_bytes == 0 &&
STps->eof >= ST_EOD_1) {
if (STps->eof < ST_EOD) {
STps->eof += 1;
retval = 0;
goto out;
}
retval = (-EIO); /* EOM or Blank Check */
goto out;
}
/* Check the buffer writability before any tape movement. Don't alter
buffer data. */
if (copy_from_user(&i, buf, 1) != 0 ||
copy_to_user (buf, &i, 1) != 0 ||
copy_from_user(&i, buf + count - 1, 1) != 0 ||
copy_to_user (buf + count - 1, &i, 1) != 0) {
retval = (-EFAULT);
goto out;
}
/* Loop until enough data in buffer or a special condition found */
for (total = 0, special = 0; total < count - STp->block_size + 1 && !special; ) {
/* Get new data if the buffer is empty */
if ((STp->buffer)->buffer_bytes == 0) {
if (STps->eof == ST_FM_HIT)
break;
special = osst_get_logical_frame(STp, &SRpnt, STp->frame_seq_number, 0);
if (special < 0) { /* No need to continue read */
STp->frame_in_buffer = 0;
retval = special;
goto out;
}
}
/* Move the data from driver buffer to user buffer */
if ((STp->buffer)->buffer_bytes > 0) {
#if DEBUG
if (debugging && STps->eof != ST_NOEOF)
printk(OSST_DEB_MSG "%s:D: EOF up (%d). Left %d, needed %d.\n", name,
STps->eof, (STp->buffer)->buffer_bytes, (int) (count - total));
#endif
/* force multiple of block size, note block_size may have been adjusted */
transfer = (((STp->buffer)->buffer_bytes < count - total ?
(STp->buffer)->buffer_bytes : count - total)/
STp->block_size) * STp->block_size;
if (transfer == 0) {
printk(KERN_WARNING
"%s:W: Nothing can be transferred, requested %Zd, tape block size (%d%c).\n",
name, count, STp->block_size < 1024?
STp->block_size:STp->block_size/1024,
STp->block_size<1024?'b':'k');
break;
}
i = from_buffer(STp->buffer, buf, transfer);
if (i) {
retval = i;
goto out;
}
STp->logical_blk_num += transfer / STp->block_size;
STps->drv_block += transfer / STp->block_size;
*ppos += transfer;
buf += transfer;
total += transfer;
}
if ((STp->buffer)->buffer_bytes == 0) {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Finished with frame %d\n",
name, STp->frame_seq_number);
#endif
STp->frame_in_buffer = 0;
STp->frame_seq_number++; /* frame to look for next time */
}
} /* for (total = 0, special = 0; total < count && !special; ) */
/* Change the eof state if no data from tape or buffer */
if (total == 0) {
if (STps->eof == ST_FM_HIT) {
STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD_2:ST_FM;
STps->drv_block = 0;
if (STps->drv_file >= 0)
STps->drv_file++;
}
else if (STps->eof == ST_EOD_1) {
STps->eof = ST_EOD_2;
if (STps->drv_block > 0 && STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
}
else if (STps->eof == ST_EOD_2)
STps->eof = ST_EOD;
}
else if (STps->eof == ST_FM)
STps->eof = ST_NOEOF;
retval = total;
out:
if (SRpnt != NULL) osst_release_request(SRpnt);
mutex_unlock(&STp->lock);
return retval;
}
/* Set the driver options */
static void osst_log_options(struct osst_tape *STp, struct st_modedef *STm, char *name)
{
printk(KERN_INFO
"%s:I: Mode %d options: buffer writes: %d, async writes: %d, read ahead: %d\n",
name, STp->current_mode, STm->do_buffer_writes, STm->do_async_writes,
STm->do_read_ahead);
printk(KERN_INFO
"%s:I: can bsr: %d, two FMs: %d, fast mteom: %d, auto lock: %d,\n",
name, STp->can_bsr, STp->two_fm, STp->fast_mteom, STp->do_auto_lock);
printk(KERN_INFO
"%s:I: defs for wr: %d, no block limits: %d, partitions: %d, s2 log: %d\n",
name, STm->defaults_for_writes, STp->omit_blklims, STp->can_partitions,
STp->scsi2_logical);
printk(KERN_INFO
"%s:I: sysv: %d\n", name, STm->sysv);
#if DEBUG
printk(KERN_INFO
"%s:D: debugging: %d\n",
name, debugging);
#endif
}
static int osst_set_options(struct osst_tape *STp, long options)
{
int value;
long code;
struct st_modedef * STm;
char * name = tape_name(STp);
STm = &(STp->modes[STp->current_mode]);
if (!STm->defined) {
memcpy(STm, &(STp->modes[0]), sizeof(*STm));
modes_defined = 1;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Initialized mode %d definition from mode 0\n",
name, STp->current_mode);
#endif
}
code = options & MT_ST_OPTIONS;
if (code == MT_ST_BOOLEANS) {
STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
STm->do_async_writes = (options & MT_ST_ASYNC_WRITES) != 0;
STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
STm->do_read_ahead = (options & MT_ST_READ_AHEAD) != 0;
STp->two_fm = (options & MT_ST_TWO_FM) != 0;
STp->fast_mteom = (options & MT_ST_FAST_MTEOM) != 0;
STp->do_auto_lock = (options & MT_ST_AUTO_LOCK) != 0;
STp->can_bsr = (options & MT_ST_CAN_BSR) != 0;
STp->omit_blklims = (options & MT_ST_NO_BLKLIMS) != 0;
if ((STp->device)->scsi_level >= SCSI_2)
STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
STp->scsi2_logical = (options & MT_ST_SCSI2LOGICAL) != 0;
STm->sysv = (options & MT_ST_SYSV) != 0;
#if DEBUG
debugging = (options & MT_ST_DEBUGGING) != 0;
#endif
osst_log_options(STp, STm, name);
}
else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
value = (code == MT_ST_SETBOOLEANS);
if ((options & MT_ST_BUFFER_WRITES) != 0)
STm->do_buffer_writes = value;
if ((options & MT_ST_ASYNC_WRITES) != 0)
STm->do_async_writes = value;
if ((options & MT_ST_DEF_WRITES) != 0)
STm->defaults_for_writes = value;
if ((options & MT_ST_READ_AHEAD) != 0)
STm->do_read_ahead = value;
if ((options & MT_ST_TWO_FM) != 0)
STp->two_fm = value;
if ((options & MT_ST_FAST_MTEOM) != 0)
STp->fast_mteom = value;
if ((options & MT_ST_AUTO_LOCK) != 0)
STp->do_auto_lock = value;
if ((options & MT_ST_CAN_BSR) != 0)
STp->can_bsr = value;
if ((options & MT_ST_NO_BLKLIMS) != 0)
STp->omit_blklims = value;
if ((STp->device)->scsi_level >= SCSI_2 &&
(options & MT_ST_CAN_PARTITIONS) != 0)
STp->can_partitions = value;
if ((options & MT_ST_SCSI2LOGICAL) != 0)
STp->scsi2_logical = value;
if ((options & MT_ST_SYSV) != 0)
STm->sysv = value;
#if DEBUG
if ((options & MT_ST_DEBUGGING) != 0)
debugging = value;
#endif
osst_log_options(STp, STm, name);
}
else if (code == MT_ST_WRITE_THRESHOLD) {
value = (options & ~MT_ST_OPTIONS) * ST_KILOBYTE;
if (value < 1 || value > osst_buffer_size) {
printk(KERN_WARNING "%s:W: Write threshold %d too small or too large.\n",
name, value);
return (-EIO);
}
STp->write_threshold = value;
printk(KERN_INFO "%s:I: Write threshold set to %d bytes.\n",
name, value);
}
else if (code == MT_ST_DEF_BLKSIZE) {
value = (options & ~MT_ST_OPTIONS);
if (value == ~MT_ST_OPTIONS) {
STm->default_blksize = (-1);
printk(KERN_INFO "%s:I: Default block size disabled.\n", name);
}
else {
if (value < 512 || value > OS_DATA_SIZE || OS_DATA_SIZE % value) {
printk(KERN_WARNING "%s:W: Default block size cannot be set to %d.\n",
name, value);
return (-EINVAL);
}
STm->default_blksize = value;
printk(KERN_INFO "%s:I: Default block size set to %d bytes.\n",
name, STm->default_blksize);
}
}
else if (code == MT_ST_TIMEOUTS) {
value = (options & ~MT_ST_OPTIONS);
if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
printk(KERN_INFO "%s:I: Long timeout set to %d seconds.\n", name,
(value & ~MT_ST_SET_LONG_TIMEOUT));
}
else {
STp->timeout = value * HZ;
printk(KERN_INFO "%s:I: Normal timeout set to %d seconds.\n", name, value);
}
}
else if (code == MT_ST_DEF_OPTIONS) {
code = (options & ~MT_ST_CLEAR_DEFAULT);
value = (options & MT_ST_CLEAR_DEFAULT);
if (code == MT_ST_DEF_DENSITY) {
if (value == MT_ST_CLEAR_DEFAULT) {
STm->default_density = (-1);
printk(KERN_INFO "%s:I: Density default disabled.\n", name);
}
else {
STm->default_density = value & 0xff;
printk(KERN_INFO "%s:I: Density default set to %x\n",
name, STm->default_density);
}
}
else if (code == MT_ST_DEF_DRVBUFFER) {
if (value == MT_ST_CLEAR_DEFAULT) {
STp->default_drvbuffer = 0xff;
printk(KERN_INFO "%s:I: Drive buffer default disabled.\n", name);
}
else {
STp->default_drvbuffer = value & 7;
printk(KERN_INFO "%s:I: Drive buffer default set to %x\n",
name, STp->default_drvbuffer);
}
}
else if (code == MT_ST_DEF_COMPRESSION) {
if (value == MT_ST_CLEAR_DEFAULT) {
STm->default_compression = ST_DONT_TOUCH;
printk(KERN_INFO "%s:I: Compression default disabled.\n", name);
}
else {
STm->default_compression = (value & 1 ? ST_YES : ST_NO);
printk(KERN_INFO "%s:I: Compression default set to %x\n",
name, (value & 1));
}
}
}
else
return (-EIO);
return 0;
}
/* Internal ioctl function */
static int osst_int_ioctl(struct osst_tape * STp, struct osst_request ** aSRpnt,
unsigned int cmd_in, unsigned long arg)
{
int timeout;
long ltmp;
int i, ioctl_result;
int chg_eof = 1;
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt = * aSRpnt;
struct st_partstat * STps;
int fileno, blkno, at_sm, frame_seq_numbr, logical_blk_num;
int datalen = 0, direction = DMA_NONE;
char * name = tape_name(STp);
if (STp->ready != ST_READY && cmd_in != MTLOAD) {
if (STp->ready == ST_NO_TAPE)
return (-ENOMEDIUM);
else
return (-EIO);
}
timeout = STp->long_timeout;
STps = &(STp->ps[STp->partition]);
fileno = STps->drv_file;
blkno = STps->drv_block;
at_sm = STps->at_sm;
frame_seq_numbr = STp->frame_seq_number;
logical_blk_num = STp->logical_blk_num;
memset(cmd, 0, MAX_COMMAND_SIZE);
switch (cmd_in) {
case MTFSFM:
chg_eof = 0; /* Changed from the FSF after this */
case MTFSF:
if (STp->raw)
return (-EIO);
if (STp->linux_media)
ioctl_result = osst_space_over_filemarks_forward_fast(STp, &SRpnt, cmd_in, arg);
else
ioctl_result = osst_space_over_filemarks_forward_slow(STp, &SRpnt, cmd_in, arg);
if (fileno >= 0)
fileno += arg;
blkno = 0;
at_sm &= (arg == 0);
goto os_bypass;
case MTBSF:
chg_eof = 0; /* Changed from the FSF after this */
case MTBSFM:
if (STp->raw)
return (-EIO);
ioctl_result = osst_space_over_filemarks_backward(STp, &SRpnt, cmd_in, arg);
if (fileno >= 0)
fileno -= arg;
blkno = (-1); /* We can't know the block number */
at_sm &= (arg == 0);
goto os_bypass;
case MTFSR:
case MTBSR:
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Skipping %lu blocks %s from logical block %d\n",
name, arg, cmd_in==MTFSR?"forward":"backward", logical_blk_num);
#endif
if (cmd_in == MTFSR) {
logical_blk_num += arg;
if (blkno >= 0) blkno += arg;
}
else {
logical_blk_num -= arg;
if (blkno >= 0) blkno -= arg;
}
ioctl_result = osst_seek_logical_blk(STp, &SRpnt, logical_blk_num);
fileno = STps->drv_file;
blkno = STps->drv_block;
at_sm &= (arg == 0);
goto os_bypass;
case MTFSS:
cmd[0] = SPACE;
cmd[1] = 0x04; /* Space Setmarks */ /* FIXME -- OS can't do this? */
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Spacing tape forward %d setmarks.\n", name,
cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
#endif
if (arg != 0) {
blkno = fileno = (-1);
at_sm = 1;
}
break;
case MTBSS:
cmd[0] = SPACE;
cmd[1] = 0x04; /* Space Setmarks */ /* FIXME -- OS can't do this? */
ltmp = (-arg);
cmd[2] = (ltmp >> 16);
cmd[3] = (ltmp >> 8);
cmd[4] = ltmp;
#if DEBUG
if (debugging) {
if (cmd[2] & 0x80)
ltmp = 0xff000000;
ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
printk(OSST_DEB_MSG "%s:D: Spacing tape backward %ld setmarks.\n",
name, (-ltmp));
}
#endif
if (arg != 0) {
blkno = fileno = (-1);
at_sm = 1;
}
break;
case MTWEOF:
if ((STps->rw == ST_WRITING || STp->dirty) && !STp->pos_unknown) {
STp->write_type = OS_WRITE_DATA;
ioctl_result = osst_flush_write_buffer(STp, &SRpnt);
} else
ioctl_result = 0;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Writing %ld filemark(s).\n", name, arg);
#endif
for (i=0; i<arg; i++)
ioctl_result |= osst_write_filemark(STp, &SRpnt);
if (fileno >= 0) fileno += arg;
if (blkno >= 0) blkno = 0;
goto os_bypass;
case MTWSM:
if (STp->write_prot)
return (-EACCES);
if (!STp->raw)
return 0;
cmd[0] = WRITE_FILEMARKS; /* FIXME -- need OS version */
if (cmd_in == MTWSM)
cmd[1] = 2;
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
timeout = STp->timeout;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Writing %d setmark(s).\n", name,
cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
#endif
if (fileno >= 0)
fileno += arg;
blkno = 0;
at_sm = (cmd_in == MTWSM);
break;
case MTOFFL:
case MTLOAD:
case MTUNLOAD:
case MTRETEN:
cmd[0] = START_STOP;
cmd[1] = 1; /* Don't wait for completion */
if (cmd_in == MTLOAD) {
if (STp->ready == ST_NO_TAPE)
cmd[4] = 4; /* open tray */
else
cmd[4] = 1; /* load */
}
if (cmd_in == MTRETEN)
cmd[4] = 3; /* retension then mount */
if (cmd_in == MTOFFL)
cmd[4] = 4; /* rewind then eject */
timeout = STp->timeout;
#if DEBUG
if (debugging) {
switch (cmd_in) {
case MTUNLOAD:
printk(OSST_DEB_MSG "%s:D: Unloading tape.\n", name);
break;
case MTLOAD:
printk(OSST_DEB_MSG "%s:D: Loading tape.\n", name);
break;
case MTRETEN:
printk(OSST_DEB_MSG "%s:D: Retensioning tape.\n", name);
break;
case MTOFFL:
printk(OSST_DEB_MSG "%s:D: Ejecting tape.\n", name);
break;
}
}
#endif
fileno = blkno = at_sm = frame_seq_numbr = logical_blk_num = 0 ;
break;
case MTNOP:
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: No-op on tape.\n", name);
#endif
return 0; /* Should do something ? */
break;
case MTEOM:
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Spacing to end of recorded medium.\n", name);
#endif
if ((osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos) < 0) ||
(osst_get_logical_frame(STp, &SRpnt, -1, 0) < 0)) {
ioctl_result = -EIO;
goto os_bypass;
}
if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_EOD) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: No EOD frame found where expected.\n", name);
#endif
ioctl_result = -EIO;
goto os_bypass;
}
ioctl_result = osst_set_frame_position(STp, &SRpnt, STp->eod_frame_ppos, 0);
fileno = STp->filemark_cnt;
blkno = at_sm = 0;
goto os_bypass;
case MTERASE:
if (STp->write_prot)
return (-EACCES);
ioctl_result = osst_reset_header(STp, &SRpnt);
i = osst_write_eod(STp, &SRpnt);
if (i < ioctl_result) ioctl_result = i;
i = osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos);
if (i < ioctl_result) ioctl_result = i;
fileno = blkno = at_sm = 0 ;
goto os_bypass;
case MTREW:
cmd[0] = REZERO_UNIT; /* rewind */
cmd[1] = 1;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Rewinding tape, Immed=%d.\n", name, cmd[1]);
#endif
fileno = blkno = at_sm = frame_seq_numbr = logical_blk_num = 0 ;
break;
case MTSETBLK: /* Set block length */
if ((STps->drv_block == 0 ) &&
!STp->dirty &&
((STp->buffer)->buffer_bytes == 0) &&
((arg & MT_ST_BLKSIZE_MASK) >= 512 ) &&
((arg & MT_ST_BLKSIZE_MASK) <= OS_DATA_SIZE) &&
!(OS_DATA_SIZE % (arg & MT_ST_BLKSIZE_MASK)) ) {
/*
* Only allowed to change the block size if you opened the
* device at the beginning of a file before writing anything.
* Note, that when reading, changing block_size is futile,
* as the size used when writing overrides it.
*/
STp->block_size = (arg & MT_ST_BLKSIZE_MASK);
printk(KERN_INFO "%s:I: Block size set to %d bytes.\n",
name, STp->block_size);
return 0;
}
case MTSETDENSITY: /* Set tape density */
case MTSETDRVBUFFER: /* Set drive buffering */
case SET_DENS_AND_BLK: /* Set density and block size */
chg_eof = 0;
if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
return (-EIO); /* Not allowed if data in buffer */
if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
(arg & MT_ST_BLKSIZE_MASK) != 0 &&
(arg & MT_ST_BLKSIZE_MASK) != STp->block_size ) {
printk(KERN_WARNING "%s:W: Illegal to set block size to %d%s.\n",
name, (int)(arg & MT_ST_BLKSIZE_MASK),
(OS_DATA_SIZE % (arg & MT_ST_BLKSIZE_MASK))?"":" now");
return (-EINVAL);
}
return 0; /* FIXME silently ignore if block size didn't change */
default:
return (-ENOSYS);
}
SRpnt = osst_do_scsi(SRpnt, STp, cmd, datalen, direction, timeout, MAX_RETRIES, 1);
ioctl_result = (STp->buffer)->syscall_result;
if (!SRpnt) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Couldn't exec scsi cmd for IOCTL\n", name);
#endif
return ioctl_result;
}
if (!ioctl_result) { /* SCSI command successful */
STp->frame_seq_number = frame_seq_numbr;
STp->logical_blk_num = logical_blk_num;
}
os_bypass:
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: IOCTL (%d) Result=%d\n", name, cmd_in, ioctl_result);
#endif
if (!ioctl_result) { /* success */
if (cmd_in == MTFSFM) {
fileno--;
blkno--;
}
if (cmd_in == MTBSFM) {
fileno++;
blkno++;
}
STps->drv_block = blkno;
STps->drv_file = fileno;
STps->at_sm = at_sm;
if (cmd_in == MTEOM)
STps->eof = ST_EOD;
else if ((cmd_in == MTFSFM || cmd_in == MTBSF) && STps->eof == ST_FM_HIT) {
ioctl_result = osst_seek_logical_blk(STp, &SRpnt, STp->logical_blk_num-1);
STps->drv_block++;
STp->logical_blk_num++;
STp->frame_seq_number++;
STp->frame_in_buffer = 0;
STp->buffer->read_pointer = 0;
}
else if (cmd_in == MTFSF)
STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_FM;
else if (chg_eof)
STps->eof = ST_NOEOF;
if (cmd_in == MTOFFL || cmd_in == MTUNLOAD)
STp->rew_at_close = 0;
else if (cmd_in == MTLOAD) {
for (i=0; i < ST_NBR_PARTITIONS; i++) {
STp->ps[i].rw = ST_IDLE;
STp->ps[i].last_block_valid = 0;/* FIXME - where else is this field maintained? */
}
STp->partition = 0;
}
if (cmd_in == MTREW) {
ioctl_result = osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos);
if (ioctl_result > 0)
ioctl_result = 0;
}
} else if (cmd_in == MTBSF || cmd_in == MTBSFM ) {
if (osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos) < 0)
STps->drv_file = STps->drv_block = -1;
else
STps->drv_file = STps->drv_block = 0;
STps->eof = ST_NOEOF;
} else if (cmd_in == MTFSF || cmd_in == MTFSFM) {
if (osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos) < 0)
STps->drv_file = STps->drv_block = -1;
else {
STps->drv_file = STp->filemark_cnt;
STps->drv_block = 0;
}
STps->eof = ST_EOD;
} else if (cmd_in == MTBSR || cmd_in == MTFSR || cmd_in == MTWEOF || cmd_in == MTEOM) {
STps->drv_file = STps->drv_block = (-1);
STps->eof = ST_NOEOF;
STp->header_ok = 0;
} else if (cmd_in == MTERASE) {
STp->header_ok = 0;
} else if (SRpnt) { /* SCSI command was not completely successful. */
if (SRpnt->sense[2] & 0x40) {
STps->eof = ST_EOM_OK;
STps->drv_block = 0;
}
if (chg_eof)
STps->eof = ST_NOEOF;
if ((SRpnt->sense[2] & 0x0f) == BLANK_CHECK)
STps->eof = ST_EOD;
if (cmd_in == MTLOAD && osst_wait_for_medium(STp, &SRpnt, 60))
ioctl_result = osst_wait_ready(STp, &SRpnt, 5 * 60, OSST_WAIT_POSITION_COMPLETE);
}
*aSRpnt = SRpnt;
return ioctl_result;
}
/* Open the device */
static int __os_scsi_tape_open(struct inode * inode, struct file * filp)
{
unsigned short flags;
int i, b_size, new_session = 0, retval = 0;
unsigned char cmd[MAX_COMMAND_SIZE];
struct osst_request * SRpnt = NULL;
struct osst_tape * STp;
struct st_modedef * STm;
struct st_partstat * STps;
char * name;
int dev = TAPE_NR(inode);
int mode = TAPE_MODE(inode);
/*
* We really want to do nonseekable_open(inode, filp); here, but some
* versions of tar incorrectly call lseek on tapes and bail out if that
* fails. So we disallow pread() and pwrite(), but permit lseeks.
*/
filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
write_lock(&os_scsi_tapes_lock);
if (dev >= osst_max_dev || os_scsi_tapes == NULL ||
(STp = os_scsi_tapes[dev]) == NULL || !STp->device) {
write_unlock(&os_scsi_tapes_lock);
return (-ENXIO);
}
name = tape_name(STp);
if (STp->in_use) {
write_unlock(&os_scsi_tapes_lock);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Device already in use.\n", name);
#endif
return (-EBUSY);
}
if (scsi_device_get(STp->device)) {
write_unlock(&os_scsi_tapes_lock);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Failed scsi_device_get.\n", name);
#endif
return (-ENXIO);
}
filp->private_data = STp;
STp->in_use = 1;
write_unlock(&os_scsi_tapes_lock);
STp->rew_at_close = TAPE_REWIND(inode);
if( !scsi_block_when_processing_errors(STp->device) ) {
return -ENXIO;
}
if (mode != STp->current_mode) {
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Mode change from %d to %d.\n",
name, STp->current_mode, mode);
#endif
new_session = 1;
STp->current_mode = mode;
}
STm = &(STp->modes[STp->current_mode]);
flags = filp->f_flags;
STp->write_prot = ((flags & O_ACCMODE) == O_RDONLY);
STp->raw = TAPE_IS_RAW(inode);
if (STp->raw)
STp->header_ok = 0;
/* Allocate data segments for this device's tape buffer */
if (!enlarge_buffer(STp->buffer, STp->restr_dma)) {
printk(KERN_ERR "%s:E: Unable to allocate memory segments for tape buffer.\n", name);
retval = (-EOVERFLOW);
goto err_out;
}
if (STp->buffer->buffer_size >= OS_FRAME_SIZE) {
for (i = 0, b_size = 0;
(i < STp->buffer->sg_segs) && ((b_size + STp->buffer->sg[i].length) <= OS_DATA_SIZE);
b_size += STp->buffer->sg[i++].length);
STp->buffer->aux = (os_aux_t *) (page_address(sg_page(&STp->buffer->sg[i])) + OS_DATA_SIZE - b_size);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: b_data points to %p in segment 0 at %p\n", name,
STp->buffer->b_data, page_address(STp->buffer->sg[0].page));
printk(OSST_DEB_MSG "%s:D: AUX points to %p in segment %d at %p\n", name,
STp->buffer->aux, i, page_address(STp->buffer->sg[i].page));
#endif
} else {
STp->buffer->aux = NULL; /* this had better never happen! */
printk(KERN_NOTICE "%s:A: Framesize %d too large for buffer.\n", name, OS_FRAME_SIZE);
retval = (-EIO);
goto err_out;
}
STp->buffer->writing = 0;
STp->buffer->syscall_result = 0;
STp->dirty = 0;
for (i=0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE;
}
STp->ready = ST_READY;
#if DEBUG
STp->nbr_waits = STp->nbr_finished = 0;
#endif
memset (cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(NULL, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
if (!SRpnt) {
retval = (STp->buffer)->syscall_result; /* FIXME - valid? */
goto err_out;
}
if ((SRpnt->sense[0] & 0x70) == 0x70 &&
(SRpnt->sense[2] & 0x0f) == NOT_READY &&
SRpnt->sense[12] == 4 ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Unit not ready, cause %x\n", name, SRpnt->sense[13]);
#endif
if (filp->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto err_out;
}
if (SRpnt->sense[13] == 2) { /* initialize command required (LOAD) */
memset (cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = START_STOP;
cmd[1] = 1;
cmd[4] = 1;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
STp->timeout, MAX_RETRIES, 1);
}
osst_wait_ready(STp, &SRpnt, (SRpnt->sense[13]==1?15:3) * 60, 0);
}
if ((SRpnt->sense[0] & 0x70) == 0x70 &&
(SRpnt->sense[2] & 0x0f) == UNIT_ATTENTION) { /* New media? */
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Unit wants attention\n", name);
#endif
STp->header_ok = 0;
for (i=0; i < 10; i++) {
memset (cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
STp->timeout, MAX_RETRIES, 1);
if ((SRpnt->sense[0] & 0x70) != 0x70 ||
(SRpnt->sense[2] & 0x0f) != UNIT_ATTENTION)
break;
}
STp->pos_unknown = 0;
STp->partition = STp->new_partition = 0;
if (STp->can_partitions)
STp->nbr_partitions = 1; /* This guess will be updated later if necessary */
for (i=0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE; /* FIXME - seems to be redundant... */
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = 0;
STps->drv_file = 0 ;
}
new_session = 1;
STp->recover_count = 0;
STp->abort_count = 0;
}
/*
* if we have valid headers from before, and the drive/tape seem untouched,
* open without reconfiguring and re-reading the headers
*/
if (!STp->buffer->syscall_result && STp->header_ok &&
!SRpnt->result && SRpnt->sense[0] == 0) {
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
cmd[1] = 8;
cmd[2] = VENDOR_IDENT_PAGE;
cmd[4] = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
if (STp->buffer->syscall_result ||
STp->buffer->b_data[MODE_HEADER_LENGTH + 2] != 'L' ||
STp->buffer->b_data[MODE_HEADER_LENGTH + 3] != 'I' ||
STp->buffer->b_data[MODE_HEADER_LENGTH + 4] != 'N' ||
STp->buffer->b_data[MODE_HEADER_LENGTH + 5] != '4' ) {
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Signature was changed to %c%c%c%c\n", name,
STp->buffer->b_data[MODE_HEADER_LENGTH + 2],
STp->buffer->b_data[MODE_HEADER_LENGTH + 3],
STp->buffer->b_data[MODE_HEADER_LENGTH + 4],
STp->buffer->b_data[MODE_HEADER_LENGTH + 5]);
#endif
STp->header_ok = 0;
}
i = STp->first_frame_position;
if (STp->header_ok && i == osst_get_frame_position(STp, &SRpnt)) {
if (STp->door_locked == ST_UNLOCKED) {
if (do_door_lock(STp, 1))
printk(KERN_INFO "%s:I: Can't lock drive door\n", name);
else
STp->door_locked = ST_LOCKED_AUTO;
}
if (!STp->frame_in_buffer) {
STp->block_size = (STm->default_blksize > 0) ?
STm->default_blksize : OS_DATA_SIZE;
STp->buffer->buffer_bytes = STp->buffer->read_pointer = 0;
}
STp->buffer->buffer_blocks = OS_DATA_SIZE / STp->block_size;
STp->fast_open = 1;
osst_release_request(SRpnt);
return 0;
}
#if DEBUG
if (i != STp->first_frame_position)
printk(OSST_DEB_MSG "%s:D: Tape position changed from %d to %d\n",
name, i, STp->first_frame_position);
#endif
STp->header_ok = 0;
}
STp->fast_open = 0;
if ((STp->buffer)->syscall_result != 0 && /* in all error conditions except no medium */
(SRpnt->sense[2] != 2 || SRpnt->sense[12] != 0x3A) ) {
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SELECT;
cmd[1] = 0x10;
cmd[4] = 4 + MODE_HEADER_LENGTH;
(STp->buffer)->b_data[0] = cmd[4] - 1;
(STp->buffer)->b_data[1] = 0; /* Medium Type - ignoring */
(STp->buffer)->b_data[2] = 0; /* Reserved */
(STp->buffer)->b_data[3] = 0; /* Block Descriptor Length */
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = 0x3f;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 1;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 2;
(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = 3;
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Applying soft reset\n", name);
#endif
SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
STp->header_ok = 0;
for (i=0; i < 10; i++) {
memset (cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
STp->timeout, MAX_RETRIES, 1);
if ((SRpnt->sense[0] & 0x70) != 0x70 ||
(SRpnt->sense[2] & 0x0f) == NOT_READY)
break;
if ((SRpnt->sense[2] & 0x0f) == UNIT_ATTENTION) {
int j;
STp->pos_unknown = 0;
STp->partition = STp->new_partition = 0;
if (STp->can_partitions)
STp->nbr_partitions = 1; /* This guess will be updated later if necessary */
for (j = 0; j < ST_NBR_PARTITIONS; j++) {
STps = &(STp->ps[j]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = 0;
STps->drv_file = 0 ;
}
new_session = 1;
}
}
}
if (osst_wait_ready(STp, &SRpnt, 15 * 60, 0)) /* FIXME - not allowed with NOBLOCK */
printk(KERN_INFO "%s:I: Device did not become Ready in open\n", name);
if ((STp->buffer)->syscall_result != 0) {
if ((STp->device)->scsi_level >= SCSI_2 &&
(SRpnt->sense[0] & 0x70) == 0x70 &&
(SRpnt->sense[2] & 0x0f) == NOT_READY &&
SRpnt->sense[12] == 0x3a) { /* Check ASC */
STp->ready = ST_NO_TAPE;
} else
STp->ready = ST_NOT_READY;
osst_release_request(SRpnt);
SRpnt = NULL;
STp->density = 0; /* Clear the erroneous "residue" */
STp->write_prot = 0;
STp->block_size = 0;
STp->ps[0].drv_file = STp->ps[0].drv_block = (-1);
STp->partition = STp->new_partition = 0;
STp->door_locked = ST_UNLOCKED;
return 0;
}
osst_configure_onstream(STp, &SRpnt);
STp->block_size = STp->raw ? OS_FRAME_SIZE : (
(STm->default_blksize > 0) ? STm->default_blksize : OS_DATA_SIZE);
STp->buffer->buffer_blocks = STp->raw ? 1 : OS_DATA_SIZE / STp->block_size;
STp->buffer->buffer_bytes =
STp->buffer->read_pointer =
STp->frame_in_buffer = 0;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Block size: %d, frame size: %d, buffer size: %d (%d blocks).\n",
name, STp->block_size, OS_FRAME_SIZE, (STp->buffer)->buffer_size,
(STp->buffer)->buffer_blocks);
#endif
if (STp->drv_write_prot) {
STp->write_prot = 1;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Write protected\n", name);
#endif
if ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR) {
retval = (-EROFS);
goto err_out;
}
}
if (new_session) { /* Change the drive parameters for the new mode */
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: New Session\n", name);
#endif
STp->density_changed = STp->blksize_changed = 0;
STp->compression_changed = 0;
}
/*
* properly position the tape and check the ADR headers
*/
if (STp->door_locked == ST_UNLOCKED) {
if (do_door_lock(STp, 1))
printk(KERN_INFO "%s:I: Can't lock drive door\n", name);
else
STp->door_locked = ST_LOCKED_AUTO;
}
osst_analyze_headers(STp, &SRpnt);
osst_release_request(SRpnt);
SRpnt = NULL;
return 0;
err_out:
if (SRpnt != NULL)
osst_release_request(SRpnt);
normalize_buffer(STp->buffer);
STp->header_ok = 0;
STp->in_use = 0;
scsi_device_put(STp->device);
return retval;
}
/* BKL pushdown: spaghetti avoidance wrapper */
static int os_scsi_tape_open(struct inode * inode, struct file * filp)
{
int ret;
mutex_lock(&osst_int_mutex);
ret = __os_scsi_tape_open(inode, filp);
mutex_unlock(&osst_int_mutex);
return ret;
}
/* Flush the tape buffer before close */
static int os_scsi_tape_flush(struct file * filp, fl_owner_t id)
{
int result = 0, result2;
struct osst_tape * STp = filp->private_data;
struct st_modedef * STm = &(STp->modes[STp->current_mode]);
struct st_partstat * STps = &(STp->ps[STp->partition]);
struct osst_request * SRpnt = NULL;
char * name = tape_name(STp);
if (file_count(filp) > 1)
return 0;
if ((STps->rw == ST_WRITING || STp->dirty) && !STp->pos_unknown) {
STp->write_type = OS_WRITE_DATA;
result = osst_flush_write_buffer(STp, &SRpnt);
if (result != 0 && result != (-ENOSPC))
goto out;
}
if ( STps->rw >= ST_WRITING && !STp->pos_unknown) {
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG "%s:D: File length %ld bytes.\n",
name, (long)(filp->f_pos));
printk(OSST_DEB_MSG "%s:D: Async write waits %d, finished %d.\n",
name, STp->nbr_waits, STp->nbr_finished);
}
#endif
result = osst_write_trailer(STp, &SRpnt, !(STp->rew_at_close));
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG "%s:D: Buffer flushed, %d EOF(s) written\n",
name, 1+STp->two_fm);
#endif
}
else if (!STp->rew_at_close) {
STps = &(STp->ps[STp->partition]);
if (!STm->sysv || STps->rw != ST_READING) {
if (STp->can_bsr)
result = osst_flush_buffer(STp, &SRpnt, 0); /* this is the default path */
else if (STps->eof == ST_FM_HIT) {
result = cross_eof(STp, &SRpnt, 0);
if (result) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_FM;
}
else
STps->eof = ST_NOEOF;
}
}
else if ((STps->eof == ST_NOEOF &&
!(result = cross_eof(STp, &SRpnt, 1))) ||
STps->eof == ST_FM_HIT) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_FM;
}
}
out:
if (STp->rew_at_close) {
result2 = osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos);
STps->drv_file = STps->drv_block = STp->frame_seq_number = STp->logical_blk_num = 0;
if (result == 0 && result2 < 0)
result = result2;
}
if (SRpnt) osst_release_request(SRpnt);
if (STp->abort_count || STp->recover_count) {
printk(KERN_INFO "%s:I:", name);
if (STp->abort_count)
printk(" %d unrecovered errors", STp->abort_count);
if (STp->recover_count)
printk(" %d recovered errors", STp->recover_count);
if (STp->write_count)
printk(" in %d frames written", STp->write_count);
if (STp->read_count)
printk(" in %d frames read", STp->read_count);
printk("\n");
STp->recover_count = 0;
STp->abort_count = 0;
}
STp->write_count = 0;
STp->read_count = 0;
return result;
}
/* Close the device and release it */
static int os_scsi_tape_close(struct inode * inode, struct file * filp)
{
int result = 0;
struct osst_tape * STp = filp->private_data;
if (STp->door_locked == ST_LOCKED_AUTO)
do_door_lock(STp, 0);
if (STp->raw)
STp->header_ok = 0;
normalize_buffer(STp->buffer);
write_lock(&os_scsi_tapes_lock);
STp->in_use = 0;
write_unlock(&os_scsi_tapes_lock);
scsi_device_put(STp->device);
return result;
}
/* The ioctl command */
static long osst_ioctl(struct file * file,
unsigned int cmd_in, unsigned long arg)
{
int i, cmd_nr, cmd_type, blk, retval = 0;
struct st_modedef * STm;
struct st_partstat * STps;
struct osst_request * SRpnt = NULL;
struct osst_tape * STp = file->private_data;
char * name = tape_name(STp);
void __user * p = (void __user *)arg;
mutex_lock(&osst_int_mutex);
if (mutex_lock_interruptible(&STp->lock)) {
mutex_unlock(&osst_int_mutex);
return -ERESTARTSYS;
}
#if DEBUG
if (debugging && !STp->in_use) {
printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
retval = (-EIO);
goto out;
}
#endif
STm = &(STp->modes[STp->current_mode]);
STps = &(STp->ps[STp->partition]);
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
if( !scsi_block_when_processing_errors(STp->device) ) {
retval = (-ENXIO);
goto out;
}
cmd_type = _IOC_TYPE(cmd_in);
cmd_nr = _IOC_NR(cmd_in);
#if DEBUG
printk(OSST_DEB_MSG "%s:D: Ioctl %d,%d in %s mode\n", name,
cmd_type, cmd_nr, STp->raw?"raw":"normal");
#endif
if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
struct mtop mtc;
int auto_weof = 0;
if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
retval = (-EINVAL);
goto out;
}
i = copy_from_user((char *) &mtc, p, sizeof(struct mtop));
if (i) {
retval = (-EFAULT);
goto out;
}
if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
printk(KERN_WARNING "%s:W: MTSETDRVBUFFER only allowed for root.\n", name);
retval = (-EPERM);
goto out;
}
if (!STm->defined && (mtc.mt_op != MTSETDRVBUFFER && (mtc.mt_count & MT_ST_OPTIONS) == 0)) {
retval = (-ENXIO);
goto out;
}
if (!STp->pos_unknown) {
if (STps->eof == ST_FM_HIT) {
if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM|| mtc.mt_op == MTEOM) {
mtc.mt_count -= 1;
if (STps->drv_file >= 0)
STps->drv_file += 1;
}
else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
mtc.mt_count += 1;
if (STps->drv_file >= 0)
STps->drv_file += 1;
}
}
if (mtc.mt_op == MTSEEK) {
/* Old position must be restored if partition will be changed */
i = !STp->can_partitions || (STp->new_partition != STp->partition);
}
else {
i = mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM ||
mtc.mt_op == MTLOCK || mtc.mt_op == MTLOAD ||
mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM ||
mtc.mt_op == MTCOMPRESSION;
}
i = osst_flush_buffer(STp, &SRpnt, i);
if (i < 0) {
retval = i;
goto out;
}
}
else {
/*
* If there was a bus reset, block further access
* to this device. If the user wants to rewind the tape,
* then reset the flag and allow access again.
*/
if(mtc.mt_op != MTREW &&
mtc.mt_op != MTOFFL &&
mtc.mt_op != MTRETEN &&
mtc.mt_op != MTERASE &&
mtc.mt_op != MTSEEK &&
mtc.mt_op != MTEOM) {
retval = (-EIO);
goto out;
}
reset_state(STp);
/* remove this when the midlevel properly clears was_reset */
STp->device->was_reset = 0;
}
if (mtc.mt_op != MTCOMPRESSION && mtc.mt_op != MTLOCK &&
mtc.mt_op != MTNOP && mtc.mt_op != MTSETBLK &&
mtc.mt_op != MTSETDENSITY && mtc.mt_op != MTSETDRVBUFFER &&
mtc.mt_op != MTMKPART && mtc.mt_op != MTSETPART &&
mtc.mt_op != MTWEOF && mtc.mt_op != MTWSM ) {
/*
* The user tells us to move to another position on the tape.
* If we were appending to the tape content, that would leave
* the tape without proper end, in that case write EOD and
* update the header to reflect its position.
*/
#if DEBUG
printk(KERN_WARNING "%s:D: auto_weod %s at ffp=%d,efp=%d,fsn=%d,lbn=%d,fn=%d,bn=%d\n", name,
STps->rw >= ST_WRITING ? "write" : STps->rw == ST_READING ? "read" : "idle",
STp->first_frame_position, STp->eod_frame_ppos, STp->frame_seq_number,
STp->logical_blk_num, STps->drv_file, STps->drv_block );
#endif
if (STps->rw >= ST_WRITING && STp->first_frame_position >= STp->eod_frame_ppos) {
auto_weof = ((STp->write_type != OS_WRITE_NEW_MARK) &&
!(mtc.mt_op == MTREW || mtc.mt_op == MTOFFL));
i = osst_write_trailer(STp, &SRpnt,
!(mtc.mt_op == MTREW || mtc.mt_op == MTOFFL));
#if DEBUG
printk(KERN_WARNING "%s:D: post trailer xeof=%d,ffp=%d,efp=%d,fsn=%d,lbn=%d,fn=%d,bn=%d\n",
name, auto_weof, STp->first_frame_position, STp->eod_frame_ppos,
STp->frame_seq_number, STp->logical_blk_num, STps->drv_file, STps->drv_block );
#endif
if (i < 0) {
retval = i;
goto out;
}
}
STps->rw = ST_IDLE;
}
if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
do_door_lock(STp, 0); /* Ignore result! */
if (mtc.mt_op == MTSETDRVBUFFER &&
(mtc.mt_count & MT_ST_OPTIONS) != 0) {
retval = osst_set_options(STp, mtc.mt_count);
goto out;
}
if (mtc.mt_op == MTSETPART) {
if (mtc.mt_count >= STp->nbr_partitions)
retval = -EINVAL;
else {
STp->new_partition = mtc.mt_count;
retval = 0;
}
goto out;
}
if (mtc.mt_op == MTMKPART) {
if (!STp->can_partitions) {
retval = (-EINVAL);
goto out;
}
if ((i = osst_int_ioctl(STp, &SRpnt, MTREW, 0)) < 0 /*||
(i = partition_tape(inode, mtc.mt_count)) < 0*/) {
retval = i;
goto out;
}
for (i=0; i < ST_NBR_PARTITIONS; i++) {
STp->ps[i].rw = ST_IDLE;
STp->ps[i].at_sm = 0;
STp->ps[i].last_block_valid = 0;
}
STp->partition = STp->new_partition = 0;
STp->nbr_partitions = 1; /* Bad guess ?-) */
STps->drv_block = STps->drv_file = 0;
retval = 0;
goto out;
}
if (mtc.mt_op == MTSEEK) {
if (STp->raw)
i = osst_set_frame_position(STp, &SRpnt, mtc.mt_count, 0);
else
i = osst_seek_sector(STp, &SRpnt, mtc.mt_count);
if (!STp->can_partitions)
STp->ps[0].rw = ST_IDLE;
retval = i;
goto out;
}
if (mtc.mt_op == MTLOCK || mtc.mt_op == MTUNLOCK) {
retval = do_door_lock(STp, (mtc.mt_op == MTLOCK));
goto out;
}
if (auto_weof)
cross_eof(STp, &SRpnt, 0);
if (mtc.mt_op == MTCOMPRESSION)
retval = -EINVAL; /* OnStream drives don't have compression hardware */
else
/* MTBSF MTBSFM MTBSR MTBSS MTEOM MTERASE MTFSF MTFSFB MTFSR MTFSS
* MTLOAD MTOFFL MTRESET MTRETEN MTREW MTUNLOAD MTWEOF MTWSM */
retval = osst_int_ioctl(STp, &SRpnt, mtc.mt_op, mtc.mt_count);
goto out;
}
if (!STm->defined) {
retval = (-ENXIO);
goto out;
}
if ((i = osst_flush_buffer(STp, &SRpnt, 0)) < 0) {
retval = i;
goto out;
}
if (cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET)) {
struct mtget mt_status;
if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
retval = (-EINVAL);
goto out;
}
mt_status.mt_type = MT_ISONSTREAM_SC;
mt_status.mt_erreg = STp->recover_erreg << MT_ST_SOFTERR_SHIFT;
mt_status.mt_dsreg =
((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
((STp->density << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
mt_status.mt_blkno = STps->drv_block;
mt_status.mt_fileno = STps->drv_file;
if (STp->block_size != 0) {
if (STps->rw == ST_WRITING)
mt_status.mt_blkno += (STp->buffer)->buffer_bytes / STp->block_size;
else if (STps->rw == ST_READING)
mt_status.mt_blkno -= ((STp->buffer)->buffer_bytes +
STp->block_size - 1) / STp->block_size;
}
mt_status.mt_gstat = 0;
if (STp->drv_write_prot)
mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
if (mt_status.mt_blkno == 0) {
if (mt_status.mt_fileno == 0)
mt_status.mt_gstat |= GMT_BOT(0xffffffff);
else
mt_status.mt_gstat |= GMT_EOF(0xffffffff);
}
mt_status.mt_resid = STp->partition;
if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
mt_status.mt_gstat |= GMT_EOT(0xffffffff);
else if (STps->eof >= ST_EOM_OK)
mt_status.mt_gstat |= GMT_EOD(0xffffffff);
if (STp->density == 1)
mt_status.mt_gstat |= GMT_D_800(0xffffffff);
else if (STp->density == 2)
mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
else if (STp->density == 3)
mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
if (STp->ready == ST_READY)
mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
if (STp->ready == ST_NO_TAPE)
mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
if (STps->at_sm)
mt_status.mt_gstat |= GMT_SM(0xffffffff);
if (STm->do_async_writes || (STm->do_buffer_writes && STp->block_size != 0) ||
STp->drv_buffer != 0)
mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);
i = copy_to_user(p, &mt_status, sizeof(struct mtget));
if (i) {
retval = (-EFAULT);
goto out;
}
STp->recover_erreg = 0; /* Clear after read */
retval = 0;
goto out;
} /* End of MTIOCGET */
if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
struct mtpos mt_pos;
if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
retval = (-EINVAL);
goto out;
}
if (STp->raw)
blk = osst_get_frame_position(STp, &SRpnt);
else
blk = osst_get_sector(STp, &SRpnt);
if (blk < 0) {
retval = blk;
goto out;
}
mt_pos.mt_blkno = blk;
i = copy_to_user(p, &mt_pos, sizeof(struct mtpos));
if (i)
retval = -EFAULT;
goto out;
}
if (SRpnt) osst_release_request(SRpnt);
mutex_unlock(&STp->lock);
retval = scsi_ioctl(STp->device, cmd_in, p);
mutex_unlock(&osst_int_mutex);
return retval;
out:
if (SRpnt) osst_release_request(SRpnt);
mutex_unlock(&STp->lock);
mutex_unlock(&osst_int_mutex);
return retval;
}
#ifdef CONFIG_COMPAT
static long osst_compat_ioctl(struct file * file, unsigned int cmd_in, unsigned long arg)
{
struct osst_tape *STp = file->private_data;
struct scsi_device *sdev = STp->device;
int ret = -ENOIOCTLCMD;
if (sdev->host->hostt->compat_ioctl) {
ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg);
}
return ret;
}
#endif
/* Memory handling routines */
/* Try to allocate a new tape buffer skeleton. Caller must not hold os_scsi_tapes_lock */
static struct osst_buffer * new_tape_buffer( int from_initialization, int need_dma, int max_sg )
{
int i;
gfp_t priority;
struct osst_buffer *tb;
if (from_initialization)
priority = GFP_ATOMIC;
else
priority = GFP_KERNEL;
i = sizeof(struct osst_buffer) + (osst_max_sg_segs - 1) * sizeof(struct scatterlist);
tb = kzalloc(i, priority);
if (!tb) {
printk(KERN_NOTICE "osst :I: Can't allocate new tape buffer.\n");
return NULL;
}
tb->sg_segs = tb->orig_sg_segs = 0;
tb->use_sg = max_sg;
tb->in_use = 1;
tb->dma = need_dma;
tb->buffer_size = 0;
#if DEBUG
if (debugging)
printk(OSST_DEB_MSG
"osst :D: Allocated tape buffer skeleton (%d bytes, %d segments, dma: %d).\n",
i, max_sg, need_dma);
#endif
return tb;
}
/* Try to allocate a temporary (while a user has the device open) enlarged tape buffer */
static int enlarge_buffer(struct osst_buffer *STbuffer, int need_dma)
{
int segs, nbr, max_segs, b_size, order, got;
gfp_t priority;
if (STbuffer->buffer_size >= OS_FRAME_SIZE)
return 1;
if (STbuffer->sg_segs) {
printk(KERN_WARNING "osst :A: Buffer not previously normalized.\n");
normalize_buffer(STbuffer);
}
/* See how many segments we can use -- need at least two */
nbr = max_segs = STbuffer->use_sg;
if (nbr <= 2)
return 0;
priority = GFP_KERNEL /* | __GFP_NOWARN */;
if (need_dma)
priority |= GFP_DMA;
/* Try to allocate the first segment up to OS_DATA_SIZE and the others
big enough to reach the goal (code assumes no segments in place) */
for (b_size = OS_DATA_SIZE, order = OSST_FIRST_ORDER; b_size >= PAGE_SIZE; order--, b_size /= 2) {
struct page *page = alloc_pages(priority, order);
STbuffer->sg[0].offset = 0;
if (page != NULL) {
sg_set_page(&STbuffer->sg[0], page, b_size, 0);
STbuffer->b_data = page_address(page);
break;
}
}
if (sg_page(&STbuffer->sg[0]) == NULL) {
printk(KERN_NOTICE "osst :I: Can't allocate tape buffer main segment.\n");
return 0;
}
/* Got initial segment of 'bsize,order', continue with same size if possible, except for AUX */
for (segs=STbuffer->sg_segs=1, got=b_size;
segs < max_segs && got < OS_FRAME_SIZE; ) {
struct page *page = alloc_pages(priority, (OS_FRAME_SIZE - got <= PAGE_SIZE) ? 0 : order);
STbuffer->sg[segs].offset = 0;
if (page == NULL) {
printk(KERN_WARNING "osst :W: Failed to enlarge buffer to %d bytes.\n",
OS_FRAME_SIZE);
#if DEBUG
STbuffer->buffer_size = got;
#endif
normalize_buffer(STbuffer);
return 0;
}
sg_set_page(&STbuffer->sg[segs], page, (OS_FRAME_SIZE - got <= PAGE_SIZE / 2) ? (OS_FRAME_SIZE - got) : b_size, 0);
got += STbuffer->sg[segs].length;
STbuffer->buffer_size = got;
STbuffer->sg_segs = ++segs;
}
#if DEBUG
if (debugging) {
printk(OSST_DEB_MSG
"osst :D: Expanded tape buffer (%d bytes, %d->%d segments, dma: %d, at: %p).\n",
got, STbuffer->orig_sg_segs, STbuffer->sg_segs, need_dma, STbuffer->b_data);
printk(OSST_DEB_MSG
"osst :D: segment sizes: first %d at %p, last %d bytes at %p.\n",
STbuffer->sg[0].length, page_address(STbuffer->sg[0].page),
STbuffer->sg[segs-1].length, page_address(STbuffer->sg[segs-1].page));
}
#endif
return 1;
}
/* Release the segments */
static void normalize_buffer(struct osst_buffer *STbuffer)
{
int i, order, b_size;
for (i=0; i < STbuffer->sg_segs; i++) {
for (b_size = PAGE_SIZE, order = 0;
b_size < STbuffer->sg[i].length;
b_size *= 2, order++);
__free_pages(sg_page(&STbuffer->sg[i]), order);
STbuffer->buffer_size -= STbuffer->sg[i].length;
}
#if DEBUG
if (debugging && STbuffer->orig_sg_segs < STbuffer->sg_segs)
printk(OSST_DEB_MSG "osst :D: Buffer at %p normalized to %d bytes (segs %d).\n",
STbuffer->b_data, STbuffer->buffer_size, STbuffer->sg_segs);
#endif
STbuffer->sg_segs = STbuffer->orig_sg_segs = 0;
}
/* Move data from the user buffer to the tape buffer. Returns zero (success) or
negative error code. */
static int append_to_buffer(const char __user *ubp, struct osst_buffer *st_bp, int do_count)
{
int i, cnt, res, offset;
for (i=0, offset=st_bp->buffer_bytes;
i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
offset -= st_bp->sg[i].length;
if (i == st_bp->sg_segs) { /* Should never happen */
printk(KERN_WARNING "osst :A: Append_to_buffer offset overflow.\n");
return (-EIO);
}
for ( ; i < st_bp->sg_segs && do_count > 0; i++) {
cnt = st_bp->sg[i].length - offset < do_count ?
st_bp->sg[i].length - offset : do_count;
res = copy_from_user(page_address(sg_page(&st_bp->sg[i])) + offset, ubp, cnt);
if (res)
return (-EFAULT);
do_count -= cnt;
st_bp->buffer_bytes += cnt;
ubp += cnt;
offset = 0;
}
if (do_count) { /* Should never happen */
printk(KERN_WARNING "osst :A: Append_to_buffer overflow (left %d).\n",
do_count);
return (-EIO);
}
return 0;
}
/* Move data from the tape buffer to the user buffer. Returns zero (success) or
negative error code. */
static int from_buffer(struct osst_buffer *st_bp, char __user *ubp, int do_count)
{
int i, cnt, res, offset;
for (i=0, offset=st_bp->read_pointer;
i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
offset -= st_bp->sg[i].length;
if (i == st_bp->sg_segs) { /* Should never happen */
printk(KERN_WARNING "osst :A: From_buffer offset overflow.\n");
return (-EIO);
}
for ( ; i < st_bp->sg_segs && do_count > 0; i++) {
cnt = st_bp->sg[i].length - offset < do_count ?
st_bp->sg[i].length - offset : do_count;
res = copy_to_user(ubp, page_address(sg_page(&st_bp->sg[i])) + offset, cnt);
if (res)
return (-EFAULT);
do_count -= cnt;
st_bp->buffer_bytes -= cnt;
st_bp->read_pointer += cnt;
ubp += cnt;
offset = 0;
}
if (do_count) { /* Should never happen */
printk(KERN_WARNING "osst :A: From_buffer overflow (left %d).\n", do_count);
return (-EIO);
}
return 0;
}
/* Sets the tail of the buffer after fill point to zero.
Returns zero (success) or negative error code. */
static int osst_zero_buffer_tail(struct osst_buffer *st_bp)
{
int i, offset, do_count, cnt;
for (i = 0, offset = st_bp->buffer_bytes;
i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
offset -= st_bp->sg[i].length;
if (i == st_bp->sg_segs) { /* Should never happen */
printk(KERN_WARNING "osst :A: Zero_buffer offset overflow.\n");
return (-EIO);
}
for (do_count = OS_DATA_SIZE - st_bp->buffer_bytes;
i < st_bp->sg_segs && do_count > 0; i++) {
cnt = st_bp->sg[i].length - offset < do_count ?
st_bp->sg[i].length - offset : do_count ;
memset(page_address(sg_page(&st_bp->sg[i])) + offset, 0, cnt);
do_count -= cnt;
offset = 0;
}
if (do_count) { /* Should never happen */
printk(KERN_WARNING "osst :A: Zero_buffer overflow (left %d).\n", do_count);
return (-EIO);
}
return 0;
}
/* Copy a osst 32K chunk of memory into the buffer.
Returns zero (success) or negative error code. */
static int osst_copy_to_buffer(struct osst_buffer *st_bp, unsigned char *ptr)
{
int i, cnt, do_count = OS_DATA_SIZE;
for (i = 0; i < st_bp->sg_segs && do_count > 0; i++) {
cnt = st_bp->sg[i].length < do_count ?
st_bp->sg[i].length : do_count ;
memcpy(page_address(sg_page(&st_bp->sg[i])), ptr, cnt);
do_count -= cnt;
ptr += cnt;
}
if (do_count || i != st_bp->sg_segs-1) { /* Should never happen */
printk(KERN_WARNING "osst :A: Copy_to_buffer overflow (left %d at sg %d).\n",
do_count, i);
return (-EIO);
}
return 0;
}
/* Copy a osst 32K chunk of memory from the buffer.
Returns zero (success) or negative error code. */
static int osst_copy_from_buffer(struct osst_buffer *st_bp, unsigned char *ptr)
{
int i, cnt, do_count = OS_DATA_SIZE;
for (i = 0; i < st_bp->sg_segs && do_count > 0; i++) {
cnt = st_bp->sg[i].length < do_count ?
st_bp->sg[i].length : do_count ;
memcpy(ptr, page_address(sg_page(&st_bp->sg[i])), cnt);
do_count -= cnt;
ptr += cnt;
}
if (do_count || i != st_bp->sg_segs-1) { /* Should never happen */
printk(KERN_WARNING "osst :A: Copy_from_buffer overflow (left %d at sg %d).\n",
do_count, i);
return (-EIO);
}
return 0;
}
/* Module housekeeping */
static void validate_options (void)
{
if (max_dev > 0)
osst_max_dev = max_dev;
if (write_threshold_kbs > 0)
osst_write_threshold = write_threshold_kbs * ST_KILOBYTE;
if (osst_write_threshold > osst_buffer_size)
osst_write_threshold = osst_buffer_size;
if (max_sg_segs >= OSST_FIRST_SG)
osst_max_sg_segs = max_sg_segs;
#if DEBUG
printk(OSST_DEB_MSG "osst :D: max tapes %d, write threshold %d, max s/g segs %d.\n",
osst_max_dev, osst_write_threshold, osst_max_sg_segs);
#endif
}
#ifndef MODULE
/* Set the boot options. Syntax: osst=xxx,yyy,...
where xxx is write threshold in 1024 byte blocks,
and yyy is number of s/g segments to use. */
static int __init osst_setup (char *str)
{
int i, ints[5];
char *stp;
stp = get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] > 0) {
for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
*parms[i].val = ints[i + 1];
} else {
while (stp != NULL) {
for (i = 0; i < ARRAY_SIZE(parms); i++) {
int len = strlen(parms[i].name);
if (!strncmp(stp, parms[i].name, len) &&
(*(stp + len) == ':' || *(stp + len) == '=')) {
*parms[i].val =
simple_strtoul(stp + len + 1, NULL, 0);
break;
}
}
if (i >= ARRAY_SIZE(parms))
printk(KERN_INFO "osst :I: Illegal parameter in '%s'\n",
stp);
stp = strchr(stp, ',');
if (stp)
stp++;
}
}
return 1;
}
__setup("osst=", osst_setup);
#endif
static const struct file_operations osst_fops = {
.owner = THIS_MODULE,
.read = osst_read,
.write = osst_write,
.unlocked_ioctl = osst_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = osst_compat_ioctl,
#endif
.open = os_scsi_tape_open,
.flush = os_scsi_tape_flush,
.release = os_scsi_tape_close,
.llseek = noop_llseek,
};
static int osst_supports(struct scsi_device * SDp)
{
struct osst_support_data {
char *vendor;
char *model;
char *rev;
char *driver_hint; /* Name of the correct driver, NULL if unknown */
};
static struct osst_support_data support_list[] = {
/* {"XXX", "Yy-", "", NULL}, example */
SIGS_FROM_OSST,
{NULL, }};
struct osst_support_data *rp;
/* We are willing to drive OnStream SC-x0 as well as the
* * IDE, ParPort, FireWire, USB variants, if accessible by
* * emulation layer (ide-scsi, usb-storage, ...) */
for (rp=&(support_list[0]); rp->vendor != NULL; rp++)
if (!strncmp(rp->vendor, SDp->vendor, strlen(rp->vendor)) &&
!strncmp(rp->model, SDp->model, strlen(rp->model)) &&
!strncmp(rp->rev, SDp->rev, strlen(rp->rev)))
return 1;
return 0;
}
/*
* sysfs support for osst driver parameter information
*/
static ssize_t osst_version_show(struct device_driver *ddd, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", osst_version);
}
static DRIVER_ATTR(version, S_IRUGO, osst_version_show, NULL);
static int osst_create_sysfs_files(struct device_driver *sysfs)
{
return driver_create_file(sysfs, &driver_attr_version);
}
static void osst_remove_sysfs_files(struct device_driver *sysfs)
{
driver_remove_file(sysfs, &driver_attr_version);
}
/*
* sysfs support for accessing ADR header information
*/
static ssize_t osst_adr_rev_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "%d.%d\n", STp->header_cache->major_rev, STp->header_cache->minor_rev);
return l;
}
DEVICE_ATTR(ADR_rev, S_IRUGO, osst_adr_rev_show, NULL);
static ssize_t osst_linux_media_version_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "LIN%d\n", STp->linux_media_version);
return l;
}
DEVICE_ATTR(media_version, S_IRUGO, osst_linux_media_version_show, NULL);
static ssize_t osst_capacity_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "%d\n", STp->capacity);
return l;
}
DEVICE_ATTR(capacity, S_IRUGO, osst_capacity_show, NULL);
static ssize_t osst_first_data_ppos_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "%d\n", STp->first_data_ppos);
return l;
}
DEVICE_ATTR(BOT_frame, S_IRUGO, osst_first_data_ppos_show, NULL);
static ssize_t osst_eod_frame_ppos_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "%d\n", STp->eod_frame_ppos);
return l;
}
DEVICE_ATTR(EOD_frame, S_IRUGO, osst_eod_frame_ppos_show, NULL);
static ssize_t osst_filemark_cnt_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct osst_tape * STp = (struct osst_tape *) dev_get_drvdata (dev);
ssize_t l = 0;
if (STp && STp->header_ok && STp->linux_media)
l = snprintf(buf, PAGE_SIZE, "%d\n", STp->filemark_cnt);
return l;
}
DEVICE_ATTR(file_count, S_IRUGO, osst_filemark_cnt_show, NULL);
static struct class *osst_sysfs_class;
static int osst_sysfs_init(void)
{
osst_sysfs_class = class_create(THIS_MODULE, "onstream_tape");
if (IS_ERR(osst_sysfs_class)) {
printk(KERN_ERR "osst :W: Unable to register sysfs class\n");
return PTR_ERR(osst_sysfs_class);
}
return 0;
}
static void osst_sysfs_destroy(dev_t dev)
{
device_destroy(osst_sysfs_class, dev);
}
static int osst_sysfs_add(dev_t dev, struct device *device, struct osst_tape * STp, char * name)
{
struct device *osst_member;
int err;
osst_member = device_create(osst_sysfs_class, device, dev, STp,
"%s", name);
if (IS_ERR(osst_member)) {
printk(KERN_WARNING "osst :W: Unable to add sysfs class member %s\n", name);
return PTR_ERR(osst_member);
}
err = device_create_file(osst_member, &dev_attr_ADR_rev);
if (err)
goto err_out;
err = device_create_file(osst_member, &dev_attr_media_version);
if (err)
goto err_out;
err = device_create_file(osst_member, &dev_attr_capacity);
if (err)
goto err_out;
err = device_create_file(osst_member, &dev_attr_BOT_frame);
if (err)
goto err_out;
err = device_create_file(osst_member, &dev_attr_EOD_frame);
if (err)
goto err_out;
err = device_create_file(osst_member, &dev_attr_file_count);
if (err)
goto err_out;
return 0;
err_out:
osst_sysfs_destroy(dev);
return err;
}
static void osst_sysfs_cleanup(void)
{
class_destroy(osst_sysfs_class);
}
/*
* osst startup / cleanup code
*/
static int osst_probe(struct device *dev)
{
struct scsi_device * SDp = to_scsi_device(dev);
struct osst_tape * tpnt;
struct st_modedef * STm;
struct st_partstat * STps;
struct osst_buffer * buffer;
struct gendisk * drive;
int i, dev_num, err = -ENODEV;
if (SDp->type != TYPE_TAPE || !osst_supports(SDp))
return -ENODEV;
drive = alloc_disk(1);
if (!drive) {
printk(KERN_ERR "osst :E: Out of memory. Device not attached.\n");
return -ENODEV;
}
/* if this is the first attach, build the infrastructure */
write_lock(&os_scsi_tapes_lock);
if (os_scsi_tapes == NULL) {
os_scsi_tapes = kmalloc(osst_max_dev * sizeof(struct osst_tape *), GFP_ATOMIC);
if (os_scsi_tapes == NULL) {
write_unlock(&os_scsi_tapes_lock);
printk(KERN_ERR "osst :E: Unable to allocate array for OnStream SCSI tapes.\n");
goto out_put_disk;
}
for (i=0; i < osst_max_dev; ++i) os_scsi_tapes[i] = NULL;
}
if (osst_nr_dev >= osst_max_dev) {
write_unlock(&os_scsi_tapes_lock);
printk(KERN_ERR "osst :E: Too many tape devices (max. %d).\n", osst_max_dev);
goto out_put_disk;
}
/* find a free minor number */
for (i = 0; i < osst_max_dev && os_scsi_tapes[i]; i++)
;
if(i >= osst_max_dev) panic ("Scsi_devices corrupt (osst)");
dev_num = i;
/* allocate a struct osst_tape for this device */
tpnt = kzalloc(sizeof(struct osst_tape), GFP_ATOMIC);
if (!tpnt) {
write_unlock(&os_scsi_tapes_lock);
printk(KERN_ERR "osst :E: Can't allocate device descriptor, device not attached.\n");
goto out_put_disk;
}
/* allocate a buffer for this device */
i = SDp->host->sg_tablesize;
if (osst_max_sg_segs < i)
i = osst_max_sg_segs;
buffer = new_tape_buffer(1, SDp->host->unchecked_isa_dma, i);
if (buffer == NULL) {
write_unlock(&os_scsi_tapes_lock);
printk(KERN_ERR "osst :E: Unable to allocate a tape buffer, device not attached.\n");
kfree(tpnt);
goto out_put_disk;
}
os_scsi_tapes[dev_num] = tpnt;
tpnt->buffer = buffer;
tpnt->device = SDp;
drive->private_data = &tpnt->driver;
sprintf(drive->disk_name, "osst%d", dev_num);
tpnt->driver = &osst_template;
tpnt->drive = drive;
tpnt->in_use = 0;
tpnt->capacity = 0xfffff;
tpnt->dirty = 0;
tpnt->drv_buffer = 1; /* Try buffering if no mode sense */
tpnt->restr_dma = (SDp->host)->unchecked_isa_dma;
tpnt->density = 0;
tpnt->do_auto_lock = OSST_AUTO_LOCK;
tpnt->can_bsr = OSST_IN_FILE_POS;
tpnt->can_partitions = 0;
tpnt->two_fm = OSST_TWO_FM;
tpnt->fast_mteom = OSST_FAST_MTEOM;
tpnt->scsi2_logical = OSST_SCSI2LOGICAL; /* FIXME */
tpnt->write_threshold = osst_write_threshold;
tpnt->default_drvbuffer = 0xff; /* No forced buffering */
tpnt->partition = 0;
tpnt->new_partition = 0;
tpnt->nbr_partitions = 0;
tpnt->min_block = 512;
tpnt->max_block = OS_DATA_SIZE;
tpnt->timeout = OSST_TIMEOUT;
tpnt->long_timeout = OSST_LONG_TIMEOUT;
/* Recognize OnStream tapes */
/* We don't need to test for OnStream, as this has been done in detect () */
tpnt->os_fw_rev = osst_parse_firmware_rev (SDp->rev);
tpnt->omit_blklims = 1;
tpnt->poll = (strncmp(SDp->model, "DI-", 3) == 0) ||
(strncmp(SDp->model, "FW-", 3) == 0) || OSST_FW_NEED_POLL(tpnt->os_fw_rev,SDp);
tpnt->frame_in_buffer = 0;
tpnt->header_ok = 0;
tpnt->linux_media = 0;
tpnt->header_cache = NULL;
for (i=0; i < ST_NBR_MODES; i++) {
STm = &(tpnt->modes[i]);
STm->defined = 0;
STm->sysv = OSST_SYSV;
STm->defaults_for_writes = 0;
STm->do_async_writes = OSST_ASYNC_WRITES;
STm->do_buffer_writes = OSST_BUFFER_WRITES;
STm->do_read_ahead = OSST_READ_AHEAD;
STm->default_compression = ST_DONT_TOUCH;
STm->default_blksize = 512;
STm->default_density = (-1); /* No forced density */
}
for (i=0; i < ST_NBR_PARTITIONS; i++) {
STps = &(tpnt->ps[i]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = (-1);
STps->drv_file = (-1);
}
tpnt->current_mode = 0;
tpnt->modes[0].defined = 1;
tpnt->modes[2].defined = 1;
tpnt->density_changed = tpnt->compression_changed = tpnt->blksize_changed = 0;
mutex_init(&tpnt->lock);
osst_nr_dev++;
write_unlock(&os_scsi_tapes_lock);
{
char name[8];
/* Rewind entry */
err = osst_sysfs_add(MKDEV(OSST_MAJOR, dev_num), dev, tpnt, tape_name(tpnt));
if (err)
goto out_free_buffer;
/* No-rewind entry */
snprintf(name, 8, "%s%s", "n", tape_name(tpnt));
err = osst_sysfs_add(MKDEV(OSST_MAJOR, dev_num + 128), dev, tpnt, name);
if (err)
goto out_free_sysfs1;
}
sdev_printk(KERN_INFO, SDp,
"osst :I: Attached OnStream %.5s tape as %s\n",
SDp->model, tape_name(tpnt));
return 0;
out_free_sysfs1:
osst_sysfs_destroy(MKDEV(OSST_MAJOR, dev_num));
out_free_buffer:
kfree(buffer);
out_put_disk:
put_disk(drive);
return err;
};
static int osst_remove(struct device *dev)
{
struct scsi_device * SDp = to_scsi_device(dev);
struct osst_tape * tpnt;
int i;
if ((SDp->type != TYPE_TAPE) || (osst_nr_dev <= 0))
return 0;
write_lock(&os_scsi_tapes_lock);
for(i=0; i < osst_max_dev; i++) {
if((tpnt = os_scsi_tapes[i]) && (tpnt->device == SDp)) {
osst_sysfs_destroy(MKDEV(OSST_MAJOR, i));
osst_sysfs_destroy(MKDEV(OSST_MAJOR, i+128));
tpnt->device = NULL;
put_disk(tpnt->drive);
os_scsi_tapes[i] = NULL;
osst_nr_dev--;
write_unlock(&os_scsi_tapes_lock);
vfree(tpnt->header_cache);
if (tpnt->buffer) {
normalize_buffer(tpnt->buffer);
kfree(tpnt->buffer);
}
kfree(tpnt);
return 0;
}
}
write_unlock(&os_scsi_tapes_lock);
return 0;
}
static int __init init_osst(void)
{
int err;
printk(KERN_INFO "osst :I: Tape driver with OnStream support version %s\nosst :I: %s\n", osst_version, cvsid);
validate_options();
err = osst_sysfs_init();
if (err)
return err;
err = register_chrdev(OSST_MAJOR, "osst", &osst_fops);
if (err < 0) {
printk(KERN_ERR "osst :E: Unable to register major %d for OnStream tapes\n", OSST_MAJOR);
goto err_out;
}
err = scsi_register_driver(&osst_template.gendrv);
if (err)
goto err_out_chrdev;
err = osst_create_sysfs_files(&osst_template.gendrv);
if (err)
goto err_out_scsidrv;
return 0;
err_out_scsidrv:
scsi_unregister_driver(&osst_template.gendrv);
err_out_chrdev:
unregister_chrdev(OSST_MAJOR, "osst");
err_out:
osst_sysfs_cleanup();
return err;
}
static void __exit exit_osst (void)
{
int i;
struct osst_tape * STp;
osst_remove_sysfs_files(&osst_template.gendrv);
scsi_unregister_driver(&osst_template.gendrv);
unregister_chrdev(OSST_MAJOR, "osst");
osst_sysfs_cleanup();
if (os_scsi_tapes) {
for (i=0; i < osst_max_dev; ++i) {
if (!(STp = os_scsi_tapes[i])) continue;
/* This is defensive, supposed to happen during detach */
vfree(STp->header_cache);
if (STp->buffer) {
normalize_buffer(STp->buffer);
kfree(STp->buffer);
}
put_disk(STp->drive);
kfree(STp);
}
kfree(os_scsi_tapes);
}
printk(KERN_INFO "osst :I: Unloaded.\n");
}
module_init(init_osst);
module_exit(exit_osst);
| gpl-2.0 |
lssjbrolli/android_kernel_samsung_klimtlte | sound/oss/sb_ess.c | 8109 | 52671 | #undef FKS_LOGGING
#undef FKS_TEST
/*
* tabs should be 4 spaces, in vi(m): set tabstop=4
*
* TODO: consistency speed calculations!!
* cleanup!
* ????: Did I break MIDI support?
*
* History:
*
* Rolf Fokkens (Dec 20 1998): ES188x recording level support on a per
* fokkensr@vertis.nl input basis.
* (Dec 24 1998): Recognition of ES1788, ES1887, ES1888,
* ES1868, ES1869 and ES1878. Could be used for
* specific handling in the future. All except
* ES1887 and ES1888 and ES688 are handled like
* ES1688.
* (Dec 27 1998): RECLEV for all (?) ES1688+ chips. ES188x now
* have the "Dec 20" support + RECLEV
* (Jan 2 1999): Preparation for Full Duplex. This means
* Audio 2 is now used for playback when dma16
* is specified. The next step would be to use
* Audio 1 and Audio 2 at the same time.
* (Jan 9 1999): Put all ESS stuff into sb_ess.[ch], this
* includes both the ESS stuff that has been in
* sb_*[ch] before I touched it and the ESS support
* I added later
* (Jan 23 1999): Full Duplex seems to work. I wrote a small
* test proggy which works OK. Haven't found
* any applications to test it though. So why did
* I bother to create it anyway?? :) Just for
* fun.
* (May 2 1999): I tried to be too smart by "introducing"
* ess_calc_best_speed (). The idea was that two
* dividers could be used to setup a samplerate,
* ess_calc_best_speed () would choose the best.
* This works for playback, but results in
* recording problems for high samplerates. I
* fixed this by removing ess_calc_best_speed ()
* and just doing what the documentation says.
* Andy Sloane (Jun 4 1999): Stole some code from ALSA to fix the playback
* andy@guildsoftware.com speed on ES1869, ES1879, ES1887, and ES1888.
* 1879's were previously ignored by this driver;
* added (untested) support for those.
* Cvetan Ivanov (Oct 27 1999): Fixed ess_dsp_init to call ess_set_dma_hw for
* zezo@inet.bg _ALL_ ESS models, not only ES1887
*
* This files contains ESS chip specifics. It's based on the existing ESS
* handling as it resided in sb_common.c, sb_mixer.c and sb_audio.c. This
* file adds features like:
* - Chip Identification (as shown in /proc/sound)
* - RECLEV support for ES1688 and later
* - 6 bits playback level support chips later than ES1688
* - Recording level support on a per-device basis for ES1887
* - Full-Duplex for ES1887
*
* Full duplex is enabled by specifying dma16. While the normal dma must
* be one of 0, 1 or 3, dma16 can be one of 0, 1, 3 or 5. DMA 5 is a 16 bit
* DMA channel, while the others are 8 bit..
*
* ESS detection isn't full proof (yet). If it fails an additional module
* parameter esstype can be specified to be one of the following:
* -1, 0, 688, 1688, 1868, 1869, 1788, 1887, 1888
* -1 means: mimic 2.0 behaviour,
* 0 means: auto detect.
* others: explicitly specify chip
* -1 is default, cause auto detect still doesn't work.
*/
/*
* About the documentation
*
* I don't know if the chips all are OK, but the documentation is buggy. 'cause
* I don't have all the cips myself, there's a lot I cannot verify. I'll try to
* keep track of my latest insights about his here. If you have additional info,
* please enlighten me (fokkensr@vertis.nl)!
*
* I had the impression that ES1688 also has 6 bit master volume control. The
* documentation about ES1888 (rev C, october '95) claims that ES1888 has
* the following features ES1688 doesn't have:
* - 6 bit master volume
* - Full Duplex
* So ES1688 apparently doesn't have 6 bit master volume control, but the
* ES1688 does have RECLEV control. Makes me wonder: does ES688 have it too?
* Without RECLEV ES688 won't be much fun I guess.
*
* From the ES1888 (rev C, october '95) documentation I got the impression
* that registers 0x68 to 0x6e don't exist which means: no recording volume
* controls. To my surprise the ES888 documentation (1/14/96) claims that
* ES888 does have these record mixer registers, but that ES1888 doesn't have
* 0x69 and 0x6b. So the rest should be there.
*
* I'm trying to get ES1887 Full Duplex. Audio 2 is playback only, while Audio 2
* is both record and playback. I think I should use Audio 2 for all playback.
*
* The documentation is an adventure: it's close but not fully accurate. I
* found out that after a reset some registers are *NOT* reset, though the
* docs say the would be. Interesting ones are 0x7f, 0x7d and 0x7a. They are
* related to the Audio 2 channel. I also was surprised about the consequences
* of writing 0x00 to 0x7f (which should be done by reset): The ES1887 moves
* into ES1888 mode. This means that it claims IRQ 11, which happens to be my
* ISDN adapter. Needless to say it no longer worked. I now understand why
* after rebooting 0x7f already was 0x05, the value of my choice: the BIOS
* did it.
*
* Oh, and this is another trap: in ES1887 docs mixer register 0x70 is
* described as if it's exactly the same as register 0xa1. This is *NOT* true.
* The description of 0x70 in ES1869 docs is accurate however.
* Well, the assumption about ES1869 was wrong: register 0x70 is very much
* like register 0xa1, except that bit 7 is always 1, whatever you want
* it to be.
*
* When using audio 2 mixer register 0x72 seems te be meaningless. Only 0xa2
* has effect.
*
* Software reset not being able to reset all registers is great! Especially
* the fact that register 0x78 isn't reset is great when you wanna change back
* to single dma operation (simplex): audio 2 is still operational, and uses
* the same dma as audio 1: your ess changes into a funny echo machine.
*
* Received the news that ES1688 is detected as a ES1788. Did some thinking:
* the ES1887 detection scheme suggests in step 2 to try if bit 3 of register
* 0x64 can be changed. This is inaccurate, first I inverted the * check: "If
* can be modified, it's a 1688", which lead to a correct detection
* of my ES1887. It resulted however in bad detection of 1688 (reported by mail)
* and 1868 (if no PnP detection first): they result in a 1788 being detected.
* I don't have docs on 1688, but I do have docs on 1868: The documentation is
* probably inaccurate in the fact that I should check bit 2, not bit 3. This
* is what I do now.
*/
/*
* About recognition of ESS chips
*
* The distinction of ES688, ES1688, ES1788, ES1887 and ES1888 is described in
* a (preliminary ??) datasheet on ES1887. Its aim is to identify ES1887, but
* during detection the text claims that "this chip may be ..." when a step
* fails. This scheme is used to distinct between the above chips.
* It appears however that some PnP chips like ES1868 are recognized as ES1788
* by the ES1887 detection scheme. These PnP chips can be detected in another
* way however: ES1868, ES1869 and ES1878 can be recognized (full proof I think)
* by repeatedly reading mixer register 0x40. This is done by ess_identify in
* sb_common.c.
* This results in the following detection steps:
* - distinct between ES688 and ES1688+ (as always done in this driver)
* if ES688 we're ready
* - try to detect ES1868, ES1869 or ES1878
* if successful we're ready
* - try to detect ES1888, ES1887 or ES1788
* if successful we're ready
* - Dunno. Must be 1688. Will do in general
*
* About RECLEV support:
*
* The existing ES1688 support didn't take care of the ES1688+ recording
* levels very well. Whenever a device was selected (recmask) for recording
* its recording level was loud, and it couldn't be changed. The fact that
* internal register 0xb4 could take care of RECLEV, didn't work meaning until
* its value was restored every time the chip was reset; this reset the
* value of 0xb4 too. I guess that's what 4front also had (have?) trouble with.
*
* About ES1887 support:
*
* The ES1887 has separate registers to control the recording levels, for all
* inputs. The ES1887 specific software makes these levels the same as their
* corresponding playback levels, unless recmask says they aren't recorded. In
* the latter case the recording volumes are 0.
* Now recording levels of inputs can be controlled, by changing the playback
* levels. Furthermore several devices can be recorded together (which is not
* possible with the ES1688).
* Besides the separate recording level control for each input, the common
* recording level can also be controlled by RECLEV as described above.
*
* Not only ES1887 have this recording mixer. I know the following from the
* documentation:
* ES688 no
* ES1688 no
* ES1868 no
* ES1869 yes
* ES1878 no
* ES1879 yes
* ES1888 no/yes Contradicting documentation; most recent: yes
* ES1946 yes This is a PCI chip; not handled by this driver
*/
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include "sound_config.h"
#include "sb_mixer.h"
#include "sb.h"
#include "sb_ess.h"
#define ESSTYPE_LIKE20 -1 /* Mimic 2.0 behaviour */
#define ESSTYPE_DETECT 0 /* Mimic 2.0 behaviour */
#define SUBMDL_ES1788 0x10 /* Subtype ES1788 for specific handling */
#define SUBMDL_ES1868 0x11 /* Subtype ES1868 for specific handling */
#define SUBMDL_ES1869 0x12 /* Subtype ES1869 for specific handling */
#define SUBMDL_ES1878 0x13 /* Subtype ES1878 for specific handling */
#define SUBMDL_ES1879 0x16 /* ES1879 was initially forgotten */
#define SUBMDL_ES1887 0x14 /* Subtype ES1887 for specific handling */
#define SUBMDL_ES1888 0x15 /* Subtype ES1888 for specific handling */
#define SB_CAP_ES18XX_RATE 0x100
#define ES1688_CLOCK1 795444 /* 128 - div */
#define ES1688_CLOCK2 397722 /* 256 - div */
#define ES18XX_CLOCK1 793800 /* 128 - div */
#define ES18XX_CLOCK2 768000 /* 256 - div */
#ifdef FKS_LOGGING
static void ess_show_mixerregs (sb_devc *devc);
#endif
static int ess_read (sb_devc * devc, unsigned char reg);
static int ess_write (sb_devc * devc, unsigned char reg, unsigned char data);
static void ess_chgmixer
(sb_devc * devc, unsigned int reg, unsigned int mask, unsigned int val);
/****************************************************************************
* *
* ESS audio *
* *
****************************************************************************/
struct ess_command {short cmd; short data;};
/*
* Commands for initializing Audio 1 for input (record)
*/
static struct ess_command ess_i08m[] = /* input 8 bit mono */
{ {0xb7, 0x51}, {0xb7, 0xd0}, {-1, 0} };
static struct ess_command ess_i16m[] = /* input 16 bit mono */
{ {0xb7, 0x71}, {0xb7, 0xf4}, {-1, 0} };
static struct ess_command ess_i08s[] = /* input 8 bit stereo */
{ {0xb7, 0x51}, {0xb7, 0x98}, {-1, 0} };
static struct ess_command ess_i16s[] = /* input 16 bit stereo */
{ {0xb7, 0x71}, {0xb7, 0xbc}, {-1, 0} };
static struct ess_command *ess_inp_cmds[] =
{ ess_i08m, ess_i16m, ess_i08s, ess_i16s };
/*
* Commands for initializing Audio 1 for output (playback)
*/
static struct ess_command ess_o08m[] = /* output 8 bit mono */
{ {0xb6, 0x80}, {0xb7, 0x51}, {0xb7, 0xd0}, {-1, 0} };
static struct ess_command ess_o16m[] = /* output 16 bit mono */
{ {0xb6, 0x00}, {0xb7, 0x71}, {0xb7, 0xf4}, {-1, 0} };
static struct ess_command ess_o08s[] = /* output 8 bit stereo */
{ {0xb6, 0x80}, {0xb7, 0x51}, {0xb7, 0x98}, {-1, 0} };
static struct ess_command ess_o16s[] = /* output 16 bit stereo */
{ {0xb6, 0x00}, {0xb7, 0x71}, {0xb7, 0xbc}, {-1, 0} };
static struct ess_command *ess_out_cmds[] =
{ ess_o08m, ess_o16m, ess_o08s, ess_o16s };
static void ess_exec_commands
(sb_devc *devc, struct ess_command *cmdtab[])
{
struct ess_command *cmd;
cmd = cmdtab [ ((devc->channels != 1) << 1) + (devc->bits != AFMT_U8) ];
while (cmd->cmd != -1) {
ess_write (devc, cmd->cmd, cmd->data);
cmd++;
}
}
static void ess_change
(sb_devc *devc, unsigned int reg, unsigned int mask, unsigned int val)
{
int value;
value = ess_read (devc, reg);
value = (value & ~mask) | (val & mask);
ess_write (devc, reg, value);
}
static void ess_set_output_parms
(int dev, unsigned long buf, int nr_bytes, int intrflag)
{
sb_devc *devc = audio_devs[dev]->devc;
if (devc->duplex) {
devc->trg_buf_16 = buf;
devc->trg_bytes_16 = nr_bytes;
devc->trg_intrflag_16 = intrflag;
devc->irq_mode_16 = IMODE_OUTPUT;
} else {
devc->trg_buf = buf;
devc->trg_bytes = nr_bytes;
devc->trg_intrflag = intrflag;
devc->irq_mode = IMODE_OUTPUT;
}
}
static void ess_set_input_parms
(int dev, unsigned long buf, int count, int intrflag)
{
sb_devc *devc = audio_devs[dev]->devc;
devc->trg_buf = buf;
devc->trg_bytes = count;
devc->trg_intrflag = intrflag;
devc->irq_mode = IMODE_INPUT;
}
static int ess_calc_div (int clock, int revert, int *speedp, int *diffp)
{
int divider;
int speed, diff;
int retval;
speed = *speedp;
divider = (clock + speed / 2) / speed;
retval = revert - divider;
if (retval > revert - 1) {
retval = revert - 1;
divider = revert - retval;
}
/* This line is suggested. Must be wrong I think
*speedp = (clock + divider / 2) / divider;
So I chose the next one */
*speedp = clock / divider;
diff = speed - *speedp;
if (diff < 0) diff =-diff;
*diffp = diff;
return retval;
}
static int ess_calc_best_speed
(int clock1, int rev1, int clock2, int rev2, int *divp, int *speedp)
{
int speed1 = *speedp, speed2 = *speedp;
int div1, div2;
int diff1, diff2;
int retval;
div1 = ess_calc_div (clock1, rev1, &speed1, &diff1);
div2 = ess_calc_div (clock2, rev2, &speed2, &diff2);
if (diff1 < diff2) {
*divp = div1;
*speedp = speed1;
retval = 1;
} else {
/* *divp = div2; */
*divp = 0x80 | div2;
*speedp = speed2;
retval = 2;
}
return retval;
}
/*
* Depending on the audiochannel ESS devices can
* have different clock settings. These are made consistent for duplex
* however.
* callers of ess_speed only do an audionum suggestion, which means
* input suggests 1, output suggests 2. This suggestion is only true
* however when doing duplex.
*/
static void ess_common_speed (sb_devc *devc, int *speedp, int *divp)
{
int diff = 0, div;
if (devc->duplex) {
/*
* The 0x80 is important for the first audio channel
*/
if (devc->submodel == SUBMDL_ES1888) {
div = 0x80 | ess_calc_div (795500, 256, speedp, &diff);
} else {
div = 0x80 | ess_calc_div (795500, 128, speedp, &diff);
}
} else if(devc->caps & SB_CAP_ES18XX_RATE) {
if (devc->submodel == SUBMDL_ES1888) {
ess_calc_best_speed(397700, 128, 795500, 256,
&div, speedp);
} else {
ess_calc_best_speed(ES18XX_CLOCK1, 128, ES18XX_CLOCK2, 256,
&div, speedp);
}
} else {
if (*speedp > 22000) {
div = 0x80 | ess_calc_div (ES1688_CLOCK1, 256, speedp, &diff);
} else {
div = 0x00 | ess_calc_div (ES1688_CLOCK2, 128, speedp, &diff);
}
}
*divp = div;
}
static void ess_speed (sb_devc *devc, int audionum)
{
int speed;
int div, div2;
ess_common_speed (devc, &(devc->speed), &div);
#ifdef FKS_REG_LOGGING
printk (KERN_INFO "FKS: ess_speed (%d) b speed = %d, div=%x\n", audionum, devc->speed, div);
#endif
/* Set filter roll-off to 90% of speed/2 */
speed = (devc->speed * 9) / 20;
div2 = 256 - 7160000 / (speed * 82);
if (!devc->duplex) audionum = 1;
if (audionum == 1) {
/* Change behaviour of register A1 *
sb_chg_mixer(devc, 0x71, 0x20, 0x20)
* For ES1869 only??? */
ess_write (devc, 0xa1, div);
ess_write (devc, 0xa2, div2);
} else {
ess_setmixer (devc, 0x70, div);
/*
* FKS: fascinating: 0x72 doesn't seem to work.
*/
ess_write (devc, 0xa2, div2);
ess_setmixer (devc, 0x72, div2);
}
}
static int ess_audio_prepare_for_input(int dev, int bsize, int bcount)
{
sb_devc *devc = audio_devs[dev]->devc;
ess_speed(devc, 1);
sb_dsp_command(devc, DSP_CMD_SPKOFF);
ess_write (devc, 0xb8, 0x0e); /* Auto init DMA mode */
ess_change (devc, 0xa8, 0x03, 3 - devc->channels); /* Mono/stereo */
ess_write (devc, 0xb9, 2); /* Demand mode (4 bytes/DMA request) */
ess_exec_commands (devc, ess_inp_cmds);
ess_change (devc, 0xb1, 0xf0, 0x50);
ess_change (devc, 0xb2, 0xf0, 0x50);
devc->trigger_bits = 0;
return 0;
}
static int ess_audio_prepare_for_output_audio1 (int dev, int bsize, int bcount)
{
sb_devc *devc = audio_devs[dev]->devc;
sb_dsp_reset(devc);
ess_speed(devc, 1);
ess_write (devc, 0xb8, 4); /* Auto init DMA mode */
ess_change (devc, 0xa8, 0x03, 3 - devc->channels); /* Mono/stereo */
ess_write (devc, 0xb9, 2); /* Demand mode (4 bytes/request) */
ess_exec_commands (devc, ess_out_cmds);
ess_change (devc, 0xb1, 0xf0, 0x50); /* Enable DMA */
ess_change (devc, 0xb2, 0xf0, 0x50); /* Enable IRQ */
sb_dsp_command(devc, DSP_CMD_SPKON); /* There be sound! */
devc->trigger_bits = 0;
return 0;
}
static int ess_audio_prepare_for_output_audio2 (int dev, int bsize, int bcount)
{
sb_devc *devc = audio_devs[dev]->devc;
unsigned char bits;
/* FKS: qqq
sb_dsp_reset(devc);
*/
/*
* Auto-Initialize:
* DMA mode + demand mode (8 bytes/request, yes I want it all!)
* But leave 16-bit DMA bit untouched!
*/
ess_chgmixer (devc, 0x78, 0xd0, 0xd0);
ess_speed(devc, 2);
/* bits 4:3 on ES1887 represent recording source. Keep them! */
bits = ess_getmixer (devc, 0x7a) & 0x18;
/* Set stereo/mono */
if (devc->channels != 1) bits |= 0x02;
/* Init DACs; UNSIGNED mode for 8 bit; SIGNED mode for 16 bit */
if (devc->bits != AFMT_U8) bits |= 0x05; /* 16 bit */
/* Enable DMA, IRQ will be shared (hopefully)*/
bits |= 0x60;
ess_setmixer (devc, 0x7a, bits);
ess_mixer_reload (devc, SOUND_MIXER_PCM); /* There be sound! */
devc->trigger_bits = 0;
return 0;
}
static int ess_audio_prepare_for_output(int dev, int bsize, int bcount)
{
sb_devc *devc = audio_devs[dev]->devc;
#ifdef FKS_REG_LOGGING
printk(KERN_INFO "ess_audio_prepare_for_output: dma_out=%d,dma_in=%d\n"
, audio_devs[dev]->dmap_out->dma, audio_devs[dev]->dmap_in->dma);
#endif
if (devc->duplex) {
return ess_audio_prepare_for_output_audio2 (dev, bsize, bcount);
} else {
return ess_audio_prepare_for_output_audio1 (dev, bsize, bcount);
}
}
static void ess_audio_halt_xfer(int dev)
{
unsigned long flags;
sb_devc *devc = audio_devs[dev]->devc;
spin_lock_irqsave(&devc->lock, flags);
sb_dsp_reset(devc);
spin_unlock_irqrestore(&devc->lock, flags);
/*
* Audio 2 may still be operational! Creates awful sounds!
*/
if (devc->duplex) ess_chgmixer(devc, 0x78, 0x03, 0x00);
}
static void ess_audio_start_input
(int dev, unsigned long buf, int nr_bytes, int intrflag)
{
int count = nr_bytes;
sb_devc *devc = audio_devs[dev]->devc;
short c = -nr_bytes;
/*
* Start a DMA input to the buffer pointed by dmaqtail
*/
if (audio_devs[dev]->dmap_in->dma > 3) count >>= 1;
count--;
devc->irq_mode = IMODE_INPUT;
ess_write (devc, 0xa4, (unsigned char) ((unsigned short) c & 0xff));
ess_write (devc, 0xa5, (unsigned char) (((unsigned short) c >> 8) & 0xff));
ess_change (devc, 0xb8, 0x0f, 0x0f); /* Go */
devc->intr_active = 1;
}
static void ess_audio_output_block_audio1
(int dev, unsigned long buf, int nr_bytes, int intrflag)
{
int count = nr_bytes;
sb_devc *devc = audio_devs[dev]->devc;
short c = -nr_bytes;
if (audio_devs[dev]->dmap_out->dma > 3)
count >>= 1;
count--;
devc->irq_mode = IMODE_OUTPUT;
ess_write (devc, 0xa4, (unsigned char) ((unsigned short) c & 0xff));
ess_write (devc, 0xa5, (unsigned char) (((unsigned short) c >> 8) & 0xff));
ess_change (devc, 0xb8, 0x05, 0x05); /* Go */
devc->intr_active = 1;
}
static void ess_audio_output_block_audio2
(int dev, unsigned long buf, int nr_bytes, int intrflag)
{
int count = nr_bytes;
sb_devc *devc = audio_devs[dev]->devc;
short c = -nr_bytes;
if (audio_devs[dev]->dmap_out->dma > 3) count >>= 1;
count--;
ess_setmixer (devc, 0x74, (unsigned char) ((unsigned short) c & 0xff));
ess_setmixer (devc, 0x76, (unsigned char) (((unsigned short) c >> 8) & 0xff));
ess_chgmixer (devc, 0x78, 0x03, 0x03); /* Go */
devc->irq_mode_16 = IMODE_OUTPUT;
devc->intr_active_16 = 1;
}
static void ess_audio_output_block
(int dev, unsigned long buf, int nr_bytes, int intrflag)
{
sb_devc *devc = audio_devs[dev]->devc;
if (devc->duplex) {
ess_audio_output_block_audio2 (dev, buf, nr_bytes, intrflag);
} else {
ess_audio_output_block_audio1 (dev, buf, nr_bytes, intrflag);
}
}
/*
* FKS: the if-statements for both bits and bits_16 are quite alike.
* Combine this...
*/
static void ess_audio_trigger(int dev, int bits)
{
sb_devc *devc = audio_devs[dev]->devc;
int bits_16 = bits & devc->irq_mode_16;
bits &= devc->irq_mode;
if (!bits && !bits_16) {
/* FKS oh oh.... wrong?? for dma 16? */
sb_dsp_command(devc, 0xd0); /* Halt DMA */
}
if (bits) {
switch (devc->irq_mode)
{
case IMODE_INPUT:
ess_audio_start_input(dev, devc->trg_buf, devc->trg_bytes,
devc->trg_intrflag);
break;
case IMODE_OUTPUT:
ess_audio_output_block(dev, devc->trg_buf, devc->trg_bytes,
devc->trg_intrflag);
break;
}
}
if (bits_16) {
switch (devc->irq_mode_16) {
case IMODE_INPUT:
ess_audio_start_input(dev, devc->trg_buf_16, devc->trg_bytes_16,
devc->trg_intrflag_16);
break;
case IMODE_OUTPUT:
ess_audio_output_block(dev, devc->trg_buf_16, devc->trg_bytes_16,
devc->trg_intrflag_16);
break;
}
}
devc->trigger_bits = bits | bits_16;
}
static int ess_audio_set_speed(int dev, int speed)
{
sb_devc *devc = audio_devs[dev]->devc;
int minspeed, maxspeed, dummydiv;
if (speed > 0) {
minspeed = (devc->duplex ? 6215 : 5000 );
maxspeed = (devc->duplex ? 44100 : 48000);
if (speed < minspeed) speed = minspeed;
if (speed > maxspeed) speed = maxspeed;
ess_common_speed (devc, &speed, &dummydiv);
devc->speed = speed;
}
return devc->speed;
}
/*
* FKS: This is a one-on-one copy of sb1_audio_set_bits
*/
static unsigned int ess_audio_set_bits(int dev, unsigned int bits)
{
sb_devc *devc = audio_devs[dev]->devc;
if (bits != 0) {
if (bits == AFMT_U8 || bits == AFMT_S16_LE) {
devc->bits = bits;
} else {
devc->bits = AFMT_U8;
}
}
return devc->bits;
}
/*
* FKS: This is a one-on-one copy of sbpro_audio_set_channels
* (*) Modified it!!
*/
static short ess_audio_set_channels(int dev, short channels)
{
sb_devc *devc = audio_devs[dev]->devc;
if (channels == 1 || channels == 2) devc->channels = channels;
return devc->channels;
}
static struct audio_driver ess_audio_driver = /* ESS ES688/1688 */
{
.owner = THIS_MODULE,
.open = sb_audio_open,
.close = sb_audio_close,
.output_block = ess_set_output_parms,
.start_input = ess_set_input_parms,
.prepare_for_input = ess_audio_prepare_for_input,
.prepare_for_output = ess_audio_prepare_for_output,
.halt_io = ess_audio_halt_xfer,
.trigger = ess_audio_trigger,
.set_speed = ess_audio_set_speed,
.set_bits = ess_audio_set_bits,
.set_channels = ess_audio_set_channels
};
/*
* ess_audio_init must be called from sb_audio_init
*/
struct audio_driver *ess_audio_init
(sb_devc *devc, int *audio_flags, int *format_mask)
{
*audio_flags = DMA_AUTOMODE;
*format_mask |= AFMT_S16_LE;
if (devc->duplex) {
int tmp_dma;
/*
* sb_audio_init thinks dma8 is for playback and
* dma16 is for record. Not now! So swap them.
*/
tmp_dma = devc->dma16;
devc->dma16 = devc->dma8;
devc->dma8 = tmp_dma;
*audio_flags |= DMA_DUPLEX;
}
return &ess_audio_driver;
}
/****************************************************************************
* *
* ESS common *
* *
****************************************************************************/
static void ess_handle_channel
(char *channel, int dev, int intr_active, unsigned char flag, int irq_mode)
{
if (!intr_active || !flag) return;
#ifdef FKS_REG_LOGGING
printk(KERN_INFO "FKS: ess_handle_channel %s irq_mode=%d\n", channel, irq_mode);
#endif
switch (irq_mode) {
case IMODE_OUTPUT:
DMAbuf_outputintr (dev, 1);
break;
case IMODE_INPUT:
DMAbuf_inputintr (dev);
break;
case IMODE_INIT:
break;
default:;
/* printk(KERN_WARNING "ESS: Unexpected interrupt\n"); */
}
}
/*
* FKS: TODO!!! Finish this!
*
* I think midi stuff uses uart401, without interrupts.
* So IMODE_MIDI isn't a value for devc->irq_mode.
*/
void ess_intr (sb_devc *devc)
{
int status;
unsigned char src;
if (devc->submodel == SUBMDL_ES1887) {
src = ess_getmixer (devc, 0x7f) >> 4;
} else {
src = 0xff;
}
#ifdef FKS_REG_LOGGING
printk(KERN_INFO "FKS: sbintr src=%x\n",(int)src);
#endif
ess_handle_channel
( "Audio 1"
, devc->dev, devc->intr_active , src & 0x01, devc->irq_mode );
ess_handle_channel
( "Audio 2"
, devc->dev, devc->intr_active_16, src & 0x02, devc->irq_mode_16);
/*
* Acknowledge interrupts
*/
if (devc->submodel == SUBMDL_ES1887 && (src & 0x02)) {
ess_chgmixer (devc, 0x7a, 0x80, 0x00);
}
if (src & 0x01) {
status = inb(DSP_DATA_AVAIL);
}
}
static void ess_extended (sb_devc * devc)
{
/* Enable extended mode */
sb_dsp_command(devc, 0xc6);
}
static int ess_write (sb_devc * devc, unsigned char reg, unsigned char data)
{
#ifdef FKS_REG_LOGGING
printk(KERN_INFO "FKS: write reg %x: %x\n", reg, data);
#endif
/* Write a byte to an extended mode register of ES1688 */
if (!sb_dsp_command(devc, reg))
return 0;
return sb_dsp_command(devc, data);
}
static int ess_read (sb_devc * devc, unsigned char reg)
{
/* Read a byte from an extended mode register of ES1688 */
/* Read register command */
if (!sb_dsp_command(devc, 0xc0)) return -1;
if (!sb_dsp_command(devc, reg )) return -1;
return sb_dsp_get_byte(devc);
}
int ess_dsp_reset(sb_devc * devc)
{
int loopc;
#ifdef FKS_REG_LOGGING
printk(KERN_INFO "FKS: ess_dsp_reset 1\n");
ess_show_mixerregs (devc);
#endif
DEB(printk("Entered ess_dsp_reset()\n"));
outb(3, DSP_RESET); /* Reset FIFO too */
udelay(10);
outb(0, DSP_RESET);
udelay(30);
for (loopc = 0; loopc < 1000 && !(inb(DSP_DATA_AVAIL) & 0x80); loopc++);
if (inb(DSP_READ) != 0xAA) {
DDB(printk("sb: No response to RESET\n"));
return 0; /* Sorry */
}
ess_extended (devc);
DEB(printk("sb_dsp_reset() OK\n"));
#ifdef FKS_LOGGING
printk(KERN_INFO "FKS: dsp_reset 2\n");
ess_show_mixerregs (devc);
#endif
return 1;
}
static int ess_irq_bits (int irq)
{
switch (irq) {
case 2:
case 9:
return 0;
case 5:
return 1;
case 7:
return 2;
case 10:
return 3;
default:
printk(KERN_ERR "ESS1688: Invalid IRQ %d\n", irq);
return -1;
}
}
/*
* Set IRQ configuration register for all ESS models
*/
static int ess_common_set_irq_hw (sb_devc * devc)
{
int irq_bits;
if ((irq_bits = ess_irq_bits (devc->irq)) == -1) return 0;
if (!ess_write (devc, 0xb1, 0x50 | (irq_bits << 2))) {
printk(KERN_ERR "ES1688: Failed to write to IRQ config register\n");
return 0;
}
return 1;
}
/*
* I wanna use modern ES1887 mixer irq handling. Funny is the
* fact that my BIOS wants the same. But suppose someone's BIOS
* doesn't do this!
* This is independent of duplex. If there's a 1887 this will
* prevent it from going into 1888 mode.
*/
static void ess_es1887_set_irq_hw (sb_devc * devc)
{
int irq_bits;
if ((irq_bits = ess_irq_bits (devc->irq)) == -1) return;
ess_chgmixer (devc, 0x7f, 0x0f, 0x01 | ((irq_bits + 1) << 1));
}
static int ess_set_irq_hw (sb_devc * devc)
{
if (devc->submodel == SUBMDL_ES1887) ess_es1887_set_irq_hw (devc);
return ess_common_set_irq_hw (devc);
}
#ifdef FKS_TEST
/*
* FKS_test:
* for ES1887: 00, 18, non wr bits: 0001 1000
* for ES1868: 00, b8, non wr bits: 1011 1000
* for ES1888: 00, f8, non wr bits: 1111 1000
* for ES1688: 00, f8, non wr bits: 1111 1000
* + ES968
*/
static void FKS_test (sb_devc * devc)
{
int val1, val2;
val1 = ess_getmixer (devc, 0x64);
ess_setmixer (devc, 0x64, ~val1);
val2 = ess_getmixer (devc, 0x64) ^ ~val1;
ess_setmixer (devc, 0x64, val1);
val1 ^= ess_getmixer (devc, 0x64);
printk (KERN_INFO "FKS: FKS_test %02x, %02x\n", (val1 & 0x0ff), (val2 & 0x0ff));
};
#endif
static unsigned int ess_identify (sb_devc * devc)
{
unsigned int val;
unsigned long flags;
spin_lock_irqsave(&devc->lock, flags);
outb(((unsigned char) (0x40 & 0xff)), MIXER_ADDR);
udelay(20);
val = inb(MIXER_DATA) << 8;
udelay(20);
val |= inb(MIXER_DATA);
udelay(20);
spin_unlock_irqrestore(&devc->lock, flags);
return val;
}
/*
* ESS technology describes a detection scheme in their docs. It involves
* fiddling with the bits in certain mixer registers. ess_probe is supposed
* to help.
*
* FKS: tracing shows ess_probe writes wrong value to 0x64. Bit 3 reads 1, but
* should be written 0 only. Check this.
*/
static int ess_probe (sb_devc * devc, int reg, int xorval)
{
int val1, val2, val3;
val1 = ess_getmixer (devc, reg);
val2 = val1 ^ xorval;
ess_setmixer (devc, reg, val2);
val3 = ess_getmixer (devc, reg);
ess_setmixer (devc, reg, val1);
return (val2 == val3);
}
int ess_init(sb_devc * devc, struct address_info *hw_config)
{
unsigned char cfg;
int ess_major = 0, ess_minor = 0;
int i;
static char name[100], modelname[10];
/*
* Try to detect ESS chips.
*/
sb_dsp_command(devc, 0xe7); /* Return identification */
for (i = 1000; i; i--) {
if (inb(DSP_DATA_AVAIL) & 0x80) {
if (ess_major == 0) {
ess_major = inb(DSP_READ);
} else {
ess_minor = inb(DSP_READ);
break;
}
}
}
if (ess_major == 0) return 0;
if (ess_major == 0x48 && (ess_minor & 0xf0) == 0x80) {
sprintf(name, "ESS ES488 AudioDrive (rev %d)",
ess_minor & 0x0f);
hw_config->name = name;
devc->model = MDL_SBPRO;
return 1;
}
/*
* This the detection heuristic of ESS technology, though somewhat
* changed to actually make it work.
* This results in the following detection steps:
* - distinct between ES688 and ES1688+ (as always done in this driver)
* if ES688 we're ready
* - try to detect ES1868, ES1869 or ES1878 (ess_identify)
* if successful we're ready
* - try to detect ES1888, ES1887 or ES1788 (aim: detect ES1887)
* if successful we're ready
* - Dunno. Must be 1688. Will do in general
*
* This is the most BETA part of the software: Will the detection
* always work?
*/
devc->model = MDL_ESS;
devc->submodel = ess_minor & 0x0f;
if (ess_major == 0x68 && (ess_minor & 0xf0) == 0x80) {
char *chip = NULL;
int submodel = -1;
switch (devc->sbmo.esstype) {
case ESSTYPE_DETECT:
case ESSTYPE_LIKE20:
break;
case 688:
submodel = 0x00;
break;
case 1688:
submodel = 0x08;
break;
case 1868:
submodel = SUBMDL_ES1868;
break;
case 1869:
submodel = SUBMDL_ES1869;
break;
case 1788:
submodel = SUBMDL_ES1788;
break;
case 1878:
submodel = SUBMDL_ES1878;
break;
case 1879:
submodel = SUBMDL_ES1879;
break;
case 1887:
submodel = SUBMDL_ES1887;
break;
case 1888:
submodel = SUBMDL_ES1888;
break;
default:
printk (KERN_ERR "Invalid esstype=%d specified\n", devc->sbmo.esstype);
return 0;
};
if (submodel != -1) {
devc->submodel = submodel;
sprintf (modelname, "ES%d", devc->sbmo.esstype);
chip = modelname;
};
if (chip == NULL && (ess_minor & 0x0f) < 8) {
chip = "ES688";
};
#ifdef FKS_TEST
FKS_test (devc);
#endif
/*
* If Nothing detected yet, and we want 2.0 behaviour...
* Then let's assume it's ES1688.
*/
if (chip == NULL && devc->sbmo.esstype == ESSTYPE_LIKE20) {
chip = "ES1688";
};
if (chip == NULL) {
int type;
type = ess_identify (devc);
switch (type) {
case 0x1868:
chip = "ES1868";
devc->submodel = SUBMDL_ES1868;
break;
case 0x1869:
chip = "ES1869";
devc->submodel = SUBMDL_ES1869;
break;
case 0x1878:
chip = "ES1878";
devc->submodel = SUBMDL_ES1878;
break;
case 0x1879:
chip = "ES1879";
devc->submodel = SUBMDL_ES1879;
break;
default:
if ((type & 0x00ff) != ((type >> 8) & 0x00ff)) {
printk ("ess_init: Unrecognized %04x\n", type);
}
};
};
#if 0
/*
* this one failed:
* the probing of bit 4 is another thought: from ES1788 and up, all
* chips seem to have hardware volume control. Bit 4 is readonly to
* check if a hardware volume interrupt has fired.
* Cause ES688/ES1688 don't have this feature, bit 4 might be writeable
* for these chips.
*/
if (chip == NULL && !ess_probe(devc, 0x64, (1 << 4))) {
#endif
/*
* the probing of bit 2 is my idea. The ES1887 docs want me to probe
* bit 3. This results in ES1688 being detected as ES1788.
* Bit 2 is for "Enable HWV IRQE", but as ES(1)688 chips don't have
* HardWare Volume, I think they don't have this IRQE.
*/
if (chip == NULL && ess_probe(devc, 0x64, (1 << 2))) {
if (ess_probe (devc, 0x70, 0x7f)) {
if (ess_probe (devc, 0x64, (1 << 5))) {
chip = "ES1887";
devc->submodel = SUBMDL_ES1887;
} else {
chip = "ES1888";
devc->submodel = SUBMDL_ES1888;
}
} else {
chip = "ES1788";
devc->submodel = SUBMDL_ES1788;
}
};
if (chip == NULL) {
chip = "ES1688";
};
printk ( KERN_INFO "ESS chip %s %s%s\n"
, chip
, ( devc->sbmo.esstype == ESSTYPE_DETECT || devc->sbmo.esstype == ESSTYPE_LIKE20
? "detected"
: "specified"
)
, ( devc->sbmo.esstype == ESSTYPE_LIKE20
? " (kernel 2.0 compatible)"
: ""
)
);
sprintf(name,"ESS %s AudioDrive (rev %d)", chip, ess_minor & 0x0f);
} else {
strcpy(name, "Jazz16");
}
/* AAS: info stolen from ALSA: these boards have different clocks */
switch(devc->submodel) {
/* APPARENTLY NOT 1869 AND 1887
case SUBMDL_ES1869:
case SUBMDL_ES1887:
*/
case SUBMDL_ES1888:
devc->caps |= SB_CAP_ES18XX_RATE;
break;
}
hw_config->name = name;
/* FKS: sb_dsp_reset to enable extended mode???? */
sb_dsp_reset(devc); /* Turn on extended mode */
/*
* Enable joystick and OPL3
*/
cfg = ess_getmixer (devc, 0x40);
ess_setmixer (devc, 0x40, cfg | 0x03);
if (devc->submodel >= 8) { /* ES1688 */
devc->caps |= SB_NO_MIDI; /* ES1688 uses MPU401 MIDI mode */
}
sb_dsp_reset (devc);
/*
* This is important! If it's not done, the IRQ probe in sb_dsp_init
* may fail.
*/
return ess_set_irq_hw (devc);
}
static int ess_set_dma_hw(sb_devc * devc)
{
unsigned char cfg, dma_bits = 0, dma16_bits;
int dma;
#ifdef FKS_LOGGING
printk(KERN_INFO "ess_set_dma_hw: dma8=%d,dma16=%d,dup=%d\n"
, devc->dma8, devc->dma16, devc->duplex);
#endif
/*
* FKS: It seems as if this duplex flag isn't set yet. Check it.
*/
dma = devc->dma8;
if (dma > 3 || dma < 0 || dma == 2) {
dma_bits = 0;
printk(KERN_ERR "ESS1688: Invalid DMA8 %d\n", dma);
return 0;
} else {
/* Extended mode DMA enable */
cfg = 0x50;
if (dma == 3) {
dma_bits = 3;
} else {
dma_bits = dma + 1;
}
}
if (!ess_write (devc, 0xb2, cfg | (dma_bits << 2))) {
printk(KERN_ERR "ESS1688: Failed to write to DMA config register\n");
return 0;
}
if (devc->duplex) {
dma = devc->dma16;
dma16_bits = 0;
if (dma >= 0) {
switch (dma) {
case 0:
dma_bits = 0x04;
break;
case 1:
dma_bits = 0x05;
break;
case 3:
dma_bits = 0x06;
break;
case 5:
dma_bits = 0x07;
dma16_bits = 0x20;
break;
default:
printk(KERN_ERR "ESS1887: Invalid DMA16 %d\n", dma);
return 0;
};
ess_chgmixer (devc, 0x78, 0x20, dma16_bits);
ess_chgmixer (devc, 0x7d, 0x07, dma_bits);
}
}
return 1;
}
/*
* This one is called from sb_dsp_init.
*
* Return values:
* 0: Failed
* 1: Succeeded or doesn't apply (not SUBMDL_ES1887)
*/
int ess_dsp_init (sb_devc *devc, struct address_info *hw_config)
{
/*
* Caller also checks this, but anyway
*/
if (devc->model != MDL_ESS) {
printk (KERN_INFO "ess_dsp_init for non ESS chip\n");
return 1;
}
/*
* This for ES1887 to run Full Duplex. Actually ES1888
* is allowed to do so too. I have no idea yet if this
* will work for ES1888 however.
*
* For SB16 having both dma8 and dma16 means enable
* Full Duplex. Let's try this for ES1887 too
*
*/
if (devc->submodel == SUBMDL_ES1887) {
if (hw_config->dma2 != -1) {
devc->dma16 = hw_config->dma2;
}
/*
* devc->duplex initialization is put here, cause
* ess_set_dma_hw needs it.
*/
if (devc->dma8 != devc->dma16 && devc->dma16 != -1) {
devc->duplex = 1;
}
}
if (!ess_set_dma_hw (devc)) {
free_irq(devc->irq, devc);
return 0;
}
return 1;
}
/****************************************************************************
* *
* ESS mixer *
* *
****************************************************************************/
#define ES688_RECORDING_DEVICES \
( SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD )
#define ES688_MIXER_DEVICES \
( SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_LINE \
| SOUND_MASK_MIC | SOUND_MASK_CD | SOUND_MASK_VOLUME \
| SOUND_MASK_LINE2 | SOUND_MASK_SPEAKER )
#define ES1688_RECORDING_DEVICES \
( ES688_RECORDING_DEVICES )
#define ES1688_MIXER_DEVICES \
( ES688_MIXER_DEVICES | SOUND_MASK_RECLEV )
#define ES1887_RECORDING_DEVICES \
( ES1688_RECORDING_DEVICES | SOUND_MASK_LINE2 | SOUND_MASK_SYNTH)
#define ES1887_MIXER_DEVICES \
( ES1688_MIXER_DEVICES )
/*
* Mixer registers of ES1887
*
* These registers specifically take care of recording levels. To make the
* mapping from playback devices to recording devices every recording
* devices = playback device + ES_REC_MIXER_RECDIFF
*/
#define ES_REC_MIXER_RECBASE (SOUND_MIXER_LINE3 + 1)
#define ES_REC_MIXER_RECDIFF (ES_REC_MIXER_RECBASE - SOUND_MIXER_SYNTH)
#define ES_REC_MIXER_RECSYNTH (SOUND_MIXER_SYNTH + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECPCM (SOUND_MIXER_PCM + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECSPEAKER (SOUND_MIXER_SPEAKER + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECLINE (SOUND_MIXER_LINE + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECMIC (SOUND_MIXER_MIC + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECCD (SOUND_MIXER_CD + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECIMIX (SOUND_MIXER_IMIX + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECALTPCM (SOUND_MIXER_ALTPCM + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECRECLEV (SOUND_MIXER_RECLEV + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECIGAIN (SOUND_MIXER_IGAIN + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECOGAIN (SOUND_MIXER_OGAIN + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECLINE1 (SOUND_MIXER_LINE1 + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECLINE2 (SOUND_MIXER_LINE2 + ES_REC_MIXER_RECDIFF)
#define ES_REC_MIXER_RECLINE3 (SOUND_MIXER_LINE3 + ES_REC_MIXER_RECDIFF)
static mixer_tab es688_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x32, 7, 4, 0x32, 3, 4),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x36, 7, 4, 0x36, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x14, 7, 4, 0x14, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3c, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x3e, 7, 4, 0x3e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x1a, 7, 4, 0x1a, 3, 4),
MIX_ENT(SOUND_MIXER_CD, 0x38, 7, 4, 0x38, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE2, 0x3a, 7, 4, 0x3a, 3, 4),
MIX_ENT(SOUND_MIXER_LINE3, 0x00, 0, 0, 0x00, 0, 0)
};
/*
* The ES1688 specifics... hopefully correct...
* - 6 bit master volume
* I was wrong, ES1888 docs say ES1688 didn't have it.
* - RECLEV control
* These may apply to ES688 too. I have no idea.
*/
static mixer_tab es1688_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x32, 7, 4, 0x32, 3, 4),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x36, 7, 4, 0x36, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x14, 7, 4, 0x14, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3c, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x3e, 7, 4, 0x3e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x1a, 7, 4, 0x1a, 3, 4),
MIX_ENT(SOUND_MIXER_CD, 0x38, 7, 4, 0x38, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0xb4, 7, 4, 0xb4, 3, 4),
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE2, 0x3a, 7, 4, 0x3a, 3, 4),
MIX_ENT(SOUND_MIXER_LINE3, 0x00, 0, 0, 0x00, 0, 0)
};
static mixer_tab es1688later_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x60, 5, 6, 0x62, 5, 6),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x36, 7, 4, 0x36, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x14, 7, 4, 0x14, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3c, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x3e, 7, 4, 0x3e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x1a, 7, 4, 0x1a, 3, 4),
MIX_ENT(SOUND_MIXER_CD, 0x38, 7, 4, 0x38, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0xb4, 7, 4, 0xb4, 3, 4),
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE2, 0x3a, 7, 4, 0x3a, 3, 4),
MIX_ENT(SOUND_MIXER_LINE3, 0x00, 0, 0, 0x00, 0, 0)
};
/*
* This one is for all ESS chips with a record mixer.
* It's not used (yet) however
*/
static mixer_tab es_rec_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x60, 5, 6, 0x62, 5, 6),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x36, 7, 4, 0x36, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x14, 7, 4, 0x14, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3c, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x3e, 7, 4, 0x3e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x1a, 7, 4, 0x1a, 3, 4),
MIX_ENT(SOUND_MIXER_CD, 0x38, 7, 4, 0x38, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0xb4, 7, 4, 0xb4, 3, 4),
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE2, 0x3a, 7, 4, 0x3a, 3, 4),
MIX_ENT(SOUND_MIXER_LINE3, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECSYNTH, 0x6b, 7, 4, 0x6b, 3, 4),
MIX_ENT(ES_REC_MIXER_RECPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECSPEAKER, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE, 0x6e, 7, 4, 0x6e, 3, 4),
MIX_ENT(ES_REC_MIXER_RECMIC, 0x68, 7, 4, 0x68, 3, 4),
MIX_ENT(ES_REC_MIXER_RECCD, 0x6a, 7, 4, 0x6a, 3, 4),
MIX_ENT(ES_REC_MIXER_RECIMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECRECLEV, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECIGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECOGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE2, 0x6c, 7, 4, 0x6c, 3, 4),
MIX_ENT(ES_REC_MIXER_RECLINE3, 0x00, 0, 0, 0x00, 0, 0)
};
/*
* This one is for ES1887. It's little different from es_rec_mix: it
* has 0x7c for PCM playback level. This is because ES1887 uses
* Audio 2 for playback.
*/
static mixer_tab es1887_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x60, 5, 6, 0x62, 5, 6),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x36, 7, 4, 0x36, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x7c, 7, 4, 0x7c, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3c, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x3e, 7, 4, 0x3e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x1a, 7, 4, 0x1a, 3, 4),
MIX_ENT(SOUND_MIXER_CD, 0x38, 7, 4, 0x38, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0xb4, 7, 4, 0xb4, 3, 4),
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE2, 0x3a, 7, 4, 0x3a, 3, 4),
MIX_ENT(SOUND_MIXER_LINE3, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECSYNTH, 0x6b, 7, 4, 0x6b, 3, 4),
MIX_ENT(ES_REC_MIXER_RECPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECSPEAKER, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE, 0x6e, 7, 4, 0x6e, 3, 4),
MIX_ENT(ES_REC_MIXER_RECMIC, 0x68, 7, 4, 0x68, 3, 4),
MIX_ENT(ES_REC_MIXER_RECCD, 0x6a, 7, 4, 0x6a, 3, 4),
MIX_ENT(ES_REC_MIXER_RECIMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECRECLEV, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECIGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECOGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE1, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(ES_REC_MIXER_RECLINE2, 0x6c, 7, 4, 0x6c, 3, 4),
MIX_ENT(ES_REC_MIXER_RECLINE3, 0x00, 0, 0, 0x00, 0, 0)
};
static int ess_has_rec_mixer (int submodel)
{
switch (submodel) {
case SUBMDL_ES1887:
return 1;
default:
return 0;
};
};
#ifdef FKS_LOGGING
static int ess_mixer_mon_regs[]
= { 0x70, 0x71, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7d, 0x7f
, 0xa1, 0xa2, 0xa4, 0xa5, 0xa8, 0xa9
, 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb9
, 0x00};
static void ess_show_mixerregs (sb_devc *devc)
{
int *mp = ess_mixer_mon_regs;
return;
while (*mp != 0) {
printk (KERN_INFO "res (%x)=%x\n", *mp, (int)(ess_getmixer (devc, *mp)));
mp++;
}
}
#endif
void ess_setmixer (sb_devc * devc, unsigned int port, unsigned int value)
{
unsigned long flags;
#ifdef FKS_LOGGING
printk(KERN_INFO "FKS: write mixer %x: %x\n", port, value);
#endif
spin_lock_irqsave(&devc->lock, flags);
if (port >= 0xa0) {
ess_write (devc, port, value);
} else {
outb(((unsigned char) (port & 0xff)), MIXER_ADDR);
udelay(20);
outb(((unsigned char) (value & 0xff)), MIXER_DATA);
udelay(20);
};
spin_unlock_irqrestore(&devc->lock, flags);
}
unsigned int ess_getmixer (sb_devc * devc, unsigned int port)
{
unsigned int val;
unsigned long flags;
spin_lock_irqsave(&devc->lock, flags);
if (port >= 0xa0) {
val = ess_read (devc, port);
} else {
outb(((unsigned char) (port & 0xff)), MIXER_ADDR);
udelay(20);
val = inb(MIXER_DATA);
udelay(20);
}
spin_unlock_irqrestore(&devc->lock, flags);
return val;
}
static void ess_chgmixer
(sb_devc * devc, unsigned int reg, unsigned int mask, unsigned int val)
{
int value;
value = ess_getmixer (devc, reg);
value = (value & ~mask) | (val & mask);
ess_setmixer (devc, reg, value);
}
/*
* ess_mixer_init must be called from sb_mixer_init
*/
void ess_mixer_init (sb_devc * devc)
{
devc->mixer_caps = SOUND_CAP_EXCL_INPUT;
/*
* Take care of ES1887 specifics...
*/
switch (devc->submodel) {
case SUBMDL_ES1887:
devc->supported_devices = ES1887_MIXER_DEVICES;
devc->supported_rec_devices = ES1887_RECORDING_DEVICES;
#ifdef FKS_LOGGING
printk (KERN_INFO "FKS: ess_mixer_init dup = %d\n", devc->duplex);
#endif
if (devc->duplex) {
devc->iomap = &es1887_mix;
devc->iomap_sz = ARRAY_SIZE(es1887_mix);
} else {
devc->iomap = &es_rec_mix;
devc->iomap_sz = ARRAY_SIZE(es_rec_mix);
}
break;
default:
if (devc->submodel < 8) {
devc->supported_devices = ES688_MIXER_DEVICES;
devc->supported_rec_devices = ES688_RECORDING_DEVICES;
devc->iomap = &es688_mix;
devc->iomap_sz = ARRAY_SIZE(es688_mix);
} else {
/*
* es1688 has 4 bits master vol.
* later chips have 6 bits (?)
*/
devc->supported_devices = ES1688_MIXER_DEVICES;
devc->supported_rec_devices = ES1688_RECORDING_DEVICES;
if (devc->submodel < 0x10) {
devc->iomap = &es1688_mix;
devc->iomap_sz = ARRAY_SIZE(es688_mix);
} else {
devc->iomap = &es1688later_mix;
devc->iomap_sz = ARRAY_SIZE(es1688later_mix);
}
}
}
}
/*
* Changing playback levels at an ESS chip with record mixer means having to
* take care of recording levels of recorded inputs (devc->recmask) too!
*/
int ess_mixer_set(sb_devc *devc, int dev, int left, int right)
{
if (ess_has_rec_mixer (devc->submodel) && (devc->recmask & (1 << dev))) {
sb_common_mixer_set (devc, dev + ES_REC_MIXER_RECDIFF, left, right);
}
return sb_common_mixer_set (devc, dev, left, right);
}
/*
* After a sb_dsp_reset extended register 0xb4 (RECLEV) is reset too. After
* sb_dsp_reset RECLEV has to be restored. This is where ess_mixer_reload
* helps.
*/
void ess_mixer_reload (sb_devc *devc, int dev)
{
int left, right, value;
value = devc->levels[dev];
left = value & 0x000000ff;
right = (value & 0x0000ff00) >> 8;
sb_common_mixer_set(devc, dev, left, right);
}
static int es_rec_set_recmask(sb_devc * devc, int mask)
{
int i, i_mask, cur_mask, diff_mask;
int value, left, right;
#ifdef FKS_LOGGING
printk (KERN_INFO "FKS: es_rec_set_recmask mask = %x\n", mask);
#endif
/*
* Changing the recmask on an ESS chip with recording mixer means:
* (1) Find the differences
* (2) For "turned-on" inputs: make the recording level the playback level
* (3) For "turned-off" inputs: make the recording level zero
*/
cur_mask = devc->recmask;
diff_mask = (cur_mask ^ mask);
for (i = 0; i < 32; i++) {
i_mask = (1 << i);
if (diff_mask & i_mask) { /* Difference? (1) */
if (mask & i_mask) { /* Turn it on (2) */
value = devc->levels[i];
left = value & 0x000000ff;
right = (value & 0x0000ff00) >> 8;
} else { /* Turn it off (3) */
left = 0;
right = 0;
}
sb_common_mixer_set(devc, i + ES_REC_MIXER_RECDIFF, left, right);
}
}
return mask;
}
int ess_set_recmask(sb_devc * devc, int *mask)
{
/* This applies to ESS chips with record mixers only! */
if (ess_has_rec_mixer (devc->submodel)) {
*mask = es_rec_set_recmask (devc, *mask);
return 1; /* Applied */
} else {
return 0; /* Not applied */
}
}
/*
* ess_mixer_reset must be called from sb_mixer_reset
*/
int ess_mixer_reset (sb_devc * devc)
{
/*
* Separate actions for ESS chips with a record mixer:
*/
if (ess_has_rec_mixer (devc->submodel)) {
switch (devc->submodel) {
case SUBMDL_ES1887:
/*
* Separate actions for ES1887:
* Change registers 7a and 1c to make the record mixer the
* actual recording source.
*/
ess_chgmixer(devc, 0x7a, 0x18, 0x08);
ess_chgmixer(devc, 0x1c, 0x07, 0x07);
break;
};
/*
* Call set_recmask for proper initialization
*/
devc->recmask = devc->supported_rec_devices;
es_rec_set_recmask(devc, 0);
devc->recmask = 0;
return 1; /* We took care of recmask. */
} else {
return 0; /* We didn't take care; caller do it */
}
}
/****************************************************************************
* *
* ESS midi *
* *
****************************************************************************/
/*
* FKS: IRQ may be shared. Hm. And if so? Then What?
*/
int ess_midi_init(sb_devc * devc, struct address_info *hw_config)
{
unsigned char cfg, tmp;
cfg = ess_getmixer (devc, 0x40) & 0x03;
if (devc->submodel < 8) {
ess_setmixer (devc, 0x40, cfg | 0x03); /* Enable OPL3 & joystick */
return 0; /* ES688 doesn't support MPU401 mode */
}
tmp = (hw_config->io_base & 0x0f0) >> 4;
if (tmp > 3) {
ess_setmixer (devc, 0x40, cfg);
return 0;
}
cfg |= tmp << 3;
tmp = 1; /* MPU enabled without interrupts */
/* May be shared: if so the value is -ve */
switch (abs(hw_config->irq)) {
case 9:
tmp = 0x4;
break;
case 5:
tmp = 0x5;
break;
case 7:
tmp = 0x6;
break;
case 10:
tmp = 0x7;
break;
default:
return 0;
}
cfg |= tmp << 5;
ess_setmixer (devc, 0x40, cfg | 0x03);
return 1;
}
| gpl-2.0 |
Haxynox/android_kernel_samsung_smdk4412 | fs/dlm/netlink.c | 8365 | 2937 | /*
* Copyright (C) 2007 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License v.2.
*/
#include <net/genetlink.h>
#include <linux/dlm.h>
#include <linux/dlm_netlink.h>
#include <linux/gfp.h>
#include "dlm_internal.h"
static uint32_t dlm_nl_seqnum;
static uint32_t listener_nlpid;
static struct genl_family family = {
.id = GENL_ID_GENERATE,
.name = DLM_GENL_NAME,
.version = DLM_GENL_VERSION,
};
static int prepare_data(u8 cmd, struct sk_buff **skbp, size_t size)
{
struct sk_buff *skb;
void *data;
skb = genlmsg_new(size, GFP_NOFS);
if (!skb)
return -ENOMEM;
/* add the message headers */
data = genlmsg_put(skb, 0, dlm_nl_seqnum++, &family, 0, cmd);
if (!data) {
nlmsg_free(skb);
return -EINVAL;
}
*skbp = skb;
return 0;
}
static struct dlm_lock_data *mk_data(struct sk_buff *skb)
{
struct nlattr *ret;
ret = nla_reserve(skb, DLM_TYPE_LOCK, sizeof(struct dlm_lock_data));
if (!ret)
return NULL;
return nla_data(ret);
}
static int send_data(struct sk_buff *skb)
{
struct genlmsghdr *genlhdr = nlmsg_data((struct nlmsghdr *)skb->data);
void *data = genlmsg_data(genlhdr);
int rv;
rv = genlmsg_end(skb, data);
if (rv < 0) {
nlmsg_free(skb);
return rv;
}
return genlmsg_unicast(&init_net, skb, listener_nlpid);
}
static int user_cmd(struct sk_buff *skb, struct genl_info *info)
{
listener_nlpid = info->snd_pid;
printk("user_cmd nlpid %u\n", listener_nlpid);
return 0;
}
static struct genl_ops dlm_nl_ops = {
.cmd = DLM_CMD_HELLO,
.doit = user_cmd,
};
int __init dlm_netlink_init(void)
{
return genl_register_family_with_ops(&family, &dlm_nl_ops, 1);
}
void dlm_netlink_exit(void)
{
genl_unregister_family(&family);
}
static void fill_data(struct dlm_lock_data *data, struct dlm_lkb *lkb)
{
struct dlm_rsb *r = lkb->lkb_resource;
memset(data, 0, sizeof(struct dlm_lock_data));
data->version = DLM_LOCK_DATA_VERSION;
data->nodeid = lkb->lkb_nodeid;
data->ownpid = lkb->lkb_ownpid;
data->id = lkb->lkb_id;
data->remid = lkb->lkb_remid;
data->status = lkb->lkb_status;
data->grmode = lkb->lkb_grmode;
data->rqmode = lkb->lkb_rqmode;
if (lkb->lkb_ua)
data->xid = lkb->lkb_ua->xid;
if (r) {
data->lockspace_id = r->res_ls->ls_global_id;
data->resource_namelen = r->res_length;
memcpy(data->resource_name, r->res_name, r->res_length);
}
}
void dlm_timeout_warn(struct dlm_lkb *lkb)
{
struct sk_buff *uninitialized_var(send_skb);
struct dlm_lock_data *data;
size_t size;
int rv;
size = nla_total_size(sizeof(struct dlm_lock_data)) +
nla_total_size(0); /* why this? */
rv = prepare_data(DLM_CMD_TIMEOUT, &send_skb, size);
if (rv < 0)
return;
data = mk_data(send_skb);
if (!data) {
nlmsg_free(send_skb);
return;
}
fill_data(data, lkb);
send_data(send_skb);
}
| gpl-2.0 |
AK-Kernel/AK-OnePone | arch/parisc/math-emu/decode_exc.c | 9901 | 11624 | /*
* Linux/PA-RISC Project (http://www.parisc-linux.org/)
*
* Floating-point emulation code
* Copyright (C) 2001 Hewlett-Packard (Paul Bame) <bame@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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
*/
/*
* BEGIN_DESC
*
* File:
* @(#) pa/fp/decode_exc.c $ Revision: $
*
* Purpose:
* <<please update with a synopsis of the functionality provided by this file>>
*
* External Interfaces:
* <<the following list was autogenerated, please review>>
* decode_fpu(Fpu_register, trap_counts)
*
* Internal Interfaces:
* <<please update>>
*
* Theory:
* <<please update with a overview of the operation of this file>>
*
* END_DESC
*/
#include <linux/kernel.h>
#include "float.h"
#include "sgl_float.h"
#include "dbl_float.h"
#include "cnv_float.h"
/* #include "types.h" */
#include <asm/signal.h>
#include <asm/siginfo.h>
/* #include <machine/sys/mdep_private.h> */
#undef Fpustatus_register
#define Fpustatus_register Fpu_register[0]
/* General definitions */
#define DOESTRAP 1
#define NOTRAP 0
#define SIGNALCODE(signal, code) ((signal) << 24 | (code))
#define copropbit 1<<31-2 /* bit position 2 */
#define opclass 9 /* bits 21 & 22 */
#define fmt 11 /* bits 19 & 20 */
#define df 13 /* bits 17 & 18 */
#define twobits 3 /* mask low-order 2 bits */
#define fivebits 31 /* mask low-order 5 bits */
#define MAX_EXCP_REG 7 /* number of excpeption registers to check */
/* Exception register definitions */
#define Excp_type(index) Exceptiontype(Fpu_register[index])
#define Excp_instr(index) Instructionfield(Fpu_register[index])
#define Clear_excp_register(index) Allexception(Fpu_register[index]) = 0
#define Excp_format() \
(current_ir >> ((current_ir>>opclass & twobits)==1 ? df : fmt) & twobits)
/* Miscellaneous definitions */
#define Fpu_sgl(index) Fpu_register[index*2]
#define Fpu_dblp1(index) Fpu_register[index*2]
#define Fpu_dblp2(index) Fpu_register[(index*2)+1]
#define Fpu_quadp1(index) Fpu_register[index*2]
#define Fpu_quadp2(index) Fpu_register[(index*2)+1]
#define Fpu_quadp3(index) Fpu_register[(index*2)+2]
#define Fpu_quadp4(index) Fpu_register[(index*2)+3]
/* Single precision floating-point definitions */
#ifndef Sgl_decrement
# define Sgl_decrement(sgl_value) Sall(sgl_value)--
#endif
/* Double precision floating-point definitions */
#ifndef Dbl_decrement
# define Dbl_decrement(dbl_valuep1,dbl_valuep2) \
if ((Dallp2(dbl_valuep2)--) == 0) Dallp1(dbl_valuep1)--
#endif
#define update_trap_counts(Fpu_register, aflags, bflags, trap_counts) { \
aflags=(Fpu_register[0])>>27; /* assumes zero fill. 32 bit */ \
Fpu_register[0] |= bflags; \
}
u_int
decode_fpu(unsigned int Fpu_register[], unsigned int trap_counts[])
{
unsigned int current_ir, excp;
int target, exception_index = 1;
boolean inexact;
unsigned int aflags;
unsigned int bflags;
unsigned int excptype;
/* Keep stats on how many floating point exceptions (based on type)
* that happen. Want to keep this overhead low, but still provide
* some information to the customer. All exits from this routine
* need to restore Fpu_register[0]
*/
bflags=(Fpu_register[0] & 0xf8000000);
Fpu_register[0] &= 0x07ffffff;
/* exception_index is used to index the exception register queue. It
* always points at the last register that contains a valid exception. A
* zero value implies no exceptions (also the initialized value). Setting
* the T-bit resets the exception_index to zero.
*/
/*
* Check for reserved-op exception. A reserved-op exception does not
* set any exception registers nor does it set the T-bit. If the T-bit
* is not set then a reserved-op exception occurred.
*
* At some point, we may want to report reserved op exceptions as
* illegal instructions.
*/
if (!Is_tbit_set()) {
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
return SIGNALCODE(SIGILL, ILL_COPROC);
}
/*
* Is a coprocessor op.
*
* Now we need to determine what type of exception occurred.
*/
for (exception_index=1; exception_index<=MAX_EXCP_REG; exception_index++) {
current_ir = Excp_instr(exception_index);
/*
* On PA89: there are 5 different unimplemented exception
* codes: 0x1, 0x9, 0xb, 0x3, and 0x23. PA-RISC 2.0 adds
* another, 0x2b. Only these have the low order bit set.
*/
excptype = Excp_type(exception_index);
if (excptype & UNIMPLEMENTEDEXCEPTION) {
/*
* Clear T-bit and exception register so that
* we can tell if a trap really occurs while
* emulating the instruction.
*/
Clear_tbit();
Clear_excp_register(exception_index);
/*
* Now emulate this instruction. If a trap occurs,
* fpudispatch will return a non-zero number
*/
excp = fpudispatch(current_ir,excptype,0,Fpu_register);
/* accumulate the status flags, don't lose them as in hpux */
if (excp) {
/*
* We now need to make sure that the T-bit and the
* exception register contain the correct values
* before continuing.
*/
/*
* Set t-bit since it might still be needed for a
* subsequent real trap (I don't understand fully -PB)
*/
Set_tbit();
/* some of the following code uses
* Excp_type(exception_index) so fix that up */
Set_exceptiontype_and_instr_field(excp,current_ir,
Fpu_register[exception_index]);
if (excp == UNIMPLEMENTEDEXCEPTION) {
/*
* it is really unimplemented, so restore the
* TIMEX extended unimplemented exception code
*/
excp = excptype;
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
return SIGNALCODE(SIGILL, ILL_COPROC);
}
/* some of the following code uses excptype, so
* fix that up too */
excptype = excp;
}
/* handle exceptions other than the real UNIMPLIMENTED the
* same way as if the hardware had caused them */
if (excp == NOEXCEPTION)
/* For now use 'break', should technically be 'continue' */
break;
}
/*
* In PA89, the underflow exception has been extended to encode
* additional information. The exception looks like pp01x0,
* where x is 1 if inexact and pp represent the inexact bit (I)
* and the round away bit (RA)
*/
if (excptype & UNDERFLOWEXCEPTION) {
/* check for underflow trap enabled */
if (Is_underflowtrap_enabled()) {
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTUND);
} else {
/*
* Isn't a real trap; we need to
* return the default value.
*/
target = current_ir & fivebits;
#ifndef lint
if (Ibit(Fpu_register[exception_index])) inexact = TRUE;
else inexact = FALSE;
#endif
switch (Excp_format()) {
case SGL:
/*
* If ra (round-away) is set, will
* want to undo the rounding done
* by the hardware.
*/
if (Rabit(Fpu_register[exception_index]))
Sgl_decrement(Fpu_sgl(target));
/* now denormalize */
sgl_denormalize(&Fpu_sgl(target),&inexact,Rounding_mode());
break;
case DBL:
/*
* If ra (round-away) is set, will
* want to undo the rounding done
* by the hardware.
*/
if (Rabit(Fpu_register[exception_index]))
Dbl_decrement(Fpu_dblp1(target),Fpu_dblp2(target));
/* now denormalize */
dbl_denormalize(&Fpu_dblp1(target),&Fpu_dblp2(target),
&inexact,Rounding_mode());
break;
}
if (inexact) Set_underflowflag();
/*
* Underflow can generate an inexact
* exception. If inexact trap is enabled,
* want to do an inexact trap, otherwise
* set inexact flag.
*/
if (inexact && Is_inexacttrap_enabled()) {
/*
* Set exception field of exception register
* to inexact, parm field to zero.
* Underflow bit should be cleared.
*/
Set_exceptiontype(Fpu_register[exception_index],
INEXACTEXCEPTION);
Set_parmfield(Fpu_register[exception_index],0);
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTRES);
}
else {
/*
* Exception register needs to be cleared.
* Inexact flag needs to be set if inexact.
*/
Clear_excp_register(exception_index);
if (inexact) Set_inexactflag();
}
}
continue;
}
switch(Excp_type(exception_index)) {
case OVERFLOWEXCEPTION:
case OVERFLOWEXCEPTION | INEXACTEXCEPTION:
/* check for overflow trap enabled */
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
if (Is_overflowtrap_enabled()) {
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTOVF);
} else {
/*
* Isn't a real trap; we need to
* return the default value.
*/
target = current_ir & fivebits;
switch (Excp_format()) {
case SGL:
Sgl_setoverflow(Fpu_sgl(target));
break;
case DBL:
Dbl_setoverflow(Fpu_dblp1(target),Fpu_dblp2(target));
break;
}
Set_overflowflag();
/*
* Overflow always generates an inexact
* exception. If inexact trap is enabled,
* want to do an inexact trap, otherwise
* set inexact flag.
*/
if (Is_inexacttrap_enabled()) {
/*
* Set exception field of exception
* register to inexact. Overflow
* bit should be cleared.
*/
Set_exceptiontype(Fpu_register[exception_index],
INEXACTEXCEPTION);
update_trap_counts(Fpu_register, aflags, bflags,
trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTRES);
}
else {
/*
* Exception register needs to be cleared.
* Inexact flag needs to be set.
*/
Clear_excp_register(exception_index);
Set_inexactflag();
}
}
break;
case INVALIDEXCEPTION:
case OPC_2E_INVALIDEXCEPTION:
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTINV);
case DIVISIONBYZEROEXCEPTION:
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
Clear_excp_register(exception_index);
return SIGNALCODE(SIGFPE, FPE_FLTDIV);
case INEXACTEXCEPTION:
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
return SIGNALCODE(SIGFPE, FPE_FLTRES);
default:
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
printk("%s(%d) Unknown FPU exception 0x%x\n", __FILE__,
__LINE__, Excp_type(exception_index));
return SIGNALCODE(SIGILL, ILL_COPROC);
case NOEXCEPTION: /* no exception */
/*
* Clear exception register in case
* other fields are non-zero.
*/
Clear_excp_register(exception_index);
break;
}
}
/*
* No real exceptions occurred.
*/
Clear_tbit();
update_trap_counts(Fpu_register, aflags, bflags, trap_counts);
return(NOTRAP);
}
| gpl-2.0 |
supersonicninja/L01FJBKERNEL | security/keys/encrypted-keys/ecryptfs_format.c | 10413 | 2628 | /*
* ecryptfs_format.c: helper functions for the encrypted key type
*
* Copyright (C) 2006 International Business Machines Corp.
* Copyright (C) 2010 Politecnico di Torino, Italy
* TORSEC group -- http://security.polito.it
*
* Authors:
* Michael A. Halcrow <mahalcro@us.ibm.com>
* Tyler Hicks <tyhicks@ou.edu>
* Roberto Sassu <roberto.sassu@polito.it>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*/
#include <linux/module.h>
#include "ecryptfs_format.h"
u8 *ecryptfs_get_auth_tok_key(struct ecryptfs_auth_tok *auth_tok)
{
return auth_tok->token.password.session_key_encryption_key;
}
EXPORT_SYMBOL(ecryptfs_get_auth_tok_key);
/*
* ecryptfs_get_versions()
*
* Source code taken from the software 'ecryptfs-utils' version 83.
*
*/
void ecryptfs_get_versions(int *major, int *minor, int *file_version)
{
*major = ECRYPTFS_VERSION_MAJOR;
*minor = ECRYPTFS_VERSION_MINOR;
if (file_version)
*file_version = ECRYPTFS_SUPPORTED_FILE_VERSION;
}
EXPORT_SYMBOL(ecryptfs_get_versions);
/*
* ecryptfs_fill_auth_tok - fill the ecryptfs_auth_tok structure
*
* Fill the ecryptfs_auth_tok structure with required ecryptfs data.
* The source code is inspired to the original function generate_payload()
* shipped with the software 'ecryptfs-utils' version 83.
*
*/
int ecryptfs_fill_auth_tok(struct ecryptfs_auth_tok *auth_tok,
const char *key_desc)
{
int major, minor;
ecryptfs_get_versions(&major, &minor, NULL);
auth_tok->version = (((uint16_t)(major << 8) & 0xFF00)
| ((uint16_t)minor & 0x00FF));
auth_tok->token_type = ECRYPTFS_PASSWORD;
strncpy((char *)auth_tok->token.password.signature, key_desc,
ECRYPTFS_PASSWORD_SIG_SIZE);
auth_tok->token.password.session_key_encryption_key_bytes =
ECRYPTFS_MAX_KEY_BYTES;
/*
* Removed auth_tok->token.password.salt and
* auth_tok->token.password.session_key_encryption_key
* initialization from the original code
*/
/* TODO: Make the hash parameterizable via policy */
auth_tok->token.password.flags |=
ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET;
/* The kernel code will encrypt the session key. */
auth_tok->session_key.encrypted_key[0] = 0;
auth_tok->session_key.encrypted_key_size = 0;
/* Default; subject to change by kernel eCryptfs */
auth_tok->token.password.hash_algo = PGP_DIGEST_ALGO_SHA512;
auth_tok->token.password.flags &= ~(ECRYPTFS_PERSISTENT_PASSWORD);
return 0;
}
EXPORT_SYMBOL(ecryptfs_fill_auth_tok);
MODULE_LICENSE("GPL");
| gpl-2.0 |
iains/darwin-gcc-5 | gcc/testsuite/gfortran.dg/boz_11.f90 | 174 | 1214 | ! { dg-do run }
!
program test0
implicit none
real, parameter :: &
r = transfer(int(b'01000000001010010101001111111101',kind=4),0.)
complex, parameter :: z = r * (0, 1.)
real(kind=8), parameter :: rd = dble(b'00000000000000000000000000000000&
&01000000001010010101001111111101')
complex(kind=8), parameter :: zd = (0._8, 1._8) * rd
integer :: x = 0
if (cmplx(b'01000000001010010101001111111101',x,4) /= r) call abort
if (cmplx(x,b'01000000001010010101001111111101',4) /= z) call abort
if (complex(b'01000000001010010101001111111101',0) /= r) call abort
if (complex(0,b'01000000001010010101001111111101') /= z) call abort
!if (cmplx(b'00000000000000000000000000000000&
! &01000000001010010101001111111101',x,8) /= rd) call abort
!if (cmplx(x,b'00000000000000000000000000000000&
! &01000000001010010101001111111101',8) /= zd) call abort
!if (dcmplx(b'00000000000000000000000000000000&
! &01000000001010010101001111111101',x) /= rd) call abort
!if (dcmplx(x,b'00000000000000000000000000000000&
! &01000000001010010101001111111101') /= zd) call abort
end program test0
| gpl-2.0 |
jaderhs/fuse-kernel | drivers/mmc/core/sdio.c | 174 | 26984 | /*
* linux/drivers/mmc/sdio.c
*
* Copyright 2006-2007 Pierre Ossman
*
* 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/err.h>
#include <linux/pm_runtime.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#include "core.h"
#include "bus.h"
#include "sd.h"
#include "sdio_bus.h"
#include "mmc_ops.h"
#include "sd_ops.h"
#include "sdio_ops.h"
#include "sdio_cis.h"
static int sdio_read_fbr(struct sdio_func *func)
{
int ret;
unsigned char data;
if (mmc_card_nonstd_func_interface(func->card)) {
func->class = SDIO_CLASS_NONE;
return 0;
}
ret = mmc_io_rw_direct(func->card, 0, 0,
SDIO_FBR_BASE(func->num) + SDIO_FBR_STD_IF, 0, &data);
if (ret)
goto out;
data &= 0x0f;
if (data == 0x0f) {
ret = mmc_io_rw_direct(func->card, 0, 0,
SDIO_FBR_BASE(func->num) + SDIO_FBR_STD_IF_EXT, 0, &data);
if (ret)
goto out;
}
func->class = data;
out:
return ret;
}
static int sdio_init_func(struct mmc_card *card, unsigned int fn)
{
int ret;
struct sdio_func *func;
BUG_ON(fn > SDIO_MAX_FUNCS);
func = sdio_alloc_func(card);
if (IS_ERR(func))
return PTR_ERR(func);
func->num = fn;
if (!(card->quirks & MMC_QUIRK_NONSTD_SDIO)) {
ret = sdio_read_fbr(func);
if (ret)
goto fail;
ret = sdio_read_func_cis(func);
if (ret)
goto fail;
} else {
func->vendor = func->card->cis.vendor;
func->device = func->card->cis.device;
func->max_blksize = func->card->cis.blksize;
}
card->sdio_func[fn - 1] = func;
return 0;
fail:
/*
* It is okay to remove the function here even though we hold
* the host lock as we haven't registered the device yet.
*/
sdio_remove_func(func);
return ret;
}
static int sdio_read_cccr(struct mmc_card *card, u32 ocr)
{
int ret;
int cccr_vsn;
int uhs = ocr & R4_18V_PRESENT;
unsigned char data;
unsigned char speed;
memset(&card->cccr, 0, sizeof(struct sdio_cccr));
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_CCCR, 0, &data);
if (ret)
goto out;
cccr_vsn = data & 0x0f;
if (cccr_vsn > SDIO_CCCR_REV_3_00) {
pr_err("%s: unrecognised CCCR structure version %d\n",
mmc_hostname(card->host), cccr_vsn);
return -EINVAL;
}
card->cccr.sdio_vsn = (data & 0xf0) >> 4;
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_CAPS, 0, &data);
if (ret)
goto out;
if (data & SDIO_CCCR_CAP_SMB)
card->cccr.multi_block = 1;
if (data & SDIO_CCCR_CAP_LSC)
card->cccr.low_speed = 1;
if (data & SDIO_CCCR_CAP_4BLS)
card->cccr.wide_bus = 1;
if (cccr_vsn >= SDIO_CCCR_REV_1_10) {
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_POWER, 0, &data);
if (ret)
goto out;
if (data & SDIO_POWER_SMPC)
card->cccr.high_power = 1;
}
if (cccr_vsn >= SDIO_CCCR_REV_1_20) {
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_SPEED, 0, &speed);
if (ret)
goto out;
card->scr.sda_spec3 = 0;
card->sw_caps.sd3_bus_mode = 0;
card->sw_caps.sd3_drv_type = 0;
if (cccr_vsn >= SDIO_CCCR_REV_3_00 && uhs) {
card->scr.sda_spec3 = 1;
ret = mmc_io_rw_direct(card, 0, 0,
SDIO_CCCR_UHS, 0, &data);
if (ret)
goto out;
if (mmc_host_uhs(card->host)) {
if (data & SDIO_UHS_DDR50)
card->sw_caps.sd3_bus_mode
|= SD_MODE_UHS_DDR50;
if (data & SDIO_UHS_SDR50)
card->sw_caps.sd3_bus_mode
|= SD_MODE_UHS_SDR50;
if (data & SDIO_UHS_SDR104)
card->sw_caps.sd3_bus_mode
|= SD_MODE_UHS_SDR104;
}
ret = mmc_io_rw_direct(card, 0, 0,
SDIO_CCCR_DRIVE_STRENGTH, 0, &data);
if (ret)
goto out;
if (data & SDIO_DRIVE_SDTA)
card->sw_caps.sd3_drv_type |= SD_DRIVER_TYPE_A;
if (data & SDIO_DRIVE_SDTC)
card->sw_caps.sd3_drv_type |= SD_DRIVER_TYPE_C;
if (data & SDIO_DRIVE_SDTD)
card->sw_caps.sd3_drv_type |= SD_DRIVER_TYPE_D;
}
/* if no uhs mode ensure we check for high speed */
if (!card->sw_caps.sd3_bus_mode) {
if (speed & SDIO_SPEED_SHS) {
card->cccr.high_speed = 1;
card->sw_caps.hs_max_dtr = 50000000;
} else {
card->cccr.high_speed = 0;
card->sw_caps.hs_max_dtr = 25000000;
}
}
}
out:
return ret;
}
static int sdio_enable_wide(struct mmc_card *card)
{
int ret;
u8 ctrl;
if (!(card->host->caps & MMC_CAP_4_BIT_DATA))
return 0;
if (card->cccr.low_speed && !card->cccr.wide_bus)
return 0;
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_IF, 0, &ctrl);
if (ret)
return ret;
if ((ctrl & SDIO_BUS_WIDTH_MASK) == SDIO_BUS_WIDTH_RESERVED)
pr_warn("%s: SDIO_CCCR_IF is invalid: 0x%02x\n",
mmc_hostname(card->host), ctrl);
/* set as 4-bit bus width */
ctrl &= ~SDIO_BUS_WIDTH_MASK;
ctrl |= SDIO_BUS_WIDTH_4BIT;
ret = mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_IF, ctrl, NULL);
if (ret)
return ret;
return 1;
}
/*
* If desired, disconnect the pull-up resistor on CD/DAT[3] (pin 1)
* of the card. This may be required on certain setups of boards,
* controllers and embedded sdio device which do not need the card's
* pull-up. As a result, card detection is disabled and power is saved.
*/
static int sdio_disable_cd(struct mmc_card *card)
{
int ret;
u8 ctrl;
if (!mmc_card_disable_cd(card))
return 0;
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_IF, 0, &ctrl);
if (ret)
return ret;
ctrl |= SDIO_BUS_CD_DISABLE;
return mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_IF, ctrl, NULL);
}
/*
* Devices that remain active during a system suspend are
* put back into 1-bit mode.
*/
static int sdio_disable_wide(struct mmc_card *card)
{
int ret;
u8 ctrl;
if (!(card->host->caps & MMC_CAP_4_BIT_DATA))
return 0;
if (card->cccr.low_speed && !card->cccr.wide_bus)
return 0;
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_IF, 0, &ctrl);
if (ret)
return ret;
if (!(ctrl & SDIO_BUS_WIDTH_4BIT))
return 0;
ctrl &= ~SDIO_BUS_WIDTH_4BIT;
ctrl |= SDIO_BUS_ASYNC_INT;
ret = mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_IF, ctrl, NULL);
if (ret)
return ret;
mmc_set_bus_width(card->host, MMC_BUS_WIDTH_1);
return 0;
}
static int sdio_enable_4bit_bus(struct mmc_card *card)
{
int err;
if (card->type == MMC_TYPE_SDIO)
err = sdio_enable_wide(card);
else if ((card->host->caps & MMC_CAP_4_BIT_DATA) &&
(card->scr.bus_widths & SD_SCR_BUS_WIDTH_4)) {
err = mmc_app_set_bus_width(card, MMC_BUS_WIDTH_4);
if (err)
return err;
err = sdio_enable_wide(card);
if (err <= 0)
mmc_app_set_bus_width(card, MMC_BUS_WIDTH_1);
} else
return 0;
if (err > 0) {
mmc_set_bus_width(card->host, MMC_BUS_WIDTH_4);
err = 0;
}
return err;
}
/*
* Test if the card supports high-speed mode and, if so, switch to it.
*/
static int mmc_sdio_switch_hs(struct mmc_card *card, int enable)
{
int ret;
u8 speed;
if (!(card->host->caps & MMC_CAP_SD_HIGHSPEED))
return 0;
if (!card->cccr.high_speed)
return 0;
ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_SPEED, 0, &speed);
if (ret)
return ret;
if (enable)
speed |= SDIO_SPEED_EHS;
else
speed &= ~SDIO_SPEED_EHS;
ret = mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_SPEED, speed, NULL);
if (ret)
return ret;
return 1;
}
/*
* Enable SDIO/combo card's high-speed mode. Return 0/1 if [not]supported.
*/
static int sdio_enable_hs(struct mmc_card *card)
{
int ret;
ret = mmc_sdio_switch_hs(card, true);
if (ret <= 0 || card->type == MMC_TYPE_SDIO)
return ret;
ret = mmc_sd_switch_hs(card);
if (ret <= 0)
mmc_sdio_switch_hs(card, false);
return ret;
}
static unsigned mmc_sdio_get_max_clock(struct mmc_card *card)
{
unsigned max_dtr;
if (mmc_card_hs(card)) {
/*
* The SDIO specification doesn't mention how
* the CIS transfer speed register relates to
* high-speed, but it seems that 50 MHz is
* mandatory.
*/
max_dtr = 50000000;
} else {
max_dtr = card->cis.max_dtr;
}
if (card->type == MMC_TYPE_SD_COMBO)
max_dtr = min(max_dtr, mmc_sd_get_max_clock(card));
return max_dtr;
}
static unsigned char host_drive_to_sdio_drive(int host_strength)
{
switch (host_strength) {
case MMC_SET_DRIVER_TYPE_A:
return SDIO_DTSx_SET_TYPE_A;
case MMC_SET_DRIVER_TYPE_B:
return SDIO_DTSx_SET_TYPE_B;
case MMC_SET_DRIVER_TYPE_C:
return SDIO_DTSx_SET_TYPE_C;
case MMC_SET_DRIVER_TYPE_D:
return SDIO_DTSx_SET_TYPE_D;
default:
return SDIO_DTSx_SET_TYPE_B;
}
}
static void sdio_select_driver_type(struct mmc_card *card)
{
int host_drv_type = SD_DRIVER_TYPE_B;
int card_drv_type = SD_DRIVER_TYPE_B;
int drive_strength;
unsigned char card_strength;
int err;
/*
* If the host doesn't support any of the Driver Types A,C or D,
* or there is no board specific handler then default Driver
* Type B is used.
*/
if (!(card->host->caps &
(MMC_CAP_DRIVER_TYPE_A |
MMC_CAP_DRIVER_TYPE_C |
MMC_CAP_DRIVER_TYPE_D)))
return;
if (!card->host->ops->select_drive_strength)
return;
if (card->host->caps & MMC_CAP_DRIVER_TYPE_A)
host_drv_type |= SD_DRIVER_TYPE_A;
if (card->host->caps & MMC_CAP_DRIVER_TYPE_C)
host_drv_type |= SD_DRIVER_TYPE_C;
if (card->host->caps & MMC_CAP_DRIVER_TYPE_D)
host_drv_type |= SD_DRIVER_TYPE_D;
if (card->sw_caps.sd3_drv_type & SD_DRIVER_TYPE_A)
card_drv_type |= SD_DRIVER_TYPE_A;
if (card->sw_caps.sd3_drv_type & SD_DRIVER_TYPE_C)
card_drv_type |= SD_DRIVER_TYPE_C;
if (card->sw_caps.sd3_drv_type & SD_DRIVER_TYPE_D)
card_drv_type |= SD_DRIVER_TYPE_D;
/*
* The drive strength that the hardware can support
* depends on the board design. Pass the appropriate
* information and let the hardware specific code
* return what is possible given the options
*/
drive_strength = card->host->ops->select_drive_strength(
card->sw_caps.uhs_max_dtr,
host_drv_type, card_drv_type);
/* if error just use default for drive strength B */
err = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_DRIVE_STRENGTH, 0,
&card_strength);
if (err)
return;
card_strength &= ~(SDIO_DRIVE_DTSx_MASK<<SDIO_DRIVE_DTSx_SHIFT);
card_strength |= host_drive_to_sdio_drive(drive_strength);
err = mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_DRIVE_STRENGTH,
card_strength, NULL);
/* if error default to drive strength B */
if (!err)
mmc_set_driver_type(card->host, drive_strength);
}
static int sdio_set_bus_speed_mode(struct mmc_card *card)
{
unsigned int bus_speed, timing;
int err;
unsigned char speed;
/*
* If the host doesn't support any of the UHS-I modes, fallback on
* default speed.
*/
if (!mmc_host_uhs(card->host))
return 0;
bus_speed = SDIO_SPEED_SDR12;
timing = MMC_TIMING_UHS_SDR12;
if ((card->host->caps & MMC_CAP_UHS_SDR104) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR104)) {
bus_speed = SDIO_SPEED_SDR104;
timing = MMC_TIMING_UHS_SDR104;
card->sw_caps.uhs_max_dtr = UHS_SDR104_MAX_DTR;
card->sd_bus_speed = UHS_SDR104_BUS_SPEED;
} else if ((card->host->caps & MMC_CAP_UHS_DDR50) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_DDR50)) {
bus_speed = SDIO_SPEED_DDR50;
timing = MMC_TIMING_UHS_DDR50;
card->sw_caps.uhs_max_dtr = UHS_DDR50_MAX_DTR;
card->sd_bus_speed = UHS_DDR50_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50)) && (card->sw_caps.sd3_bus_mode &
SD_MODE_UHS_SDR50)) {
bus_speed = SDIO_SPEED_SDR50;
timing = MMC_TIMING_UHS_SDR50;
card->sw_caps.uhs_max_dtr = UHS_SDR50_MAX_DTR;
card->sd_bus_speed = UHS_SDR50_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR25)) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR25)) {
bus_speed = SDIO_SPEED_SDR25;
timing = MMC_TIMING_UHS_SDR25;
card->sw_caps.uhs_max_dtr = UHS_SDR25_MAX_DTR;
card->sd_bus_speed = UHS_SDR25_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR25 |
MMC_CAP_UHS_SDR12)) && (card->sw_caps.sd3_bus_mode &
SD_MODE_UHS_SDR12)) {
bus_speed = SDIO_SPEED_SDR12;
timing = MMC_TIMING_UHS_SDR12;
card->sw_caps.uhs_max_dtr = UHS_SDR12_MAX_DTR;
card->sd_bus_speed = UHS_SDR12_BUS_SPEED;
}
err = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_SPEED, 0, &speed);
if (err)
return err;
speed &= ~SDIO_SPEED_BSS_MASK;
speed |= bus_speed;
err = mmc_io_rw_direct(card, 1, 0, SDIO_CCCR_SPEED, speed, NULL);
if (err)
return err;
if (bus_speed) {
mmc_set_timing(card->host, timing);
mmc_set_clock(card->host, card->sw_caps.uhs_max_dtr);
}
return 0;
}
/*
* UHS-I specific initialization procedure
*/
static int mmc_sdio_init_uhs_card(struct mmc_card *card)
{
int err;
if (!card->scr.sda_spec3)
return 0;
/*
* Switch to wider bus (if supported).
*/
if (card->host->caps & MMC_CAP_4_BIT_DATA)
err = sdio_enable_4bit_bus(card);
/* Set the driver strength for the card */
sdio_select_driver_type(card);
/* Set bus speed mode of the card */
err = sdio_set_bus_speed_mode(card);
if (err)
goto out;
/*
* SPI mode doesn't define CMD19 and tuning is only valid for SDR50 and
* SDR104 mode SD-cards. Note that tuning is mandatory for SDR104.
*/
if (!mmc_host_is_spi(card->host) &&
((card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR50) ||
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR104)))
err = mmc_execute_tuning(card);
out:
return err;
}
/*
* Handle the detection and initialisation of a card.
*
* In the case of a resume, "oldcard" will contain the card
* we're trying to reinitialise.
*/
static int mmc_sdio_init_card(struct mmc_host *host, u32 ocr,
struct mmc_card *oldcard, int powered_resume)
{
struct mmc_card *card;
int err;
int retries = 10;
u32 rocr = 0;
u32 ocr_card = ocr;
BUG_ON(!host);
WARN_ON(!host->claimed);
/* to query card if 1.8V signalling is supported */
if (mmc_host_uhs(host))
ocr |= R4_18V_PRESENT;
try_again:
if (!retries) {
pr_warn("%s: Skipping voltage switch\n", mmc_hostname(host));
ocr &= ~R4_18V_PRESENT;
}
/*
* Inform the card of the voltage
*/
if (!powered_resume) {
err = mmc_send_io_op_cond(host, ocr, &rocr);
if (err)
goto err;
}
/*
* For SPI, enable CRC as appropriate.
*/
if (mmc_host_is_spi(host)) {
err = mmc_spi_set_crc(host, use_spi_crc);
if (err)
goto err;
}
/*
* Allocate card structure.
*/
card = mmc_alloc_card(host, NULL);
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto err;
}
if ((rocr & R4_MEMORY_PRESENT) &&
mmc_sd_get_cid(host, ocr & rocr, card->raw_cid, NULL) == 0) {
card->type = MMC_TYPE_SD_COMBO;
if (oldcard && (oldcard->type != MMC_TYPE_SD_COMBO ||
memcmp(card->raw_cid, oldcard->raw_cid, sizeof(card->raw_cid)) != 0)) {
mmc_remove_card(card);
return -ENOENT;
}
} else {
card->type = MMC_TYPE_SDIO;
if (oldcard && oldcard->type != MMC_TYPE_SDIO) {
mmc_remove_card(card);
return -ENOENT;
}
}
/*
* Call the optional HC's init_card function to handle quirks.
*/
if (host->ops->init_card)
host->ops->init_card(host, card);
/*
* If the host and card support UHS-I mode request the card
* to switch to 1.8V signaling level. No 1.8v signalling if
* UHS mode is not enabled to maintain compatibility and some
* systems that claim 1.8v signalling in fact do not support
* it.
*/
if (!powered_resume && (rocr & ocr & R4_18V_PRESENT)) {
err = mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180,
ocr);
if (err == -EAGAIN) {
sdio_reset(host);
mmc_go_idle(host);
mmc_send_if_cond(host, host->ocr_avail);
mmc_remove_card(card);
retries--;
goto try_again;
} else if (err) {
ocr &= ~R4_18V_PRESENT;
}
err = 0;
} else {
ocr &= ~R4_18V_PRESENT;
}
/*
* For native busses: set card RCA and quit open drain mode.
*/
if (!powered_resume && !mmc_host_is_spi(host)) {
err = mmc_send_relative_addr(host, &card->rca);
if (err)
goto remove;
/*
* Update oldcard with the new RCA received from the SDIO
* device -- we're doing this so that it's updated in the
* "card" struct when oldcard overwrites that later.
*/
if (oldcard)
oldcard->rca = card->rca;
}
/*
* Read CSD, before selecting the card
*/
if (!oldcard && card->type == MMC_TYPE_SD_COMBO) {
err = mmc_sd_get_csd(host, card);
if (err)
return err;
mmc_decode_cid(card);
}
/*
* Select card, as all following commands rely on that.
*/
if (!powered_resume && !mmc_host_is_spi(host)) {
err = mmc_select_card(card);
if (err)
goto remove;
}
if (card->quirks & MMC_QUIRK_NONSTD_SDIO) {
/*
* This is non-standard SDIO device, meaning it doesn't
* have any CIA (Common I/O area) registers present.
* It's host's responsibility to fill cccr and cis
* structures in init_card().
*/
mmc_set_clock(host, card->cis.max_dtr);
if (card->cccr.high_speed) {
mmc_set_timing(card->host, MMC_TIMING_SD_HS);
}
goto finish;
}
/*
* Read the common registers.
*/
err = sdio_read_cccr(card, ocr);
if (err)
goto remove;
/*
* Read the common CIS tuples.
*/
err = sdio_read_common_cis(card);
if (err)
goto remove;
if (oldcard) {
int same = (card->cis.vendor == oldcard->cis.vendor &&
card->cis.device == oldcard->cis.device);
mmc_remove_card(card);
if (!same)
return -ENOENT;
card = oldcard;
}
card->ocr = ocr_card;
mmc_fixup_device(card, NULL);
if (card->type == MMC_TYPE_SD_COMBO) {
err = mmc_sd_setup_card(host, card, oldcard != NULL);
/* handle as SDIO-only card if memory init failed */
if (err) {
mmc_go_idle(host);
if (mmc_host_is_spi(host))
/* should not fail, as it worked previously */
mmc_spi_set_crc(host, use_spi_crc);
card->type = MMC_TYPE_SDIO;
} else
card->dev.type = &sd_type;
}
/*
* If needed, disconnect card detection pull-up resistor.
*/
err = sdio_disable_cd(card);
if (err)
goto remove;
/* Initialization sequence for UHS-I cards */
/* Only if card supports 1.8v and UHS signaling */
if ((ocr & R4_18V_PRESENT) && card->sw_caps.sd3_bus_mode) {
err = mmc_sdio_init_uhs_card(card);
if (err)
goto remove;
} else {
/*
* Switch to high-speed (if supported).
*/
err = sdio_enable_hs(card);
if (err > 0)
mmc_set_timing(card->host, MMC_TIMING_SD_HS);
else if (err)
goto remove;
/*
* Change to the card's maximum speed.
*/
mmc_set_clock(host, mmc_sdio_get_max_clock(card));
/*
* Switch to wider bus (if supported).
*/
err = sdio_enable_4bit_bus(card);
if (err)
goto remove;
}
finish:
if (!oldcard)
host->card = card;
return 0;
remove:
if (!oldcard)
mmc_remove_card(card);
err:
return err;
}
/*
* Host is being removed. Free up the current card.
*/
static void mmc_sdio_remove(struct mmc_host *host)
{
int i;
BUG_ON(!host);
BUG_ON(!host->card);
for (i = 0;i < host->card->sdio_funcs;i++) {
if (host->card->sdio_func[i]) {
sdio_remove_func(host->card->sdio_func[i]);
host->card->sdio_func[i] = NULL;
}
}
mmc_remove_card(host->card);
host->card = NULL;
}
/*
* Card detection - card is alive.
*/
static int mmc_sdio_alive(struct mmc_host *host)
{
return mmc_select_card(host->card);
}
/*
* Card detection callback from host.
*/
static void mmc_sdio_detect(struct mmc_host *host)
{
int err;
BUG_ON(!host);
BUG_ON(!host->card);
/* Make sure card is powered before detecting it */
if (host->caps & MMC_CAP_POWER_OFF_CARD) {
err = pm_runtime_get_sync(&host->card->dev);
if (err < 0) {
pm_runtime_put_noidle(&host->card->dev);
goto out;
}
}
mmc_claim_host(host);
/*
* Just check if our card has been removed.
*/
err = _mmc_detect_card_removed(host);
mmc_release_host(host);
/*
* Tell PM core it's OK to power off the card now.
*
* The _sync variant is used in order to ensure that the card
* is left powered off in case an error occurred, and the card
* is going to be removed.
*
* Since there is no specific reason to believe a new user
* is about to show up at this point, the _sync variant is
* desirable anyway.
*/
if (host->caps & MMC_CAP_POWER_OFF_CARD)
pm_runtime_put_sync(&host->card->dev);
out:
if (err) {
mmc_sdio_remove(host);
mmc_claim_host(host);
mmc_detach_bus(host);
mmc_power_off(host);
mmc_release_host(host);
}
}
/*
* SDIO pre_suspend. We need to suspend all functions separately.
* Therefore all registered functions must have drivers with suspend
* and resume methods. Failing that we simply remove the whole card.
*/
static int mmc_sdio_pre_suspend(struct mmc_host *host)
{
int i, err = 0;
for (i = 0; i < host->card->sdio_funcs; i++) {
struct sdio_func *func = host->card->sdio_func[i];
if (func && sdio_func_present(func) && func->dev.driver) {
const struct dev_pm_ops *pmops = func->dev.driver->pm;
if (!pmops || !pmops->suspend || !pmops->resume) {
/* force removal of entire card in that case */
err = -ENOSYS;
break;
}
}
}
return err;
}
/*
* SDIO suspend. Suspend all functions separately.
*/
static int mmc_sdio_suspend(struct mmc_host *host)
{
if (mmc_card_keep_power(host) && mmc_card_wake_sdio_irq(host)) {
mmc_claim_host(host);
sdio_disable_wide(host->card);
mmc_release_host(host);
}
if (!mmc_card_keep_power(host))
mmc_power_off(host);
return 0;
}
static int mmc_sdio_resume(struct mmc_host *host)
{
int err = 0;
BUG_ON(!host);
BUG_ON(!host->card);
/* Basic card reinitialization. */
mmc_claim_host(host);
/* Restore power if needed */
if (!mmc_card_keep_power(host)) {
mmc_power_up(host, host->card->ocr);
/*
* Tell runtime PM core we just powered up the card,
* since it still believes the card is powered off.
* Note that currently runtime PM is only enabled
* for SDIO cards that are MMC_CAP_POWER_OFF_CARD
*/
if (host->caps & MMC_CAP_POWER_OFF_CARD) {
pm_runtime_disable(&host->card->dev);
pm_runtime_set_active(&host->card->dev);
pm_runtime_enable(&host->card->dev);
}
}
/* No need to reinitialize powered-resumed nonremovable cards */
if (mmc_card_is_removable(host) || !mmc_card_keep_power(host)) {
sdio_reset(host);
mmc_go_idle(host);
mmc_send_if_cond(host, host->card->ocr);
err = mmc_send_io_op_cond(host, 0, NULL);
if (!err)
err = mmc_sdio_init_card(host, host->card->ocr,
host->card,
mmc_card_keep_power(host));
} else if (mmc_card_keep_power(host) && mmc_card_wake_sdio_irq(host)) {
/* We may have switched to 1-bit mode during suspend */
err = sdio_enable_4bit_bus(host->card);
}
if (!err && host->sdio_irqs) {
if (!(host->caps2 & MMC_CAP2_SDIO_IRQ_NOTHREAD)) {
wake_up_process(host->sdio_irq_thread);
} else if (host->caps & MMC_CAP_SDIO_IRQ) {
mmc_host_clk_hold(host);
host->ops->enable_sdio_irq(host, 1);
mmc_host_clk_release(host);
}
}
mmc_release_host(host);
host->pm_flags &= ~MMC_PM_KEEP_POWER;
return err;
}
static int mmc_sdio_power_restore(struct mmc_host *host)
{
int ret;
BUG_ON(!host);
BUG_ON(!host->card);
mmc_claim_host(host);
/*
* Reset the card by performing the same steps that are taken by
* mmc_rescan_try_freq() and mmc_attach_sdio() during a "normal" probe.
*
* sdio_reset() is technically not needed. Having just powered up the
* hardware, it should already be in reset state. However, some
* platforms (such as SD8686 on OLPC) do not instantly cut power,
* meaning that a reset is required when restoring power soon after
* powering off. It is harmless in other cases.
*
* The CMD5 reset (mmc_send_io_op_cond()), according to the SDIO spec,
* is not necessary for non-removable cards. However, it is required
* for OLPC SD8686 (which expects a [CMD5,5,3,7] init sequence), and
* harmless in other situations.
*
*/
sdio_reset(host);
mmc_go_idle(host);
mmc_send_if_cond(host, host->card->ocr);
ret = mmc_send_io_op_cond(host, 0, NULL);
if (ret)
goto out;
ret = mmc_sdio_init_card(host, host->card->ocr, host->card,
mmc_card_keep_power(host));
if (!ret && host->sdio_irqs)
mmc_signal_sdio_irq(host);
out:
mmc_release_host(host);
return ret;
}
static int mmc_sdio_runtime_suspend(struct mmc_host *host)
{
/* No references to the card, cut the power to it. */
mmc_power_off(host);
return 0;
}
static int mmc_sdio_runtime_resume(struct mmc_host *host)
{
/* Restore power and re-initialize. */
mmc_power_up(host, host->card->ocr);
return mmc_sdio_power_restore(host);
}
static const struct mmc_bus_ops mmc_sdio_ops = {
.remove = mmc_sdio_remove,
.detect = mmc_sdio_detect,
.pre_suspend = mmc_sdio_pre_suspend,
.suspend = mmc_sdio_suspend,
.resume = mmc_sdio_resume,
.runtime_suspend = mmc_sdio_runtime_suspend,
.runtime_resume = mmc_sdio_runtime_resume,
.power_restore = mmc_sdio_power_restore,
.alive = mmc_sdio_alive,
};
/*
* Starting point for SDIO card init.
*/
int mmc_attach_sdio(struct mmc_host *host)
{
int err, i, funcs;
u32 ocr, rocr;
struct mmc_card *card;
BUG_ON(!host);
WARN_ON(!host->claimed);
err = mmc_send_io_op_cond(host, 0, &ocr);
if (err)
return err;
mmc_attach_bus(host, &mmc_sdio_ops);
if (host->ocr_avail_sdio)
host->ocr_avail = host->ocr_avail_sdio;
rocr = mmc_select_voltage(host, ocr);
/*
* Can we support the voltage(s) of the card(s)?
*/
if (!rocr) {
err = -EINVAL;
goto err;
}
/*
* Detect and init the card.
*/
err = mmc_sdio_init_card(host, rocr, NULL, 0);
if (err)
goto err;
card = host->card;
/*
* Enable runtime PM only if supported by host+card+board
*/
if (host->caps & MMC_CAP_POWER_OFF_CARD) {
/*
* Let runtime PM core know our card is active
*/
err = pm_runtime_set_active(&card->dev);
if (err)
goto remove;
/*
* Enable runtime PM for this card
*/
pm_runtime_enable(&card->dev);
}
/*
* The number of functions on the card is encoded inside
* the ocr.
*/
funcs = (ocr & 0x70000000) >> 28;
card->sdio_funcs = 0;
/*
* Initialize (but don't add) all present functions.
*/
for (i = 0; i < funcs; i++, card->sdio_funcs++) {
err = sdio_init_func(host->card, i + 1);
if (err)
goto remove;
/*
* Enable Runtime PM for this func (if supported)
*/
if (host->caps & MMC_CAP_POWER_OFF_CARD)
pm_runtime_enable(&card->sdio_func[i]->dev);
}
/*
* First add the card to the driver model...
*/
mmc_release_host(host);
err = mmc_add_card(host->card);
if (err)
goto remove_added;
/*
* ...then the SDIO functions.
*/
for (i = 0;i < funcs;i++) {
err = sdio_add_func(host->card->sdio_func[i]);
if (err)
goto remove_added;
}
mmc_claim_host(host);
return 0;
remove_added:
/* Remove without lock if the device has been added. */
mmc_sdio_remove(host);
mmc_claim_host(host);
remove:
/* And with lock if it hasn't been added. */
mmc_release_host(host);
if (host->card)
mmc_sdio_remove(host);
mmc_claim_host(host);
err:
mmc_detach_bus(host);
pr_err("%s: error %d whilst initialising SDIO card\n",
mmc_hostname(host), err);
return err;
}
| gpl-2.0 |
jongwonk/linux_samsung | arch/microblaze/kernel/dma.c | 430 | 5380 | /*
* Copyright (C) 2009-2010 PetaLogix
* Copyright (C) 2006 Benjamin Herrenschmidt, IBM Corporation
*
* Provide default implementations of the DMA mapping callbacks for
* directly mapped busses.
*/
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/gfp.h>
#include <linux/dma-debug.h>
#include <linux/export.h>
#include <linux/bug.h>
#define NOT_COHERENT_CACHE
static void *dma_direct_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag,
struct dma_attrs *attrs)
{
#ifdef NOT_COHERENT_CACHE
return consistent_alloc(flag, size, dma_handle);
#else
void *ret;
struct page *page;
int node = dev_to_node(dev);
/* ignore region specifiers */
flag &= ~(__GFP_HIGHMEM);
page = alloc_pages_node(node, flag, get_order(size));
if (page == NULL)
return NULL;
ret = page_address(page);
memset(ret, 0, size);
*dma_handle = virt_to_phys(ret);
return ret;
#endif
}
static void dma_direct_free_coherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t dma_handle,
struct dma_attrs *attrs)
{
#ifdef NOT_COHERENT_CACHE
consistent_free(size, vaddr);
#else
free_pages((unsigned long)vaddr, get_order(size));
#endif
}
static int dma_direct_map_sg(struct device *dev, struct scatterlist *sgl,
int nents, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i;
/* FIXME this part of code is untested */
for_each_sg(sgl, sg, nents, i) {
sg->dma_address = sg_phys(sg);
__dma_sync(page_to_phys(sg_page(sg)) + sg->offset,
sg->length, direction);
}
return nents;
}
static int dma_direct_dma_supported(struct device *dev, u64 mask)
{
return 1;
}
static inline dma_addr_t dma_direct_map_page(struct device *dev,
struct page *page,
unsigned long offset,
size_t size,
enum dma_data_direction direction,
struct dma_attrs *attrs)
{
__dma_sync(page_to_phys(page) + offset, size, direction);
return page_to_phys(page) + offset;
}
static inline void dma_direct_unmap_page(struct device *dev,
dma_addr_t dma_address,
size_t size,
enum dma_data_direction direction,
struct dma_attrs *attrs)
{
/* There is not necessary to do cache cleanup
*
* phys_to_virt is here because in __dma_sync_page is __virt_to_phys and
* dma_address is physical address
*/
__dma_sync(dma_address, size, direction);
}
static inline void
dma_direct_sync_single_for_cpu(struct device *dev,
dma_addr_t dma_handle, size_t size,
enum dma_data_direction direction)
{
/*
* It's pointless to flush the cache as the memory segment
* is given to the CPU
*/
if (direction == DMA_FROM_DEVICE)
__dma_sync(dma_handle, size, direction);
}
static inline void
dma_direct_sync_single_for_device(struct device *dev,
dma_addr_t dma_handle, size_t size,
enum dma_data_direction direction)
{
/*
* It's pointless to invalidate the cache if the device isn't
* supposed to write to the relevant region
*/
if (direction == DMA_TO_DEVICE)
__dma_sync(dma_handle, size, direction);
}
static inline void
dma_direct_sync_sg_for_cpu(struct device *dev,
struct scatterlist *sgl, int nents,
enum dma_data_direction direction)
{
struct scatterlist *sg;
int i;
/* FIXME this part of code is untested */
if (direction == DMA_FROM_DEVICE)
for_each_sg(sgl, sg, nents, i)
__dma_sync(sg->dma_address, sg->length, direction);
}
static inline void
dma_direct_sync_sg_for_device(struct device *dev,
struct scatterlist *sgl, int nents,
enum dma_data_direction direction)
{
struct scatterlist *sg;
int i;
/* FIXME this part of code is untested */
if (direction == DMA_TO_DEVICE)
for_each_sg(sgl, sg, nents, i)
__dma_sync(sg->dma_address, sg->length, direction);
}
int dma_direct_mmap_coherent(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t handle, size_t size,
struct dma_attrs *attrs)
{
#ifdef CONFIG_MMU
unsigned long user_count = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
unsigned long off = vma->vm_pgoff;
unsigned long pfn;
if (off >= count || user_count > (count - off))
return -ENXIO;
#ifdef NOT_COHERENT_CACHE
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
pfn = consistent_virt_to_pfn(cpu_addr);
#else
pfn = virt_to_pfn(cpu_addr);
#endif
return remap_pfn_range(vma, vma->vm_start, pfn + off,
vma->vm_end - vma->vm_start, vma->vm_page_prot);
#else
return -ENXIO;
#endif
}
struct dma_map_ops dma_direct_ops = {
.alloc = dma_direct_alloc_coherent,
.free = dma_direct_free_coherent,
.mmap = dma_direct_mmap_coherent,
.map_sg = dma_direct_map_sg,
.dma_supported = dma_direct_dma_supported,
.map_page = dma_direct_map_page,
.unmap_page = dma_direct_unmap_page,
.sync_single_for_cpu = dma_direct_sync_single_for_cpu,
.sync_single_for_device = dma_direct_sync_single_for_device,
.sync_sg_for_cpu = dma_direct_sync_sg_for_cpu,
.sync_sg_for_device = dma_direct_sync_sg_for_device,
};
EXPORT_SYMBOL(dma_direct_ops);
/* Number of entries preallocated for DMA-API debugging */
#define PREALLOC_DMA_DEBUG_ENTRIES (1 << 16)
static int __init dma_init(void)
{
dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
return 0;
}
fs_initcall(dma_init);
| gpl-2.0 |
koalo/linux | drivers/pinctrl/vt8500/pinctrl-wmt.c | 430 | 15965 | /*
* Pinctrl driver for the Wondermedia SoC's
*
* Copyright (c) 2013 Tony Prisk <linux@prisktech.co.nz>
*
* 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.
*/
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include "pinctrl-wmt.h"
static inline void wmt_setbits(struct wmt_pinctrl_data *data, u32 reg,
u32 mask)
{
u32 val;
val = readl_relaxed(data->base + reg);
val |= mask;
writel_relaxed(val, data->base + reg);
}
static inline void wmt_clearbits(struct wmt_pinctrl_data *data, u32 reg,
u32 mask)
{
u32 val;
val = readl_relaxed(data->base + reg);
val &= ~mask;
writel_relaxed(val, data->base + reg);
}
enum wmt_func_sel {
WMT_FSEL_GPIO_IN = 0,
WMT_FSEL_GPIO_OUT = 1,
WMT_FSEL_ALT = 2,
WMT_FSEL_COUNT = 3,
};
static const char * const wmt_functions[WMT_FSEL_COUNT] = {
[WMT_FSEL_GPIO_IN] = "gpio_in",
[WMT_FSEL_GPIO_OUT] = "gpio_out",
[WMT_FSEL_ALT] = "alt",
};
static int wmt_pmx_get_functions_count(struct pinctrl_dev *pctldev)
{
return WMT_FSEL_COUNT;
}
static const char *wmt_pmx_get_function_name(struct pinctrl_dev *pctldev,
unsigned selector)
{
return wmt_functions[selector];
}
static int wmt_pmx_get_function_groups(struct pinctrl_dev *pctldev,
unsigned selector,
const char * const **groups,
unsigned * const num_groups)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
/* every pin does every function */
*groups = data->groups;
*num_groups = data->ngroups;
return 0;
}
static int wmt_set_pinmux(struct wmt_pinctrl_data *data, unsigned func,
unsigned pin)
{
u32 bank = WMT_BANK_FROM_PIN(pin);
u32 bit = WMT_BIT_FROM_PIN(pin);
u32 reg_en = data->banks[bank].reg_en;
u32 reg_dir = data->banks[bank].reg_dir;
if (reg_dir == NO_REG) {
dev_err(data->dev, "pin:%d no direction register defined\n",
pin);
return -EINVAL;
}
/*
* If reg_en == NO_REG, we assume it is a dedicated GPIO and cannot be
* disabled (as on VT8500) and that no alternate function is available.
*/
switch (func) {
case WMT_FSEL_GPIO_IN:
if (reg_en != NO_REG)
wmt_setbits(data, reg_en, BIT(bit));
wmt_clearbits(data, reg_dir, BIT(bit));
break;
case WMT_FSEL_GPIO_OUT:
if (reg_en != NO_REG)
wmt_setbits(data, reg_en, BIT(bit));
wmt_setbits(data, reg_dir, BIT(bit));
break;
case WMT_FSEL_ALT:
if (reg_en == NO_REG) {
dev_err(data->dev, "pin:%d no alt function available\n",
pin);
return -EINVAL;
}
wmt_clearbits(data, reg_en, BIT(bit));
}
return 0;
}
static int wmt_pmx_enable(struct pinctrl_dev *pctldev,
unsigned func_selector,
unsigned group_selector)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
u32 pinnum = data->pins[group_selector].number;
return wmt_set_pinmux(data, func_selector, pinnum);
}
static void wmt_pmx_disable(struct pinctrl_dev *pctldev,
unsigned func_selector,
unsigned group_selector)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
u32 pinnum = data->pins[group_selector].number;
/* disable by setting GPIO_IN */
wmt_set_pinmux(data, WMT_FSEL_GPIO_IN, pinnum);
}
static void wmt_pmx_gpio_disable_free(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range,
unsigned offset)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
/* disable by setting GPIO_IN */
wmt_set_pinmux(data, WMT_FSEL_GPIO_IN, offset);
}
static int wmt_pmx_gpio_set_direction(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range,
unsigned offset,
bool input)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
wmt_set_pinmux(data, (input ? WMT_FSEL_GPIO_IN : WMT_FSEL_GPIO_OUT),
offset);
return 0;
}
static struct pinmux_ops wmt_pinmux_ops = {
.get_functions_count = wmt_pmx_get_functions_count,
.get_function_name = wmt_pmx_get_function_name,
.get_function_groups = wmt_pmx_get_function_groups,
.enable = wmt_pmx_enable,
.disable = wmt_pmx_disable,
.gpio_disable_free = wmt_pmx_gpio_disable_free,
.gpio_set_direction = wmt_pmx_gpio_set_direction,
};
static int wmt_get_groups_count(struct pinctrl_dev *pctldev)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
return data->ngroups;
}
static const char *wmt_get_group_name(struct pinctrl_dev *pctldev,
unsigned selector)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
return data->groups[selector];
}
static int wmt_get_group_pins(struct pinctrl_dev *pctldev,
unsigned selector,
const unsigned **pins,
unsigned *num_pins)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
*pins = &data->pins[selector].number;
*num_pins = 1;
return 0;
}
static int wmt_pctl_find_group_by_pin(struct wmt_pinctrl_data *data, u32 pin)
{
int i;
for (i = 0; i < data->npins; i++) {
if (data->pins[i].number == pin)
return i;
}
return -EINVAL;
}
static int wmt_pctl_dt_node_to_map_func(struct wmt_pinctrl_data *data,
struct device_node *np,
u32 pin, u32 fnum,
struct pinctrl_map **maps)
{
int group;
struct pinctrl_map *map = *maps;
if (fnum >= ARRAY_SIZE(wmt_functions)) {
dev_err(data->dev, "invalid wm,function %d\n", fnum);
return -EINVAL;
}
group = wmt_pctl_find_group_by_pin(data, pin);
if (group < 0) {
dev_err(data->dev, "unable to match pin %d to group\n", pin);
return group;
}
map->type = PIN_MAP_TYPE_MUX_GROUP;
map->data.mux.group = data->groups[group];
map->data.mux.function = wmt_functions[fnum];
(*maps)++;
return 0;
}
static int wmt_pctl_dt_node_to_map_pull(struct wmt_pinctrl_data *data,
struct device_node *np,
u32 pin, u32 pull,
struct pinctrl_map **maps)
{
int group;
unsigned long *configs;
struct pinctrl_map *map = *maps;
if (pull > 2) {
dev_err(data->dev, "invalid wm,pull %d\n", pull);
return -EINVAL;
}
group = wmt_pctl_find_group_by_pin(data, pin);
if (group < 0) {
dev_err(data->dev, "unable to match pin %d to group\n", pin);
return group;
}
configs = kzalloc(sizeof(*configs), GFP_KERNEL);
if (!configs)
return -ENOMEM;
configs[0] = pull;
map->type = PIN_MAP_TYPE_CONFIGS_PIN;
map->data.configs.group_or_pin = data->groups[group];
map->data.configs.configs = configs;
map->data.configs.num_configs = 1;
(*maps)++;
return 0;
}
static void wmt_pctl_dt_free_map(struct pinctrl_dev *pctldev,
struct pinctrl_map *maps,
unsigned num_maps)
{
int i;
for (i = 0; i < num_maps; i++)
if (maps[i].type == PIN_MAP_TYPE_CONFIGS_PIN)
kfree(maps[i].data.configs.configs);
kfree(maps);
}
static int wmt_pctl_dt_node_to_map(struct pinctrl_dev *pctldev,
struct device_node *np,
struct pinctrl_map **map,
unsigned *num_maps)
{
struct pinctrl_map *maps, *cur_map;
struct property *pins, *funcs, *pulls;
u32 pin, func, pull;
int num_pins, num_funcs, num_pulls, maps_per_pin;
int i, err;
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
pins = of_find_property(np, "wm,pins", NULL);
if (!pins) {
dev_err(data->dev, "missing wmt,pins property\n");
return -EINVAL;
}
funcs = of_find_property(np, "wm,function", NULL);
pulls = of_find_property(np, "wm,pull", NULL);
if (!funcs && !pulls) {
dev_err(data->dev, "neither wm,function nor wm,pull specified\n");
return -EINVAL;
}
/*
* The following lines calculate how many values are defined for each
* of the properties.
*/
num_pins = pins->length / sizeof(u32);
num_funcs = funcs ? (funcs->length / sizeof(u32)) : 0;
num_pulls = pulls ? (pulls->length / sizeof(u32)) : 0;
if (num_funcs > 1 && num_funcs != num_pins) {
dev_err(data->dev, "wm,function must have 1 or %d entries\n",
num_pins);
return -EINVAL;
}
if (num_pulls > 1 && num_pulls != num_pins) {
dev_err(data->dev, "wm,pull must have 1 or %d entries\n",
num_pins);
return -EINVAL;
}
maps_per_pin = 0;
if (num_funcs)
maps_per_pin++;
if (num_pulls)
maps_per_pin++;
cur_map = maps = kzalloc(num_pins * maps_per_pin * sizeof(*maps),
GFP_KERNEL);
if (!maps)
return -ENOMEM;
for (i = 0; i < num_pins; i++) {
err = of_property_read_u32_index(np, "wm,pins", i, &pin);
if (err)
goto fail;
if (pin >= (data->nbanks * 32)) {
dev_err(data->dev, "invalid wm,pins value\n");
err = -EINVAL;
goto fail;
}
if (num_funcs) {
err = of_property_read_u32_index(np, "wm,function",
(num_funcs > 1 ? i : 0), &func);
if (err)
goto fail;
err = wmt_pctl_dt_node_to_map_func(data, np, pin, func,
&cur_map);
if (err)
goto fail;
}
if (num_pulls) {
err = of_property_read_u32_index(np, "wm,pull",
(num_pulls > 1 ? i : 0), &pull);
if (err)
goto fail;
err = wmt_pctl_dt_node_to_map_pull(data, np, pin, pull,
&cur_map);
if (err)
goto fail;
}
}
*map = maps;
*num_maps = num_pins * maps_per_pin;
return 0;
/*
* The fail path removes any maps that have been allocated. The fail path is
* only called from code after maps has been kzalloc'd. It is also safe to
* pass 'num_pins * maps_per_pin' as the map count even though we probably
* failed before all the mappings were read as all maps are allocated at once,
* and configs are only allocated for .type = PIN_MAP_TYPE_CONFIGS_PIN - there
* is no failpath where a config can be allocated without .type being set.
*/
fail:
wmt_pctl_dt_free_map(pctldev, maps, num_pins * maps_per_pin);
return err;
}
static struct pinctrl_ops wmt_pctl_ops = {
.get_groups_count = wmt_get_groups_count,
.get_group_name = wmt_get_group_name,
.get_group_pins = wmt_get_group_pins,
.dt_node_to_map = wmt_pctl_dt_node_to_map,
.dt_free_map = wmt_pctl_dt_free_map,
};
static int wmt_pinconf_get(struct pinctrl_dev *pctldev, unsigned pin,
unsigned long *config)
{
return -ENOTSUPP;
}
static int wmt_pinconf_set(struct pinctrl_dev *pctldev, unsigned pin,
unsigned long config)
{
struct wmt_pinctrl_data *data = pinctrl_dev_get_drvdata(pctldev);
enum pin_config_param param = pinconf_to_config_param(config);
u16 arg = pinconf_to_config_argument(config);
u32 bank = WMT_BANK_FROM_PIN(pin);
u32 bit = WMT_BIT_FROM_PIN(pin);
u32 reg_pull_en = data->banks[bank].reg_pull_en;
u32 reg_pull_cfg = data->banks[bank].reg_pull_cfg;
if ((reg_pull_en == NO_REG) || (reg_pull_cfg == NO_REG)) {
dev_err(data->dev, "bias functions not supported on pin %d\n",
pin);
return -EINVAL;
}
if ((param == PIN_CONFIG_BIAS_PULL_DOWN) ||
(param == PIN_CONFIG_BIAS_PULL_UP)) {
if (arg == 0)
param = PIN_CONFIG_BIAS_DISABLE;
}
switch (param) {
case PIN_CONFIG_BIAS_DISABLE:
wmt_clearbits(data, reg_pull_en, BIT(bit));
break;
case PIN_CONFIG_BIAS_PULL_DOWN:
wmt_clearbits(data, reg_pull_cfg, BIT(bit));
wmt_setbits(data, reg_pull_en, BIT(bit));
break;
case PIN_CONFIG_BIAS_PULL_UP:
wmt_setbits(data, reg_pull_cfg, BIT(bit));
wmt_setbits(data, reg_pull_en, BIT(bit));
break;
default:
dev_err(data->dev, "unknown pinconf param\n");
return -EINVAL;
}
return 0;
}
static struct pinconf_ops wmt_pinconf_ops = {
.pin_config_get = wmt_pinconf_get,
.pin_config_set = wmt_pinconf_set,
};
static struct pinctrl_desc wmt_desc = {
.owner = THIS_MODULE,
.name = "pinctrl-wmt",
.pctlops = &wmt_pctl_ops,
.pmxops = &wmt_pinmux_ops,
.confops = &wmt_pinconf_ops,
};
static int wmt_gpio_request(struct gpio_chip *chip, unsigned offset)
{
return pinctrl_request_gpio(chip->base + offset);
}
static void wmt_gpio_free(struct gpio_chip *chip, unsigned offset)
{
pinctrl_free_gpio(chip->base + offset);
}
static int wmt_gpio_get_direction(struct gpio_chip *chip, unsigned offset)
{
struct wmt_pinctrl_data *data = dev_get_drvdata(chip->dev);
u32 bank = WMT_BANK_FROM_PIN(offset);
u32 bit = WMT_BIT_FROM_PIN(offset);
u32 reg_dir = data->banks[bank].reg_dir;
u32 val;
val = readl_relaxed(data->base + reg_dir);
if (val & BIT(bit))
return GPIOF_DIR_OUT;
else
return GPIOF_DIR_IN;
}
static int wmt_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
return pinctrl_gpio_direction_input(chip->base + offset);
}
static int wmt_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
return pinctrl_gpio_direction_output(chip->base + offset);
}
static int wmt_gpio_get_value(struct gpio_chip *chip, unsigned offset)
{
struct wmt_pinctrl_data *data = dev_get_drvdata(chip->dev);
u32 bank = WMT_BANK_FROM_PIN(offset);
u32 bit = WMT_BIT_FROM_PIN(offset);
u32 reg_data_in = data->banks[bank].reg_data_in;
if (reg_data_in == NO_REG) {
dev_err(data->dev, "no data in register defined\n");
return -EINVAL;
}
return !!(readl_relaxed(data->base + reg_data_in) & BIT(bit));
}
static void wmt_gpio_set_value(struct gpio_chip *chip, unsigned offset,
int val)
{
struct wmt_pinctrl_data *data = dev_get_drvdata(chip->dev);
u32 bank = WMT_BANK_FROM_PIN(offset);
u32 bit = WMT_BIT_FROM_PIN(offset);
u32 reg_data_out = data->banks[bank].reg_data_out;
if (reg_data_out == NO_REG) {
dev_err(data->dev, "no data out register defined\n");
return;
}
if (val)
wmt_setbits(data, reg_data_out, BIT(bit));
else
wmt_clearbits(data, reg_data_out, BIT(bit));
}
static struct gpio_chip wmt_gpio_chip = {
.label = "gpio-wmt",
.owner = THIS_MODULE,
.request = wmt_gpio_request,
.free = wmt_gpio_free,
.get_direction = wmt_gpio_get_direction,
.direction_input = wmt_gpio_direction_input,
.direction_output = wmt_gpio_direction_output,
.get = wmt_gpio_get_value,
.set = wmt_gpio_set_value,
.can_sleep = 0,
};
int wmt_pinctrl_probe(struct platform_device *pdev,
struct wmt_pinctrl_data *data)
{
int err;
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
data->base = devm_request_and_ioremap(&pdev->dev, res);
if (!data->base) {
dev_err(&pdev->dev, "failed to map memory resource\n");
return -EBUSY;
}
wmt_desc.pins = data->pins;
wmt_desc.npins = data->npins;
data->gpio_chip = wmt_gpio_chip;
data->gpio_chip.dev = &pdev->dev;
data->gpio_chip.of_node = pdev->dev.of_node;
data->gpio_chip.ngpio = data->nbanks * 32;
platform_set_drvdata(pdev, data);
data->dev = &pdev->dev;
data->pctl_dev = pinctrl_register(&wmt_desc, &pdev->dev, data);
if (!data->pctl_dev) {
dev_err(&pdev->dev, "Failed to register pinctrl\n");
return -EINVAL;
}
err = gpiochip_add(&data->gpio_chip);
if (err) {
dev_err(&pdev->dev, "could not add GPIO chip\n");
goto fail_gpio;
}
err = gpiochip_add_pin_range(&data->gpio_chip, dev_name(data->dev),
0, 0, data->nbanks * 32);
if (err)
goto fail_range;
dev_info(&pdev->dev, "Pin controller initialized\n");
return 0;
fail_range:
if (gpiochip_remove(&data->gpio_chip))
dev_err(&pdev->dev, "failed to remove gpio chip\n");
fail_gpio:
pinctrl_unregister(data->pctl_dev);
return err;
}
int wmt_pinctrl_remove(struct platform_device *pdev)
{
struct wmt_pinctrl_data *data = platform_get_drvdata(pdev);
int err;
err = gpiochip_remove(&data->gpio_chip);
if (err)
dev_err(&pdev->dev, "failed to remove gpio chip\n");
pinctrl_unregister(data->pctl_dev);
return 0;
}
| gpl-2.0 |
allan888/Linux_kernel_asynchronous | drivers/hid/hid-plantronics.c | 430 | 1581 | /*
* Plantronics USB HID Driver
*
* Copyright (c) 2014 JD Cole <jd.cole@plantronics.com>
* Copyright (c) 2014 Terry Junge <terry.junge@plantronics.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 "hid-ids.h"
#include <linux/hid.h>
#include <linux/module.h>
static int plantronics_input_mapping(struct hid_device *hdev,
struct hid_input *hi,
struct hid_field *field,
struct hid_usage *usage,
unsigned long **bit, int *max)
{
if (field->application == HID_CP_CONSUMERCONTROL
&& (usage->hid & HID_USAGE_PAGE) == HID_UP_CONSUMER) {
hid_dbg(hdev, "usage: %08x (appl: %08x) - defaulted\n",
usage->hid, field->application);
return 0;
}
hid_dbg(hdev, "usage: %08x (appl: %08x) - ignored\n",
usage->hid, field->application);
return -1;
}
static const struct hid_device_id plantronics_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_PLANTRONICS, HID_ANY_ID) },
{ }
};
MODULE_DEVICE_TABLE(hid, plantronics_devices);
static struct hid_driver plantronics_driver = {
.name = "plantronics",
.id_table = plantronics_devices,
.input_mapping = plantronics_input_mapping,
};
module_hid_driver(plantronics_driver);
MODULE_AUTHOR("JD Cole <jd.cole@plantronics.com>");
MODULE_AUTHOR("Terry Junge <terry.junge@plantronics.com>");
MODULE_DESCRIPTION("Plantronics USB HID Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
baberthal/linux | arch/powerpc/platforms/cell/interrupt.c | 430 | 10743 | /*
* Cell Internal Interrupt Controller
*
* Copyright (C) 2006 Benjamin Herrenschmidt (benh@kernel.crashing.org)
* IBM, Corp.
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005
*
* Author: Arnd Bergmann <arndb@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.
*
* TODO:
* - Fix various assumptions related to HW CPU numbers vs. linux CPU numbers
* vs node numbers in the setup code
* - Implement proper handling of maxcpus=1/2 (that is, routing of irqs from
* a non-active node to the active node)
*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/kernel_stat.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/prom.h>
#include <asm/ptrace.h>
#include <asm/machdep.h>
#include <asm/cell-regs.h>
#include "interrupt.h"
struct iic {
struct cbe_iic_thread_regs __iomem *regs;
u8 target_id;
u8 eoi_stack[16];
int eoi_ptr;
struct device_node *node;
};
static DEFINE_PER_CPU(struct iic, cpu_iic);
#define IIC_NODE_COUNT 2
static struct irq_domain *iic_host;
/* Convert between "pending" bits and hw irq number */
static irq_hw_number_t iic_pending_to_hwnum(struct cbe_iic_pending_bits bits)
{
unsigned char unit = bits.source & 0xf;
unsigned char node = bits.source >> 4;
unsigned char class = bits.class & 3;
/* Decode IPIs */
if (bits.flags & CBE_IIC_IRQ_IPI)
return IIC_IRQ_TYPE_IPI | (bits.prio >> 4);
else
return (node << IIC_IRQ_NODE_SHIFT) | (class << 4) | unit;
}
static void iic_mask(struct irq_data *d)
{
}
static void iic_unmask(struct irq_data *d)
{
}
static void iic_eoi(struct irq_data *d)
{
struct iic *iic = this_cpu_ptr(&cpu_iic);
out_be64(&iic->regs->prio, iic->eoi_stack[--iic->eoi_ptr]);
BUG_ON(iic->eoi_ptr < 0);
}
static struct irq_chip iic_chip = {
.name = "CELL-IIC",
.irq_mask = iic_mask,
.irq_unmask = iic_unmask,
.irq_eoi = iic_eoi,
};
static void iic_ioexc_eoi(struct irq_data *d)
{
}
static void iic_ioexc_cascade(unsigned int irq, struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
struct cbe_iic_regs __iomem *node_iic =
(void __iomem *)irq_desc_get_handler_data(desc);
unsigned int base = (irq & 0xffffff00) | IIC_IRQ_TYPE_IOEXC;
unsigned long bits, ack;
int cascade;
for (;;) {
bits = in_be64(&node_iic->iic_is);
if (bits == 0)
break;
/* pre-ack edge interrupts */
ack = bits & IIC_ISR_EDGE_MASK;
if (ack)
out_be64(&node_iic->iic_is, ack);
/* handle them */
for (cascade = 63; cascade >= 0; cascade--)
if (bits & (0x8000000000000000UL >> cascade)) {
unsigned int cirq =
irq_linear_revmap(iic_host,
base | cascade);
if (cirq != NO_IRQ)
generic_handle_irq(cirq);
}
/* post-ack level interrupts */
ack = bits & ~IIC_ISR_EDGE_MASK;
if (ack)
out_be64(&node_iic->iic_is, ack);
}
chip->irq_eoi(&desc->irq_data);
}
static struct irq_chip iic_ioexc_chip = {
.name = "CELL-IOEX",
.irq_mask = iic_mask,
.irq_unmask = iic_unmask,
.irq_eoi = iic_ioexc_eoi,
};
/* Get an IRQ number from the pending state register of the IIC */
static unsigned int iic_get_irq(void)
{
struct cbe_iic_pending_bits pending;
struct iic *iic;
unsigned int virq;
iic = this_cpu_ptr(&cpu_iic);
*(unsigned long *) &pending =
in_be64((u64 __iomem *) &iic->regs->pending_destr);
if (!(pending.flags & CBE_IIC_IRQ_VALID))
return NO_IRQ;
virq = irq_linear_revmap(iic_host, iic_pending_to_hwnum(pending));
if (virq == NO_IRQ)
return NO_IRQ;
iic->eoi_stack[++iic->eoi_ptr] = pending.prio;
BUG_ON(iic->eoi_ptr > 15);
return virq;
}
void iic_setup_cpu(void)
{
out_be64(&this_cpu_ptr(&cpu_iic)->regs->prio, 0xff);
}
u8 iic_get_target_id(int cpu)
{
return per_cpu(cpu_iic, cpu).target_id;
}
EXPORT_SYMBOL_GPL(iic_get_target_id);
#ifdef CONFIG_SMP
/* Use the highest interrupt priorities for IPI */
static inline int iic_msg_to_irq(int msg)
{
return IIC_IRQ_TYPE_IPI + 0xf - msg;
}
void iic_message_pass(int cpu, int msg)
{
out_be64(&per_cpu(cpu_iic, cpu).regs->generate, (0xf - msg) << 4);
}
struct irq_domain *iic_get_irq_host(int node)
{
return iic_host;
}
EXPORT_SYMBOL_GPL(iic_get_irq_host);
static void iic_request_ipi(int msg)
{
int virq;
virq = irq_create_mapping(iic_host, iic_msg_to_irq(msg));
if (virq == NO_IRQ) {
printk(KERN_ERR
"iic: failed to map IPI %s\n", smp_ipi_name[msg]);
return;
}
/*
* If smp_request_message_ipi encounters an error it will notify
* the error. If a message is not needed it will return non-zero.
*/
if (smp_request_message_ipi(virq, msg))
irq_dispose_mapping(virq);
}
void iic_request_IPIs(void)
{
iic_request_ipi(PPC_MSG_CALL_FUNCTION);
iic_request_ipi(PPC_MSG_RESCHEDULE);
iic_request_ipi(PPC_MSG_TICK_BROADCAST);
iic_request_ipi(PPC_MSG_DEBUGGER_BREAK);
}
#endif /* CONFIG_SMP */
static int iic_host_match(struct irq_domain *h, struct device_node *node)
{
return of_device_is_compatible(node,
"IBM,CBEA-Internal-Interrupt-Controller");
}
static int iic_host_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
switch (hw & IIC_IRQ_TYPE_MASK) {
case IIC_IRQ_TYPE_IPI:
irq_set_chip_and_handler(virq, &iic_chip, handle_percpu_irq);
break;
case IIC_IRQ_TYPE_IOEXC:
irq_set_chip_and_handler(virq, &iic_ioexc_chip,
handle_edge_eoi_irq);
break;
default:
irq_set_chip_and_handler(virq, &iic_chip, handle_edge_eoi_irq);
}
return 0;
}
static int iic_host_xlate(struct irq_domain *h, struct device_node *ct,
const u32 *intspec, unsigned int intsize,
irq_hw_number_t *out_hwirq, unsigned int *out_flags)
{
unsigned int node, ext, unit, class;
const u32 *val;
if (!of_device_is_compatible(ct,
"IBM,CBEA-Internal-Interrupt-Controller"))
return -ENODEV;
if (intsize != 1)
return -ENODEV;
val = of_get_property(ct, "#interrupt-cells", NULL);
if (val == NULL || *val != 1)
return -ENODEV;
node = intspec[0] >> 24;
ext = (intspec[0] >> 16) & 0xff;
class = (intspec[0] >> 8) & 0xff;
unit = intspec[0] & 0xff;
/* Check if node is in supported range */
if (node > 1)
return -EINVAL;
/* Build up interrupt number, special case for IO exceptions */
*out_hwirq = (node << IIC_IRQ_NODE_SHIFT);
if (unit == IIC_UNIT_IIC && class == 1)
*out_hwirq |= IIC_IRQ_TYPE_IOEXC | ext;
else
*out_hwirq |= IIC_IRQ_TYPE_NORMAL |
(class << IIC_IRQ_CLASS_SHIFT) | unit;
/* Dummy flags, ignored by iic code */
*out_flags = IRQ_TYPE_EDGE_RISING;
return 0;
}
static const struct irq_domain_ops iic_host_ops = {
.match = iic_host_match,
.map = iic_host_map,
.xlate = iic_host_xlate,
};
static void __init init_one_iic(unsigned int hw_cpu, unsigned long addr,
struct device_node *node)
{
/* XXX FIXME: should locate the linux CPU number from the HW cpu
* number properly. We are lucky for now
*/
struct iic *iic = &per_cpu(cpu_iic, hw_cpu);
iic->regs = ioremap(addr, sizeof(struct cbe_iic_thread_regs));
BUG_ON(iic->regs == NULL);
iic->target_id = ((hw_cpu & 2) << 3) | ((hw_cpu & 1) ? 0xf : 0xe);
iic->eoi_stack[0] = 0xff;
iic->node = of_node_get(node);
out_be64(&iic->regs->prio, 0);
printk(KERN_INFO "IIC for CPU %d target id 0x%x : %s\n",
hw_cpu, iic->target_id, node->full_name);
}
static int __init setup_iic(void)
{
struct device_node *dn;
struct resource r0, r1;
unsigned int node, cascade, found = 0;
struct cbe_iic_regs __iomem *node_iic;
const u32 *np;
for (dn = NULL;
(dn = of_find_node_by_name(dn,"interrupt-controller")) != NULL;) {
if (!of_device_is_compatible(dn,
"IBM,CBEA-Internal-Interrupt-Controller"))
continue;
np = of_get_property(dn, "ibm,interrupt-server-ranges", NULL);
if (np == NULL) {
printk(KERN_WARNING "IIC: CPU association not found\n");
of_node_put(dn);
return -ENODEV;
}
if (of_address_to_resource(dn, 0, &r0) ||
of_address_to_resource(dn, 1, &r1)) {
printk(KERN_WARNING "IIC: Can't resolve addresses\n");
of_node_put(dn);
return -ENODEV;
}
found++;
init_one_iic(np[0], r0.start, dn);
init_one_iic(np[1], r1.start, dn);
/* Setup cascade for IO exceptions. XXX cleanup tricks to get
* node vs CPU etc...
* Note that we configure the IIC_IRR here with a hard coded
* priority of 1. We might want to improve that later.
*/
node = np[0] >> 1;
node_iic = cbe_get_cpu_iic_regs(np[0]);
cascade = node << IIC_IRQ_NODE_SHIFT;
cascade |= 1 << IIC_IRQ_CLASS_SHIFT;
cascade |= IIC_UNIT_IIC;
cascade = irq_create_mapping(iic_host, cascade);
if (cascade == NO_IRQ)
continue;
/*
* irq_data is a generic pointer that gets passed back
* to us later, so the forced cast is fine.
*/
irq_set_handler_data(cascade, (void __force *)node_iic);
irq_set_chained_handler(cascade, iic_ioexc_cascade);
out_be64(&node_iic->iic_ir,
(1 << 12) /* priority */ |
(node << 4) /* dest node */ |
IIC_UNIT_THREAD_0 /* route them to thread 0 */);
/* Flush pending (make sure it triggers if there is
* anything pending
*/
out_be64(&node_iic->iic_is, 0xfffffffffffffffful);
}
if (found)
return 0;
else
return -ENODEV;
}
void __init iic_init_IRQ(void)
{
/* Setup an irq host data structure */
iic_host = irq_domain_add_linear(NULL, IIC_SOURCE_COUNT, &iic_host_ops,
NULL);
BUG_ON(iic_host == NULL);
irq_set_default_host(iic_host);
/* Discover and initialize iics */
if (setup_iic() < 0)
panic("IIC: Failed to initialize !\n");
/* Set master interrupt handling function */
ppc_md.get_irq = iic_get_irq;
/* Enable on current CPU */
iic_setup_cpu();
}
void iic_set_interrupt_routing(int cpu, int thread, int priority)
{
struct cbe_iic_regs __iomem *iic_regs = cbe_get_cpu_iic_regs(cpu);
u64 iic_ir = 0;
int node = cpu >> 1;
/* Set which node and thread will handle the next interrupt */
iic_ir |= CBE_IIC_IR_PRIO(priority) |
CBE_IIC_IR_DEST_NODE(node);
if (thread == 0)
iic_ir |= CBE_IIC_IR_DEST_UNIT(CBE_IIC_IR_PT_0);
else
iic_ir |= CBE_IIC_IR_DEST_UNIT(CBE_IIC_IR_PT_1);
out_be64(&iic_regs->iic_ir, iic_ir);
}
| gpl-2.0 |
kecinzer/kernel_opo_kecinzer | drivers/md/dm-req-crypt.c | 686 | 24086 | /* Copyright (c) 2014, The Linux Foundation. All rights reserved.
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/mempool.h>
#include <linux/slab.h>
#include <linux/crypto.h>
#include <linux/workqueue.h>
#include <linux/backing-dev.h>
#include <linux/atomic.h>
#include <linux/scatterlist.h>
#include <linux/device-mapper.h>
#include <linux/printk.h>
#include <linux/pft.h>
#include <crypto/scatterwalk.h>
#include <asm/page.h>
#include <asm/unaligned.h>
#include <crypto/hash.h>
#include <crypto/md5.h>
#include <crypto/algapi.h>
#include <mach/qcrypto.h>
#define DM_MSG_PREFIX "req-crypt"
#define MAX_SG_LIST 1024
#define REQ_DM_512_KB (512*1024)
#define MAX_ENCRYPTION_BUFFERS 1
#define MIN_IOS 16
#define MIN_POOL_PAGES 32
#define KEY_SIZE_XTS 64
#define AES_XTS_IV_LEN 16
#define DM_REQ_CRYPT_ERROR -1
#define DM_REQ_CRYPT_ERROR_AFTER_PAGE_MALLOC -2
struct req_crypt_result {
struct completion completion;
int err;
};
#define FDE_KEY_ID 0
#define PFE_KEY_ID 1
static struct dm_dev *dev;
static struct kmem_cache *_req_crypt_io_pool;
static sector_t start_sector_orig;
static struct workqueue_struct *req_crypt_queue;
static mempool_t *req_io_pool;
static mempool_t *req_page_pool;
static bool is_fde_enabled;
static struct crypto_ablkcipher *tfm;
struct req_dm_crypt_io {
struct work_struct work;
struct request *cloned_request;
int error;
atomic_t pending;
struct timespec start_time;
bool should_encrypt;
bool should_decrypt;
u32 key_id;
};
static void req_crypt_cipher_complete
(struct crypto_async_request *req, int err);
static bool req_crypt_should_encrypt(struct req_dm_crypt_io *req)
{
int ret;
bool should_encrypt = false;
struct bio *bio = NULL;
u32 key_id = 0;
bool is_encrypted = false;
bool is_inplace = false;
if (!req || !req->cloned_request || !req->cloned_request->bio)
return false;
bio = req->cloned_request->bio;
ret = pft_get_key_index(bio, &key_id, &is_encrypted, &is_inplace);
/* req->key_id = key_id; @todo support more than 1 pfe key */
if ((ret == 0) && (is_encrypted || is_inplace)) {
should_encrypt = true;
req->key_id = PFE_KEY_ID;
} else if (is_fde_enabled) {
should_encrypt = true;
req->key_id = FDE_KEY_ID;
}
return should_encrypt;
}
static bool req_crypt_should_deccrypt(struct req_dm_crypt_io *req)
{
int ret;
bool should_deccrypt = false;
struct bio *bio = NULL;
u32 key_id = 0;
bool is_encrypted = false;
bool is_inplace = false;
if (!req || !req->cloned_request || !req->cloned_request->bio)
return false;
bio = req->cloned_request->bio;
ret = pft_get_key_index(bio, &key_id, &is_encrypted, &is_inplace);
/* req->key_id = key_id; @todo support more than 1 pfe key */
if ((ret == 0) && (is_encrypted && !is_inplace)) {
should_deccrypt = true;
req->key_id = PFE_KEY_ID;
} else if (is_fde_enabled) {
should_deccrypt = true;
req->key_id = FDE_KEY_ID;
}
return should_deccrypt;
}
static void req_crypt_inc_pending(struct req_dm_crypt_io *io)
{
atomic_inc(&io->pending);
}
static void req_crypt_dec_pending_encrypt(struct req_dm_crypt_io *io)
{
int error = 0;
struct request *clone = NULL;
if (io) {
error = io->error;
if (io->cloned_request) {
clone = io->cloned_request;
} else {
DMERR("%s io->cloned_request is NULL\n",
__func__);
/*
* If Clone is NULL we cannot do anything,
* this should never happen
*/
BUG();
}
} else {
DMERR("%s io is NULL\n", __func__);
/*
* If Clone is NULL we cannot do anything,
* this should never happen
*/
BUG();
}
atomic_dec(&io->pending);
if (error < 0) {
dm_kill_unmapped_request(clone, error);
mempool_free(io, req_io_pool);
} else
dm_dispatch_request(clone);
}
static void req_crypt_dec_pending_decrypt(struct req_dm_crypt_io *io)
{
int error = 0;
struct request *clone = NULL;
if (io) {
error = io->error;
if (io->cloned_request) {
clone = io->cloned_request;
} else {
DMERR("%s io->cloned_request is NULL\n",
__func__);
/*
* If Clone is NULL we cannot do anything,
* this should never happen
*/
BUG();
}
} else {
DMERR("%s io is NULL\n",
__func__);
/*
* If Clone is NULL we cannot do anything,
* this should never happen
*/
BUG();
}
/* Should never get here if io or Clone is NULL */
dm_end_request(clone, error);
atomic_dec(&io->pending);
mempool_free(io, req_io_pool);
}
/*
* The callback that will be called by the worker queue to perform Decryption
* for reads and use the dm function to complete the bios and requests.
*/
static void req_cryptd_crypt_read_convert(struct req_dm_crypt_io *io)
{
struct request *clone = NULL;
int error = 0;
int total_sg_len = 0, rc = 0, total_bytes_in_req = 0;
struct ablkcipher_request *req = NULL;
struct req_crypt_result result;
struct scatterlist *req_sg_read = NULL;
int err = 0;
u8 IV[AES_XTS_IV_LEN];
if (io) {
error = io->error;
if (io->cloned_request) {
clone = io->cloned_request;
} else {
DMERR("%s io->cloned_request is NULL\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto submit_request;
}
} else {
DMERR("%s io is NULL\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto submit_request;
}
req_crypt_inc_pending(io);
if (error != 0) {
err = error;
goto submit_request;
}
req = ablkcipher_request_alloc(tfm, GFP_KERNEL);
if (!req) {
DMERR("%s ablkcipher request allocation failed\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
ablkcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
req_crypt_cipher_complete, &result);
init_completion(&result.completion);
err = qcrypto_cipher_set_device(req, io->key_id);
if (err != 0) {
DMERR("%s qcrypto_cipher_set_device failed with err %d\n",
__func__, err);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
qcrypto_cipher_set_flag(req,
QCRYPTO_CTX_USE_PIPE_KEY | QCRYPTO_CTX_XTS_DU_SIZE_512B);
crypto_ablkcipher_clear_flags(tfm, ~0);
crypto_ablkcipher_setkey(tfm, NULL, KEY_SIZE_XTS);
req_sg_read = kzalloc(sizeof(struct scatterlist) *
MAX_SG_LIST, GFP_KERNEL);
if (!req_sg_read) {
DMERR("%s req_sg_read allocation failed\n",
__func__);
err = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
total_sg_len = blk_rq_map_sg(clone->q, clone, req_sg_read);
if ((total_sg_len <= 0) || (total_sg_len > MAX_SG_LIST)) {
DMERR("%s Request Error%d", __func__, total_sg_len);
err = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
total_bytes_in_req = clone->__data_len;
if (total_bytes_in_req > REQ_DM_512_KB) {
DMERR("%s total_bytes_in_req > 512 MB %d",
__func__, total_bytes_in_req);
err = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
memset(IV, 0, AES_XTS_IV_LEN);
memcpy(IV, &clone->__sector, sizeof(sector_t));
ablkcipher_request_set_crypt(req, req_sg_read, req_sg_read,
total_bytes_in_req, (void *) IV);
rc = crypto_ablkcipher_decrypt(req);
switch (rc) {
case 0:
break;
case -EBUSY:
/*
* Lets make this synchronous request by waiting on
* in progress as well
*/
case -EINPROGRESS:
wait_for_completion_io(&result.completion);
if (result.err) {
DMERR("%s error = %d encrypting the request\n",
__func__, result.err);
err = DM_REQ_CRYPT_ERROR;
}
break;
default:
err = DM_REQ_CRYPT_ERROR;
break;
}
ablkcipher_req_alloc_failure:
if (req)
ablkcipher_request_free(req);
kfree(req_sg_read);
submit_request:
if (io)
io->error = err;
req_crypt_dec_pending_decrypt(io);
}
/*
* This callback is called by the worker queue to perform non-decrypt reads
* and use the dm function to complete the bios and requests.
*/
static void req_cryptd_crypt_read_plain(struct req_dm_crypt_io *io)
{
struct request *clone = NULL;
int error = 0;
if (!io || !io->cloned_request) {
DMERR("%s io is invalid\n", __func__);
BUG(); /* should not happen */
}
clone = io->cloned_request;
dm_end_request(clone, error);
mempool_free(io, req_io_pool);
}
/*
* The callback that will be called by the worker queue to perform Encryption
* for writes and submit the request using the elevelator.
*/
static void req_cryptd_crypt_write_convert(struct req_dm_crypt_io *io)
{
struct request *clone = NULL;
struct bio *bio_src = NULL;
unsigned int total_sg_len_req_in = 0, total_sg_len_req_out = 0,
total_bytes_in_req = 0, error = DM_MAPIO_REMAPPED, rc = 0;
struct req_iterator iter = {0, NULL};
struct req_iterator iter1 = {0, NULL};
struct ablkcipher_request *req = NULL;
struct req_crypt_result result;
struct bio_vec *bvec = NULL;
struct scatterlist *req_sg_in = NULL;
struct scatterlist *req_sg_out = NULL;
int copy_bio_sector_to_req = 0;
gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
struct page *page = NULL;
u8 IV[AES_XTS_IV_LEN];
int remaining_size = 0;
int err = 0;
if (io) {
if (io->cloned_request) {
clone = io->cloned_request;
} else {
DMERR("%s io->cloned_request is NULL\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto submit_request;
}
} else {
DMERR("%s io is NULL\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto submit_request;
}
req_crypt_inc_pending(io);
req = ablkcipher_request_alloc(tfm, GFP_KERNEL);
if (!req) {
DMERR("%s ablkcipher request allocation failed\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
ablkcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
req_crypt_cipher_complete, &result);
init_completion(&result.completion);
err = qcrypto_cipher_set_device(req, io->key_id);
if (err != 0) {
DMERR("%s qcrypto_cipher_set_device failed with err %d\n",
__func__, err);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
qcrypto_cipher_set_flag(req,
QCRYPTO_CTX_USE_PIPE_KEY | QCRYPTO_CTX_XTS_DU_SIZE_512B);
crypto_ablkcipher_clear_flags(tfm, ~0);
crypto_ablkcipher_setkey(tfm, NULL, KEY_SIZE_XTS);
req_sg_in = kzalloc(sizeof(struct scatterlist) * MAX_SG_LIST,
GFP_KERNEL);
if (!req_sg_in) {
DMERR("%s req_sg_in allocation failed\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
req_sg_out = kzalloc(sizeof(struct scatterlist) * MAX_SG_LIST,
GFP_KERNEL);
if (!req_sg_out) {
DMERR("%s req_sg_out allocation failed\n",
__func__);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
total_sg_len_req_in = blk_rq_map_sg(clone->q, clone, req_sg_in);
if ((total_sg_len_req_in <= 0) ||
(total_sg_len_req_in > MAX_SG_LIST)) {
DMERR("%s Request Error%d", __func__, total_sg_len_req_in);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
total_bytes_in_req = clone->__data_len;
if (total_bytes_in_req > REQ_DM_512_KB) {
DMERR("%s total_bytes_in_req > 512 MB %d",
__func__, total_bytes_in_req);
error = DM_REQ_CRYPT_ERROR;
goto ablkcipher_req_alloc_failure;
}
rq_for_each_segment(bvec, clone, iter) {
if (bvec->bv_len > remaining_size) {
page = NULL;
while (page == NULL) {
page = mempool_alloc(req_page_pool, gfp_mask);
if (!page) {
DMERR("%s Crypt page alloc failed",
__func__);
congestion_wait(BLK_RW_ASYNC, HZ/100);
}
}
bvec->bv_page = page;
bvec->bv_offset = 0;
remaining_size = PAGE_SIZE - bvec->bv_len;
if (remaining_size < 0)
BUG();
} else {
bvec->bv_page = page;
bvec->bv_offset = PAGE_SIZE - remaining_size;
remaining_size = remaining_size - bvec->bv_len;
}
}
total_sg_len_req_out = blk_rq_map_sg(clone->q, clone, req_sg_out);
if ((total_sg_len_req_out <= 0) ||
(total_sg_len_req_out > MAX_SG_LIST)) {
DMERR("%s Request Error %d", __func__, total_sg_len_req_out);
error = DM_REQ_CRYPT_ERROR_AFTER_PAGE_MALLOC;
goto ablkcipher_req_alloc_failure;
}
memset(IV, 0, AES_XTS_IV_LEN);
memcpy(IV, &clone->__sector, sizeof(sector_t));
ablkcipher_request_set_crypt(req, req_sg_in, req_sg_out,
total_bytes_in_req, (void *) IV);
rc = crypto_ablkcipher_encrypt(req);
switch (rc) {
case 0:
break;
case -EBUSY:
/*
* Lets make this synchronous request by waiting on
* in progress as well
*/
case -EINPROGRESS:
wait_for_completion_interruptible(&result.completion);
if (result.err) {
DMERR("%s error = %d encrypting the request\n",
__func__, result.err);
error = DM_REQ_CRYPT_ERROR_AFTER_PAGE_MALLOC;
goto ablkcipher_req_alloc_failure;
}
break;
default:
error = DM_REQ_CRYPT_ERROR_AFTER_PAGE_MALLOC;
goto ablkcipher_req_alloc_failure;
}
__rq_for_each_bio(bio_src, clone) {
if (copy_bio_sector_to_req == 0) {
clone->buffer = bio_data(bio_src);
copy_bio_sector_to_req++;
}
blk_queue_bounce(clone->q, &bio_src);
}
ablkcipher_req_alloc_failure:
if (req)
ablkcipher_request_free(req);
if (error == DM_REQ_CRYPT_ERROR_AFTER_PAGE_MALLOC) {
bvec = NULL;
rq_for_each_segment(bvec, clone, iter1) {
if (bvec->bv_offset == 0) {
mempool_free(bvec->bv_page, req_page_pool);
bvec->bv_page = NULL;
} else
bvec->bv_page = NULL;
}
}
kfree(req_sg_in);
kfree(req_sg_out);
submit_request:
if (io)
io->error = error;
req_crypt_dec_pending_encrypt(io);
}
/*
* This callback is called by the worker queue to perform non-encrypted writes
* and submit the request using the elevelator.
*/
static void req_cryptd_crypt_write_plain(struct req_dm_crypt_io *io)
{
struct request *clone = NULL;
if (!io || !io->cloned_request) {
DMERR("%s io is invalid\n", __func__);
BUG(); /* should not happen */
}
clone = io->cloned_request;
io->error = 0;
dm_dispatch_request(clone);
}
/* Queue callback function that will get triggered */
static void req_cryptd_crypt(struct work_struct *work)
{
struct req_dm_crypt_io *io =
container_of(work, struct req_dm_crypt_io, work);
if (rq_data_dir(io->cloned_request) == WRITE) {
if (io->should_encrypt)
req_cryptd_crypt_write_convert(io);
else
req_cryptd_crypt_write_plain(io);
} else if (rq_data_dir(io->cloned_request) == READ) {
if (io->should_decrypt)
req_cryptd_crypt_read_convert(io);
else
req_cryptd_crypt_read_plain(io);
} else {
DMERR("%s received non-write request for Clone %u\n",
__func__, (unsigned int)io->cloned_request);
}
}
static void req_cryptd_queue_crypt(struct req_dm_crypt_io *io)
{
INIT_WORK(&io->work, req_cryptd_crypt);
queue_work(req_crypt_queue, &io->work);
}
/*
* Cipher complete callback, this is triggered by the Linux crypto api once
* the operation is done. This signals the waiting thread that the crypto
* operation is complete.
*/
static void req_crypt_cipher_complete(struct crypto_async_request *req, int err)
{
struct req_crypt_result *res = req->data;
if (err == -EINPROGRESS)
return;
res->err = err;
complete(&res->completion);
}
/*
* If bio->bi_dev is a partition, remap the location
*/
static inline void req_crypt_blk_partition_remap(struct bio *bio)
{
struct block_device *bdev = bio->bi_bdev;
if (bio_sectors(bio) && bdev != bdev->bd_contains) {
struct hd_struct *p = bdev->bd_part;
/*
* Check for integer overflow, should never happen.
*/
if (p->start_sect > (UINT_MAX - bio->bi_sector))
BUG();
bio->bi_sector += p->start_sect;
bio->bi_bdev = bdev->bd_contains;
}
}
/*
* The endio function is called from ksoftirqd context (atomic).
* For write operations the new pages created form the mempool
* is freed and returned. * For read operations, decryption is
* required, since this is called in a atomic * context, the
* request is sent to a worker queue to complete decryptiona and
* free the request once done.
*/
static int req_crypt_endio(struct dm_target *ti, struct request *clone,
int error, union map_info *map_context)
{
int err = 0;
struct req_iterator iter1;
struct bio_vec *bvec = NULL;
struct req_dm_crypt_io *req_io = map_context->ptr;
/* If it is a write request, do nothing just return. */
bvec = NULL;
if (rq_data_dir(clone) == WRITE) {
rq_for_each_segment(bvec, clone, iter1) {
if (req_io->should_encrypt && bvec->bv_offset == 0) {
mempool_free(bvec->bv_page, req_page_pool);
bvec->bv_page = NULL;
} else
bvec->bv_page = NULL;
}
mempool_free(req_io, req_io_pool);
goto submit_request;
} else if (rq_data_dir(clone) == READ) {
req_io->error = error;
req_cryptd_queue_crypt(req_io);
err = DM_ENDIO_INCOMPLETE;
goto submit_request;
}
submit_request:
return err;
}
/*
* This function is called with interrupts disabled
* The function remaps the clone for the underlying device.
* If it is a write request, it calls into the worker queue to
* encrypt the data
* and submit the request directly using the elevator
* For a read request no pre-processing is required the request
* is returned to dm once mapping is done
*/
static int req_crypt_map(struct dm_target *ti, struct request *clone,
union map_info *map_context)
{
struct req_dm_crypt_io *req_io = NULL;
int error = DM_REQ_CRYPT_ERROR, copy_bio_sector_to_req = 0;
struct bio *bio_src = NULL;
if ((rq_data_dir(clone) != READ) &&
(rq_data_dir(clone) != WRITE)) {
error = DM_REQ_CRYPT_ERROR;
DMERR("%s Unknown request\n", __func__);
goto submit_request;
}
req_io = mempool_alloc(req_io_pool, GFP_NOWAIT);
if (!req_io) {
DMERR("%s req_io allocation failed\n", __func__);
error = DM_REQ_CRYPT_ERROR;
goto submit_request;
}
/* Save the clone in the req_io, the callback to the worker
* queue will get the req_io
*/
req_io->cloned_request = clone;
map_context->ptr = req_io;
atomic_set(&req_io->pending, 0);
if (rq_data_dir(clone) == WRITE)
req_io->should_encrypt = req_crypt_should_encrypt(req_io);
if (rq_data_dir(clone) == READ)
req_io->should_decrypt = req_crypt_should_deccrypt(req_io);
/* Get the queue of the underlying original device */
clone->q = bdev_get_queue(dev->bdev);
clone->rq_disk = dev->bdev->bd_disk;
__rq_for_each_bio(bio_src, clone) {
bio_src->bi_bdev = dev->bdev;
/* Currently the way req-dm works is that once the underlying
* device driver completes the request by calling into the
* block layer. The block layer completes the bios (clones) and
* then the cloned request. This is undesirable for req-dm-crypt
* hence added a flag BIO_DONTFREE, this flag will ensure that
* blk layer does not complete the cloned bios before completing
* the request. When the crypt endio is called, post-processsing
* is done and then the dm layer will complete the bios (clones)
* and free them.
*/
bio_src->bi_flags |= 1 << BIO_DONTFREE;
/*
* If this device has partitions, remap block n
* of partition p to block n+start(p) of the disk.
*/
req_crypt_blk_partition_remap(bio_src);
if (copy_bio_sector_to_req == 0) {
clone->__sector = bio_src->bi_sector;
clone->buffer = bio_data(bio_src);
copy_bio_sector_to_req++;
}
blk_queue_bounce(clone->q, &bio_src);
}
if (rq_data_dir(clone) == READ) {
error = DM_MAPIO_REMAPPED;
goto submit_request;
} else if (rq_data_dir(clone) == WRITE) {
req_cryptd_queue_crypt(req_io);
error = DM_MAPIO_SUBMITTED;
goto submit_request;
}
submit_request:
return error;
}
static void req_crypt_dtr(struct dm_target *ti)
{
DMDEBUG("dm-req-crypt Destructor.\n");
if (req_crypt_queue) {
destroy_workqueue(req_crypt_queue);
req_crypt_queue = NULL;
}
if (req_io_pool) {
mempool_destroy(req_io_pool);
req_io_pool = NULL;
}
if (req_page_pool) {
mempool_destroy(req_page_pool);
req_page_pool = NULL;
}
if (tfm) {
crypto_free_ablkcipher(tfm);
tfm = NULL;
}
}
/*
* Construct an encryption mapping:
* <cipher> <key> <iv_offset> <dev_path> <start>
*/
static int req_crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
{
unsigned long long tmpll;
char dummy;
int err = DM_REQ_CRYPT_ERROR;
DMDEBUG("dm-req-crypt Constructor.\n");
if (argc < 5) {
DMERR(" %s Not enough args\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
if (argv[3]) {
if (dm_get_device(ti, argv[3],
dm_table_get_mode(ti->table), &dev)) {
DMERR(" %s Device Lookup failed\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
} else {
DMERR(" %s Arg[3] invalid\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
if (argv[4]) {
if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
DMERR("%s Invalid device sector\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
} else {
DMERR(" %s Arg[4] invalid\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
start_sector_orig = tmpll;
/* Allow backward compatible */
if (argc >= 6) {
if (argv[5]) {
if (!strcmp(argv[5], "fde_enabled"))
is_fde_enabled = true;
else
is_fde_enabled = false;
} else {
DMERR(" %s Arg[5] invalid\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
} else {
DMERR(" %s Arg[5] missing, set FDE enabled.\n", __func__);
is_fde_enabled = true; /* backward compatible */
}
DMDEBUG("%s is_fde_enabled=%d\n", __func__, is_fde_enabled);
req_crypt_queue = alloc_workqueue("req_cryptd",
WQ_NON_REENTRANT |
WQ_HIGHPRI |
WQ_CPU_INTENSIVE|
WQ_MEM_RECLAIM,
1);
if (!req_crypt_queue) {
DMERR("%s req_crypt_queue not allocated\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
/* Allocate the crypto alloc blk cipher and keep the handle */
tfm = crypto_alloc_ablkcipher("qcom-xts(aes)", 0, 0);
if (IS_ERR(tfm)) {
DMERR("%s ablkcipher tfm allocation failed : error\n",
__func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
req_io_pool = mempool_create_slab_pool(MIN_IOS, _req_crypt_io_pool);
BUG_ON(!req_io_pool);
if (!req_io_pool) {
DMERR("%s req_io_pool not allocated\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
req_page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
if (!req_page_pool) {
DMERR("%s req_page_pool not allocated\n", __func__);
err = DM_REQ_CRYPT_ERROR;
goto ctr_exit;
}
err = 0;
ctr_exit:
if (err != 0) {
if (req_crypt_queue) {
destroy_workqueue(req_crypt_queue);
req_crypt_queue = NULL;
}
if (req_io_pool) {
mempool_destroy(req_io_pool);
req_io_pool = NULL;
}
if (req_page_pool) {
mempool_destroy(req_page_pool);
req_page_pool = NULL;
}
if (tfm) {
crypto_free_ablkcipher(tfm);
tfm = NULL;
}
}
return err;
}
static int req_crypt_iterate_devices(struct dm_target *ti,
iterate_devices_callout_fn fn, void *data)
{
return fn(ti, dev, start_sector_orig, ti->len, data);
}
static struct target_type req_crypt_target = {
.name = "req-crypt",
.version = {1, 0, 0},
.module = THIS_MODULE,
.ctr = req_crypt_ctr,
.dtr = req_crypt_dtr,
.map_rq = req_crypt_map,
.rq_end_io = req_crypt_endio,
.iterate_devices = req_crypt_iterate_devices,
};
static int __init req_dm_crypt_init(void)
{
int r;
_req_crypt_io_pool = KMEM_CACHE(req_dm_crypt_io, 0);
if (!_req_crypt_io_pool)
return -ENOMEM;
r = dm_register_target(&req_crypt_target);
if (r < 0) {
DMERR("register failed %d", r);
kmem_cache_destroy(_req_crypt_io_pool);
}
DMINFO("dm-req-crypt successfully initalized.\n");
return r;
}
static void __exit req_dm_crypt_exit(void)
{
kmem_cache_destroy(_req_crypt_io_pool);
dm_unregister_target(&req_crypt_target);
}
module_init(req_dm_crypt_init);
module_exit(req_dm_crypt_exit);
MODULE_DESCRIPTION(DM_NAME " target for request based transparent encryption / decryption");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
mohammad92/GT-S5360_Kernel_GB_Opensource_Update4 | drivers/pci/hotplug/pcihp_slot.c | 942 | 5623 | /*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2003-2004 Intel Corporation
* (c) Copyright 2009 Hewlett-Packard Development Company, L.P.
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
static struct hpp_type0 pci_default_type0 = {
.revision = 1,
.cache_line_size = 8,
.latency_timer = 0x40,
.enable_serr = 0,
.enable_perr = 0,
};
static void program_hpp_type0(struct pci_dev *dev, struct hpp_type0 *hpp)
{
u16 pci_cmd, pci_bctl;
if (!hpp) {
/*
* Perhaps we *should* use default settings for PCIe, but
* pciehp didn't, so we won't either.
*/
if (pci_is_pcie(dev))
return;
dev_info(&dev->dev, "using default PCI settings\n");
hpp = &pci_default_type0;
}
if (hpp->revision > 1) {
dev_warn(&dev->dev,
"PCI settings rev %d not supported; using defaults\n",
hpp->revision);
hpp = &pci_default_type0;
}
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, hpp->cache_line_size);
pci_write_config_byte(dev, PCI_LATENCY_TIMER, hpp->latency_timer);
pci_read_config_word(dev, PCI_COMMAND, &pci_cmd);
if (hpp->enable_serr)
pci_cmd |= PCI_COMMAND_SERR;
else
pci_cmd &= ~PCI_COMMAND_SERR;
if (hpp->enable_perr)
pci_cmd |= PCI_COMMAND_PARITY;
else
pci_cmd &= ~PCI_COMMAND_PARITY;
pci_write_config_word(dev, PCI_COMMAND, pci_cmd);
/* Program bridge control value */
if ((dev->class >> 8) == PCI_CLASS_BRIDGE_PCI) {
pci_write_config_byte(dev, PCI_SEC_LATENCY_TIMER,
hpp->latency_timer);
pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &pci_bctl);
if (hpp->enable_serr)
pci_bctl |= PCI_BRIDGE_CTL_SERR;
else
pci_bctl &= ~PCI_BRIDGE_CTL_SERR;
if (hpp->enable_perr)
pci_bctl |= PCI_BRIDGE_CTL_PARITY;
else
pci_bctl &= ~PCI_BRIDGE_CTL_PARITY;
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, pci_bctl);
}
}
static void program_hpp_type1(struct pci_dev *dev, struct hpp_type1 *hpp)
{
if (hpp)
dev_warn(&dev->dev, "PCI-X settings not supported\n");
}
static void program_hpp_type2(struct pci_dev *dev, struct hpp_type2 *hpp)
{
int pos;
u16 reg16;
u32 reg32;
if (!hpp)
return;
/* Find PCI Express capability */
pos = pci_pcie_cap(dev);
if (!pos)
return;
if (hpp->revision > 1) {
dev_warn(&dev->dev, "PCIe settings rev %d not supported\n",
hpp->revision);
return;
}
/* Initialize Device Control Register */
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
reg16 = (reg16 & hpp->pci_exp_devctl_and) | hpp->pci_exp_devctl_or;
pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, reg16);
/* Initialize Link Control Register */
if (dev->subordinate) {
pci_read_config_word(dev, pos + PCI_EXP_LNKCTL, ®16);
reg16 = (reg16 & hpp->pci_exp_lnkctl_and)
| hpp->pci_exp_lnkctl_or;
pci_write_config_word(dev, pos + PCI_EXP_LNKCTL, reg16);
}
/* Find Advanced Error Reporting Enhanced Capability */
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return;
/* Initialize Uncorrectable Error Mask Register */
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, ®32);
reg32 = (reg32 & hpp->unc_err_mask_and) | hpp->unc_err_mask_or;
pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, reg32);
/* Initialize Uncorrectable Error Severity Register */
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, ®32);
reg32 = (reg32 & hpp->unc_err_sever_and) | hpp->unc_err_sever_or;
pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, reg32);
/* Initialize Correctable Error Mask Register */
pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK, ®32);
reg32 = (reg32 & hpp->cor_err_mask_and) | hpp->cor_err_mask_or;
pci_write_config_dword(dev, pos + PCI_ERR_COR_MASK, reg32);
/* Initialize Advanced Error Capabilities and Control Register */
pci_read_config_dword(dev, pos + PCI_ERR_CAP, ®32);
reg32 = (reg32 & hpp->adv_err_cap_and) | hpp->adv_err_cap_or;
pci_write_config_dword(dev, pos + PCI_ERR_CAP, reg32);
/*
* FIXME: The following two registers are not supported yet.
*
* o Secondary Uncorrectable Error Severity Register
* o Secondary Uncorrectable Error Mask Register
*/
}
void pci_configure_slot(struct pci_dev *dev)
{
struct pci_dev *cdev;
struct hotplug_params hpp;
int ret;
if (!(dev->hdr_type == PCI_HEADER_TYPE_NORMAL ||
(dev->hdr_type == PCI_HEADER_TYPE_BRIDGE &&
(dev->class >> 8) == PCI_CLASS_BRIDGE_PCI)))
return;
memset(&hpp, 0, sizeof(hpp));
ret = pci_get_hp_params(dev, &hpp);
if (ret)
dev_warn(&dev->dev, "no hotplug settings from platform\n");
program_hpp_type2(dev, hpp.t2);
program_hpp_type1(dev, hpp.t1);
program_hpp_type0(dev, hpp.t0);
if (dev->subordinate) {
list_for_each_entry(cdev, &dev->subordinate->devices,
bus_list)
pci_configure_slot(cdev);
}
}
EXPORT_SYMBOL_GPL(pci_configure_slot);
| gpl-2.0 |
vakkov/android-n900-nitdroid_kernel | drivers/isdn/hisax/hfc_2bs0.c | 942 | 15670 | /* $Id: hfc_2bs0.c,v 1.20.2.6 2004/02/11 13:21:33 keil Exp $
*
* specific routines for CCD's HFC 2BS0
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "hfc_2bs0.h"
#include "isac.h"
#include "isdnl1.h"
#include <linux/interrupt.h>
#include <linux/slab.h>
static inline int
WaitForBusy(struct IsdnCardState *cs)
{
int to = 130;
u_char val;
while (!(cs->BC_Read_Reg(cs, HFC_STATUS, 0) & HFC_BUSY) && to) {
val = cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2 |
(cs->hw.hfc.cip & 3));
udelay(1);
to--;
}
if (!to) {
printk(KERN_WARNING "HiSax: waitforBusy timeout\n");
return (0);
} else
return (to);
}
static inline int
WaitNoBusy(struct IsdnCardState *cs)
{
int to = 125;
while ((cs->BC_Read_Reg(cs, HFC_STATUS, 0) & HFC_BUSY) && to) {
udelay(1);
to--;
}
if (!to) {
printk(KERN_WARNING "HiSax: waitforBusy timeout\n");
return (0);
} else
return (to);
}
static int
GetFreeFifoBytes(struct BCState *bcs)
{
int s;
if (bcs->hw.hfc.f1 == bcs->hw.hfc.f2)
return (bcs->cs->hw.hfc.fifosize);
s = bcs->hw.hfc.send[bcs->hw.hfc.f1] - bcs->hw.hfc.send[bcs->hw.hfc.f2];
if (s <= 0)
s += bcs->cs->hw.hfc.fifosize;
s = bcs->cs->hw.hfc.fifosize - s;
return (s);
}
static int
ReadZReg(struct BCState *bcs, u_char reg)
{
int val;
WaitNoBusy(bcs->cs);
val = 256 * bcs->cs->BC_Read_Reg(bcs->cs, HFC_DATA, reg | HFC_CIP | HFC_Z_HIGH);
WaitNoBusy(bcs->cs);
val += bcs->cs->BC_Read_Reg(bcs->cs, HFC_DATA, reg | HFC_CIP | HFC_Z_LOW);
return (val);
}
static void
hfc_clear_fifo(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
int idx, cnt;
int rcnt, z1, z2;
u_char cip, f1, f2;
if ((cs->debug & L1_DEB_HSCX) && !(cs->debug & L1_DEB_HSCX_FIFO))
debugl1(cs, "hfc_clear_fifo");
cip = HFC_CIP | HFC_F1 | HFC_REC | HFC_CHANNEL(bcs->channel);
if ((cip & 0xc3) != (cs->hw.hfc.cip & 0xc3)) {
cs->BC_Write_Reg(cs, HFC_STATUS, cip, cip);
WaitForBusy(cs);
}
WaitNoBusy(cs);
f1 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
cip = HFC_CIP | HFC_F2 | HFC_REC | HFC_CHANNEL(bcs->channel);
WaitNoBusy(cs);
f2 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
z1 = ReadZReg(bcs, HFC_Z1 | HFC_REC | HFC_CHANNEL(bcs->channel));
z2 = ReadZReg(bcs, HFC_Z2 | HFC_REC | HFC_CHANNEL(bcs->channel));
cnt = 32;
while (((f1 != f2) || (z1 != z2)) && cnt--) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc clear %d f1(%d) f2(%d)",
bcs->channel, f1, f2);
rcnt = z1 - z2;
if (rcnt < 0)
rcnt += cs->hw.hfc.fifosize;
if (rcnt)
rcnt++;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc clear %d z1(%x) z2(%x) cnt(%d)",
bcs->channel, z1, z2, rcnt);
cip = HFC_CIP | HFC_FIFO_OUT | HFC_REC | HFC_CHANNEL(bcs->channel);
idx = 0;
while ((idx < rcnt) && WaitNoBusy(cs)) {
cs->BC_Read_Reg(cs, HFC_DATA_NODEB, cip);
idx++;
}
if (f1 != f2) {
WaitNoBusy(cs);
cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2_INC | HFC_REC |
HFC_CHANNEL(bcs->channel));
WaitForBusy(cs);
}
cip = HFC_CIP | HFC_F1 | HFC_REC | HFC_CHANNEL(bcs->channel);
WaitNoBusy(cs);
f1 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
cip = HFC_CIP | HFC_F2 | HFC_REC | HFC_CHANNEL(bcs->channel);
WaitNoBusy(cs);
f2 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
z1 = ReadZReg(bcs, HFC_Z1 | HFC_REC | HFC_CHANNEL(bcs->channel));
z2 = ReadZReg(bcs, HFC_Z2 | HFC_REC | HFC_CHANNEL(bcs->channel));
}
return;
}
static struct sk_buff
*
hfc_empty_fifo(struct BCState *bcs, int count)
{
u_char *ptr;
struct sk_buff *skb;
struct IsdnCardState *cs = bcs->cs;
int idx;
int chksum;
u_char stat, cip;
if ((cs->debug & L1_DEB_HSCX) && !(cs->debug & L1_DEB_HSCX_FIFO))
debugl1(cs, "hfc_empty_fifo");
idx = 0;
if (count > HSCX_BUFMAX + 3) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hfc_empty_fifo: incoming packet too large");
cip = HFC_CIP | HFC_FIFO_OUT | HFC_REC | HFC_CHANNEL(bcs->channel);
while ((idx++ < count) && WaitNoBusy(cs))
cs->BC_Read_Reg(cs, HFC_DATA_NODEB, cip);
WaitNoBusy(cs);
stat = cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2_INC | HFC_REC |
HFC_CHANNEL(bcs->channel));
WaitForBusy(cs);
return (NULL);
}
if ((count < 4) && (bcs->mode != L1_MODE_TRANS)) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hfc_empty_fifo: incoming packet too small");
cip = HFC_CIP | HFC_FIFO_OUT | HFC_REC | HFC_CHANNEL(bcs->channel);
while ((idx++ < count) && WaitNoBusy(cs))
cs->BC_Read_Reg(cs, HFC_DATA_NODEB, cip);
WaitNoBusy(cs);
stat = cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2_INC | HFC_REC |
HFC_CHANNEL(bcs->channel));
WaitForBusy(cs);
#ifdef ERROR_STATISTIC
bcs->err_inv++;
#endif
return (NULL);
}
if (bcs->mode == L1_MODE_TRANS)
count -= 1;
else
count -= 3;
if (!(skb = dev_alloc_skb(count)))
printk(KERN_WARNING "HFC: receive out of memory\n");
else {
ptr = skb_put(skb, count);
idx = 0;
cip = HFC_CIP | HFC_FIFO_OUT | HFC_REC | HFC_CHANNEL(bcs->channel);
while ((idx < count) && WaitNoBusy(cs)) {
*ptr++ = cs->BC_Read_Reg(cs, HFC_DATA_NODEB, cip);
idx++;
}
if (idx != count) {
debugl1(cs, "RFIFO BUSY error");
printk(KERN_WARNING "HFC FIFO channel %d BUSY Error\n", bcs->channel);
dev_kfree_skb_any(skb);
if (bcs->mode != L1_MODE_TRANS) {
WaitNoBusy(cs);
stat = cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2_INC | HFC_REC |
HFC_CHANNEL(bcs->channel));
WaitForBusy(cs);
}
return (NULL);
}
if (bcs->mode != L1_MODE_TRANS) {
WaitNoBusy(cs);
chksum = (cs->BC_Read_Reg(cs, HFC_DATA, cip) << 8);
WaitNoBusy(cs);
chksum += cs->BC_Read_Reg(cs, HFC_DATA, cip);
WaitNoBusy(cs);
stat = cs->BC_Read_Reg(cs, HFC_DATA, cip);
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc_empty_fifo %d chksum %x stat %x",
bcs->channel, chksum, stat);
if (stat) {
debugl1(cs, "FIFO CRC error");
dev_kfree_skb_any(skb);
skb = NULL;
#ifdef ERROR_STATISTIC
bcs->err_crc++;
#endif
}
WaitNoBusy(cs);
stat = cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F2_INC | HFC_REC |
HFC_CHANNEL(bcs->channel));
WaitForBusy(cs);
}
}
return (skb);
}
static void
hfc_fill_fifo(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
int idx, fcnt;
int count;
int z1, z2;
u_char cip;
if (!bcs->tx_skb)
return;
if (bcs->tx_skb->len <= 0)
return;
cip = HFC_CIP | HFC_F1 | HFC_SEND | HFC_CHANNEL(bcs->channel);
if ((cip & 0xc3) != (cs->hw.hfc.cip & 0xc3)) {
cs->BC_Write_Reg(cs, HFC_STATUS, cip, cip);
WaitForBusy(cs);
}
WaitNoBusy(cs);
if (bcs->mode != L1_MODE_TRANS) {
bcs->hw.hfc.f1 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
cip = HFC_CIP | HFC_F2 | HFC_SEND | HFC_CHANNEL(bcs->channel);
WaitNoBusy(cs);
bcs->hw.hfc.f2 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
bcs->hw.hfc.send[bcs->hw.hfc.f1] = ReadZReg(bcs, HFC_Z1 | HFC_SEND | HFC_CHANNEL(bcs->channel));
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc_fill_fifo %d f1(%d) f2(%d) z1(%x)",
bcs->channel, bcs->hw.hfc.f1, bcs->hw.hfc.f2,
bcs->hw.hfc.send[bcs->hw.hfc.f1]);
fcnt = bcs->hw.hfc.f1 - bcs->hw.hfc.f2;
if (fcnt < 0)
fcnt += 32;
if (fcnt > 30) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc_fill_fifo more as 30 frames");
return;
}
count = GetFreeFifoBytes(bcs);
}
else {
WaitForBusy(cs);
z1 = ReadZReg(bcs, HFC_Z1 | HFC_REC | HFC_CHANNEL(bcs->channel));
z2 = ReadZReg(bcs, HFC_Z2 | HFC_REC | HFC_CHANNEL(bcs->channel));
count = z1 - z2;
if (count < 0)
count += cs->hw.hfc.fifosize;
} /* L1_MODE_TRANS */
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc_fill_fifo %d count(%ld/%d)",
bcs->channel, bcs->tx_skb->len,
count);
if (count < bcs->tx_skb->len) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc_fill_fifo no fifo mem");
return;
}
cip = HFC_CIP | HFC_FIFO_IN | HFC_SEND | HFC_CHANNEL(bcs->channel);
idx = 0;
while ((idx < bcs->tx_skb->len) && WaitNoBusy(cs))
cs->BC_Write_Reg(cs, HFC_DATA_NODEB, cip, bcs->tx_skb->data[idx++]);
if (idx != bcs->tx_skb->len) {
debugl1(cs, "FIFO Send BUSY error");
printk(KERN_WARNING "HFC S FIFO channel %d BUSY Error\n", bcs->channel);
} else {
count = bcs->tx_skb->len;
bcs->tx_cnt -= count;
if (PACKET_NOACK == bcs->tx_skb->pkt_type)
count = -1;
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
if (bcs->mode != L1_MODE_TRANS) {
WaitForBusy(cs);
WaitNoBusy(cs);
cs->BC_Read_Reg(cs, HFC_DATA, HFC_CIP | HFC_F1_INC | HFC_SEND | HFC_CHANNEL(bcs->channel));
}
if (test_bit(FLG_LLI_L1WAKEUP,&bcs->st->lli.flag) &&
(count >= 0)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += count;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
return;
}
void
main_irq_hfc(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
int z1, z2, rcnt;
u_char f1, f2, cip;
int receive, transmit, count = 5;
struct sk_buff *skb;
Begin:
count--;
cip = HFC_CIP | HFC_F1 | HFC_REC | HFC_CHANNEL(bcs->channel);
if ((cip & 0xc3) != (cs->hw.hfc.cip & 0xc3)) {
cs->BC_Write_Reg(cs, HFC_STATUS, cip, cip);
WaitForBusy(cs);
}
WaitNoBusy(cs);
receive = 0;
if (bcs->mode == L1_MODE_HDLC) {
f1 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
cip = HFC_CIP | HFC_F2 | HFC_REC | HFC_CHANNEL(bcs->channel);
WaitNoBusy(cs);
f2 = cs->BC_Read_Reg(cs, HFC_DATA, cip);
if (f1 != f2) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc rec %d f1(%d) f2(%d)",
bcs->channel, f1, f2);
receive = 1;
}
}
if (receive || (bcs->mode == L1_MODE_TRANS)) {
WaitForBusy(cs);
z1 = ReadZReg(bcs, HFC_Z1 | HFC_REC | HFC_CHANNEL(bcs->channel));
z2 = ReadZReg(bcs, HFC_Z2 | HFC_REC | HFC_CHANNEL(bcs->channel));
rcnt = z1 - z2;
if (rcnt < 0)
rcnt += cs->hw.hfc.fifosize;
if ((bcs->mode == L1_MODE_HDLC) || (rcnt)) {
rcnt++;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hfc rec %d z1(%x) z2(%x) cnt(%d)",
bcs->channel, z1, z2, rcnt);
/* sti(); */
if ((skb = hfc_empty_fifo(bcs, rcnt))) {
skb_queue_tail(&bcs->rqueue, skb);
schedule_event(bcs, B_RCVBUFREADY);
}
}
receive = 1;
}
if (bcs->tx_skb) {
transmit = 1;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
hfc_fill_fifo(bcs);
if (test_bit(BC_FLG_BUSY, &bcs->Flag))
transmit = 0;
} else {
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
transmit = 1;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
hfc_fill_fifo(bcs);
if (test_bit(BC_FLG_BUSY, &bcs->Flag))
transmit = 0;
} else {
transmit = 0;
schedule_event(bcs, B_XMTBUFREADY);
}
}
if ((receive || transmit) && count)
goto Begin;
return;
}
static void
mode_hfc(struct BCState *bcs, int mode, int bc)
{
struct IsdnCardState *cs = bcs->cs;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HFC 2BS0 mode %d bchan %d/%d",
mode, bc, bcs->channel);
bcs->mode = mode;
bcs->channel = bc;
switch (mode) {
case (L1_MODE_NULL):
if (bc) {
cs->hw.hfc.ctmt &= ~1;
cs->hw.hfc.isac_spcr &= ~0x03;
}
else {
cs->hw.hfc.ctmt &= ~2;
cs->hw.hfc.isac_spcr &= ~0x0c;
}
break;
case (L1_MODE_TRANS):
cs->hw.hfc.ctmt &= ~(1 << bc); /* set HDLC mode */
cs->BC_Write_Reg(cs, HFC_STATUS, cs->hw.hfc.ctmt, cs->hw.hfc.ctmt);
hfc_clear_fifo(bcs); /* complete fifo clear */
if (bc) {
cs->hw.hfc.ctmt |= 1;
cs->hw.hfc.isac_spcr &= ~0x03;
cs->hw.hfc.isac_spcr |= 0x02;
} else {
cs->hw.hfc.ctmt |= 2;
cs->hw.hfc.isac_spcr &= ~0x0c;
cs->hw.hfc.isac_spcr |= 0x08;
}
break;
case (L1_MODE_HDLC):
if (bc) {
cs->hw.hfc.ctmt &= ~1;
cs->hw.hfc.isac_spcr &= ~0x03;
cs->hw.hfc.isac_spcr |= 0x02;
} else {
cs->hw.hfc.ctmt &= ~2;
cs->hw.hfc.isac_spcr &= ~0x0c;
cs->hw.hfc.isac_spcr |= 0x08;
}
break;
}
cs->BC_Write_Reg(cs, HFC_STATUS, cs->hw.hfc.ctmt, cs->hw.hfc.ctmt);
cs->writeisac(cs, ISAC_SPCR, cs->hw.hfc.isac_spcr);
if (mode == L1_MODE_HDLC)
hfc_clear_fifo(bcs);
}
static void
hfc_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct sk_buff *skb = arg;
u_long flags;
switch (pr) {
case (PH_DATA | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
skb_queue_tail(&bcs->squeue, skb);
} else {
bcs->tx_skb = skb;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
printk(KERN_WARNING "hfc_l2l1: this shouldn't happen\n");
} else {
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->tx_skb = skb;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | REQUEST):
if (!bcs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (PH_ACTIVATE | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag);
mode_hfc(bcs, st->l1.mode, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | REQUEST):
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | CONFIRM):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag);
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
mode_hfc(bcs, 0, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
st->l1.l1l2(st, PH_DEACTIVATE | CONFIRM, NULL);
break;
}
}
static void
close_hfcstate(struct BCState *bcs)
{
mode_hfc(bcs, 0, bcs->channel);
if (test_bit(BC_FLG_INIT, &bcs->Flag)) {
skb_queue_purge(&bcs->rqueue);
skb_queue_purge(&bcs->squeue);
if (bcs->tx_skb) {
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
test_and_clear_bit(BC_FLG_INIT, &bcs->Flag);
}
static int
open_hfcstate(struct IsdnCardState *cs, struct BCState *bcs)
{
if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) {
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
}
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->event = 0;
bcs->tx_cnt = 0;
return (0);
}
static int
setstack_hfc(struct PStack *st, struct BCState *bcs)
{
bcs->channel = st->l1.bc;
if (open_hfcstate(st->l1.hardware, bcs))
return (-1);
st->l1.bcs = bcs;
st->l2.l2l1 = hfc_l2l1;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
return (0);
}
static void
init_send(struct BCState *bcs)
{
int i;
if (!(bcs->hw.hfc.send = kmalloc(32 * sizeof(unsigned int), GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for hfc.send\n");
return;
}
for (i = 0; i < 32; i++)
bcs->hw.hfc.send[i] = 0x1fff;
}
void
inithfc(struct IsdnCardState *cs)
{
init_send(&cs->bcs[0]);
init_send(&cs->bcs[1]);
cs->BC_Send_Data = &hfc_fill_fifo;
cs->bcs[0].BC_SetStack = setstack_hfc;
cs->bcs[1].BC_SetStack = setstack_hfc;
cs->bcs[0].BC_Close = close_hfcstate;
cs->bcs[1].BC_Close = close_hfcstate;
mode_hfc(cs->bcs, 0, 0);
mode_hfc(cs->bcs + 1, 0, 0);
}
void
releasehfc(struct IsdnCardState *cs)
{
kfree(cs->bcs[0].hw.hfc.send);
cs->bcs[0].hw.hfc.send = NULL;
kfree(cs->bcs[1].hw.hfc.send);
cs->bcs[1].hw.hfc.send = NULL;
}
| gpl-2.0 |
satgass/android_kernel_lenovo_msm8916 | drivers/input/misc/gp2ap002a00f.c | 2478 | 6123 | /*
* Copyright (C) 2011 Sony Ericsson Mobile Communications Inc.
*
* Author: Courtney Cavin <courtney.cavin@sonyericsson.com>
* Prepared for up-stream by: Oskar Andero <oskar.andero@sonyericsson.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/i2c.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/input/gp2ap002a00f.h>
struct gp2a_data {
struct input_dev *input;
const struct gp2a_platform_data *pdata;
struct i2c_client *i2c_client;
};
enum gp2a_addr {
GP2A_ADDR_PROX = 0x0,
GP2A_ADDR_GAIN = 0x1,
GP2A_ADDR_HYS = 0x2,
GP2A_ADDR_CYCLE = 0x3,
GP2A_ADDR_OPMOD = 0x4,
GP2A_ADDR_CON = 0x6
};
enum gp2a_controls {
/* Software Shutdown control: 0 = shutdown, 1 = normal operation */
GP2A_CTRL_SSD = 0x01
};
static int gp2a_report(struct gp2a_data *dt)
{
int vo = gpio_get_value(dt->pdata->vout_gpio);
input_report_switch(dt->input, SW_FRONT_PROXIMITY, !vo);
input_sync(dt->input);
return 0;
}
static irqreturn_t gp2a_irq(int irq, void *handle)
{
struct gp2a_data *dt = handle;
gp2a_report(dt);
return IRQ_HANDLED;
}
static int gp2a_enable(struct gp2a_data *dt)
{
return i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_OPMOD,
GP2A_CTRL_SSD);
}
static int gp2a_disable(struct gp2a_data *dt)
{
return i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_OPMOD,
0x00);
}
static int gp2a_device_open(struct input_dev *dev)
{
struct gp2a_data *dt = input_get_drvdata(dev);
int error;
error = gp2a_enable(dt);
if (error < 0) {
dev_err(&dt->i2c_client->dev,
"unable to activate, err %d\n", error);
return error;
}
gp2a_report(dt);
return 0;
}
static void gp2a_device_close(struct input_dev *dev)
{
struct gp2a_data *dt = input_get_drvdata(dev);
int error;
error = gp2a_disable(dt);
if (error < 0)
dev_err(&dt->i2c_client->dev,
"unable to deactivate, err %d\n", error);
}
static int gp2a_initialize(struct gp2a_data *dt)
{
int error;
error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_GAIN,
0x08);
if (error < 0)
return error;
error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_HYS,
0xc2);
if (error < 0)
return error;
error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_CYCLE,
0x04);
if (error < 0)
return error;
error = gp2a_disable(dt);
return error;
}
static int gp2a_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
const struct gp2a_platform_data *pdata = client->dev.platform_data;
struct gp2a_data *dt;
int error;
if (!pdata)
return -EINVAL;
if (pdata->hw_setup) {
error = pdata->hw_setup(client);
if (error < 0)
return error;
}
error = gpio_request_one(pdata->vout_gpio, GPIOF_IN, GP2A_I2C_NAME);
if (error)
goto err_hw_shutdown;
dt = kzalloc(sizeof(struct gp2a_data), GFP_KERNEL);
if (!dt) {
error = -ENOMEM;
goto err_free_gpio;
}
dt->pdata = pdata;
dt->i2c_client = client;
error = gp2a_initialize(dt);
if (error < 0)
goto err_free_mem;
dt->input = input_allocate_device();
if (!dt->input) {
error = -ENOMEM;
goto err_free_mem;
}
input_set_drvdata(dt->input, dt);
dt->input->open = gp2a_device_open;
dt->input->close = gp2a_device_close;
dt->input->name = GP2A_I2C_NAME;
dt->input->id.bustype = BUS_I2C;
dt->input->dev.parent = &client->dev;
input_set_capability(dt->input, EV_SW, SW_FRONT_PROXIMITY);
error = request_threaded_irq(client->irq, NULL, gp2a_irq,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
IRQF_ONESHOT,
GP2A_I2C_NAME, dt);
if (error) {
dev_err(&client->dev, "irq request failed\n");
goto err_free_input_dev;
}
error = input_register_device(dt->input);
if (error) {
dev_err(&client->dev, "device registration failed\n");
goto err_free_irq;
}
device_init_wakeup(&client->dev, pdata->wakeup);
i2c_set_clientdata(client, dt);
return 0;
err_free_irq:
free_irq(client->irq, dt);
err_free_input_dev:
input_free_device(dt->input);
err_free_mem:
kfree(dt);
err_free_gpio:
gpio_free(pdata->vout_gpio);
err_hw_shutdown:
if (pdata->hw_shutdown)
pdata->hw_shutdown(client);
return error;
}
static int gp2a_remove(struct i2c_client *client)
{
struct gp2a_data *dt = i2c_get_clientdata(client);
const struct gp2a_platform_data *pdata = dt->pdata;
device_init_wakeup(&client->dev, false);
free_irq(client->irq, dt);
input_unregister_device(dt->input);
kfree(dt);
gpio_free(pdata->vout_gpio);
if (pdata->hw_shutdown)
pdata->hw_shutdown(client);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int gp2a_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct gp2a_data *dt = i2c_get_clientdata(client);
int retval = 0;
if (device_may_wakeup(&client->dev)) {
enable_irq_wake(client->irq);
} else {
mutex_lock(&dt->input->mutex);
if (dt->input->users)
retval = gp2a_disable(dt);
mutex_unlock(&dt->input->mutex);
}
return retval;
}
static int gp2a_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct gp2a_data *dt = i2c_get_clientdata(client);
int retval = 0;
if (device_may_wakeup(&client->dev)) {
disable_irq_wake(client->irq);
} else {
mutex_lock(&dt->input->mutex);
if (dt->input->users)
retval = gp2a_enable(dt);
mutex_unlock(&dt->input->mutex);
}
return retval;
}
#endif
static SIMPLE_DEV_PM_OPS(gp2a_pm, gp2a_suspend, gp2a_resume);
static const struct i2c_device_id gp2a_i2c_id[] = {
{ GP2A_I2C_NAME, 0 },
{ }
};
static struct i2c_driver gp2a_i2c_driver = {
.driver = {
.name = GP2A_I2C_NAME,
.owner = THIS_MODULE,
.pm = &gp2a_pm,
},
.probe = gp2a_probe,
.remove = gp2a_remove,
.id_table = gp2a_i2c_id,
};
module_i2c_driver(gp2a_i2c_driver);
MODULE_AUTHOR("Courtney Cavin <courtney.cavin@sonyericsson.com>");
MODULE_DESCRIPTION("Sharp GP2AP002A00F I2C Proximity/Opto sensor driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
CyanogenMod/android_kernel_lge_g3 | drivers/s390/scsi/zfcp_aux.c | 3502 | 15538 | /*
* zfcp device driver
*
* Module interface and handling of zfcp data structures.
*
* Copyright IBM Corporation 2002, 2010
*/
/*
* Driver authors:
* Martin Peschke (originator of the driver)
* Raimund Schroeder
* Aron Zeh
* Wolfgang Taphorn
* Stefan Bader
* Heiko Carstens (kernel 2.6 port of the driver)
* Andreas Herrmann
* Maxim Shchetynin
* Volker Sameske
* Ralph Wuerthner
* Michael Loehr
* Swen Schillig
* Christof Schmitt
* Martin Petermann
* Sven Schuetz
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/miscdevice.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/module.h>
#include "zfcp_ext.h"
#include "zfcp_fc.h"
#include "zfcp_reqlist.h"
#define ZFCP_BUS_ID_SIZE 20
MODULE_AUTHOR("IBM Deutschland Entwicklung GmbH - linux390@de.ibm.com");
MODULE_DESCRIPTION("FCP HBA driver");
MODULE_LICENSE("GPL");
static char *init_device;
module_param_named(device, init_device, charp, 0400);
MODULE_PARM_DESC(device, "specify initial device");
static struct kmem_cache * __init zfcp_cache_hw_align(const char *name,
unsigned long size)
{
return kmem_cache_create(name, size, roundup_pow_of_two(size), 0, NULL);
}
static void __init zfcp_init_device_configure(char *busid, u64 wwpn, u64 lun)
{
struct ccw_device *cdev;
struct zfcp_adapter *adapter;
struct zfcp_port *port;
cdev = get_ccwdev_by_busid(&zfcp_ccw_driver, busid);
if (!cdev)
return;
if (ccw_device_set_online(cdev))
goto out_ccw_device;
adapter = zfcp_ccw_adapter_by_cdev(cdev);
if (!adapter)
goto out_ccw_device;
port = zfcp_get_port_by_wwpn(adapter, wwpn);
if (!port)
goto out_port;
flush_work(&port->rport_work);
zfcp_unit_add(port, lun);
put_device(&port->dev);
out_port:
zfcp_ccw_adapter_put(adapter);
out_ccw_device:
put_device(&cdev->dev);
return;
}
static void __init zfcp_init_device_setup(char *devstr)
{
char *token;
char *str, *str_saved;
char busid[ZFCP_BUS_ID_SIZE];
u64 wwpn, lun;
/* duplicate devstr and keep the original for sysfs presentation*/
str_saved = kstrdup(devstr, GFP_KERNEL);
str = str_saved;
if (!str)
return;
token = strsep(&str, ",");
if (!token || strlen(token) >= ZFCP_BUS_ID_SIZE)
goto err_out;
strncpy(busid, token, ZFCP_BUS_ID_SIZE);
token = strsep(&str, ",");
if (!token || strict_strtoull(token, 0, (unsigned long long *) &wwpn))
goto err_out;
token = strsep(&str, ",");
if (!token || strict_strtoull(token, 0, (unsigned long long *) &lun))
goto err_out;
kfree(str_saved);
zfcp_init_device_configure(busid, wwpn, lun);
return;
err_out:
kfree(str_saved);
pr_err("%s is not a valid SCSI device\n", devstr);
}
static int __init zfcp_module_init(void)
{
int retval = -ENOMEM;
zfcp_fsf_qtcb_cache = zfcp_cache_hw_align("zfcp_fsf_qtcb",
sizeof(struct fsf_qtcb));
if (!zfcp_fsf_qtcb_cache)
goto out_qtcb_cache;
zfcp_fc_req_cache = zfcp_cache_hw_align("zfcp_fc_req",
sizeof(struct zfcp_fc_req));
if (!zfcp_fc_req_cache)
goto out_fc_cache;
zfcp_scsi_transport_template =
fc_attach_transport(&zfcp_transport_functions);
if (!zfcp_scsi_transport_template)
goto out_transport;
scsi_transport_reserve_device(zfcp_scsi_transport_template,
sizeof(struct zfcp_scsi_dev));
retval = misc_register(&zfcp_cfdc_misc);
if (retval) {
pr_err("Registering the misc device zfcp_cfdc failed\n");
goto out_misc;
}
retval = ccw_driver_register(&zfcp_ccw_driver);
if (retval) {
pr_err("The zfcp device driver could not register with "
"the common I/O layer\n");
goto out_ccw_register;
}
if (init_device)
zfcp_init_device_setup(init_device);
return 0;
out_ccw_register:
misc_deregister(&zfcp_cfdc_misc);
out_misc:
fc_release_transport(zfcp_scsi_transport_template);
out_transport:
kmem_cache_destroy(zfcp_fc_req_cache);
out_fc_cache:
kmem_cache_destroy(zfcp_fsf_qtcb_cache);
out_qtcb_cache:
return retval;
}
module_init(zfcp_module_init);
static void __exit zfcp_module_exit(void)
{
ccw_driver_unregister(&zfcp_ccw_driver);
misc_deregister(&zfcp_cfdc_misc);
fc_release_transport(zfcp_scsi_transport_template);
kmem_cache_destroy(zfcp_fc_req_cache);
kmem_cache_destroy(zfcp_fsf_qtcb_cache);
}
module_exit(zfcp_module_exit);
/**
* zfcp_get_port_by_wwpn - find port in port list of adapter by wwpn
* @adapter: pointer to adapter to search for port
* @wwpn: wwpn to search for
*
* Returns: pointer to zfcp_port or NULL
*/
struct zfcp_port *zfcp_get_port_by_wwpn(struct zfcp_adapter *adapter,
u64 wwpn)
{
unsigned long flags;
struct zfcp_port *port;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list)
if (port->wwpn == wwpn) {
if (!get_device(&port->dev))
port = NULL;
read_unlock_irqrestore(&adapter->port_list_lock, flags);
return port;
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
return NULL;
}
static int zfcp_allocate_low_mem_buffers(struct zfcp_adapter *adapter)
{
adapter->pool.erp_req =
mempool_create_kmalloc_pool(1, sizeof(struct zfcp_fsf_req));
if (!adapter->pool.erp_req)
return -ENOMEM;
adapter->pool.gid_pn_req =
mempool_create_kmalloc_pool(1, sizeof(struct zfcp_fsf_req));
if (!adapter->pool.gid_pn_req)
return -ENOMEM;
adapter->pool.scsi_req =
mempool_create_kmalloc_pool(1, sizeof(struct zfcp_fsf_req));
if (!adapter->pool.scsi_req)
return -ENOMEM;
adapter->pool.scsi_abort =
mempool_create_kmalloc_pool(1, sizeof(struct zfcp_fsf_req));
if (!adapter->pool.scsi_abort)
return -ENOMEM;
adapter->pool.status_read_req =
mempool_create_kmalloc_pool(FSF_STATUS_READS_RECOM,
sizeof(struct zfcp_fsf_req));
if (!adapter->pool.status_read_req)
return -ENOMEM;
adapter->pool.qtcb_pool =
mempool_create_slab_pool(4, zfcp_fsf_qtcb_cache);
if (!adapter->pool.qtcb_pool)
return -ENOMEM;
BUILD_BUG_ON(sizeof(struct fsf_status_read_buffer) > PAGE_SIZE);
adapter->pool.sr_data =
mempool_create_page_pool(FSF_STATUS_READS_RECOM, 0);
if (!adapter->pool.sr_data)
return -ENOMEM;
adapter->pool.gid_pn =
mempool_create_slab_pool(1, zfcp_fc_req_cache);
if (!adapter->pool.gid_pn)
return -ENOMEM;
return 0;
}
static void zfcp_free_low_mem_buffers(struct zfcp_adapter *adapter)
{
if (adapter->pool.erp_req)
mempool_destroy(adapter->pool.erp_req);
if (adapter->pool.scsi_req)
mempool_destroy(adapter->pool.scsi_req);
if (adapter->pool.scsi_abort)
mempool_destroy(adapter->pool.scsi_abort);
if (adapter->pool.qtcb_pool)
mempool_destroy(adapter->pool.qtcb_pool);
if (adapter->pool.status_read_req)
mempool_destroy(adapter->pool.status_read_req);
if (adapter->pool.sr_data)
mempool_destroy(adapter->pool.sr_data);
if (adapter->pool.gid_pn)
mempool_destroy(adapter->pool.gid_pn);
}
/**
* zfcp_status_read_refill - refill the long running status_read_requests
* @adapter: ptr to struct zfcp_adapter for which the buffers should be refilled
*
* Returns: 0 on success, 1 otherwise
*
* if there are 16 or more status_read requests missing an adapter_reopen
* is triggered
*/
int zfcp_status_read_refill(struct zfcp_adapter *adapter)
{
while (atomic_read(&adapter->stat_miss) > 0)
if (zfcp_fsf_status_read(adapter->qdio)) {
if (atomic_read(&adapter->stat_miss) >=
adapter->stat_read_buf_num) {
zfcp_erp_adapter_reopen(adapter, 0, "axsref1");
return 1;
}
break;
} else
atomic_dec(&adapter->stat_miss);
return 0;
}
static void _zfcp_status_read_scheduler(struct work_struct *work)
{
zfcp_status_read_refill(container_of(work, struct zfcp_adapter,
stat_work));
}
static void zfcp_print_sl(struct seq_file *m, struct service_level *sl)
{
struct zfcp_adapter *adapter =
container_of(sl, struct zfcp_adapter, service_level);
seq_printf(m, "zfcp: %s microcode level %x\n",
dev_name(&adapter->ccw_device->dev),
adapter->fsf_lic_version);
}
static int zfcp_setup_adapter_work_queue(struct zfcp_adapter *adapter)
{
char name[TASK_COMM_LEN];
snprintf(name, sizeof(name), "zfcp_q_%s",
dev_name(&adapter->ccw_device->dev));
adapter->work_queue = create_singlethread_workqueue(name);
if (adapter->work_queue)
return 0;
return -ENOMEM;
}
static void zfcp_destroy_adapter_work_queue(struct zfcp_adapter *adapter)
{
if (adapter->work_queue)
destroy_workqueue(adapter->work_queue);
adapter->work_queue = NULL;
}
/**
* zfcp_adapter_enqueue - enqueue a new adapter to the list
* @ccw_device: pointer to the struct cc_device
*
* Returns: struct zfcp_adapter*
* Enqueues an adapter at the end of the adapter list in the driver data.
* All adapter internal structures are set up.
* Proc-fs entries are also created.
*/
struct zfcp_adapter *zfcp_adapter_enqueue(struct ccw_device *ccw_device)
{
struct zfcp_adapter *adapter;
if (!get_device(&ccw_device->dev))
return ERR_PTR(-ENODEV);
adapter = kzalloc(sizeof(struct zfcp_adapter), GFP_KERNEL);
if (!adapter) {
put_device(&ccw_device->dev);
return ERR_PTR(-ENOMEM);
}
kref_init(&adapter->ref);
ccw_device->handler = NULL;
adapter->ccw_device = ccw_device;
INIT_WORK(&adapter->stat_work, _zfcp_status_read_scheduler);
INIT_WORK(&adapter->scan_work, zfcp_fc_scan_ports);
INIT_WORK(&adapter->ns_up_work, zfcp_fc_sym_name_update);
if (zfcp_qdio_setup(adapter))
goto failed;
if (zfcp_allocate_low_mem_buffers(adapter))
goto failed;
adapter->req_list = zfcp_reqlist_alloc();
if (!adapter->req_list)
goto failed;
if (zfcp_dbf_adapter_register(adapter))
goto failed;
if (zfcp_setup_adapter_work_queue(adapter))
goto failed;
if (zfcp_fc_gs_setup(adapter))
goto failed;
rwlock_init(&adapter->port_list_lock);
INIT_LIST_HEAD(&adapter->port_list);
INIT_LIST_HEAD(&adapter->events.list);
INIT_WORK(&adapter->events.work, zfcp_fc_post_event);
spin_lock_init(&adapter->events.list_lock);
init_waitqueue_head(&adapter->erp_ready_wq);
init_waitqueue_head(&adapter->erp_done_wqh);
INIT_LIST_HEAD(&adapter->erp_ready_head);
INIT_LIST_HEAD(&adapter->erp_running_head);
rwlock_init(&adapter->erp_lock);
rwlock_init(&adapter->abort_lock);
if (zfcp_erp_thread_setup(adapter))
goto failed;
adapter->service_level.seq_print = zfcp_print_sl;
dev_set_drvdata(&ccw_device->dev, adapter);
if (sysfs_create_group(&ccw_device->dev.kobj,
&zfcp_sysfs_adapter_attrs))
goto failed;
/* report size limit per scatter-gather segment */
adapter->dma_parms.max_segment_size = ZFCP_QDIO_SBALE_LEN;
adapter->ccw_device->dev.dma_parms = &adapter->dma_parms;
if (!zfcp_scsi_adapter_register(adapter))
return adapter;
failed:
zfcp_adapter_unregister(adapter);
return ERR_PTR(-ENOMEM);
}
void zfcp_adapter_unregister(struct zfcp_adapter *adapter)
{
struct ccw_device *cdev = adapter->ccw_device;
cancel_work_sync(&adapter->scan_work);
cancel_work_sync(&adapter->stat_work);
cancel_work_sync(&adapter->ns_up_work);
zfcp_destroy_adapter_work_queue(adapter);
zfcp_fc_wka_ports_force_offline(adapter->gs);
zfcp_scsi_adapter_unregister(adapter);
sysfs_remove_group(&cdev->dev.kobj, &zfcp_sysfs_adapter_attrs);
zfcp_erp_thread_kill(adapter);
zfcp_dbf_adapter_unregister(adapter);
zfcp_qdio_destroy(adapter->qdio);
zfcp_ccw_adapter_put(adapter); /* final put to release */
}
/**
* zfcp_adapter_release - remove the adapter from the resource list
* @ref: pointer to struct kref
* locks: adapter list write lock is assumed to be held by caller
*/
void zfcp_adapter_release(struct kref *ref)
{
struct zfcp_adapter *adapter = container_of(ref, struct zfcp_adapter,
ref);
struct ccw_device *cdev = adapter->ccw_device;
dev_set_drvdata(&adapter->ccw_device->dev, NULL);
zfcp_fc_gs_destroy(adapter);
zfcp_free_low_mem_buffers(adapter);
kfree(adapter->req_list);
kfree(adapter->fc_stats);
kfree(adapter->stats_reset_data);
kfree(adapter);
put_device(&cdev->dev);
}
/**
* zfcp_device_unregister - remove port, unit from system
* @dev: reference to device which is to be removed
* @grp: related reference to attribute group
*
* Helper function to unregister port, unit from system
*/
void zfcp_device_unregister(struct device *dev,
const struct attribute_group *grp)
{
sysfs_remove_group(&dev->kobj, grp);
device_unregister(dev);
}
static void zfcp_port_release(struct device *dev)
{
struct zfcp_port *port = container_of(dev, struct zfcp_port, dev);
zfcp_ccw_adapter_put(port->adapter);
kfree(port);
}
/**
* zfcp_port_enqueue - enqueue port to port list of adapter
* @adapter: adapter where remote port is added
* @wwpn: WWPN of the remote port to be enqueued
* @status: initial status for the port
* @d_id: destination id of the remote port to be enqueued
* Returns: pointer to enqueued port on success, ERR_PTR on error
*
* All port internal structures are set up and the sysfs entry is generated.
* d_id is used to enqueue ports with a well known address like the Directory
* Service for nameserver lookup.
*/
struct zfcp_port *zfcp_port_enqueue(struct zfcp_adapter *adapter, u64 wwpn,
u32 status, u32 d_id)
{
struct zfcp_port *port;
int retval = -ENOMEM;
kref_get(&adapter->ref);
port = zfcp_get_port_by_wwpn(adapter, wwpn);
if (port) {
put_device(&port->dev);
retval = -EEXIST;
goto err_out;
}
port = kzalloc(sizeof(struct zfcp_port), GFP_KERNEL);
if (!port)
goto err_out;
rwlock_init(&port->unit_list_lock);
INIT_LIST_HEAD(&port->unit_list);
INIT_WORK(&port->gid_pn_work, zfcp_fc_port_did_lookup);
INIT_WORK(&port->test_link_work, zfcp_fc_link_test_work);
INIT_WORK(&port->rport_work, zfcp_scsi_rport_work);
port->adapter = adapter;
port->d_id = d_id;
port->wwpn = wwpn;
port->rport_task = RPORT_NONE;
port->dev.parent = &adapter->ccw_device->dev;
port->dev.release = zfcp_port_release;
if (dev_set_name(&port->dev, "0x%016llx", (unsigned long long)wwpn)) {
kfree(port);
goto err_out;
}
retval = -EINVAL;
if (device_register(&port->dev)) {
put_device(&port->dev);
goto err_out;
}
if (sysfs_create_group(&port->dev.kobj,
&zfcp_sysfs_port_attrs))
goto err_out_put;
write_lock_irq(&adapter->port_list_lock);
list_add_tail(&port->list, &adapter->port_list);
write_unlock_irq(&adapter->port_list_lock);
atomic_set_mask(status | ZFCP_STATUS_COMMON_RUNNING, &port->status);
return port;
err_out_put:
device_unregister(&port->dev);
err_out:
zfcp_ccw_adapter_put(adapter);
return ERR_PTR(retval);
}
/**
* zfcp_sg_free_table - free memory used by scatterlists
* @sg: pointer to scatterlist
* @count: number of scatterlist which are to be free'ed
* the scatterlist are expected to reference pages always
*/
void zfcp_sg_free_table(struct scatterlist *sg, int count)
{
int i;
for (i = 0; i < count; i++, sg++)
if (sg)
free_page((unsigned long) sg_virt(sg));
else
break;
}
/**
* zfcp_sg_setup_table - init scatterlist and allocate, assign buffers
* @sg: pointer to struct scatterlist
* @count: number of scatterlists which should be assigned with buffers
* of size page
*
* Returns: 0 on success, -ENOMEM otherwise
*/
int zfcp_sg_setup_table(struct scatterlist *sg, int count)
{
void *addr;
int i;
sg_init_table(sg, count);
for (i = 0; i < count; i++, sg++) {
addr = (void *) get_zeroed_page(GFP_KERNEL);
if (!addr) {
zfcp_sg_free_table(sg, i);
return -ENOMEM;
}
sg_set_buf(sg, addr, PAGE_SIZE);
}
return 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_bn_omap | drivers/isdn/capi/capilib.c | 4270 | 4630 |
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/isdn/capilli.h>
#define DBG(format, arg...) do { \
printk(KERN_DEBUG "%s: " format "\n" , __func__ , ## arg); \
} while (0)
struct capilib_msgidqueue {
struct capilib_msgidqueue *next;
u16 msgid;
};
struct capilib_ncci {
struct list_head list;
u16 applid;
u32 ncci;
u32 winsize;
int nmsg;
struct capilib_msgidqueue *msgidqueue;
struct capilib_msgidqueue *msgidlast;
struct capilib_msgidqueue *msgidfree;
struct capilib_msgidqueue msgidpool[CAPI_MAXDATAWINDOW];
};
// ---------------------------------------------------------------------------
// NCCI Handling
static inline void mq_init(struct capilib_ncci * np)
{
u_int i;
np->msgidqueue = NULL;
np->msgidlast = NULL;
np->nmsg = 0;
memset(np->msgidpool, 0, sizeof(np->msgidpool));
np->msgidfree = &np->msgidpool[0];
for (i = 1; i < np->winsize; i++) {
np->msgidpool[i].next = np->msgidfree;
np->msgidfree = &np->msgidpool[i];
}
}
static inline int mq_enqueue(struct capilib_ncci * np, u16 msgid)
{
struct capilib_msgidqueue *mq;
if ((mq = np->msgidfree) == NULL)
return 0;
np->msgidfree = mq->next;
mq->msgid = msgid;
mq->next = NULL;
if (np->msgidlast)
np->msgidlast->next = mq;
np->msgidlast = mq;
if (!np->msgidqueue)
np->msgidqueue = mq;
np->nmsg++;
return 1;
}
static inline int mq_dequeue(struct capilib_ncci * np, u16 msgid)
{
struct capilib_msgidqueue **pp;
for (pp = &np->msgidqueue; *pp; pp = &(*pp)->next) {
if ((*pp)->msgid == msgid) {
struct capilib_msgidqueue *mq = *pp;
*pp = mq->next;
if (mq == np->msgidlast)
np->msgidlast = NULL;
mq->next = np->msgidfree;
np->msgidfree = mq;
np->nmsg--;
return 1;
}
}
return 0;
}
void capilib_new_ncci(struct list_head *head, u16 applid, u32 ncci, u32 winsize)
{
struct capilib_ncci *np;
np = kmalloc(sizeof(*np), GFP_ATOMIC);
if (!np) {
printk(KERN_WARNING "capilib_new_ncci: no memory.\n");
return;
}
if (winsize > CAPI_MAXDATAWINDOW) {
printk(KERN_ERR "capi_new_ncci: winsize %d too big\n",
winsize);
winsize = CAPI_MAXDATAWINDOW;
}
np->applid = applid;
np->ncci = ncci;
np->winsize = winsize;
mq_init(np);
list_add_tail(&np->list, head);
DBG("kcapi: appl %d ncci 0x%x up", applid, ncci);
}
EXPORT_SYMBOL(capilib_new_ncci);
void capilib_free_ncci(struct list_head *head, u16 applid, u32 ncci)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
printk(KERN_INFO "kcapi: appl %d ncci 0x%x down\n", applid, ncci);
list_del(&np->list);
kfree(np);
return;
}
printk(KERN_ERR "capilib_free_ncci: ncci 0x%x not found\n", ncci);
}
EXPORT_SYMBOL(capilib_free_ncci);
void capilib_release_appl(struct list_head *head, u16 applid)
{
struct list_head *l, *n;
struct capilib_ncci *np;
list_for_each_safe(l, n, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
printk(KERN_INFO "kcapi: appl %d ncci 0x%x forced down\n", applid, np->ncci);
list_del(&np->list);
kfree(np);
}
}
EXPORT_SYMBOL(capilib_release_appl);
void capilib_release(struct list_head *head)
{
struct list_head *l, *n;
struct capilib_ncci *np;
list_for_each_safe(l, n, head) {
np = list_entry(l, struct capilib_ncci, list);
printk(KERN_INFO "kcapi: appl %d ncci 0x%x forced down\n", np->applid, np->ncci);
list_del(&np->list);
kfree(np);
}
}
EXPORT_SYMBOL(capilib_release);
u16 capilib_data_b3_req(struct list_head *head, u16 applid, u32 ncci, u16 msgid)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
if (mq_enqueue(np, msgid) == 0)
return CAPI_SENDQUEUEFULL;
return CAPI_NOERROR;
}
printk(KERN_ERR "capilib_data_b3_req: ncci 0x%x not found\n", ncci);
return CAPI_NOERROR;
}
EXPORT_SYMBOL(capilib_data_b3_req);
void capilib_data_b3_conf(struct list_head *head, u16 applid, u32 ncci, u16 msgid)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
if (mq_dequeue(np, msgid) == 0) {
printk(KERN_ERR "kcapi: msgid %hu ncci 0x%x not on queue\n",
msgid, ncci);
}
return;
}
printk(KERN_ERR "capilib_data_b3_conf: ncci 0x%x not found\n", ncci);
}
EXPORT_SYMBOL(capilib_data_b3_conf);
| gpl-2.0 |
dr87/G2-L-KERNEL | arch/x86/kernel/cpu/intel_cacheinfo.c | 4526 | 32777 | /*
* Routines to indentify caches on Intel CPU.
*
* Changes:
* Venkatesh Pallipadi : Adding cache identification through cpuid(4)
* Ashok Raj <ashok.raj@intel.com>: Work with CPU hotplug infrastructure.
* Andi Kleen / Andreas Herrmann : CPUID4 emulation on AMD.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/compiler.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <asm/processor.h>
#include <linux/smp.h>
#include <asm/amd_nb.h>
#include <asm/smp.h>
#define LVL_1_INST 1
#define LVL_1_DATA 2
#define LVL_2 3
#define LVL_3 4
#define LVL_TRACE 5
struct _cache_table {
unsigned char descriptor;
char cache_type;
short size;
};
#define MB(x) ((x) * 1024)
/* All the cache descriptor types we care about (no TLB or
trace cache entries) */
static const struct _cache_table __cpuinitconst cache_table[] =
{
{ 0x06, LVL_1_INST, 8 }, /* 4-way set assoc, 32 byte line size */
{ 0x08, LVL_1_INST, 16 }, /* 4-way set assoc, 32 byte line size */
{ 0x09, LVL_1_INST, 32 }, /* 4-way set assoc, 64 byte line size */
{ 0x0a, LVL_1_DATA, 8 }, /* 2 way set assoc, 32 byte line size */
{ 0x0c, LVL_1_DATA, 16 }, /* 4-way set assoc, 32 byte line size */
{ 0x0d, LVL_1_DATA, 16 }, /* 4-way set assoc, 64 byte line size */
{ 0x0e, LVL_1_DATA, 24 }, /* 6-way set assoc, 64 byte line size */
{ 0x21, LVL_2, 256 }, /* 8-way set assoc, 64 byte line size */
{ 0x22, LVL_3, 512 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x23, LVL_3, MB(1) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x25, LVL_3, MB(2) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x29, LVL_3, MB(4) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x2c, LVL_1_DATA, 32 }, /* 8-way set assoc, 64 byte line size */
{ 0x30, LVL_1_INST, 32 }, /* 8-way set assoc, 64 byte line size */
{ 0x39, LVL_2, 128 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3a, LVL_2, 192 }, /* 6-way set assoc, sectored cache, 64 byte line size */
{ 0x3b, LVL_2, 128 }, /* 2-way set assoc, sectored cache, 64 byte line size */
{ 0x3c, LVL_2, 256 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3d, LVL_2, 384 }, /* 6-way set assoc, sectored cache, 64 byte line size */
{ 0x3e, LVL_2, 512 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3f, LVL_2, 256 }, /* 2-way set assoc, 64 byte line size */
{ 0x41, LVL_2, 128 }, /* 4-way set assoc, 32 byte line size */
{ 0x42, LVL_2, 256 }, /* 4-way set assoc, 32 byte line size */
{ 0x43, LVL_2, 512 }, /* 4-way set assoc, 32 byte line size */
{ 0x44, LVL_2, MB(1) }, /* 4-way set assoc, 32 byte line size */
{ 0x45, LVL_2, MB(2) }, /* 4-way set assoc, 32 byte line size */
{ 0x46, LVL_3, MB(4) }, /* 4-way set assoc, 64 byte line size */
{ 0x47, LVL_3, MB(8) }, /* 8-way set assoc, 64 byte line size */
{ 0x48, LVL_2, MB(3) }, /* 12-way set assoc, 64 byte line size */
{ 0x49, LVL_3, MB(4) }, /* 16-way set assoc, 64 byte line size */
{ 0x4a, LVL_3, MB(6) }, /* 12-way set assoc, 64 byte line size */
{ 0x4b, LVL_3, MB(8) }, /* 16-way set assoc, 64 byte line size */
{ 0x4c, LVL_3, MB(12) }, /* 12-way set assoc, 64 byte line size */
{ 0x4d, LVL_3, MB(16) }, /* 16-way set assoc, 64 byte line size */
{ 0x4e, LVL_2, MB(6) }, /* 24-way set assoc, 64 byte line size */
{ 0x60, LVL_1_DATA, 16 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x66, LVL_1_DATA, 8 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x67, LVL_1_DATA, 16 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x68, LVL_1_DATA, 32 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x70, LVL_TRACE, 12 }, /* 8-way set assoc */
{ 0x71, LVL_TRACE, 16 }, /* 8-way set assoc */
{ 0x72, LVL_TRACE, 32 }, /* 8-way set assoc */
{ 0x73, LVL_TRACE, 64 }, /* 8-way set assoc */
{ 0x78, LVL_2, MB(1) }, /* 4-way set assoc, 64 byte line size */
{ 0x79, LVL_2, 128 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7a, LVL_2, 256 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7b, LVL_2, 512 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7c, LVL_2, MB(1) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7d, LVL_2, MB(2) }, /* 8-way set assoc, 64 byte line size */
{ 0x7f, LVL_2, 512 }, /* 2-way set assoc, 64 byte line size */
{ 0x80, LVL_2, 512 }, /* 8-way set assoc, 64 byte line size */
{ 0x82, LVL_2, 256 }, /* 8-way set assoc, 32 byte line size */
{ 0x83, LVL_2, 512 }, /* 8-way set assoc, 32 byte line size */
{ 0x84, LVL_2, MB(1) }, /* 8-way set assoc, 32 byte line size */
{ 0x85, LVL_2, MB(2) }, /* 8-way set assoc, 32 byte line size */
{ 0x86, LVL_2, 512 }, /* 4-way set assoc, 64 byte line size */
{ 0x87, LVL_2, MB(1) }, /* 8-way set assoc, 64 byte line size */
{ 0xd0, LVL_3, 512 }, /* 4-way set assoc, 64 byte line size */
{ 0xd1, LVL_3, MB(1) }, /* 4-way set assoc, 64 byte line size */
{ 0xd2, LVL_3, MB(2) }, /* 4-way set assoc, 64 byte line size */
{ 0xd6, LVL_3, MB(1) }, /* 8-way set assoc, 64 byte line size */
{ 0xd7, LVL_3, MB(2) }, /* 8-way set assoc, 64 byte line size */
{ 0xd8, LVL_3, MB(4) }, /* 12-way set assoc, 64 byte line size */
{ 0xdc, LVL_3, MB(2) }, /* 12-way set assoc, 64 byte line size */
{ 0xdd, LVL_3, MB(4) }, /* 12-way set assoc, 64 byte line size */
{ 0xde, LVL_3, MB(8) }, /* 12-way set assoc, 64 byte line size */
{ 0xe2, LVL_3, MB(2) }, /* 16-way set assoc, 64 byte line size */
{ 0xe3, LVL_3, MB(4) }, /* 16-way set assoc, 64 byte line size */
{ 0xe4, LVL_3, MB(8) }, /* 16-way set assoc, 64 byte line size */
{ 0xea, LVL_3, MB(12) }, /* 24-way set assoc, 64 byte line size */
{ 0xeb, LVL_3, MB(18) }, /* 24-way set assoc, 64 byte line size */
{ 0xec, LVL_3, MB(24) }, /* 24-way set assoc, 64 byte line size */
{ 0x00, 0, 0}
};
enum _cache_type {
CACHE_TYPE_NULL = 0,
CACHE_TYPE_DATA = 1,
CACHE_TYPE_INST = 2,
CACHE_TYPE_UNIFIED = 3
};
union _cpuid4_leaf_eax {
struct {
enum _cache_type type:5;
unsigned int level:3;
unsigned int is_self_initializing:1;
unsigned int is_fully_associative:1;
unsigned int reserved:4;
unsigned int num_threads_sharing:12;
unsigned int num_cores_on_die:6;
} split;
u32 full;
};
union _cpuid4_leaf_ebx {
struct {
unsigned int coherency_line_size:12;
unsigned int physical_line_partition:10;
unsigned int ways_of_associativity:10;
} split;
u32 full;
};
union _cpuid4_leaf_ecx {
struct {
unsigned int number_of_sets:32;
} split;
u32 full;
};
struct _cpuid4_info_regs {
union _cpuid4_leaf_eax eax;
union _cpuid4_leaf_ebx ebx;
union _cpuid4_leaf_ecx ecx;
unsigned long size;
struct amd_northbridge *nb;
};
struct _cpuid4_info {
struct _cpuid4_info_regs base;
DECLARE_BITMAP(shared_cpu_map, NR_CPUS);
};
unsigned short num_cache_leaves;
/* AMD doesn't have CPUID4. Emulate it here to report the same
information to the user. This makes some assumptions about the machine:
L2 not shared, no SMT etc. that is currently true on AMD CPUs.
In theory the TLBs could be reported as fake type (they are in "dummy").
Maybe later */
union l1_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:8;
unsigned assoc:8;
unsigned size_in_kb:8;
};
unsigned val;
};
union l2_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:4;
unsigned assoc:4;
unsigned size_in_kb:16;
};
unsigned val;
};
union l3_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:4;
unsigned assoc:4;
unsigned res:2;
unsigned size_encoded:14;
};
unsigned val;
};
static const unsigned short __cpuinitconst assocs[] = {
[1] = 1,
[2] = 2,
[4] = 4,
[6] = 8,
[8] = 16,
[0xa] = 32,
[0xb] = 48,
[0xc] = 64,
[0xd] = 96,
[0xe] = 128,
[0xf] = 0xffff /* fully associative - no way to show this currently */
};
static const unsigned char __cpuinitconst levels[] = { 1, 1, 2, 3 };
static const unsigned char __cpuinitconst types[] = { 1, 2, 3, 3 };
static void __cpuinit
amd_cpuid4(int leaf, union _cpuid4_leaf_eax *eax,
union _cpuid4_leaf_ebx *ebx,
union _cpuid4_leaf_ecx *ecx)
{
unsigned dummy;
unsigned line_size, lines_per_tag, assoc, size_in_kb;
union l1_cache l1i, l1d;
union l2_cache l2;
union l3_cache l3;
union l1_cache *l1 = &l1d;
eax->full = 0;
ebx->full = 0;
ecx->full = 0;
cpuid(0x80000005, &dummy, &dummy, &l1d.val, &l1i.val);
cpuid(0x80000006, &dummy, &dummy, &l2.val, &l3.val);
switch (leaf) {
case 1:
l1 = &l1i;
case 0:
if (!l1->val)
return;
assoc = assocs[l1->assoc];
line_size = l1->line_size;
lines_per_tag = l1->lines_per_tag;
size_in_kb = l1->size_in_kb;
break;
case 2:
if (!l2.val)
return;
assoc = assocs[l2.assoc];
line_size = l2.line_size;
lines_per_tag = l2.lines_per_tag;
/* cpu_data has errata corrections for K7 applied */
size_in_kb = __this_cpu_read(cpu_info.x86_cache_size);
break;
case 3:
if (!l3.val)
return;
assoc = assocs[l3.assoc];
line_size = l3.line_size;
lines_per_tag = l3.lines_per_tag;
size_in_kb = l3.size_encoded * 512;
if (boot_cpu_has(X86_FEATURE_AMD_DCM)) {
size_in_kb = size_in_kb >> 1;
assoc = assoc >> 1;
}
break;
default:
return;
}
eax->split.is_self_initializing = 1;
eax->split.type = types[leaf];
eax->split.level = levels[leaf];
eax->split.num_threads_sharing = 0;
eax->split.num_cores_on_die = __this_cpu_read(cpu_info.x86_max_cores) - 1;
if (assoc == 0xffff)
eax->split.is_fully_associative = 1;
ebx->split.coherency_line_size = line_size - 1;
ebx->split.ways_of_associativity = assoc - 1;
ebx->split.physical_line_partition = lines_per_tag - 1;
ecx->split.number_of_sets = (size_in_kb * 1024) / line_size /
(ebx->split.ways_of_associativity + 1) - 1;
}
struct _cache_attr {
struct attribute attr;
ssize_t (*show)(struct _cpuid4_info *, char *, unsigned int);
ssize_t (*store)(struct _cpuid4_info *, const char *, size_t count,
unsigned int);
};
#ifdef CONFIG_AMD_NB
/*
* L3 cache descriptors
*/
static void __cpuinit amd_calc_l3_indices(struct amd_northbridge *nb)
{
struct amd_l3_cache *l3 = &nb->l3_cache;
unsigned int sc0, sc1, sc2, sc3;
u32 val = 0;
pci_read_config_dword(nb->misc, 0x1C4, &val);
/* calculate subcache sizes */
l3->subcaches[0] = sc0 = !(val & BIT(0));
l3->subcaches[1] = sc1 = !(val & BIT(4));
if (boot_cpu_data.x86 == 0x15) {
l3->subcaches[0] = sc0 += !(val & BIT(1));
l3->subcaches[1] = sc1 += !(val & BIT(5));
}
l3->subcaches[2] = sc2 = !(val & BIT(8)) + !(val & BIT(9));
l3->subcaches[3] = sc3 = !(val & BIT(12)) + !(val & BIT(13));
l3->indices = (max(max3(sc0, sc1, sc2), sc3) << 10) - 1;
}
static void __cpuinit amd_init_l3_cache(struct _cpuid4_info_regs *this_leaf, int index)
{
int node;
/* only for L3, and not in virtualized environments */
if (index < 3)
return;
node = amd_get_nb_id(smp_processor_id());
this_leaf->nb = node_to_amd_nb(node);
if (this_leaf->nb && !this_leaf->nb->l3_cache.indices)
amd_calc_l3_indices(this_leaf->nb);
}
/*
* check whether a slot used for disabling an L3 index is occupied.
* @l3: L3 cache descriptor
* @slot: slot number (0..1)
*
* @returns: the disabled index if used or negative value if slot free.
*/
int amd_get_l3_disable_slot(struct amd_northbridge *nb, unsigned slot)
{
unsigned int reg = 0;
pci_read_config_dword(nb->misc, 0x1BC + slot * 4, ®);
/* check whether this slot is activated already */
if (reg & (3UL << 30))
return reg & 0xfff;
return -1;
}
static ssize_t show_cache_disable(struct _cpuid4_info *this_leaf, char *buf,
unsigned int slot)
{
int index;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
return -EINVAL;
index = amd_get_l3_disable_slot(this_leaf->base.nb, slot);
if (index >= 0)
return sprintf(buf, "%d\n", index);
return sprintf(buf, "FREE\n");
}
#define SHOW_CACHE_DISABLE(slot) \
static ssize_t \
show_cache_disable_##slot(struct _cpuid4_info *this_leaf, char *buf, \
unsigned int cpu) \
{ \
return show_cache_disable(this_leaf, buf, slot); \
}
SHOW_CACHE_DISABLE(0)
SHOW_CACHE_DISABLE(1)
static void amd_l3_disable_index(struct amd_northbridge *nb, int cpu,
unsigned slot, unsigned long idx)
{
int i;
idx |= BIT(30);
/*
* disable index in all 4 subcaches
*/
for (i = 0; i < 4; i++) {
u32 reg = idx | (i << 20);
if (!nb->l3_cache.subcaches[i])
continue;
pci_write_config_dword(nb->misc, 0x1BC + slot * 4, reg);
/*
* We need to WBINVD on a core on the node containing the L3
* cache which indices we disable therefore a simple wbinvd()
* is not sufficient.
*/
wbinvd_on_cpu(cpu);
reg |= BIT(31);
pci_write_config_dword(nb->misc, 0x1BC + slot * 4, reg);
}
}
/*
* disable a L3 cache index by using a disable-slot
*
* @l3: L3 cache descriptor
* @cpu: A CPU on the node containing the L3 cache
* @slot: slot number (0..1)
* @index: index to disable
*
* @return: 0 on success, error status on failure
*/
int amd_set_l3_disable_slot(struct amd_northbridge *nb, int cpu, unsigned slot,
unsigned long index)
{
int ret = 0;
/* check if @slot is already used or the index is already disabled */
ret = amd_get_l3_disable_slot(nb, slot);
if (ret >= 0)
return -EEXIST;
if (index > nb->l3_cache.indices)
return -EINVAL;
/* check whether the other slot has disabled the same index already */
if (index == amd_get_l3_disable_slot(nb, !slot))
return -EEXIST;
amd_l3_disable_index(nb, cpu, slot, index);
return 0;
}
static ssize_t store_cache_disable(struct _cpuid4_info *this_leaf,
const char *buf, size_t count,
unsigned int slot)
{
unsigned long val = 0;
int cpu, err = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
return -EINVAL;
cpu = cpumask_first(to_cpumask(this_leaf->shared_cpu_map));
if (strict_strtoul(buf, 10, &val) < 0)
return -EINVAL;
err = amd_set_l3_disable_slot(this_leaf->base.nb, cpu, slot, val);
if (err) {
if (err == -EEXIST)
pr_warning("L3 slot %d in use/index already disabled!\n",
slot);
return err;
}
return count;
}
#define STORE_CACHE_DISABLE(slot) \
static ssize_t \
store_cache_disable_##slot(struct _cpuid4_info *this_leaf, \
const char *buf, size_t count, \
unsigned int cpu) \
{ \
return store_cache_disable(this_leaf, buf, count, slot); \
}
STORE_CACHE_DISABLE(0)
STORE_CACHE_DISABLE(1)
static struct _cache_attr cache_disable_0 = __ATTR(cache_disable_0, 0644,
show_cache_disable_0, store_cache_disable_0);
static struct _cache_attr cache_disable_1 = __ATTR(cache_disable_1, 0644,
show_cache_disable_1, store_cache_disable_1);
static ssize_t
show_subcaches(struct _cpuid4_info *this_leaf, char *buf, unsigned int cpu)
{
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
return -EINVAL;
return sprintf(buf, "%x\n", amd_get_subcaches(cpu));
}
static ssize_t
store_subcaches(struct _cpuid4_info *this_leaf, const char *buf, size_t count,
unsigned int cpu)
{
unsigned long val;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
return -EINVAL;
if (strict_strtoul(buf, 16, &val) < 0)
return -EINVAL;
if (amd_set_subcaches(cpu, val))
return -EINVAL;
return count;
}
static struct _cache_attr subcaches =
__ATTR(subcaches, 0644, show_subcaches, store_subcaches);
#else /* CONFIG_AMD_NB */
#define amd_init_l3_cache(x, y)
#endif /* CONFIG_AMD_NB */
static int
__cpuinit cpuid4_cache_lookup_regs(int index,
struct _cpuid4_info_regs *this_leaf)
{
union _cpuid4_leaf_eax eax;
union _cpuid4_leaf_ebx ebx;
union _cpuid4_leaf_ecx ecx;
unsigned edx;
if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) {
amd_cpuid4(index, &eax, &ebx, &ecx);
amd_init_l3_cache(this_leaf, index);
} else {
cpuid_count(4, index, &eax.full, &ebx.full, &ecx.full, &edx);
}
if (eax.split.type == CACHE_TYPE_NULL)
return -EIO; /* better error ? */
this_leaf->eax = eax;
this_leaf->ebx = ebx;
this_leaf->ecx = ecx;
this_leaf->size = (ecx.split.number_of_sets + 1) *
(ebx.split.coherency_line_size + 1) *
(ebx.split.physical_line_partition + 1) *
(ebx.split.ways_of_associativity + 1);
return 0;
}
static int __cpuinit find_num_cache_leaves(void)
{
unsigned int eax, ebx, ecx, edx;
union _cpuid4_leaf_eax cache_eax;
int i = -1;
do {
++i;
/* Do cpuid(4) loop to find out num_cache_leaves */
cpuid_count(4, i, &eax, &ebx, &ecx, &edx);
cache_eax.full = eax;
} while (cache_eax.split.type != CACHE_TYPE_NULL);
return i;
}
unsigned int __cpuinit init_intel_cacheinfo(struct cpuinfo_x86 *c)
{
/* Cache sizes */
unsigned int trace = 0, l1i = 0, l1d = 0, l2 = 0, l3 = 0;
unsigned int new_l1d = 0, new_l1i = 0; /* Cache sizes from cpuid(4) */
unsigned int new_l2 = 0, new_l3 = 0, i; /* Cache sizes from cpuid(4) */
unsigned int l2_id = 0, l3_id = 0, num_threads_sharing, index_msb;
#ifdef CONFIG_X86_HT
unsigned int cpu = c->cpu_index;
#endif
if (c->cpuid_level > 3) {
static int is_initialized;
if (is_initialized == 0) {
/* Init num_cache_leaves from boot CPU */
num_cache_leaves = find_num_cache_leaves();
is_initialized++;
}
/*
* Whenever possible use cpuid(4), deterministic cache
* parameters cpuid leaf to find the cache details
*/
for (i = 0; i < num_cache_leaves; i++) {
struct _cpuid4_info_regs this_leaf;
int retval;
retval = cpuid4_cache_lookup_regs(i, &this_leaf);
if (retval >= 0) {
switch (this_leaf.eax.split.level) {
case 1:
if (this_leaf.eax.split.type ==
CACHE_TYPE_DATA)
new_l1d = this_leaf.size/1024;
else if (this_leaf.eax.split.type ==
CACHE_TYPE_INST)
new_l1i = this_leaf.size/1024;
break;
case 2:
new_l2 = this_leaf.size/1024;
num_threads_sharing = 1 + this_leaf.eax.split.num_threads_sharing;
index_msb = get_count_order(num_threads_sharing);
l2_id = c->apicid >> index_msb;
break;
case 3:
new_l3 = this_leaf.size/1024;
num_threads_sharing = 1 + this_leaf.eax.split.num_threads_sharing;
index_msb = get_count_order(
num_threads_sharing);
l3_id = c->apicid >> index_msb;
break;
default:
break;
}
}
}
}
/*
* Don't use cpuid2 if cpuid4 is supported. For P4, we use cpuid2 for
* trace cache
*/
if ((num_cache_leaves == 0 || c->x86 == 15) && c->cpuid_level > 1) {
/* supports eax=2 call */
int j, n;
unsigned int regs[4];
unsigned char *dp = (unsigned char *)regs;
int only_trace = 0;
if (num_cache_leaves != 0 && c->x86 == 15)
only_trace = 1;
/* Number of times to iterate */
n = cpuid_eax(2) & 0xFF;
for (i = 0 ; i < n ; i++) {
cpuid(2, ®s[0], ®s[1], ®s[2], ®s[3]);
/* If bit 31 is set, this is an unknown format */
for (j = 0 ; j < 3 ; j++)
if (regs[j] & (1 << 31))
regs[j] = 0;
/* Byte 0 is level count, not a descriptor */
for (j = 1 ; j < 16 ; j++) {
unsigned char des = dp[j];
unsigned char k = 0;
/* look up this descriptor in the table */
while (cache_table[k].descriptor != 0) {
if (cache_table[k].descriptor == des) {
if (only_trace && cache_table[k].cache_type != LVL_TRACE)
break;
switch (cache_table[k].cache_type) {
case LVL_1_INST:
l1i += cache_table[k].size;
break;
case LVL_1_DATA:
l1d += cache_table[k].size;
break;
case LVL_2:
l2 += cache_table[k].size;
break;
case LVL_3:
l3 += cache_table[k].size;
break;
case LVL_TRACE:
trace += cache_table[k].size;
break;
}
break;
}
k++;
}
}
}
}
if (new_l1d)
l1d = new_l1d;
if (new_l1i)
l1i = new_l1i;
if (new_l2) {
l2 = new_l2;
#ifdef CONFIG_X86_HT
per_cpu(cpu_llc_id, cpu) = l2_id;
#endif
}
if (new_l3) {
l3 = new_l3;
#ifdef CONFIG_X86_HT
per_cpu(cpu_llc_id, cpu) = l3_id;
#endif
}
c->x86_cache_size = l3 ? l3 : (l2 ? l2 : (l1i+l1d));
return l2;
}
#ifdef CONFIG_SYSFS
/* pointer to _cpuid4_info array (for each cache leaf) */
static DEFINE_PER_CPU(struct _cpuid4_info *, ici_cpuid4_info);
#define CPUID4_INFO_IDX(x, y) (&((per_cpu(ici_cpuid4_info, x))[y]))
#ifdef CONFIG_SMP
static int __cpuinit cache_shared_amd_cpu_map_setup(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf;
int ret, i, sibling;
struct cpuinfo_x86 *c = &cpu_data(cpu);
ret = 0;
if (index == 3) {
ret = 1;
for_each_cpu(i, cpu_llc_shared_mask(cpu)) {
if (!per_cpu(ici_cpuid4_info, i))
continue;
this_leaf = CPUID4_INFO_IDX(i, index);
for_each_cpu(sibling, cpu_llc_shared_mask(cpu)) {
if (!cpu_online(sibling))
continue;
set_bit(sibling, this_leaf->shared_cpu_map);
}
}
} else if ((c->x86 == 0x15) && ((index == 1) || (index == 2))) {
ret = 1;
for_each_cpu(i, cpu_sibling_mask(cpu)) {
if (!per_cpu(ici_cpuid4_info, i))
continue;
this_leaf = CPUID4_INFO_IDX(i, index);
for_each_cpu(sibling, cpu_sibling_mask(cpu)) {
if (!cpu_online(sibling))
continue;
set_bit(sibling, this_leaf->shared_cpu_map);
}
}
}
return ret;
}
static void __cpuinit cache_shared_cpu_map_setup(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf, *sibling_leaf;
unsigned long num_threads_sharing;
int index_msb, i;
struct cpuinfo_x86 *c = &cpu_data(cpu);
if (c->x86_vendor == X86_VENDOR_AMD) {
if (cache_shared_amd_cpu_map_setup(cpu, index))
return;
}
this_leaf = CPUID4_INFO_IDX(cpu, index);
num_threads_sharing = 1 + this_leaf->base.eax.split.num_threads_sharing;
if (num_threads_sharing == 1)
cpumask_set_cpu(cpu, to_cpumask(this_leaf->shared_cpu_map));
else {
index_msb = get_count_order(num_threads_sharing);
for_each_online_cpu(i) {
if (cpu_data(i).apicid >> index_msb ==
c->apicid >> index_msb) {
cpumask_set_cpu(i,
to_cpumask(this_leaf->shared_cpu_map));
if (i != cpu && per_cpu(ici_cpuid4_info, i)) {
sibling_leaf =
CPUID4_INFO_IDX(i, index);
cpumask_set_cpu(cpu, to_cpumask(
sibling_leaf->shared_cpu_map));
}
}
}
}
}
static void __cpuinit cache_remove_shared_cpu_map(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf, *sibling_leaf;
int sibling;
this_leaf = CPUID4_INFO_IDX(cpu, index);
for_each_cpu(sibling, to_cpumask(this_leaf->shared_cpu_map)) {
sibling_leaf = CPUID4_INFO_IDX(sibling, index);
cpumask_clear_cpu(cpu,
to_cpumask(sibling_leaf->shared_cpu_map));
}
}
#else
static void __cpuinit cache_shared_cpu_map_setup(unsigned int cpu, int index)
{
}
static void __cpuinit cache_remove_shared_cpu_map(unsigned int cpu, int index)
{
}
#endif
static void __cpuinit free_cache_attributes(unsigned int cpu)
{
int i;
for (i = 0; i < num_cache_leaves; i++)
cache_remove_shared_cpu_map(cpu, i);
kfree(per_cpu(ici_cpuid4_info, cpu));
per_cpu(ici_cpuid4_info, cpu) = NULL;
}
static void __cpuinit get_cpu_leaves(void *_retval)
{
int j, *retval = _retval, cpu = smp_processor_id();
/* Do cpuid and store the results */
for (j = 0; j < num_cache_leaves; j++) {
struct _cpuid4_info *this_leaf = CPUID4_INFO_IDX(cpu, j);
*retval = cpuid4_cache_lookup_regs(j, &this_leaf->base);
if (unlikely(*retval < 0)) {
int i;
for (i = 0; i < j; i++)
cache_remove_shared_cpu_map(cpu, i);
break;
}
cache_shared_cpu_map_setup(cpu, j);
}
}
static int __cpuinit detect_cache_attributes(unsigned int cpu)
{
int retval;
if (num_cache_leaves == 0)
return -ENOENT;
per_cpu(ici_cpuid4_info, cpu) = kzalloc(
sizeof(struct _cpuid4_info) * num_cache_leaves, GFP_KERNEL);
if (per_cpu(ici_cpuid4_info, cpu) == NULL)
return -ENOMEM;
smp_call_function_single(cpu, get_cpu_leaves, &retval, true);
if (retval) {
kfree(per_cpu(ici_cpuid4_info, cpu));
per_cpu(ici_cpuid4_info, cpu) = NULL;
}
return retval;
}
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/cpu.h>
/* pointer to kobject for cpuX/cache */
static DEFINE_PER_CPU(struct kobject *, ici_cache_kobject);
struct _index_kobject {
struct kobject kobj;
unsigned int cpu;
unsigned short index;
};
/* pointer to array of kobjects for cpuX/cache/indexY */
static DEFINE_PER_CPU(struct _index_kobject *, ici_index_kobject);
#define INDEX_KOBJECT_PTR(x, y) (&((per_cpu(ici_index_kobject, x))[y]))
#define show_one_plus(file_name, object, val) \
static ssize_t show_##file_name(struct _cpuid4_info *this_leaf, char *buf, \
unsigned int cpu) \
{ \
return sprintf(buf, "%lu\n", (unsigned long)this_leaf->object + val); \
}
show_one_plus(level, base.eax.split.level, 0);
show_one_plus(coherency_line_size, base.ebx.split.coherency_line_size, 1);
show_one_plus(physical_line_partition, base.ebx.split.physical_line_partition, 1);
show_one_plus(ways_of_associativity, base.ebx.split.ways_of_associativity, 1);
show_one_plus(number_of_sets, base.ecx.split.number_of_sets, 1);
static ssize_t show_size(struct _cpuid4_info *this_leaf, char *buf,
unsigned int cpu)
{
return sprintf(buf, "%luK\n", this_leaf->base.size / 1024);
}
static ssize_t show_shared_cpu_map_func(struct _cpuid4_info *this_leaf,
int type, char *buf)
{
ptrdiff_t len = PTR_ALIGN(buf + PAGE_SIZE - 1, PAGE_SIZE) - buf;
int n = 0;
if (len > 1) {
const struct cpumask *mask;
mask = to_cpumask(this_leaf->shared_cpu_map);
n = type ?
cpulist_scnprintf(buf, len-2, mask) :
cpumask_scnprintf(buf, len-2, mask);
buf[n++] = '\n';
buf[n] = '\0';
}
return n;
}
static inline ssize_t show_shared_cpu_map(struct _cpuid4_info *leaf, char *buf,
unsigned int cpu)
{
return show_shared_cpu_map_func(leaf, 0, buf);
}
static inline ssize_t show_shared_cpu_list(struct _cpuid4_info *leaf, char *buf,
unsigned int cpu)
{
return show_shared_cpu_map_func(leaf, 1, buf);
}
static ssize_t show_type(struct _cpuid4_info *this_leaf, char *buf,
unsigned int cpu)
{
switch (this_leaf->base.eax.split.type) {
case CACHE_TYPE_DATA:
return sprintf(buf, "Data\n");
case CACHE_TYPE_INST:
return sprintf(buf, "Instruction\n");
case CACHE_TYPE_UNIFIED:
return sprintf(buf, "Unified\n");
default:
return sprintf(buf, "Unknown\n");
}
}
#define to_object(k) container_of(k, struct _index_kobject, kobj)
#define to_attr(a) container_of(a, struct _cache_attr, attr)
#define define_one_ro(_name) \
static struct _cache_attr _name = \
__ATTR(_name, 0444, show_##_name, NULL)
define_one_ro(level);
define_one_ro(type);
define_one_ro(coherency_line_size);
define_one_ro(physical_line_partition);
define_one_ro(ways_of_associativity);
define_one_ro(number_of_sets);
define_one_ro(size);
define_one_ro(shared_cpu_map);
define_one_ro(shared_cpu_list);
static struct attribute *default_attrs[] = {
&type.attr,
&level.attr,
&coherency_line_size.attr,
&physical_line_partition.attr,
&ways_of_associativity.attr,
&number_of_sets.attr,
&size.attr,
&shared_cpu_map.attr,
&shared_cpu_list.attr,
NULL
};
#ifdef CONFIG_AMD_NB
static struct attribute ** __cpuinit amd_l3_attrs(void)
{
static struct attribute **attrs;
int n;
if (attrs)
return attrs;
n = sizeof (default_attrs) / sizeof (struct attribute *);
if (amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
n += 2;
if (amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
n += 1;
attrs = kzalloc(n * sizeof (struct attribute *), GFP_KERNEL);
if (attrs == NULL)
return attrs = default_attrs;
for (n = 0; default_attrs[n]; n++)
attrs[n] = default_attrs[n];
if (amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE)) {
attrs[n++] = &cache_disable_0.attr;
attrs[n++] = &cache_disable_1.attr;
}
if (amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
attrs[n++] = &subcaches.attr;
return attrs;
}
#endif
static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
{
struct _cache_attr *fattr = to_attr(attr);
struct _index_kobject *this_leaf = to_object(kobj);
ssize_t ret;
ret = fattr->show ?
fattr->show(CPUID4_INFO_IDX(this_leaf->cpu, this_leaf->index),
buf, this_leaf->cpu) :
0;
return ret;
}
static ssize_t store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct _cache_attr *fattr = to_attr(attr);
struct _index_kobject *this_leaf = to_object(kobj);
ssize_t ret;
ret = fattr->store ?
fattr->store(CPUID4_INFO_IDX(this_leaf->cpu, this_leaf->index),
buf, count, this_leaf->cpu) :
0;
return ret;
}
static const struct sysfs_ops sysfs_ops = {
.show = show,
.store = store,
};
static struct kobj_type ktype_cache = {
.sysfs_ops = &sysfs_ops,
.default_attrs = default_attrs,
};
static struct kobj_type ktype_percpu_entry = {
.sysfs_ops = &sysfs_ops,
};
static void __cpuinit cpuid4_cache_sysfs_exit(unsigned int cpu)
{
kfree(per_cpu(ici_cache_kobject, cpu));
kfree(per_cpu(ici_index_kobject, cpu));
per_cpu(ici_cache_kobject, cpu) = NULL;
per_cpu(ici_index_kobject, cpu) = NULL;
free_cache_attributes(cpu);
}
static int __cpuinit cpuid4_cache_sysfs_init(unsigned int cpu)
{
int err;
if (num_cache_leaves == 0)
return -ENOENT;
err = detect_cache_attributes(cpu);
if (err)
return err;
/* Allocate all required memory */
per_cpu(ici_cache_kobject, cpu) =
kzalloc(sizeof(struct kobject), GFP_KERNEL);
if (unlikely(per_cpu(ici_cache_kobject, cpu) == NULL))
goto err_out;
per_cpu(ici_index_kobject, cpu) = kzalloc(
sizeof(struct _index_kobject) * num_cache_leaves, GFP_KERNEL);
if (unlikely(per_cpu(ici_index_kobject, cpu) == NULL))
goto err_out;
return 0;
err_out:
cpuid4_cache_sysfs_exit(cpu);
return -ENOMEM;
}
static DECLARE_BITMAP(cache_dev_map, NR_CPUS);
/* Add/Remove cache interface for CPU device */
static int __cpuinit cache_add_dev(struct device *dev)
{
unsigned int cpu = dev->id;
unsigned long i, j;
struct _index_kobject *this_object;
struct _cpuid4_info *this_leaf;
int retval;
retval = cpuid4_cache_sysfs_init(cpu);
if (unlikely(retval < 0))
return retval;
retval = kobject_init_and_add(per_cpu(ici_cache_kobject, cpu),
&ktype_percpu_entry,
&dev->kobj, "%s", "cache");
if (retval < 0) {
cpuid4_cache_sysfs_exit(cpu);
return retval;
}
for (i = 0; i < num_cache_leaves; i++) {
this_object = INDEX_KOBJECT_PTR(cpu, i);
this_object->cpu = cpu;
this_object->index = i;
this_leaf = CPUID4_INFO_IDX(cpu, i);
ktype_cache.default_attrs = default_attrs;
#ifdef CONFIG_AMD_NB
if (this_leaf->base.nb)
ktype_cache.default_attrs = amd_l3_attrs();
#endif
retval = kobject_init_and_add(&(this_object->kobj),
&ktype_cache,
per_cpu(ici_cache_kobject, cpu),
"index%1lu", i);
if (unlikely(retval)) {
for (j = 0; j < i; j++)
kobject_put(&(INDEX_KOBJECT_PTR(cpu, j)->kobj));
kobject_put(per_cpu(ici_cache_kobject, cpu));
cpuid4_cache_sysfs_exit(cpu);
return retval;
}
kobject_uevent(&(this_object->kobj), KOBJ_ADD);
}
cpumask_set_cpu(cpu, to_cpumask(cache_dev_map));
kobject_uevent(per_cpu(ici_cache_kobject, cpu), KOBJ_ADD);
return 0;
}
static void __cpuinit cache_remove_dev(struct device *dev)
{
unsigned int cpu = dev->id;
unsigned long i;
if (per_cpu(ici_cpuid4_info, cpu) == NULL)
return;
if (!cpumask_test_cpu(cpu, to_cpumask(cache_dev_map)))
return;
cpumask_clear_cpu(cpu, to_cpumask(cache_dev_map));
for (i = 0; i < num_cache_leaves; i++)
kobject_put(&(INDEX_KOBJECT_PTR(cpu, i)->kobj));
kobject_put(per_cpu(ici_cache_kobject, cpu));
cpuid4_cache_sysfs_exit(cpu);
}
static int __cpuinit cacheinfo_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct device *dev;
dev = get_cpu_device(cpu);
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
cache_add_dev(dev);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
cache_remove_dev(dev);
break;
}
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata cacheinfo_cpu_notifier = {
.notifier_call = cacheinfo_cpu_callback,
};
static int __cpuinit cache_sysfs_init(void)
{
int i;
if (num_cache_leaves == 0)
return 0;
for_each_online_cpu(i) {
int err;
struct device *dev = get_cpu_device(i);
err = cache_add_dev(dev);
if (err)
return err;
}
register_hotcpu_notifier(&cacheinfo_cpu_notifier);
return 0;
}
device_initcall(cache_sysfs_init);
#endif
| gpl-2.0 |
aniketroxx/civic-sa77 | arch/m68k/hp300/config.c | 4782 | 6671 | /*
* linux/arch/m68k/hp300/config.c
*
* Copyright (C) 1998 Philip Blundell <philb@gnu.org>
*
* This file contains the HP300-specific initialisation code. It gets
* called by setup.c.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/console.h>
#include <asm/bootinfo.h>
#include <asm/machdep.h>
#include <asm/blinken.h>
#include <asm/io.h> /* readb() and writeb() */
#include <asm/hp300hw.h>
#include <asm/rtc.h>
#include "time.h"
unsigned long hp300_model;
unsigned long hp300_uart_scode = -1;
unsigned char hp300_ledstate;
EXPORT_SYMBOL(hp300_ledstate);
static char s_hp330[] __initdata = "330";
static char s_hp340[] __initdata = "340";
static char s_hp345[] __initdata = "345";
static char s_hp360[] __initdata = "360";
static char s_hp370[] __initdata = "370";
static char s_hp375[] __initdata = "375";
static char s_hp380[] __initdata = "380";
static char s_hp385[] __initdata = "385";
static char s_hp400[] __initdata = "400";
static char s_hp425t[] __initdata = "425t";
static char s_hp425s[] __initdata = "425s";
static char s_hp425e[] __initdata = "425e";
static char s_hp433t[] __initdata = "433t";
static char s_hp433s[] __initdata = "433s";
static char *hp300_models[] __initdata = {
[HP_320] = NULL,
[HP_330] = s_hp330,
[HP_340] = s_hp340,
[HP_345] = s_hp345,
[HP_350] = NULL,
[HP_360] = s_hp360,
[HP_370] = s_hp370,
[HP_375] = s_hp375,
[HP_380] = s_hp380,
[HP_385] = s_hp385,
[HP_400] = s_hp400,
[HP_425T] = s_hp425t,
[HP_425S] = s_hp425s,
[HP_425E] = s_hp425e,
[HP_433T] = s_hp433t,
[HP_433S] = s_hp433s,
};
static char hp300_model_name[13] = "HP9000/";
extern void hp300_reset(void);
#ifdef CONFIG_SERIAL_8250_CONSOLE
extern int hp300_setup_serial_console(void) __init;
#endif
int __init hp300_parse_bootinfo(const struct bi_record *record)
{
int unknown = 0;
const unsigned long *data = record->data;
switch (record->tag) {
case BI_HP300_MODEL:
hp300_model = *data;
break;
case BI_HP300_UART_SCODE:
hp300_uart_scode = *data;
break;
case BI_HP300_UART_ADDR:
/* serial port address: ignored here */
break;
default:
unknown = 1;
}
return unknown;
}
#ifdef CONFIG_HEARTBEAT
static void hp300_pulse(int x)
{
if (x)
blinken_leds(0x10, 0);
else
blinken_leds(0, 0x10);
}
#endif
static void hp300_get_model(char *model)
{
strcpy(model, hp300_model_name);
}
#define RTCBASE 0xf0420000
#define RTC_DATA 0x1
#define RTC_CMD 0x3
#define RTC_BUSY 0x02
#define RTC_DATA_RDY 0x01
#define rtc_busy() (in_8(RTCBASE + RTC_CMD) & RTC_BUSY)
#define rtc_data_available() (in_8(RTCBASE + RTC_CMD) & RTC_DATA_RDY)
#define rtc_status() (in_8(RTCBASE + RTC_CMD))
#define rtc_command(x) out_8(RTCBASE + RTC_CMD, (x))
#define rtc_read_data() (in_8(RTCBASE + RTC_DATA))
#define rtc_write_data(x) out_8(RTCBASE + RTC_DATA, (x))
#define RTC_SETREG 0xe0
#define RTC_WRITEREG 0xc2
#define RTC_READREG 0xc3
#define RTC_REG_SEC2 0
#define RTC_REG_SEC1 1
#define RTC_REG_MIN2 2
#define RTC_REG_MIN1 3
#define RTC_REG_HOUR2 4
#define RTC_REG_HOUR1 5
#define RTC_REG_WDAY 6
#define RTC_REG_DAY2 7
#define RTC_REG_DAY1 8
#define RTC_REG_MON2 9
#define RTC_REG_MON1 10
#define RTC_REG_YEAR2 11
#define RTC_REG_YEAR1 12
#define RTC_HOUR1_24HMODE 0x8
#define RTC_STAT_MASK 0xf0
#define RTC_STAT_RDY 0x40
static inline unsigned char hp300_rtc_read(unsigned char reg)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data(reg);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static inline unsigned char hp300_rtc_write(unsigned char reg,
unsigned char val)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data((val << 4) | reg);
while (rtc_busy());
rtc_command(RTC_WRITEREG);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static int hp300_hwclk(int op, struct rtc_time *t)
{
if (!op) { /* read */
t->tm_sec = hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
t->tm_min = hp300_rtc_read(RTC_REG_MIN1) * 10 +
hp300_rtc_read(RTC_REG_MIN2);
t->tm_hour = (hp300_rtc_read(RTC_REG_HOUR1) & 3) * 10 +
hp300_rtc_read(RTC_REG_HOUR2);
t->tm_wday = -1;
t->tm_mday = hp300_rtc_read(RTC_REG_DAY1) * 10 +
hp300_rtc_read(RTC_REG_DAY2);
t->tm_mon = hp300_rtc_read(RTC_REG_MON1) * 10 +
hp300_rtc_read(RTC_REG_MON2) - 1;
t->tm_year = hp300_rtc_read(RTC_REG_YEAR1) * 10 +
hp300_rtc_read(RTC_REG_YEAR2);
if (t->tm_year <= 69)
t->tm_year += 100;
} else {
hp300_rtc_write(RTC_REG_SEC1, t->tm_sec / 10);
hp300_rtc_write(RTC_REG_SEC2, t->tm_sec % 10);
hp300_rtc_write(RTC_REG_MIN1, t->tm_min / 10);
hp300_rtc_write(RTC_REG_MIN2, t->tm_min % 10);
hp300_rtc_write(RTC_REG_HOUR1,
((t->tm_hour / 10) & 3) | RTC_HOUR1_24HMODE);
hp300_rtc_write(RTC_REG_HOUR2, t->tm_hour % 10);
hp300_rtc_write(RTC_REG_DAY1, t->tm_mday / 10);
hp300_rtc_write(RTC_REG_DAY2, t->tm_mday % 10);
hp300_rtc_write(RTC_REG_MON1, (t->tm_mon + 1) / 10);
hp300_rtc_write(RTC_REG_MON2, (t->tm_mon + 1) % 10);
if (t->tm_year >= 100)
t->tm_year -= 100;
hp300_rtc_write(RTC_REG_YEAR1, t->tm_year / 10);
hp300_rtc_write(RTC_REG_YEAR2, t->tm_year % 10);
}
return 0;
}
static unsigned int hp300_get_ss(void)
{
return hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
}
static void __init hp300_init_IRQ(void)
{
}
void __init config_hp300(void)
{
mach_sched_init = hp300_sched_init;
mach_init_IRQ = hp300_init_IRQ;
mach_get_model = hp300_get_model;
mach_gettimeoffset = hp300_gettimeoffset;
mach_hwclk = hp300_hwclk;
mach_get_ss = hp300_get_ss;
mach_reset = hp300_reset;
#ifdef CONFIG_HEARTBEAT
mach_heartbeat = hp300_pulse;
#endif
mach_max_dma_address = 0xffffffff;
if (hp300_model >= HP_330 && hp300_model <= HP_433S && hp300_model != HP_350) {
printk(KERN_INFO "Detected HP9000 model %s\n", hp300_models[hp300_model-HP_320]);
strcat(hp300_model_name, hp300_models[hp300_model-HP_320]);
}
else {
panic("Unknown HP9000 Model");
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
hp300_setup_serial_console();
#endif
}
| gpl-2.0 |
nopy/android_kernel_huawei_u8815 | drivers/infiniband/ulp/ipoib/ipoib_ethtool.c | 8110 | 2985 | /*
* Copyright (c) 2007 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/kernel.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include "ipoib.h"
static void ipoib_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
strncpy(drvinfo->driver, "ipoib", sizeof(drvinfo->driver) - 1);
}
static int ipoib_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
coal->rx_coalesce_usecs = priv->ethtool.coalesce_usecs;
coal->rx_max_coalesced_frames = priv->ethtool.max_coalesced_frames;
return 0;
}
static int ipoib_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
int ret;
/*
* These values are saved in the private data and returned
* when ipoib_get_coalesce() is called
*/
if (coal->rx_coalesce_usecs > 0xffff ||
coal->rx_max_coalesced_frames > 0xffff)
return -EINVAL;
ret = ib_modify_cq(priv->recv_cq, coal->rx_max_coalesced_frames,
coal->rx_coalesce_usecs);
if (ret && ret != -ENOSYS) {
ipoib_warn(priv, "failed modifying CQ (%d)\n", ret);
return ret;
}
priv->ethtool.coalesce_usecs = coal->rx_coalesce_usecs;
priv->ethtool.max_coalesced_frames = coal->rx_max_coalesced_frames;
return 0;
}
static const struct ethtool_ops ipoib_ethtool_ops = {
.get_drvinfo = ipoib_get_drvinfo,
.get_coalesce = ipoib_get_coalesce,
.set_coalesce = ipoib_set_coalesce,
};
void ipoib_set_ethtool_ops(struct net_device *dev)
{
SET_ETHTOOL_OPS(dev, &ipoib_ethtool_ops);
}
| gpl-2.0 |
alfsamsung/LG_X3_P880_v20a | arch/x86/xen/multicalls.c | 8366 | 4917 | /*
* Xen hypercall batching.
*
* Xen allows multiple hypercalls to be issued at once, using the
* multicall interface. This allows the cost of trapping into the
* hypervisor to be amortized over several calls.
*
* This file implements a simple interface for multicalls. There's a
* per-cpu buffer of outstanding multicalls. When you want to queue a
* multicall for issuing, you can allocate a multicall slot for the
* call and its arguments, along with storage for space which is
* pointed to by the arguments (for passing pointers to structures,
* etc). When the multicall is actually issued, all the space for the
* commands and allocated memory is freed for reuse.
*
* Multicalls are flushed whenever any of the buffers get full, or
* when explicitly requested. There's no way to get per-multicall
* return results back. It will BUG if any of the multicalls fail.
*
* Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
*/
#include <linux/percpu.h>
#include <linux/hardirq.h>
#include <linux/debugfs.h>
#include <asm/xen/hypercall.h>
#include "multicalls.h"
#include "debugfs.h"
#define MC_BATCH 32
#define MC_DEBUG 0
#define MC_ARGS (MC_BATCH * 16)
struct mc_buffer {
unsigned mcidx, argidx, cbidx;
struct multicall_entry entries[MC_BATCH];
#if MC_DEBUG
struct multicall_entry debug[MC_BATCH];
void *caller[MC_BATCH];
#endif
unsigned char args[MC_ARGS];
struct callback {
void (*fn)(void *);
void *data;
} callbacks[MC_BATCH];
};
static DEFINE_PER_CPU(struct mc_buffer, mc_buffer);
DEFINE_PER_CPU(unsigned long, xen_mc_irq_flags);
void xen_mc_flush(void)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct multicall_entry *mc;
int ret = 0;
unsigned long flags;
int i;
BUG_ON(preemptible());
/* Disable interrupts in case someone comes in and queues
something in the middle */
local_irq_save(flags);
trace_xen_mc_flush(b->mcidx, b->argidx, b->cbidx);
switch (b->mcidx) {
case 0:
/* no-op */
BUG_ON(b->argidx != 0);
break;
case 1:
/* Singleton multicall - bypass multicall machinery
and just do the call directly. */
mc = &b->entries[0];
mc->result = privcmd_call(mc->op,
mc->args[0], mc->args[1], mc->args[2],
mc->args[3], mc->args[4]);
ret = mc->result < 0;
break;
default:
#if MC_DEBUG
memcpy(b->debug, b->entries,
b->mcidx * sizeof(struct multicall_entry));
#endif
if (HYPERVISOR_multicall(b->entries, b->mcidx) != 0)
BUG();
for (i = 0; i < b->mcidx; i++)
if (b->entries[i].result < 0)
ret++;
#if MC_DEBUG
if (ret) {
printk(KERN_ERR "%d multicall(s) failed: cpu %d\n",
ret, smp_processor_id());
dump_stack();
for (i = 0; i < b->mcidx; i++) {
printk(KERN_DEBUG " call %2d/%d: op=%lu arg=[%lx] result=%ld\t%pF\n",
i+1, b->mcidx,
b->debug[i].op,
b->debug[i].args[0],
b->entries[i].result,
b->caller[i]);
}
}
#endif
}
b->mcidx = 0;
b->argidx = 0;
for (i = 0; i < b->cbidx; i++) {
struct callback *cb = &b->callbacks[i];
(*cb->fn)(cb->data);
}
b->cbidx = 0;
local_irq_restore(flags);
WARN_ON(ret);
}
struct multicall_space __xen_mc_entry(size_t args)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct multicall_space ret;
unsigned argidx = roundup(b->argidx, sizeof(u64));
trace_xen_mc_entry_alloc(args);
BUG_ON(preemptible());
BUG_ON(b->argidx >= MC_ARGS);
if (unlikely(b->mcidx == MC_BATCH ||
(argidx + args) >= MC_ARGS)) {
trace_xen_mc_flush_reason((b->mcidx == MC_BATCH) ?
XEN_MC_FL_BATCH : XEN_MC_FL_ARGS);
xen_mc_flush();
argidx = roundup(b->argidx, sizeof(u64));
}
ret.mc = &b->entries[b->mcidx];
#if MC_DEBUG
b->caller[b->mcidx] = __builtin_return_address(0);
#endif
b->mcidx++;
ret.args = &b->args[argidx];
b->argidx = argidx + args;
BUG_ON(b->argidx >= MC_ARGS);
return ret;
}
struct multicall_space xen_mc_extend_args(unsigned long op, size_t size)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct multicall_space ret = { NULL, NULL };
BUG_ON(preemptible());
BUG_ON(b->argidx >= MC_ARGS);
if (unlikely(b->mcidx == 0 ||
b->entries[b->mcidx - 1].op != op)) {
trace_xen_mc_extend_args(op, size, XEN_MC_XE_BAD_OP);
goto out;
}
if (unlikely((b->argidx + size) >= MC_ARGS)) {
trace_xen_mc_extend_args(op, size, XEN_MC_XE_NO_SPACE);
goto out;
}
ret.mc = &b->entries[b->mcidx - 1];
ret.args = &b->args[b->argidx];
b->argidx += size;
BUG_ON(b->argidx >= MC_ARGS);
trace_xen_mc_extend_args(op, size, XEN_MC_XE_OK);
out:
return ret;
}
void xen_mc_callback(void (*fn)(void *), void *data)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct callback *cb;
if (b->cbidx == MC_BATCH) {
trace_xen_mc_flush_reason(XEN_MC_FL_CALLBACK);
xen_mc_flush();
}
trace_xen_mc_callback(fn, data);
cb = &b->callbacks[b->cbidx++];
cb->fn = fn;
cb->data = data;
}
| gpl-2.0 |
jfdsmabalot/kernel_samsung_klte | drivers/net/wireless/b43legacy/leds.c | 9902 | 7074 | /*
Broadcom B43 wireless driver
LED control
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>,
Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it>
Copyright (c) 2005-2007 Michael Buesch <m@bues.ch>
Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org>
Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "b43legacy.h"
#include "leds.h"
#include "rfkill.h"
static void b43legacy_led_turn_on(struct b43legacy_wldev *dev, u8 led_index,
bool activelow)
{
struct b43legacy_wl *wl = dev->wl;
unsigned long flags;
u16 ctl;
spin_lock_irqsave(&wl->leds_lock, flags);
ctl = b43legacy_read16(dev, B43legacy_MMIO_GPIO_CONTROL);
if (activelow)
ctl &= ~(1 << led_index);
else
ctl |= (1 << led_index);
b43legacy_write16(dev, B43legacy_MMIO_GPIO_CONTROL, ctl);
spin_unlock_irqrestore(&wl->leds_lock, flags);
}
static void b43legacy_led_turn_off(struct b43legacy_wldev *dev, u8 led_index,
bool activelow)
{
struct b43legacy_wl *wl = dev->wl;
unsigned long flags;
u16 ctl;
spin_lock_irqsave(&wl->leds_lock, flags);
ctl = b43legacy_read16(dev, B43legacy_MMIO_GPIO_CONTROL);
if (activelow)
ctl |= (1 << led_index);
else
ctl &= ~(1 << led_index);
b43legacy_write16(dev, B43legacy_MMIO_GPIO_CONTROL, ctl);
spin_unlock_irqrestore(&wl->leds_lock, flags);
}
/* Callback from the LED subsystem. */
static void b43legacy_led_brightness_set(struct led_classdev *led_dev,
enum led_brightness brightness)
{
struct b43legacy_led *led = container_of(led_dev, struct b43legacy_led,
led_dev);
struct b43legacy_wldev *dev = led->dev;
bool radio_enabled;
/* Checking the radio-enabled status here is slightly racy,
* but we want to avoid the locking overhead and we don't care
* whether the LED has the wrong state for a second. */
radio_enabled = (dev->phy.radio_on && dev->radio_hw_enable);
if (brightness == LED_OFF || !radio_enabled)
b43legacy_led_turn_off(dev, led->index, led->activelow);
else
b43legacy_led_turn_on(dev, led->index, led->activelow);
}
static int b43legacy_register_led(struct b43legacy_wldev *dev,
struct b43legacy_led *led,
const char *name,
const char *default_trigger,
u8 led_index, bool activelow)
{
int err;
b43legacy_led_turn_off(dev, led_index, activelow);
if (led->dev)
return -EEXIST;
if (!default_trigger)
return -EINVAL;
led->dev = dev;
led->index = led_index;
led->activelow = activelow;
strncpy(led->name, name, sizeof(led->name));
led->led_dev.name = led->name;
led->led_dev.default_trigger = default_trigger;
led->led_dev.brightness_set = b43legacy_led_brightness_set;
err = led_classdev_register(dev->dev->dev, &led->led_dev);
if (err) {
b43legacywarn(dev->wl, "LEDs: Failed to register %s\n", name);
led->dev = NULL;
return err;
}
return 0;
}
static void b43legacy_unregister_led(struct b43legacy_led *led)
{
if (!led->dev)
return;
led_classdev_unregister(&led->led_dev);
b43legacy_led_turn_off(led->dev, led->index, led->activelow);
led->dev = NULL;
}
static void b43legacy_map_led(struct b43legacy_wldev *dev,
u8 led_index,
enum b43legacy_led_behaviour behaviour,
bool activelow)
{
struct ieee80211_hw *hw = dev->wl->hw;
char name[B43legacy_LED_MAX_NAME_LEN + 1];
/* Map the b43 specific LED behaviour value to the
* generic LED triggers. */
switch (behaviour) {
case B43legacy_LED_INACTIVE:
break;
case B43legacy_LED_OFF:
b43legacy_led_turn_off(dev, led_index, activelow);
break;
case B43legacy_LED_ON:
b43legacy_led_turn_on(dev, led_index, activelow);
break;
case B43legacy_LED_ACTIVITY:
case B43legacy_LED_TRANSFER:
case B43legacy_LED_APTRANSFER:
snprintf(name, sizeof(name),
"b43legacy-%s::tx", wiphy_name(hw->wiphy));
b43legacy_register_led(dev, &dev->led_tx, name,
ieee80211_get_tx_led_name(hw),
led_index, activelow);
snprintf(name, sizeof(name),
"b43legacy-%s::rx", wiphy_name(hw->wiphy));
b43legacy_register_led(dev, &dev->led_rx, name,
ieee80211_get_rx_led_name(hw),
led_index, activelow);
break;
case B43legacy_LED_RADIO_ALL:
case B43legacy_LED_RADIO_A:
case B43legacy_LED_RADIO_B:
case B43legacy_LED_MODE_BG:
snprintf(name, sizeof(name),
"b43legacy-%s::radio", wiphy_name(hw->wiphy));
b43legacy_register_led(dev, &dev->led_radio, name,
ieee80211_get_radio_led_name(hw),
led_index, activelow);
/* Sync the RF-kill LED state with radio and switch states. */
if (dev->phy.radio_on && b43legacy_is_hw_radio_enabled(dev))
b43legacy_led_turn_on(dev, led_index, activelow);
break;
case B43legacy_LED_WEIRD:
case B43legacy_LED_ASSOC:
snprintf(name, sizeof(name),
"b43legacy-%s::assoc", wiphy_name(hw->wiphy));
b43legacy_register_led(dev, &dev->led_assoc, name,
ieee80211_get_assoc_led_name(hw),
led_index, activelow);
break;
default:
b43legacywarn(dev->wl, "LEDs: Unknown behaviour 0x%02X\n",
behaviour);
break;
}
}
void b43legacy_leds_init(struct b43legacy_wldev *dev)
{
struct ssb_bus *bus = dev->dev->bus;
u8 sprom[4];
int i;
enum b43legacy_led_behaviour behaviour;
bool activelow;
sprom[0] = bus->sprom.gpio0;
sprom[1] = bus->sprom.gpio1;
sprom[2] = bus->sprom.gpio2;
sprom[3] = bus->sprom.gpio3;
for (i = 0; i < 4; i++) {
if (sprom[i] == 0xFF) {
/* There is no LED information in the SPROM
* for this LED. Hardcode it here. */
activelow = false;
switch (i) {
case 0:
behaviour = B43legacy_LED_ACTIVITY;
activelow = true;
if (bus->boardinfo.vendor == PCI_VENDOR_ID_COMPAQ)
behaviour = B43legacy_LED_RADIO_ALL;
break;
case 1:
behaviour = B43legacy_LED_RADIO_B;
if (bus->boardinfo.vendor == PCI_VENDOR_ID_ASUSTEK)
behaviour = B43legacy_LED_ASSOC;
break;
case 2:
behaviour = B43legacy_LED_RADIO_A;
break;
case 3:
behaviour = B43legacy_LED_OFF;
break;
default:
B43legacy_WARN_ON(1);
return;
}
} else {
behaviour = sprom[i] & B43legacy_LED_BEHAVIOUR;
activelow = !!(sprom[i] & B43legacy_LED_ACTIVELOW);
}
b43legacy_map_led(dev, i, behaviour, activelow);
}
}
void b43legacy_leds_exit(struct b43legacy_wldev *dev)
{
b43legacy_unregister_led(&dev->led_tx);
b43legacy_unregister_led(&dev->led_rx);
b43legacy_unregister_led(&dev->led_assoc);
b43legacy_unregister_led(&dev->led_radio);
}
| gpl-2.0 |
junhe/linux | kernel/time/tick-sched.c | 175 | 29718 | /*
* linux/kernel/time/tick-sched.c
*
* Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
* Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
* Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
*
* No idle tick implementation for low and high resolution timers
*
* Started by: Thomas Gleixner and Ingo Molnar
*
* Distribute under GPLv2.
*/
#include <linux/cpu.h>
#include <linux/err.h>
#include <linux/hrtimer.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/percpu.h>
#include <linux/profile.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/irq_work.h>
#include <linux/posix-timers.h>
#include <linux/perf_event.h>
#include <linux/context_tracking.h>
#include <asm/irq_regs.h>
#include "tick-internal.h"
#include <trace/events/timer.h>
/*
* Per cpu nohz control structure
*/
static DEFINE_PER_CPU(struct tick_sched, tick_cpu_sched);
/*
* The time, when the last jiffy update happened. Protected by jiffies_lock.
*/
static ktime_t last_jiffies_update;
struct tick_sched *tick_get_tick_sched(int cpu)
{
return &per_cpu(tick_cpu_sched, cpu);
}
/*
* Must be called with interrupts disabled !
*/
static void tick_do_update_jiffies64(ktime_t now)
{
unsigned long ticks = 0;
ktime_t delta;
/*
* Do a quick check without holding jiffies_lock:
*/
delta = ktime_sub(now, last_jiffies_update);
if (delta.tv64 < tick_period.tv64)
return;
/* Reevalute with jiffies_lock held */
write_seqlock(&jiffies_lock);
delta = ktime_sub(now, last_jiffies_update);
if (delta.tv64 >= tick_period.tv64) {
delta = ktime_sub(delta, tick_period);
last_jiffies_update = ktime_add(last_jiffies_update,
tick_period);
/* Slow path for long timeouts */
if (unlikely(delta.tv64 >= tick_period.tv64)) {
s64 incr = ktime_to_ns(tick_period);
ticks = ktime_divns(delta, incr);
last_jiffies_update = ktime_add_ns(last_jiffies_update,
incr * ticks);
}
do_timer(++ticks);
/* Keep the tick_next_period variable up to date */
tick_next_period = ktime_add(last_jiffies_update, tick_period);
} else {
write_sequnlock(&jiffies_lock);
return;
}
write_sequnlock(&jiffies_lock);
update_wall_time();
}
/*
* Initialize and return retrieve the jiffies update.
*/
static ktime_t tick_init_jiffy_update(void)
{
ktime_t period;
write_seqlock(&jiffies_lock);
/* Did we start the jiffies update yet ? */
if (last_jiffies_update.tv64 == 0)
last_jiffies_update = tick_next_period;
period = last_jiffies_update;
write_sequnlock(&jiffies_lock);
return period;
}
static void tick_sched_do_timer(ktime_t now)
{
int cpu = smp_processor_id();
#ifdef CONFIG_NO_HZ_COMMON
/*
* Check if the do_timer duty was dropped. We don't care about
* concurrency: This happens only when the cpu in charge went
* into a long sleep. If two cpus happen to assign themself to
* this duty, then the jiffies update is still serialized by
* jiffies_lock.
*/
if (unlikely(tick_do_timer_cpu == TICK_DO_TIMER_NONE)
&& !tick_nohz_full_cpu(cpu))
tick_do_timer_cpu = cpu;
#endif
/* Check, if the jiffies need an update */
if (tick_do_timer_cpu == cpu)
tick_do_update_jiffies64(now);
}
static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
{
#ifdef CONFIG_NO_HZ_COMMON
/*
* When we are idle and the tick is stopped, we have to touch
* the watchdog as we might not schedule for a really long
* time. This happens on complete idle SMP systems while
* waiting on the login prompt. We also increment the "start of
* idle" jiffy stamp so the idle accounting adjustment we do
* when we go busy again does not account too much ticks.
*/
if (ts->tick_stopped) {
touch_softlockup_watchdog();
if (is_idle_task(current))
ts->idle_jiffies++;
}
#endif
update_process_times(user_mode(regs));
profile_tick(CPU_PROFILING);
}
#ifdef CONFIG_NO_HZ_FULL
cpumask_var_t tick_nohz_full_mask;
cpumask_var_t housekeeping_mask;
bool tick_nohz_full_running;
static bool can_stop_full_tick(void)
{
WARN_ON_ONCE(!irqs_disabled());
if (!sched_can_stop_tick()) {
trace_tick_stop(0, "more than 1 task in runqueue\n");
return false;
}
if (!posix_cpu_timers_can_stop_tick(current)) {
trace_tick_stop(0, "posix timers running\n");
return false;
}
if (!perf_event_can_stop_tick()) {
trace_tick_stop(0, "perf events running\n");
return false;
}
/* sched_clock_tick() needs us? */
#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
/*
* TODO: kick full dynticks CPUs when
* sched_clock_stable is set.
*/
if (!sched_clock_stable()) {
trace_tick_stop(0, "unstable sched clock\n");
/*
* Don't allow the user to think they can get
* full NO_HZ with this machine.
*/
WARN_ONCE(tick_nohz_full_running,
"NO_HZ FULL will not work with unstable sched clock");
return false;
}
#endif
return true;
}
static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now);
/*
* Re-evaluate the need for the tick on the current CPU
* and restart it if necessary.
*/
void __tick_nohz_full_check(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
if (tick_nohz_full_cpu(smp_processor_id())) {
if (ts->tick_stopped && !is_idle_task(current)) {
if (!can_stop_full_tick())
tick_nohz_restart_sched_tick(ts, ktime_get());
}
}
}
static void nohz_full_kick_work_func(struct irq_work *work)
{
__tick_nohz_full_check();
}
static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) = {
.func = nohz_full_kick_work_func,
};
/*
* Kick this CPU if it's full dynticks in order to force it to
* re-evaluate its dependency on the tick and restart it if necessary.
* This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
* is NMI safe.
*/
void tick_nohz_full_kick(void)
{
if (!tick_nohz_full_cpu(smp_processor_id()))
return;
irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
}
/*
* Kick the CPU if it's full dynticks in order to force it to
* re-evaluate its dependency on the tick and restart it if necessary.
*/
void tick_nohz_full_kick_cpu(int cpu)
{
if (!tick_nohz_full_cpu(cpu))
return;
irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
}
static void nohz_full_kick_ipi(void *info)
{
__tick_nohz_full_check();
}
/*
* Kick all full dynticks CPUs in order to force these to re-evaluate
* their dependency on the tick and restart it if necessary.
*/
void tick_nohz_full_kick_all(void)
{
if (!tick_nohz_full_running)
return;
preempt_disable();
smp_call_function_many(tick_nohz_full_mask,
nohz_full_kick_ipi, NULL, false);
tick_nohz_full_kick();
preempt_enable();
}
/*
* Re-evaluate the need for the tick as we switch the current task.
* It might need the tick due to per task/process properties:
* perf events, posix cpu timers, ...
*/
void __tick_nohz_task_switch(struct task_struct *tsk)
{
unsigned long flags;
local_irq_save(flags);
if (!tick_nohz_full_cpu(smp_processor_id()))
goto out;
if (tick_nohz_tick_stopped() && !can_stop_full_tick())
tick_nohz_full_kick();
out:
local_irq_restore(flags);
}
/* Parse the boot-time nohz CPU list from the kernel parameters. */
static int __init tick_nohz_full_setup(char *str)
{
alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
if (cpulist_parse(str, tick_nohz_full_mask) < 0) {
pr_warning("NOHZ: Incorrect nohz_full cpumask\n");
free_bootmem_cpumask_var(tick_nohz_full_mask);
return 1;
}
tick_nohz_full_running = true;
return 1;
}
__setup("nohz_full=", tick_nohz_full_setup);
static int tick_nohz_cpu_down_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DOWN_PREPARE:
/*
* If we handle the timekeeping duty for full dynticks CPUs,
* we can't safely shutdown that CPU.
*/
if (tick_nohz_full_running && tick_do_timer_cpu == cpu)
return NOTIFY_BAD;
break;
}
return NOTIFY_OK;
}
static int tick_nohz_init_all(void)
{
int err = -1;
#ifdef CONFIG_NO_HZ_FULL_ALL
if (!alloc_cpumask_var(&tick_nohz_full_mask, GFP_KERNEL)) {
WARN(1, "NO_HZ: Can't allocate full dynticks cpumask\n");
return err;
}
err = 0;
cpumask_setall(tick_nohz_full_mask);
tick_nohz_full_running = true;
#endif
return err;
}
void __init tick_nohz_init(void)
{
int cpu;
if (!tick_nohz_full_running) {
if (tick_nohz_init_all() < 0)
return;
}
if (!alloc_cpumask_var(&housekeeping_mask, GFP_KERNEL)) {
WARN(1, "NO_HZ: Can't allocate not-full dynticks cpumask\n");
cpumask_clear(tick_nohz_full_mask);
tick_nohz_full_running = false;
return;
}
/*
* Full dynticks uses irq work to drive the tick rescheduling on safe
* locking contexts. But then we need irq work to raise its own
* interrupts to avoid circular dependency on the tick
*/
if (!arch_irq_work_has_interrupt()) {
pr_warning("NO_HZ: Can't run full dynticks because arch doesn't "
"support irq work self-IPIs\n");
cpumask_clear(tick_nohz_full_mask);
cpumask_copy(housekeeping_mask, cpu_possible_mask);
tick_nohz_full_running = false;
return;
}
cpu = smp_processor_id();
if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
pr_warning("NO_HZ: Clearing %d from nohz_full range for timekeeping\n", cpu);
cpumask_clear_cpu(cpu, tick_nohz_full_mask);
}
cpumask_andnot(housekeeping_mask,
cpu_possible_mask, tick_nohz_full_mask);
for_each_cpu(cpu, tick_nohz_full_mask)
context_tracking_cpu_set(cpu);
cpu_notifier(tick_nohz_cpu_down_callback, 0);
pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
cpumask_pr_args(tick_nohz_full_mask));
}
#endif
/*
* NOHZ - aka dynamic tick functionality
*/
#ifdef CONFIG_NO_HZ_COMMON
/*
* NO HZ enabled ?
*/
static int tick_nohz_enabled __read_mostly = 1;
unsigned long tick_nohz_active __read_mostly;
/*
* Enable / Disable tickless mode
*/
static int __init setup_tick_nohz(char *str)
{
if (!strcmp(str, "off"))
tick_nohz_enabled = 0;
else if (!strcmp(str, "on"))
tick_nohz_enabled = 1;
else
return 0;
return 1;
}
__setup("nohz=", setup_tick_nohz);
int tick_nohz_tick_stopped(void)
{
return __this_cpu_read(tick_cpu_sched.tick_stopped);
}
/**
* tick_nohz_update_jiffies - update jiffies when idle was interrupted
*
* Called from interrupt entry when the CPU was idle
*
* In case the sched_tick was stopped on this CPU, we have to check if jiffies
* must be updated. Otherwise an interrupt handler could use a stale jiffy
* value. We do this unconditionally on any cpu, as we don't know whether the
* cpu, which has the update task assigned is in a long sleep.
*/
static void tick_nohz_update_jiffies(ktime_t now)
{
unsigned long flags;
__this_cpu_write(tick_cpu_sched.idle_waketime, now);
local_irq_save(flags);
tick_do_update_jiffies64(now);
local_irq_restore(flags);
touch_softlockup_watchdog();
}
/*
* Updates the per cpu time idle statistics counters
*/
static void
update_ts_time_stats(int cpu, struct tick_sched *ts, ktime_t now, u64 *last_update_time)
{
ktime_t delta;
if (ts->idle_active) {
delta = ktime_sub(now, ts->idle_entrytime);
if (nr_iowait_cpu(cpu) > 0)
ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
else
ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
ts->idle_entrytime = now;
}
if (last_update_time)
*last_update_time = ktime_to_us(now);
}
static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
{
update_ts_time_stats(smp_processor_id(), ts, now, NULL);
ts->idle_active = 0;
sched_clock_idle_wakeup_event(0);
}
static ktime_t tick_nohz_start_idle(struct tick_sched *ts)
{
ktime_t now = ktime_get();
ts->idle_entrytime = now;
ts->idle_active = 1;
sched_clock_idle_sleep_event();
return now;
}
/**
* get_cpu_idle_time_us - get the total idle time of a cpu
* @cpu: CPU number to query
* @last_update_time: variable to store update time in. Do not update
* counters if NULL.
*
* Return the cummulative idle time (since boot) for a given
* CPU, in microseconds.
*
* This time is measured via accounting rather than sampling,
* and is as accurate as ktime_get() is.
*
* This function returns -1 if NOHZ is not enabled.
*/
u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
{
struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
ktime_t now, idle;
if (!tick_nohz_active)
return -1;
now = ktime_get();
if (last_update_time) {
update_ts_time_stats(cpu, ts, now, last_update_time);
idle = ts->idle_sleeptime;
} else {
if (ts->idle_active && !nr_iowait_cpu(cpu)) {
ktime_t delta = ktime_sub(now, ts->idle_entrytime);
idle = ktime_add(ts->idle_sleeptime, delta);
} else {
idle = ts->idle_sleeptime;
}
}
return ktime_to_us(idle);
}
EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
/**
* get_cpu_iowait_time_us - get the total iowait time of a cpu
* @cpu: CPU number to query
* @last_update_time: variable to store update time in. Do not update
* counters if NULL.
*
* Return the cummulative iowait time (since boot) for a given
* CPU, in microseconds.
*
* This time is measured via accounting rather than sampling,
* and is as accurate as ktime_get() is.
*
* This function returns -1 if NOHZ is not enabled.
*/
u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
{
struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
ktime_t now, iowait;
if (!tick_nohz_active)
return -1;
now = ktime_get();
if (last_update_time) {
update_ts_time_stats(cpu, ts, now, last_update_time);
iowait = ts->iowait_sleeptime;
} else {
if (ts->idle_active && nr_iowait_cpu(cpu) > 0) {
ktime_t delta = ktime_sub(now, ts->idle_entrytime);
iowait = ktime_add(ts->iowait_sleeptime, delta);
} else {
iowait = ts->iowait_sleeptime;
}
}
return ktime_to_us(iowait);
}
EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
{
hrtimer_cancel(&ts->sched_timer);
hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
/* Forward the time to expire in the future */
hrtimer_forward(&ts->sched_timer, now, tick_period);
if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED);
else
tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
}
static ktime_t tick_nohz_stop_sched_tick(struct tick_sched *ts,
ktime_t now, int cpu)
{
struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
u64 basemono, next_tick, next_tmr, next_rcu, delta, expires;
unsigned long seq, basejiff;
ktime_t tick;
/* Read jiffies and the time when jiffies were updated last */
do {
seq = read_seqbegin(&jiffies_lock);
basemono = last_jiffies_update.tv64;
basejiff = jiffies;
} while (read_seqretry(&jiffies_lock, seq));
ts->last_jiffies = basejiff;
if (rcu_needs_cpu(basemono, &next_rcu) ||
arch_needs_cpu() || irq_work_needs_cpu()) {
next_tick = basemono + TICK_NSEC;
} else {
/*
* Get the next pending timer. If high resolution
* timers are enabled this only takes the timer wheel
* timers into account. If high resolution timers are
* disabled this also looks at the next expiring
* hrtimer.
*/
next_tmr = get_next_timer_interrupt(basejiff, basemono);
ts->next_timer = next_tmr;
/* Take the next rcu event into account */
next_tick = next_rcu < next_tmr ? next_rcu : next_tmr;
}
/*
* If the tick is due in the next period, keep it ticking or
* restart it proper.
*/
delta = next_tick - basemono;
if (delta <= (u64)TICK_NSEC) {
tick.tv64 = 0;
if (!ts->tick_stopped)
goto out;
if (delta == 0) {
/* Tick is stopped, but required now. Enforce it */
tick_nohz_restart(ts, now);
goto out;
}
}
/*
* If this cpu is the one which updates jiffies, then give up
* the assignment and let it be taken by the cpu which runs
* the tick timer next, which might be this cpu as well. If we
* don't drop this here the jiffies might be stale and
* do_timer() never invoked. Keep track of the fact that it
* was the one which had the do_timer() duty last. If this cpu
* is the one which had the do_timer() duty last, we limit the
* sleep time to the timekeeping max_deferement value.
* Otherwise we can sleep as long as we want.
*/
delta = timekeeping_max_deferment();
if (cpu == tick_do_timer_cpu) {
tick_do_timer_cpu = TICK_DO_TIMER_NONE;
ts->do_timer_last = 1;
} else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
delta = KTIME_MAX;
ts->do_timer_last = 0;
} else if (!ts->do_timer_last) {
delta = KTIME_MAX;
}
#ifdef CONFIG_NO_HZ_FULL
/* Limit the tick delta to the maximum scheduler deferment */
if (!ts->inidle)
delta = min(delta, scheduler_tick_max_deferment());
#endif
/* Calculate the next expiry time */
if (delta < (KTIME_MAX - basemono))
expires = basemono + delta;
else
expires = KTIME_MAX;
expires = min_t(u64, expires, next_tick);
tick.tv64 = expires;
/* Skip reprogram of event if its not changed */
if (ts->tick_stopped && (expires == dev->next_event.tv64))
goto out;
/*
* nohz_stop_sched_tick can be called several times before
* the nohz_restart_sched_tick is called. This happens when
* interrupts arrive which do not cause a reschedule. In the
* first call we save the current tick time, so we can restart
* the scheduler tick in nohz_restart_sched_tick.
*/
if (!ts->tick_stopped) {
nohz_balance_enter_idle(cpu);
calc_load_enter_idle();
ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
ts->tick_stopped = 1;
trace_tick_stop(1, " ");
}
/*
* If the expiration time == KTIME_MAX, then we simply stop
* the tick timer.
*/
if (unlikely(expires == KTIME_MAX)) {
if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
hrtimer_cancel(&ts->sched_timer);
goto out;
}
if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
hrtimer_start(&ts->sched_timer, tick, HRTIMER_MODE_ABS_PINNED);
else
tick_program_event(tick, 1);
out:
/* Update the estimated sleep length */
ts->sleep_length = ktime_sub(dev->next_event, now);
return tick;
}
static void tick_nohz_full_stop_tick(struct tick_sched *ts)
{
#ifdef CONFIG_NO_HZ_FULL
int cpu = smp_processor_id();
if (!tick_nohz_full_cpu(cpu) || is_idle_task(current))
return;
if (!ts->tick_stopped && ts->nohz_mode == NOHZ_MODE_INACTIVE)
return;
if (!can_stop_full_tick())
return;
tick_nohz_stop_sched_tick(ts, ktime_get(), cpu);
#endif
}
static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
{
/*
* If this cpu is offline and it is the one which updates
* jiffies, then give up the assignment and let it be taken by
* the cpu which runs the tick timer next. If we don't drop
* this here the jiffies might be stale and do_timer() never
* invoked.
*/
if (unlikely(!cpu_online(cpu))) {
if (cpu == tick_do_timer_cpu)
tick_do_timer_cpu = TICK_DO_TIMER_NONE;
return false;
}
if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE)) {
ts->sleep_length = (ktime_t) { .tv64 = NSEC_PER_SEC/HZ };
return false;
}
if (need_resched())
return false;
if (unlikely(local_softirq_pending() && cpu_online(cpu))) {
static int ratelimit;
if (ratelimit < 10 &&
(local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
pr_warn("NOHZ: local_softirq_pending %02x\n",
(unsigned int) local_softirq_pending());
ratelimit++;
}
return false;
}
if (tick_nohz_full_enabled()) {
/*
* Keep the tick alive to guarantee timekeeping progression
* if there are full dynticks CPUs around
*/
if (tick_do_timer_cpu == cpu)
return false;
/*
* Boot safety: make sure the timekeeping duty has been
* assigned before entering dyntick-idle mode,
*/
if (tick_do_timer_cpu == TICK_DO_TIMER_NONE)
return false;
}
return true;
}
static void __tick_nohz_idle_enter(struct tick_sched *ts)
{
ktime_t now, expires;
int cpu = smp_processor_id();
now = tick_nohz_start_idle(ts);
if (can_stop_idle_tick(cpu, ts)) {
int was_stopped = ts->tick_stopped;
ts->idle_calls++;
expires = tick_nohz_stop_sched_tick(ts, now, cpu);
if (expires.tv64 > 0LL) {
ts->idle_sleeps++;
ts->idle_expires = expires;
}
if (!was_stopped && ts->tick_stopped)
ts->idle_jiffies = ts->last_jiffies;
}
}
/**
* tick_nohz_idle_enter - stop the idle tick from the idle task
*
* When the next event is more than a tick into the future, stop the idle tick
* Called when we start the idle loop.
*
* The arch is responsible of calling:
*
* - rcu_idle_enter() after its last use of RCU before the CPU is put
* to sleep.
* - rcu_idle_exit() before the first use of RCU after the CPU is woken up.
*/
void tick_nohz_idle_enter(void)
{
struct tick_sched *ts;
WARN_ON_ONCE(irqs_disabled());
/*
* Update the idle state in the scheduler domain hierarchy
* when tick_nohz_stop_sched_tick() is called from the idle loop.
* State will be updated to busy during the first busy tick after
* exiting idle.
*/
set_cpu_sd_state_idle();
local_irq_disable();
ts = this_cpu_ptr(&tick_cpu_sched);
ts->inidle = 1;
__tick_nohz_idle_enter(ts);
local_irq_enable();
}
/**
* tick_nohz_irq_exit - update next tick event from interrupt exit
*
* When an interrupt fires while we are idle and it doesn't cause
* a reschedule, it may still add, modify or delete a timer, enqueue
* an RCU callback, etc...
* So we need to re-calculate and reprogram the next tick event.
*/
void tick_nohz_irq_exit(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
if (ts->inidle)
__tick_nohz_idle_enter(ts);
else
tick_nohz_full_stop_tick(ts);
}
/**
* tick_nohz_get_sleep_length - return the length of the current sleep
*
* Called from power state control code with interrupts disabled
*/
ktime_t tick_nohz_get_sleep_length(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
return ts->sleep_length;
}
static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
{
/* Update jiffies first */
tick_do_update_jiffies64(now);
update_cpu_load_nohz();
calc_load_exit_idle();
touch_softlockup_watchdog();
/*
* Cancel the scheduled timer and restore the tick
*/
ts->tick_stopped = 0;
ts->idle_exittime = now;
tick_nohz_restart(ts, now);
}
static void tick_nohz_account_idle_ticks(struct tick_sched *ts)
{
#ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
unsigned long ticks;
if (vtime_accounting_enabled())
return;
/*
* We stopped the tick in idle. Update process times would miss the
* time we slept as update_process_times does only a 1 tick
* accounting. Enforce that this is accounted to idle !
*/
ticks = jiffies - ts->idle_jiffies;
/*
* We might be one off. Do not randomly account a huge number of ticks!
*/
if (ticks && ticks < LONG_MAX)
account_idle_ticks(ticks);
#endif
}
/**
* tick_nohz_idle_exit - restart the idle tick from the idle task
*
* Restart the idle tick when the CPU is woken up from idle
* This also exit the RCU extended quiescent state. The CPU
* can use RCU again after this function is called.
*/
void tick_nohz_idle_exit(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
ktime_t now;
local_irq_disable();
WARN_ON_ONCE(!ts->inidle);
ts->inidle = 0;
if (ts->idle_active || ts->tick_stopped)
now = ktime_get();
if (ts->idle_active)
tick_nohz_stop_idle(ts, now);
if (ts->tick_stopped) {
tick_nohz_restart_sched_tick(ts, now);
tick_nohz_account_idle_ticks(ts);
}
local_irq_enable();
}
/*
* The nohz low res interrupt handler
*/
static void tick_nohz_handler(struct clock_event_device *dev)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
struct pt_regs *regs = get_irq_regs();
ktime_t now = ktime_get();
dev->next_event.tv64 = KTIME_MAX;
tick_sched_do_timer(now);
tick_sched_handle(ts, regs);
/* No need to reprogram if we are running tickless */
if (unlikely(ts->tick_stopped))
return;
hrtimer_forward(&ts->sched_timer, now, tick_period);
tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
}
static inline void tick_nohz_activate(struct tick_sched *ts, int mode)
{
if (!tick_nohz_enabled)
return;
ts->nohz_mode = mode;
/* One update is enough */
if (!test_and_set_bit(0, &tick_nohz_active))
timers_update_migration(true);
}
/**
* tick_nohz_switch_to_nohz - switch to nohz mode
*/
static void tick_nohz_switch_to_nohz(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
ktime_t next;
if (!tick_nohz_enabled)
return;
if (tick_switch_to_oneshot(tick_nohz_handler))
return;
/*
* Recycle the hrtimer in ts, so we can share the
* hrtimer_forward with the highres code.
*/
hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
/* Get the next period */
next = tick_init_jiffy_update();
hrtimer_forward_now(&ts->sched_timer, tick_period);
hrtimer_set_expires(&ts->sched_timer, next);
tick_program_event(next, 1);
tick_nohz_activate(ts, NOHZ_MODE_LOWRES);
}
/*
* When NOHZ is enabled and the tick is stopped, we need to kick the
* tick timer from irq_enter() so that the jiffies update is kept
* alive during long running softirqs. That's ugly as hell, but
* correctness is key even if we need to fix the offending softirq in
* the first place.
*
* Note, this is different to tick_nohz_restart. We just kick the
* timer and do not touch the other magic bits which need to be done
* when idle is left.
*/
static void tick_nohz_kick_tick(struct tick_sched *ts, ktime_t now)
{
#if 0
/* Switch back to 2.6.27 behaviour */
ktime_t delta;
/*
* Do not touch the tick device, when the next expiry is either
* already reached or less/equal than the tick period.
*/
delta = ktime_sub(hrtimer_get_expires(&ts->sched_timer), now);
if (delta.tv64 <= tick_period.tv64)
return;
tick_nohz_restart(ts, now);
#endif
}
static inline void tick_nohz_irq_enter(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
ktime_t now;
if (!ts->idle_active && !ts->tick_stopped)
return;
now = ktime_get();
if (ts->idle_active)
tick_nohz_stop_idle(ts, now);
if (ts->tick_stopped) {
tick_nohz_update_jiffies(now);
tick_nohz_kick_tick(ts, now);
}
}
#else
static inline void tick_nohz_switch_to_nohz(void) { }
static inline void tick_nohz_irq_enter(void) { }
static inline void tick_nohz_activate(struct tick_sched *ts, int mode) { }
#endif /* CONFIG_NO_HZ_COMMON */
/*
* Called from irq_enter to notify about the possible interruption of idle()
*/
void tick_irq_enter(void)
{
tick_check_oneshot_broadcast_this_cpu();
tick_nohz_irq_enter();
}
/*
* High resolution timer specific code
*/
#ifdef CONFIG_HIGH_RES_TIMERS
/*
* We rearm the timer until we get disabled by the idle code.
* Called with interrupts disabled.
*/
static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
{
struct tick_sched *ts =
container_of(timer, struct tick_sched, sched_timer);
struct pt_regs *regs = get_irq_regs();
ktime_t now = ktime_get();
tick_sched_do_timer(now);
/*
* Do not call, when we are not in irq context and have
* no valid regs pointer
*/
if (regs)
tick_sched_handle(ts, regs);
/* No need to reprogram if we are in idle or full dynticks mode */
if (unlikely(ts->tick_stopped))
return HRTIMER_NORESTART;
hrtimer_forward(timer, now, tick_period);
return HRTIMER_RESTART;
}
static int sched_skew_tick;
static int __init skew_tick(char *str)
{
get_option(&str, &sched_skew_tick);
return 0;
}
early_param("skew_tick", skew_tick);
/**
* tick_setup_sched_timer - setup the tick emulation timer
*/
void tick_setup_sched_timer(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
ktime_t now = ktime_get();
/*
* Emulate tick processing via per-CPU hrtimers:
*/
hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
ts->sched_timer.function = tick_sched_timer;
/* Get the next period (per cpu) */
hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
/* Offset the tick to avert jiffies_lock contention. */
if (sched_skew_tick) {
u64 offset = ktime_to_ns(tick_period) >> 1;
do_div(offset, num_possible_cpus());
offset *= smp_processor_id();
hrtimer_add_expires_ns(&ts->sched_timer, offset);
}
hrtimer_forward(&ts->sched_timer, now, tick_period);
hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED);
tick_nohz_activate(ts, NOHZ_MODE_HIGHRES);
}
#endif /* HIGH_RES_TIMERS */
#if defined CONFIG_NO_HZ_COMMON || defined CONFIG_HIGH_RES_TIMERS
void tick_cancel_sched_timer(int cpu)
{
struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
# ifdef CONFIG_HIGH_RES_TIMERS
if (ts->sched_timer.base)
hrtimer_cancel(&ts->sched_timer);
# endif
memset(ts, 0, sizeof(*ts));
}
#endif
/**
* Async notification about clocksource changes
*/
void tick_clock_notify(void)
{
int cpu;
for_each_possible_cpu(cpu)
set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
}
/*
* Async notification about clock event changes
*/
void tick_oneshot_notify(void)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
set_bit(0, &ts->check_clocks);
}
/**
* Check, if a change happened, which makes oneshot possible.
*
* Called cyclic from the hrtimer softirq (driven by the timer
* softirq) allow_nohz signals, that we can switch into low-res nohz
* mode, because high resolution timers are disabled (either compile
* or runtime). Called with interrupts disabled.
*/
int tick_check_oneshot_change(int allow_nohz)
{
struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
if (!test_and_clear_bit(0, &ts->check_clocks))
return 0;
if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
return 0;
if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
return 0;
if (!allow_nohz)
return 1;
tick_nohz_switch_to_nohz();
return 0;
}
| gpl-2.0 |
anshus012/binutils | newlib/libc/sys/linux/getrlimit64.c | 175 | 1515 | /* Copyright (C) 1991, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <sys/resource.h>
#include <sys/types.h>
/* Put the soft and hard limits for RESOURCE in *RLIMITS.
Returns 0 if successful, -1 if not (and sets errno). */
int
getrlimit64 (enum __rlimit_resource resource, struct rlimit64 *rlimits)
{
struct rlimit rlimits32;
if (__getrlimit (resource, &rlimits32) < 0)
return -1;
if (rlimits32.rlim_cur == RLIM_INFINITY)
rlimits->rlim_cur = RLIM64_INFINITY;
else
rlimits->rlim_cur = rlimits32.rlim_cur;
if (rlimits32.rlim_max == RLIM_INFINITY)
rlimits->rlim_max = RLIM64_INFINITY;
else
rlimits->rlim_max = rlimits32.rlim_max;
return 0;
}
| gpl-2.0 |
beermix/xbmc | lib/libUPnP/Platinum/Source/Core/PltEvent.cpp | 175 | 11911 | /*****************************************************************
|
| Platinum - Control/Event
|
| Copyright (c) 2004-2010, Plutinosoft, LLC.
| All rights reserved.
| http://www.plutinosoft.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.
|
| OEMs, ISVs, VARs and other distributors that combine and
| distribute commercially licensed software with Platinum software
| and do not wish to distribute the source code for the commercially
| licensed software under version 2, or (at your option) any later
| version, of the GNU General Public License (the "GPL") must enter
| into a commercial license agreement with Plutinosoft, LLC.
| licensing@plutinosoft.com
|
| 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 LICENSE.txt. If not, write to
| the Free Software Foundation, Inc.,
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| http://www.gnu.org/licenses/gpl-2.0.html
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "PltTaskManager.h"
#include "PltEvent.h"
#include "PltService.h"
#include "PltUPnP.h"
#include "PltDeviceData.h"
#include "PltUtilities.h"
#include "PltCtrlPointTask.h"
NPT_SET_LOCAL_LOGGER("platinum.core.event")
/*----------------------------------------------------------------------
| PLT_EventNotification::PLT_EventNotification
+---------------------------------------------------------------------*/
PLT_EventNotification*
PLT_EventNotification::Parse(const NPT_HttpRequest& request,
const NPT_HttpRequestContext& context,
NPT_HttpResponse& response)
{
NPT_COMPILER_UNUSED(context);
PLT_LOG_HTTP_MESSAGE(NPT_LOG_LEVEL_FINER, "PLT_CtrlPoint::ProcessHttpNotify:", request);
PLT_EventNotification *notification = new PLT_EventNotification();
notification->m_RequestUrl = request.GetUrl();
const NPT_String* sid = PLT_UPnPMessageHelper::GetSID(request);
const NPT_String* nt = PLT_UPnPMessageHelper::GetNT(request);
const NPT_String* nts = PLT_UPnPMessageHelper::GetNTS(request);
if (!sid || sid->GetLength() == 0) {
NPT_CHECK_LABEL_WARNING(NPT_FAILURE, bad_request);
}
notification->m_SID = *sid;
if (!nt || nt->GetLength() == 0 || !nts || nts->GetLength() == 0) {
response.SetStatus(400, "Bad request");
NPT_CHECK_LABEL_WARNING(NPT_FAILURE, bad_request);
}
if (nt->Compare("upnp:event", true) || nts->Compare("upnp:propchange", true)) {
NPT_CHECK_LABEL_WARNING(NPT_FAILURE, bad_request);
}
// if the sequence number is less than our current one, we got it out of order
// so we disregard it
PLT_UPnPMessageHelper::GetSeq(request, notification->m_EventKey);
// parse body
if (NPT_FAILED(PLT_HttpHelper::GetBody(request, notification->m_XmlBody))) {
NPT_CHECK_LABEL_WARNING(NPT_FAILURE, bad_request);
}
return notification;
bad_request:
NPT_LOG_SEVERE("CtrlPoint received bad event notify request\r\n");
if (response.GetStatusCode() == 200) {
response.SetStatus(412, "Precondition Failed");
}
delete notification;
return NULL;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::PLT_EventSubscriber
+---------------------------------------------------------------------*/
PLT_EventSubscriber::PLT_EventSubscriber(PLT_TaskManagerReference task_manager,
PLT_Service* service,
const char* sid,
NPT_Timeout timeout_secs /* = -1 */) :
m_TaskManager(task_manager),
m_Service(service),
m_EventKey(0),
m_SubscriberTask(NULL),
m_SID(sid)
{
NPT_LOG_FINE_1("Creating new subscriber (%s)", m_SID.GetChars());
SetTimeout(timeout_secs);
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::~PLT_EventSubscriber
+---------------------------------------------------------------------*/
PLT_EventSubscriber::~PLT_EventSubscriber()
{
NPT_LOG_FINE_1("Deleting subscriber (%s)", m_SID.GetChars());
if (m_SubscriberTask) {
m_SubscriberTask->Kill();
m_SubscriberTask = NULL;
}
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::GetService
+---------------------------------------------------------------------*/
PLT_Service*
PLT_EventSubscriber::GetService()
{
return m_Service;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::GetEventKey
+---------------------------------------------------------------------*/
NPT_Ordinal
PLT_EventSubscriber::GetEventKey()
{
return m_EventKey;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::SetEventKey
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::SetEventKey(NPT_Ordinal value)
{
m_EventKey = value;
return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::GetLocalIf
+---------------------------------------------------------------------*/
NPT_SocketAddress
PLT_EventSubscriber::GetLocalIf()
{
return m_LocalIf;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::SetLocalIf
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::SetLocalIf(NPT_SocketAddress value)
{
m_LocalIf = value;
return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::GetExpirationTime
+---------------------------------------------------------------------*/
// a TimeStamp of 0 means no expiration
NPT_TimeStamp
PLT_EventSubscriber::GetExpirationTime()
{
return m_ExpirationTime;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::SetExpirationTime
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::SetTimeout(NPT_Timeout seconds)
{
NPT_LOG_FINE_2("subscriber (%s) expiring in %d seconds",
m_SID.GetChars(),
seconds);
// -1 means infinite but we default to 300 secs
if (seconds == -1) seconds = 300;
NPT_System::GetCurrentTimeStamp(m_ExpirationTime);
m_ExpirationTime += NPT_TimeInterval((double)seconds);
return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::FindCallbackURL
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::FindCallbackURL(const char* callback_url)
{
NPT_String res;
return NPT_ContainerFind(m_CallbackURLs,
NPT_StringFinder(callback_url),
res);
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::AddCallbackURL
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::AddCallbackURL(const char* callback_url)
{
NPT_CHECK_POINTER_FATAL(callback_url);
NPT_LOG_FINE_2("Adding callback \"%s\" to subscriber %s",
callback_url,
m_SID.GetChars());
return m_CallbackURLs.Add(callback_url);
}
/*----------------------------------------------------------------------
| PLT_EventSubscriber::Notify
+---------------------------------------------------------------------*/
NPT_Result
PLT_EventSubscriber::Notify(NPT_List<PLT_StateVariable*>& vars)
{
// verify we have eventable variables
bool foundVars = false;
NPT_Reference<NPT_XmlElementNode> propertyset(new NPT_XmlElementNode("e", "propertyset"));
NPT_CHECK_SEVERE(propertyset->SetNamespaceUri(
"e",
"urn:schemas-upnp-org:event-1-0"));
NPT_List<PLT_StateVariable*>::Iterator var = vars.GetFirstItem();
while (var) {
if ((*var)->IsSendingEvents()) {
NPT_XmlElementNode* property = new NPT_XmlElementNode("e", "property");
NPT_CHECK_FATAL(propertyset->AddChild(property));
NPT_CHECK_FATAL(PLT_XmlHelper::AddChildText(property,
(*var)->GetName(),
(*var)->GetValue()));
foundVars = true;
}
++var;
}
// no eventable state variables found!
if (foundVars == false) {
return NPT_FAILURE;
}
// format the body with the xml
NPT_String xml;
if (NPT_FAILED(PLT_XmlHelper::Serialize(*propertyset, xml))) {
NPT_CHECK_FATAL(NPT_FAILURE);
}
propertyset = NULL;
// parse the callback url
NPT_HttpUrl url(m_CallbackURLs[0]);
if (!url.IsValid()) {
NPT_CHECK_FATAL(NPT_FAILURE);
}
// format request
NPT_HttpRequest* request =
new NPT_HttpRequest(url,
"NOTIFY",
NPT_HTTP_PROTOCOL_1_1);
NPT_HttpEntity* entity;
PLT_HttpHelper::SetBody(*request, xml, &entity);
// add the extra headers
entity->SetContentType("text/xml; charset=\"utf-8\"");
PLT_UPnPMessageHelper::SetNT(*request, "upnp:event");
PLT_UPnPMessageHelper::SetNTS(*request, "upnp:propchange");
PLT_UPnPMessageHelper::SetSID(*request, m_SID);
PLT_UPnPMessageHelper::SetSeq(*request, m_EventKey);
// wrap around sequence to 1
if (++m_EventKey == 0) m_EventKey = 1;
// start the task now if not started already
if (!m_SubscriberTask) {
// TODO: the subscriber task should inform subscriber if
// a notification failed to be received so it can be removed
// from the list of subscribers inside the device host
NPT_Reference<PLT_HttpClientSocketTask> task(new PLT_HttpClientSocketTask(request, true));
// short connection time out in case subscriber is not alive
NPT_HttpClient::Config config;
config.m_ConnectionTimeout = 2000;
task->SetHttpClientConfig(config);
// add initial delay to make sure ctrlpoint receives response to subscription
// before our first NOTIFY. Also make sure task is not auto-destroy
// since we want to destroy it manually when the subscriber goes away.
NPT_TimeInterval delay(0.05f);
NPT_CHECK_FATAL(m_TaskManager->StartTask(task.AsPointer(), NULL /*&delay*/, false));
// Task successfully started, keep around for future notifications
m_SubscriberTask = task.AsPointer();
task.Detach();
} else {
m_SubscriberTask->AddRequest(request);
}
return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
| PLT_EventSubscriberFinderByService::operator()
+---------------------------------------------------------------------*/
bool
PLT_EventSubscriberFinderByService::operator()(PLT_EventSubscriberReference const & eventSub) const
{
return (m_Service == eventSub->GetService());
}
| gpl-2.0 |
KatsuraKKKK/linux | arch/x86/mm/numa.c | 431 | 22235 | /* Common code for 32 and 64-bit NUMA */
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/mmzone.h>
#include <linux/ctype.h>
#include <linux/module.h>
#include <linux/nodemask.h>
#include <linux/sched.h>
#include <linux/topology.h>
#include <asm/e820.h>
#include <asm/proto.h>
#include <asm/dma.h>
#include <asm/acpi.h>
#include <asm/amd_nb.h>
#include "numa_internal.h"
int __initdata numa_off;
nodemask_t numa_nodes_parsed __initdata;
struct pglist_data *node_data[MAX_NUMNODES] __read_mostly;
EXPORT_SYMBOL(node_data);
static struct numa_meminfo numa_meminfo
#ifndef CONFIG_MEMORY_HOTPLUG
__initdata
#endif
;
static int numa_distance_cnt;
static u8 *numa_distance;
static __init int numa_setup(char *opt)
{
if (!opt)
return -EINVAL;
if (!strncmp(opt, "off", 3))
numa_off = 1;
#ifdef CONFIG_NUMA_EMU
if (!strncmp(opt, "fake=", 5))
numa_emu_cmdline(opt + 5);
#endif
#ifdef CONFIG_ACPI_NUMA
if (!strncmp(opt, "noacpi", 6))
acpi_numa = -1;
#endif
return 0;
}
early_param("numa", numa_setup);
/*
* apicid, cpu, node mappings
*/
s16 __apicid_to_node[MAX_LOCAL_APIC] = {
[0 ... MAX_LOCAL_APIC-1] = NUMA_NO_NODE
};
int numa_cpu_node(int cpu)
{
int apicid = early_per_cpu(x86_cpu_to_apicid, cpu);
if (apicid != BAD_APICID)
return __apicid_to_node[apicid];
return NUMA_NO_NODE;
}
cpumask_var_t node_to_cpumask_map[MAX_NUMNODES];
EXPORT_SYMBOL(node_to_cpumask_map);
/*
* Map cpu index to node index
*/
DEFINE_EARLY_PER_CPU(int, x86_cpu_to_node_map, NUMA_NO_NODE);
EXPORT_EARLY_PER_CPU_SYMBOL(x86_cpu_to_node_map);
void numa_set_node(int cpu, int node)
{
int *cpu_to_node_map = early_per_cpu_ptr(x86_cpu_to_node_map);
/* early setting, no percpu area yet */
if (cpu_to_node_map) {
cpu_to_node_map[cpu] = node;
return;
}
#ifdef CONFIG_DEBUG_PER_CPU_MAPS
if (cpu >= nr_cpu_ids || !cpu_possible(cpu)) {
printk(KERN_ERR "numa_set_node: invalid cpu# (%d)\n", cpu);
dump_stack();
return;
}
#endif
per_cpu(x86_cpu_to_node_map, cpu) = node;
set_cpu_numa_node(cpu, node);
}
void numa_clear_node(int cpu)
{
numa_set_node(cpu, NUMA_NO_NODE);
}
/*
* Allocate node_to_cpumask_map based on number of available nodes
* Requires node_possible_map to be valid.
*
* Note: cpumask_of_node() is not valid until after this is done.
* (Use CONFIG_DEBUG_PER_CPU_MAPS to check this.)
*/
void __init setup_node_to_cpumask_map(void)
{
unsigned int node;
/* setup nr_node_ids if not done yet */
if (nr_node_ids == MAX_NUMNODES)
setup_nr_node_ids();
/* allocate the map */
for (node = 0; node < nr_node_ids; node++)
alloc_bootmem_cpumask_var(&node_to_cpumask_map[node]);
/* cpumask_of_node() will now work */
pr_debug("Node to cpumask map for %d nodes\n", nr_node_ids);
}
static int __init numa_add_memblk_to(int nid, u64 start, u64 end,
struct numa_meminfo *mi)
{
/* ignore zero length blks */
if (start == end)
return 0;
/* whine about and ignore invalid blks */
if (start > end || nid < 0 || nid >= MAX_NUMNODES) {
pr_warning("NUMA: Warning: invalid memblk node %d [mem %#010Lx-%#010Lx]\n",
nid, start, end - 1);
return 0;
}
if (mi->nr_blks >= NR_NODE_MEMBLKS) {
pr_err("NUMA: too many memblk ranges\n");
return -EINVAL;
}
mi->blk[mi->nr_blks].start = start;
mi->blk[mi->nr_blks].end = end;
mi->blk[mi->nr_blks].nid = nid;
mi->nr_blks++;
return 0;
}
/**
* numa_remove_memblk_from - Remove one numa_memblk from a numa_meminfo
* @idx: Index of memblk to remove
* @mi: numa_meminfo to remove memblk from
*
* Remove @idx'th numa_memblk from @mi by shifting @mi->blk[] and
* decrementing @mi->nr_blks.
*/
void __init numa_remove_memblk_from(int idx, struct numa_meminfo *mi)
{
mi->nr_blks--;
memmove(&mi->blk[idx], &mi->blk[idx + 1],
(mi->nr_blks - idx) * sizeof(mi->blk[0]));
}
/**
* numa_add_memblk - Add one numa_memblk to numa_meminfo
* @nid: NUMA node ID of the new memblk
* @start: Start address of the new memblk
* @end: End address of the new memblk
*
* Add a new memblk to the default numa_meminfo.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int __init numa_add_memblk(int nid, u64 start, u64 end)
{
return numa_add_memblk_to(nid, start, end, &numa_meminfo);
}
/* Allocate NODE_DATA for a node on the local memory */
static void __init alloc_node_data(int nid)
{
const size_t nd_size = roundup(sizeof(pg_data_t), PAGE_SIZE);
u64 nd_pa;
void *nd;
int tnid;
/*
* Allocate node data. Try node-local memory and then any node.
* Never allocate in DMA zone.
*/
nd_pa = memblock_alloc_nid(nd_size, SMP_CACHE_BYTES, nid);
if (!nd_pa) {
nd_pa = __memblock_alloc_base(nd_size, SMP_CACHE_BYTES,
MEMBLOCK_ALLOC_ACCESSIBLE);
if (!nd_pa) {
pr_err("Cannot find %zu bytes in node %d\n",
nd_size, nid);
return;
}
}
nd = __va(nd_pa);
/* report and initialize */
printk(KERN_INFO "NODE_DATA(%d) allocated [mem %#010Lx-%#010Lx]\n", nid,
nd_pa, nd_pa + nd_size - 1);
tnid = early_pfn_to_nid(nd_pa >> PAGE_SHIFT);
if (tnid != nid)
printk(KERN_INFO " NODE_DATA(%d) on node %d\n", nid, tnid);
node_data[nid] = nd;
memset(NODE_DATA(nid), 0, sizeof(pg_data_t));
node_set_online(nid);
}
/**
* numa_cleanup_meminfo - Cleanup a numa_meminfo
* @mi: numa_meminfo to clean up
*
* Sanitize @mi by merging and removing unncessary memblks. Also check for
* conflicts and clear unused memblks.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int __init numa_cleanup_meminfo(struct numa_meminfo *mi)
{
const u64 low = 0;
const u64 high = PFN_PHYS(max_pfn);
int i, j, k;
/* first, trim all entries */
for (i = 0; i < mi->nr_blks; i++) {
struct numa_memblk *bi = &mi->blk[i];
/* make sure all blocks are inside the limits */
bi->start = max(bi->start, low);
bi->end = min(bi->end, high);
/* and there's no empty block */
if (bi->start >= bi->end)
numa_remove_memblk_from(i--, mi);
}
/* merge neighboring / overlapping entries */
for (i = 0; i < mi->nr_blks; i++) {
struct numa_memblk *bi = &mi->blk[i];
for (j = i + 1; j < mi->nr_blks; j++) {
struct numa_memblk *bj = &mi->blk[j];
u64 start, end;
/*
* See whether there are overlapping blocks. Whine
* about but allow overlaps of the same nid. They
* will be merged below.
*/
if (bi->end > bj->start && bi->start < bj->end) {
if (bi->nid != bj->nid) {
pr_err("NUMA: node %d [mem %#010Lx-%#010Lx] overlaps with node %d [mem %#010Lx-%#010Lx]\n",
bi->nid, bi->start, bi->end - 1,
bj->nid, bj->start, bj->end - 1);
return -EINVAL;
}
pr_warning("NUMA: Warning: node %d [mem %#010Lx-%#010Lx] overlaps with itself [mem %#010Lx-%#010Lx]\n",
bi->nid, bi->start, bi->end - 1,
bj->start, bj->end - 1);
}
/*
* Join together blocks on the same node, holes
* between which don't overlap with memory on other
* nodes.
*/
if (bi->nid != bj->nid)
continue;
start = min(bi->start, bj->start);
end = max(bi->end, bj->end);
for (k = 0; k < mi->nr_blks; k++) {
struct numa_memblk *bk = &mi->blk[k];
if (bi->nid == bk->nid)
continue;
if (start < bk->end && end > bk->start)
break;
}
if (k < mi->nr_blks)
continue;
printk(KERN_INFO "NUMA: Node %d [mem %#010Lx-%#010Lx] + [mem %#010Lx-%#010Lx] -> [mem %#010Lx-%#010Lx]\n",
bi->nid, bi->start, bi->end - 1, bj->start,
bj->end - 1, start, end - 1);
bi->start = start;
bi->end = end;
numa_remove_memblk_from(j--, mi);
}
}
/* clear unused ones */
for (i = mi->nr_blks; i < ARRAY_SIZE(mi->blk); i++) {
mi->blk[i].start = mi->blk[i].end = 0;
mi->blk[i].nid = NUMA_NO_NODE;
}
return 0;
}
/*
* Set nodes, which have memory in @mi, in *@nodemask.
*/
static void __init numa_nodemask_from_meminfo(nodemask_t *nodemask,
const struct numa_meminfo *mi)
{
int i;
for (i = 0; i < ARRAY_SIZE(mi->blk); i++)
if (mi->blk[i].start != mi->blk[i].end &&
mi->blk[i].nid != NUMA_NO_NODE)
node_set(mi->blk[i].nid, *nodemask);
}
/**
* numa_reset_distance - Reset NUMA distance table
*
* The current table is freed. The next numa_set_distance() call will
* create a new one.
*/
void __init numa_reset_distance(void)
{
size_t size = numa_distance_cnt * numa_distance_cnt * sizeof(numa_distance[0]);
/* numa_distance could be 1LU marking allocation failure, test cnt */
if (numa_distance_cnt)
memblock_free(__pa(numa_distance), size);
numa_distance_cnt = 0;
numa_distance = NULL; /* enable table creation */
}
static int __init numa_alloc_distance(void)
{
nodemask_t nodes_parsed;
size_t size;
int i, j, cnt = 0;
u64 phys;
/* size the new table and allocate it */
nodes_parsed = numa_nodes_parsed;
numa_nodemask_from_meminfo(&nodes_parsed, &numa_meminfo);
for_each_node_mask(i, nodes_parsed)
cnt = i;
cnt++;
size = cnt * cnt * sizeof(numa_distance[0]);
phys = memblock_find_in_range(0, PFN_PHYS(max_pfn_mapped),
size, PAGE_SIZE);
if (!phys) {
pr_warning("NUMA: Warning: can't allocate distance table!\n");
/* don't retry until explicitly reset */
numa_distance = (void *)1LU;
return -ENOMEM;
}
memblock_reserve(phys, size);
numa_distance = __va(phys);
numa_distance_cnt = cnt;
/* fill with the default distances */
for (i = 0; i < cnt; i++)
for (j = 0; j < cnt; j++)
numa_distance[i * cnt + j] = i == j ?
LOCAL_DISTANCE : REMOTE_DISTANCE;
printk(KERN_DEBUG "NUMA: Initialized distance table, cnt=%d\n", cnt);
return 0;
}
/**
* numa_set_distance - Set NUMA distance from one NUMA to another
* @from: the 'from' node to set distance
* @to: the 'to' node to set distance
* @distance: NUMA distance
*
* Set the distance from node @from to @to to @distance. If distance table
* doesn't exist, one which is large enough to accommodate all the currently
* known nodes will be created.
*
* If such table cannot be allocated, a warning is printed and further
* calls are ignored until the distance table is reset with
* numa_reset_distance().
*
* If @from or @to is higher than the highest known node or lower than zero
* at the time of table creation or @distance doesn't make sense, the call
* is ignored.
* This is to allow simplification of specific NUMA config implementations.
*/
void __init numa_set_distance(int from, int to, int distance)
{
if (!numa_distance && numa_alloc_distance() < 0)
return;
if (from >= numa_distance_cnt || to >= numa_distance_cnt ||
from < 0 || to < 0) {
pr_warn_once("NUMA: Warning: node ids are out of bound, from=%d to=%d distance=%d\n",
from, to, distance);
return;
}
if ((u8)distance != distance ||
(from == to && distance != LOCAL_DISTANCE)) {
pr_warn_once("NUMA: Warning: invalid distance parameter, from=%d to=%d distance=%d\n",
from, to, distance);
return;
}
numa_distance[from * numa_distance_cnt + to] = distance;
}
int __node_distance(int from, int to)
{
if (from >= numa_distance_cnt || to >= numa_distance_cnt)
return from == to ? LOCAL_DISTANCE : REMOTE_DISTANCE;
return numa_distance[from * numa_distance_cnt + to];
}
EXPORT_SYMBOL(__node_distance);
/*
* Sanity check to catch more bad NUMA configurations (they are amazingly
* common). Make sure the nodes cover all memory.
*/
static bool __init numa_meminfo_cover_memory(const struct numa_meminfo *mi)
{
u64 numaram, e820ram;
int i;
numaram = 0;
for (i = 0; i < mi->nr_blks; i++) {
u64 s = mi->blk[i].start >> PAGE_SHIFT;
u64 e = mi->blk[i].end >> PAGE_SHIFT;
numaram += e - s;
numaram -= __absent_pages_in_range(mi->blk[i].nid, s, e);
if ((s64)numaram < 0)
numaram = 0;
}
e820ram = max_pfn - absent_pages_in_range(0, max_pfn);
/* We seem to lose 3 pages somewhere. Allow 1M of slack. */
if ((s64)(e820ram - numaram) >= (1 << (20 - PAGE_SHIFT))) {
printk(KERN_ERR "NUMA: nodes only cover %LuMB of your %LuMB e820 RAM. Not used.\n",
(numaram << PAGE_SHIFT) >> 20,
(e820ram << PAGE_SHIFT) >> 20);
return false;
}
return true;
}
static void __init numa_clear_kernel_node_hotplug(void)
{
int i, nid;
nodemask_t numa_kernel_nodes = NODE_MASK_NONE;
unsigned long start, end;
struct memblock_region *r;
/*
* At this time, all memory regions reserved by memblock are
* used by the kernel. Set the nid in memblock.reserved will
* mark out all the nodes the kernel resides in.
*/
for (i = 0; i < numa_meminfo.nr_blks; i++) {
struct numa_memblk *mb = &numa_meminfo.blk[i];
memblock_set_node(mb->start, mb->end - mb->start,
&memblock.reserved, mb->nid);
}
/*
* Mark all kernel nodes.
*
* When booting with mem=nn[kMG] or in a kdump kernel, numa_meminfo
* may not include all the memblock.reserved memory ranges because
* trim_snb_memory() reserves specific pages for Sandy Bridge graphics.
*/
for_each_memblock(reserved, r)
if (r->nid != MAX_NUMNODES)
node_set(r->nid, numa_kernel_nodes);
/* Clear MEMBLOCK_HOTPLUG flag for memory in kernel nodes. */
for (i = 0; i < numa_meminfo.nr_blks; i++) {
nid = numa_meminfo.blk[i].nid;
if (!node_isset(nid, numa_kernel_nodes))
continue;
start = numa_meminfo.blk[i].start;
end = numa_meminfo.blk[i].end;
memblock_clear_hotplug(start, end - start);
}
}
static int __init numa_register_memblks(struct numa_meminfo *mi)
{
unsigned long uninitialized_var(pfn_align);
int i, nid;
/* Account for nodes with cpus and no memory */
node_possible_map = numa_nodes_parsed;
numa_nodemask_from_meminfo(&node_possible_map, mi);
if (WARN_ON(nodes_empty(node_possible_map)))
return -EINVAL;
for (i = 0; i < mi->nr_blks; i++) {
struct numa_memblk *mb = &mi->blk[i];
memblock_set_node(mb->start, mb->end - mb->start,
&memblock.memory, mb->nid);
}
/*
* At very early time, the kernel have to use some memory such as
* loading the kernel image. We cannot prevent this anyway. So any
* node the kernel resides in should be un-hotpluggable.
*
* And when we come here, alloc node data won't fail.
*/
numa_clear_kernel_node_hotplug();
/*
* If sections array is gonna be used for pfn -> nid mapping, check
* whether its granularity is fine enough.
*/
#ifdef NODE_NOT_IN_PAGE_FLAGS
pfn_align = node_map_pfn_alignment();
if (pfn_align && pfn_align < PAGES_PER_SECTION) {
printk(KERN_WARNING "Node alignment %LuMB < min %LuMB, rejecting NUMA config\n",
PFN_PHYS(pfn_align) >> 20,
PFN_PHYS(PAGES_PER_SECTION) >> 20);
return -EINVAL;
}
#endif
if (!numa_meminfo_cover_memory(mi))
return -EINVAL;
/* Finally register nodes. */
for_each_node_mask(nid, node_possible_map) {
u64 start = PFN_PHYS(max_pfn);
u64 end = 0;
for (i = 0; i < mi->nr_blks; i++) {
if (nid != mi->blk[i].nid)
continue;
start = min(mi->blk[i].start, start);
end = max(mi->blk[i].end, end);
}
if (start >= end)
continue;
/*
* Don't confuse VM with a node that doesn't have the
* minimum amount of memory:
*/
if (end && (end - start) < NODE_MIN_SIZE)
continue;
alloc_node_data(nid);
}
/* Dump memblock with node info and return. */
memblock_dump_all();
return 0;
}
/*
* There are unfortunately some poorly designed mainboards around that
* only connect memory to a single CPU. This breaks the 1:1 cpu->node
* mapping. To avoid this fill in the mapping for all possible CPUs,
* as the number of CPUs is not known yet. We round robin the existing
* nodes.
*/
static void __init numa_init_array(void)
{
int rr, i;
rr = first_node(node_online_map);
for (i = 0; i < nr_cpu_ids; i++) {
if (early_cpu_to_node(i) != NUMA_NO_NODE)
continue;
numa_set_node(i, rr);
rr = next_node(rr, node_online_map);
if (rr == MAX_NUMNODES)
rr = first_node(node_online_map);
}
}
static int __init numa_init(int (*init_func)(void))
{
int i;
int ret;
for (i = 0; i < MAX_LOCAL_APIC; i++)
set_apicid_to_node(i, NUMA_NO_NODE);
nodes_clear(numa_nodes_parsed);
nodes_clear(node_possible_map);
nodes_clear(node_online_map);
memset(&numa_meminfo, 0, sizeof(numa_meminfo));
WARN_ON(memblock_set_node(0, ULLONG_MAX, &memblock.memory,
MAX_NUMNODES));
WARN_ON(memblock_set_node(0, ULLONG_MAX, &memblock.reserved,
MAX_NUMNODES));
/* In case that parsing SRAT failed. */
WARN_ON(memblock_clear_hotplug(0, ULLONG_MAX));
numa_reset_distance();
ret = init_func();
if (ret < 0)
return ret;
/*
* We reset memblock back to the top-down direction
* here because if we configured ACPI_NUMA, we have
* parsed SRAT in init_func(). It is ok to have the
* reset here even if we did't configure ACPI_NUMA
* or acpi numa init fails and fallbacks to dummy
* numa init.
*/
memblock_set_bottom_up(false);
ret = numa_cleanup_meminfo(&numa_meminfo);
if (ret < 0)
return ret;
numa_emulation(&numa_meminfo, numa_distance_cnt);
ret = numa_register_memblks(&numa_meminfo);
if (ret < 0)
return ret;
for (i = 0; i < nr_cpu_ids; i++) {
int nid = early_cpu_to_node(i);
if (nid == NUMA_NO_NODE)
continue;
if (!node_online(nid))
numa_clear_node(i);
}
numa_init_array();
return 0;
}
/**
* dummy_numa_init - Fallback dummy NUMA init
*
* Used if there's no underlying NUMA architecture, NUMA initialization
* fails, or NUMA is disabled on the command line.
*
* Must online at least one node and add memory blocks that cover all
* allowed memory. This function must not fail.
*/
static int __init dummy_numa_init(void)
{
printk(KERN_INFO "%s\n",
numa_off ? "NUMA turned off" : "No NUMA configuration found");
printk(KERN_INFO "Faking a node at [mem %#018Lx-%#018Lx]\n",
0LLU, PFN_PHYS(max_pfn) - 1);
node_set(0, numa_nodes_parsed);
numa_add_memblk(0, 0, PFN_PHYS(max_pfn));
return 0;
}
/**
* x86_numa_init - Initialize NUMA
*
* Try each configured NUMA initialization method until one succeeds. The
* last fallback is dummy single node config encomapssing whole memory and
* never fails.
*/
void __init x86_numa_init(void)
{
if (!numa_off) {
#ifdef CONFIG_ACPI_NUMA
if (!numa_init(x86_acpi_numa_init))
return;
#endif
#ifdef CONFIG_AMD_NUMA
if (!numa_init(amd_numa_init))
return;
#endif
}
numa_init(dummy_numa_init);
}
static __init int find_near_online_node(int node)
{
int n, val;
int min_val = INT_MAX;
int best_node = -1;
for_each_online_node(n) {
val = node_distance(node, n);
if (val < min_val) {
min_val = val;
best_node = n;
}
}
return best_node;
}
/*
* Setup early cpu_to_node.
*
* Populate cpu_to_node[] only if x86_cpu_to_apicid[],
* and apicid_to_node[] tables have valid entries for a CPU.
* This means we skip cpu_to_node[] initialisation for NUMA
* emulation and faking node case (when running a kernel compiled
* for NUMA on a non NUMA box), which is OK as cpu_to_node[]
* is already initialized in a round robin manner at numa_init_array,
* prior to this call, and this initialization is good enough
* for the fake NUMA cases.
*
* Called before the per_cpu areas are setup.
*/
void __init init_cpu_to_node(void)
{
int cpu;
u16 *cpu_to_apicid = early_per_cpu_ptr(x86_cpu_to_apicid);
BUG_ON(cpu_to_apicid == NULL);
for_each_possible_cpu(cpu) {
int node = numa_cpu_node(cpu);
if (node == NUMA_NO_NODE)
continue;
if (!node_online(node))
node = find_near_online_node(node);
numa_set_node(cpu, node);
}
}
#ifndef CONFIG_DEBUG_PER_CPU_MAPS
# ifndef CONFIG_NUMA_EMU
void numa_add_cpu(int cpu)
{
cpumask_set_cpu(cpu, node_to_cpumask_map[early_cpu_to_node(cpu)]);
}
void numa_remove_cpu(int cpu)
{
cpumask_clear_cpu(cpu, node_to_cpumask_map[early_cpu_to_node(cpu)]);
}
# endif /* !CONFIG_NUMA_EMU */
#else /* !CONFIG_DEBUG_PER_CPU_MAPS */
int __cpu_to_node(int cpu)
{
if (early_per_cpu_ptr(x86_cpu_to_node_map)) {
printk(KERN_WARNING
"cpu_to_node(%d): usage too early!\n", cpu);
dump_stack();
return early_per_cpu_ptr(x86_cpu_to_node_map)[cpu];
}
return per_cpu(x86_cpu_to_node_map, cpu);
}
EXPORT_SYMBOL(__cpu_to_node);
/*
* Same function as cpu_to_node() but used if called before the
* per_cpu areas are setup.
*/
int early_cpu_to_node(int cpu)
{
if (early_per_cpu_ptr(x86_cpu_to_node_map))
return early_per_cpu_ptr(x86_cpu_to_node_map)[cpu];
if (!cpu_possible(cpu)) {
printk(KERN_WARNING
"early_cpu_to_node(%d): no per_cpu area!\n", cpu);
dump_stack();
return NUMA_NO_NODE;
}
return per_cpu(x86_cpu_to_node_map, cpu);
}
void debug_cpumask_set_cpu(int cpu, int node, bool enable)
{
struct cpumask *mask;
if (node == NUMA_NO_NODE) {
/* early_cpu_to_node() already emits a warning and trace */
return;
}
mask = node_to_cpumask_map[node];
if (!mask) {
pr_err("node_to_cpumask_map[%i] NULL\n", node);
dump_stack();
return;
}
if (enable)
cpumask_set_cpu(cpu, mask);
else
cpumask_clear_cpu(cpu, mask);
printk(KERN_DEBUG "%s cpu %d node %d: mask now %*pbl\n",
enable ? "numa_add_cpu" : "numa_remove_cpu",
cpu, node, cpumask_pr_args(mask));
return;
}
# ifndef CONFIG_NUMA_EMU
static void numa_set_cpumask(int cpu, bool enable)
{
debug_cpumask_set_cpu(cpu, early_cpu_to_node(cpu), enable);
}
void numa_add_cpu(int cpu)
{
numa_set_cpumask(cpu, true);
}
void numa_remove_cpu(int cpu)
{
numa_set_cpumask(cpu, false);
}
# endif /* !CONFIG_NUMA_EMU */
/*
* Returns a pointer to the bitmask of CPUs on Node 'node'.
*/
const struct cpumask *cpumask_of_node(int node)
{
if (node >= nr_node_ids) {
printk(KERN_WARNING
"cpumask_of_node(%d): node > nr_node_ids(%d)\n",
node, nr_node_ids);
dump_stack();
return cpu_none_mask;
}
if (node_to_cpumask_map[node] == NULL) {
printk(KERN_WARNING
"cpumask_of_node(%d): no node_to_cpumask_map!\n",
node);
dump_stack();
return cpu_online_mask;
}
return node_to_cpumask_map[node];
}
EXPORT_SYMBOL(cpumask_of_node);
#endif /* !CONFIG_DEBUG_PER_CPU_MAPS */
#ifdef CONFIG_MEMORY_HOTPLUG
int memory_add_physaddr_to_nid(u64 start)
{
struct numa_meminfo *mi = &numa_meminfo;
int nid = mi->blk[0].nid;
int i;
for (i = 0; i < mi->nr_blks; i++)
if (mi->blk[i].start <= start && mi->blk[i].end > start)
nid = mi->blk[i].nid;
return nid;
}
EXPORT_SYMBOL_GPL(memory_add_physaddr_to_nid);
#endif
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_galaxytab-cdma | drivers/staging/msm/tvenc.c | 943 | 6256 | /* Copyright (c) 2008-2009, 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/uaccess.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/pm_qos_params.h>
#define TVENC_C
#include "tvenc.h"
#include "msm_fb.h"
static int tvenc_probe(struct platform_device *pdev);
static int tvenc_remove(struct platform_device *pdev);
static int tvenc_off(struct platform_device *pdev);
static int tvenc_on(struct platform_device *pdev);
static struct platform_device *pdev_list[MSM_FB_MAX_DEV_LIST];
static int pdev_list_cnt;
static struct clk *tvenc_clk;
static struct clk *tvdac_clk;
static struct platform_driver tvenc_driver = {
.probe = tvenc_probe,
.remove = tvenc_remove,
.suspend = NULL,
// .suspend_late = NULL,
// .resume_early = NULL,
.resume = NULL,
.shutdown = NULL,
.driver = {
.name = "tvenc",
},
};
static struct tvenc_platform_data *tvenc_pdata;
static int tvenc_off(struct platform_device *pdev)
{
int ret = 0;
ret = panel_next_off(pdev);
clk_disable(tvenc_clk);
clk_disable(tvdac_clk);
if (tvenc_pdata && tvenc_pdata->pm_vid_en)
ret = tvenc_pdata->pm_vid_en(0);
//pm_qos_update_requirement(PM_QOS_SYSTEM_BUS_FREQ , "tvenc",
// PM_QOS_DEFAULT_VALUE);
if (ret)
printk(KERN_ERR "%s: pm_vid_en(off) failed! %d\n",
__func__, ret);
return ret;
}
static int tvenc_on(struct platform_device *pdev)
{
int ret = 0;
// pm_qos_update_requirement(PM_QOS_SYSTEM_BUS_FREQ , "tvenc",
// 128000);
if (tvenc_pdata && tvenc_pdata->pm_vid_en)
ret = tvenc_pdata->pm_vid_en(1);
if (ret) {
printk(KERN_ERR "%s: pm_vid_en(on) failed! %d\n",
__func__, ret);
return ret;
}
clk_enable(tvenc_clk);
clk_enable(tvdac_clk);
ret = panel_next_on(pdev);
return ret;
}
void tvenc_gen_test_pattern(struct msm_fb_data_type *mfd)
{
uint32 reg = 0, i;
reg = readl(MSM_TV_ENC_CTL);
reg |= TVENC_CTL_TEST_PATT_EN;
for (i = 0; i < 3; i++) {
TV_OUT(TV_ENC_CTL, 0); /* disable TV encoder */
switch (i) {
/*
* TV Encoder - Color Bar Test Pattern
*/
case 0:
reg |= TVENC_CTL_TPG_CLRBAR;
break;
/*
* TV Encoder - Red Frame Test Pattern
*/
case 1:
reg |= TVENC_CTL_TPG_REDCLR;
break;
/*
* TV Encoder - Modulated Ramp Test Pattern
*/
default:
reg |= TVENC_CTL_TPG_MODRAMP;
break;
}
TV_OUT(TV_ENC_CTL, reg);
mdelay(5000);
switch (i) {
/*
* TV Encoder - Color Bar Test Pattern
*/
case 0:
reg &= ~TVENC_CTL_TPG_CLRBAR;
break;
/*
* TV Encoder - Red Frame Test Pattern
*/
case 1:
reg &= ~TVENC_CTL_TPG_REDCLR;
break;
/*
* TV Encoder - Modulated Ramp Test Pattern
*/
default:
reg &= ~TVENC_CTL_TPG_MODRAMP;
break;
}
}
}
static int tvenc_resource_initialized;
static int tvenc_probe(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
struct platform_device *mdp_dev = NULL;
struct msm_fb_panel_data *pdata = NULL;
int rc;
if (pdev->id == 0) {
tvenc_base = ioremap(pdev->resource[0].start,
pdev->resource[0].end -
pdev->resource[0].start + 1);
if (!tvenc_base) {
printk(KERN_ERR
"tvenc_base ioremap failed!\n");
return -ENOMEM;
}
tvenc_pdata = pdev->dev.platform_data;
tvenc_resource_initialized = 1;
return 0;
}
if (!tvenc_resource_initialized)
return -EPERM;
mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
if (pdev_list_cnt >= MSM_FB_MAX_DEV_LIST)
return -ENOMEM;
if (tvenc_base == NULL)
return -ENOMEM;
mdp_dev = platform_device_alloc("mdp", pdev->id);
if (!mdp_dev)
return -ENOMEM;
/*
* link to the latest pdev
*/
mfd->pdev = mdp_dev;
mfd->dest = DISPLAY_TV;
/*
* alloc panel device data
*/
if (platform_device_add_data
(mdp_dev, pdev->dev.platform_data,
sizeof(struct msm_fb_panel_data))) {
printk(KERN_ERR "tvenc_probe: platform_device_add_data failed!\n");
platform_device_put(mdp_dev);
return -ENOMEM;
}
/*
* data chain
*/
pdata = mdp_dev->dev.platform_data;
pdata->on = tvenc_on;
pdata->off = tvenc_off;
pdata->next = pdev;
/*
* get/set panel specific fb info
*/
mfd->panel_info = pdata->panel_info;
mfd->fb_imgType = MDP_YCRYCB_H2V1;
/*
* set driver data
*/
platform_set_drvdata(mdp_dev, mfd);
/*
* register in mdp driver
*/
rc = platform_device_add(mdp_dev);
if (rc)
goto tvenc_probe_err;
pdev_list[pdev_list_cnt++] = pdev;
return 0;
tvenc_probe_err:
platform_device_put(mdp_dev);
return rc;
}
static int tvenc_remove(struct platform_device *pdev)
{
// pm_qos_remove_requirement(PM_QOS_SYSTEM_BUS_FREQ , "tvenc");
return 0;
}
static int tvenc_register_driver(void)
{
return platform_driver_register(&tvenc_driver);
}
static int __init tvenc_driver_init(void)
{
tvenc_clk = clk_get(NULL, "tv_enc_clk");
tvdac_clk = clk_get(NULL, "tv_dac_clk");
if (IS_ERR(tvenc_clk)) {
printk(KERN_ERR "error: can't get tvenc_clk!\n");
return IS_ERR(tvenc_clk);
}
if (IS_ERR(tvdac_clk)) {
printk(KERN_ERR "error: can't get tvdac_clk!\n");
return IS_ERR(tvdac_clk);
}
// pm_qos_add_requirement(PM_QOS_SYSTEM_BUS_FREQ , "tvenc",
// PM_QOS_DEFAULT_VALUE);
return tvenc_register_driver();
}
module_init(tvenc_driver_init);
| gpl-2.0 |
androidarmv6/android_kernel_samsung_msm7x27 | drivers/video/aty/aty128fb.c | 943 | 67382 | /* $Id: aty128fb.c,v 1.1.1.1.36.1 1999/12/11 09:03:05 Exp $
* linux/drivers/video/aty128fb.c -- Frame buffer device for ATI Rage128
*
* Copyright (C) 1999-2003, Brad Douglas <brad@neruo.com>
* Copyright (C) 1999, Anthony Tong <atong@uiuc.edu>
*
* Ani Joshi / Jeff Garzik
* - Code cleanup
*
* Michel Danzer <michdaen@iiic.ethz.ch>
* - 15/16 bit cleanup
* - fix panning
*
* Benjamin Herrenschmidt
* - pmac-specific PM stuff
* - various fixes & cleanups
*
* Andreas Hundt <andi@convergence.de>
* - FB_ACTIVATE fixes
*
* Paul Mackerras <paulus@samba.org>
* - Convert to new framebuffer API,
* fix colormap setting at 16 bits/pixel (565)
*
* Paul Mundt
* - PCI hotplug
*
* Jon Smirl <jonsmirl@yahoo.com>
* - PCI ID update
* - replace ROM BIOS search
*
* Based off of Geert's atyfb.c and vfb.c.
*
* TODO:
* - monitor sensing (DDC)
* - virtual display
* - other platform support (only ppc/x86 supported)
* - hardware cursor support
*
* Please cc: your patches to brad@neruo.com.
*/
/*
* A special note of gratitude to ATI's devrel for providing documentation,
* example code and hardware. Thanks Nitya. -atong and brad
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/uaccess.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/ioport.h>
#include <linux/console.h>
#include <linux/backlight.h>
#include <asm/io.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include "../macmodes.h"
#endif
#ifdef CONFIG_PMAC_BACKLIGHT
#include <asm/backlight.h>
#endif
#ifdef CONFIG_BOOTX_TEXT
#include <asm/btext.h>
#endif /* CONFIG_BOOTX_TEXT */
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#include <video/aty128.h>
/* Debug flag */
#undef DEBUG
#ifdef DEBUG
#define DBG(fmt, args...) printk(KERN_DEBUG "aty128fb: %s " fmt, __func__, ##args);
#else
#define DBG(fmt, args...)
#endif
#ifndef CONFIG_PPC_PMAC
/* default mode */
static struct fb_var_screeninfo default_var __devinitdata = {
/* 640x480, 60 Hz, Non-Interlaced (25.175 MHz dotclock) */
640, 480, 640, 480, 0, 0, 8, 0,
{0, 8, 0}, {0, 8, 0}, {0, 8, 0}, {0, 0, 0},
0, 0, -1, -1, 0, 39722, 48, 16, 33, 10, 96, 2,
0, FB_VMODE_NONINTERLACED
};
#else /* CONFIG_PPC_PMAC */
/* default to 1024x768 at 75Hz on PPC - this will work
* on the iMac, the usual 640x480 @ 60Hz doesn't. */
static struct fb_var_screeninfo default_var = {
/* 1024x768, 75 Hz, Non-Interlaced (78.75 MHz dotclock) */
1024, 768, 1024, 768, 0, 0, 8, 0,
{0, 8, 0}, {0, 8, 0}, {0, 8, 0}, {0, 0, 0},
0, 0, -1, -1, 0, 12699, 160, 32, 28, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED
};
#endif /* CONFIG_PPC_PMAC */
/* default modedb mode */
/* 640x480, 60 Hz, Non-Interlaced (25.172 MHz dotclock) */
static struct fb_videomode defaultmode __devinitdata = {
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 39722,
.left_margin = 48,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 96,
.vsync_len = 2,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED
};
/* Chip generations */
enum {
rage_128,
rage_128_pci,
rage_128_pro,
rage_128_pro_pci,
rage_M3,
rage_M3_pci,
rage_M4,
rage_128_ultra,
};
/* Must match above enum */
static const char *r128_family[] __devinitdata = {
"AGP",
"PCI",
"PRO AGP",
"PRO PCI",
"M3 AGP",
"M3 PCI",
"M4 AGP",
"Ultra AGP",
};
/*
* PCI driver prototypes
*/
static int aty128_probe(struct pci_dev *pdev,
const struct pci_device_id *ent);
static void aty128_remove(struct pci_dev *pdev);
static int aty128_pci_suspend(struct pci_dev *pdev, pm_message_t state);
static int aty128_pci_resume(struct pci_dev *pdev);
static int aty128_do_resume(struct pci_dev *pdev);
/* supported Rage128 chipsets */
static struct pci_device_id aty128_pci_tbl[] = {
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_LE,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_M3_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_LF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_M3 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_MF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_M4 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_ML,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_M4 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PA,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PB,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PC,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PD,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PE,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PG,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PH,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PI,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PJ,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PK,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PL,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PN,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PO,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PQ,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PR,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PS,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PT,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PU,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PV,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PW,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_PX,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pro },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_RE,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_RF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_RG,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_RK,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_RL,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SE,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_pci },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SG,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SH,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SK,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SL,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_SN,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128 },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TF,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TL,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TR,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TS,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TT,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RAGE128_TU,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, rage_128_ultra },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, aty128_pci_tbl);
static struct pci_driver aty128fb_driver = {
.name = "aty128fb",
.id_table = aty128_pci_tbl,
.probe = aty128_probe,
.remove = __devexit_p(aty128_remove),
.suspend = aty128_pci_suspend,
.resume = aty128_pci_resume,
};
/* packed BIOS settings */
#ifndef CONFIG_PPC
typedef struct {
u8 clock_chip_type;
u8 struct_size;
u8 accelerator_entry;
u8 VGA_entry;
u16 VGA_table_offset;
u16 POST_table_offset;
u16 XCLK;
u16 MCLK;
u8 num_PLL_blocks;
u8 size_PLL_blocks;
u16 PCLK_ref_freq;
u16 PCLK_ref_divider;
u32 PCLK_min_freq;
u32 PCLK_max_freq;
u16 MCLK_ref_freq;
u16 MCLK_ref_divider;
u32 MCLK_min_freq;
u32 MCLK_max_freq;
u16 XCLK_ref_freq;
u16 XCLK_ref_divider;
u32 XCLK_min_freq;
u32 XCLK_max_freq;
} __attribute__ ((packed)) PLL_BLOCK;
#endif /* !CONFIG_PPC */
/* onboard memory information */
struct aty128_meminfo {
u8 ML;
u8 MB;
u8 Trcd;
u8 Trp;
u8 Twr;
u8 CL;
u8 Tr2w;
u8 LoopLatency;
u8 DspOn;
u8 Rloop;
const char *name;
};
/* various memory configurations */
static const struct aty128_meminfo sdr_128 =
{ 4, 4, 3, 3, 1, 3, 1, 16, 30, 16, "128-bit SDR SGRAM (1:1)" };
static const struct aty128_meminfo sdr_64 =
{ 4, 8, 3, 3, 1, 3, 1, 17, 46, 17, "64-bit SDR SGRAM (1:1)" };
static const struct aty128_meminfo sdr_sgram =
{ 4, 4, 1, 2, 1, 2, 1, 16, 24, 16, "64-bit SDR SGRAM (2:1)" };
static const struct aty128_meminfo ddr_sgram =
{ 4, 4, 3, 3, 2, 3, 1, 16, 31, 16, "64-bit DDR SGRAM" };
static struct fb_fix_screeninfo aty128fb_fix __devinitdata = {
.id = "ATY Rage128",
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.xpanstep = 8,
.ypanstep = 1,
.mmio_len = 0x2000,
.accel = FB_ACCEL_ATI_RAGE128,
};
static char *mode_option __devinitdata = NULL;
#ifdef CONFIG_PPC_PMAC
static int default_vmode __devinitdata = VMODE_1024_768_60;
static int default_cmode __devinitdata = CMODE_8;
#endif
static int default_crt_on __devinitdata = 0;
static int default_lcd_on __devinitdata = 1;
#ifdef CONFIG_MTRR
static bool mtrr = true;
#endif
#ifdef CONFIG_PMAC_BACKLIGHT
static int backlight __devinitdata = 1;
#else
static int backlight __devinitdata = 0;
#endif
/* PLL constants */
struct aty128_constants {
u32 ref_clk;
u32 ppll_min;
u32 ppll_max;
u32 ref_divider;
u32 xclk;
u32 fifo_width;
u32 fifo_depth;
};
struct aty128_crtc {
u32 gen_cntl;
u32 h_total, h_sync_strt_wid;
u32 v_total, v_sync_strt_wid;
u32 pitch;
u32 offset, offset_cntl;
u32 xoffset, yoffset;
u32 vxres, vyres;
u32 depth, bpp;
};
struct aty128_pll {
u32 post_divider;
u32 feedback_divider;
u32 vclk;
};
struct aty128_ddafifo {
u32 dda_config;
u32 dda_on_off;
};
/* register values for a specific mode */
struct aty128fb_par {
struct aty128_crtc crtc;
struct aty128_pll pll;
struct aty128_ddafifo fifo_reg;
u32 accel_flags;
struct aty128_constants constants; /* PLL and others */
void __iomem *regbase; /* remapped mmio */
u32 vram_size; /* onboard video ram */
int chip_gen;
const struct aty128_meminfo *mem; /* onboard mem info */
#ifdef CONFIG_MTRR
struct { int vram; int vram_valid; } mtrr;
#endif
int blitter_may_be_busy;
int fifo_slots; /* free slots in FIFO (64 max) */
int pm_reg;
int crt_on, lcd_on;
struct pci_dev *pdev;
struct fb_info *next;
int asleep;
int lock_blank;
u8 red[32]; /* see aty128fb_setcolreg */
u8 green[64];
u8 blue[32];
u32 pseudo_palette[16]; /* used for TRUECOLOR */
};
#define round_div(n, d) ((n+(d/2))/d)
static int aty128fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int aty128fb_set_par(struct fb_info *info);
static int aty128fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info);
static int aty128fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *fb);
static int aty128fb_blank(int blank, struct fb_info *fb);
static int aty128fb_ioctl(struct fb_info *info, u_int cmd, unsigned long arg);
static int aty128fb_sync(struct fb_info *info);
/*
* Internal routines
*/
static int aty128_encode_var(struct fb_var_screeninfo *var,
const struct aty128fb_par *par);
static int aty128_decode_var(struct fb_var_screeninfo *var,
struct aty128fb_par *par);
#if 0
static void __devinit aty128_get_pllinfo(struct aty128fb_par *par,
void __iomem *bios);
static void __devinit __iomem *aty128_map_ROM(struct pci_dev *pdev, const struct aty128fb_par *par);
#endif
static void aty128_timings(struct aty128fb_par *par);
static void aty128_init_engine(struct aty128fb_par *par);
static void aty128_reset_engine(const struct aty128fb_par *par);
static void aty128_flush_pixel_cache(const struct aty128fb_par *par);
static void do_wait_for_fifo(u16 entries, struct aty128fb_par *par);
static void wait_for_fifo(u16 entries, struct aty128fb_par *par);
static void wait_for_idle(struct aty128fb_par *par);
static u32 depth_to_dst(u32 depth);
#ifdef CONFIG_FB_ATY128_BACKLIGHT
static void aty128_bl_set_power(struct fb_info *info, int power);
#endif
#define BIOS_IN8(v) (readb(bios + (v)))
#define BIOS_IN16(v) (readb(bios + (v)) | \
(readb(bios + (v) + 1) << 8))
#define BIOS_IN32(v) (readb(bios + (v)) | \
(readb(bios + (v) + 1) << 8) | \
(readb(bios + (v) + 2) << 16) | \
(readb(bios + (v) + 3) << 24))
static struct fb_ops aty128fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = aty128fb_check_var,
.fb_set_par = aty128fb_set_par,
.fb_setcolreg = aty128fb_setcolreg,
.fb_pan_display = aty128fb_pan_display,
.fb_blank = aty128fb_blank,
.fb_ioctl = aty128fb_ioctl,
.fb_sync = aty128fb_sync,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
/*
* Functions to read from/write to the mmio registers
* - endian conversions may possibly be avoided by
* using the other register aperture. TODO.
*/
static inline u32 _aty_ld_le32(volatile unsigned int regindex,
const struct aty128fb_par *par)
{
return readl (par->regbase + regindex);
}
static inline void _aty_st_le32(volatile unsigned int regindex, u32 val,
const struct aty128fb_par *par)
{
writel (val, par->regbase + regindex);
}
static inline u8 _aty_ld_8(unsigned int regindex,
const struct aty128fb_par *par)
{
return readb (par->regbase + regindex);
}
static inline void _aty_st_8(unsigned int regindex, u8 val,
const struct aty128fb_par *par)
{
writeb (val, par->regbase + regindex);
}
#define aty_ld_le32(regindex) _aty_ld_le32(regindex, par)
#define aty_st_le32(regindex, val) _aty_st_le32(regindex, val, par)
#define aty_ld_8(regindex) _aty_ld_8(regindex, par)
#define aty_st_8(regindex, val) _aty_st_8(regindex, val, par)
/*
* Functions to read from/write to the pll registers
*/
#define aty_ld_pll(pll_index) _aty_ld_pll(pll_index, par)
#define aty_st_pll(pll_index, val) _aty_st_pll(pll_index, val, par)
static u32 _aty_ld_pll(unsigned int pll_index,
const struct aty128fb_par *par)
{
aty_st_8(CLOCK_CNTL_INDEX, pll_index & 0x3F);
return aty_ld_le32(CLOCK_CNTL_DATA);
}
static void _aty_st_pll(unsigned int pll_index, u32 val,
const struct aty128fb_par *par)
{
aty_st_8(CLOCK_CNTL_INDEX, (pll_index & 0x3F) | PLL_WR_EN);
aty_st_le32(CLOCK_CNTL_DATA, val);
}
/* return true when the PLL has completed an atomic update */
static int aty_pll_readupdate(const struct aty128fb_par *par)
{
return !(aty_ld_pll(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R);
}
static void aty_pll_wait_readupdate(const struct aty128fb_par *par)
{
unsigned long timeout = jiffies + HZ/100; // should be more than enough
int reset = 1;
while (time_before(jiffies, timeout))
if (aty_pll_readupdate(par)) {
reset = 0;
break;
}
if (reset) /* reset engine?? */
printk(KERN_DEBUG "aty128fb: PLL write timeout!\n");
}
/* tell PLL to update */
static void aty_pll_writeupdate(const struct aty128fb_par *par)
{
aty_pll_wait_readupdate(par);
aty_st_pll(PPLL_REF_DIV,
aty_ld_pll(PPLL_REF_DIV) | PPLL_ATOMIC_UPDATE_W);
}
/* write to the scratch register to test r/w functionality */
static int __devinit register_test(const struct aty128fb_par *par)
{
u32 val;
int flag = 0;
val = aty_ld_le32(BIOS_0_SCRATCH);
aty_st_le32(BIOS_0_SCRATCH, 0x55555555);
if (aty_ld_le32(BIOS_0_SCRATCH) == 0x55555555) {
aty_st_le32(BIOS_0_SCRATCH, 0xAAAAAAAA);
if (aty_ld_le32(BIOS_0_SCRATCH) == 0xAAAAAAAA)
flag = 1;
}
aty_st_le32(BIOS_0_SCRATCH, val); // restore value
return flag;
}
/*
* Accelerator engine functions
*/
static void do_wait_for_fifo(u16 entries, struct aty128fb_par *par)
{
int i;
for (;;) {
for (i = 0; i < 2000000; i++) {
par->fifo_slots = aty_ld_le32(GUI_STAT) & 0x0fff;
if (par->fifo_slots >= entries)
return;
}
aty128_reset_engine(par);
}
}
static void wait_for_idle(struct aty128fb_par *par)
{
int i;
do_wait_for_fifo(64, par);
for (;;) {
for (i = 0; i < 2000000; i++) {
if (!(aty_ld_le32(GUI_STAT) & (1 << 31))) {
aty128_flush_pixel_cache(par);
par->blitter_may_be_busy = 0;
return;
}
}
aty128_reset_engine(par);
}
}
static void wait_for_fifo(u16 entries, struct aty128fb_par *par)
{
if (par->fifo_slots < entries)
do_wait_for_fifo(64, par);
par->fifo_slots -= entries;
}
static void aty128_flush_pixel_cache(const struct aty128fb_par *par)
{
int i;
u32 tmp;
tmp = aty_ld_le32(PC_NGUI_CTLSTAT);
tmp &= ~(0x00ff);
tmp |= 0x00ff;
aty_st_le32(PC_NGUI_CTLSTAT, tmp);
for (i = 0; i < 2000000; i++)
if (!(aty_ld_le32(PC_NGUI_CTLSTAT) & PC_BUSY))
break;
}
static void aty128_reset_engine(const struct aty128fb_par *par)
{
u32 gen_reset_cntl, clock_cntl_index, mclk_cntl;
aty128_flush_pixel_cache(par);
clock_cntl_index = aty_ld_le32(CLOCK_CNTL_INDEX);
mclk_cntl = aty_ld_pll(MCLK_CNTL);
aty_st_pll(MCLK_CNTL, mclk_cntl | 0x00030000);
gen_reset_cntl = aty_ld_le32(GEN_RESET_CNTL);
aty_st_le32(GEN_RESET_CNTL, gen_reset_cntl | SOFT_RESET_GUI);
aty_ld_le32(GEN_RESET_CNTL);
aty_st_le32(GEN_RESET_CNTL, gen_reset_cntl & ~(SOFT_RESET_GUI));
aty_ld_le32(GEN_RESET_CNTL);
aty_st_pll(MCLK_CNTL, mclk_cntl);
aty_st_le32(CLOCK_CNTL_INDEX, clock_cntl_index);
aty_st_le32(GEN_RESET_CNTL, gen_reset_cntl);
/* use old pio mode */
aty_st_le32(PM4_BUFFER_CNTL, PM4_BUFFER_CNTL_NONPM4);
DBG("engine reset");
}
static void aty128_init_engine(struct aty128fb_par *par)
{
u32 pitch_value;
wait_for_idle(par);
/* 3D scaler not spoken here */
wait_for_fifo(1, par);
aty_st_le32(SCALE_3D_CNTL, 0x00000000);
aty128_reset_engine(par);
pitch_value = par->crtc.pitch;
if (par->crtc.bpp == 24) {
pitch_value = pitch_value * 3;
}
wait_for_fifo(4, par);
/* setup engine offset registers */
aty_st_le32(DEFAULT_OFFSET, 0x00000000);
/* setup engine pitch registers */
aty_st_le32(DEFAULT_PITCH, pitch_value);
/* set the default scissor register to max dimensions */
aty_st_le32(DEFAULT_SC_BOTTOM_RIGHT, (0x1FFF << 16) | 0x1FFF);
/* set the drawing controls registers */
aty_st_le32(DP_GUI_MASTER_CNTL,
GMC_SRC_PITCH_OFFSET_DEFAULT |
GMC_DST_PITCH_OFFSET_DEFAULT |
GMC_SRC_CLIP_DEFAULT |
GMC_DST_CLIP_DEFAULT |
GMC_BRUSH_SOLIDCOLOR |
(depth_to_dst(par->crtc.depth) << 8) |
GMC_SRC_DSTCOLOR |
GMC_BYTE_ORDER_MSB_TO_LSB |
GMC_DP_CONVERSION_TEMP_6500 |
ROP3_PATCOPY |
GMC_DP_SRC_RECT |
GMC_3D_FCN_EN_CLR |
GMC_DST_CLR_CMP_FCN_CLEAR |
GMC_AUX_CLIP_CLEAR |
GMC_WRITE_MASK_SET);
wait_for_fifo(8, par);
/* clear the line drawing registers */
aty_st_le32(DST_BRES_ERR, 0);
aty_st_le32(DST_BRES_INC, 0);
aty_st_le32(DST_BRES_DEC, 0);
/* set brush color registers */
aty_st_le32(DP_BRUSH_FRGD_CLR, 0xFFFFFFFF); /* white */
aty_st_le32(DP_BRUSH_BKGD_CLR, 0x00000000); /* black */
/* set source color registers */
aty_st_le32(DP_SRC_FRGD_CLR, 0xFFFFFFFF); /* white */
aty_st_le32(DP_SRC_BKGD_CLR, 0x00000000); /* black */
/* default write mask */
aty_st_le32(DP_WRITE_MASK, 0xFFFFFFFF);
/* Wait for all the writes to be completed before returning */
wait_for_idle(par);
}
/* convert depth values to their register representation */
static u32 depth_to_dst(u32 depth)
{
if (depth <= 8)
return DST_8BPP;
else if (depth <= 15)
return DST_15BPP;
else if (depth == 16)
return DST_16BPP;
else if (depth <= 24)
return DST_24BPP;
else if (depth <= 32)
return DST_32BPP;
return -EINVAL;
}
/*
* PLL informations retreival
*/
#ifndef __sparc__
static void __iomem * __devinit aty128_map_ROM(const struct aty128fb_par *par, struct pci_dev *dev)
{
u16 dptr;
u8 rom_type;
void __iomem *bios;
size_t rom_size;
/* Fix from ATI for problem with Rage128 hardware not leaving ROM enabled */
unsigned int temp;
temp = aty_ld_le32(RAGE128_MPP_TB_CONFIG);
temp &= 0x00ffffffu;
temp |= 0x04 << 24;
aty_st_le32(RAGE128_MPP_TB_CONFIG, temp);
temp = aty_ld_le32(RAGE128_MPP_TB_CONFIG);
bios = pci_map_rom(dev, &rom_size);
if (!bios) {
printk(KERN_ERR "aty128fb: ROM failed to map\n");
return NULL;
}
/* Very simple test to make sure it appeared */
if (BIOS_IN16(0) != 0xaa55) {
printk(KERN_DEBUG "aty128fb: Invalid ROM signature %x should "
" be 0xaa55\n", BIOS_IN16(0));
goto failed;
}
/* Look for the PCI data to check the ROM type */
dptr = BIOS_IN16(0x18);
/* Check the PCI data signature. If it's wrong, we still assume a normal x86 ROM
* for now, until I've verified this works everywhere. The goal here is more
* to phase out Open Firmware images.
*
* Currently, we only look at the first PCI data, we could iteratre and deal with
* them all, and we should use fb_bios_start relative to start of image and not
* relative start of ROM, but so far, I never found a dual-image ATI card
*
* typedef struct {
* u32 signature; + 0x00
* u16 vendor; + 0x04
* u16 device; + 0x06
* u16 reserved_1; + 0x08
* u16 dlen; + 0x0a
* u8 drevision; + 0x0c
* u8 class_hi; + 0x0d
* u16 class_lo; + 0x0e
* u16 ilen; + 0x10
* u16 irevision; + 0x12
* u8 type; + 0x14
* u8 indicator; + 0x15
* u16 reserved_2; + 0x16
* } pci_data_t;
*/
if (BIOS_IN32(dptr) != (('R' << 24) | ('I' << 16) | ('C' << 8) | 'P')) {
printk(KERN_WARNING "aty128fb: PCI DATA signature in ROM incorrect: %08x\n",
BIOS_IN32(dptr));
goto anyway;
}
rom_type = BIOS_IN8(dptr + 0x14);
switch(rom_type) {
case 0:
printk(KERN_INFO "aty128fb: Found Intel x86 BIOS ROM Image\n");
break;
case 1:
printk(KERN_INFO "aty128fb: Found Open Firmware ROM Image\n");
goto failed;
case 2:
printk(KERN_INFO "aty128fb: Found HP PA-RISC ROM Image\n");
goto failed;
default:
printk(KERN_INFO "aty128fb: Found unknown type %d ROM Image\n", rom_type);
goto failed;
}
anyway:
return bios;
failed:
pci_unmap_rom(dev, bios);
return NULL;
}
static void __devinit aty128_get_pllinfo(struct aty128fb_par *par, unsigned char __iomem *bios)
{
unsigned int bios_hdr;
unsigned int bios_pll;
bios_hdr = BIOS_IN16(0x48);
bios_pll = BIOS_IN16(bios_hdr + 0x30);
par->constants.ppll_max = BIOS_IN32(bios_pll + 0x16);
par->constants.ppll_min = BIOS_IN32(bios_pll + 0x12);
par->constants.xclk = BIOS_IN16(bios_pll + 0x08);
par->constants.ref_divider = BIOS_IN16(bios_pll + 0x10);
par->constants.ref_clk = BIOS_IN16(bios_pll + 0x0e);
DBG("ppll_max %d ppll_min %d xclk %d ref_divider %d ref clock %d\n",
par->constants.ppll_max, par->constants.ppll_min,
par->constants.xclk, par->constants.ref_divider,
par->constants.ref_clk);
}
#ifdef CONFIG_X86
static void __iomem * __devinit aty128_find_mem_vbios(struct aty128fb_par *par)
{
/* I simplified this code as we used to miss the signatures in
* a lot of case. It's now closer to XFree, we just don't check
* for signatures at all... Something better will have to be done
* if we end up having conflicts
*/
u32 segstart;
unsigned char __iomem *rom_base = NULL;
for (segstart=0x000c0000; segstart<0x000f0000; segstart+=0x00001000) {
rom_base = ioremap(segstart, 0x10000);
if (rom_base == NULL)
return NULL;
if (readb(rom_base) == 0x55 && readb(rom_base + 1) == 0xaa)
break;
iounmap(rom_base);
rom_base = NULL;
}
return rom_base;
}
#endif
#endif /* ndef(__sparc__) */
/* fill in known card constants if pll_block is not available */
static void __devinit aty128_timings(struct aty128fb_par *par)
{
#ifdef CONFIG_PPC_OF
/* instead of a table lookup, assume OF has properly
* setup the PLL registers and use their values
* to set the XCLK values and reference divider values */
u32 x_mpll_ref_fb_div;
u32 xclk_cntl;
u32 Nx, M;
unsigned PostDivSet[] = { 0, 1, 2, 4, 8, 3, 6, 12 };
#endif
if (!par->constants.ref_clk)
par->constants.ref_clk = 2950;
#ifdef CONFIG_PPC_OF
x_mpll_ref_fb_div = aty_ld_pll(X_MPLL_REF_FB_DIV);
xclk_cntl = aty_ld_pll(XCLK_CNTL) & 0x7;
Nx = (x_mpll_ref_fb_div & 0x00ff00) >> 8;
M = x_mpll_ref_fb_div & 0x0000ff;
par->constants.xclk = round_div((2 * Nx * par->constants.ref_clk),
(M * PostDivSet[xclk_cntl]));
par->constants.ref_divider =
aty_ld_pll(PPLL_REF_DIV) & PPLL_REF_DIV_MASK;
#endif
if (!par->constants.ref_divider) {
par->constants.ref_divider = 0x3b;
aty_st_pll(X_MPLL_REF_FB_DIV, 0x004c4c1e);
aty_pll_writeupdate(par);
}
aty_st_pll(PPLL_REF_DIV, par->constants.ref_divider);
aty_pll_writeupdate(par);
/* from documentation */
if (!par->constants.ppll_min)
par->constants.ppll_min = 12500;
if (!par->constants.ppll_max)
par->constants.ppll_max = 25000; /* 23000 on some cards? */
if (!par->constants.xclk)
par->constants.xclk = 0x1d4d; /* same as mclk */
par->constants.fifo_width = 128;
par->constants.fifo_depth = 32;
switch (aty_ld_le32(MEM_CNTL) & 0x3) {
case 0:
par->mem = &sdr_128;
break;
case 1:
par->mem = &sdr_sgram;
break;
case 2:
par->mem = &ddr_sgram;
break;
default:
par->mem = &sdr_sgram;
}
}
/*
* CRTC programming
*/
/* Program the CRTC registers */
static void aty128_set_crtc(const struct aty128_crtc *crtc,
const struct aty128fb_par *par)
{
aty_st_le32(CRTC_GEN_CNTL, crtc->gen_cntl);
aty_st_le32(CRTC_H_TOTAL_DISP, crtc->h_total);
aty_st_le32(CRTC_H_SYNC_STRT_WID, crtc->h_sync_strt_wid);
aty_st_le32(CRTC_V_TOTAL_DISP, crtc->v_total);
aty_st_le32(CRTC_V_SYNC_STRT_WID, crtc->v_sync_strt_wid);
aty_st_le32(CRTC_PITCH, crtc->pitch);
aty_st_le32(CRTC_OFFSET, crtc->offset);
aty_st_le32(CRTC_OFFSET_CNTL, crtc->offset_cntl);
/* Disable ATOMIC updating. Is this the right place? */
aty_st_pll(PPLL_CNTL, aty_ld_pll(PPLL_CNTL) & ~(0x00030000));
}
static int aty128_var_to_crtc(const struct fb_var_screeninfo *var,
struct aty128_crtc *crtc,
const struct aty128fb_par *par)
{
u32 xres, yres, vxres, vyres, xoffset, yoffset, bpp, dst;
u32 left, right, upper, lower, hslen, vslen, sync, vmode;
u32 h_total, h_disp, h_sync_strt, h_sync_wid, h_sync_pol;
u32 v_total, v_disp, v_sync_strt, v_sync_wid, v_sync_pol, c_sync;
u32 depth, bytpp;
u8 mode_bytpp[7] = { 0, 0, 1, 2, 2, 3, 4 };
/* input */
xres = var->xres;
yres = var->yres;
vxres = var->xres_virtual;
vyres = var->yres_virtual;
xoffset = var->xoffset;
yoffset = var->yoffset;
bpp = var->bits_per_pixel;
left = var->left_margin;
right = var->right_margin;
upper = var->upper_margin;
lower = var->lower_margin;
hslen = var->hsync_len;
vslen = var->vsync_len;
sync = var->sync;
vmode = var->vmode;
if (bpp != 16)
depth = bpp;
else
depth = (var->green.length == 6) ? 16 : 15;
/* check for mode eligibility
* accept only non interlaced modes */
if ((vmode & FB_VMODE_MASK) != FB_VMODE_NONINTERLACED)
return -EINVAL;
/* convert (and round up) and validate */
xres = (xres + 7) & ~7;
xoffset = (xoffset + 7) & ~7;
if (vxres < xres + xoffset)
vxres = xres + xoffset;
if (vyres < yres + yoffset)
vyres = yres + yoffset;
/* convert depth into ATI register depth */
dst = depth_to_dst(depth);
if (dst == -EINVAL) {
printk(KERN_ERR "aty128fb: Invalid depth or RGBA\n");
return -EINVAL;
}
/* convert register depth to bytes per pixel */
bytpp = mode_bytpp[dst];
/* make sure there is enough video ram for the mode */
if ((u32)(vxres * vyres * bytpp) > par->vram_size) {
printk(KERN_ERR "aty128fb: Not enough memory for mode\n");
return -EINVAL;
}
h_disp = (xres >> 3) - 1;
h_total = (((xres + right + hslen + left) >> 3) - 1) & 0xFFFFL;
v_disp = yres - 1;
v_total = (yres + upper + vslen + lower - 1) & 0xFFFFL;
/* check to make sure h_total and v_total are in range */
if (((h_total >> 3) - 1) > 0x1ff || (v_total - 1) > 0x7FF) {
printk(KERN_ERR "aty128fb: invalid width ranges\n");
return -EINVAL;
}
h_sync_wid = (hslen + 7) >> 3;
if (h_sync_wid == 0)
h_sync_wid = 1;
else if (h_sync_wid > 0x3f) /* 0x3f = max hwidth */
h_sync_wid = 0x3f;
h_sync_strt = (h_disp << 3) + right;
v_sync_wid = vslen;
if (v_sync_wid == 0)
v_sync_wid = 1;
else if (v_sync_wid > 0x1f) /* 0x1f = max vwidth */
v_sync_wid = 0x1f;
v_sync_strt = v_disp + lower;
h_sync_pol = sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
v_sync_pol = sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
c_sync = sync & FB_SYNC_COMP_HIGH_ACT ? (1 << 4) : 0;
crtc->gen_cntl = 0x3000000L | c_sync | (dst << 8);
crtc->h_total = h_total | (h_disp << 16);
crtc->v_total = v_total | (v_disp << 16);
crtc->h_sync_strt_wid = h_sync_strt | (h_sync_wid << 16) |
(h_sync_pol << 23);
crtc->v_sync_strt_wid = v_sync_strt | (v_sync_wid << 16) |
(v_sync_pol << 23);
crtc->pitch = vxres >> 3;
crtc->offset = 0;
if ((var->activate & FB_ACTIVATE_MASK) == FB_ACTIVATE_NOW)
crtc->offset_cntl = 0x00010000;
else
crtc->offset_cntl = 0;
crtc->vxres = vxres;
crtc->vyres = vyres;
crtc->xoffset = xoffset;
crtc->yoffset = yoffset;
crtc->depth = depth;
crtc->bpp = bpp;
return 0;
}
static int aty128_pix_width_to_var(int pix_width, struct fb_var_screeninfo *var)
{
/* fill in pixel info */
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 0;
var->transp.msb_right = 0;
switch (pix_width) {
case CRTC_PIX_WIDTH_8BPP:
var->bits_per_pixel = 8;
var->red.offset = 0;
var->red.length = 8;
var->green.offset = 0;
var->green.length = 8;
var->blue.length = 8;
break;
case CRTC_PIX_WIDTH_15BPP:
var->bits_per_pixel = 16;
var->red.offset = 10;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 5;
var->blue.length = 5;
break;
case CRTC_PIX_WIDTH_16BPP:
var->bits_per_pixel = 16;
var->red.offset = 11;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.length = 5;
break;
case CRTC_PIX_WIDTH_24BPP:
var->bits_per_pixel = 24;
var->red.offset = 16;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.length = 8;
break;
case CRTC_PIX_WIDTH_32BPP:
var->bits_per_pixel = 32;
var->red.offset = 16;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.length = 8;
var->transp.offset = 24;
var->transp.length = 8;
break;
default:
printk(KERN_ERR "aty128fb: Invalid pixel width\n");
return -EINVAL;
}
return 0;
}
static int aty128_crtc_to_var(const struct aty128_crtc *crtc,
struct fb_var_screeninfo *var)
{
u32 xres, yres, left, right, upper, lower, hslen, vslen, sync;
u32 h_total, h_disp, h_sync_strt, h_sync_dly, h_sync_wid, h_sync_pol;
u32 v_total, v_disp, v_sync_strt, v_sync_wid, v_sync_pol, c_sync;
u32 pix_width;
/* fun with masking */
h_total = crtc->h_total & 0x1ff;
h_disp = (crtc->h_total >> 16) & 0xff;
h_sync_strt = (crtc->h_sync_strt_wid >> 3) & 0x1ff;
h_sync_dly = crtc->h_sync_strt_wid & 0x7;
h_sync_wid = (crtc->h_sync_strt_wid >> 16) & 0x3f;
h_sync_pol = (crtc->h_sync_strt_wid >> 23) & 0x1;
v_total = crtc->v_total & 0x7ff;
v_disp = (crtc->v_total >> 16) & 0x7ff;
v_sync_strt = crtc->v_sync_strt_wid & 0x7ff;
v_sync_wid = (crtc->v_sync_strt_wid >> 16) & 0x1f;
v_sync_pol = (crtc->v_sync_strt_wid >> 23) & 0x1;
c_sync = crtc->gen_cntl & CRTC_CSYNC_EN ? 1 : 0;
pix_width = crtc->gen_cntl & CRTC_PIX_WIDTH_MASK;
/* do conversions */
xres = (h_disp + 1) << 3;
yres = v_disp + 1;
left = ((h_total - h_sync_strt - h_sync_wid) << 3) - h_sync_dly;
right = ((h_sync_strt - h_disp) << 3) + h_sync_dly;
hslen = h_sync_wid << 3;
upper = v_total - v_sync_strt - v_sync_wid;
lower = v_sync_strt - v_disp;
vslen = v_sync_wid;
sync = (h_sync_pol ? 0 : FB_SYNC_HOR_HIGH_ACT) |
(v_sync_pol ? 0 : FB_SYNC_VERT_HIGH_ACT) |
(c_sync ? FB_SYNC_COMP_HIGH_ACT : 0);
aty128_pix_width_to_var(pix_width, var);
var->xres = xres;
var->yres = yres;
var->xres_virtual = crtc->vxres;
var->yres_virtual = crtc->vyres;
var->xoffset = crtc->xoffset;
var->yoffset = crtc->yoffset;
var->left_margin = left;
var->right_margin = right;
var->upper_margin = upper;
var->lower_margin = lower;
var->hsync_len = hslen;
var->vsync_len = vslen;
var->sync = sync;
var->vmode = FB_VMODE_NONINTERLACED;
return 0;
}
static void aty128_set_crt_enable(struct aty128fb_par *par, int on)
{
if (on) {
aty_st_le32(CRTC_EXT_CNTL, aty_ld_le32(CRTC_EXT_CNTL) | CRT_CRTC_ON);
aty_st_le32(DAC_CNTL, (aty_ld_le32(DAC_CNTL) | DAC_PALETTE2_SNOOP_EN));
} else
aty_st_le32(CRTC_EXT_CNTL, aty_ld_le32(CRTC_EXT_CNTL) & ~CRT_CRTC_ON);
}
static void aty128_set_lcd_enable(struct aty128fb_par *par, int on)
{
u32 reg;
#ifdef CONFIG_FB_ATY128_BACKLIGHT
struct fb_info *info = pci_get_drvdata(par->pdev);
#endif
if (on) {
reg = aty_ld_le32(LVDS_GEN_CNTL);
reg |= LVDS_ON | LVDS_EN | LVDS_BLON | LVDS_DIGION;
reg &= ~LVDS_DISPLAY_DIS;
aty_st_le32(LVDS_GEN_CNTL, reg);
#ifdef CONFIG_FB_ATY128_BACKLIGHT
aty128_bl_set_power(info, FB_BLANK_UNBLANK);
#endif
} else {
#ifdef CONFIG_FB_ATY128_BACKLIGHT
aty128_bl_set_power(info, FB_BLANK_POWERDOWN);
#endif
reg = aty_ld_le32(LVDS_GEN_CNTL);
reg |= LVDS_DISPLAY_DIS;
aty_st_le32(LVDS_GEN_CNTL, reg);
mdelay(100);
reg &= ~(LVDS_ON /*| LVDS_EN*/);
aty_st_le32(LVDS_GEN_CNTL, reg);
}
}
static void aty128_set_pll(struct aty128_pll *pll, const struct aty128fb_par *par)
{
u32 div3;
unsigned char post_conv[] = /* register values for post dividers */
{ 2, 0, 1, 4, 2, 2, 6, 2, 3, 2, 2, 2, 7 };
/* select PPLL_DIV_3 */
aty_st_le32(CLOCK_CNTL_INDEX, aty_ld_le32(CLOCK_CNTL_INDEX) | (3 << 8));
/* reset PLL */
aty_st_pll(PPLL_CNTL,
aty_ld_pll(PPLL_CNTL) | PPLL_RESET | PPLL_ATOMIC_UPDATE_EN);
/* write the reference divider */
aty_pll_wait_readupdate(par);
aty_st_pll(PPLL_REF_DIV, par->constants.ref_divider & 0x3ff);
aty_pll_writeupdate(par);
div3 = aty_ld_pll(PPLL_DIV_3);
div3 &= ~PPLL_FB3_DIV_MASK;
div3 |= pll->feedback_divider;
div3 &= ~PPLL_POST3_DIV_MASK;
div3 |= post_conv[pll->post_divider] << 16;
/* write feedback and post dividers */
aty_pll_wait_readupdate(par);
aty_st_pll(PPLL_DIV_3, div3);
aty_pll_writeupdate(par);
aty_pll_wait_readupdate(par);
aty_st_pll(HTOTAL_CNTL, 0); /* no horiz crtc adjustment */
aty_pll_writeupdate(par);
/* clear the reset, just in case */
aty_st_pll(PPLL_CNTL, aty_ld_pll(PPLL_CNTL) & ~PPLL_RESET);
}
static int aty128_var_to_pll(u32 period_in_ps, struct aty128_pll *pll,
const struct aty128fb_par *par)
{
const struct aty128_constants c = par->constants;
unsigned char post_dividers[] = {1,2,4,8,3,6,12};
u32 output_freq;
u32 vclk; /* in .01 MHz */
int i = 0;
u32 n, d;
vclk = 100000000 / period_in_ps; /* convert units to 10 kHz */
/* adjust pixel clock if necessary */
if (vclk > c.ppll_max)
vclk = c.ppll_max;
if (vclk * 12 < c.ppll_min)
vclk = c.ppll_min/12;
/* now, find an acceptable divider */
for (i = 0; i < ARRAY_SIZE(post_dividers); i++) {
output_freq = post_dividers[i] * vclk;
if (output_freq >= c.ppll_min && output_freq <= c.ppll_max) {
pll->post_divider = post_dividers[i];
break;
}
}
if (i == ARRAY_SIZE(post_dividers))
return -EINVAL;
/* calculate feedback divider */
n = c.ref_divider * output_freq;
d = c.ref_clk;
pll->feedback_divider = round_div(n, d);
pll->vclk = vclk;
DBG("post %d feedback %d vlck %d output %d ref_divider %d "
"vclk_per: %d\n", pll->post_divider,
pll->feedback_divider, vclk, output_freq,
c.ref_divider, period_in_ps);
return 0;
}
static int aty128_pll_to_var(const struct aty128_pll *pll, struct fb_var_screeninfo *var)
{
var->pixclock = 100000000 / pll->vclk;
return 0;
}
static void aty128_set_fifo(const struct aty128_ddafifo *dsp,
const struct aty128fb_par *par)
{
aty_st_le32(DDA_CONFIG, dsp->dda_config);
aty_st_le32(DDA_ON_OFF, dsp->dda_on_off);
}
static int aty128_ddafifo(struct aty128_ddafifo *dsp,
const struct aty128_pll *pll,
u32 depth,
const struct aty128fb_par *par)
{
const struct aty128_meminfo *m = par->mem;
u32 xclk = par->constants.xclk;
u32 fifo_width = par->constants.fifo_width;
u32 fifo_depth = par->constants.fifo_depth;
s32 x, b, p, ron, roff;
u32 n, d, bpp;
/* round up to multiple of 8 */
bpp = (depth+7) & ~7;
n = xclk * fifo_width;
d = pll->vclk * bpp;
x = round_div(n, d);
ron = 4 * m->MB +
3 * ((m->Trcd - 2 > 0) ? m->Trcd - 2 : 0) +
2 * m->Trp +
m->Twr +
m->CL +
m->Tr2w +
x;
DBG("x %x\n", x);
b = 0;
while (x) {
x >>= 1;
b++;
}
p = b + 1;
ron <<= (11 - p);
n <<= (11 - p);
x = round_div(n, d);
roff = x * (fifo_depth - 4);
if ((ron + m->Rloop) >= roff) {
printk(KERN_ERR "aty128fb: Mode out of range!\n");
return -EINVAL;
}
DBG("p: %x rloop: %x x: %x ron: %x roff: %x\n",
p, m->Rloop, x, ron, roff);
dsp->dda_config = p << 16 | m->Rloop << 20 | x;
dsp->dda_on_off = ron << 16 | roff;
return 0;
}
/*
* This actually sets the video mode.
*/
static int aty128fb_set_par(struct fb_info *info)
{
struct aty128fb_par *par = info->par;
u32 config;
int err;
if ((err = aty128_decode_var(&info->var, par)) != 0)
return err;
if (par->blitter_may_be_busy)
wait_for_idle(par);
/* clear all registers that may interfere with mode setting */
aty_st_le32(OVR_CLR, 0);
aty_st_le32(OVR_WID_LEFT_RIGHT, 0);
aty_st_le32(OVR_WID_TOP_BOTTOM, 0);
aty_st_le32(OV0_SCALE_CNTL, 0);
aty_st_le32(MPP_TB_CONFIG, 0);
aty_st_le32(MPP_GP_CONFIG, 0);
aty_st_le32(SUBPIC_CNTL, 0);
aty_st_le32(VIPH_CONTROL, 0);
aty_st_le32(I2C_CNTL_1, 0); /* turn off i2c */
aty_st_le32(GEN_INT_CNTL, 0); /* turn off interrupts */
aty_st_le32(CAP0_TRIG_CNTL, 0);
aty_st_le32(CAP1_TRIG_CNTL, 0);
aty_st_8(CRTC_EXT_CNTL + 1, 4); /* turn video off */
aty128_set_crtc(&par->crtc, par);
aty128_set_pll(&par->pll, par);
aty128_set_fifo(&par->fifo_reg, par);
config = aty_ld_le32(CNFG_CNTL) & ~3;
#if defined(__BIG_ENDIAN)
if (par->crtc.bpp == 32)
config |= 2; /* make aperture do 32 bit swapping */
else if (par->crtc.bpp == 16)
config |= 1; /* make aperture do 16 bit swapping */
#endif
aty_st_le32(CNFG_CNTL, config);
aty_st_8(CRTC_EXT_CNTL + 1, 0); /* turn the video back on */
info->fix.line_length = (par->crtc.vxres * par->crtc.bpp) >> 3;
info->fix.visual = par->crtc.bpp == 8 ? FB_VISUAL_PSEUDOCOLOR
: FB_VISUAL_DIRECTCOLOR;
if (par->chip_gen == rage_M3) {
aty128_set_crt_enable(par, par->crt_on);
aty128_set_lcd_enable(par, par->lcd_on);
}
if (par->accel_flags & FB_ACCELF_TEXT)
aty128_init_engine(par);
#ifdef CONFIG_BOOTX_TEXT
btext_update_display(info->fix.smem_start,
(((par->crtc.h_total>>16) & 0xff)+1)*8,
((par->crtc.v_total>>16) & 0x7ff)+1,
par->crtc.bpp,
par->crtc.vxres*par->crtc.bpp/8);
#endif /* CONFIG_BOOTX_TEXT */
return 0;
}
/*
* encode/decode the User Defined Part of the Display
*/
static int aty128_decode_var(struct fb_var_screeninfo *var, struct aty128fb_par *par)
{
int err;
struct aty128_crtc crtc;
struct aty128_pll pll;
struct aty128_ddafifo fifo_reg;
if ((err = aty128_var_to_crtc(var, &crtc, par)))
return err;
if ((err = aty128_var_to_pll(var->pixclock, &pll, par)))
return err;
if ((err = aty128_ddafifo(&fifo_reg, &pll, crtc.depth, par)))
return err;
par->crtc = crtc;
par->pll = pll;
par->fifo_reg = fifo_reg;
par->accel_flags = var->accel_flags;
return 0;
}
static int aty128_encode_var(struct fb_var_screeninfo *var,
const struct aty128fb_par *par)
{
int err;
if ((err = aty128_crtc_to_var(&par->crtc, var)))
return err;
if ((err = aty128_pll_to_var(&par->pll, var)))
return err;
var->nonstd = 0;
var->activate = 0;
var->height = -1;
var->width = -1;
var->accel_flags = par->accel_flags;
return 0;
}
static int aty128fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct aty128fb_par par;
int err;
par = *(struct aty128fb_par *)info->par;
if ((err = aty128_decode_var(var, &par)) != 0)
return err;
aty128_encode_var(var, &par);
return 0;
}
/*
* Pan or Wrap the Display
*/
static int aty128fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *fb)
{
struct aty128fb_par *par = fb->par;
u32 xoffset, yoffset;
u32 offset;
u32 xres, yres;
xres = (((par->crtc.h_total >> 16) & 0xff) + 1) << 3;
yres = ((par->crtc.v_total >> 16) & 0x7ff) + 1;
xoffset = (var->xoffset +7) & ~7;
yoffset = var->yoffset;
if (xoffset+xres > par->crtc.vxres || yoffset+yres > par->crtc.vyres)
return -EINVAL;
par->crtc.xoffset = xoffset;
par->crtc.yoffset = yoffset;
offset = ((yoffset * par->crtc.vxres + xoffset)*(par->crtc.bpp >> 3)) & ~7;
if (par->crtc.bpp == 24)
offset += 8 * (offset % 3); /* Must be multiple of 8 and 3 */
aty_st_le32(CRTC_OFFSET, offset);
return 0;
}
/*
* Helper function to store a single palette register
*/
static void aty128_st_pal(u_int regno, u_int red, u_int green, u_int blue,
struct aty128fb_par *par)
{
if (par->chip_gen == rage_M3) {
#if 0
/* Note: For now, on M3, we set palette on both heads, which may
* be useless. Can someone with a M3 check this ?
*
* This code would still be useful if using the second CRTC to
* do mirroring
*/
aty_st_le32(DAC_CNTL, aty_ld_le32(DAC_CNTL) | DAC_PALETTE_ACCESS_CNTL);
aty_st_8(PALETTE_INDEX, regno);
aty_st_le32(PALETTE_DATA, (red<<16)|(green<<8)|blue);
#endif
aty_st_le32(DAC_CNTL, aty_ld_le32(DAC_CNTL) & ~DAC_PALETTE_ACCESS_CNTL);
}
aty_st_8(PALETTE_INDEX, regno);
aty_st_le32(PALETTE_DATA, (red<<16)|(green<<8)|blue);
}
static int aty128fb_sync(struct fb_info *info)
{
struct aty128fb_par *par = info->par;
if (par->blitter_may_be_busy)
wait_for_idle(par);
return 0;
}
#ifndef MODULE
static int __devinit aty128fb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!strncmp(this_opt, "lcd:", 4)) {
default_lcd_on = simple_strtoul(this_opt+4, NULL, 0);
continue;
} else if (!strncmp(this_opt, "crt:", 4)) {
default_crt_on = simple_strtoul(this_opt+4, NULL, 0);
continue;
} else if (!strncmp(this_opt, "backlight:", 10)) {
backlight = simple_strtoul(this_opt+10, NULL, 0);
continue;
}
#ifdef CONFIG_MTRR
if(!strncmp(this_opt, "nomtrr", 6)) {
mtrr = 0;
continue;
}
#endif
#ifdef CONFIG_PPC_PMAC
/* vmode and cmode deprecated */
if (!strncmp(this_opt, "vmode:", 6)) {
unsigned int vmode = simple_strtoul(this_opt+6, NULL, 0);
if (vmode > 0 && vmode <= VMODE_MAX)
default_vmode = vmode;
continue;
} else if (!strncmp(this_opt, "cmode:", 6)) {
unsigned int cmode = simple_strtoul(this_opt+6, NULL, 0);
switch (cmode) {
case 0:
case 8:
default_cmode = CMODE_8;
break;
case 15:
case 16:
default_cmode = CMODE_16;
break;
case 24:
case 32:
default_cmode = CMODE_32;
break;
}
continue;
}
#endif /* CONFIG_PPC_PMAC */
mode_option = this_opt;
}
return 0;
}
#endif /* MODULE */
/* Backlight */
#ifdef CONFIG_FB_ATY128_BACKLIGHT
#define MAX_LEVEL 0xFF
static int aty128_bl_get_level_brightness(struct aty128fb_par *par,
int level)
{
struct fb_info *info = pci_get_drvdata(par->pdev);
int atylevel;
/* Get and convert the value */
/* No locking of bl_curve since we read a single value */
atylevel = MAX_LEVEL -
(info->bl_curve[level] * FB_BACKLIGHT_MAX / MAX_LEVEL);
if (atylevel < 0)
atylevel = 0;
else if (atylevel > MAX_LEVEL)
atylevel = MAX_LEVEL;
return atylevel;
}
/* We turn off the LCD completely instead of just dimming the backlight.
* This provides greater power saving and the display is useless without
* backlight anyway
*/
#define BACKLIGHT_LVDS_OFF
/* That one prevents proper CRT output with LCD off */
#undef BACKLIGHT_DAC_OFF
static int aty128_bl_update_status(struct backlight_device *bd)
{
struct aty128fb_par *par = bl_get_data(bd);
unsigned int reg = aty_ld_le32(LVDS_GEN_CNTL);
int level;
if (bd->props.power != FB_BLANK_UNBLANK ||
bd->props.fb_blank != FB_BLANK_UNBLANK ||
!par->lcd_on)
level = 0;
else
level = bd->props.brightness;
reg |= LVDS_BL_MOD_EN | LVDS_BLON;
if (level > 0) {
reg |= LVDS_DIGION;
if (!(reg & LVDS_ON)) {
reg &= ~LVDS_BLON;
aty_st_le32(LVDS_GEN_CNTL, reg);
aty_ld_le32(LVDS_GEN_CNTL);
mdelay(10);
reg |= LVDS_BLON;
aty_st_le32(LVDS_GEN_CNTL, reg);
}
reg &= ~LVDS_BL_MOD_LEVEL_MASK;
reg |= (aty128_bl_get_level_brightness(par, level) << LVDS_BL_MOD_LEVEL_SHIFT);
#ifdef BACKLIGHT_LVDS_OFF
reg |= LVDS_ON | LVDS_EN;
reg &= ~LVDS_DISPLAY_DIS;
#endif
aty_st_le32(LVDS_GEN_CNTL, reg);
#ifdef BACKLIGHT_DAC_OFF
aty_st_le32(DAC_CNTL, aty_ld_le32(DAC_CNTL) & (~DAC_PDWN));
#endif
} else {
reg &= ~LVDS_BL_MOD_LEVEL_MASK;
reg |= (aty128_bl_get_level_brightness(par, 0) << LVDS_BL_MOD_LEVEL_SHIFT);
#ifdef BACKLIGHT_LVDS_OFF
reg |= LVDS_DISPLAY_DIS;
aty_st_le32(LVDS_GEN_CNTL, reg);
aty_ld_le32(LVDS_GEN_CNTL);
udelay(10);
reg &= ~(LVDS_ON | LVDS_EN | LVDS_BLON | LVDS_DIGION);
#endif
aty_st_le32(LVDS_GEN_CNTL, reg);
#ifdef BACKLIGHT_DAC_OFF
aty_st_le32(DAC_CNTL, aty_ld_le32(DAC_CNTL) | DAC_PDWN);
#endif
}
return 0;
}
static int aty128_bl_get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static struct backlight_ops aty128_bl_data = {
.get_brightness = aty128_bl_get_brightness,
.update_status = aty128_bl_update_status,
};
static void aty128_bl_set_power(struct fb_info *info, int power)
{
if (info->bl_dev) {
info->bl_dev->props.power = power;
backlight_update_status(info->bl_dev);
}
}
static void aty128_bl_init(struct aty128fb_par *par)
{
struct backlight_properties props;
struct fb_info *info = pci_get_drvdata(par->pdev);
struct backlight_device *bd;
char name[12];
/* Could be extended to Rage128Pro LVDS output too */
if (par->chip_gen != rage_M3)
return;
#ifdef CONFIG_PMAC_BACKLIGHT
if (!pmac_has_backlight_type("ati"))
return;
#endif
snprintf(name, sizeof(name), "aty128bl%d", info->node);
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = FB_BACKLIGHT_LEVELS - 1;
bd = backlight_device_register(name, info->dev, par, &aty128_bl_data,
&props);
if (IS_ERR(bd)) {
info->bl_dev = NULL;
printk(KERN_WARNING "aty128: Backlight registration failed\n");
goto error;
}
info->bl_dev = bd;
fb_bl_default_curve(info, 0,
63 * FB_BACKLIGHT_MAX / MAX_LEVEL,
219 * FB_BACKLIGHT_MAX / MAX_LEVEL);
bd->props.brightness = bd->props.max_brightness;
bd->props.power = FB_BLANK_UNBLANK;
backlight_update_status(bd);
printk("aty128: Backlight initialized (%s)\n", name);
return;
error:
return;
}
static void aty128_bl_exit(struct backlight_device *bd)
{
backlight_device_unregister(bd);
printk("aty128: Backlight unloaded\n");
}
#endif /* CONFIG_FB_ATY128_BACKLIGHT */
/*
* Initialisation
*/
#ifdef CONFIG_PPC_PMAC__disabled
static void aty128_early_resume(void *data)
{
struct aty128fb_par *par = data;
if (try_acquire_console_sem())
return;
pci_restore_state(par->pdev);
aty128_do_resume(par->pdev);
release_console_sem();
}
#endif /* CONFIG_PPC_PMAC */
static int __devinit aty128_init(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct aty128fb_par *par = info->par;
struct fb_var_screeninfo var;
char video_card[50];
u8 chip_rev;
u32 dac;
/* Get the chip revision */
chip_rev = (aty_ld_le32(CNFG_CNTL) >> 16) & 0x1F;
strcpy(video_card, "Rage128 XX ");
video_card[8] = ent->device >> 8;
video_card[9] = ent->device & 0xFF;
/* range check to make sure */
if (ent->driver_data < ARRAY_SIZE(r128_family))
strlcat(video_card, r128_family[ent->driver_data], sizeof(video_card));
printk(KERN_INFO "aty128fb: %s [chip rev 0x%x] ", video_card, chip_rev);
if (par->vram_size % (1024 * 1024) == 0)
printk("%dM %s\n", par->vram_size / (1024*1024), par->mem->name);
else
printk("%dk %s\n", par->vram_size / 1024, par->mem->name);
par->chip_gen = ent->driver_data;
/* fill in info */
info->fbops = &aty128fb_ops;
info->flags = FBINFO_FLAG_DEFAULT;
par->lcd_on = default_lcd_on;
par->crt_on = default_crt_on;
var = default_var;
#ifdef CONFIG_PPC_PMAC
if (machine_is(powermac)) {
/* Indicate sleep capability */
if (par->chip_gen == rage_M3) {
pmac_call_feature(PMAC_FTR_DEVICE_CAN_WAKE, NULL, 0, 1);
#if 0 /* Disable the early video resume hack for now as it's causing problems, among
* others we now rely on the PCI core restoring the config space for us, which
* isn't the case with that hack, and that code path causes various things to
* be called with interrupts off while they shouldn't. I'm leaving the code in
* as it can be useful for debugging purposes
*/
pmac_set_early_video_resume(aty128_early_resume, par);
#endif
}
/* Find default mode */
if (mode_option) {
if (!mac_find_mode(&var, info, mode_option, 8))
var = default_var;
} else {
if (default_vmode <= 0 || default_vmode > VMODE_MAX)
default_vmode = VMODE_1024_768_60;
/* iMacs need that resolution
* PowerMac2,1 first r128 iMacs
* PowerMac2,2 summer 2000 iMacs
* PowerMac4,1 january 2001 iMacs "flower power"
*/
if (of_machine_is_compatible("PowerMac2,1") ||
of_machine_is_compatible("PowerMac2,2") ||
of_machine_is_compatible("PowerMac4,1"))
default_vmode = VMODE_1024_768_75;
/* iBook SE */
if (of_machine_is_compatible("PowerBook2,2"))
default_vmode = VMODE_800_600_60;
/* PowerBook Firewire (Pismo), iBook Dual USB */
if (of_machine_is_compatible("PowerBook3,1") ||
of_machine_is_compatible("PowerBook4,1"))
default_vmode = VMODE_1024_768_60;
/* PowerBook Titanium */
if (of_machine_is_compatible("PowerBook3,2"))
default_vmode = VMODE_1152_768_60;
if (default_cmode > 16)
default_cmode = CMODE_32;
else if (default_cmode > 8)
default_cmode = CMODE_16;
else
default_cmode = CMODE_8;
if (mac_vmode_to_var(default_vmode, default_cmode, &var))
var = default_var;
}
} else
#endif /* CONFIG_PPC_PMAC */
{
if (mode_option)
if (fb_find_mode(&var, info, mode_option, NULL,
0, &defaultmode, 8) == 0)
var = default_var;
}
var.accel_flags &= ~FB_ACCELF_TEXT;
// var.accel_flags |= FB_ACCELF_TEXT;/* FIXME Will add accel later */
if (aty128fb_check_var(&var, info)) {
printk(KERN_ERR "aty128fb: Cannot set default mode.\n");
return 0;
}
/* setup the DAC the way we like it */
dac = aty_ld_le32(DAC_CNTL);
dac |= (DAC_8BIT_EN | DAC_RANGE_CNTL);
dac |= DAC_MASK;
if (par->chip_gen == rage_M3)
dac |= DAC_PALETTE2_SNOOP_EN;
aty_st_le32(DAC_CNTL, dac);
/* turn off bus mastering, just in case */
aty_st_le32(BUS_CNTL, aty_ld_le32(BUS_CNTL) | BUS_MASTER_DIS);
info->var = var;
fb_alloc_cmap(&info->cmap, 256, 0);
var.activate = FB_ACTIVATE_NOW;
aty128_init_engine(par);
par->pm_reg = pci_find_capability(pdev, PCI_CAP_ID_PM);
par->pdev = pdev;
par->asleep = 0;
par->lock_blank = 0;
#ifdef CONFIG_FB_ATY128_BACKLIGHT
if (backlight)
aty128_bl_init(par);
#endif
if (register_framebuffer(info) < 0)
return 0;
printk(KERN_INFO "fb%d: %s frame buffer device on %s\n",
info->node, info->fix.id, video_card);
return 1; /* success! */
}
#ifdef CONFIG_PCI
/* register a card ++ajoshi */
static int __devinit aty128_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
unsigned long fb_addr, reg_addr;
struct aty128fb_par *par;
struct fb_info *info;
int err;
#ifndef __sparc__
void __iomem *bios = NULL;
#endif
/* Enable device in PCI config */
if ((err = pci_enable_device(pdev))) {
printk(KERN_ERR "aty128fb: Cannot enable PCI device: %d\n",
err);
return -ENODEV;
}
fb_addr = pci_resource_start(pdev, 0);
if (!request_mem_region(fb_addr, pci_resource_len(pdev, 0),
"aty128fb FB")) {
printk(KERN_ERR "aty128fb: cannot reserve frame "
"buffer memory\n");
return -ENODEV;
}
reg_addr = pci_resource_start(pdev, 2);
if (!request_mem_region(reg_addr, pci_resource_len(pdev, 2),
"aty128fb MMIO")) {
printk(KERN_ERR "aty128fb: cannot reserve MMIO region\n");
goto err_free_fb;
}
/* We have the resources. Now virtualize them */
info = framebuffer_alloc(sizeof(struct aty128fb_par), &pdev->dev);
if (info == NULL) {
printk(KERN_ERR "aty128fb: can't alloc fb_info_aty128\n");
goto err_free_mmio;
}
par = info->par;
info->pseudo_palette = par->pseudo_palette;
/* Virtualize mmio region */
info->fix.mmio_start = reg_addr;
par->regbase = pci_ioremap_bar(pdev, 2);
if (!par->regbase)
goto err_free_info;
/* Grab memory size from the card */
// How does this relate to the resource length from the PCI hardware?
par->vram_size = aty_ld_le32(CNFG_MEMSIZE) & 0x03FFFFFF;
/* Virtualize the framebuffer */
info->screen_base = ioremap(fb_addr, par->vram_size);
if (!info->screen_base)
goto err_unmap_out;
/* Set up info->fix */
info->fix = aty128fb_fix;
info->fix.smem_start = fb_addr;
info->fix.smem_len = par->vram_size;
info->fix.mmio_start = reg_addr;
/* If we can't test scratch registers, something is seriously wrong */
if (!register_test(par)) {
printk(KERN_ERR "aty128fb: Can't write to video register!\n");
goto err_out;
}
#ifndef __sparc__
bios = aty128_map_ROM(par, pdev);
#ifdef CONFIG_X86
if (bios == NULL)
bios = aty128_find_mem_vbios(par);
#endif
if (bios == NULL)
printk(KERN_INFO "aty128fb: BIOS not located, guessing timings.\n");
else {
printk(KERN_INFO "aty128fb: Rage128 BIOS located\n");
aty128_get_pllinfo(par, bios);
pci_unmap_rom(pdev, bios);
}
#endif /* __sparc__ */
aty128_timings(par);
pci_set_drvdata(pdev, info);
if (!aty128_init(pdev, ent))
goto err_out;
#ifdef CONFIG_MTRR
if (mtrr) {
par->mtrr.vram = mtrr_add(info->fix.smem_start,
par->vram_size, MTRR_TYPE_WRCOMB, 1);
par->mtrr.vram_valid = 1;
/* let there be speed */
printk(KERN_INFO "aty128fb: Rage128 MTRR set to ON\n");
}
#endif /* CONFIG_MTRR */
return 0;
err_out:
iounmap(info->screen_base);
err_unmap_out:
iounmap(par->regbase);
err_free_info:
framebuffer_release(info);
err_free_mmio:
release_mem_region(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2));
err_free_fb:
release_mem_region(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
return -ENODEV;
}
static void __devexit aty128_remove(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct aty128fb_par *par;
if (!info)
return;
par = info->par;
unregister_framebuffer(info);
#ifdef CONFIG_FB_ATY128_BACKLIGHT
aty128_bl_exit(info->bl_dev);
#endif
#ifdef CONFIG_MTRR
if (par->mtrr.vram_valid)
mtrr_del(par->mtrr.vram, info->fix.smem_start,
par->vram_size);
#endif /* CONFIG_MTRR */
iounmap(par->regbase);
iounmap(info->screen_base);
release_mem_region(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
release_mem_region(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2));
framebuffer_release(info);
}
#endif /* CONFIG_PCI */
/*
* Blank the display.
*/
static int aty128fb_blank(int blank, struct fb_info *fb)
{
struct aty128fb_par *par = fb->par;
u8 state;
if (par->lock_blank || par->asleep)
return 0;
switch (blank) {
case FB_BLANK_NORMAL:
state = 4;
break;
case FB_BLANK_VSYNC_SUSPEND:
state = 6;
break;
case FB_BLANK_HSYNC_SUSPEND:
state = 5;
break;
case FB_BLANK_POWERDOWN:
state = 7;
break;
case FB_BLANK_UNBLANK:
default:
state = 0;
break;
}
aty_st_8(CRTC_EXT_CNTL+1, state);
if (par->chip_gen == rage_M3) {
aty128_set_crt_enable(par, par->crt_on && !blank);
aty128_set_lcd_enable(par, par->lcd_on && !blank);
}
return 0;
}
/*
* Set a single color register. The values supplied are already
* rounded down to the hardware's capabilities (according to the
* entries in the var structure). Return != 0 for invalid regno.
*/
static int aty128fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
struct aty128fb_par *par = info->par;
if (regno > 255
|| (par->crtc.depth == 16 && regno > 63)
|| (par->crtc.depth == 15 && regno > 31))
return 1;
red >>= 8;
green >>= 8;
blue >>= 8;
if (regno < 16) {
int i;
u32 *pal = info->pseudo_palette;
switch (par->crtc.depth) {
case 15:
pal[regno] = (regno << 10) | (regno << 5) | regno;
break;
case 16:
pal[regno] = (regno << 11) | (regno << 6) | regno;
break;
case 24:
pal[regno] = (regno << 16) | (regno << 8) | regno;
break;
case 32:
i = (regno << 8) | regno;
pal[regno] = (i << 16) | i;
break;
}
}
if (par->crtc.depth == 16 && regno > 0) {
/*
* With the 5-6-5 split of bits for RGB at 16 bits/pixel, we
* have 32 slots for R and B values but 64 slots for G values.
* Thus the R and B values go in one slot but the G value
* goes in a different slot, and we have to avoid disturbing
* the other fields in the slots we touch.
*/
par->green[regno] = green;
if (regno < 32) {
par->red[regno] = red;
par->blue[regno] = blue;
aty128_st_pal(regno * 8, red, par->green[regno*2],
blue, par);
}
red = par->red[regno/2];
blue = par->blue[regno/2];
regno <<= 2;
} else if (par->crtc.bpp == 16)
regno <<= 3;
aty128_st_pal(regno, red, green, blue, par);
return 0;
}
#define ATY_MIRROR_LCD_ON 0x00000001
#define ATY_MIRROR_CRT_ON 0x00000002
/* out param: u32* backlight value: 0 to 15 */
#define FBIO_ATY128_GET_MIRROR _IOR('@', 1, __u32)
/* in param: u32* backlight value: 0 to 15 */
#define FBIO_ATY128_SET_MIRROR _IOW('@', 2, __u32)
static int aty128fb_ioctl(struct fb_info *info, u_int cmd, u_long arg)
{
struct aty128fb_par *par = info->par;
u32 value;
int rc;
switch (cmd) {
case FBIO_ATY128_SET_MIRROR:
if (par->chip_gen != rage_M3)
return -EINVAL;
rc = get_user(value, (__u32 __user *)arg);
if (rc)
return rc;
par->lcd_on = (value & 0x01) != 0;
par->crt_on = (value & 0x02) != 0;
if (!par->crt_on && !par->lcd_on)
par->lcd_on = 1;
aty128_set_crt_enable(par, par->crt_on);
aty128_set_lcd_enable(par, par->lcd_on);
return 0;
case FBIO_ATY128_GET_MIRROR:
if (par->chip_gen != rage_M3)
return -EINVAL;
value = (par->crt_on << 1) | par->lcd_on;
return put_user(value, (__u32 __user *)arg);
}
return -EINVAL;
}
#if 0
/*
* Accelerated functions
*/
static inline void aty128_rectcopy(int srcx, int srcy, int dstx, int dsty,
u_int width, u_int height,
struct fb_info_aty128 *par)
{
u32 save_dp_datatype, save_dp_cntl, dstval;
if (!width || !height)
return;
dstval = depth_to_dst(par->current_par.crtc.depth);
if (dstval == DST_24BPP) {
srcx *= 3;
dstx *= 3;
width *= 3;
} else if (dstval == -EINVAL) {
printk("aty128fb: invalid depth or RGBA\n");
return;
}
wait_for_fifo(2, par);
save_dp_datatype = aty_ld_le32(DP_DATATYPE);
save_dp_cntl = aty_ld_le32(DP_CNTL);
wait_for_fifo(6, par);
aty_st_le32(SRC_Y_X, (srcy << 16) | srcx);
aty_st_le32(DP_MIX, ROP3_SRCCOPY | DP_SRC_RECT);
aty_st_le32(DP_CNTL, DST_X_LEFT_TO_RIGHT | DST_Y_TOP_TO_BOTTOM);
aty_st_le32(DP_DATATYPE, save_dp_datatype | dstval | SRC_DSTCOLOR);
aty_st_le32(DST_Y_X, (dsty << 16) | dstx);
aty_st_le32(DST_HEIGHT_WIDTH, (height << 16) | width);
par->blitter_may_be_busy = 1;
wait_for_fifo(2, par);
aty_st_le32(DP_DATATYPE, save_dp_datatype);
aty_st_le32(DP_CNTL, save_dp_cntl);
}
/*
* Text mode accelerated functions
*/
static void fbcon_aty128_bmove(struct display *p, int sy, int sx, int dy, int dx,
int height, int width)
{
sx *= fontwidth(p);
sy *= fontheight(p);
dx *= fontwidth(p);
dy *= fontheight(p);
width *= fontwidth(p);
height *= fontheight(p);
aty128_rectcopy(sx, sy, dx, dy, width, height,
(struct fb_info_aty128 *)p->fb_info);
}
#endif /* 0 */
static void aty128_set_suspend(struct aty128fb_par *par, int suspend)
{
u32 pmgt;
struct pci_dev *pdev = par->pdev;
if (!par->pm_reg)
return;
/* Set the chip into the appropriate suspend mode (we use D2,
* D3 would require a complete re-initialisation of the chip,
* including PCI config registers, clocks, AGP configuration, ...)
*
* For resume, the core will have already brought us back to D0
*/
if (suspend) {
/* Make sure CRTC2 is reset. Remove that the day we decide to
* actually use CRTC2 and replace it with real code for disabling
* the CRTC2 output during sleep
*/
aty_st_le32(CRTC2_GEN_CNTL, aty_ld_le32(CRTC2_GEN_CNTL) &
~(CRTC2_EN));
/* Set the power management mode to be PCI based */
/* Use this magic value for now */
pmgt = 0x0c005407;
aty_st_pll(POWER_MANAGEMENT, pmgt);
(void)aty_ld_pll(POWER_MANAGEMENT);
aty_st_le32(BUS_CNTL1, 0x00000010);
aty_st_le32(MEM_POWER_MISC, 0x0c830000);
mdelay(100);
/* Switch PCI power management to D2 */
pci_set_power_state(pdev, PCI_D2);
}
}
static int aty128_pci_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct aty128fb_par *par = info->par;
/* Because we may change PCI D state ourselves, we need to
* first save the config space content so the core can
* restore it properly on resume.
*/
pci_save_state(pdev);
/* We don't do anything but D2, for now we return 0, but
* we may want to change that. How do we know if the BIOS
* can properly take care of D3 ? Also, with swsusp, we
* know we'll be rebooted, ...
*/
#ifndef CONFIG_PPC_PMAC
/* HACK ALERT ! Once I find a proper way to say to each driver
* individually what will happen with it's PCI slot, I'll change
* that. On laptops, the AGP slot is just unclocked, so D2 is
* expected, while on desktops, the card is powered off
*/
return 0;
#endif /* CONFIG_PPC_PMAC */
if (state.event == pdev->dev.power.power_state.event)
return 0;
printk(KERN_DEBUG "aty128fb: suspending...\n");
acquire_console_sem();
fb_set_suspend(info, 1);
/* Make sure engine is reset */
wait_for_idle(par);
aty128_reset_engine(par);
wait_for_idle(par);
/* Blank display and LCD */
aty128fb_blank(FB_BLANK_POWERDOWN, info);
/* Sleep */
par->asleep = 1;
par->lock_blank = 1;
#ifdef CONFIG_PPC_PMAC
/* On powermac, we have hooks to properly suspend/resume AGP now,
* use them here. We'll ultimately need some generic support here,
* but the generic code isn't quite ready for that yet
*/
pmac_suspend_agp_for_card(pdev);
#endif /* CONFIG_PPC_PMAC */
/* We need a way to make sure the fbdev layer will _not_ touch the
* framebuffer before we put the chip to suspend state. On 2.4, I
* used dummy fb ops, 2.5 need proper support for this at the
* fbdev level
*/
if (state.event != PM_EVENT_ON)
aty128_set_suspend(par, 1);
release_console_sem();
pdev->dev.power.power_state = state;
return 0;
}
static int aty128_do_resume(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct aty128fb_par *par = info->par;
if (pdev->dev.power.power_state.event == PM_EVENT_ON)
return 0;
/* PCI state will have been restored by the core, so
* we should be in D0 now with our config space fully
* restored
*/
/* Wakeup chip */
aty128_set_suspend(par, 0);
par->asleep = 0;
/* Restore display & engine */
aty128_reset_engine(par);
wait_for_idle(par);
aty128fb_set_par(info);
fb_pan_display(info, &info->var);
fb_set_cmap(&info->cmap, info);
/* Refresh */
fb_set_suspend(info, 0);
/* Unblank */
par->lock_blank = 0;
aty128fb_blank(0, info);
#ifdef CONFIG_PPC_PMAC
/* On powermac, we have hooks to properly suspend/resume AGP now,
* use them here. We'll ultimately need some generic support here,
* but the generic code isn't quite ready for that yet
*/
pmac_resume_agp_for_card(pdev);
#endif /* CONFIG_PPC_PMAC */
pdev->dev.power.power_state = PMSG_ON;
printk(KERN_DEBUG "aty128fb: resumed !\n");
return 0;
}
static int aty128_pci_resume(struct pci_dev *pdev)
{
int rc;
acquire_console_sem();
rc = aty128_do_resume(pdev);
release_console_sem();
return rc;
}
static int __devinit aty128fb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("aty128fb", &option))
return -ENODEV;
aty128fb_setup(option);
#endif
return pci_register_driver(&aty128fb_driver);
}
static void __exit aty128fb_exit(void)
{
pci_unregister_driver(&aty128fb_driver);
}
module_init(aty128fb_init);
module_exit(aty128fb_exit);
MODULE_AUTHOR("(c)1999-2003 Brad Douglas <brad@neruo.com>");
MODULE_DESCRIPTION("FBDev driver for ATI Rage128 / Pro cards");
MODULE_LICENSE("GPL");
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Specify resolution as \"<xres>x<yres>[-<bpp>][@<refresh>]\" ");
#ifdef CONFIG_MTRR
module_param_named(nomtrr, mtrr, invbool, 0);
MODULE_PARM_DESC(nomtrr, "bool: Disable MTRR support (0 or 1=disabled) (default=0)");
#endif
| gpl-2.0 |
diegoheusser/linux | arch/sh/kernel/cpu/sh4a/clock-sh7366.c | 1455 | 9378 | /*
* arch/sh/kernel/cpu/sh4a/clock-sh7366.c
*
* SH7366 clock framework support
*
* Copyright (C) 2009 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <asm/clock.h>
/* SH7366 registers */
#define FRQCR 0xa4150000
#define VCLKCR 0xa4150004
#define SCLKACR 0xa4150008
#define SCLKBCR 0xa415000c
#define PLLCR 0xa4150024
#define MSTPCR0 0xa4150030
#define MSTPCR1 0xa4150034
#define MSTPCR2 0xa4150038
#define DLLFRQ 0xa4150050
/* Fixed 32 KHz root clock for RTC and Power Management purposes */
static struct clk r_clk = {
.rate = 32768,
};
/*
* Default rate for the root input clock, reset this with clk_set_rate()
* from the platform code.
*/
struct clk extal_clk = {
.rate = 33333333,
};
/* The dll block multiplies the 32khz r_clk, may be used instead of extal */
static unsigned long dll_recalc(struct clk *clk)
{
unsigned long mult;
if (__raw_readl(PLLCR) & 0x1000)
mult = __raw_readl(DLLFRQ);
else
mult = 0;
return clk->parent->rate * mult;
}
static struct sh_clk_ops dll_clk_ops = {
.recalc = dll_recalc,
};
static struct clk dll_clk = {
.ops = &dll_clk_ops,
.parent = &r_clk,
.flags = CLK_ENABLE_ON_INIT,
};
static unsigned long pll_recalc(struct clk *clk)
{
unsigned long mult = 1;
unsigned long div = 1;
if (__raw_readl(PLLCR) & 0x4000)
mult = (((__raw_readl(FRQCR) >> 24) & 0x1f) + 1);
else
div = 2;
return (clk->parent->rate * mult) / div;
}
static struct sh_clk_ops pll_clk_ops = {
.recalc = pll_recalc,
};
static struct clk pll_clk = {
.ops = &pll_clk_ops,
.flags = CLK_ENABLE_ON_INIT,
};
struct clk *main_clks[] = {
&r_clk,
&extal_clk,
&dll_clk,
&pll_clk,
};
static int multipliers[] = { 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
static int divisors[] = { 1, 3, 2, 5, 3, 4, 5, 6, 8, 10, 12, 16, 20 };
static struct clk_div_mult_table div4_div_mult_table = {
.divisors = divisors,
.nr_divisors = ARRAY_SIZE(divisors),
.multipliers = multipliers,
.nr_multipliers = ARRAY_SIZE(multipliers),
};
static struct clk_div4_table div4_table = {
.div_mult_table = &div4_div_mult_table,
};
enum { DIV4_I, DIV4_U, DIV4_SH, DIV4_B, DIV4_B3, DIV4_P,
DIV4_SIUA, DIV4_SIUB, DIV4_NR };
#define DIV4(_reg, _bit, _mask, _flags) \
SH_CLK_DIV4(&pll_clk, _reg, _bit, _mask, _flags)
struct clk div4_clks[DIV4_NR] = {
[DIV4_I] = DIV4(FRQCR, 20, 0x1fef, CLK_ENABLE_ON_INIT),
[DIV4_U] = DIV4(FRQCR, 16, 0x1fff, CLK_ENABLE_ON_INIT),
[DIV4_SH] = DIV4(FRQCR, 12, 0x1fff, CLK_ENABLE_ON_INIT),
[DIV4_B] = DIV4(FRQCR, 8, 0x1fff, CLK_ENABLE_ON_INIT),
[DIV4_B3] = DIV4(FRQCR, 4, 0x1fff, CLK_ENABLE_ON_INIT),
[DIV4_P] = DIV4(FRQCR, 0, 0x1fff, 0),
[DIV4_SIUA] = DIV4(SCLKACR, 0, 0x1fff, 0),
[DIV4_SIUB] = DIV4(SCLKBCR, 0, 0x1fff, 0),
};
enum { DIV6_V, DIV6_NR };
struct clk div6_clks[DIV6_NR] = {
[DIV6_V] = SH_CLK_DIV6(&pll_clk, VCLKCR, 0),
};
#define MSTP(_parent, _reg, _bit, _flags) \
SH_CLK_MSTP32(_parent, _reg, _bit, _flags)
enum { MSTP031, MSTP030, MSTP029, MSTP028, MSTP026,
MSTP023, MSTP022, MSTP021, MSTP020, MSTP019, MSTP018, MSTP017, MSTP016,
MSTP015, MSTP014, MSTP013, MSTP012, MSTP011, MSTP010,
MSTP007, MSTP006, MSTP005, MSTP002, MSTP001,
MSTP109, MSTP100,
MSTP227, MSTP226, MSTP224, MSTP223, MSTP222, MSTP218, MSTP217,
MSTP211, MSTP207, MSTP205, MSTP204, MSTP203, MSTP202, MSTP201, MSTP200,
MSTP_NR };
static struct clk mstp_clks[MSTP_NR] = {
/* See page 52 of Datasheet V0.40: Overview -> Block Diagram */
[MSTP031] = MSTP(&div4_clks[DIV4_I], MSTPCR0, 31, CLK_ENABLE_ON_INIT),
[MSTP030] = MSTP(&div4_clks[DIV4_I], MSTPCR0, 30, CLK_ENABLE_ON_INIT),
[MSTP029] = MSTP(&div4_clks[DIV4_I], MSTPCR0, 29, CLK_ENABLE_ON_INIT),
[MSTP028] = MSTP(&div4_clks[DIV4_SH], MSTPCR0, 28, CLK_ENABLE_ON_INIT),
[MSTP026] = MSTP(&div4_clks[DIV4_B], MSTPCR0, 26, CLK_ENABLE_ON_INIT),
[MSTP023] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 23, 0),
[MSTP022] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 22, 0),
[MSTP021] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 21, 0),
[MSTP020] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 20, 0),
[MSTP019] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 19, 0),
[MSTP017] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 17, 0),
[MSTP015] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 15, 0),
[MSTP014] = MSTP(&r_clk, MSTPCR0, 14, 0),
[MSTP013] = MSTP(&r_clk, MSTPCR0, 13, 0),
[MSTP011] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 11, 0),
[MSTP010] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 10, 0),
[MSTP007] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 7, 0),
[MSTP006] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 6, 0),
[MSTP005] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 5, 0),
[MSTP002] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 2, 0),
[MSTP001] = MSTP(&div4_clks[DIV4_P], MSTPCR0, 1, 0),
[MSTP109] = MSTP(&div4_clks[DIV4_P], MSTPCR1, 9, 0),
[MSTP227] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 27, 0),
[MSTP226] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 26, 0),
[MSTP224] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 24, 0),
[MSTP223] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 23, 0),
[MSTP222] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 22, 0),
[MSTP218] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 18, 0),
[MSTP217] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 17, 0),
[MSTP211] = MSTP(&div4_clks[DIV4_P], MSTPCR2, 11, 0),
[MSTP207] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 7, CLK_ENABLE_ON_INIT),
[MSTP205] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 5, 0),
[MSTP204] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 4, 0),
[MSTP203] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 3, 0),
[MSTP202] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 2, CLK_ENABLE_ON_INIT),
[MSTP201] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 1, CLK_ENABLE_ON_INIT),
[MSTP200] = MSTP(&div4_clks[DIV4_B], MSTPCR2, 0, 0),
};
static struct clk_lookup lookups[] = {
/* main clocks */
CLKDEV_CON_ID("rclk", &r_clk),
CLKDEV_CON_ID("extal", &extal_clk),
CLKDEV_CON_ID("dll_clk", &dll_clk),
CLKDEV_CON_ID("pll_clk", &pll_clk),
/* DIV4 clocks */
CLKDEV_CON_ID("cpu_clk", &div4_clks[DIV4_I]),
CLKDEV_CON_ID("umem_clk", &div4_clks[DIV4_U]),
CLKDEV_CON_ID("shyway_clk", &div4_clks[DIV4_SH]),
CLKDEV_CON_ID("bus_clk", &div4_clks[DIV4_B]),
CLKDEV_CON_ID("b3_clk", &div4_clks[DIV4_B3]),
CLKDEV_CON_ID("peripheral_clk", &div4_clks[DIV4_P]),
CLKDEV_CON_ID("siua_clk", &div4_clks[DIV4_SIUA]),
CLKDEV_CON_ID("siub_clk", &div4_clks[DIV4_SIUB]),
/* DIV6 clocks */
CLKDEV_CON_ID("video_clk", &div6_clks[DIV6_V]),
/* MSTP32 clocks */
CLKDEV_CON_ID("tlb0", &mstp_clks[MSTP031]),
CLKDEV_CON_ID("ic0", &mstp_clks[MSTP030]),
CLKDEV_CON_ID("oc0", &mstp_clks[MSTP029]),
CLKDEV_CON_ID("rsmem0", &mstp_clks[MSTP028]),
CLKDEV_CON_ID("xymem0", &mstp_clks[MSTP026]),
CLKDEV_CON_ID("intc3", &mstp_clks[MSTP023]),
CLKDEV_CON_ID("intc0", &mstp_clks[MSTP022]),
CLKDEV_CON_ID("dmac0", &mstp_clks[MSTP021]),
CLKDEV_CON_ID("sh0", &mstp_clks[MSTP020]),
CLKDEV_CON_ID("hudi0", &mstp_clks[MSTP019]),
CLKDEV_CON_ID("ubc0", &mstp_clks[MSTP017]),
CLKDEV_CON_ID("tmu_fck", &mstp_clks[MSTP015]),
CLKDEV_ICK_ID("fck", "sh-cmt-32.0", &mstp_clks[MSTP014]),
CLKDEV_CON_ID("rwdt0", &mstp_clks[MSTP013]),
CLKDEV_CON_ID("mfi0", &mstp_clks[MSTP011]),
CLKDEV_CON_ID("flctl0", &mstp_clks[MSTP010]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.0", &mstp_clks[MSTP007]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.1", &mstp_clks[MSTP006]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.2", &mstp_clks[MSTP005]),
CLKDEV_CON_ID("msiof0", &mstp_clks[MSTP002]),
CLKDEV_CON_ID("sbr0", &mstp_clks[MSTP001]),
CLKDEV_DEV_ID("i2c-sh_mobile.0", &mstp_clks[MSTP109]),
CLKDEV_CON_ID("icb0", &mstp_clks[MSTP227]),
CLKDEV_CON_ID("meram0", &mstp_clks[MSTP226]),
CLKDEV_CON_ID("dacy1", &mstp_clks[MSTP224]),
CLKDEV_CON_ID("dacy0", &mstp_clks[MSTP223]),
CLKDEV_CON_ID("tsif0", &mstp_clks[MSTP222]),
CLKDEV_CON_ID("sdhi0", &mstp_clks[MSTP218]),
CLKDEV_CON_ID("mmcif0", &mstp_clks[MSTP217]),
CLKDEV_CON_ID("usbf0", &mstp_clks[MSTP211]),
CLKDEV_CON_ID("veu1", &mstp_clks[MSTP207]),
CLKDEV_CON_ID("vou0", &mstp_clks[MSTP205]),
CLKDEV_CON_ID("beu0", &mstp_clks[MSTP204]),
CLKDEV_CON_ID("ceu0", &mstp_clks[MSTP203]),
CLKDEV_CON_ID("veu0", &mstp_clks[MSTP202]),
CLKDEV_CON_ID("vpu0", &mstp_clks[MSTP201]),
CLKDEV_CON_ID("lcdc0", &mstp_clks[MSTP200]),
};
int __init arch_clk_init(void)
{
int k, ret = 0;
/* autodetect extal or dll configuration */
if (__raw_readl(PLLCR) & 0x1000)
pll_clk.parent = &dll_clk;
else
pll_clk.parent = &extal_clk;
for (k = 0; !ret && (k < ARRAY_SIZE(main_clks)); k++)
ret = clk_register(main_clks[k]);
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
if (!ret)
ret = sh_clk_div4_register(div4_clks, DIV4_NR, &div4_table);
if (!ret)
ret = sh_clk_div6_register(div6_clks, DIV6_NR);
if (!ret)
ret = sh_clk_mstp_register(mstp_clks, MSTP_NR);
return ret;
}
| gpl-2.0 |
Kurre/kernel_exynos_KK | drivers/platform/x86/asus-wmi.c | 1967 | 46658 | /*
* Asus PC WMI hotkey driver
*
* Copyright(C) 2010 Intel Corporation.
* Copyright(C) 2010-2011 Corentin Chary <corentin.chary@gmail.com>
*
* Portions based on wistron_btns.c:
* Copyright (C) 2005 Miloslav Trmac <mitr@volny.cz>
* Copyright (C) 2005 Bernhard Rosenkraenzer <bero@arklinux.org>
* Copyright (C) 2005 Dmitry Torokhov <dtor@mail.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/leds.h>
#include <linux/rfkill.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/platform_device.h>
#include <linux/thermal.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include "asus-wmi.h"
MODULE_AUTHOR("Corentin Chary <corentincj@iksaif.net>, "
"Yong Wang <yong.y.wang@intel.com>");
MODULE_DESCRIPTION("Asus Generic WMI Driver");
MODULE_LICENSE("GPL");
#define to_platform_driver(drv) \
(container_of((drv), struct platform_driver, driver))
#define to_asus_wmi_driver(pdrv) \
(container_of((pdrv), struct asus_wmi_driver, platform_driver))
#define ASUS_WMI_MGMT_GUID "97845ED0-4E6D-11DE-8A39-0800200C9A66"
#define NOTIFY_BRNUP_MIN 0x11
#define NOTIFY_BRNUP_MAX 0x1f
#define NOTIFY_BRNDOWN_MIN 0x20
#define NOTIFY_BRNDOWN_MAX 0x2e
#define NOTIFY_KBD_BRTUP 0xc4
#define NOTIFY_KBD_BRTDWN 0xc5
/* WMI Methods */
#define ASUS_WMI_METHODID_SPEC 0x43455053 /* BIOS SPECification */
#define ASUS_WMI_METHODID_SFBD 0x44424653 /* Set First Boot Device */
#define ASUS_WMI_METHODID_GLCD 0x44434C47 /* Get LCD status */
#define ASUS_WMI_METHODID_GPID 0x44495047 /* Get Panel ID?? (Resol) */
#define ASUS_WMI_METHODID_QMOD 0x444F4D51 /* Quiet MODe */
#define ASUS_WMI_METHODID_SPLV 0x4C425053 /* Set Panel Light Value */
#define ASUS_WMI_METHODID_SFUN 0x4E554653 /* FUNCtionalities */
#define ASUS_WMI_METHODID_SDSP 0x50534453 /* Set DiSPlay output */
#define ASUS_WMI_METHODID_GDSP 0x50534447 /* Get DiSPlay output */
#define ASUS_WMI_METHODID_DEVP 0x50564544 /* DEVice Policy */
#define ASUS_WMI_METHODID_OSVR 0x5256534F /* OS VeRsion */
#define ASUS_WMI_METHODID_DSTS 0x53544344 /* Device STatuS */
#define ASUS_WMI_METHODID_DSTS2 0x53545344 /* Device STatuS #2*/
#define ASUS_WMI_METHODID_BSTS 0x53545342 /* Bios STatuS ? */
#define ASUS_WMI_METHODID_DEVS 0x53564544 /* DEVice Set */
#define ASUS_WMI_METHODID_CFVS 0x53564643 /* CPU Frequency Volt Set */
#define ASUS_WMI_METHODID_KBFT 0x5446424B /* KeyBoard FilTer */
#define ASUS_WMI_METHODID_INIT 0x54494E49 /* INITialize */
#define ASUS_WMI_METHODID_HKEY 0x59454B48 /* Hot KEY ?? */
#define ASUS_WMI_UNSUPPORTED_METHOD 0xFFFFFFFE
/* Wireless */
#define ASUS_WMI_DEVID_HW_SWITCH 0x00010001
#define ASUS_WMI_DEVID_WIRELESS_LED 0x00010002
#define ASUS_WMI_DEVID_CWAP 0x00010003
#define ASUS_WMI_DEVID_WLAN 0x00010011
#define ASUS_WMI_DEVID_BLUETOOTH 0x00010013
#define ASUS_WMI_DEVID_GPS 0x00010015
#define ASUS_WMI_DEVID_WIMAX 0x00010017
#define ASUS_WMI_DEVID_WWAN3G 0x00010019
#define ASUS_WMI_DEVID_UWB 0x00010021
/* Leds */
/* 0x000200XX and 0x000400XX */
#define ASUS_WMI_DEVID_LED1 0x00020011
#define ASUS_WMI_DEVID_LED2 0x00020012
#define ASUS_WMI_DEVID_LED3 0x00020013
#define ASUS_WMI_DEVID_LED4 0x00020014
#define ASUS_WMI_DEVID_LED5 0x00020015
#define ASUS_WMI_DEVID_LED6 0x00020016
/* Backlight and Brightness */
#define ASUS_WMI_DEVID_BACKLIGHT 0x00050011
#define ASUS_WMI_DEVID_BRIGHTNESS 0x00050012
#define ASUS_WMI_DEVID_KBD_BACKLIGHT 0x00050021
#define ASUS_WMI_DEVID_LIGHT_SENSOR 0x00050022 /* ?? */
/* Misc */
#define ASUS_WMI_DEVID_CAMERA 0x00060013
/* Storage */
#define ASUS_WMI_DEVID_CARDREADER 0x00080013
/* Input */
#define ASUS_WMI_DEVID_TOUCHPAD 0x00100011
#define ASUS_WMI_DEVID_TOUCHPAD_LED 0x00100012
/* Fan, Thermal */
#define ASUS_WMI_DEVID_THERMAL_CTRL 0x00110011
#define ASUS_WMI_DEVID_FAN_CTRL 0x00110012
/* Power */
#define ASUS_WMI_DEVID_PROCESSOR_STATE 0x00120012
/* DSTS masks */
#define ASUS_WMI_DSTS_STATUS_BIT 0x00000001
#define ASUS_WMI_DSTS_UNKNOWN_BIT 0x00000002
#define ASUS_WMI_DSTS_PRESENCE_BIT 0x00010000
#define ASUS_WMI_DSTS_USER_BIT 0x00020000
#define ASUS_WMI_DSTS_BIOS_BIT 0x00040000
#define ASUS_WMI_DSTS_BRIGHTNESS_MASK 0x000000FF
#define ASUS_WMI_DSTS_MAX_BRIGTH_MASK 0x0000FF00
struct bios_args {
u32 arg0;
u32 arg1;
} __packed;
/*
* <platform>/ - debugfs root directory
* dev_id - current dev_id
* ctrl_param - current ctrl_param
* method_id - current method_id
* devs - call DEVS(dev_id, ctrl_param) and print result
* dsts - call DSTS(dev_id) and print result
* call - call method_id(dev_id, ctrl_param) and print result
*/
struct asus_wmi_debug {
struct dentry *root;
u32 method_id;
u32 dev_id;
u32 ctrl_param;
};
struct asus_rfkill {
struct asus_wmi *asus;
struct rfkill *rfkill;
u32 dev_id;
};
struct asus_wmi {
int dsts_id;
int spec;
int sfun;
struct input_dev *inputdev;
struct backlight_device *backlight_device;
struct device *hwmon_device;
struct platform_device *platform_device;
struct led_classdev tpd_led;
int tpd_led_wk;
struct led_classdev kbd_led;
int kbd_led_wk;
struct workqueue_struct *led_workqueue;
struct work_struct tpd_led_work;
struct work_struct kbd_led_work;
struct asus_rfkill wlan;
struct asus_rfkill bluetooth;
struct asus_rfkill wimax;
struct asus_rfkill wwan3g;
struct asus_rfkill gps;
struct asus_rfkill uwb;
struct hotplug_slot *hotplug_slot;
struct mutex hotplug_lock;
struct mutex wmi_lock;
struct workqueue_struct *hotplug_workqueue;
struct work_struct hotplug_work;
struct asus_wmi_debug debug;
struct asus_wmi_driver *driver;
};
static int asus_wmi_input_init(struct asus_wmi *asus)
{
int err;
asus->inputdev = input_allocate_device();
if (!asus->inputdev)
return -ENOMEM;
asus->inputdev->name = asus->driver->input_name;
asus->inputdev->phys = asus->driver->input_phys;
asus->inputdev->id.bustype = BUS_HOST;
asus->inputdev->dev.parent = &asus->platform_device->dev;
set_bit(EV_REP, asus->inputdev->evbit);
err = sparse_keymap_setup(asus->inputdev, asus->driver->keymap, NULL);
if (err)
goto err_free_dev;
err = input_register_device(asus->inputdev);
if (err)
goto err_free_keymap;
return 0;
err_free_keymap:
sparse_keymap_free(asus->inputdev);
err_free_dev:
input_free_device(asus->inputdev);
return err;
}
static void asus_wmi_input_exit(struct asus_wmi *asus)
{
if (asus->inputdev) {
sparse_keymap_free(asus->inputdev);
input_unregister_device(asus->inputdev);
}
asus->inputdev = NULL;
}
static int asus_wmi_evaluate_method(u32 method_id, u32 arg0, u32 arg1,
u32 *retval)
{
struct bios_args args = {
.arg0 = arg0,
.arg1 = arg1,
};
struct acpi_buffer input = { (acpi_size) sizeof(args), &args };
struct acpi_buffer output = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_status status;
union acpi_object *obj;
u32 tmp;
status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID, 1, method_id,
&input, &output);
if (ACPI_FAILURE(status))
goto exit;
obj = (union acpi_object *)output.pointer;
if (obj && obj->type == ACPI_TYPE_INTEGER)
tmp = (u32) obj->integer.value;
else
tmp = 0;
if (retval)
*retval = tmp;
kfree(obj);
exit:
if (ACPI_FAILURE(status))
return -EIO;
if (tmp == ASUS_WMI_UNSUPPORTED_METHOD)
return -ENODEV;
return 0;
}
static int asus_wmi_get_devstate(struct asus_wmi *asus, u32 dev_id, u32 *retval)
{
return asus_wmi_evaluate_method(asus->dsts_id, dev_id, 0, retval);
}
static int asus_wmi_set_devstate(u32 dev_id, u32 ctrl_param,
u32 *retval)
{
return asus_wmi_evaluate_method(ASUS_WMI_METHODID_DEVS, dev_id,
ctrl_param, retval);
}
/* Helper for special devices with magic return codes */
static int asus_wmi_get_devstate_bits(struct asus_wmi *asus,
u32 dev_id, u32 mask)
{
u32 retval = 0;
int err;
err = asus_wmi_get_devstate(asus, dev_id, &retval);
if (err < 0)
return err;
if (!(retval & ASUS_WMI_DSTS_PRESENCE_BIT))
return -ENODEV;
if (mask == ASUS_WMI_DSTS_STATUS_BIT) {
if (retval & ASUS_WMI_DSTS_UNKNOWN_BIT)
return -ENODEV;
}
return retval & mask;
}
static int asus_wmi_get_devstate_simple(struct asus_wmi *asus, u32 dev_id)
{
return asus_wmi_get_devstate_bits(asus, dev_id,
ASUS_WMI_DSTS_STATUS_BIT);
}
/*
* LEDs
*/
/*
* These functions actually update the LED's, and are called from a
* workqueue. By doing this as separate work rather than when the LED
* subsystem asks, we avoid messing with the Asus ACPI stuff during a
* potentially bad time, such as a timer interrupt.
*/
static void tpd_led_update(struct work_struct *work)
{
int ctrl_param;
struct asus_wmi *asus;
asus = container_of(work, struct asus_wmi, tpd_led_work);
ctrl_param = asus->tpd_led_wk;
asus_wmi_set_devstate(ASUS_WMI_DEVID_TOUCHPAD_LED, ctrl_param, NULL);
}
static void tpd_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct asus_wmi *asus;
asus = container_of(led_cdev, struct asus_wmi, tpd_led);
asus->tpd_led_wk = !!value;
queue_work(asus->led_workqueue, &asus->tpd_led_work);
}
static int read_tpd_led_state(struct asus_wmi *asus)
{
return asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_TOUCHPAD_LED);
}
static enum led_brightness tpd_led_get(struct led_classdev *led_cdev)
{
struct asus_wmi *asus;
asus = container_of(led_cdev, struct asus_wmi, tpd_led);
return read_tpd_led_state(asus);
}
static void kbd_led_update(struct work_struct *work)
{
int ctrl_param = 0;
struct asus_wmi *asus;
asus = container_of(work, struct asus_wmi, kbd_led_work);
/*
* bits 0-2: level
* bit 7: light on/off
*/
if (asus->kbd_led_wk > 0)
ctrl_param = 0x80 | (asus->kbd_led_wk & 0x7F);
asus_wmi_set_devstate(ASUS_WMI_DEVID_KBD_BACKLIGHT, ctrl_param, NULL);
}
static int kbd_led_read(struct asus_wmi *asus, int *level, int *env)
{
int retval;
/*
* bits 0-2: level
* bit 7: light on/off
* bit 8-10: environment (0: dark, 1: normal, 2: light)
* bit 17: status unknown
*/
retval = asus_wmi_get_devstate_bits(asus, ASUS_WMI_DEVID_KBD_BACKLIGHT,
0xFFFF);
/* Unknown status is considered as off */
if (retval == 0x8000)
retval = 0;
if (retval >= 0) {
if (level)
*level = retval & 0x7F;
if (env)
*env = (retval >> 8) & 0x7F;
retval = 0;
}
return retval;
}
static void kbd_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct asus_wmi *asus;
asus = container_of(led_cdev, struct asus_wmi, kbd_led);
if (value > asus->kbd_led.max_brightness)
value = asus->kbd_led.max_brightness;
else if (value < 0)
value = 0;
asus->kbd_led_wk = value;
queue_work(asus->led_workqueue, &asus->kbd_led_work);
}
static enum led_brightness kbd_led_get(struct led_classdev *led_cdev)
{
struct asus_wmi *asus;
int retval, value;
asus = container_of(led_cdev, struct asus_wmi, kbd_led);
retval = kbd_led_read(asus, &value, NULL);
if (retval < 0)
return retval;
return value;
}
static void asus_wmi_led_exit(struct asus_wmi *asus)
{
if (!IS_ERR_OR_NULL(asus->kbd_led.dev))
led_classdev_unregister(&asus->kbd_led);
if (!IS_ERR_OR_NULL(asus->tpd_led.dev))
led_classdev_unregister(&asus->tpd_led);
if (asus->led_workqueue)
destroy_workqueue(asus->led_workqueue);
}
static int asus_wmi_led_init(struct asus_wmi *asus)
{
int rv = 0;
asus->led_workqueue = create_singlethread_workqueue("led_workqueue");
if (!asus->led_workqueue)
return -ENOMEM;
if (read_tpd_led_state(asus) >= 0) {
INIT_WORK(&asus->tpd_led_work, tpd_led_update);
asus->tpd_led.name = "asus::touchpad";
asus->tpd_led.brightness_set = tpd_led_set;
asus->tpd_led.brightness_get = tpd_led_get;
asus->tpd_led.max_brightness = 1;
rv = led_classdev_register(&asus->platform_device->dev,
&asus->tpd_led);
if (rv)
goto error;
}
if (kbd_led_read(asus, NULL, NULL) >= 0) {
INIT_WORK(&asus->kbd_led_work, kbd_led_update);
asus->kbd_led.name = "asus::kbd_backlight";
asus->kbd_led.brightness_set = kbd_led_set;
asus->kbd_led.brightness_get = kbd_led_get;
asus->kbd_led.max_brightness = 3;
rv = led_classdev_register(&asus->platform_device->dev,
&asus->kbd_led);
}
error:
if (rv)
asus_wmi_led_exit(asus);
return rv;
}
/*
* PCI hotplug (for wlan rfkill)
*/
static bool asus_wlan_rfkill_blocked(struct asus_wmi *asus)
{
int result = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_WLAN);
if (result < 0)
return false;
return !result;
}
static void asus_rfkill_hotplug(struct asus_wmi *asus)
{
struct pci_dev *dev;
struct pci_bus *bus;
bool blocked;
bool absent;
u32 l;
mutex_lock(&asus->wmi_lock);
blocked = asus_wlan_rfkill_blocked(asus);
mutex_unlock(&asus->wmi_lock);
mutex_lock(&asus->hotplug_lock);
if (asus->wlan.rfkill)
rfkill_set_sw_state(asus->wlan.rfkill, blocked);
if (asus->hotplug_slot) {
bus = pci_find_bus(0, 1);
if (!bus) {
pr_warn("Unable to find PCI bus 1?\n");
goto out_unlock;
}
if (pci_bus_read_config_dword(bus, 0, PCI_VENDOR_ID, &l)) {
pr_err("Unable to read PCI config space?\n");
goto out_unlock;
}
absent = (l == 0xffffffff);
if (blocked != absent) {
pr_warn("BIOS says wireless lan is %s, "
"but the pci device is %s\n",
blocked ? "blocked" : "unblocked",
absent ? "absent" : "present");
pr_warn("skipped wireless hotplug as probably "
"inappropriate for this model\n");
goto out_unlock;
}
if (!blocked) {
dev = pci_get_slot(bus, 0);
if (dev) {
/* Device already present */
pci_dev_put(dev);
goto out_unlock;
}
dev = pci_scan_single_device(bus, 0);
if (dev) {
pci_bus_assign_resources(bus);
if (pci_bus_add_device(dev))
pr_err("Unable to hotplug wifi\n");
}
} else {
dev = pci_get_slot(bus, 0);
if (dev) {
pci_stop_and_remove_bus_device(dev);
pci_dev_put(dev);
}
}
}
out_unlock:
mutex_unlock(&asus->hotplug_lock);
}
static void asus_rfkill_notify(acpi_handle handle, u32 event, void *data)
{
struct asus_wmi *asus = data;
if (event != ACPI_NOTIFY_BUS_CHECK)
return;
/*
* We can't call directly asus_rfkill_hotplug because most
* of the time WMBC is still being executed and not reetrant.
* There is currently no way to tell ACPICA that we want this
* method to be serialized, we schedule a asus_rfkill_hotplug
* call later, in a safer context.
*/
queue_work(asus->hotplug_workqueue, &asus->hotplug_work);
}
static int asus_register_rfkill_notifier(struct asus_wmi *asus, char *node)
{
acpi_status status;
acpi_handle handle;
status = acpi_get_handle(NULL, node, &handle);
if (ACPI_SUCCESS(status)) {
status = acpi_install_notify_handler(handle,
ACPI_SYSTEM_NOTIFY,
asus_rfkill_notify, asus);
if (ACPI_FAILURE(status))
pr_warn("Failed to register notify on %s\n", node);
} else
return -ENODEV;
return 0;
}
static void asus_unregister_rfkill_notifier(struct asus_wmi *asus, char *node)
{
acpi_status status = AE_OK;
acpi_handle handle;
status = acpi_get_handle(NULL, node, &handle);
if (ACPI_SUCCESS(status)) {
status = acpi_remove_notify_handler(handle,
ACPI_SYSTEM_NOTIFY,
asus_rfkill_notify);
if (ACPI_FAILURE(status))
pr_err("Error removing rfkill notify handler %s\n",
node);
}
}
static int asus_get_adapter_status(struct hotplug_slot *hotplug_slot,
u8 *value)
{
struct asus_wmi *asus = hotplug_slot->private;
int result = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_WLAN);
if (result < 0)
return result;
*value = !!result;
return 0;
}
static void asus_cleanup_pci_hotplug(struct hotplug_slot *hotplug_slot)
{
kfree(hotplug_slot->info);
kfree(hotplug_slot);
}
static struct hotplug_slot_ops asus_hotplug_slot_ops = {
.owner = THIS_MODULE,
.get_adapter_status = asus_get_adapter_status,
.get_power_status = asus_get_adapter_status,
};
static void asus_hotplug_work(struct work_struct *work)
{
struct asus_wmi *asus;
asus = container_of(work, struct asus_wmi, hotplug_work);
asus_rfkill_hotplug(asus);
}
static int asus_setup_pci_hotplug(struct asus_wmi *asus)
{
int ret = -ENOMEM;
struct pci_bus *bus = pci_find_bus(0, 1);
if (!bus) {
pr_err("Unable to find wifi PCI bus\n");
return -ENODEV;
}
asus->hotplug_workqueue =
create_singlethread_workqueue("hotplug_workqueue");
if (!asus->hotplug_workqueue)
goto error_workqueue;
INIT_WORK(&asus->hotplug_work, asus_hotplug_work);
asus->hotplug_slot = kzalloc(sizeof(struct hotplug_slot), GFP_KERNEL);
if (!asus->hotplug_slot)
goto error_slot;
asus->hotplug_slot->info = kzalloc(sizeof(struct hotplug_slot_info),
GFP_KERNEL);
if (!asus->hotplug_slot->info)
goto error_info;
asus->hotplug_slot->private = asus;
asus->hotplug_slot->release = &asus_cleanup_pci_hotplug;
asus->hotplug_slot->ops = &asus_hotplug_slot_ops;
asus_get_adapter_status(asus->hotplug_slot,
&asus->hotplug_slot->info->adapter_status);
ret = pci_hp_register(asus->hotplug_slot, bus, 0, "asus-wifi");
if (ret) {
pr_err("Unable to register hotplug slot - %d\n", ret);
goto error_register;
}
return 0;
error_register:
kfree(asus->hotplug_slot->info);
error_info:
kfree(asus->hotplug_slot);
asus->hotplug_slot = NULL;
error_slot:
destroy_workqueue(asus->hotplug_workqueue);
error_workqueue:
return ret;
}
/*
* Rfkill devices
*/
static int asus_rfkill_set(void *data, bool blocked)
{
struct asus_rfkill *priv = data;
u32 ctrl_param = !blocked;
return asus_wmi_set_devstate(priv->dev_id, ctrl_param, NULL);
}
static void asus_rfkill_query(struct rfkill *rfkill, void *data)
{
struct asus_rfkill *priv = data;
int result;
result = asus_wmi_get_devstate_simple(priv->asus, priv->dev_id);
if (result < 0)
return;
rfkill_set_sw_state(priv->rfkill, !result);
}
static int asus_rfkill_wlan_set(void *data, bool blocked)
{
struct asus_rfkill *priv = data;
struct asus_wmi *asus = priv->asus;
int ret;
/*
* This handler is enabled only if hotplug is enabled.
* In this case, the asus_wmi_set_devstate() will
* trigger a wmi notification and we need to wait
* this call to finish before being able to call
* any wmi method
*/
mutex_lock(&asus->wmi_lock);
ret = asus_rfkill_set(data, blocked);
mutex_unlock(&asus->wmi_lock);
return ret;
}
static const struct rfkill_ops asus_rfkill_wlan_ops = {
.set_block = asus_rfkill_wlan_set,
.query = asus_rfkill_query,
};
static const struct rfkill_ops asus_rfkill_ops = {
.set_block = asus_rfkill_set,
.query = asus_rfkill_query,
};
static int asus_new_rfkill(struct asus_wmi *asus,
struct asus_rfkill *arfkill,
const char *name, enum rfkill_type type, int dev_id)
{
int result = asus_wmi_get_devstate_simple(asus, dev_id);
struct rfkill **rfkill = &arfkill->rfkill;
if (result < 0)
return result;
arfkill->dev_id = dev_id;
arfkill->asus = asus;
if (dev_id == ASUS_WMI_DEVID_WLAN &&
asus->driver->quirks->hotplug_wireless)
*rfkill = rfkill_alloc(name, &asus->platform_device->dev, type,
&asus_rfkill_wlan_ops, arfkill);
else
*rfkill = rfkill_alloc(name, &asus->platform_device->dev, type,
&asus_rfkill_ops, arfkill);
if (!*rfkill)
return -EINVAL;
rfkill_init_sw_state(*rfkill, !result);
result = rfkill_register(*rfkill);
if (result) {
rfkill_destroy(*rfkill);
*rfkill = NULL;
return result;
}
return 0;
}
static void asus_wmi_rfkill_exit(struct asus_wmi *asus)
{
asus_unregister_rfkill_notifier(asus, "\\_SB.PCI0.P0P5");
asus_unregister_rfkill_notifier(asus, "\\_SB.PCI0.P0P6");
asus_unregister_rfkill_notifier(asus, "\\_SB.PCI0.P0P7");
if (asus->wlan.rfkill) {
rfkill_unregister(asus->wlan.rfkill);
rfkill_destroy(asus->wlan.rfkill);
asus->wlan.rfkill = NULL;
}
/*
* Refresh pci hotplug in case the rfkill state was changed after
* asus_unregister_rfkill_notifier()
*/
asus_rfkill_hotplug(asus);
if (asus->hotplug_slot)
pci_hp_deregister(asus->hotplug_slot);
if (asus->hotplug_workqueue)
destroy_workqueue(asus->hotplug_workqueue);
if (asus->bluetooth.rfkill) {
rfkill_unregister(asus->bluetooth.rfkill);
rfkill_destroy(asus->bluetooth.rfkill);
asus->bluetooth.rfkill = NULL;
}
if (asus->wimax.rfkill) {
rfkill_unregister(asus->wimax.rfkill);
rfkill_destroy(asus->wimax.rfkill);
asus->wimax.rfkill = NULL;
}
if (asus->wwan3g.rfkill) {
rfkill_unregister(asus->wwan3g.rfkill);
rfkill_destroy(asus->wwan3g.rfkill);
asus->wwan3g.rfkill = NULL;
}
if (asus->gps.rfkill) {
rfkill_unregister(asus->gps.rfkill);
rfkill_destroy(asus->gps.rfkill);
asus->gps.rfkill = NULL;
}
if (asus->uwb.rfkill) {
rfkill_unregister(asus->uwb.rfkill);
rfkill_destroy(asus->uwb.rfkill);
asus->uwb.rfkill = NULL;
}
}
static int asus_wmi_rfkill_init(struct asus_wmi *asus)
{
int result = 0;
mutex_init(&asus->hotplug_lock);
mutex_init(&asus->wmi_lock);
result = asus_new_rfkill(asus, &asus->wlan, "asus-wlan",
RFKILL_TYPE_WLAN, ASUS_WMI_DEVID_WLAN);
if (result && result != -ENODEV)
goto exit;
result = asus_new_rfkill(asus, &asus->bluetooth,
"asus-bluetooth", RFKILL_TYPE_BLUETOOTH,
ASUS_WMI_DEVID_BLUETOOTH);
if (result && result != -ENODEV)
goto exit;
result = asus_new_rfkill(asus, &asus->wimax, "asus-wimax",
RFKILL_TYPE_WIMAX, ASUS_WMI_DEVID_WIMAX);
if (result && result != -ENODEV)
goto exit;
result = asus_new_rfkill(asus, &asus->wwan3g, "asus-wwan3g",
RFKILL_TYPE_WWAN, ASUS_WMI_DEVID_WWAN3G);
if (result && result != -ENODEV)
goto exit;
result = asus_new_rfkill(asus, &asus->gps, "asus-gps",
RFKILL_TYPE_GPS, ASUS_WMI_DEVID_GPS);
if (result && result != -ENODEV)
goto exit;
result = asus_new_rfkill(asus, &asus->uwb, "asus-uwb",
RFKILL_TYPE_UWB, ASUS_WMI_DEVID_UWB);
if (result && result != -ENODEV)
goto exit;
if (!asus->driver->quirks->hotplug_wireless)
goto exit;
result = asus_setup_pci_hotplug(asus);
/*
* If we get -EBUSY then something else is handling the PCI hotplug -
* don't fail in this case
*/
if (result == -EBUSY)
result = 0;
asus_register_rfkill_notifier(asus, "\\_SB.PCI0.P0P5");
asus_register_rfkill_notifier(asus, "\\_SB.PCI0.P0P6");
asus_register_rfkill_notifier(asus, "\\_SB.PCI0.P0P7");
/*
* Refresh pci hotplug in case the rfkill state was changed during
* setup.
*/
asus_rfkill_hotplug(asus);
exit:
if (result && result != -ENODEV)
asus_wmi_rfkill_exit(asus);
if (result == -ENODEV)
result = 0;
return result;
}
/*
* Hwmon device
*/
static ssize_t asus_hwmon_pwm1(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct asus_wmi *asus = dev_get_drvdata(dev);
u32 value;
int err;
err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_FAN_CTRL, &value);
if (err < 0)
return err;
value &= 0xFF;
if (value == 1) /* Low Speed */
value = 85;
else if (value == 2)
value = 170;
else if (value == 3)
value = 255;
else if (value != 0) {
pr_err("Unknown fan speed %#x", value);
value = -1;
}
return sprintf(buf, "%d\n", value);
}
static ssize_t asus_hwmon_temp1(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct asus_wmi *asus = dev_get_drvdata(dev);
u32 value;
int err;
err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_THERMAL_CTRL, &value);
if (err < 0)
return err;
value = KELVIN_TO_CELSIUS((value & 0xFFFF)) * 1000;
return sprintf(buf, "%d\n", value);
}
static SENSOR_DEVICE_ATTR(pwm1, S_IRUGO, asus_hwmon_pwm1, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, asus_hwmon_temp1, NULL, 0);
static ssize_t
show_name(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "asus\n");
}
static SENSOR_DEVICE_ATTR(name, S_IRUGO, show_name, NULL, 0);
static struct attribute *hwmon_attributes[] = {
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_name.dev_attr.attr,
NULL
};
static umode_t asus_hwmon_sysfs_is_visible(struct kobject *kobj,
struct attribute *attr, int idx)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev->parent);
struct asus_wmi *asus = platform_get_drvdata(pdev);
bool ok = true;
int dev_id = -1;
u32 value = ASUS_WMI_UNSUPPORTED_METHOD;
if (attr == &sensor_dev_attr_pwm1.dev_attr.attr)
dev_id = ASUS_WMI_DEVID_FAN_CTRL;
else if (attr == &sensor_dev_attr_temp1_input.dev_attr.attr)
dev_id = ASUS_WMI_DEVID_THERMAL_CTRL;
if (dev_id != -1) {
int err = asus_wmi_get_devstate(asus, dev_id, &value);
if (err < 0)
return 0; /* can't return negative here */
}
if (dev_id == ASUS_WMI_DEVID_FAN_CTRL) {
/*
* We need to find a better way, probably using sfun,
* bits or spec ...
* Currently we disable it if:
* - ASUS_WMI_UNSUPPORTED_METHOD is returned
* - reverved bits are non-zero
* - sfun and presence bit are not set
*/
if (value == ASUS_WMI_UNSUPPORTED_METHOD || value & 0xFFF80000
|| (!asus->sfun && !(value & ASUS_WMI_DSTS_PRESENCE_BIT)))
ok = false;
} else if (dev_id == ASUS_WMI_DEVID_THERMAL_CTRL) {
/* If value is zero, something is clearly wrong */
if (value == 0)
ok = false;
}
return ok ? attr->mode : 0;
}
static struct attribute_group hwmon_attribute_group = {
.is_visible = asus_hwmon_sysfs_is_visible,
.attrs = hwmon_attributes
};
static void asus_wmi_hwmon_exit(struct asus_wmi *asus)
{
struct device *hwmon;
hwmon = asus->hwmon_device;
if (!hwmon)
return;
sysfs_remove_group(&hwmon->kobj, &hwmon_attribute_group);
hwmon_device_unregister(hwmon);
asus->hwmon_device = NULL;
}
static int asus_wmi_hwmon_init(struct asus_wmi *asus)
{
struct device *hwmon;
int result;
hwmon = hwmon_device_register(&asus->platform_device->dev);
if (IS_ERR(hwmon)) {
pr_err("Could not register asus hwmon device\n");
return PTR_ERR(hwmon);
}
dev_set_drvdata(hwmon, asus);
asus->hwmon_device = hwmon;
result = sysfs_create_group(&hwmon->kobj, &hwmon_attribute_group);
if (result)
asus_wmi_hwmon_exit(asus);
return result;
}
/*
* Backlight
*/
static int read_backlight_power(struct asus_wmi *asus)
{
int ret;
if (asus->driver->quirks->store_backlight_power)
ret = !asus->driver->panel_power;
else
ret = asus_wmi_get_devstate_simple(asus,
ASUS_WMI_DEVID_BACKLIGHT);
if (ret < 0)
return ret;
return ret ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;
}
static int read_brightness_max(struct asus_wmi *asus)
{
u32 retval;
int err;
err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_BRIGHTNESS, &retval);
if (err < 0)
return err;
retval = retval & ASUS_WMI_DSTS_MAX_BRIGTH_MASK;
retval >>= 8;
if (!retval)
return -ENODEV;
return retval;
}
static int read_brightness(struct backlight_device *bd)
{
struct asus_wmi *asus = bl_get_data(bd);
u32 retval;
int err;
err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_BRIGHTNESS, &retval);
if (err < 0)
return err;
return retval & ASUS_WMI_DSTS_BRIGHTNESS_MASK;
}
static u32 get_scalar_command(struct backlight_device *bd)
{
struct asus_wmi *asus = bl_get_data(bd);
u32 ctrl_param = 0;
if ((asus->driver->brightness < bd->props.brightness) ||
bd->props.brightness == bd->props.max_brightness)
ctrl_param = 0x00008001;
else if ((asus->driver->brightness > bd->props.brightness) ||
bd->props.brightness == 0)
ctrl_param = 0x00008000;
asus->driver->brightness = bd->props.brightness;
return ctrl_param;
}
static int update_bl_status(struct backlight_device *bd)
{
struct asus_wmi *asus = bl_get_data(bd);
u32 ctrl_param;
int power, err = 0;
power = read_backlight_power(asus);
if (power != -ENODEV && bd->props.power != power) {
ctrl_param = !!(bd->props.power == FB_BLANK_UNBLANK);
err = asus_wmi_set_devstate(ASUS_WMI_DEVID_BACKLIGHT,
ctrl_param, NULL);
if (asus->driver->quirks->store_backlight_power)
asus->driver->panel_power = bd->props.power;
/* When using scalar brightness, updating the brightness
* will mess with the backlight power */
if (asus->driver->quirks->scalar_panel_brightness)
return err;
}
if (asus->driver->quirks->scalar_panel_brightness)
ctrl_param = get_scalar_command(bd);
else
ctrl_param = bd->props.brightness;
err = asus_wmi_set_devstate(ASUS_WMI_DEVID_BRIGHTNESS,
ctrl_param, NULL);
return err;
}
static const struct backlight_ops asus_wmi_bl_ops = {
.get_brightness = read_brightness,
.update_status = update_bl_status,
};
static int asus_wmi_backlight_notify(struct asus_wmi *asus, int code)
{
struct backlight_device *bd = asus->backlight_device;
int old = bd->props.brightness;
int new = old;
if (code >= NOTIFY_BRNUP_MIN && code <= NOTIFY_BRNUP_MAX)
new = code - NOTIFY_BRNUP_MIN + 1;
else if (code >= NOTIFY_BRNDOWN_MIN && code <= NOTIFY_BRNDOWN_MAX)
new = code - NOTIFY_BRNDOWN_MIN;
bd->props.brightness = new;
backlight_update_status(bd);
backlight_force_update(bd, BACKLIGHT_UPDATE_HOTKEY);
return old;
}
static int asus_wmi_backlight_init(struct asus_wmi *asus)
{
struct backlight_device *bd;
struct backlight_properties props;
int max;
int power;
max = read_brightness_max(asus);
if (max == -ENODEV)
max = 0;
else if (max < 0)
return max;
power = read_backlight_power(asus);
if (power == -ENODEV)
power = FB_BLANK_UNBLANK;
else if (power < 0)
return power;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = max;
bd = backlight_device_register(asus->driver->name,
&asus->platform_device->dev, asus,
&asus_wmi_bl_ops, &props);
if (IS_ERR(bd)) {
pr_err("Could not register backlight device\n");
return PTR_ERR(bd);
}
asus->backlight_device = bd;
if (asus->driver->quirks->store_backlight_power)
asus->driver->panel_power = power;
bd->props.brightness = read_brightness(bd);
bd->props.power = power;
backlight_update_status(bd);
asus->driver->brightness = bd->props.brightness;
return 0;
}
static void asus_wmi_backlight_exit(struct asus_wmi *asus)
{
if (asus->backlight_device)
backlight_device_unregister(asus->backlight_device);
asus->backlight_device = NULL;
}
static void asus_wmi_notify(u32 value, void *context)
{
struct asus_wmi *asus = context;
struct acpi_buffer response = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *obj;
acpi_status status;
int code;
int orig_code;
unsigned int key_value = 1;
bool autorelease = 1;
status = wmi_get_event_data(value, &response);
if (status != AE_OK) {
pr_err("bad event status 0x%x\n", status);
return;
}
obj = (union acpi_object *)response.pointer;
if (!obj || obj->type != ACPI_TYPE_INTEGER)
goto exit;
code = obj->integer.value;
orig_code = code;
if (asus->driver->key_filter) {
asus->driver->key_filter(asus->driver, &code, &key_value,
&autorelease);
if (code == ASUS_WMI_KEY_IGNORE)
goto exit;
}
if (code >= NOTIFY_BRNUP_MIN && code <= NOTIFY_BRNUP_MAX)
code = NOTIFY_BRNUP_MIN;
else if (code >= NOTIFY_BRNDOWN_MIN &&
code <= NOTIFY_BRNDOWN_MAX)
code = NOTIFY_BRNDOWN_MIN;
if (code == NOTIFY_BRNUP_MIN || code == NOTIFY_BRNDOWN_MIN) {
if (!acpi_video_backlight_support())
asus_wmi_backlight_notify(asus, orig_code);
} else if (!sparse_keymap_report_event(asus->inputdev, code,
key_value, autorelease))
pr_info("Unknown key %x pressed\n", code);
exit:
kfree(obj);
}
/*
* Sys helpers
*/
static int parse_arg(const char *buf, unsigned long count, int *val)
{
if (!count)
return 0;
if (sscanf(buf, "%i", val) != 1)
return -EINVAL;
return count;
}
static ssize_t store_sys_wmi(struct asus_wmi *asus, int devid,
const char *buf, size_t count)
{
u32 retval;
int rv, err, value;
value = asus_wmi_get_devstate_simple(asus, devid);
if (value == -ENODEV) /* Check device presence */
return value;
rv = parse_arg(buf, count, &value);
err = asus_wmi_set_devstate(devid, value, &retval);
if (err < 0)
return err;
return rv;
}
static ssize_t show_sys_wmi(struct asus_wmi *asus, int devid, char *buf)
{
int value = asus_wmi_get_devstate_simple(asus, devid);
if (value < 0)
return value;
return sprintf(buf, "%d\n", value);
}
#define ASUS_WMI_CREATE_DEVICE_ATTR(_name, _mode, _cm) \
static ssize_t show_##_name(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct asus_wmi *asus = dev_get_drvdata(dev); \
\
return show_sys_wmi(asus, _cm, buf); \
} \
static ssize_t store_##_name(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct asus_wmi *asus = dev_get_drvdata(dev); \
\
return store_sys_wmi(asus, _cm, buf, count); \
} \
static struct device_attribute dev_attr_##_name = { \
.attr = { \
.name = __stringify(_name), \
.mode = _mode }, \
.show = show_##_name, \
.store = store_##_name, \
}
ASUS_WMI_CREATE_DEVICE_ATTR(touchpad, 0644, ASUS_WMI_DEVID_TOUCHPAD);
ASUS_WMI_CREATE_DEVICE_ATTR(camera, 0644, ASUS_WMI_DEVID_CAMERA);
ASUS_WMI_CREATE_DEVICE_ATTR(cardr, 0644, ASUS_WMI_DEVID_CARDREADER);
static ssize_t store_cpufv(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int value, rv;
if (!count || sscanf(buf, "%i", &value) != 1)
return -EINVAL;
if (value < 0 || value > 2)
return -EINVAL;
rv = asus_wmi_evaluate_method(ASUS_WMI_METHODID_CFVS, value, 0, NULL);
if (rv < 0)
return rv;
return count;
}
static DEVICE_ATTR(cpufv, S_IRUGO | S_IWUSR, NULL, store_cpufv);
static struct attribute *platform_attributes[] = {
&dev_attr_cpufv.attr,
&dev_attr_camera.attr,
&dev_attr_cardr.attr,
&dev_attr_touchpad.attr,
NULL
};
static umode_t asus_sysfs_is_visible(struct kobject *kobj,
struct attribute *attr, int idx)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev);
struct asus_wmi *asus = platform_get_drvdata(pdev);
bool ok = true;
int devid = -1;
if (attr == &dev_attr_camera.attr)
devid = ASUS_WMI_DEVID_CAMERA;
else if (attr == &dev_attr_cardr.attr)
devid = ASUS_WMI_DEVID_CARDREADER;
else if (attr == &dev_attr_touchpad.attr)
devid = ASUS_WMI_DEVID_TOUCHPAD;
if (devid != -1)
ok = !(asus_wmi_get_devstate_simple(asus, devid) < 0);
return ok ? attr->mode : 0;
}
static struct attribute_group platform_attribute_group = {
.is_visible = asus_sysfs_is_visible,
.attrs = platform_attributes
};
static void asus_wmi_sysfs_exit(struct platform_device *device)
{
sysfs_remove_group(&device->dev.kobj, &platform_attribute_group);
}
static int asus_wmi_sysfs_init(struct platform_device *device)
{
return sysfs_create_group(&device->dev.kobj, &platform_attribute_group);
}
/*
* Platform device
*/
static int asus_wmi_platform_init(struct asus_wmi *asus)
{
int rv;
/* INIT enable hotkeys on some models */
if (!asus_wmi_evaluate_method(ASUS_WMI_METHODID_INIT, 0, 0, &rv))
pr_info("Initialization: %#x", rv);
/* We don't know yet what to do with this version... */
if (!asus_wmi_evaluate_method(ASUS_WMI_METHODID_SPEC, 0, 0x9, &rv)) {
pr_info("BIOS WMI version: %d.%d", rv >> 16, rv & 0xFF);
asus->spec = rv;
}
/*
* The SFUN method probably allows the original driver to get the list
* of features supported by a given model. For now, 0x0100 or 0x0800
* bit signifies that the laptop is equipped with a Wi-Fi MiniPCI card.
* The significance of others is yet to be found.
*/
if (!asus_wmi_evaluate_method(ASUS_WMI_METHODID_SFUN, 0, 0, &rv)) {
pr_info("SFUN value: %#x", rv);
asus->sfun = rv;
}
/*
* Eee PC and Notebooks seems to have different method_id for DSTS,
* but it may also be related to the BIOS's SPEC.
* Note, on most Eeepc, there is no way to check if a method exist
* or note, while on notebooks, they returns 0xFFFFFFFE on failure,
* but once again, SPEC may probably be used for that kind of things.
*/
if (!asus_wmi_evaluate_method(ASUS_WMI_METHODID_DSTS, 0, 0, NULL))
asus->dsts_id = ASUS_WMI_METHODID_DSTS;
else
asus->dsts_id = ASUS_WMI_METHODID_DSTS2;
/* CWAP allow to define the behavior of the Fn+F2 key,
* this method doesn't seems to be present on Eee PCs */
if (asus->driver->quirks->wapf >= 0)
asus_wmi_set_devstate(ASUS_WMI_DEVID_CWAP,
asus->driver->quirks->wapf, NULL);
return asus_wmi_sysfs_init(asus->platform_device);
}
static void asus_wmi_platform_exit(struct asus_wmi *asus)
{
asus_wmi_sysfs_exit(asus->platform_device);
}
/*
* debugfs
*/
struct asus_wmi_debugfs_node {
struct asus_wmi *asus;
char *name;
int (*show) (struct seq_file *m, void *data);
};
static int show_dsts(struct seq_file *m, void *data)
{
struct asus_wmi *asus = m->private;
int err;
u32 retval = -1;
err = asus_wmi_get_devstate(asus, asus->debug.dev_id, &retval);
if (err < 0)
return err;
seq_printf(m, "DSTS(%#x) = %#x\n", asus->debug.dev_id, retval);
return 0;
}
static int show_devs(struct seq_file *m, void *data)
{
struct asus_wmi *asus = m->private;
int err;
u32 retval = -1;
err = asus_wmi_set_devstate(asus->debug.dev_id, asus->debug.ctrl_param,
&retval);
if (err < 0)
return err;
seq_printf(m, "DEVS(%#x, %#x) = %#x\n", asus->debug.dev_id,
asus->debug.ctrl_param, retval);
return 0;
}
static int show_call(struct seq_file *m, void *data)
{
struct asus_wmi *asus = m->private;
struct bios_args args = {
.arg0 = asus->debug.dev_id,
.arg1 = asus->debug.ctrl_param,
};
struct acpi_buffer input = { (acpi_size) sizeof(args), &args };
struct acpi_buffer output = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *obj;
acpi_status status;
status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID,
1, asus->debug.method_id,
&input, &output);
if (ACPI_FAILURE(status))
return -EIO;
obj = (union acpi_object *)output.pointer;
if (obj && obj->type == ACPI_TYPE_INTEGER)
seq_printf(m, "%#x(%#x, %#x) = %#x\n", asus->debug.method_id,
asus->debug.dev_id, asus->debug.ctrl_param,
(u32) obj->integer.value);
else
seq_printf(m, "%#x(%#x, %#x) = t:%d\n", asus->debug.method_id,
asus->debug.dev_id, asus->debug.ctrl_param,
obj ? obj->type : -1);
kfree(obj);
return 0;
}
static struct asus_wmi_debugfs_node asus_wmi_debug_files[] = {
{NULL, "devs", show_devs},
{NULL, "dsts", show_dsts},
{NULL, "call", show_call},
};
static int asus_wmi_debugfs_open(struct inode *inode, struct file *file)
{
struct asus_wmi_debugfs_node *node = inode->i_private;
return single_open(file, node->show, node->asus);
}
static const struct file_operations asus_wmi_debugfs_io_ops = {
.owner = THIS_MODULE,
.open = asus_wmi_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void asus_wmi_debugfs_exit(struct asus_wmi *asus)
{
debugfs_remove_recursive(asus->debug.root);
}
static int asus_wmi_debugfs_init(struct asus_wmi *asus)
{
struct dentry *dent;
int i;
asus->debug.root = debugfs_create_dir(asus->driver->name, NULL);
if (!asus->debug.root) {
pr_err("failed to create debugfs directory");
goto error_debugfs;
}
dent = debugfs_create_x32("method_id", S_IRUGO | S_IWUSR,
asus->debug.root, &asus->debug.method_id);
if (!dent)
goto error_debugfs;
dent = debugfs_create_x32("dev_id", S_IRUGO | S_IWUSR,
asus->debug.root, &asus->debug.dev_id);
if (!dent)
goto error_debugfs;
dent = debugfs_create_x32("ctrl_param", S_IRUGO | S_IWUSR,
asus->debug.root, &asus->debug.ctrl_param);
if (!dent)
goto error_debugfs;
for (i = 0; i < ARRAY_SIZE(asus_wmi_debug_files); i++) {
struct asus_wmi_debugfs_node *node = &asus_wmi_debug_files[i];
node->asus = asus;
dent = debugfs_create_file(node->name, S_IFREG | S_IRUGO,
asus->debug.root, node,
&asus_wmi_debugfs_io_ops);
if (!dent) {
pr_err("failed to create debug file: %s\n", node->name);
goto error_debugfs;
}
}
return 0;
error_debugfs:
asus_wmi_debugfs_exit(asus);
return -ENOMEM;
}
/*
* WMI Driver
*/
static int asus_wmi_add(struct platform_device *pdev)
{
struct platform_driver *pdrv = to_platform_driver(pdev->dev.driver);
struct asus_wmi_driver *wdrv = to_asus_wmi_driver(pdrv);
struct asus_wmi *asus;
acpi_status status;
int err;
asus = kzalloc(sizeof(struct asus_wmi), GFP_KERNEL);
if (!asus)
return -ENOMEM;
asus->driver = wdrv;
asus->platform_device = pdev;
wdrv->platform_device = pdev;
platform_set_drvdata(asus->platform_device, asus);
if (wdrv->detect_quirks)
wdrv->detect_quirks(asus->driver);
err = asus_wmi_platform_init(asus);
if (err)
goto fail_platform;
err = asus_wmi_input_init(asus);
if (err)
goto fail_input;
err = asus_wmi_hwmon_init(asus);
if (err)
goto fail_hwmon;
err = asus_wmi_led_init(asus);
if (err)
goto fail_leds;
err = asus_wmi_rfkill_init(asus);
if (err)
goto fail_rfkill;
if (!acpi_video_backlight_support()) {
err = asus_wmi_backlight_init(asus);
if (err && err != -ENODEV)
goto fail_backlight;
} else
pr_info("Backlight controlled by ACPI video driver\n");
status = wmi_install_notify_handler(asus->driver->event_guid,
asus_wmi_notify, asus);
if (ACPI_FAILURE(status)) {
pr_err("Unable to register notify handler - %d\n", status);
err = -ENODEV;
goto fail_wmi_handler;
}
err = asus_wmi_debugfs_init(asus);
if (err)
goto fail_debugfs;
return 0;
fail_debugfs:
wmi_remove_notify_handler(asus->driver->event_guid);
fail_wmi_handler:
asus_wmi_backlight_exit(asus);
fail_backlight:
asus_wmi_rfkill_exit(asus);
fail_rfkill:
asus_wmi_led_exit(asus);
fail_leds:
asus_wmi_hwmon_exit(asus);
fail_hwmon:
asus_wmi_input_exit(asus);
fail_input:
asus_wmi_platform_exit(asus);
fail_platform:
kfree(asus);
return err;
}
static int asus_wmi_remove(struct platform_device *device)
{
struct asus_wmi *asus;
asus = platform_get_drvdata(device);
wmi_remove_notify_handler(asus->driver->event_guid);
asus_wmi_backlight_exit(asus);
asus_wmi_input_exit(asus);
asus_wmi_hwmon_exit(asus);
asus_wmi_led_exit(asus);
asus_wmi_rfkill_exit(asus);
asus_wmi_debugfs_exit(asus);
asus_wmi_platform_exit(asus);
kfree(asus);
return 0;
}
/*
* Platform driver - hibernate/resume callbacks
*/
static int asus_hotk_thaw(struct device *device)
{
struct asus_wmi *asus = dev_get_drvdata(device);
if (asus->wlan.rfkill) {
bool wlan;
/*
* Work around bios bug - acpi _PTS turns off the wireless led
* during suspend. Normally it restores it on resume, but
* we should kick it ourselves in case hibernation is aborted.
*/
wlan = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_WLAN);
asus_wmi_set_devstate(ASUS_WMI_DEVID_WLAN, wlan, NULL);
}
return 0;
}
static int asus_hotk_restore(struct device *device)
{
struct asus_wmi *asus = dev_get_drvdata(device);
int bl;
/* Refresh both wlan rfkill state and pci hotplug */
if (asus->wlan.rfkill)
asus_rfkill_hotplug(asus);
if (asus->bluetooth.rfkill) {
bl = !asus_wmi_get_devstate_simple(asus,
ASUS_WMI_DEVID_BLUETOOTH);
rfkill_set_sw_state(asus->bluetooth.rfkill, bl);
}
if (asus->wimax.rfkill) {
bl = !asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_WIMAX);
rfkill_set_sw_state(asus->wimax.rfkill, bl);
}
if (asus->wwan3g.rfkill) {
bl = !asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_WWAN3G);
rfkill_set_sw_state(asus->wwan3g.rfkill, bl);
}
if (asus->gps.rfkill) {
bl = !asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_GPS);
rfkill_set_sw_state(asus->gps.rfkill, bl);
}
if (asus->uwb.rfkill) {
bl = !asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_UWB);
rfkill_set_sw_state(asus->uwb.rfkill, bl);
}
return 0;
}
static const struct dev_pm_ops asus_pm_ops = {
.thaw = asus_hotk_thaw,
.restore = asus_hotk_restore,
};
static int asus_wmi_probe(struct platform_device *pdev)
{
struct platform_driver *pdrv = to_platform_driver(pdev->dev.driver);
struct asus_wmi_driver *wdrv = to_asus_wmi_driver(pdrv);
int ret;
if (!wmi_has_guid(ASUS_WMI_MGMT_GUID)) {
pr_warn("Management GUID not found\n");
return -ENODEV;
}
if (wdrv->event_guid && !wmi_has_guid(wdrv->event_guid)) {
pr_warn("Event GUID not found\n");
return -ENODEV;
}
if (wdrv->probe) {
ret = wdrv->probe(pdev);
if (ret)
return ret;
}
return asus_wmi_add(pdev);
}
static bool used;
int __init_or_module asus_wmi_register_driver(struct asus_wmi_driver *driver)
{
struct platform_driver *platform_driver;
struct platform_device *platform_device;
if (used)
return -EBUSY;
platform_driver = &driver->platform_driver;
platform_driver->remove = asus_wmi_remove;
platform_driver->driver.owner = driver->owner;
platform_driver->driver.name = driver->name;
platform_driver->driver.pm = &asus_pm_ops;
platform_device = platform_create_bundle(platform_driver,
asus_wmi_probe,
NULL, 0, NULL, 0);
if (IS_ERR(platform_device))
return PTR_ERR(platform_device);
used = true;
return 0;
}
EXPORT_SYMBOL_GPL(asus_wmi_register_driver);
void asus_wmi_unregister_driver(struct asus_wmi_driver *driver)
{
platform_device_unregister(driver->platform_device);
platform_driver_unregister(&driver->platform_driver);
used = false;
}
EXPORT_SYMBOL_GPL(asus_wmi_unregister_driver);
static int __init asus_wmi_init(void)
{
if (!wmi_has_guid(ASUS_WMI_MGMT_GUID)) {
pr_info("Asus Management GUID not found");
return -ENODEV;
}
pr_info("ASUS WMI generic driver loaded");
return 0;
}
static void __exit asus_wmi_exit(void)
{
pr_info("ASUS WMI generic driver unloaded");
}
module_init(asus_wmi_init);
module_exit(asus_wmi_exit);
| gpl-2.0 |
Ander-Alvarez/android_kernel_motorola_msm8916 | sound/soc/codecs/wm8510.c | 2479 | 19646 | /*
* wm8510.c -- WM8510 ALSA Soc Audio driver
*
* Copyright 2006 Wolfson Microelectronics PLC.
*
* Author: Liam Girdwood <lrg@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/of_device.h>
#include <linux/regmap.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include "wm8510.h"
/*
* wm8510 register cache
* We can't read the WM8510 register space when we are
* using 2 wire for device control, so we cache them instead.
*/
static const struct reg_default wm8510_reg_defaults[] = {
{ 1, 0x0000 },
{ 2, 0x0000 },
{ 3, 0x0000 },
{ 4, 0x0050 },
{ 5, 0x0000 },
{ 6, 0x0140 },
{ 7, 0x0000 },
{ 8, 0x0000 },
{ 9, 0x0000 },
{ 10, 0x0000 },
{ 11, 0x00ff },
{ 12, 0x0000 },
{ 13, 0x0000 },
{ 14, 0x0100 },
{ 15, 0x00ff },
{ 16, 0x0000 },
{ 17, 0x0000 },
{ 18, 0x012c },
{ 19, 0x002c },
{ 20, 0x002c },
{ 21, 0x002c },
{ 22, 0x002c },
{ 23, 0x0000 },
{ 24, 0x0032 },
{ 25, 0x0000 },
{ 26, 0x0000 },
{ 27, 0x0000 },
{ 28, 0x0000 },
{ 29, 0x0000 },
{ 30, 0x0000 },
{ 31, 0x0000 },
{ 32, 0x0038 },
{ 33, 0x000b },
{ 34, 0x0032 },
{ 35, 0x0000 },
{ 36, 0x0008 },
{ 37, 0x000c },
{ 38, 0x0093 },
{ 39, 0x00e9 },
{ 40, 0x0000 },
{ 41, 0x0000 },
{ 42, 0x0000 },
{ 43, 0x0000 },
{ 44, 0x0003 },
{ 45, 0x0010 },
{ 46, 0x0000 },
{ 47, 0x0000 },
{ 48, 0x0000 },
{ 49, 0x0002 },
{ 50, 0x0001 },
{ 51, 0x0000 },
{ 52, 0x0000 },
{ 53, 0x0000 },
{ 54, 0x0039 },
{ 55, 0x0000 },
{ 56, 0x0001 },
};
static bool wm8510_volatile(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8510_RESET:
return true;
default:
return false;
}
}
#define WM8510_POWER1_BIASEN 0x08
#define WM8510_POWER1_BUFIOEN 0x10
#define wm8510_reset(c) snd_soc_write(c, WM8510_RESET, 0)
/* codec private data */
struct wm8510_priv {
struct regmap *regmap;
};
static const char *wm8510_companding[] = { "Off", "NC", "u-law", "A-law" };
static const char *wm8510_deemp[] = { "None", "32kHz", "44.1kHz", "48kHz" };
static const char *wm8510_alc[] = { "ALC", "Limiter" };
static const struct soc_enum wm8510_enum[] = {
SOC_ENUM_SINGLE(WM8510_COMP, 1, 4, wm8510_companding), /* adc */
SOC_ENUM_SINGLE(WM8510_COMP, 3, 4, wm8510_companding), /* dac */
SOC_ENUM_SINGLE(WM8510_DAC, 4, 4, wm8510_deemp),
SOC_ENUM_SINGLE(WM8510_ALC3, 8, 2, wm8510_alc),
};
static const struct snd_kcontrol_new wm8510_snd_controls[] = {
SOC_SINGLE("Digital Loopback Switch", WM8510_COMP, 0, 1, 0),
SOC_ENUM("DAC Companding", wm8510_enum[1]),
SOC_ENUM("ADC Companding", wm8510_enum[0]),
SOC_ENUM("Playback De-emphasis", wm8510_enum[2]),
SOC_SINGLE("DAC Inversion Switch", WM8510_DAC, 0, 1, 0),
SOC_SINGLE("Master Playback Volume", WM8510_DACVOL, 0, 127, 0),
SOC_SINGLE("High Pass Filter Switch", WM8510_ADC, 8, 1, 0),
SOC_SINGLE("High Pass Cut Off", WM8510_ADC, 4, 7, 0),
SOC_SINGLE("ADC Inversion Switch", WM8510_COMP, 0, 1, 0),
SOC_SINGLE("Capture Volume", WM8510_ADCVOL, 0, 127, 0),
SOC_SINGLE("DAC Playback Limiter Switch", WM8510_DACLIM1, 8, 1, 0),
SOC_SINGLE("DAC Playback Limiter Decay", WM8510_DACLIM1, 4, 15, 0),
SOC_SINGLE("DAC Playback Limiter Attack", WM8510_DACLIM1, 0, 15, 0),
SOC_SINGLE("DAC Playback Limiter Threshold", WM8510_DACLIM2, 4, 7, 0),
SOC_SINGLE("DAC Playback Limiter Boost", WM8510_DACLIM2, 0, 15, 0),
SOC_SINGLE("ALC Enable Switch", WM8510_ALC1, 8, 1, 0),
SOC_SINGLE("ALC Capture Max Gain", WM8510_ALC1, 3, 7, 0),
SOC_SINGLE("ALC Capture Min Gain", WM8510_ALC1, 0, 7, 0),
SOC_SINGLE("ALC Capture ZC Switch", WM8510_ALC2, 8, 1, 0),
SOC_SINGLE("ALC Capture Hold", WM8510_ALC2, 4, 7, 0),
SOC_SINGLE("ALC Capture Target", WM8510_ALC2, 0, 15, 0),
SOC_ENUM("ALC Capture Mode", wm8510_enum[3]),
SOC_SINGLE("ALC Capture Decay", WM8510_ALC3, 4, 15, 0),
SOC_SINGLE("ALC Capture Attack", WM8510_ALC3, 0, 15, 0),
SOC_SINGLE("ALC Capture Noise Gate Switch", WM8510_NGATE, 3, 1, 0),
SOC_SINGLE("ALC Capture Noise Gate Threshold", WM8510_NGATE, 0, 7, 0),
SOC_SINGLE("Capture PGA ZC Switch", WM8510_INPPGA, 7, 1, 0),
SOC_SINGLE("Capture PGA Volume", WM8510_INPPGA, 0, 63, 0),
SOC_SINGLE("Speaker Playback ZC Switch", WM8510_SPKVOL, 7, 1, 0),
SOC_SINGLE("Speaker Playback Switch", WM8510_SPKVOL, 6, 1, 1),
SOC_SINGLE("Speaker Playback Volume", WM8510_SPKVOL, 0, 63, 0),
SOC_SINGLE("Speaker Boost", WM8510_OUTPUT, 2, 1, 0),
SOC_SINGLE("Capture Boost(+20dB)", WM8510_ADCBOOST, 8, 1, 0),
SOC_SINGLE("Mono Playback Switch", WM8510_MONOMIX, 6, 1, 1),
};
/* Speaker Output Mixer */
static const struct snd_kcontrol_new wm8510_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8510_SPKMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8510_SPKMIX, 5, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8510_SPKMIX, 0, 1, 0),
};
/* Mono Output Mixer */
static const struct snd_kcontrol_new wm8510_mono_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8510_MONOMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8510_MONOMIX, 2, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8510_MONOMIX, 0, 1, 0),
};
static const struct snd_kcontrol_new wm8510_boost_controls[] = {
SOC_DAPM_SINGLE("Mic PGA Switch", WM8510_INPPGA, 6, 1, 1),
SOC_DAPM_SINGLE("Aux Volume", WM8510_ADCBOOST, 0, 7, 0),
SOC_DAPM_SINGLE("Mic Volume", WM8510_ADCBOOST, 4, 7, 0),
};
static const struct snd_kcontrol_new wm8510_micpga_controls[] = {
SOC_DAPM_SINGLE("MICP Switch", WM8510_INPUT, 0, 1, 0),
SOC_DAPM_SINGLE("MICN Switch", WM8510_INPUT, 1, 1, 0),
SOC_DAPM_SINGLE("AUX Switch", WM8510_INPUT, 2, 1, 0),
};
static const struct snd_soc_dapm_widget wm8510_dapm_widgets[] = {
SND_SOC_DAPM_MIXER("Speaker Mixer", WM8510_POWER3, 2, 0,
&wm8510_speaker_mixer_controls[0],
ARRAY_SIZE(wm8510_speaker_mixer_controls)),
SND_SOC_DAPM_MIXER("Mono Mixer", WM8510_POWER3, 3, 0,
&wm8510_mono_mixer_controls[0],
ARRAY_SIZE(wm8510_mono_mixer_controls)),
SND_SOC_DAPM_DAC("DAC", "HiFi Playback", WM8510_POWER3, 0, 0),
SND_SOC_DAPM_ADC("ADC", "HiFi Capture", WM8510_POWER2, 0, 0),
SND_SOC_DAPM_PGA("Aux Input", WM8510_POWER1, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpkN Out", WM8510_POWER3, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpkP Out", WM8510_POWER3, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("Mono Out", WM8510_POWER3, 7, 0, NULL, 0),
SND_SOC_DAPM_MIXER("Mic PGA", WM8510_POWER2, 2, 0,
&wm8510_micpga_controls[0],
ARRAY_SIZE(wm8510_micpga_controls)),
SND_SOC_DAPM_MIXER("Boost Mixer", WM8510_POWER2, 4, 0,
&wm8510_boost_controls[0],
ARRAY_SIZE(wm8510_boost_controls)),
SND_SOC_DAPM_MICBIAS("Mic Bias", WM8510_POWER1, 4, 0),
SND_SOC_DAPM_INPUT("MICN"),
SND_SOC_DAPM_INPUT("MICP"),
SND_SOC_DAPM_INPUT("AUX"),
SND_SOC_DAPM_OUTPUT("MONOOUT"),
SND_SOC_DAPM_OUTPUT("SPKOUTP"),
SND_SOC_DAPM_OUTPUT("SPKOUTN"),
};
static const struct snd_soc_dapm_route wm8510_dapm_routes[] = {
/* Mono output mixer */
{"Mono Mixer", "PCM Playback Switch", "DAC"},
{"Mono Mixer", "Aux Playback Switch", "Aux Input"},
{"Mono Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Speaker output mixer */
{"Speaker Mixer", "PCM Playback Switch", "DAC"},
{"Speaker Mixer", "Aux Playback Switch", "Aux Input"},
{"Speaker Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Outputs */
{"Mono Out", NULL, "Mono Mixer"},
{"MONOOUT", NULL, "Mono Out"},
{"SpkN Out", NULL, "Speaker Mixer"},
{"SpkP Out", NULL, "Speaker Mixer"},
{"SPKOUTN", NULL, "SpkN Out"},
{"SPKOUTP", NULL, "SpkP Out"},
/* Microphone PGA */
{"Mic PGA", "MICN Switch", "MICN"},
{"Mic PGA", "MICP Switch", "MICP"},
{ "Mic PGA", "AUX Switch", "Aux Input" },
/* Boost Mixer */
{"Boost Mixer", "Mic PGA Switch", "Mic PGA"},
{"Boost Mixer", "Mic Volume", "MICP"},
{"Boost Mixer", "Aux Volume", "Aux Input"},
{"ADC", NULL, "Boost Mixer"},
};
struct pll_ {
unsigned int pre_div:4; /* prescale - 1 */
unsigned int n:4;
unsigned int k;
};
static struct pll_ pll_div;
/* The size in bits of the pll divide multiplied by 10
* to allow rounding later */
#define FIXED_PLL_SIZE ((1 << 24) * 10)
static void pll_factors(unsigned int target, unsigned int source)
{
unsigned long long Kpart;
unsigned int K, Ndiv, Nmod;
Ndiv = target / source;
if (Ndiv < 6) {
source >>= 1;
pll_div.pre_div = 1;
Ndiv = target / source;
} else
pll_div.pre_div = 0;
if ((Ndiv < 6) || (Ndiv > 12))
printk(KERN_WARNING
"WM8510 N value %u outwith recommended range!d\n",
Ndiv);
pll_div.n = Ndiv;
Nmod = target % source;
Kpart = FIXED_PLL_SIZE * (long long)Nmod;
do_div(Kpart, source);
K = Kpart & 0xFFFFFFFF;
/* Check if we need to round */
if ((K % 10) >= 5)
K += 5;
/* Move down to proper range now rounding is done */
K /= 10;
pll_div.k = K;
}
static int wm8510_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id,
int source, unsigned int freq_in, unsigned int freq_out)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
if (freq_in == 0 || freq_out == 0) {
/* Clock CODEC directly from MCLK */
reg = snd_soc_read(codec, WM8510_CLOCK);
snd_soc_write(codec, WM8510_CLOCK, reg & 0x0ff);
/* Turn off PLL */
reg = snd_soc_read(codec, WM8510_POWER1);
snd_soc_write(codec, WM8510_POWER1, reg & 0x1df);
return 0;
}
pll_factors(freq_out*4, freq_in);
snd_soc_write(codec, WM8510_PLLN, (pll_div.pre_div << 4) | pll_div.n);
snd_soc_write(codec, WM8510_PLLK1, pll_div.k >> 18);
snd_soc_write(codec, WM8510_PLLK2, (pll_div.k >> 9) & 0x1ff);
snd_soc_write(codec, WM8510_PLLK3, pll_div.k & 0x1ff);
reg = snd_soc_read(codec, WM8510_POWER1);
snd_soc_write(codec, WM8510_POWER1, reg | 0x020);
/* Run CODEC from PLL instead of MCLK */
reg = snd_soc_read(codec, WM8510_CLOCK);
snd_soc_write(codec, WM8510_CLOCK, reg | 0x100);
return 0;
}
/*
* Configure WM8510 clock dividers.
*/
static int wm8510_set_dai_clkdiv(struct snd_soc_dai *codec_dai,
int div_id, int div)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
switch (div_id) {
case WM8510_OPCLKDIV:
reg = snd_soc_read(codec, WM8510_GPIO) & 0x1cf;
snd_soc_write(codec, WM8510_GPIO, reg | div);
break;
case WM8510_MCLKDIV:
reg = snd_soc_read(codec, WM8510_CLOCK) & 0x11f;
snd_soc_write(codec, WM8510_CLOCK, reg | div);
break;
case WM8510_ADCCLK:
reg = snd_soc_read(codec, WM8510_ADC) & 0x1f7;
snd_soc_write(codec, WM8510_ADC, reg | div);
break;
case WM8510_DACCLK:
reg = snd_soc_read(codec, WM8510_DAC) & 0x1f7;
snd_soc_write(codec, WM8510_DAC, reg | div);
break;
case WM8510_BCLKDIV:
reg = snd_soc_read(codec, WM8510_CLOCK) & 0x1e3;
snd_soc_write(codec, WM8510_CLOCK, reg | div);
break;
default:
return -EINVAL;
}
return 0;
}
static int wm8510_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface = 0;
u16 clk = snd_soc_read(codec, WM8510_CLOCK) & 0x1fe;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
clk |= 0x0001;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= 0x0010;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= 0x0008;
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= 0x00018;
break;
default:
return -EINVAL;
}
/* clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= 0x0180;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= 0x0100;
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= 0x0080;
break;
default:
return -EINVAL;
}
snd_soc_write(codec, WM8510_IFACE, iface);
snd_soc_write(codec, WM8510_CLOCK, clk);
return 0;
}
static int wm8510_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
u16 iface = snd_soc_read(codec, WM8510_IFACE) & 0x19f;
u16 adn = snd_soc_read(codec, WM8510_ADD) & 0x1f1;
/* bit size */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface |= 0x0020;
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface |= 0x0040;
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface |= 0x0060;
break;
}
/* filter coefficient */
switch (params_rate(params)) {
case 8000:
adn |= 0x5 << 1;
break;
case 11025:
adn |= 0x4 << 1;
break;
case 16000:
adn |= 0x3 << 1;
break;
case 22050:
adn |= 0x2 << 1;
break;
case 32000:
adn |= 0x1 << 1;
break;
case 44100:
case 48000:
break;
}
snd_soc_write(codec, WM8510_IFACE, iface);
snd_soc_write(codec, WM8510_ADD, adn);
return 0;
}
static int wm8510_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 mute_reg = snd_soc_read(codec, WM8510_DAC) & 0xffbf;
if (mute)
snd_soc_write(codec, WM8510_DAC, mute_reg | 0x40);
else
snd_soc_write(codec, WM8510_DAC, mute_reg);
return 0;
}
/* liam need to make this lower power with dapm */
static int wm8510_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct wm8510_priv *wm8510 = snd_soc_codec_get_drvdata(codec);
u16 power1 = snd_soc_read(codec, WM8510_POWER1) & ~0x3;
switch (level) {
case SND_SOC_BIAS_ON:
case SND_SOC_BIAS_PREPARE:
power1 |= 0x1; /* VMID 50k */
snd_soc_write(codec, WM8510_POWER1, power1);
break;
case SND_SOC_BIAS_STANDBY:
power1 |= WM8510_POWER1_BIASEN | WM8510_POWER1_BUFIOEN;
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
regcache_sync(wm8510->regmap);
/* Initial cap charge at VMID 5k */
snd_soc_write(codec, WM8510_POWER1, power1 | 0x3);
mdelay(100);
}
power1 |= 0x2; /* VMID 500k */
snd_soc_write(codec, WM8510_POWER1, power1);
break;
case SND_SOC_BIAS_OFF:
snd_soc_write(codec, WM8510_POWER1, 0);
snd_soc_write(codec, WM8510_POWER2, 0);
snd_soc_write(codec, WM8510_POWER3, 0);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8510_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\
SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 |\
SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000)
#define WM8510_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops wm8510_dai_ops = {
.hw_params = wm8510_pcm_hw_params,
.digital_mute = wm8510_mute,
.set_fmt = wm8510_set_dai_fmt,
.set_clkdiv = wm8510_set_dai_clkdiv,
.set_pll = wm8510_set_dai_pll,
};
static struct snd_soc_dai_driver wm8510_dai = {
.name = "wm8510-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = WM8510_RATES,
.formats = WM8510_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = WM8510_RATES,
.formats = WM8510_FORMATS,},
.ops = &wm8510_dai_ops,
.symmetric_rates = 1,
};
static int wm8510_suspend(struct snd_soc_codec *codec)
{
wm8510_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8510_resume(struct snd_soc_codec *codec)
{
wm8510_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int wm8510_probe(struct snd_soc_codec *codec)
{
int ret;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, SND_SOC_REGMAP);
if (ret < 0) {
printk(KERN_ERR "wm8510: failed to set cache I/O: %d\n", ret);
return ret;
}
wm8510_reset(codec);
/* power on device */
wm8510_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return ret;
}
/* power down chip */
static int wm8510_remove(struct snd_soc_codec *codec)
{
wm8510_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8510 = {
.probe = wm8510_probe,
.remove = wm8510_remove,
.suspend = wm8510_suspend,
.resume = wm8510_resume,
.set_bias_level = wm8510_set_bias_level,
.controls = wm8510_snd_controls,
.num_controls = ARRAY_SIZE(wm8510_snd_controls),
.dapm_widgets = wm8510_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8510_dapm_widgets),
.dapm_routes = wm8510_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(wm8510_dapm_routes),
};
static const struct of_device_id wm8510_of_match[] = {
{ .compatible = "wlf,wm8510" },
{ },
};
static const struct regmap_config wm8510_regmap = {
.reg_bits = 7,
.val_bits = 9,
.max_register = WM8510_MONOMIX,
.reg_defaults = wm8510_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(wm8510_reg_defaults),
.cache_type = REGCACHE_RBTREE,
.volatile_reg = wm8510_volatile,
};
#if defined(CONFIG_SPI_MASTER)
static int wm8510_spi_probe(struct spi_device *spi)
{
struct wm8510_priv *wm8510;
int ret;
wm8510 = devm_kzalloc(&spi->dev, sizeof(struct wm8510_priv),
GFP_KERNEL);
if (wm8510 == NULL)
return -ENOMEM;
wm8510->regmap = devm_regmap_init_spi(spi, &wm8510_regmap);
if (IS_ERR(wm8510->regmap))
return PTR_ERR(wm8510->regmap);
spi_set_drvdata(spi, wm8510);
ret = snd_soc_register_codec(&spi->dev,
&soc_codec_dev_wm8510, &wm8510_dai, 1);
return ret;
}
static int wm8510_spi_remove(struct spi_device *spi)
{
snd_soc_unregister_codec(&spi->dev);
return 0;
}
static struct spi_driver wm8510_spi_driver = {
.driver = {
.name = "wm8510",
.owner = THIS_MODULE,
.of_match_table = wm8510_of_match,
},
.probe = wm8510_spi_probe,
.remove = wm8510_spi_remove,
};
#endif /* CONFIG_SPI_MASTER */
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static int wm8510_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8510_priv *wm8510;
int ret;
wm8510 = devm_kzalloc(&i2c->dev, sizeof(struct wm8510_priv),
GFP_KERNEL);
if (wm8510 == NULL)
return -ENOMEM;
wm8510->regmap = devm_regmap_init_i2c(i2c, &wm8510_regmap);
if (IS_ERR(wm8510->regmap))
return PTR_ERR(wm8510->regmap);
i2c_set_clientdata(i2c, wm8510);
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8510, &wm8510_dai, 1);
return ret;
}
static int wm8510_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id wm8510_i2c_id[] = {
{ "wm8510", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8510_i2c_id);
static struct i2c_driver wm8510_i2c_driver = {
.driver = {
.name = "wm8510",
.owner = THIS_MODULE,
.of_match_table = wm8510_of_match,
},
.probe = wm8510_i2c_probe,
.remove = wm8510_i2c_remove,
.id_table = wm8510_i2c_id,
};
#endif
static int __init wm8510_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8510_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8510 I2C driver: %d\n",
ret);
}
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&wm8510_spi_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8510 SPI driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8510_modinit);
static void __exit wm8510_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8510_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&wm8510_spi_driver);
#endif
}
module_exit(wm8510_exit);
MODULE_DESCRIPTION("ASoC WM8510 driver");
MODULE_AUTHOR("Liam Girdwood");
MODULE_LICENSE("GPL");
| gpl-2.0 |
venkatkamesh/android_kernel_sony_msm8994 | arch/arm/mach-pxa/colibri-evalboard.c | 2735 | 3413 | /*
* linux/arch/arm/mach-pxa/colibri-evalboard.c
*
* Support for Toradex Colibri Evaluation Carrier Board
* Daniel Mack <daniel@caiaq.de>
* Marek Vasut <marek.vasut@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/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <asm/mach/arch.h>
#include <linux/i2c.h>
#include <linux/i2c/pxa-i2c.h>
#include <mach/pxa27x.h>
#include <mach/colibri.h>
#include <linux/platform_data/mmc-pxamci.h>
#include <linux/platform_data/usb-ohci-pxa27x.h>
#include <mach/pxa27x-udc.h>
#include "generic.h"
#include "devices.h"
/******************************************************************************
* SD/MMC card controller
******************************************************************************/
#if defined(CONFIG_MMC_PXA) || defined(CONFIG_MMC_PXA_MODULE)
static struct pxamci_platform_data colibri_mci_platform_data = {
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34,
.gpio_power = -1,
.gpio_card_ro = -1,
.detect_delay_ms = 200,
};
static void __init colibri_mmc_init(void)
{
if (machine_is_colibri()) /* PXA270 Colibri */
colibri_mci_platform_data.gpio_card_detect =
GPIO0_COLIBRI_PXA270_SD_DETECT;
if (machine_is_colibri300()) /* PXA300 Colibri */
colibri_mci_platform_data.gpio_card_detect =
GPIO13_COLIBRI_PXA300_SD_DETECT;
else /* PXA320 Colibri */
colibri_mci_platform_data.gpio_card_detect =
GPIO28_COLIBRI_PXA320_SD_DETECT;
pxa_set_mci_info(&colibri_mci_platform_data);
}
#else
static inline void colibri_mmc_init(void) {}
#endif
/******************************************************************************
* USB Host
******************************************************************************/
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
static int colibri_ohci_init(struct device *dev)
{
UP2OCR = UP2OCR_HXS | UP2OCR_HXOE | UP2OCR_DPPDE | UP2OCR_DMPDE;
return 0;
}
static struct pxaohci_platform_data colibri_ohci_info = {
.port_mode = PMM_PERPORT_MODE,
.flags = ENABLE_PORT1 |
POWER_CONTROL_LOW | POWER_SENSE_LOW,
.init = colibri_ohci_init,
};
static void __init colibri_uhc_init(void)
{
/* Colibri PXA270 has two usb ports, TBA for 320 */
if (machine_is_colibri())
colibri_ohci_info.flags |= ENABLE_PORT2;
pxa_set_ohci_info(&colibri_ohci_info);
}
#else
static inline void colibri_uhc_init(void) {}
#endif
/******************************************************************************
* I2C RTC
******************************************************************************/
#if defined(CONFIG_RTC_DRV_DS1307) || defined(CONFIG_RTC_DRV_DS1307_MODULE)
static struct i2c_board_info __initdata colibri_i2c_devs[] = {
{
I2C_BOARD_INFO("m41t00", 0x68),
},
};
static void __init colibri_rtc_init(void)
{
pxa_set_i2c_info(NULL);
i2c_register_board_info(0, ARRAY_AND_SIZE(colibri_i2c_devs));
}
#else
static inline void colibri_rtc_init(void) {}
#endif
void __init colibri_evalboard_init(void)
{
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
colibri_mmc_init();
colibri_uhc_init();
colibri_rtc_init();
}
| gpl-2.0 |
vmobi-gogh/android_kernel_samsung_gogh | arch/arm/mach-s3c2440/irq.c | 2991 | 2962 | /* linux/arch/arm/mach-s3c2440/irq.c
*
* Copyright (c) 2003-2004 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/sysdev.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <mach/regs-irq.h>
#include <mach/regs-gpio.h>
#include <plat/cpu.h>
#include <plat/pm.h>
#include <plat/irq.h>
/* WDT/AC97 */
static void s3c_irq_demux_wdtac97(unsigned int irq,
struct irq_desc *desc)
{
unsigned int subsrc, submsk;
/* read the current pending interrupts, and the mask
* for what it is available */
subsrc = __raw_readl(S3C2410_SUBSRCPND);
submsk = __raw_readl(S3C2410_INTSUBMSK);
subsrc &= ~submsk;
subsrc >>= 13;
subsrc &= 3;
if (subsrc != 0) {
if (subsrc & 1) {
generic_handle_irq(IRQ_S3C2440_WDT);
}
if (subsrc & 2) {
generic_handle_irq(IRQ_S3C2440_AC97);
}
}
}
#define INTMSK_WDT (1UL << (IRQ_WDT - IRQ_EINT0))
static void
s3c_irq_wdtac97_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_WDT, 3 << 13);
}
static void
s3c_irq_wdtac97_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_WDT);
}
static void
s3c_irq_wdtac97_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_WDT, 3 << 13);
}
static struct irq_chip s3c_irq_wdtac97 = {
.irq_mask = s3c_irq_wdtac97_mask,
.irq_unmask = s3c_irq_wdtac97_unmask,
.irq_ack = s3c_irq_wdtac97_ack,
};
static int s3c2440_irq_add(struct sys_device *sysdev)
{
unsigned int irqno;
printk("S3C2440: IRQ Support\n");
/* add new chained handler for wdt, ac7 */
irq_set_chip_and_handler(IRQ_WDT, &s3c_irq_level_chip,
handle_level_irq);
irq_set_chained_handler(IRQ_WDT, s3c_irq_demux_wdtac97);
for (irqno = IRQ_S3C2440_WDT; irqno <= IRQ_S3C2440_AC97; irqno++) {
irq_set_chip_and_handler(irqno, &s3c_irq_wdtac97,
handle_level_irq);
set_irq_flags(irqno, IRQF_VALID);
}
return 0;
}
static struct sysdev_driver s3c2440_irq_driver = {
.add = s3c2440_irq_add,
};
static int s3c2440_irq_init(void)
{
return sysdev_driver_register(&s3c2440_sysclass, &s3c2440_irq_driver);
}
arch_initcall(s3c2440_irq_init);
| gpl-2.0 |
vegetalte-dev/android_kernel_bq_vegetalte_LP | drivers/tty/vt/vt_ioctl.c | 3247 | 34103 | /*
* Copyright (C) 1992 obz under the linux copyright
*
* Dynamic diacritical handling - aeb@cwi.nl - Dec 1993
* Dynamic keymap and string allocation - aeb@cwi.nl - May 1994
* Restrict VT switching via ioctl() - grif@cs.ucr.edu - Dec 1995
* Some code moved for less code duplication - Andi Kleen - Mar 1997
* Check put/get_user, cleanups - acme@conectiva.com.br - Jun 2001
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/timer.h>
#include <linux/kernel.h>
#include <linux/compat.h>
#include <linux/module.h>
#include <linux/kd.h>
#include <linux/vt.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/major.h>
#include <linux/fs.h>
#include <linux/console.h>
#include <linux/consolemap.h>
#include <linux/signal.h>
#include <linux/suspend.h>
#include <linux/timex.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/kbd_kern.h>
#include <linux/vt_kern.h>
#include <linux/kbd_diacr.h>
#include <linux/selection.h>
char vt_dont_switch;
extern struct tty_driver *console_driver;
#define VT_IS_IN_USE(i) (console_driver->ttys[i] && console_driver->ttys[i]->count)
#define VT_BUSY(i) (VT_IS_IN_USE(i) || i == fg_console || vc_cons[i].d == sel_cons)
/*
* Console (vt and kd) routines, as defined by USL SVR4 manual, and by
* experimentation and study of X386 SYSV handling.
*
* One point of difference: SYSV vt's are /dev/vtX, which X >= 0, and
* /dev/console is a separate ttyp. Under Linux, /dev/tty0 is /dev/console,
* and the vc start at /dev/ttyX, X >= 1. We maintain that here, so we will
* always treat our set of vt as numbered 1..MAX_NR_CONSOLES (corresponding to
* ttys 0..MAX_NR_CONSOLES-1). Explicitly naming VT 0 is illegal, but using
* /dev/tty0 (fg_console) as a target is legal, since an implicit aliasing
* to the current console is done by the main ioctl code.
*/
#ifdef CONFIG_X86
#include <linux/syscalls.h>
#endif
static void complete_change_console(struct vc_data *vc);
/*
* User space VT_EVENT handlers
*/
struct vt_event_wait {
struct list_head list;
struct vt_event event;
int done;
};
static LIST_HEAD(vt_events);
static DEFINE_SPINLOCK(vt_event_lock);
static DECLARE_WAIT_QUEUE_HEAD(vt_event_waitqueue);
/**
* vt_event_post
* @event: the event that occurred
* @old: old console
* @new: new console
*
* Post an VT event to interested VT handlers
*/
void vt_event_post(unsigned int event, unsigned int old, unsigned int new)
{
struct list_head *pos, *head;
unsigned long flags;
int wake = 0;
spin_lock_irqsave(&vt_event_lock, flags);
head = &vt_events;
list_for_each(pos, head) {
struct vt_event_wait *ve = list_entry(pos,
struct vt_event_wait, list);
if (!(ve->event.event & event))
continue;
ve->event.event = event;
/* kernel view is consoles 0..n-1, user space view is
console 1..n with 0 meaning current, so we must bias */
ve->event.oldev = old + 1;
ve->event.newev = new + 1;
wake = 1;
ve->done = 1;
}
spin_unlock_irqrestore(&vt_event_lock, flags);
if (wake)
wake_up_interruptible(&vt_event_waitqueue);
}
static void __vt_event_queue(struct vt_event_wait *vw)
{
unsigned long flags;
/* Prepare the event */
INIT_LIST_HEAD(&vw->list);
vw->done = 0;
/* Queue our event */
spin_lock_irqsave(&vt_event_lock, flags);
list_add(&vw->list, &vt_events);
spin_unlock_irqrestore(&vt_event_lock, flags);
}
static void __vt_event_wait(struct vt_event_wait *vw)
{
/* Wait for it to pass */
wait_event_interruptible(vt_event_waitqueue, vw->done);
}
static void __vt_event_dequeue(struct vt_event_wait *vw)
{
unsigned long flags;
/* Dequeue it */
spin_lock_irqsave(&vt_event_lock, flags);
list_del(&vw->list);
spin_unlock_irqrestore(&vt_event_lock, flags);
}
/**
* vt_event_wait - wait for an event
* @vw: our event
*
* Waits for an event to occur which completes our vt_event_wait
* structure. On return the structure has wv->done set to 1 for success
* or 0 if some event such as a signal ended the wait.
*/
static void vt_event_wait(struct vt_event_wait *vw)
{
__vt_event_queue(vw);
__vt_event_wait(vw);
__vt_event_dequeue(vw);
}
/**
* vt_event_wait_ioctl - event ioctl handler
* @arg: argument to ioctl
*
* Implement the VT_WAITEVENT ioctl using the VT event interface
*/
static int vt_event_wait_ioctl(struct vt_event __user *event)
{
struct vt_event_wait vw;
if (copy_from_user(&vw.event, event, sizeof(struct vt_event)))
return -EFAULT;
/* Highest supported event for now */
if (vw.event.event & ~VT_MAX_EVENT)
return -EINVAL;
vt_event_wait(&vw);
/* If it occurred report it */
if (vw.done) {
if (copy_to_user(event, &vw.event, sizeof(struct vt_event)))
return -EFAULT;
return 0;
}
return -EINTR;
}
/**
* vt_waitactive - active console wait
* @event: event code
* @n: new console
*
* Helper for event waits. Used to implement the legacy
* event waiting ioctls in terms of events
*/
int vt_waitactive(int n)
{
struct vt_event_wait vw;
do {
vw.event.event = VT_EVENT_SWITCH;
__vt_event_queue(&vw);
if (n == fg_console + 1) {
__vt_event_dequeue(&vw);
break;
}
__vt_event_wait(&vw);
__vt_event_dequeue(&vw);
if (vw.done == 0)
return -EINTR;
} while (vw.event.newev != n);
return 0;
}
/*
* these are the valid i/o ports we're allowed to change. they map all the
* video ports
*/
#define GPFIRST 0x3b4
#define GPLAST 0x3df
#define GPNUM (GPLAST - GPFIRST + 1)
static inline int
do_fontx_ioctl(int cmd, struct consolefontdesc __user *user_cfd, int perm, struct console_font_op *op)
{
struct consolefontdesc cfdarg;
int i;
if (copy_from_user(&cfdarg, user_cfd, sizeof(struct consolefontdesc)))
return -EFAULT;
switch (cmd) {
case PIO_FONTX:
if (!perm)
return -EPERM;
op->op = KD_FONT_OP_SET;
op->flags = KD_FONT_FLAG_OLD;
op->width = 8;
op->height = cfdarg.charheight;
op->charcount = cfdarg.charcount;
op->data = cfdarg.chardata;
return con_font_op(vc_cons[fg_console].d, op);
case GIO_FONTX: {
op->op = KD_FONT_OP_GET;
op->flags = KD_FONT_FLAG_OLD;
op->width = 8;
op->height = cfdarg.charheight;
op->charcount = cfdarg.charcount;
op->data = cfdarg.chardata;
i = con_font_op(vc_cons[fg_console].d, op);
if (i)
return i;
cfdarg.charheight = op->height;
cfdarg.charcount = op->charcount;
if (copy_to_user(user_cfd, &cfdarg, sizeof(struct consolefontdesc)))
return -EFAULT;
return 0;
}
}
return -EINVAL;
}
static inline int
do_unimap_ioctl(int cmd, struct unimapdesc __user *user_ud, int perm, struct vc_data *vc)
{
struct unimapdesc tmp;
if (copy_from_user(&tmp, user_ud, sizeof tmp))
return -EFAULT;
if (tmp.entries)
if (!access_ok(VERIFY_WRITE, tmp.entries,
tmp.entry_ct*sizeof(struct unipair)))
return -EFAULT;
switch (cmd) {
case PIO_UNIMAP:
if (!perm)
return -EPERM;
return con_set_unimap(vc, tmp.entry_ct, tmp.entries);
case GIO_UNIMAP:
if (!perm && fg_console != vc->vc_num)
return -EPERM;
return con_get_unimap(vc, tmp.entry_ct, &(user_ud->entry_ct), tmp.entries);
}
return 0;
}
/* deallocate a single console, if possible (leave 0) */
static int vt_disallocate(unsigned int vc_num)
{
struct vc_data *vc = NULL;
int ret = 0;
console_lock();
if (VT_BUSY(vc_num))
ret = -EBUSY;
else if (vc_num)
vc = vc_deallocate(vc_num);
console_unlock();
if (vc && vc_num >= MIN_NR_CONSOLES) {
tty_port_destroy(&vc->port);
kfree(vc);
}
return ret;
}
/* deallocate all unused consoles, but leave 0 */
static void vt_disallocate_all(void)
{
struct vc_data *vc[MAX_NR_CONSOLES];
int i;
console_lock();
for (i = 1; i < MAX_NR_CONSOLES; i++)
if (!VT_BUSY(i))
vc[i] = vc_deallocate(i);
else
vc[i] = NULL;
console_unlock();
for (i = 1; i < MAX_NR_CONSOLES; i++) {
if (vc[i] && i >= MIN_NR_CONSOLES) {
tty_port_destroy(&vc[i]->port);
kfree(vc[i]);
}
}
}
/*
* We handle the console-specific ioctl's here. We allow the
* capability to modify any console, not just the fg_console.
*/
int vt_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct vc_data *vc = tty->driver_data;
struct console_font_op op; /* used in multiple places here */
unsigned int console;
unsigned char ucval;
unsigned int uival;
void __user *up = (void __user *)arg;
int i, perm;
int ret = 0;
console = vc->vc_num;
if (!vc_cons_allocated(console)) { /* impossible? */
ret = -ENOIOCTLCMD;
goto out;
}
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = 0;
if (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))
perm = 1;
switch (cmd) {
case TIOCLINUX:
ret = tioclinux(tty, arg);
break;
case KIOCSOUND:
if (!perm)
return -EPERM;
/*
* The use of PIT_TICK_RATE is historic, it used to be
* the platform-dependent CLOCK_TICK_RATE between 2.6.12
* and 2.6.36, which was a minor but unfortunate ABI
* change. kd_mksound is locked by the input layer.
*/
if (arg)
arg = PIT_TICK_RATE / arg;
kd_mksound(arg, 0);
break;
case KDMKTONE:
if (!perm)
return -EPERM;
{
unsigned int ticks, count;
/*
* Generate the tone for the appropriate number of ticks.
* If the time is zero, turn off sound ourselves.
*/
ticks = HZ * ((arg >> 16) & 0xffff) / 1000;
count = ticks ? (arg & 0xffff) : 0;
if (count)
count = PIT_TICK_RATE / count;
kd_mksound(count, ticks);
break;
}
case KDGKBTYPE:
/*
* this is naïve.
*/
ucval = KB_101;
ret = put_user(ucval, (char __user *)arg);
break;
/*
* These cannot be implemented on any machine that implements
* ioperm() in user level (such as Alpha PCs) or not at all.
*
* XXX: you should never use these, just call ioperm directly..
*/
#ifdef CONFIG_X86
case KDADDIO:
case KDDELIO:
/*
* KDADDIO and KDDELIO may be able to add ports beyond what
* we reject here, but to be safe...
*
* These are locked internally via sys_ioperm
*/
if (arg < GPFIRST || arg > GPLAST) {
ret = -EINVAL;
break;
}
ret = sys_ioperm(arg, 1, (cmd == KDADDIO)) ? -ENXIO : 0;
break;
case KDENABIO:
case KDDISABIO:
ret = sys_ioperm(GPFIRST, GPNUM,
(cmd == KDENABIO)) ? -ENXIO : 0;
break;
#endif
/* Linux m68k/i386 interface for setting the keyboard delay/repeat rate */
case KDKBDREP:
{
struct kbd_repeat kbrep;
if (!capable(CAP_SYS_TTY_CONFIG))
return -EPERM;
if (copy_from_user(&kbrep, up, sizeof(struct kbd_repeat))) {
ret = -EFAULT;
break;
}
ret = kbd_rate(&kbrep);
if (ret)
break;
if (copy_to_user(up, &kbrep, sizeof(struct kbd_repeat)))
ret = -EFAULT;
break;
}
case KDSETMODE:
/*
* currently, setting the mode from KD_TEXT to KD_GRAPHICS
* doesn't do a whole lot. i'm not sure if it should do any
* restoration of modes or what...
*
* XXX It should at least call into the driver, fbdev's definitely
* need to restore their engine state. --BenH
*/
if (!perm)
return -EPERM;
switch (arg) {
case KD_GRAPHICS:
break;
case KD_TEXT0:
case KD_TEXT1:
arg = KD_TEXT;
case KD_TEXT:
break;
default:
ret = -EINVAL;
goto out;
}
/* FIXME: this needs the console lock extending */
if (vc->vc_mode == (unsigned char) arg)
break;
vc->vc_mode = (unsigned char) arg;
if (console != fg_console)
break;
/*
* explicitly blank/unblank the screen if switching modes
*/
console_lock();
if (arg == KD_TEXT)
do_unblank_screen(1);
else
do_blank_screen(1);
console_unlock();
break;
case KDGETMODE:
uival = vc->vc_mode;
goto setint;
case KDMAPDISP:
case KDUNMAPDISP:
/*
* these work like a combination of mmap and KDENABIO.
* this could be easily finished.
*/
ret = -EINVAL;
break;
case KDSKBMODE:
if (!perm)
return -EPERM;
ret = vt_do_kdskbmode(console, arg);
if (ret == 0)
tty_ldisc_flush(tty);
break;
case KDGKBMODE:
uival = vt_do_kdgkbmode(console);
ret = put_user(uival, (int __user *)arg);
break;
/* this could be folded into KDSKBMODE, but for compatibility
reasons it is not so easy to fold KDGKBMETA into KDGKBMODE */
case KDSKBMETA:
ret = vt_do_kdskbmeta(console, arg);
break;
case KDGKBMETA:
/* FIXME: should review whether this is worth locking */
uival = vt_do_kdgkbmeta(console);
setint:
ret = put_user(uival, (int __user *)arg);
break;
case KDGETKEYCODE:
case KDSETKEYCODE:
if(!capable(CAP_SYS_TTY_CONFIG))
perm = 0;
ret = vt_do_kbkeycode_ioctl(cmd, up, perm);
break;
case KDGKBENT:
case KDSKBENT:
ret = vt_do_kdsk_ioctl(cmd, up, perm, console);
break;
case KDGKBSENT:
case KDSKBSENT:
ret = vt_do_kdgkb_ioctl(cmd, up, perm);
break;
/* Diacritical processing. Handled in keyboard.c as it has
to operate on the keyboard locks and structures */
case KDGKBDIACR:
case KDGKBDIACRUC:
case KDSKBDIACR:
case KDSKBDIACRUC:
ret = vt_do_diacrit(cmd, up, perm);
break;
/* the ioctls below read/set the flags usually shown in the leds */
/* don't use them - they will go away without warning */
case KDGKBLED:
case KDSKBLED:
case KDGETLED:
case KDSETLED:
ret = vt_do_kdskled(console, cmd, arg, perm);
break;
/*
* A process can indicate its willingness to accept signals
* generated by pressing an appropriate key combination.
* Thus, one can have a daemon that e.g. spawns a new console
* upon a keypress and then changes to it.
* See also the kbrequest field of inittab(5).
*/
case KDSIGACCEPT:
{
if (!perm || !capable(CAP_KILL))
return -EPERM;
if (!valid_signal(arg) || arg < 1 || arg == SIGKILL)
ret = -EINVAL;
else {
spin_lock_irq(&vt_spawn_con.lock);
put_pid(vt_spawn_con.pid);
vt_spawn_con.pid = get_pid(task_pid(current));
vt_spawn_con.sig = arg;
spin_unlock_irq(&vt_spawn_con.lock);
}
break;
}
case VT_SETMODE:
{
struct vt_mode tmp;
if (!perm)
return -EPERM;
if (copy_from_user(&tmp, up, sizeof(struct vt_mode))) {
ret = -EFAULT;
goto out;
}
if (tmp.mode != VT_AUTO && tmp.mode != VT_PROCESS) {
ret = -EINVAL;
goto out;
}
console_lock();
vc->vt_mode = tmp;
/* the frsig is ignored, so we set it to 0 */
vc->vt_mode.frsig = 0;
put_pid(vc->vt_pid);
vc->vt_pid = get_pid(task_pid(current));
/* no switch is required -- saw@shade.msu.ru */
vc->vt_newvt = -1;
console_unlock();
break;
}
case VT_GETMODE:
{
struct vt_mode tmp;
int rc;
console_lock();
memcpy(&tmp, &vc->vt_mode, sizeof(struct vt_mode));
console_unlock();
rc = copy_to_user(up, &tmp, sizeof(struct vt_mode));
if (rc)
ret = -EFAULT;
break;
}
/*
* Returns global vt state. Note that VT 0 is always open, since
* it's an alias for the current VT, and people can't use it here.
* We cannot return state for more than 16 VTs, since v_state is short.
*/
case VT_GETSTATE:
{
struct vt_stat __user *vtstat = up;
unsigned short state, mask;
/* Review: FIXME: Console lock ? */
if (put_user(fg_console + 1, &vtstat->v_active))
ret = -EFAULT;
else {
state = 1; /* /dev/tty0 is always open */
for (i = 0, mask = 2; i < MAX_NR_CONSOLES && mask;
++i, mask <<= 1)
if (VT_IS_IN_USE(i))
state |= mask;
ret = put_user(state, &vtstat->v_state);
}
break;
}
/*
* Returns the first available (non-opened) console.
*/
case VT_OPENQRY:
/* FIXME: locking ? - but then this is a stupid API */
for (i = 0; i < MAX_NR_CONSOLES; ++i)
if (! VT_IS_IN_USE(i))
break;
uival = i < MAX_NR_CONSOLES ? (i+1) : -1;
goto setint;
/*
* ioctl(fd, VT_ACTIVATE, num) will cause us to switch to vt # num,
* with num >= 1 (switches to vt 0, our console, are not allowed, just
* to preserve sanity).
*/
case VT_ACTIVATE:
if (!perm)
return -EPERM;
if (arg == 0 || arg > MAX_NR_CONSOLES)
ret = -ENXIO;
else {
arg--;
console_lock();
ret = vc_allocate(arg);
console_unlock();
if (ret)
break;
set_console(arg);
}
break;
case VT_SETACTIVATE:
{
struct vt_setactivate vsa;
if (!perm)
return -EPERM;
if (copy_from_user(&vsa, (struct vt_setactivate __user *)arg,
sizeof(struct vt_setactivate))) {
ret = -EFAULT;
goto out;
}
if (vsa.console == 0 || vsa.console > MAX_NR_CONSOLES)
ret = -ENXIO;
else {
vsa.console--;
console_lock();
ret = vc_allocate(vsa.console);
if (ret == 0) {
struct vc_data *nvc;
/* This is safe providing we don't drop the
console sem between vc_allocate and
finishing referencing nvc */
nvc = vc_cons[vsa.console].d;
nvc->vt_mode = vsa.mode;
nvc->vt_mode.frsig = 0;
put_pid(nvc->vt_pid);
nvc->vt_pid = get_pid(task_pid(current));
}
console_unlock();
if (ret)
break;
/* Commence switch and lock */
/* Review set_console locks */
set_console(vsa.console);
}
break;
}
/*
* wait until the specified VT has been activated
*/
case VT_WAITACTIVE:
if (!perm)
return -EPERM;
if (arg == 0 || arg > MAX_NR_CONSOLES)
ret = -ENXIO;
else
ret = vt_waitactive(arg);
break;
/*
* If a vt is under process control, the kernel will not switch to it
* immediately, but postpone the operation until the process calls this
* ioctl, allowing the switch to complete.
*
* According to the X sources this is the behavior:
* 0: pending switch-from not OK
* 1: pending switch-from OK
* 2: completed switch-to OK
*/
case VT_RELDISP:
if (!perm)
return -EPERM;
console_lock();
if (vc->vt_mode.mode != VT_PROCESS) {
console_unlock();
ret = -EINVAL;
break;
}
/*
* Switching-from response
*/
if (vc->vt_newvt >= 0) {
if (arg == 0)
/*
* Switch disallowed, so forget we were trying
* to do it.
*/
vc->vt_newvt = -1;
else {
/*
* The current vt has been released, so
* complete the switch.
*/
int newvt;
newvt = vc->vt_newvt;
vc->vt_newvt = -1;
ret = vc_allocate(newvt);
if (ret) {
console_unlock();
break;
}
/*
* When we actually do the console switch,
* make sure we are atomic with respect to
* other console switches..
*/
complete_change_console(vc_cons[newvt].d);
}
} else {
/*
* Switched-to response
*/
/*
* If it's just an ACK, ignore it
*/
if (arg != VT_ACKACQ)
ret = -EINVAL;
}
console_unlock();
break;
/*
* Disallocate memory associated to VT (but leave VT1)
*/
case VT_DISALLOCATE:
if (arg > MAX_NR_CONSOLES) {
ret = -ENXIO;
break;
}
if (arg == 0)
vt_disallocate_all();
else
ret = vt_disallocate(--arg);
break;
case VT_RESIZE:
{
struct vt_sizes __user *vtsizes = up;
struct vc_data *vc;
ushort ll,cc;
if (!perm)
return -EPERM;
if (get_user(ll, &vtsizes->v_rows) ||
get_user(cc, &vtsizes->v_cols))
ret = -EFAULT;
else {
console_lock();
for (i = 0; i < MAX_NR_CONSOLES; i++) {
vc = vc_cons[i].d;
if (vc) {
vc->vc_resize_user = 1;
/* FIXME: review v tty lock */
vc_resize(vc_cons[i].d, cc, ll);
}
}
console_unlock();
}
break;
}
case VT_RESIZEX:
{
struct vt_consize __user *vtconsize = up;
ushort ll,cc,vlin,clin,vcol,ccol;
if (!perm)
return -EPERM;
if (!access_ok(VERIFY_READ, vtconsize,
sizeof(struct vt_consize))) {
ret = -EFAULT;
break;
}
/* FIXME: Should check the copies properly */
__get_user(ll, &vtconsize->v_rows);
__get_user(cc, &vtconsize->v_cols);
__get_user(vlin, &vtconsize->v_vlin);
__get_user(clin, &vtconsize->v_clin);
__get_user(vcol, &vtconsize->v_vcol);
__get_user(ccol, &vtconsize->v_ccol);
vlin = vlin ? vlin : vc->vc_scan_lines;
if (clin) {
if (ll) {
if (ll != vlin/clin) {
/* Parameters don't add up */
ret = -EINVAL;
break;
}
} else
ll = vlin/clin;
}
if (vcol && ccol) {
if (cc) {
if (cc != vcol/ccol) {
ret = -EINVAL;
break;
}
} else
cc = vcol/ccol;
}
if (clin > 32) {
ret = -EINVAL;
break;
}
for (i = 0; i < MAX_NR_CONSOLES; i++) {
if (!vc_cons[i].d)
continue;
console_lock();
if (vlin)
vc_cons[i].d->vc_scan_lines = vlin;
if (clin)
vc_cons[i].d->vc_font.height = clin;
vc_cons[i].d->vc_resize_user = 1;
vc_resize(vc_cons[i].d, cc, ll);
console_unlock();
}
break;
}
case PIO_FONT: {
if (!perm)
return -EPERM;
op.op = KD_FONT_OP_SET;
op.flags = KD_FONT_FLAG_OLD | KD_FONT_FLAG_DONT_RECALC; /* Compatibility */
op.width = 8;
op.height = 0;
op.charcount = 256;
op.data = up;
ret = con_font_op(vc_cons[fg_console].d, &op);
break;
}
case GIO_FONT: {
op.op = KD_FONT_OP_GET;
op.flags = KD_FONT_FLAG_OLD;
op.width = 8;
op.height = 32;
op.charcount = 256;
op.data = up;
ret = con_font_op(vc_cons[fg_console].d, &op);
break;
}
case PIO_CMAP:
if (!perm)
ret = -EPERM;
else
ret = con_set_cmap(up);
break;
case GIO_CMAP:
ret = con_get_cmap(up);
break;
case PIO_FONTX:
case GIO_FONTX:
ret = do_fontx_ioctl(cmd, up, perm, &op);
break;
case PIO_FONTRESET:
{
if (!perm)
return -EPERM;
#ifdef BROKEN_GRAPHICS_PROGRAMS
/* With BROKEN_GRAPHICS_PROGRAMS defined, the default
font is not saved. */
ret = -ENOSYS;
break;
#else
{
op.op = KD_FONT_OP_SET_DEFAULT;
op.data = NULL;
ret = con_font_op(vc_cons[fg_console].d, &op);
if (ret)
break;
console_lock();
con_set_default_unimap(vc_cons[fg_console].d);
console_unlock();
break;
}
#endif
}
case KDFONTOP: {
if (copy_from_user(&op, up, sizeof(op))) {
ret = -EFAULT;
break;
}
if (!perm && op.op != KD_FONT_OP_GET)
return -EPERM;
ret = con_font_op(vc, &op);
if (ret)
break;
if (copy_to_user(up, &op, sizeof(op)))
ret = -EFAULT;
break;
}
case PIO_SCRNMAP:
if (!perm)
ret = -EPERM;
else
ret = con_set_trans_old(up);
break;
case GIO_SCRNMAP:
ret = con_get_trans_old(up);
break;
case PIO_UNISCRNMAP:
if (!perm)
ret = -EPERM;
else
ret = con_set_trans_new(up);
break;
case GIO_UNISCRNMAP:
ret = con_get_trans_new(up);
break;
case PIO_UNIMAPCLR:
{ struct unimapinit ui;
if (!perm)
return -EPERM;
ret = copy_from_user(&ui, up, sizeof(struct unimapinit));
if (ret)
ret = -EFAULT;
else
con_clear_unimap(vc, &ui);
break;
}
case PIO_UNIMAP:
case GIO_UNIMAP:
ret = do_unimap_ioctl(cmd, up, perm, vc);
break;
case VT_LOCKSWITCH:
if (!capable(CAP_SYS_TTY_CONFIG))
return -EPERM;
vt_dont_switch = 1;
break;
case VT_UNLOCKSWITCH:
if (!capable(CAP_SYS_TTY_CONFIG))
return -EPERM;
vt_dont_switch = 0;
break;
case VT_GETHIFONTMASK:
ret = put_user(vc->vc_hi_font_mask,
(unsigned short __user *)arg);
break;
case VT_WAITEVENT:
ret = vt_event_wait_ioctl((struct vt_event __user *)arg);
break;
default:
ret = -ENOIOCTLCMD;
}
out:
return ret;
}
void reset_vc(struct vc_data *vc)
{
vc->vc_mode = KD_TEXT;
vt_reset_unicode(vc->vc_num);
vc->vt_mode.mode = VT_AUTO;
vc->vt_mode.waitv = 0;
vc->vt_mode.relsig = 0;
vc->vt_mode.acqsig = 0;
vc->vt_mode.frsig = 0;
put_pid(vc->vt_pid);
vc->vt_pid = NULL;
vc->vt_newvt = -1;
if (!in_interrupt()) /* Via keyboard.c:SAK() - akpm */
reset_palette(vc);
}
void vc_SAK(struct work_struct *work)
{
struct vc *vc_con =
container_of(work, struct vc, SAK_work);
struct vc_data *vc;
struct tty_struct *tty;
console_lock();
vc = vc_con->d;
if (vc) {
/* FIXME: review tty ref counting */
tty = vc->port.tty;
/*
* SAK should also work in all raw modes and reset
* them properly.
*/
if (tty)
__do_SAK(tty);
reset_vc(vc);
}
console_unlock();
}
#ifdef CONFIG_COMPAT
struct compat_consolefontdesc {
unsigned short charcount; /* characters in font (256 or 512) */
unsigned short charheight; /* scan lines per character (1-32) */
compat_caddr_t chardata; /* font data in expanded form */
};
static inline int
compat_fontx_ioctl(int cmd, struct compat_consolefontdesc __user *user_cfd,
int perm, struct console_font_op *op)
{
struct compat_consolefontdesc cfdarg;
int i;
if (copy_from_user(&cfdarg, user_cfd, sizeof(struct compat_consolefontdesc)))
return -EFAULT;
switch (cmd) {
case PIO_FONTX:
if (!perm)
return -EPERM;
op->op = KD_FONT_OP_SET;
op->flags = KD_FONT_FLAG_OLD;
op->width = 8;
op->height = cfdarg.charheight;
op->charcount = cfdarg.charcount;
op->data = compat_ptr(cfdarg.chardata);
return con_font_op(vc_cons[fg_console].d, op);
case GIO_FONTX:
op->op = KD_FONT_OP_GET;
op->flags = KD_FONT_FLAG_OLD;
op->width = 8;
op->height = cfdarg.charheight;
op->charcount = cfdarg.charcount;
op->data = compat_ptr(cfdarg.chardata);
i = con_font_op(vc_cons[fg_console].d, op);
if (i)
return i;
cfdarg.charheight = op->height;
cfdarg.charcount = op->charcount;
if (copy_to_user(user_cfd, &cfdarg, sizeof(struct compat_consolefontdesc)))
return -EFAULT;
return 0;
}
return -EINVAL;
}
struct compat_console_font_op {
compat_uint_t op; /* operation code KD_FONT_OP_* */
compat_uint_t flags; /* KD_FONT_FLAG_* */
compat_uint_t width, height; /* font size */
compat_uint_t charcount;
compat_caddr_t data; /* font data with height fixed to 32 */
};
static inline int
compat_kdfontop_ioctl(struct compat_console_font_op __user *fontop,
int perm, struct console_font_op *op, struct vc_data *vc)
{
int i;
if (copy_from_user(op, fontop, sizeof(struct compat_console_font_op)))
return -EFAULT;
if (!perm && op->op != KD_FONT_OP_GET)
return -EPERM;
op->data = compat_ptr(((struct compat_console_font_op *)op)->data);
i = con_font_op(vc, op);
if (i)
return i;
((struct compat_console_font_op *)op)->data = (unsigned long)op->data;
if (copy_to_user(fontop, op, sizeof(struct compat_console_font_op)))
return -EFAULT;
return 0;
}
struct compat_unimapdesc {
unsigned short entry_ct;
compat_caddr_t entries;
};
static inline int
compat_unimap_ioctl(unsigned int cmd, struct compat_unimapdesc __user *user_ud,
int perm, struct vc_data *vc)
{
struct compat_unimapdesc tmp;
struct unipair __user *tmp_entries;
if (copy_from_user(&tmp, user_ud, sizeof tmp))
return -EFAULT;
tmp_entries = compat_ptr(tmp.entries);
if (tmp_entries)
if (!access_ok(VERIFY_WRITE, tmp_entries,
tmp.entry_ct*sizeof(struct unipair)))
return -EFAULT;
switch (cmd) {
case PIO_UNIMAP:
if (!perm)
return -EPERM;
return con_set_unimap(vc, tmp.entry_ct, tmp_entries);
case GIO_UNIMAP:
if (!perm && fg_console != vc->vc_num)
return -EPERM;
return con_get_unimap(vc, tmp.entry_ct, &(user_ud->entry_ct), tmp_entries);
}
return 0;
}
long vt_compat_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct vc_data *vc = tty->driver_data;
struct console_font_op op; /* used in multiple places here */
unsigned int console;
void __user *up = (void __user *)arg;
int perm;
int ret = 0;
console = vc->vc_num;
if (!vc_cons_allocated(console)) { /* impossible? */
ret = -ENOIOCTLCMD;
goto out;
}
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = 0;
if (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))
perm = 1;
switch (cmd) {
/*
* these need special handlers for incompatible data structures
*/
case PIO_FONTX:
case GIO_FONTX:
ret = compat_fontx_ioctl(cmd, up, perm, &op);
break;
case KDFONTOP:
ret = compat_kdfontop_ioctl(up, perm, &op, vc);
break;
case PIO_UNIMAP:
case GIO_UNIMAP:
ret = compat_unimap_ioctl(cmd, up, perm, vc);
break;
/*
* all these treat 'arg' as an integer
*/
case KIOCSOUND:
case KDMKTONE:
#ifdef CONFIG_X86
case KDADDIO:
case KDDELIO:
#endif
case KDSETMODE:
case KDMAPDISP:
case KDUNMAPDISP:
case KDSKBMODE:
case KDSKBMETA:
case KDSKBLED:
case KDSETLED:
case KDSIGACCEPT:
case VT_ACTIVATE:
case VT_WAITACTIVE:
case VT_RELDISP:
case VT_DISALLOCATE:
case VT_RESIZE:
case VT_RESIZEX:
goto fallback;
/*
* the rest has a compatible data structure behind arg,
* but we have to convert it to a proper 64 bit pointer.
*/
default:
arg = (unsigned long)compat_ptr(arg);
goto fallback;
}
out:
return ret;
fallback:
return vt_ioctl(tty, cmd, arg);
}
#endif /* CONFIG_COMPAT */
/*
* Performs the back end of a vt switch. Called under the console
* semaphore.
*/
static void complete_change_console(struct vc_data *vc)
{
unsigned char old_vc_mode;
int old = fg_console;
last_console = fg_console;
/*
* If we're switching, we could be going from KD_GRAPHICS to
* KD_TEXT mode or vice versa, which means we need to blank or
* unblank the screen later.
*/
old_vc_mode = vc_cons[fg_console].d->vc_mode;
switch_screen(vc);
/*
* This can't appear below a successful kill_pid(). If it did,
* then the *blank_screen operation could occur while X, having
* received acqsig, is waking up on another processor. This
* condition can lead to overlapping accesses to the VGA range
* and the framebuffer (causing system lockups).
*
* To account for this we duplicate this code below only if the
* controlling process is gone and we've called reset_vc.
*/
if (old_vc_mode != vc->vc_mode) {
if (vc->vc_mode == KD_TEXT)
do_unblank_screen(1);
else
do_blank_screen(1);
}
/*
* If this new console is under process control, send it a signal
* telling it that it has acquired. Also check if it has died and
* clean up (similar to logic employed in change_console())
*/
if (vc->vt_mode.mode == VT_PROCESS) {
/*
* Send the signal as privileged - kill_pid() will
* tell us if the process has gone or something else
* is awry
*/
if (kill_pid(vc->vt_pid, vc->vt_mode.acqsig, 1) != 0) {
/*
* The controlling process has died, so we revert back to
* normal operation. In this case, we'll also change back
* to KD_TEXT mode. I'm not sure if this is strictly correct
* but it saves the agony when the X server dies and the screen
* remains blanked due to KD_GRAPHICS! It would be nice to do
* this outside of VT_PROCESS but there is no single process
* to account for and tracking tty count may be undesirable.
*/
reset_vc(vc);
if (old_vc_mode != vc->vc_mode) {
if (vc->vc_mode == KD_TEXT)
do_unblank_screen(1);
else
do_blank_screen(1);
}
}
}
/*
* Wake anyone waiting for their VT to activate
*/
vt_event_post(VT_EVENT_SWITCH, old, vc->vc_num);
return;
}
/*
* Performs the front-end of a vt switch
*/
void change_console(struct vc_data *new_vc)
{
struct vc_data *vc;
if (!new_vc || new_vc->vc_num == fg_console || vt_dont_switch)
return;
/*
* If this vt is in process mode, then we need to handshake with
* that process before switching. Essentially, we store where that
* vt wants to switch to and wait for it to tell us when it's done
* (via VT_RELDISP ioctl).
*
* We also check to see if the controlling process still exists.
* If it doesn't, we reset this vt to auto mode and continue.
* This is a cheap way to track process control. The worst thing
* that can happen is: we send a signal to a process, it dies, and
* the switch gets "lost" waiting for a response; hopefully, the
* user will try again, we'll detect the process is gone (unless
* the user waits just the right amount of time :-) and revert the
* vt to auto control.
*/
vc = vc_cons[fg_console].d;
if (vc->vt_mode.mode == VT_PROCESS) {
/*
* Send the signal as privileged - kill_pid() will
* tell us if the process has gone or something else
* is awry.
*
* We need to set vt_newvt *before* sending the signal or we
* have a race.
*/
vc->vt_newvt = new_vc->vc_num;
if (kill_pid(vc->vt_pid, vc->vt_mode.relsig, 1) == 0) {
/*
* It worked. Mark the vt to switch to and
* return. The process needs to send us a
* VT_RELDISP ioctl to complete the switch.
*/
return;
}
/*
* The controlling process has died, so we revert back to
* normal operation. In this case, we'll also change back
* to KD_TEXT mode. I'm not sure if this is strictly correct
* but it saves the agony when the X server dies and the screen
* remains blanked due to KD_GRAPHICS! It would be nice to do
* this outside of VT_PROCESS but there is no single process
* to account for and tracking tty count may be undesirable.
*/
reset_vc(vc);
/*
* Fall through to normal (VT_AUTO) handling of the switch...
*/
}
/*
* Ignore all switches in KD_GRAPHICS+VT_AUTO mode
*/
if (vc->vc_mode == KD_GRAPHICS)
return;
complete_change_console(new_vc);
}
/* Perform a kernel triggered VT switch for suspend/resume */
static int disable_vt_switch;
int vt_move_to_console(unsigned int vt, int alloc)
{
int prev;
console_lock();
/* Graphics mode - up to X */
if (disable_vt_switch) {
console_unlock();
return 0;
}
prev = fg_console;
if (alloc && vc_allocate(vt)) {
/* we can't have a free VC for now. Too bad,
* we don't want to mess the screen for now. */
console_unlock();
return -ENOSPC;
}
if (set_console(vt)) {
/*
* We're unable to switch to the SUSPEND_CONSOLE.
* Let the calling function know so it can decide
* what to do.
*/
console_unlock();
return -EIO;
}
console_unlock();
if (vt_waitactive(vt + 1)) {
pr_debug("Suspend: Can't switch VCs.");
return -EINTR;
}
return prev;
}
/*
* Normally during a suspend, we allocate a new console and switch to it.
* When we resume, we switch back to the original console. This switch
* can be slow, so on systems where the framebuffer can handle restoration
* of video registers anyways, there's little point in doing the console
* switch. This function allows you to disable it by passing it '0'.
*/
void pm_set_vt_switch(int do_switch)
{
console_lock();
disable_vt_switch = !do_switch;
console_unlock();
}
EXPORT_SYMBOL(pm_set_vt_switch);
| gpl-2.0 |
sud-vastav/android_kernel_xiaomi_armani | drivers/s390/scsi/zfcp_dbf.c | 3503 | 14808 | /*
* zfcp device driver
*
* Debug traces for zfcp.
*
* Copyright IBM Corporation 2002, 2010
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/ctype.h>
#include <linux/slab.h>
#include <asm/debug.h>
#include "zfcp_dbf.h"
#include "zfcp_ext.h"
#include "zfcp_fc.h"
static u32 dbfsize = 4;
module_param(dbfsize, uint, 0400);
MODULE_PARM_DESC(dbfsize,
"number of pages for each debug feature area (default 4)");
static inline unsigned int zfcp_dbf_plen(unsigned int offset)
{
return sizeof(struct zfcp_dbf_pay) + offset - ZFCP_DBF_PAY_MAX_REC;
}
static inline
void zfcp_dbf_pl_write(struct zfcp_dbf *dbf, void *data, u16 length, char *area,
u64 req_id)
{
struct zfcp_dbf_pay *pl = &dbf->pay_buf;
u16 offset = 0, rec_length;
spin_lock(&dbf->pay_lock);
memset(pl, 0, sizeof(*pl));
pl->fsf_req_id = req_id;
memcpy(pl->area, area, ZFCP_DBF_TAG_LEN);
while (offset < length) {
rec_length = min((u16) ZFCP_DBF_PAY_MAX_REC,
(u16) (length - offset));
memcpy(pl->data, data + offset, rec_length);
debug_event(dbf->pay, 1, pl, zfcp_dbf_plen(rec_length));
offset += rec_length;
pl->counter++;
}
spin_unlock(&dbf->pay_lock);
}
/**
* zfcp_dbf_hba_fsf_res - trace event for fsf responses
* @tag: tag indicating which kind of unsolicited status has been received
* @req: request for which a response was received
*/
void zfcp_dbf_hba_fsf_res(char *tag, struct zfcp_fsf_req *req)
{
struct zfcp_dbf *dbf = req->adapter->dbf;
struct fsf_qtcb_prefix *q_pref = &req->qtcb->prefix;
struct fsf_qtcb_header *q_head = &req->qtcb->header;
struct zfcp_dbf_hba *rec = &dbf->hba_buf;
unsigned long flags;
spin_lock_irqsave(&dbf->hba_lock, flags);
memset(rec, 0, sizeof(*rec));
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
rec->id = ZFCP_DBF_HBA_RES;
rec->fsf_req_id = req->req_id;
rec->fsf_req_status = req->status;
rec->fsf_cmd = req->fsf_command;
rec->fsf_seq_no = req->seq_no;
rec->u.res.req_issued = req->issued;
rec->u.res.prot_status = q_pref->prot_status;
rec->u.res.fsf_status = q_head->fsf_status;
memcpy(rec->u.res.prot_status_qual, &q_pref->prot_status_qual,
FSF_PROT_STATUS_QUAL_SIZE);
memcpy(rec->u.res.fsf_status_qual, &q_head->fsf_status_qual,
FSF_STATUS_QUALIFIER_SIZE);
if (req->fsf_command != FSF_QTCB_FCP_CMND) {
rec->pl_len = q_head->log_length;
zfcp_dbf_pl_write(dbf, (char *)q_pref + q_head->log_start,
rec->pl_len, "fsf_res", req->req_id);
}
debug_event(dbf->hba, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->hba_lock, flags);
}
/**
* zfcp_dbf_hba_fsf_uss - trace event for an unsolicited status buffer
* @tag: tag indicating which kind of unsolicited status has been received
* @req: request providing the unsolicited status
*/
void zfcp_dbf_hba_fsf_uss(char *tag, struct zfcp_fsf_req *req)
{
struct zfcp_dbf *dbf = req->adapter->dbf;
struct fsf_status_read_buffer *srb = req->data;
struct zfcp_dbf_hba *rec = &dbf->hba_buf;
unsigned long flags;
spin_lock_irqsave(&dbf->hba_lock, flags);
memset(rec, 0, sizeof(*rec));
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
rec->id = ZFCP_DBF_HBA_USS;
rec->fsf_req_id = req->req_id;
rec->fsf_req_status = req->status;
rec->fsf_cmd = req->fsf_command;
if (!srb)
goto log;
rec->u.uss.status_type = srb->status_type;
rec->u.uss.status_subtype = srb->status_subtype;
rec->u.uss.d_id = ntoh24(srb->d_id);
rec->u.uss.lun = srb->fcp_lun;
memcpy(&rec->u.uss.queue_designator, &srb->queue_designator,
sizeof(rec->u.uss.queue_designator));
/* status read buffer payload length */
rec->pl_len = (!srb->length) ? 0 : srb->length -
offsetof(struct fsf_status_read_buffer, payload);
if (rec->pl_len)
zfcp_dbf_pl_write(dbf, srb->payload.data, rec->pl_len,
"fsf_uss", req->req_id);
log:
debug_event(dbf->hba, 2, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->hba_lock, flags);
}
/**
* zfcp_dbf_hba_bit_err - trace event for bit error conditions
* @tag: tag indicating which kind of unsolicited status has been received
* @req: request which caused the bit_error condition
*/
void zfcp_dbf_hba_bit_err(char *tag, struct zfcp_fsf_req *req)
{
struct zfcp_dbf *dbf = req->adapter->dbf;
struct zfcp_dbf_hba *rec = &dbf->hba_buf;
struct fsf_status_read_buffer *sr_buf = req->data;
unsigned long flags;
spin_lock_irqsave(&dbf->hba_lock, flags);
memset(rec, 0, sizeof(*rec));
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
rec->id = ZFCP_DBF_HBA_BIT;
rec->fsf_req_id = req->req_id;
rec->fsf_req_status = req->status;
rec->fsf_cmd = req->fsf_command;
memcpy(&rec->u.be, &sr_buf->payload.bit_error,
sizeof(struct fsf_bit_error_payload));
debug_event(dbf->hba, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->hba_lock, flags);
}
/**
* zfcp_dbf_hba_def_err - trace event for deferred error messages
* @adapter: pointer to struct zfcp_adapter
* @req_id: request id which caused the deferred error message
* @scount: number of sbals incl. the signaling sbal
* @pl: array of all involved sbals
*/
void zfcp_dbf_hba_def_err(struct zfcp_adapter *adapter, u64 req_id, u16 scount,
void **pl)
{
struct zfcp_dbf *dbf = adapter->dbf;
struct zfcp_dbf_pay *payload = &dbf->pay_buf;
unsigned long flags;
u16 length;
if (!pl)
return;
spin_lock_irqsave(&dbf->pay_lock, flags);
memset(payload, 0, sizeof(*payload));
memcpy(payload->area, "def_err", 7);
payload->fsf_req_id = req_id;
payload->counter = 0;
length = min((u16)sizeof(struct qdio_buffer),
(u16)ZFCP_DBF_PAY_MAX_REC);
while ((char *)pl[payload->counter] && payload->counter < scount) {
memcpy(payload->data, (char *)pl[payload->counter], length);
debug_event(dbf->pay, 1, payload, zfcp_dbf_plen(length));
payload->counter++;
}
spin_unlock_irqrestore(&dbf->pay_lock, flags);
}
static void zfcp_dbf_set_common(struct zfcp_dbf_rec *rec,
struct zfcp_adapter *adapter,
struct zfcp_port *port,
struct scsi_device *sdev)
{
rec->adapter_status = atomic_read(&adapter->status);
if (port) {
rec->port_status = atomic_read(&port->status);
rec->wwpn = port->wwpn;
rec->d_id = port->d_id;
}
if (sdev) {
rec->lun_status = atomic_read(&sdev_to_zfcp(sdev)->status);
rec->lun = zfcp_scsi_dev_lun(sdev);
}
}
/**
* zfcp_dbf_rec_trig - trace event related to triggered recovery
* @tag: identifier for event
* @adapter: adapter on which the erp_action should run
* @port: remote port involved in the erp_action
* @sdev: scsi device involved in the erp_action
* @want: wanted erp_action
* @need: required erp_action
*
* The adapter->erp_lock has to be held.
*/
void zfcp_dbf_rec_trig(char *tag, struct zfcp_adapter *adapter,
struct zfcp_port *port, struct scsi_device *sdev,
u8 want, u8 need)
{
struct zfcp_dbf *dbf = adapter->dbf;
struct zfcp_dbf_rec *rec = &dbf->rec_buf;
struct list_head *entry;
unsigned long flags;
spin_lock_irqsave(&dbf->rec_lock, flags);
memset(rec, 0, sizeof(*rec));
rec->id = ZFCP_DBF_REC_TRIG;
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
zfcp_dbf_set_common(rec, adapter, port, sdev);
list_for_each(entry, &adapter->erp_ready_head)
rec->u.trig.ready++;
list_for_each(entry, &adapter->erp_running_head)
rec->u.trig.running++;
rec->u.trig.want = want;
rec->u.trig.need = need;
debug_event(dbf->rec, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->rec_lock, flags);
}
/**
* zfcp_dbf_rec_run - trace event related to running recovery
* @tag: identifier for event
* @erp: erp_action running
*/
void zfcp_dbf_rec_run(char *tag, struct zfcp_erp_action *erp)
{
struct zfcp_dbf *dbf = erp->adapter->dbf;
struct zfcp_dbf_rec *rec = &dbf->rec_buf;
unsigned long flags;
spin_lock_irqsave(&dbf->rec_lock, flags);
memset(rec, 0, sizeof(*rec));
rec->id = ZFCP_DBF_REC_RUN;
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
zfcp_dbf_set_common(rec, erp->adapter, erp->port, erp->sdev);
rec->u.run.fsf_req_id = erp->fsf_req_id;
rec->u.run.rec_status = erp->status;
rec->u.run.rec_step = erp->step;
rec->u.run.rec_action = erp->action;
if (erp->sdev)
rec->u.run.rec_count =
atomic_read(&sdev_to_zfcp(erp->sdev)->erp_counter);
else if (erp->port)
rec->u.run.rec_count = atomic_read(&erp->port->erp_counter);
else
rec->u.run.rec_count = atomic_read(&erp->adapter->erp_counter);
debug_event(dbf->rec, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->rec_lock, flags);
}
static inline
void zfcp_dbf_san(char *tag, struct zfcp_dbf *dbf, void *data, u8 id, u16 len,
u64 req_id, u32 d_id)
{
struct zfcp_dbf_san *rec = &dbf->san_buf;
u16 rec_len;
unsigned long flags;
spin_lock_irqsave(&dbf->san_lock, flags);
memset(rec, 0, sizeof(*rec));
rec->id = id;
rec->fsf_req_id = req_id;
rec->d_id = d_id;
rec_len = min(len, (u16)ZFCP_DBF_SAN_MAX_PAYLOAD);
memcpy(rec->payload, data, rec_len);
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
debug_event(dbf->san, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->san_lock, flags);
}
/**
* zfcp_dbf_san_req - trace event for issued SAN request
* @tag: indentifier for event
* @fsf_req: request containing issued CT data
* d_id: destination ID
*/
void zfcp_dbf_san_req(char *tag, struct zfcp_fsf_req *fsf, u32 d_id)
{
struct zfcp_dbf *dbf = fsf->adapter->dbf;
struct zfcp_fsf_ct_els *ct_els = fsf->data;
u16 length;
length = (u16)(ct_els->req->length + FC_CT_HDR_LEN);
zfcp_dbf_san(tag, dbf, sg_virt(ct_els->req), ZFCP_DBF_SAN_REQ, length,
fsf->req_id, d_id);
}
/**
* zfcp_dbf_san_res - trace event for received SAN request
* @tag: indentifier for event
* @fsf_req: request containing issued CT data
*/
void zfcp_dbf_san_res(char *tag, struct zfcp_fsf_req *fsf)
{
struct zfcp_dbf *dbf = fsf->adapter->dbf;
struct zfcp_fsf_ct_els *ct_els = fsf->data;
u16 length;
length = (u16)(ct_els->resp->length + FC_CT_HDR_LEN);
zfcp_dbf_san(tag, dbf, sg_virt(ct_els->resp), ZFCP_DBF_SAN_RES, length,
fsf->req_id, 0);
}
/**
* zfcp_dbf_san_in_els - trace event for incoming ELS
* @tag: indentifier for event
* @fsf_req: request containing issued CT data
*/
void zfcp_dbf_san_in_els(char *tag, struct zfcp_fsf_req *fsf)
{
struct zfcp_dbf *dbf = fsf->adapter->dbf;
struct fsf_status_read_buffer *srb =
(struct fsf_status_read_buffer *) fsf->data;
u16 length;
length = (u16)(srb->length -
offsetof(struct fsf_status_read_buffer, payload));
zfcp_dbf_san(tag, dbf, srb->payload.data, ZFCP_DBF_SAN_ELS, length,
fsf->req_id, ntoh24(srb->d_id));
}
/**
* zfcp_dbf_scsi - trace event for scsi commands
* @tag: identifier for event
* @sc: pointer to struct scsi_cmnd
* @fsf: pointer to struct zfcp_fsf_req
*/
void zfcp_dbf_scsi(char *tag, struct scsi_cmnd *sc, struct zfcp_fsf_req *fsf)
{
struct zfcp_adapter *adapter =
(struct zfcp_adapter *) sc->device->host->hostdata[0];
struct zfcp_dbf *dbf = adapter->dbf;
struct zfcp_dbf_scsi *rec = &dbf->scsi_buf;
struct fcp_resp_with_ext *fcp_rsp;
struct fcp_resp_rsp_info *fcp_rsp_info;
unsigned long flags;
spin_lock_irqsave(&dbf->scsi_lock, flags);
memset(rec, 0, sizeof(*rec));
memcpy(rec->tag, tag, ZFCP_DBF_TAG_LEN);
rec->id = ZFCP_DBF_SCSI_CMND;
rec->scsi_result = sc->result;
rec->scsi_retries = sc->retries;
rec->scsi_allowed = sc->allowed;
rec->scsi_id = sc->device->id;
rec->scsi_lun = sc->device->lun;
rec->host_scribble = (unsigned long)sc->host_scribble;
memcpy(rec->scsi_opcode, sc->cmnd,
min((int)sc->cmd_len, ZFCP_DBF_SCSI_OPCODE));
if (fsf) {
rec->fsf_req_id = fsf->req_id;
fcp_rsp = (struct fcp_resp_with_ext *)
&(fsf->qtcb->bottom.io.fcp_rsp);
memcpy(&rec->fcp_rsp, fcp_rsp, FCP_RESP_WITH_EXT);
if (fcp_rsp->resp.fr_flags & FCP_RSP_LEN_VAL) {
fcp_rsp_info = (struct fcp_resp_rsp_info *) &fcp_rsp[1];
rec->fcp_rsp_info = fcp_rsp_info->rsp_code;
}
if (fcp_rsp->resp.fr_flags & FCP_SNS_LEN_VAL) {
rec->pl_len = min((u16)SCSI_SENSE_BUFFERSIZE,
(u16)ZFCP_DBF_PAY_MAX_REC);
zfcp_dbf_pl_write(dbf, sc->sense_buffer, rec->pl_len,
"fcp_sns", fsf->req_id);
}
}
debug_event(dbf->scsi, 1, rec, sizeof(*rec));
spin_unlock_irqrestore(&dbf->scsi_lock, flags);
}
static debug_info_t *zfcp_dbf_reg(const char *name, int size, int rec_size)
{
struct debug_info *d;
d = debug_register(name, size, 1, rec_size);
if (!d)
return NULL;
debug_register_view(d, &debug_hex_ascii_view);
debug_set_level(d, 3);
return d;
}
static void zfcp_dbf_unregister(struct zfcp_dbf *dbf)
{
if (!dbf)
return;
debug_unregister(dbf->scsi);
debug_unregister(dbf->san);
debug_unregister(dbf->hba);
debug_unregister(dbf->pay);
debug_unregister(dbf->rec);
kfree(dbf);
}
/**
* zfcp_adapter_debug_register - registers debug feature for an adapter
* @adapter: pointer to adapter for which debug features should be registered
* return: -ENOMEM on error, 0 otherwise
*/
int zfcp_dbf_adapter_register(struct zfcp_adapter *adapter)
{
char name[DEBUG_MAX_NAME_LEN];
struct zfcp_dbf *dbf;
dbf = kzalloc(sizeof(struct zfcp_dbf), GFP_KERNEL);
if (!dbf)
return -ENOMEM;
spin_lock_init(&dbf->pay_lock);
spin_lock_init(&dbf->hba_lock);
spin_lock_init(&dbf->san_lock);
spin_lock_init(&dbf->scsi_lock);
spin_lock_init(&dbf->rec_lock);
/* debug feature area which records recovery activity */
sprintf(name, "zfcp_%s_rec", dev_name(&adapter->ccw_device->dev));
dbf->rec = zfcp_dbf_reg(name, dbfsize, sizeof(struct zfcp_dbf_rec));
if (!dbf->rec)
goto err_out;
/* debug feature area which records HBA (FSF and QDIO) conditions */
sprintf(name, "zfcp_%s_hba", dev_name(&adapter->ccw_device->dev));
dbf->hba = zfcp_dbf_reg(name, dbfsize, sizeof(struct zfcp_dbf_hba));
if (!dbf->hba)
goto err_out;
/* debug feature area which records payload info */
sprintf(name, "zfcp_%s_pay", dev_name(&adapter->ccw_device->dev));
dbf->pay = zfcp_dbf_reg(name, dbfsize * 2, sizeof(struct zfcp_dbf_pay));
if (!dbf->pay)
goto err_out;
/* debug feature area which records SAN command failures and recovery */
sprintf(name, "zfcp_%s_san", dev_name(&adapter->ccw_device->dev));
dbf->san = zfcp_dbf_reg(name, dbfsize, sizeof(struct zfcp_dbf_san));
if (!dbf->san)
goto err_out;
/* debug feature area which records SCSI command failures and recovery */
sprintf(name, "zfcp_%s_scsi", dev_name(&adapter->ccw_device->dev));
dbf->scsi = zfcp_dbf_reg(name, dbfsize, sizeof(struct zfcp_dbf_scsi));
if (!dbf->scsi)
goto err_out;
adapter->dbf = dbf;
return 0;
err_out:
zfcp_dbf_unregister(dbf);
return -ENOMEM;
}
/**
* zfcp_adapter_debug_unregister - unregisters debug feature for an adapter
* @adapter: pointer to adapter for which debug features should be unregistered
*/
void zfcp_dbf_adapter_unregister(struct zfcp_adapter *adapter)
{
struct zfcp_dbf *dbf = adapter->dbf;
adapter->dbf = NULL;
zfcp_dbf_unregister(dbf);
}
| gpl-2.0 |
thiz11/kernel_mediatek_wiko | drivers/s390/net/qeth_l3_sys.c | 5039 | 30306 | /*
* drivers/s390/net/qeth_l3_sys.c
*
* Copyright IBM Corp. 2007
* Author(s): Utz Bacher <utz.bacher@de.ibm.com>,
* Frank Pavlic <fpavlic@de.ibm.com>,
* Thomas Spatzier <tspat@de.ibm.com>,
* Frank Blaschka <frank.blaschka@de.ibm.com>
*/
#include <linux/slab.h>
#include <asm/ebcdic.h>
#include "qeth_l3.h"
#define QETH_DEVICE_ATTR(_id, _name, _mode, _show, _store) \
struct device_attribute dev_attr_##_id = __ATTR(_name, _mode, _show, _store)
static ssize_t qeth_l3_dev_route_show(struct qeth_card *card,
struct qeth_routing_info *route, char *buf)
{
switch (route->type) {
case PRIMARY_ROUTER:
return sprintf(buf, "%s\n", "primary router");
case SECONDARY_ROUTER:
return sprintf(buf, "%s\n", "secondary router");
case MULTICAST_ROUTER:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "multicast router+");
else
return sprintf(buf, "%s\n", "multicast router");
case PRIMARY_CONNECTOR:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "primary connector+");
else
return sprintf(buf, "%s\n", "primary connector");
case SECONDARY_CONNECTOR:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "secondary connector+");
else
return sprintf(buf, "%s\n", "secondary connector");
default:
return sprintf(buf, "%s\n", "no");
}
}
static ssize_t qeth_l3_dev_route4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_show(card, &card->options.route4, buf);
}
static ssize_t qeth_l3_dev_route_store(struct qeth_card *card,
struct qeth_routing_info *route, enum qeth_prot_versions prot,
const char *buf, size_t count)
{
enum qeth_routing_types old_route_type = route->type;
char *tmp;
int rc = 0;
tmp = strsep((char **) &buf, "\n");
mutex_lock(&card->conf_mutex);
if (!strcmp(tmp, "no_router")) {
route->type = NO_ROUTER;
} else if (!strcmp(tmp, "primary_connector")) {
route->type = PRIMARY_CONNECTOR;
} else if (!strcmp(tmp, "secondary_connector")) {
route->type = SECONDARY_CONNECTOR;
} else if (!strcmp(tmp, "primary_router")) {
route->type = PRIMARY_ROUTER;
} else if (!strcmp(tmp, "secondary_router")) {
route->type = SECONDARY_ROUTER;
} else if (!strcmp(tmp, "multicast_router")) {
route->type = MULTICAST_ROUTER;
} else {
rc = -EINVAL;
goto out;
}
if (((card->state == CARD_STATE_SOFTSETUP) ||
(card->state == CARD_STATE_UP)) &&
(old_route_type != route->type)) {
if (prot == QETH_PROT_IPV4)
rc = qeth_l3_setrouting_v4(card);
else if (prot == QETH_PROT_IPV6)
rc = qeth_l3_setrouting_v6(card);
}
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_route4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_store(card, &card->options.route4,
QETH_PROT_IPV4, buf, count);
}
static DEVICE_ATTR(route4, 0644, qeth_l3_dev_route4_show,
qeth_l3_dev_route4_store);
static ssize_t qeth_l3_dev_route6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_show(card, &card->options.route6, buf);
}
static ssize_t qeth_l3_dev_route6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_store(card, &card->options.route6,
QETH_PROT_IPV6, buf, count);
}
static DEVICE_ATTR(route6, 0644, qeth_l3_dev_route6_show,
qeth_l3_dev_route6_store);
static ssize_t qeth_l3_dev_fake_broadcast_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->options.fake_broadcast? 1:0);
}
static ssize_t qeth_l3_dev_fake_broadcast_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int i, rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
i = simple_strtoul(buf, &tmp, 16);
if ((i == 0) || (i == 1))
card->options.fake_broadcast = i;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(fake_broadcast, 0644, qeth_l3_dev_fake_broadcast_show,
qeth_l3_dev_fake_broadcast_store);
static ssize_t qeth_l3_dev_broadcast_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR)))
return sprintf(buf, "n/a\n");
return sprintf(buf, "%s\n", (card->options.broadcast_mode ==
QETH_TR_BROADCAST_ALLRINGS)?
"all rings":"local");
}
static ssize_t qeth_l3_dev_broadcast_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR))) {
rc = -EINVAL;
goto out;
}
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "local"))
card->options.broadcast_mode = QETH_TR_BROADCAST_LOCAL;
else if (!strcmp(tmp, "all_rings"))
card->options.broadcast_mode = QETH_TR_BROADCAST_ALLRINGS;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(broadcast_mode, 0644, qeth_l3_dev_broadcast_mode_show,
qeth_l3_dev_broadcast_mode_store);
static ssize_t qeth_l3_dev_canonical_macaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR)))
return sprintf(buf, "n/a\n");
return sprintf(buf, "%i\n", (card->options.macaddr_mode ==
QETH_TR_MACADDR_CANONICAL)? 1:0);
}
static ssize_t qeth_l3_dev_canonical_macaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int i, rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR))) {
rc = -EINVAL;
goto out;
}
i = simple_strtoul(buf, &tmp, 16);
if ((i == 0) || (i == 1))
card->options.macaddr_mode = i?
QETH_TR_MACADDR_CANONICAL :
QETH_TR_MACADDR_NONCANONICAL;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(canonical_macaddr, 0644, qeth_l3_dev_canonical_macaddr_show,
qeth_l3_dev_canonical_macaddr_store);
static ssize_t qeth_l3_dev_sniffer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->options.sniffer ? 1 : 0);
}
static ssize_t qeth_l3_dev_sniffer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
int rc = 0;
unsigned long i;
if (!card)
return -EINVAL;
if (card->info.type != QETH_CARD_TYPE_IQD)
return -EPERM;
if (card->options.cq == QETH_CQ_ENABLED)
return -EPERM;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
rc = strict_strtoul(buf, 16, &i);
if (rc) {
rc = -EINVAL;
goto out;
}
switch (i) {
case 0:
card->options.sniffer = i;
break;
case 1:
qdio_get_ssqd_desc(CARD_DDEV(card), &card->ssqd);
if (card->ssqd.qdioac2 & QETH_SNIFF_AVAIL) {
card->options.sniffer = i;
if (card->qdio.init_pool.buf_count !=
QETH_IN_BUF_COUNT_MAX)
qeth_realloc_buffer_pool(card,
QETH_IN_BUF_COUNT_MAX);
} else
rc = -EPERM;
break;
default:
rc = -EINVAL;
}
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(sniffer, 0644, qeth_l3_dev_sniffer_show,
qeth_l3_dev_sniffer_store);
static ssize_t qeth_l3_dev_hsuid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
char tmp_hsuid[9];
if (!card)
return -EINVAL;
if (card->info.type != QETH_CARD_TYPE_IQD)
return -EPERM;
if (card->state == CARD_STATE_DOWN)
return -EPERM;
memcpy(tmp_hsuid, card->options.hsuid, sizeof(tmp_hsuid));
EBCASC(tmp_hsuid, 8);
return sprintf(buf, "%s\n", tmp_hsuid);
}
static ssize_t qeth_l3_dev_hsuid_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
struct qeth_ipaddr *addr;
char *tmp;
int i;
if (!card)
return -EINVAL;
if (card->info.type != QETH_CARD_TYPE_IQD)
return -EPERM;
if (card->state != CARD_STATE_DOWN &&
card->state != CARD_STATE_RECOVER)
return -EPERM;
if (card->options.sniffer)
return -EPERM;
if (card->options.cq == QETH_CQ_NOTAVAILABLE)
return -EPERM;
tmp = strsep((char **)&buf, "\n");
if (strlen(tmp) > 8)
return -EINVAL;
if (card->options.hsuid[0]) {
/* delete old ip address */
addr = qeth_l3_get_addr_buffer(QETH_PROT_IPV6);
if (addr != NULL) {
addr->u.a6.addr.s6_addr32[0] = 0xfe800000;
addr->u.a6.addr.s6_addr32[1] = 0x00000000;
for (i = 8; i < 16; i++)
addr->u.a6.addr.s6_addr[i] =
card->options.hsuid[i - 8];
addr->u.a6.pfxlen = 0;
addr->type = QETH_IP_TYPE_NORMAL;
} else
return -ENOMEM;
if (!qeth_l3_delete_ip(card, addr))
kfree(addr);
qeth_l3_set_ip_addr_list(card);
}
if (strlen(tmp) == 0) {
/* delete ip address only */
card->options.hsuid[0] = '\0';
if (card->dev)
memcpy(card->dev->perm_addr, card->options.hsuid, 9);
qeth_configure_cq(card, QETH_CQ_DISABLED);
return count;
}
if (qeth_configure_cq(card, QETH_CQ_ENABLED))
return -EPERM;
for (i = 0; i < 8; i++)
card->options.hsuid[i] = ' ';
card->options.hsuid[8] = '\0';
strncpy(card->options.hsuid, tmp, strlen(tmp));
ASCEBC(card->options.hsuid, 8);
if (card->dev)
memcpy(card->dev->perm_addr, card->options.hsuid, 9);
addr = qeth_l3_get_addr_buffer(QETH_PROT_IPV6);
if (addr != NULL) {
addr->u.a6.addr.s6_addr32[0] = 0xfe800000;
addr->u.a6.addr.s6_addr32[1] = 0x00000000;
for (i = 8; i < 16; i++)
addr->u.a6.addr.s6_addr[i] = card->options.hsuid[i - 8];
addr->u.a6.pfxlen = 0;
addr->type = QETH_IP_TYPE_NORMAL;
} else
return -ENOMEM;
if (!qeth_l3_add_ip(card, addr))
kfree(addr);
qeth_l3_set_ip_addr_list(card);
return count;
}
static DEVICE_ATTR(hsuid, 0644, qeth_l3_dev_hsuid_show,
qeth_l3_dev_hsuid_store);
static struct attribute *qeth_l3_device_attrs[] = {
&dev_attr_route4.attr,
&dev_attr_route6.attr,
&dev_attr_fake_broadcast.attr,
&dev_attr_broadcast_mode.attr,
&dev_attr_canonical_macaddr.attr,
&dev_attr_sniffer.attr,
&dev_attr_hsuid.attr,
NULL,
};
static struct attribute_group qeth_l3_device_attr_group = {
.attrs = qeth_l3_device_attrs,
};
static ssize_t qeth_l3_dev_ipato_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.enabled? 1:0);
}
static ssize_t qeth_l3_dev_ipato_enable_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
struct qeth_ipaddr *tmpipa, *t;
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.enabled = (card->ipato.enabled)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.enabled = 1;
list_for_each_entry_safe(tmpipa, t, card->ip_tbd_list, entry) {
if ((tmpipa->type == QETH_IP_TYPE_NORMAL) &&
qeth_l3_is_addr_covered_by_ipato(card, tmpipa))
tmpipa->set_flags |=
QETH_IPA_SETIP_TAKEOVER_FLAG;
}
} else if (!strcmp(tmp, "0")) {
card->ipato.enabled = 0;
list_for_each_entry_safe(tmpipa, t, card->ip_tbd_list, entry) {
if (tmpipa->set_flags &
QETH_IPA_SETIP_TAKEOVER_FLAG)
tmpipa->set_flags &=
~QETH_IPA_SETIP_TAKEOVER_FLAG;
}
} else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_enable, enable, 0644,
qeth_l3_dev_ipato_enable_show,
qeth_l3_dev_ipato_enable_store);
static ssize_t qeth_l3_dev_ipato_invert4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.invert4? 1:0);
}
static ssize_t qeth_l3_dev_ipato_invert4_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.invert4 = (card->ipato.invert4)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.invert4 = 1;
} else if (!strcmp(tmp, "0")) {
card->ipato.invert4 = 0;
} else
rc = -EINVAL;
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_invert4, invert4, 0644,
qeth_l3_dev_ipato_invert4_show,
qeth_l3_dev_ipato_invert4_store);
static ssize_t qeth_l3_dev_ipato_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipato_entry *ipatoe;
unsigned long flags;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
/* add strlen for "/<mask>\n" */
entry_len += (proto == QETH_PROT_IPV4)? 5 : 6;
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipatoe, &card->ipato.entries, entry) {
if (ipatoe->proto != proto)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, ipatoe->addr, addr_str);
i += snprintf(buf + i, PAGE_SIZE - i,
"%s/%i\n", addr_str, ipatoe->mask_bits);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_ipato_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_ipatoe(const char *buf, enum qeth_prot_versions proto,
u8 *addr, int *mask_bits)
{
const char *start, *end;
char *tmp;
char buffer[40] = {0, };
start = buf;
/* get address string */
end = strchr(start, '/');
if (!end || (end - start >= 40)) {
return -EINVAL;
}
strncpy(buffer, start, end - start);
if (qeth_l3_string_to_ipaddr(buffer, proto, addr)) {
return -EINVAL;
}
start = end + 1;
*mask_bits = simple_strtoul(start, &tmp, 10);
if (!strlen(start) ||
(tmp == start) ||
(*mask_bits > ((proto == QETH_PROT_IPV4) ? 32 : 128))) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_ipato_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
struct qeth_ipato_entry *ipatoe;
u8 addr[16];
int mask_bits;
int rc = 0;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_ipatoe(buf, proto, addr, &mask_bits);
if (rc)
goto out;
ipatoe = kzalloc(sizeof(struct qeth_ipato_entry), GFP_KERNEL);
if (!ipatoe) {
rc = -ENOMEM;
goto out;
}
ipatoe->proto = proto;
memcpy(ipatoe->addr, addr, (proto == QETH_PROT_IPV4)? 4:16);
ipatoe->mask_bits = mask_bits;
rc = qeth_l3_add_ipato_entry(card, ipatoe);
if (rc)
kfree(ipatoe);
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_ipato_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(ipato_add4, add4, 0644,
qeth_l3_dev_ipato_add4_show,
qeth_l3_dev_ipato_add4_store);
static ssize_t qeth_l3_dev_ipato_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int mask_bits;
int rc = 0;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_ipatoe(buf, proto, addr, &mask_bits);
if (!rc)
qeth_l3_del_ipato_entry(card, proto, addr, mask_bits);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_ipato_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(ipato_del4, del4, 0200, NULL,
qeth_l3_dev_ipato_del4_store);
static ssize_t qeth_l3_dev_ipato_invert6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.invert6? 1:0);
}
static ssize_t qeth_l3_dev_ipato_invert6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.invert6 = (card->ipato.invert6)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.invert6 = 1;
} else if (!strcmp(tmp, "0")) {
card->ipato.invert6 = 0;
} else
rc = -EINVAL;
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_invert6, invert6, 0644,
qeth_l3_dev_ipato_invert6_show,
qeth_l3_dev_ipato_invert6_store);
static ssize_t qeth_l3_dev_ipato_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_ipato_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(ipato_add6, add6, 0644,
qeth_l3_dev_ipato_add6_show,
qeth_l3_dev_ipato_add6_store);
static ssize_t qeth_l3_dev_ipato_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(ipato_del6, del6, 0200, NULL,
qeth_l3_dev_ipato_del6_store);
static struct attribute *qeth_ipato_device_attrs[] = {
&dev_attr_ipato_enable.attr,
&dev_attr_ipato_invert4.attr,
&dev_attr_ipato_add4.attr,
&dev_attr_ipato_del4.attr,
&dev_attr_ipato_invert6.attr,
&dev_attr_ipato_add6.attr,
&dev_attr_ipato_del6.attr,
NULL,
};
static struct attribute_group qeth_device_ipato_group = {
.name = "ipa_takeover",
.attrs = qeth_ipato_device_attrs,
};
static ssize_t qeth_l3_dev_vipa_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipaddr *ipaddr;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
unsigned long flags;
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
entry_len += 2; /* \n + terminator */
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipaddr, &card->ip_list, entry) {
if (ipaddr->proto != proto)
continue;
if (ipaddr->type != QETH_IP_TYPE_VIPA)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, (const u8 *)&ipaddr->u,
addr_str);
i += snprintf(buf + i, PAGE_SIZE - i, "%s\n", addr_str);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_vipa_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_vipae(const char *buf, enum qeth_prot_versions proto,
u8 *addr)
{
if (qeth_l3_string_to_ipaddr(buf, proto, addr)) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_vipa_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16] = {0, };
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_vipae(buf, proto, addr);
if (!rc)
rc = qeth_l3_add_vipa(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_vipa_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(vipa_add4, add4, 0644,
qeth_l3_dev_vipa_add4_show,
qeth_l3_dev_vipa_add4_store);
static ssize_t qeth_l3_dev_vipa_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_vipae(buf, proto, addr);
if (!rc)
qeth_l3_del_vipa(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_vipa_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(vipa_del4, del4, 0200, NULL,
qeth_l3_dev_vipa_del4_store);
static ssize_t qeth_l3_dev_vipa_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_vipa_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(vipa_add6, add6, 0644,
qeth_l3_dev_vipa_add6_show,
qeth_l3_dev_vipa_add6_store);
static ssize_t qeth_l3_dev_vipa_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(vipa_del6, del6, 0200, NULL,
qeth_l3_dev_vipa_del6_store);
static struct attribute *qeth_vipa_device_attrs[] = {
&dev_attr_vipa_add4.attr,
&dev_attr_vipa_del4.attr,
&dev_attr_vipa_add6.attr,
&dev_attr_vipa_del6.attr,
NULL,
};
static struct attribute_group qeth_device_vipa_group = {
.name = "vipa",
.attrs = qeth_vipa_device_attrs,
};
static ssize_t qeth_l3_dev_rxip_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipaddr *ipaddr;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
unsigned long flags;
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
entry_len += 2; /* \n + terminator */
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipaddr, &card->ip_list, entry) {
if (ipaddr->proto != proto)
continue;
if (ipaddr->type != QETH_IP_TYPE_RXIP)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, (const u8 *)&ipaddr->u,
addr_str);
i += snprintf(buf + i, PAGE_SIZE - i, "%s\n", addr_str);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_rxip_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_rxipe(const char *buf, enum qeth_prot_versions proto,
u8 *addr)
{
if (qeth_l3_string_to_ipaddr(buf, proto, addr)) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_rxip_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16] = {0, };
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_rxipe(buf, proto, addr);
if (!rc)
rc = qeth_l3_add_rxip(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_rxip_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(rxip_add4, add4, 0644,
qeth_l3_dev_rxip_add4_show,
qeth_l3_dev_rxip_add4_store);
static ssize_t qeth_l3_dev_rxip_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_rxipe(buf, proto, addr);
if (!rc)
qeth_l3_del_rxip(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_rxip_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(rxip_del4, del4, 0200, NULL,
qeth_l3_dev_rxip_del4_store);
static ssize_t qeth_l3_dev_rxip_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_rxip_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(rxip_add6, add6, 0644,
qeth_l3_dev_rxip_add6_show,
qeth_l3_dev_rxip_add6_store);
static ssize_t qeth_l3_dev_rxip_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(rxip_del6, del6, 0200, NULL,
qeth_l3_dev_rxip_del6_store);
static struct attribute *qeth_rxip_device_attrs[] = {
&dev_attr_rxip_add4.attr,
&dev_attr_rxip_del4.attr,
&dev_attr_rxip_add6.attr,
&dev_attr_rxip_del6.attr,
NULL,
};
static struct attribute_group qeth_device_rxip_group = {
.name = "rxip",
.attrs = qeth_rxip_device_attrs,
};
int qeth_l3_create_device_attributes(struct device *dev)
{
int ret;
ret = sysfs_create_group(&dev->kobj, &qeth_l3_device_attr_group);
if (ret)
return ret;
ret = sysfs_create_group(&dev->kobj, &qeth_device_ipato_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
return ret;
}
ret = sysfs_create_group(&dev->kobj, &qeth_device_vipa_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
return ret;
}
ret = sysfs_create_group(&dev->kobj, &qeth_device_rxip_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
sysfs_remove_group(&dev->kobj, &qeth_device_vipa_group);
return ret;
}
return 0;
}
void qeth_l3_remove_device_attributes(struct device *dev)
{
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
sysfs_remove_group(&dev->kobj, &qeth_device_vipa_group);
sysfs_remove_group(&dev->kobj, &qeth_device_rxip_group);
}
| gpl-2.0 |
jekkos/android_kernel_htc_msm8960 | drivers/net/ethernet/xscale/ixp2000/enp2611.c | 9647 | 6201 | /*
* IXP2400 MSF network device driver for the Radisys ENP2611
* Copyright (C) 2004, 2005 Lennert Buytenhek <buytenh@wantstofly.org>
* Dedicated to Marija Kulikova.
*
* 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/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <asm/hardware/uengine.h>
#include <asm/mach-types.h>
#include <asm/io.h>
#include "ixpdev.h"
#include "caleb.h"
#include "ixp2400-msf.h"
#include "pm3386.h"
/***********************************************************************
* The Radisys ENP2611 is a PCI form factor board with three SFP GBIC
* slots, connected via two PMC/Sierra 3386s and an SPI-3 bridge FPGA
* to the IXP2400.
*
* +-------------+
* SFP GBIC #0 ---+ | +---------+
* | PM3386 #0 +-------+ |
* SFP GBIC #1 ---+ | | "Caleb" | +---------+
* +-------------+ | | | |
* | SPI-3 +---------+ IXP2400 |
* +-------------+ | bridge | | |
* SFP GBIC #2 ---+ | | FPGA | +---------+
* | PM3386 #1 +-------+ |
* | | +---------+
* +-------------+
* ^ ^ ^
* | 1.25Gbaud | 104MHz | 104MHz
* | SERDES ea. | SPI-3 ea. | SPI-3
*
***********************************************************************/
static struct ixp2400_msf_parameters enp2611_msf_parameters =
{
.rx_mode = IXP2400_RX_MODE_UTOPIA_POS |
IXP2400_RX_MODE_1x32 |
IXP2400_RX_MODE_MPHY |
IXP2400_RX_MODE_MPHY_32 |
IXP2400_RX_MODE_MPHY_POLLED_STATUS |
IXP2400_RX_MODE_MPHY_LEVEL3 |
IXP2400_RX_MODE_RBUF_SIZE_64,
.rxclk01_multiplier = IXP2400_PLL_MULTIPLIER_16,
.rx_poll_ports = 3,
.rx_channel_mode = {
IXP2400_PORT_RX_MODE_MASTER |
IXP2400_PORT_RX_MODE_POS_PHY |
IXP2400_PORT_RX_MODE_POS_PHY_L3 |
IXP2400_PORT_RX_MODE_ODD_PARITY |
IXP2400_PORT_RX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_RX_MODE_MASTER |
IXP2400_PORT_RX_MODE_POS_PHY |
IXP2400_PORT_RX_MODE_POS_PHY_L3 |
IXP2400_PORT_RX_MODE_ODD_PARITY |
IXP2400_PORT_RX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_RX_MODE_MASTER |
IXP2400_PORT_RX_MODE_POS_PHY |
IXP2400_PORT_RX_MODE_POS_PHY_L3 |
IXP2400_PORT_RX_MODE_ODD_PARITY |
IXP2400_PORT_RX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_RX_MODE_MASTER |
IXP2400_PORT_RX_MODE_POS_PHY |
IXP2400_PORT_RX_MODE_POS_PHY_L3 |
IXP2400_PORT_RX_MODE_ODD_PARITY |
IXP2400_PORT_RX_MODE_2_CYCLE_DECODE
},
.tx_mode = IXP2400_TX_MODE_UTOPIA_POS |
IXP2400_TX_MODE_1x32 |
IXP2400_TX_MODE_MPHY |
IXP2400_TX_MODE_MPHY_32 |
IXP2400_TX_MODE_MPHY_POLLED_STATUS |
IXP2400_TX_MODE_MPHY_LEVEL3 |
IXP2400_TX_MODE_TBUF_SIZE_64,
.txclk01_multiplier = IXP2400_PLL_MULTIPLIER_16,
.tx_poll_ports = 3,
.tx_channel_mode = {
IXP2400_PORT_TX_MODE_MASTER |
IXP2400_PORT_TX_MODE_POS_PHY |
IXP2400_PORT_TX_MODE_ODD_PARITY |
IXP2400_PORT_TX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_TX_MODE_MASTER |
IXP2400_PORT_TX_MODE_POS_PHY |
IXP2400_PORT_TX_MODE_ODD_PARITY |
IXP2400_PORT_TX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_TX_MODE_MASTER |
IXP2400_PORT_TX_MODE_POS_PHY |
IXP2400_PORT_TX_MODE_ODD_PARITY |
IXP2400_PORT_TX_MODE_2_CYCLE_DECODE,
IXP2400_PORT_TX_MODE_MASTER |
IXP2400_PORT_TX_MODE_POS_PHY |
IXP2400_PORT_TX_MODE_ODD_PARITY |
IXP2400_PORT_TX_MODE_2_CYCLE_DECODE
}
};
static struct net_device *nds[3];
static struct timer_list link_check_timer;
/* @@@ Poll the SFP moddef0 line too. */
/* @@@ Try to use the pm3386 DOOL interrupt as well. */
static void enp2611_check_link_status(unsigned long __dummy)
{
int i;
for (i = 0; i < 3; i++) {
struct net_device *dev;
int status;
dev = nds[i];
if (dev == NULL)
continue;
status = pm3386_is_link_up(i);
if (status && !netif_carrier_ok(dev)) {
/* @@@ Should report autonegotiation status. */
printk(KERN_INFO "%s: NIC Link is Up\n", dev->name);
pm3386_enable_tx(i);
caleb_enable_tx(i);
netif_carrier_on(dev);
} else if (!status && netif_carrier_ok(dev)) {
printk(KERN_INFO "%s: NIC Link is Down\n", dev->name);
netif_carrier_off(dev);
caleb_disable_tx(i);
pm3386_disable_tx(i);
}
}
link_check_timer.expires = jiffies + HZ / 10;
add_timer(&link_check_timer);
}
static void enp2611_set_port_admin_status(int port, int up)
{
if (up) {
caleb_enable_rx(port);
pm3386_set_carrier(port, 1);
pm3386_enable_rx(port);
} else {
caleb_disable_tx(port);
pm3386_disable_tx(port);
/* @@@ Flush out pending packets. */
pm3386_set_carrier(port, 0);
pm3386_disable_rx(port);
caleb_disable_rx(port);
}
}
static int __init enp2611_init_module(void)
{
int ports;
int i;
if (!machine_is_enp2611())
return -ENODEV;
caleb_reset();
pm3386_reset();
ports = pm3386_port_count();
for (i = 0; i < ports; i++) {
nds[i] = ixpdev_alloc(i, sizeof(struct ixpdev_priv));
if (nds[i] == NULL) {
while (--i >= 0)
free_netdev(nds[i]);
return -ENOMEM;
}
pm3386_init_port(i);
pm3386_get_mac(i, nds[i]->dev_addr);
}
ixp2400_msf_init(&enp2611_msf_parameters);
if (ixpdev_init(ports, nds, enp2611_set_port_admin_status)) {
for (i = 0; i < ports; i++)
if (nds[i])
free_netdev(nds[i]);
return -EINVAL;
}
init_timer(&link_check_timer);
link_check_timer.function = enp2611_check_link_status;
link_check_timer.expires = jiffies;
add_timer(&link_check_timer);
return 0;
}
static void __exit enp2611_cleanup_module(void)
{
int i;
del_timer_sync(&link_check_timer);
ixpdev_deinit();
for (i = 0; i < 3; i++)
free_netdev(nds[i]);
}
module_init(enp2611_init_module);
module_exit(enp2611_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
jenswi-linaro/linux | drivers/misc/cxl/irq.c | 176 | 14309 | /*
* Copyright 2014 IBM Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/pid.h>
#include <asm/cputable.h>
#include <misc/cxl-base.h>
#include "cxl.h"
#include "trace.h"
/* XXX: This is implementation specific */
static irqreturn_t handle_psl_slice_error(struct cxl_context *ctx, u64 dsisr, u64 errstat)
{
u64 fir1, fir2, fir_slice, serr, afu_debug;
fir1 = cxl_p1_read(ctx->afu->adapter, CXL_PSL_FIR1);
fir2 = cxl_p1_read(ctx->afu->adapter, CXL_PSL_FIR2);
fir_slice = cxl_p1n_read(ctx->afu, CXL_PSL_FIR_SLICE_An);
serr = cxl_p1n_read(ctx->afu, CXL_PSL_SERR_An);
afu_debug = cxl_p1n_read(ctx->afu, CXL_AFU_DEBUG_An);
dev_crit(&ctx->afu->dev, "PSL ERROR STATUS: 0x%016llx\n", errstat);
dev_crit(&ctx->afu->dev, "PSL_FIR1: 0x%016llx\n", fir1);
dev_crit(&ctx->afu->dev, "PSL_FIR2: 0x%016llx\n", fir2);
dev_crit(&ctx->afu->dev, "PSL_SERR_An: 0x%016llx\n", serr);
dev_crit(&ctx->afu->dev, "PSL_FIR_SLICE_An: 0x%016llx\n", fir_slice);
dev_crit(&ctx->afu->dev, "CXL_PSL_AFU_DEBUG_An: 0x%016llx\n", afu_debug);
dev_crit(&ctx->afu->dev, "STOPPING CXL TRACE\n");
cxl_stop_trace(ctx->afu->adapter);
return cxl_ack_irq(ctx, 0, errstat);
}
irqreturn_t cxl_slice_irq_err(int irq, void *data)
{
struct cxl_afu *afu = data;
u64 fir_slice, errstat, serr, afu_debug;
WARN(irq, "CXL SLICE ERROR interrupt %i\n", irq);
serr = cxl_p1n_read(afu, CXL_PSL_SERR_An);
fir_slice = cxl_p1n_read(afu, CXL_PSL_FIR_SLICE_An);
errstat = cxl_p2n_read(afu, CXL_PSL_ErrStat_An);
afu_debug = cxl_p1n_read(afu, CXL_AFU_DEBUG_An);
dev_crit(&afu->dev, "PSL_SERR_An: 0x%016llx\n", serr);
dev_crit(&afu->dev, "PSL_FIR_SLICE_An: 0x%016llx\n", fir_slice);
dev_crit(&afu->dev, "CXL_PSL_ErrStat_An: 0x%016llx\n", errstat);
dev_crit(&afu->dev, "CXL_PSL_AFU_DEBUG_An: 0x%016llx\n", afu_debug);
cxl_p1n_write(afu, CXL_PSL_SERR_An, serr);
return IRQ_HANDLED;
}
static irqreturn_t cxl_irq_err(int irq, void *data)
{
struct cxl *adapter = data;
u64 fir1, fir2, err_ivte;
WARN(1, "CXL ERROR interrupt %i\n", irq);
err_ivte = cxl_p1_read(adapter, CXL_PSL_ErrIVTE);
dev_crit(&adapter->dev, "PSL_ErrIVTE: 0x%016llx\n", err_ivte);
dev_crit(&adapter->dev, "STOPPING CXL TRACE\n");
cxl_stop_trace(adapter);
fir1 = cxl_p1_read(adapter, CXL_PSL_FIR1);
fir2 = cxl_p1_read(adapter, CXL_PSL_FIR2);
dev_crit(&adapter->dev, "PSL_FIR1: 0x%016llx\nPSL_FIR2: 0x%016llx\n", fir1, fir2);
return IRQ_HANDLED;
}
static irqreturn_t schedule_cxl_fault(struct cxl_context *ctx, u64 dsisr, u64 dar)
{
ctx->dsisr = dsisr;
ctx->dar = dar;
schedule_work(&ctx->fault_work);
return IRQ_HANDLED;
}
static irqreturn_t cxl_irq(int irq, void *data, struct cxl_irq_info *irq_info)
{
struct cxl_context *ctx = data;
u64 dsisr, dar;
dsisr = irq_info->dsisr;
dar = irq_info->dar;
trace_cxl_psl_irq(ctx, irq, dsisr, dar);
pr_devel("CXL interrupt %i for afu pe: %i DSISR: %#llx DAR: %#llx\n", irq, ctx->pe, dsisr, dar);
if (dsisr & CXL_PSL_DSISR_An_DS) {
/*
* We don't inherently need to sleep to handle this, but we do
* need to get a ref to the task's mm, which we can't do from
* irq context without the potential for a deadlock since it
* takes the task_lock. An alternate option would be to keep a
* reference to the task's mm the entire time it has cxl open,
* but to do that we need to solve the issue where we hold a
* ref to the mm, but the mm can hold a ref to the fd after an
* mmap preventing anything from being cleaned up.
*/
pr_devel("Scheduling segment miss handling for later pe: %i\n", ctx->pe);
return schedule_cxl_fault(ctx, dsisr, dar);
}
if (dsisr & CXL_PSL_DSISR_An_M)
pr_devel("CXL interrupt: PTE not found\n");
if (dsisr & CXL_PSL_DSISR_An_P)
pr_devel("CXL interrupt: Storage protection violation\n");
if (dsisr & CXL_PSL_DSISR_An_A)
pr_devel("CXL interrupt: AFU lock access to write through or cache inhibited storage\n");
if (dsisr & CXL_PSL_DSISR_An_S)
pr_devel("CXL interrupt: Access was afu_wr or afu_zero\n");
if (dsisr & CXL_PSL_DSISR_An_K)
pr_devel("CXL interrupt: Access not permitted by virtual page class key protection\n");
if (dsisr & CXL_PSL_DSISR_An_DM) {
/*
* In some cases we might be able to handle the fault
* immediately if hash_page would succeed, but we still need
* the task's mm, which as above we can't get without a lock
*/
pr_devel("Scheduling page fault handling for later pe: %i\n", ctx->pe);
return schedule_cxl_fault(ctx, dsisr, dar);
}
if (dsisr & CXL_PSL_DSISR_An_ST)
WARN(1, "CXL interrupt: Segment Table PTE not found\n");
if (dsisr & CXL_PSL_DSISR_An_UR)
pr_devel("CXL interrupt: AURP PTE not found\n");
if (dsisr & CXL_PSL_DSISR_An_PE)
return handle_psl_slice_error(ctx, dsisr, irq_info->errstat);
if (dsisr & CXL_PSL_DSISR_An_AE) {
pr_devel("CXL interrupt: AFU Error 0x%016llx\n", irq_info->afu_err);
if (ctx->pending_afu_err) {
/*
* This shouldn't happen - the PSL treats these errors
* as fatal and will have reset the AFU, so there's not
* much point buffering multiple AFU errors.
* OTOH if we DO ever see a storm of these come in it's
* probably best that we log them somewhere:
*/
dev_err_ratelimited(&ctx->afu->dev, "CXL AFU Error "
"undelivered to pe %i: 0x%016llx\n",
ctx->pe, irq_info->afu_err);
} else {
spin_lock(&ctx->lock);
ctx->afu_err = irq_info->afu_err;
ctx->pending_afu_err = 1;
spin_unlock(&ctx->lock);
wake_up_all(&ctx->wq);
}
cxl_ack_irq(ctx, CXL_PSL_TFC_An_A, 0);
return IRQ_HANDLED;
}
if (dsisr & CXL_PSL_DSISR_An_OC)
pr_devel("CXL interrupt: OS Context Warning\n");
WARN(1, "Unhandled CXL PSL IRQ\n");
return IRQ_HANDLED;
}
static irqreturn_t fail_psl_irq(struct cxl_afu *afu, struct cxl_irq_info *irq_info)
{
if (irq_info->dsisr & CXL_PSL_DSISR_TRANS)
cxl_p2n_write(afu, CXL_PSL_TFC_An, CXL_PSL_TFC_An_AE);
else
cxl_p2n_write(afu, CXL_PSL_TFC_An, CXL_PSL_TFC_An_A);
return IRQ_HANDLED;
}
static irqreturn_t cxl_irq_multiplexed(int irq, void *data)
{
struct cxl_afu *afu = data;
struct cxl_context *ctx;
struct cxl_irq_info irq_info;
int ph = cxl_p2n_read(afu, CXL_PSL_PEHandle_An) & 0xffff;
int ret;
if ((ret = cxl_get_irq(afu, &irq_info))) {
WARN(1, "Unable to get CXL IRQ Info: %i\n", ret);
return fail_psl_irq(afu, &irq_info);
}
rcu_read_lock();
ctx = idr_find(&afu->contexts_idr, ph);
if (ctx) {
ret = cxl_irq(irq, ctx, &irq_info);
rcu_read_unlock();
return ret;
}
rcu_read_unlock();
WARN(1, "Unable to demultiplex CXL PSL IRQ for PE %i DSISR %016llx DAR"
" %016llx\n(Possible AFU HW issue - was a term/remove acked"
" with outstanding transactions?)\n", ph, irq_info.dsisr,
irq_info.dar);
return fail_psl_irq(afu, &irq_info);
}
static irqreturn_t cxl_irq_afu(int irq, void *data)
{
struct cxl_context *ctx = data;
irq_hw_number_t hwirq = irqd_to_hwirq(irq_get_irq_data(irq));
int irq_off, afu_irq = 1;
__u16 range;
int r;
for (r = 1; r < CXL_IRQ_RANGES; r++) {
irq_off = hwirq - ctx->irqs.offset[r];
range = ctx->irqs.range[r];
if (irq_off >= 0 && irq_off < range) {
afu_irq += irq_off;
break;
}
afu_irq += range;
}
if (unlikely(r >= CXL_IRQ_RANGES)) {
WARN(1, "Recieved AFU IRQ out of range for pe %i (virq %i hwirq %lx)\n",
ctx->pe, irq, hwirq);
return IRQ_HANDLED;
}
trace_cxl_afu_irq(ctx, afu_irq, irq, hwirq);
pr_devel("Received AFU interrupt %i for pe: %i (virq %i hwirq %lx)\n",
afu_irq, ctx->pe, irq, hwirq);
if (unlikely(!ctx->irq_bitmap)) {
WARN(1, "Recieved AFU IRQ for context with no IRQ bitmap\n");
return IRQ_HANDLED;
}
spin_lock(&ctx->lock);
set_bit(afu_irq - 1, ctx->irq_bitmap);
ctx->pending_irq = true;
spin_unlock(&ctx->lock);
wake_up_all(&ctx->wq);
return IRQ_HANDLED;
}
unsigned int cxl_map_irq(struct cxl *adapter, irq_hw_number_t hwirq,
irq_handler_t handler, void *cookie, const char *name)
{
unsigned int virq;
int result;
/* IRQ Domain? */
virq = irq_create_mapping(NULL, hwirq);
if (!virq) {
dev_warn(&adapter->dev, "cxl_map_irq: irq_create_mapping failed\n");
return 0;
}
cxl_setup_irq(adapter, hwirq, virq);
pr_devel("hwirq %#lx mapped to virq %u\n", hwirq, virq);
result = request_irq(virq, handler, 0, name, cookie);
if (result) {
dev_warn(&adapter->dev, "cxl_map_irq: request_irq failed: %i\n", result);
return 0;
}
return virq;
}
void cxl_unmap_irq(unsigned int virq, void *cookie)
{
free_irq(virq, cookie);
irq_dispose_mapping(virq);
}
static int cxl_register_one_irq(struct cxl *adapter,
irq_handler_t handler,
void *cookie,
irq_hw_number_t *dest_hwirq,
unsigned int *dest_virq,
const char *name)
{
int hwirq, virq;
if ((hwirq = cxl_alloc_one_irq(adapter)) < 0)
return hwirq;
if (!(virq = cxl_map_irq(adapter, hwirq, handler, cookie, name)))
goto err;
*dest_hwirq = hwirq;
*dest_virq = virq;
return 0;
err:
cxl_release_one_irq(adapter, hwirq);
return -ENOMEM;
}
int cxl_register_psl_err_irq(struct cxl *adapter)
{
int rc;
adapter->irq_name = kasprintf(GFP_KERNEL, "cxl-%s-err",
dev_name(&adapter->dev));
if (!adapter->irq_name)
return -ENOMEM;
if ((rc = cxl_register_one_irq(adapter, cxl_irq_err, adapter,
&adapter->err_hwirq,
&adapter->err_virq,
adapter->irq_name))) {
kfree(adapter->irq_name);
adapter->irq_name = NULL;
return rc;
}
cxl_p1_write(adapter, CXL_PSL_ErrIVTE, adapter->err_hwirq & 0xffff);
return 0;
}
void cxl_release_psl_err_irq(struct cxl *adapter)
{
if (adapter->err_virq != irq_find_mapping(NULL, adapter->err_hwirq))
return;
cxl_p1_write(adapter, CXL_PSL_ErrIVTE, 0x0000000000000000);
cxl_unmap_irq(adapter->err_virq, adapter);
cxl_release_one_irq(adapter, adapter->err_hwirq);
kfree(adapter->irq_name);
}
int cxl_register_serr_irq(struct cxl_afu *afu)
{
u64 serr;
int rc;
afu->err_irq_name = kasprintf(GFP_KERNEL, "cxl-%s-err",
dev_name(&afu->dev));
if (!afu->err_irq_name)
return -ENOMEM;
if ((rc = cxl_register_one_irq(afu->adapter, cxl_slice_irq_err, afu,
&afu->serr_hwirq,
&afu->serr_virq, afu->err_irq_name))) {
kfree(afu->err_irq_name);
afu->err_irq_name = NULL;
return rc;
}
serr = cxl_p1n_read(afu, CXL_PSL_SERR_An);
serr = (serr & 0x00ffffffffff0000ULL) | (afu->serr_hwirq & 0xffff);
cxl_p1n_write(afu, CXL_PSL_SERR_An, serr);
return 0;
}
void cxl_release_serr_irq(struct cxl_afu *afu)
{
if (afu->serr_virq != irq_find_mapping(NULL, afu->serr_hwirq))
return;
cxl_p1n_write(afu, CXL_PSL_SERR_An, 0x0000000000000000);
cxl_unmap_irq(afu->serr_virq, afu);
cxl_release_one_irq(afu->adapter, afu->serr_hwirq);
kfree(afu->err_irq_name);
}
int cxl_register_psl_irq(struct cxl_afu *afu)
{
int rc;
afu->psl_irq_name = kasprintf(GFP_KERNEL, "cxl-%s",
dev_name(&afu->dev));
if (!afu->psl_irq_name)
return -ENOMEM;
if ((rc = cxl_register_one_irq(afu->adapter, cxl_irq_multiplexed, afu,
&afu->psl_hwirq, &afu->psl_virq,
afu->psl_irq_name))) {
kfree(afu->psl_irq_name);
afu->psl_irq_name = NULL;
}
return rc;
}
void cxl_release_psl_irq(struct cxl_afu *afu)
{
if (afu->psl_virq != irq_find_mapping(NULL, afu->psl_hwirq))
return;
cxl_unmap_irq(afu->psl_virq, afu);
cxl_release_one_irq(afu->adapter, afu->psl_hwirq);
kfree(afu->psl_irq_name);
}
void afu_irq_name_free(struct cxl_context *ctx)
{
struct cxl_irq_name *irq_name, *tmp;
list_for_each_entry_safe(irq_name, tmp, &ctx->irq_names, list) {
kfree(irq_name->name);
list_del(&irq_name->list);
kfree(irq_name);
}
}
int afu_allocate_irqs(struct cxl_context *ctx, u32 count)
{
int rc, r, i, j = 1;
struct cxl_irq_name *irq_name;
/* Initialize the list head to hold irq names */
INIT_LIST_HEAD(&ctx->irq_names);
if ((rc = cxl_alloc_irq_ranges(&ctx->irqs, ctx->afu->adapter, count)))
return rc;
/* Multiplexed PSL Interrupt */
ctx->irqs.offset[0] = ctx->afu->psl_hwirq;
ctx->irqs.range[0] = 1;
ctx->irq_count = count;
ctx->irq_bitmap = kcalloc(BITS_TO_LONGS(count),
sizeof(*ctx->irq_bitmap), GFP_KERNEL);
if (!ctx->irq_bitmap)
goto out;
/*
* Allocate names first. If any fail, bail out before allocating
* actual hardware IRQs.
*/
for (r = 1; r < CXL_IRQ_RANGES; r++) {
for (i = 0; i < ctx->irqs.range[r]; i++) {
irq_name = kmalloc(sizeof(struct cxl_irq_name),
GFP_KERNEL);
if (!irq_name)
goto out;
irq_name->name = kasprintf(GFP_KERNEL, "cxl-%s-pe%i-%i",
dev_name(&ctx->afu->dev),
ctx->pe, j);
if (!irq_name->name) {
kfree(irq_name);
goto out;
}
/* Add to tail so next look get the correct order */
list_add_tail(&irq_name->list, &ctx->irq_names);
j++;
}
}
return 0;
out:
cxl_release_irq_ranges(&ctx->irqs, ctx->afu->adapter);
afu_irq_name_free(ctx);
return -ENOMEM;
}
static void afu_register_hwirqs(struct cxl_context *ctx)
{
irq_hw_number_t hwirq;
struct cxl_irq_name *irq_name;
int r,i;
/* We've allocated all memory now, so let's do the irq allocations */
irq_name = list_first_entry(&ctx->irq_names, struct cxl_irq_name, list);
for (r = 1; r < CXL_IRQ_RANGES; r++) {
hwirq = ctx->irqs.offset[r];
for (i = 0; i < ctx->irqs.range[r]; hwirq++, i++) {
cxl_map_irq(ctx->afu->adapter, hwirq,
cxl_irq_afu, ctx, irq_name->name);
irq_name = list_next_entry(irq_name, list);
}
}
}
int afu_register_irqs(struct cxl_context *ctx, u32 count)
{
int rc;
rc = afu_allocate_irqs(ctx, count);
if (rc)
return rc;
afu_register_hwirqs(ctx);
return 0;
}
void afu_release_irqs(struct cxl_context *ctx, void *cookie)
{
irq_hw_number_t hwirq;
unsigned int virq;
int r, i;
for (r = 1; r < CXL_IRQ_RANGES; r++) {
hwirq = ctx->irqs.offset[r];
for (i = 0; i < ctx->irqs.range[r]; hwirq++, i++) {
virq = irq_find_mapping(NULL, hwirq);
if (virq)
cxl_unmap_irq(virq, cookie);
}
}
afu_irq_name_free(ctx);
cxl_release_irq_ranges(&ctx->irqs, ctx->afu->adapter);
ctx->irq_count = 0;
}
| gpl-2.0 |
zaidshb/semc-kernel-qsd8k | net/core/stream.c | 176 | 5117 | /*
* SUCS NET3:
*
* Generic stream handling routines. These are generic for most
* protocols. Even IP. Tonight 8-).
* This is used because TCP, LLC (others too) layer all have mostly
* identical sendmsg() and recvmsg() code.
* So we (will) share it here.
*
* Authors: Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* (from old tcp.c code)
* Alan Cox <alan@lxorguk.ukuu.org.uk> (Borrowed comments 8-))
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/signal.h>
#include <linux/tcp.h>
#include <linux/wait.h>
#include <net/sock.h>
/**
* sk_stream_write_space - stream socket write_space callback.
* @sk: socket
*
* FIXME: write proper description
*/
void sk_stream_write_space(struct sock *sk)
{
struct socket *sock = sk->sk_socket;
if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk) && sock) {
clear_bit(SOCK_NOSPACE, &sock->flags);
if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
wake_up_interruptible(sk->sk_sleep);
if (sock->fasync_list && !(sk->sk_shutdown & SEND_SHUTDOWN))
sock_wake_async(sock, SOCK_WAKE_SPACE, POLL_OUT);
}
}
EXPORT_SYMBOL(sk_stream_write_space);
/**
* sk_stream_wait_connect - Wait for a socket to get into the connected state
* @sk: sock to wait on
* @timeo_p: for how long to wait
*
* Must be called with the socket locked.
*/
int sk_stream_wait_connect(struct sock *sk, long *timeo_p)
{
struct task_struct *tsk = current;
DEFINE_WAIT(wait);
int done;
do {
int err = sock_error(sk);
if (err)
return err;
if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV))
return -EPIPE;
if (!*timeo_p)
return -EAGAIN;
if (signal_pending(tsk))
return sock_intr_errno(*timeo_p);
prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
sk->sk_write_pending++;
done = sk_wait_event(sk, timeo_p,
!sk->sk_err &&
!((1 << sk->sk_state) &
~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)));
finish_wait(sk->sk_sleep, &wait);
sk->sk_write_pending--;
} while (!done);
return 0;
}
EXPORT_SYMBOL(sk_stream_wait_connect);
/**
* sk_stream_closing - Return 1 if we still have things to send in our buffers.
* @sk: socket to verify
*/
static inline int sk_stream_closing(struct sock *sk)
{
return (1 << sk->sk_state) &
(TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_LAST_ACK);
}
void sk_stream_wait_close(struct sock *sk, long timeout)
{
if (timeout) {
DEFINE_WAIT(wait);
do {
prepare_to_wait(sk->sk_sleep, &wait,
TASK_INTERRUPTIBLE);
if (sk_wait_event(sk, &timeout, !sk_stream_closing(sk)))
break;
} while (!signal_pending(current) && timeout);
finish_wait(sk->sk_sleep, &wait);
}
}
EXPORT_SYMBOL(sk_stream_wait_close);
/**
* sk_stream_wait_memory - Wait for more memory for a socket
* @sk: socket to wait for memory
* @timeo_p: for how long
*/
int sk_stream_wait_memory(struct sock *sk, long *timeo_p)
{
int err = 0;
long vm_wait = 0;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
if (sk_stream_memory_free(sk))
current_timeo = vm_wait = (net_random() % (HZ / 5)) + 2;
while (1) {
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
goto do_error;
if (!*timeo_p)
goto do_nonblock;
if (signal_pending(current))
goto do_interrupted;
clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
if (sk_stream_memory_free(sk) && !vm_wait)
break;
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
sk->sk_write_pending++;
sk_wait_event(sk, ¤t_timeo, !sk->sk_err &&
!(sk->sk_shutdown & SEND_SHUTDOWN) &&
sk_stream_memory_free(sk) &&
vm_wait);
sk->sk_write_pending--;
if (vm_wait) {
vm_wait -= current_timeo;
current_timeo = *timeo_p;
if (current_timeo != MAX_SCHEDULE_TIMEOUT &&
(current_timeo -= vm_wait) < 0)
current_timeo = 0;
vm_wait = 0;
}
*timeo_p = current_timeo;
}
out:
finish_wait(sk->sk_sleep, &wait);
return err;
do_error:
err = -EPIPE;
goto out;
do_nonblock:
err = -EAGAIN;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
}
EXPORT_SYMBOL(sk_stream_wait_memory);
int sk_stream_error(struct sock *sk, int flags, int err)
{
if (err == -EPIPE)
err = sock_error(sk) ? : -EPIPE;
if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
return err;
}
EXPORT_SYMBOL(sk_stream_error);
void sk_stream_kill_queues(struct sock *sk)
{
/* First the read buffer. */
__skb_queue_purge(&sk->sk_receive_queue);
/* Next, the error queue. */
__skb_queue_purge(&sk->sk_error_queue);
/* Next, the write queue. */
WARN_ON(!skb_queue_empty(&sk->sk_write_queue));
/* Account for returned memory. */
sk_mem_reclaim(sk);
WARN_ON(sk->sk_wmem_queued);
WARN_ON(sk->sk_forward_alloc);
/* It is _impossible_ for the backlog to contain anything
* when we get here. All user references to this socket
* have gone away, only the net layer knows can touch it.
*/
}
EXPORT_SYMBOL(sk_stream_kill_queues);
| gpl-2.0 |
ravikwow/jordan-kernel | fs/cifs/readdir.c | 432 | 26439 | /*
* fs/cifs/readdir.c
*
* Directory search handling
*
* Copyright (C) International Business Machines Corp., 2004, 2008
* Author(s): Steve French (sfrench@us.ibm.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/stat.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_unicode.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include "cifsfs.h"
/*
* To be safe - for UCS to UTF-8 with strings loaded with the rare long
* characters alloc more to account for such multibyte target UTF-8
* characters.
*/
#define UNICODE_NAME_MAX ((4 * NAME_MAX) + 2)
#ifdef CONFIG_CIFS_DEBUG2
static void dump_cifs_file_struct(struct file *file, char *label)
{
struct cifsFileInfo *cf;
if (file) {
cf = file->private_data;
if (cf == NULL) {
cFYI(1, ("empty cifs private file data"));
return;
}
if (cf->invalidHandle)
cFYI(1, ("invalid handle"));
if (cf->srch_inf.endOfSearch)
cFYI(1, ("end of search"));
if (cf->srch_inf.emptyDir)
cFYI(1, ("empty dir"));
}
}
#else
static inline void dump_cifs_file_struct(struct file *file, char *label)
{
}
#endif /* DEBUG2 */
/*
* Find the dentry that matches "name". If there isn't one, create one. If it's
* a negative dentry or the uniqueid changed, then drop it and recreate it.
*/
static struct dentry *
cifs_readdir_lookup(struct dentry *parent, struct qstr *name,
struct cifs_fattr *fattr)
{
struct dentry *dentry, *alias;
struct inode *inode;
struct super_block *sb = parent->d_inode->i_sb;
cFYI(1, ("For %s", name->name));
dentry = d_lookup(parent, name);
if (dentry) {
/* FIXME: check for inode number changes? */
if (dentry->d_inode != NULL)
return dentry;
d_drop(dentry);
dput(dentry);
}
dentry = d_alloc(parent, name);
if (dentry == NULL)
return NULL;
inode = cifs_iget(sb, fattr);
if (!inode) {
dput(dentry);
return NULL;
}
if (CIFS_SB(sb)->tcon->nocase)
dentry->d_op = &cifs_ci_dentry_ops;
else
dentry->d_op = &cifs_dentry_ops;
alias = d_materialise_unique(dentry, inode);
if (alias != NULL) {
dput(dentry);
if (IS_ERR(alias))
return NULL;
dentry = alias;
}
return dentry;
}
static void
cifs_fill_common_info(struct cifs_fattr *fattr, struct cifs_sb_info *cifs_sb)
{
fattr->cf_uid = cifs_sb->mnt_uid;
fattr->cf_gid = cifs_sb->mnt_gid;
if (fattr->cf_cifsattrs & ATTR_DIRECTORY) {
fattr->cf_mode = S_IFDIR | cifs_sb->mnt_dir_mode;
fattr->cf_dtype = DT_DIR;
} else {
fattr->cf_mode = S_IFREG | cifs_sb->mnt_file_mode;
fattr->cf_dtype = DT_REG;
}
if (fattr->cf_cifsattrs & ATTR_READONLY)
fattr->cf_mode &= ~S_IWUGO;
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL &&
fattr->cf_cifsattrs & ATTR_SYSTEM) {
if (fattr->cf_eof == 0) {
fattr->cf_mode &= ~S_IFMT;
fattr->cf_mode |= S_IFIFO;
fattr->cf_dtype = DT_FIFO;
} else {
/*
* trying to get the type and mode via SFU can be slow,
* so just call those regular files for now, and mark
* for reval
*/
fattr->cf_flags |= CIFS_FATTR_NEED_REVAL;
}
}
}
static void
cifs_dir_info_to_fattr(struct cifs_fattr *fattr, FILE_DIRECTORY_INFO *info,
struct cifs_sb_info *cifs_sb)
{
memset(fattr, 0, sizeof(*fattr));
fattr->cf_cifsattrs = le32_to_cpu(info->ExtFileAttributes);
fattr->cf_eof = le64_to_cpu(info->EndOfFile);
fattr->cf_bytes = le64_to_cpu(info->AllocationSize);
fattr->cf_atime = cifs_NTtimeToUnix(info->LastAccessTime);
fattr->cf_ctime = cifs_NTtimeToUnix(info->ChangeTime);
fattr->cf_mtime = cifs_NTtimeToUnix(info->LastWriteTime);
cifs_fill_common_info(fattr, cifs_sb);
}
static void
cifs_std_info_to_fattr(struct cifs_fattr *fattr, FIND_FILE_STANDARD_INFO *info,
struct cifs_sb_info *cifs_sb)
{
int offset = cifs_sb->tcon->ses->server->timeAdj;
memset(fattr, 0, sizeof(*fattr));
fattr->cf_atime = cnvrtDosUnixTm(info->LastAccessDate,
info->LastAccessTime, offset);
fattr->cf_ctime = cnvrtDosUnixTm(info->LastWriteDate,
info->LastWriteTime, offset);
fattr->cf_mtime = cnvrtDosUnixTm(info->LastWriteDate,
info->LastWriteTime, offset);
fattr->cf_cifsattrs = le16_to_cpu(info->Attributes);
fattr->cf_bytes = le32_to_cpu(info->AllocationSize);
fattr->cf_eof = le32_to_cpu(info->DataSize);
cifs_fill_common_info(fattr, cifs_sb);
}
/* BB eventually need to add the following helper function to
resolve NT_STATUS_STOPPED_ON_SYMLINK return code when
we try to do FindFirst on (NTFS) directory symlinks */
/*
int get_symlink_reparse_path(char *full_path, struct cifs_sb_info *cifs_sb,
int xid)
{
__u16 fid;
int len;
int oplock = 0;
int rc;
struct cifsTconInfo *ptcon = cifs_sb->tcon;
char *tmpbuffer;
rc = CIFSSMBOpen(xid, ptcon, full_path, FILE_OPEN, GENERIC_READ,
OPEN_REPARSE_POINT, &fid, &oplock, NULL,
cifs_sb->local_nls,
cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR);
if (!rc) {
tmpbuffer = kmalloc(maxpath);
rc = CIFSSMBQueryReparseLinkInfo(xid, ptcon, full_path,
tmpbuffer,
maxpath -1,
fid,
cifs_sb->local_nls);
if (CIFSSMBClose(xid, ptcon, fid)) {
cFYI(1, ("Error closing temporary reparsepoint open)"));
}
}
}
*/
static int initiate_cifs_search(const int xid, struct file *file)
{
int rc = 0;
char *full_path;
struct cifsFileInfo *cifsFile;
struct cifs_sb_info *cifs_sb;
struct cifsTconInfo *pTcon;
if (file->private_data == NULL) {
file->private_data =
kzalloc(sizeof(struct cifsFileInfo), GFP_KERNEL);
}
if (file->private_data == NULL)
return -ENOMEM;
cifsFile = file->private_data;
cifsFile->invalidHandle = true;
cifsFile->srch_inf.endOfSearch = false;
cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
if (cifs_sb == NULL)
return -EINVAL;
pTcon = cifs_sb->tcon;
if (pTcon == NULL)
return -EINVAL;
full_path = build_path_from_dentry(file->f_path.dentry);
if (full_path == NULL)
return -ENOMEM;
cFYI(1, ("Full path: %s start at: %lld", full_path, file->f_pos));
ffirst_retry:
/* test for Unix extensions */
/* but now check for them on the share/mount not on the SMB session */
/* if (pTcon->ses->capabilities & CAP_UNIX) { */
if (pTcon->unix_ext)
cifsFile->srch_inf.info_level = SMB_FIND_FILE_UNIX;
else if ((pTcon->ses->capabilities &
(CAP_NT_SMBS | CAP_NT_FIND)) == 0) {
cifsFile->srch_inf.info_level = SMB_FIND_FILE_INFO_STANDARD;
} else if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
cifsFile->srch_inf.info_level = SMB_FIND_FILE_ID_FULL_DIR_INFO;
} else /* not srvinos - BB fixme add check for backlevel? */ {
cifsFile->srch_inf.info_level = SMB_FIND_FILE_DIRECTORY_INFO;
}
rc = CIFSFindFirst(xid, pTcon, full_path, cifs_sb->local_nls,
&cifsFile->netfid, &cifsFile->srch_inf,
cifs_sb->mnt_cifs_flags &
CIFS_MOUNT_MAP_SPECIAL_CHR, CIFS_DIR_SEP(cifs_sb));
if (rc == 0)
cifsFile->invalidHandle = false;
/* BB add following call to handle readdir on new NTFS symlink errors
else if STATUS_STOPPED_ON_SYMLINK
call get_symlink_reparse_path and retry with new path */
else if ((rc == -EOPNOTSUPP) &&
(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM)) {
cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
goto ffirst_retry;
}
kfree(full_path);
return rc;
}
/* return length of unicode string in bytes */
static int cifs_unicode_bytelen(char *str)
{
int len;
__le16 *ustr = (__le16 *)str;
for (len = 0; len <= PATH_MAX; len++) {
if (ustr[len] == 0)
return len << 1;
}
cFYI(1, ("Unicode string longer than PATH_MAX found"));
return len << 1;
}
static char *nxt_dir_entry(char *old_entry, char *end_of_smb, int level)
{
char *new_entry;
FILE_DIRECTORY_INFO *pDirInfo = (FILE_DIRECTORY_INFO *)old_entry;
if (level == SMB_FIND_FILE_INFO_STANDARD) {
FIND_FILE_STANDARD_INFO *pfData;
pfData = (FIND_FILE_STANDARD_INFO *)pDirInfo;
new_entry = old_entry + sizeof(FIND_FILE_STANDARD_INFO) +
pfData->FileNameLength;
} else
new_entry = old_entry + le32_to_cpu(pDirInfo->NextEntryOffset);
cFYI(1, ("new entry %p old entry %p", new_entry, old_entry));
/* validate that new_entry is not past end of SMB */
if (new_entry >= end_of_smb) {
cERROR(1,
("search entry %p began after end of SMB %p old entry %p",
new_entry, end_of_smb, old_entry));
return NULL;
} else if (((level == SMB_FIND_FILE_INFO_STANDARD) &&
(new_entry + sizeof(FIND_FILE_STANDARD_INFO) > end_of_smb))
|| ((level != SMB_FIND_FILE_INFO_STANDARD) &&
(new_entry + sizeof(FILE_DIRECTORY_INFO) > end_of_smb))) {
cERROR(1, ("search entry %p extends after end of SMB %p",
new_entry, end_of_smb));
return NULL;
} else
return new_entry;
}
#define UNICODE_DOT cpu_to_le16(0x2e)
/* return 0 if no match and 1 for . (current directory) and 2 for .. (parent) */
static int cifs_entry_is_dot(char *current_entry, struct cifsFileInfo *cfile)
{
int rc = 0;
char *filename = NULL;
int len = 0;
if (cfile->srch_inf.info_level == SMB_FIND_FILE_UNIX) {
FILE_UNIX_INFO *pFindData = (FILE_UNIX_INFO *)current_entry;
filename = &pFindData->FileName[0];
if (cfile->srch_inf.unicode) {
len = cifs_unicode_bytelen(filename);
} else {
/* BB should we make this strnlen of PATH_MAX? */
len = strnlen(filename, 5);
}
} else if (cfile->srch_inf.info_level == SMB_FIND_FILE_DIRECTORY_INFO) {
FILE_DIRECTORY_INFO *pFindData =
(FILE_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (cfile->srch_inf.info_level ==
SMB_FIND_FILE_FULL_DIRECTORY_INFO) {
FILE_FULL_DIRECTORY_INFO *pFindData =
(FILE_FULL_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (cfile->srch_inf.info_level ==
SMB_FIND_FILE_ID_FULL_DIR_INFO) {
SEARCH_ID_FULL_DIR_INFO *pFindData =
(SEARCH_ID_FULL_DIR_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (cfile->srch_inf.info_level ==
SMB_FIND_FILE_BOTH_DIRECTORY_INFO) {
FILE_BOTH_DIRECTORY_INFO *pFindData =
(FILE_BOTH_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (cfile->srch_inf.info_level == SMB_FIND_FILE_INFO_STANDARD) {
FIND_FILE_STANDARD_INFO *pFindData =
(FIND_FILE_STANDARD_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = pFindData->FileNameLength;
} else {
cFYI(1, ("Unknown findfirst level %d",
cfile->srch_inf.info_level));
}
if (filename) {
if (cfile->srch_inf.unicode) {
__le16 *ufilename = (__le16 *)filename;
if (len == 2) {
/* check for . */
if (ufilename[0] == UNICODE_DOT)
rc = 1;
} else if (len == 4) {
/* check for .. */
if ((ufilename[0] == UNICODE_DOT)
&& (ufilename[1] == UNICODE_DOT))
rc = 2;
}
} else /* ASCII */ {
if (len == 1) {
if (filename[0] == '.')
rc = 1;
} else if (len == 2) {
if ((filename[0] == '.') && (filename[1] == '.'))
rc = 2;
}
}
}
return rc;
}
/* Check if directory that we are searching has changed so we can decide
whether we can use the cached search results from the previous search */
static int is_dir_changed(struct file *file)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct cifsInodeInfo *cifsInfo = CIFS_I(inode);
if (cifsInfo->time == 0)
return 1; /* directory was changed, perhaps due to unlink */
else
return 0;
}
static int cifs_save_resume_key(const char *current_entry,
struct cifsFileInfo *cifsFile)
{
int rc = 0;
unsigned int len = 0;
__u16 level;
char *filename;
if ((cifsFile == NULL) || (current_entry == NULL))
return -EINVAL;
level = cifsFile->srch_inf.info_level;
if (level == SMB_FIND_FILE_UNIX) {
FILE_UNIX_INFO *pFindData = (FILE_UNIX_INFO *)current_entry;
filename = &pFindData->FileName[0];
if (cifsFile->srch_inf.unicode) {
len = cifs_unicode_bytelen(filename);
} else {
/* BB should we make this strnlen of PATH_MAX? */
len = strnlen(filename, PATH_MAX);
}
cifsFile->srch_inf.resume_key = pFindData->ResumeKey;
} else if (level == SMB_FIND_FILE_DIRECTORY_INFO) {
FILE_DIRECTORY_INFO *pFindData =
(FILE_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
cifsFile->srch_inf.resume_key = pFindData->FileIndex;
} else if (level == SMB_FIND_FILE_FULL_DIRECTORY_INFO) {
FILE_FULL_DIRECTORY_INFO *pFindData =
(FILE_FULL_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
cifsFile->srch_inf.resume_key = pFindData->FileIndex;
} else if (level == SMB_FIND_FILE_ID_FULL_DIR_INFO) {
SEARCH_ID_FULL_DIR_INFO *pFindData =
(SEARCH_ID_FULL_DIR_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
cifsFile->srch_inf.resume_key = pFindData->FileIndex;
} else if (level == SMB_FIND_FILE_BOTH_DIRECTORY_INFO) {
FILE_BOTH_DIRECTORY_INFO *pFindData =
(FILE_BOTH_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
cifsFile->srch_inf.resume_key = pFindData->FileIndex;
} else if (level == SMB_FIND_FILE_INFO_STANDARD) {
FIND_FILE_STANDARD_INFO *pFindData =
(FIND_FILE_STANDARD_INFO *)current_entry;
filename = &pFindData->FileName[0];
/* one byte length, no name conversion */
len = (unsigned int)pFindData->FileNameLength;
cifsFile->srch_inf.resume_key = pFindData->ResumeKey;
} else {
cFYI(1, ("Unknown findfirst level %d", level));
return -EINVAL;
}
cifsFile->srch_inf.resume_name_len = len;
cifsFile->srch_inf.presume_name = filename;
return rc;
}
/* find the corresponding entry in the search */
/* Note that the SMB server returns search entries for . and .. which
complicates logic here if we choose to parse for them and we do not
assume that they are located in the findfirst return buffer.*/
/* We start counting in the buffer with entry 2 and increment for every
entry (do not increment for . or .. entry) */
static int find_cifs_entry(const int xid, struct cifsTconInfo *pTcon,
struct file *file, char **ppCurrentEntry, int *num_to_ret)
{
int rc = 0;
int pos_in_buf = 0;
loff_t first_entry_in_buffer;
loff_t index_to_find = file->f_pos;
struct cifsFileInfo *cifsFile = file->private_data;
/* check if index in the buffer */
if ((cifsFile == NULL) || (ppCurrentEntry == NULL) ||
(num_to_ret == NULL))
return -ENOENT;
*ppCurrentEntry = NULL;
first_entry_in_buffer =
cifsFile->srch_inf.index_of_last_entry -
cifsFile->srch_inf.entries_in_buffer;
/* if first entry in buf is zero then is first buffer
in search response data which means it is likely . and ..
will be in this buffer, although some servers do not return
. and .. for the root of a drive and for those we need
to start two entries earlier */
dump_cifs_file_struct(file, "In fce ");
if (((index_to_find < cifsFile->srch_inf.index_of_last_entry) &&
is_dir_changed(file)) ||
(index_to_find < first_entry_in_buffer)) {
/* close and restart search */
cFYI(1, ("search backing up - close and restart search"));
write_lock(&GlobalSMBSeslock);
if (!cifsFile->srch_inf.endOfSearch &&
!cifsFile->invalidHandle) {
cifsFile->invalidHandle = true;
write_unlock(&GlobalSMBSeslock);
CIFSFindClose(xid, pTcon, cifsFile->netfid);
} else
write_unlock(&GlobalSMBSeslock);
if (cifsFile->srch_inf.ntwrk_buf_start) {
cFYI(1, ("freeing SMB ff cache buf on search rewind"));
if (cifsFile->srch_inf.smallBuf)
cifs_small_buf_release(cifsFile->srch_inf.
ntwrk_buf_start);
else
cifs_buf_release(cifsFile->srch_inf.
ntwrk_buf_start);
cifsFile->srch_inf.ntwrk_buf_start = NULL;
}
rc = initiate_cifs_search(xid, file);
if (rc) {
cFYI(1, ("error %d reinitiating a search on rewind",
rc));
return rc;
}
cifs_save_resume_key(cifsFile->srch_inf.last_entry, cifsFile);
}
while ((index_to_find >= cifsFile->srch_inf.index_of_last_entry) &&
(rc == 0) && !cifsFile->srch_inf.endOfSearch) {
cFYI(1, ("calling findnext2"));
rc = CIFSFindNext(xid, pTcon, cifsFile->netfid,
&cifsFile->srch_inf);
cifs_save_resume_key(cifsFile->srch_inf.last_entry, cifsFile);
if (rc)
return -ENOENT;
}
if (index_to_find < cifsFile->srch_inf.index_of_last_entry) {
/* we found the buffer that contains the entry */
/* scan and find it */
int i;
char *current_entry;
char *end_of_smb = cifsFile->srch_inf.ntwrk_buf_start +
smbCalcSize((struct smb_hdr *)
cifsFile->srch_inf.ntwrk_buf_start);
current_entry = cifsFile->srch_inf.srch_entries_start;
first_entry_in_buffer = cifsFile->srch_inf.index_of_last_entry
- cifsFile->srch_inf.entries_in_buffer;
pos_in_buf = index_to_find - first_entry_in_buffer;
cFYI(1, ("found entry - pos_in_buf %d", pos_in_buf));
for (i = 0; (i < (pos_in_buf)) && (current_entry != NULL); i++) {
/* go entry by entry figuring out which is first */
current_entry = nxt_dir_entry(current_entry, end_of_smb,
cifsFile->srch_inf.info_level);
}
if ((current_entry == NULL) && (i < pos_in_buf)) {
/* BB fixme - check if we should flag this error */
cERROR(1, ("reached end of buf searching for pos in buf"
" %d index to find %lld rc %d",
pos_in_buf, index_to_find, rc));
}
rc = 0;
*ppCurrentEntry = current_entry;
} else {
cFYI(1, ("index not in buffer - could not findnext into it"));
return 0;
}
if (pos_in_buf >= cifsFile->srch_inf.entries_in_buffer) {
cFYI(1, ("can not return entries pos_in_buf beyond last"));
*num_to_ret = 0;
} else
*num_to_ret = cifsFile->srch_inf.entries_in_buffer - pos_in_buf;
return rc;
}
/* inode num, inode type and filename returned */
static int cifs_get_name_from_search_buf(struct qstr *pqst,
char *current_entry, __u16 level, unsigned int unicode,
struct cifs_sb_info *cifs_sb, unsigned int max_len, __u64 *pinum)
{
int rc = 0;
unsigned int len = 0;
char *filename;
struct nls_table *nlt = cifs_sb->local_nls;
*pinum = 0;
if (level == SMB_FIND_FILE_UNIX) {
FILE_UNIX_INFO *pFindData = (FILE_UNIX_INFO *)current_entry;
filename = &pFindData->FileName[0];
if (unicode) {
len = cifs_unicode_bytelen(filename);
} else {
/* BB should we make this strnlen of PATH_MAX? */
len = strnlen(filename, PATH_MAX);
}
*pinum = le64_to_cpu(pFindData->basic.UniqueId);
} else if (level == SMB_FIND_FILE_DIRECTORY_INFO) {
FILE_DIRECTORY_INFO *pFindData =
(FILE_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (level == SMB_FIND_FILE_FULL_DIRECTORY_INFO) {
FILE_FULL_DIRECTORY_INFO *pFindData =
(FILE_FULL_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (level == SMB_FIND_FILE_ID_FULL_DIR_INFO) {
SEARCH_ID_FULL_DIR_INFO *pFindData =
(SEARCH_ID_FULL_DIR_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
*pinum = le64_to_cpu(pFindData->UniqueId);
} else if (level == SMB_FIND_FILE_BOTH_DIRECTORY_INFO) {
FILE_BOTH_DIRECTORY_INFO *pFindData =
(FILE_BOTH_DIRECTORY_INFO *)current_entry;
filename = &pFindData->FileName[0];
len = le32_to_cpu(pFindData->FileNameLength);
} else if (level == SMB_FIND_FILE_INFO_STANDARD) {
FIND_FILE_STANDARD_INFO *pFindData =
(FIND_FILE_STANDARD_INFO *)current_entry;
filename = &pFindData->FileName[0];
/* one byte length, no name conversion */
len = (unsigned int)pFindData->FileNameLength;
} else {
cFYI(1, ("Unknown findfirst level %d", level));
return -EINVAL;
}
if (len > max_len) {
cERROR(1, ("bad search response length %d past smb end", len));
return -EINVAL;
}
if (unicode) {
pqst->len = cifs_from_ucs2((char *) pqst->name,
(__le16 *) filename,
UNICODE_NAME_MAX,
min(len, max_len), nlt,
cifs_sb->mnt_cifs_flags &
CIFS_MOUNT_MAP_SPECIAL_CHR);
pqst->len -= nls_nullsize(nlt);
} else {
pqst->name = filename;
pqst->len = len;
}
pqst->hash = full_name_hash(pqst->name, pqst->len);
/* cFYI(1, ("filldir on %s",pqst->name)); */
return rc;
}
static int cifs_filldir(char *pfindEntry, struct file *file, filldir_t filldir,
void *direntry, char *scratch_buf, unsigned int max_len)
{
int rc = 0;
struct qstr qstring;
struct cifsFileInfo *pCifsF;
u64 inum;
ino_t ino;
struct super_block *sb;
struct cifs_sb_info *cifs_sb;
struct dentry *tmp_dentry;
struct cifs_fattr fattr;
/* get filename and len into qstring */
/* get dentry */
/* decide whether to create and populate ionde */
if ((direntry == NULL) || (file == NULL))
return -EINVAL;
pCifsF = file->private_data;
if ((scratch_buf == NULL) || (pfindEntry == NULL) || (pCifsF == NULL))
return -ENOENT;
rc = cifs_entry_is_dot(pfindEntry, pCifsF);
/* skip . and .. since we added them first */
if (rc != 0)
return 0;
sb = file->f_path.dentry->d_sb;
cifs_sb = CIFS_SB(sb);
qstring.name = scratch_buf;
rc = cifs_get_name_from_search_buf(&qstring, pfindEntry,
pCifsF->srch_inf.info_level,
pCifsF->srch_inf.unicode, cifs_sb,
max_len, &inum /* returned */);
if (rc)
return rc;
if (pCifsF->srch_inf.info_level == SMB_FIND_FILE_UNIX)
cifs_unix_basic_to_fattr(&fattr,
&((FILE_UNIX_INFO *) pfindEntry)->basic,
cifs_sb);
else if (pCifsF->srch_inf.info_level == SMB_FIND_FILE_INFO_STANDARD)
cifs_std_info_to_fattr(&fattr, (FIND_FILE_STANDARD_INFO *)
pfindEntry, cifs_sb);
else
cifs_dir_info_to_fattr(&fattr, (FILE_DIRECTORY_INFO *)
pfindEntry, cifs_sb);
if (inum && (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM)) {
fattr.cf_uniqueid = inum;
} else {
fattr.cf_uniqueid = iunique(sb, ROOT_I);
cifs_autodisable_serverino(cifs_sb);
}
ino = cifs_uniqueid_to_ino_t(fattr.cf_uniqueid);
tmp_dentry = cifs_readdir_lookup(file->f_dentry, &qstring, &fattr);
rc = filldir(direntry, qstring.name, qstring.len, file->f_pos,
ino, fattr.cf_dtype);
/*
* we can not return filldir errors to the caller since they are
* "normal" when the stat blocksize is too small - we return remapped
* error instead
*
* FIXME: This looks bogus. filldir returns -EOVERFLOW in the above
* case already. Why should we be clobbering other errors from it?
*/
if (rc) {
cFYI(1, ("filldir rc = %d", rc));
rc = -EOVERFLOW;
}
dput(tmp_dentry);
return rc;
}
int cifs_readdir(struct file *file, void *direntry, filldir_t filldir)
{
int rc = 0;
int xid, i;
struct cifs_sb_info *cifs_sb;
struct cifsTconInfo *pTcon;
struct cifsFileInfo *cifsFile = NULL;
char *current_entry;
int num_to_fill = 0;
char *tmp_buf = NULL;
char *end_of_smb;
unsigned int max_len;
xid = GetXid();
cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
pTcon = cifs_sb->tcon;
if (pTcon == NULL)
return -EINVAL;
switch ((int) file->f_pos) {
case 0:
if (filldir(direntry, ".", 1, file->f_pos,
file->f_path.dentry->d_inode->i_ino, DT_DIR) < 0) {
cERROR(1, ("Filldir for current dir failed"));
rc = -ENOMEM;
break;
}
file->f_pos++;
case 1:
if (filldir(direntry, "..", 2, file->f_pos,
file->f_path.dentry->d_parent->d_inode->i_ino, DT_DIR) < 0) {
cERROR(1, ("Filldir for parent dir failed"));
rc = -ENOMEM;
break;
}
file->f_pos++;
default:
/* 1) If search is active,
is in current search buffer?
if it before then restart search
if after then keep searching till find it */
if (file->private_data == NULL) {
rc = initiate_cifs_search(xid, file);
cFYI(1, ("initiate cifs search rc %d", rc));
if (rc) {
FreeXid(xid);
return rc;
}
}
if (file->private_data == NULL) {
rc = -EINVAL;
FreeXid(xid);
return rc;
}
cifsFile = file->private_data;
if (cifsFile->srch_inf.endOfSearch) {
if (cifsFile->srch_inf.emptyDir) {
cFYI(1, ("End of search, empty dir"));
rc = 0;
break;
}
} /* else {
cifsFile->invalidHandle = true;
CIFSFindClose(xid, pTcon, cifsFile->netfid);
} */
rc = find_cifs_entry(xid, pTcon, file,
¤t_entry, &num_to_fill);
if (rc) {
cFYI(1, ("fce error %d", rc));
goto rddir2_exit;
} else if (current_entry != NULL) {
cFYI(1, ("entry %lld found", file->f_pos));
} else {
cFYI(1, ("could not find entry"));
goto rddir2_exit;
}
cFYI(1, ("loop through %d times filling dir for net buf %p",
num_to_fill, cifsFile->srch_inf.ntwrk_buf_start));
max_len = smbCalcSize((struct smb_hdr *)
cifsFile->srch_inf.ntwrk_buf_start);
end_of_smb = cifsFile->srch_inf.ntwrk_buf_start + max_len;
tmp_buf = kmalloc(UNICODE_NAME_MAX, GFP_KERNEL);
for (i = 0; (i < num_to_fill) && (rc == 0); i++) {
if (current_entry == NULL) {
/* evaluate whether this case is an error */
cERROR(1, ("past SMB end, num to fill %d i %d",
num_to_fill, i));
break;
}
/* if buggy server returns . and .. late do
we want to check for that here? */
rc = cifs_filldir(current_entry, file,
filldir, direntry, tmp_buf, max_len);
if (rc == -EOVERFLOW) {
rc = 0;
break;
}
file->f_pos++;
if (file->f_pos ==
cifsFile->srch_inf.index_of_last_entry) {
cFYI(1, ("last entry in buf at pos %lld %s",
file->f_pos, tmp_buf));
cifs_save_resume_key(current_entry, cifsFile);
break;
} else
current_entry =
nxt_dir_entry(current_entry, end_of_smb,
cifsFile->srch_inf.info_level);
}
kfree(tmp_buf);
break;
} /* end switch */
rddir2_exit:
FreeXid(xid);
return rc;
}
| gpl-2.0 |
jollaman999/msm-mako-lollipop-mr1 | drivers/media/radio/radio-tavarua.c | 432 | 141029 | /* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* Qualcomm Tavarua FM core driver
*/
/* driver definitions */
#define DRIVER_AUTHOR "Qualcomm"
#define DRIVER_NAME "radio-tavarua"
#define DRIVER_CARD "Qualcomm FM Radio Transceiver"
#define DRIVER_DESC "I2C radio driver for Qualcomm FM Radio Transceiver "
#define DRIVER_VERSION "1.0.0"
#include <linux/version.h>
#include <linux/init.h> /* Initdata */
#include <linux/delay.h> /* udelay */
#include <linux/uaccess.h> /* copy to/from user */
#include <linux/kfifo.h> /* lock free circular buffer */
#include <linux/param.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
/* kernel includes */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/videodev2.h>
#include <linux/mutex.h>
#include <media/v4l2-common.h>
#include <asm/unaligned.h>
#include <media/v4l2-ioctl.h>
#include <linux/unistd.h>
#include <asm/atomic.h>
#include <media/tavarua.h>
#include <linux/mfd/marimba.h>
#include <linux/platform_device.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
/*
regional parameters for radio device
*/
struct region_params_t {
enum tavarua_region_t region;
unsigned int band_high;
unsigned int band_low;
char emphasis;
char rds_std;
char spacing;
};
struct srch_params_t {
unsigned short srch_pi;
unsigned char srch_pty;
unsigned int preset_num;
int get_list;
};
/* Main radio device structure,
acts as a shadow copy of the
actual tavaura registers */
struct tavarua_device {
struct video_device *videodev;
/* driver management */
atomic_t users;
/* top level driver data */
struct marimba *marimba;
struct device *dev;
/* platform specific functionality */
struct marimba_fm_platform_data *pdata;
unsigned int chipID;
/*RDS buffers + Radio event buffer*/
struct kfifo data_buf[TAVARUA_BUF_MAX];
/* search paramters */
struct srch_params_t srch_params;
/* keep track of pending xfrs */
int pending_xfrs[TAVARUA_XFR_MAX];
int xfr_bytes_left;
int xfr_in_progress;
/* Transmit data */
enum tavarua_xfr_ctrl_t tx_mode;
/* synchrnous xfr data */
unsigned char sync_xfr_regs[XFR_REG_NUM];
struct completion sync_xfr_start;
struct completion shutdown_done;
struct completion sync_req_done;
int tune_req;
/* internal register status */
unsigned char registers[RADIO_REGISTERS];
/* regional settings */
struct region_params_t region_params;
/* power mode */
int lp_mode;
int handle_irq;
/* global lock */
struct mutex lock;
/* buffer locks*/
spinlock_t buf_lock[TAVARUA_BUF_MAX];
/* work queue */
struct workqueue_struct *wqueue;
struct delayed_work work;
/* wait queue for blocking event read */
wait_queue_head_t event_queue;
/* wait queue for raw rds read */
wait_queue_head_t read_queue;
/* PTY for FM Tx */
int pty;
/* PI for FM TX */
int pi;
/*PS repeatcount for PS Tx */
int ps_repeatcount;
int enable_optimized_srch_alg;
unsigned char spur_table_size;
struct fm_spur_data spur_data;
atomic_t validate_channel;
unsigned char is_station_valid;
};
/**************************************************************************
* Module Parameters
**************************************************************************/
/* Radio Nr */
static int radio_nr = -1;
module_param(radio_nr, int, 0);
MODULE_PARM_DESC(radio_nr, "Radio Nr");
static int wait_timeout = WAIT_TIMEOUT;
/* Bahama's version*/
static u8 bahama_version;
/* RDS buffer blocks */
static unsigned int rds_buf = 100;
module_param(rds_buf, uint, 0);
MODULE_PARM_DESC(rds_buf, "RDS buffer entries: *100*");
/* static variables */
static struct tavarua_device *private_data;
/* forward declerations */
static int tavarua_disable_interrupts(struct tavarua_device *radio);
static int tavarua_setup_interrupts(struct tavarua_device *radio,
enum radio_state_t state);
static int tavarua_start(struct tavarua_device *radio,
enum radio_state_t state);
static int tavarua_request_irq(struct tavarua_device *radio);
static void start_pending_xfr(struct tavarua_device *radio);
static int update_spur_table(struct tavarua_device *radio);
static int xfr_rdwr_data(struct tavarua_device *radio, int op, int size,
unsigned long offset, unsigned char *buf);
static int compute_MPX_DCC(struct tavarua_device *radio, int *val);
/* work function */
static void read_int_stat(struct work_struct *work);
static int is_bahama(void)
{
int id = 0;
switch (id = adie_get_detected_connectivity_type()) {
case BAHAMA_ID:
FMDBG("It is Bahama\n");
return 1;
case MARIMBA_ID:
FMDBG("It is Marimba\n");
return 0;
default:
printk(KERN_ERR "%s: unexpected adie connectivity type: %d\n",
__func__, id);
return -ENODEV;
}
}
static int set_fm_slave_id(struct tavarua_device *radio)
{
int bahama_present = is_bahama();
if (bahama_present == -ENODEV)
return -ENODEV;
if (bahama_present)
radio->marimba->mod_id = SLAVE_ID_BAHAMA_FM;
else
radio->marimba->mod_id = MARIMBA_SLAVE_ID_FM;
return 0;
}
/*=============================================================================
FUNCTION: tavarua_isr
=============================================================================*/
/**
This function is called when GPIO is toggled. This functions queues the event
to interrupt queue, which is later handled by isr handling funcion.
i.e. INIT_DELAYED_WORK(&radio->work, read_int_stat);
@param irq: irq that is toggled.
@param dev_id: structure pointer passed by client.
@return IRQ_HANDLED.
*/
static irqreturn_t tavarua_isr(int irq, void *dev_id)
{
struct tavarua_device *radio = dev_id;
/* schedule a tasklet to handle host intr */
/* The call to queue_delayed_work ensures that a minimum delay (in jiffies)
* passes before the work is actually executed. The return value from the
* function is nonzero if the work_struct was actually added to queue
* (otherwise, it may have already been there and will not be added a second
* time).
*/
queue_delayed_work(radio->wqueue, &radio->work,
msecs_to_jiffies(TAVARUA_DELAY));
return IRQ_HANDLED;
}
/**************************************************************************
* Interface to radio internal registers over top level marimba driver
*************************************************************************/
/*=============================================================================
FUNCTION: tavarua_read_registers
=============================================================================*/
/**
This function is called to read a number of bytes from an I2C interface.
The bytes read are stored in internal register status (shadow copy).
@param radio: structure pointer passed by client.
@param offset: register offset.
@param len: num of bytes.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_read_registers(struct tavarua_device *radio,
unsigned char offset, int len)
{
int retval = 0, i = 0;
retval = set_fm_slave_id(radio);
if (retval == -ENODEV)
return retval;
FMDBG_I2C("I2C Slave: %x, Read Offset(%x): Data [",
radio->marimba->mod_id,
offset);
retval = marimba_read(radio->marimba, offset,
&radio->registers[offset], len);
if (retval > 0) {
for (i = 0; i < len; i++)
FMDBG_I2C("%02x ", radio->registers[offset+i]);
FMDBG_I2C(" ]\n");
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_write_register
=============================================================================*/
/**
This function is called to write a byte over the I2C interface.
The corresponding shadow copy is stored in internal register status.
@param radio: structure pointer passed by client.
@param offset: register offset.
@param value: buffer to be written to the registers.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_write_register(struct tavarua_device *radio,
unsigned char offset, unsigned char value)
{
int retval;
retval = set_fm_slave_id(radio);
if (retval == -ENODEV)
return retval;
FMDBG_I2C("I2C Slave: %x, Write Offset(%x): Data[",
radio->marimba->mod_id,
offset);
retval = marimba_write(radio->marimba, offset, &value, 1);
if (retval > 0) {
if (offset < RADIO_REGISTERS) {
radio->registers[offset] = value;
FMDBG_I2C("%02x ", radio->registers[offset]);
}
FMDBG_I2C(" ]\n");
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_write_registers
=============================================================================*/
/**
This function is called to write a number of bytes over the I2C interface.
The corresponding shadow copy is stored in internal register status.
@param radio: structure pointer passed by client.
@param offset: register offset.
@param buf: buffer to be written to the registers.
@param len: num of bytes.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_write_registers(struct tavarua_device *radio,
unsigned char offset, unsigned char *buf, int len)
{
int i;
int retval;
retval = set_fm_slave_id(radio);
if (retval == -ENODEV)
return retval;
FMDBG_I2C("I2C Slave: %x, Write Offset(%x): Data[",
radio->marimba->mod_id,
offset);
retval = marimba_write(radio->marimba, offset, buf, len);
if (retval > 0) { /* if write successful, update internal state too */
for (i = 0; i < len; i++) {
if ((offset+i) < RADIO_REGISTERS) {
radio->registers[offset+i] = buf[i];
FMDBG_I2C("%x ", radio->registers[offset+i]);
}
}
FMDBG_I2C(" ]\n");
}
return retval;
}
/*=============================================================================
FUNCTION: read_data_blocks
=============================================================================*/
/**
This function reads Raw RDS blocks from Core regs to driver
internal regs (shadow copy).
@param radio: structure pointer passed by client.
@param offset: register offset.
@return => 0 if successful.
@return < 0 if failure.
*/
static int read_data_blocks(struct tavarua_device *radio, unsigned char offset)
{
/* read all 3 RDS blocks */
return tavarua_read_registers(radio, offset, RDS_BLOCK*4);
}
/*=============================================================================
FUNCTION: tavarua_rds_read
=============================================================================*/
/**
This is a rds processing function reads that reads Raw RDS blocks from Core
regs to driver internal regs (shadow copy). It then fills the V4L2 RDS buffer,
which is read by App using JNI interface.
@param radio: structure pointer passed by client.
@return None.
*/
static void tavarua_rds_read(struct tavarua_device *radio)
{
struct kfifo *rds_buf = &radio->data_buf[TAVARUA_BUF_RAW_RDS];
unsigned char blocknum;
unsigned char tmp[3];
if (read_data_blocks(radio, RAW_RDS) < 0)
return;
/* copy all four RDS blocks to internal buffer */
for (blocknum = 0; blocknum < RDS_BLOCKS_NUM; blocknum++) {
/* Fill the V4L2 RDS buffer */
put_unaligned(cpu_to_le16(radio->registers[RAW_RDS +
blocknum*RDS_BLOCK]), (unsigned short *) tmp);
tmp[2] = blocknum; /* offset name */
tmp[2] |= blocknum << 3; /* received offset */
tmp[2] |= 0x40; /* corrected error(s) */
/* copy RDS block to internal buffer */
kfifo_in_locked(rds_buf, tmp, 3, &radio->buf_lock[TAVARUA_BUF_RAW_RDS]);
}
/* wake up read queue */
if (kfifo_len(rds_buf))
wake_up_interruptible(&radio->read_queue);
}
/*=============================================================================
FUNCTION: request_read_xfr
=============================================================================*/
/**
This function sets the desired MODE in the XFRCTRL register and also sets the
CTRL field to read.
This is an asynchronous way of reading the XFR registers. Client would request
by setting the desired mode in the XFRCTRL register and then would initiate
the actual data register read by calling copy_from_xfr up on SOC signals
success.
NOTE:
The Data Transfer (XFR) registers are used to pass various data and
configuration parameters between the Core and host processor.
To read from the XFR registers, the host processor must set the desired MODE
in the XFRCTRL register and set the CTRL field to read. The Core will then
populate the XFRDAT0 - XFRDAT15 registers with the defined mode bytes. The
Core will set the TRANSFER interrupt status bit and interrupt the host if the
TRANSFERCTRL interrupt control bit is set. The host can then extract the XFR
mode bytes once it detects that the Core has updated the registers.
@param radio: structure pointer passed by client.
@return Always returns 0.
*/
static int request_read_xfr(struct tavarua_device *radio,
enum tavarua_xfr_ctrl_t mode){
tavarua_write_register(radio, XFRCTRL, mode);
msleep(TAVARUA_DELAY);
return 0;
}
/*=============================================================================
FUNCTION: copy_from_xfr
=============================================================================*/
/**
This function is used to read XFR mode bytes once it detects that the Core
has updated the registers. It also updates XFR regs to the appropriate
internal buffer n bytes.
NOTE:
This function should be used in conjuction with request_read_xfr. Refer
request_read_xfr for XFR mode transaction details.
@param radio: structure pointer passed by client.
@param buf_type: Index into RDS/Radio event buffer to use.
@param len: num of bytes.
@return Always returns 0.
*/
static int copy_from_xfr(struct tavarua_device *radio,
enum tavarua_buf_t buf_type, unsigned int n){
struct kfifo *data_fifo = &radio->data_buf[buf_type];
unsigned char *xfr_regs = &radio->registers[XFRCTRL+1];
kfifo_in_locked(data_fifo, xfr_regs, n, &radio->buf_lock[buf_type]);
return 0;
}
/*=============================================================================
FUNCTION: write_to_xfr
=============================================================================*/
/**
This function sets the desired MODE in the XFRCTRL register and it also sets
the CTRL field and data to write.
This also writes all the XFRDATx registers with the desired input buffer.
NOTE:
The Data Transfer (XFR) registers are used to pass various data and
configuration parameters between the Core and host processor.
To write data to the Core, the host processor updates XFRDAT0 - XFRDAT15 with
the appropriate mode bytes. The host processor must then set the desired MODE
in the XFRCTRL register and set the CTRL field to write. The core will detect
that the XFRCTRL register was written to and will read the XFR mode bytes.
After reading all the mode bytes, the Core will set the TRANSFER interrupt
status bit and interrupt the host if the TRANSFERCTRL interrupt control bit
is set.
@param radio: structure pointer passed by client.
@param mode: XFR mode to write in XFRCTRL register.
@param buf: buffer to be written to the registers.
@param len: num of bytes.
@return => 0 if successful.
@return < 0 if failure.
*/
static int write_to_xfr(struct tavarua_device *radio, unsigned char mode,
char *buf, int len)
{
char buffer[len+1];
memcpy(buffer+1, buf, len);
/* buffer[0] corresponds to XFRCTRL register
set the CTRL bit to 1 for write mode
*/
buffer[0] = ((1<<7) | mode);
return tavarua_write_registers(radio, XFRCTRL, buffer, sizeof(buffer));
}
/*=============================================================================
FUNCTION: xfr_intf_own
=============================================================================*/
/**
This function is used to check if there is any pending XFR mode operation.
If yes, wait for it to complete, else update the flag to indicate XFR
operation is in progress
@param radio: structure pointer passed by client.
@return 0 on success.
-ETIME on timeout.
*/
static int xfr_intf_own(struct tavarua_device *radio)
{
mutex_lock(&radio->lock);
if (radio->xfr_in_progress) {
radio->pending_xfrs[TAVARUA_XFR_SYNC] = 1;
mutex_unlock(&radio->lock);
if (!wait_for_completion_timeout(&radio->sync_xfr_start,
msecs_to_jiffies(wait_timeout)))
return -ETIME;
} else {
FMDBG("gained ownership of xfr\n");
radio->xfr_in_progress = 1;
mutex_unlock(&radio->lock);
}
return 0;
}
/*=============================================================================
FUNCTION: sync_read_xfr
=============================================================================*/
/**
This function is used to do synchronous XFR read operation.
@param radio: structure pointer passed by client.
@param xfr_type: XFR mode to write in XFRCTRL register.
@param buf: buffer to be read from the core.
@return => 0 if successful.
@return < 0 if failure.
*/
static int sync_read_xfr(struct tavarua_device *radio,
enum tavarua_xfr_ctrl_t xfr_type, unsigned char *buf)
{
int retval;
retval = xfr_intf_own(radio);
if (retval < 0)
return retval;
retval = tavarua_write_register(radio, XFRCTRL, xfr_type);
if (retval >= 0) {
/* Wait for interrupt i.e. complete
(&radio->sync_req_done); call */
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout)) || (retval < 0)) {
retval = -ETIME;
} else {
memcpy(buf, radio->sync_xfr_regs, XFR_REG_NUM);
}
}
radio->xfr_in_progress = 0;
start_pending_xfr(radio);
FMDBG("%s: %d\n", __func__, retval);
return retval;
}
/*=============================================================================
FUNCTION: sync_write_xfr
=============================================================================*/
/**
This function is used to do synchronous XFR write operation.
@param radio: structure pointer passed by client.
@param xfr_type: XFR mode to write in XFRCTRL register.
@param buf: buffer to be written to the core.
@return => 0 if successful.
@return < 0 if failure.
*/
static int sync_write_xfr(struct tavarua_device *radio,
enum tavarua_xfr_ctrl_t xfr_type, unsigned char *buf)
{
int retval;
retval = xfr_intf_own(radio);
if (retval < 0)
return retval;
retval = write_to_xfr(radio, xfr_type, buf, XFR_REG_NUM);
if (retval >= 0) {
/* Wait for interrupt i.e. complete
(&radio->sync_req_done); call */
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout)) || (retval < 0)) {
FMDBG("Write xfr timeout");
}
}
radio->xfr_in_progress = 0;
start_pending_xfr(radio);
FMDBG("%s: %d\n", __func__, retval);
return retval;
}
/*=============================================================================
FUNCTION: start_pending_xfr
=============================================================================*/
/**
This function checks if their are any pending xfr interrupts and if
the interrupts are either RDS PS, RDS RT, RDS AF, SCANNEXT, SEARCH or SYNC
then initiates corresponding read operation. Preference is given to RAW RDS
data (SYNC) over processed data (PS, RT, AF, etc) from core.
@param radio: structure pointer passed by client.
@return None.
*/
static void start_pending_xfr(struct tavarua_device *radio)
{
int i;
enum tavarua_xfr_t xfr;
for (i = 0; i < TAVARUA_XFR_MAX; i++) {
if (radio->pending_xfrs[i]) {
radio->xfr_in_progress = 1;
xfr = (enum tavarua_xfr_t)i;
switch (xfr) {
/* priority given to synchronous xfrs */
case TAVARUA_XFR_SYNC:
complete(&radio->sync_xfr_start);
break;
/* asynchrnous xfrs */
case TAVARUA_XFR_SRCH_LIST:
request_read_xfr(radio, RX_STATIONS_0);
break;
case TAVARUA_XFR_RT_RDS:
request_read_xfr(radio, RDS_RT_0);
break;
case TAVARUA_XFR_PS_RDS:
request_read_xfr(radio, RDS_PS_0);
break;
case TAVARUA_XFR_AF_LIST:
request_read_xfr(radio, RDS_AF_0);
break;
default:
FMDERR("%s: Unsupported XFR %d\n",
__func__, xfr);
}
radio->pending_xfrs[i] = 0;
FMDBG("resurrect xfr %d\n", i);
}
}
return;
}
/*=============================================================================
FUNCTION: tavarua_q_event
=============================================================================*/
/**
This function is called to queue an event for user.
NOTE:
Applications call the VIDIOC_QBUF ioctl to enqueue an empty (capturing) or
filled (output) buffer in the driver's incoming queue.
Pleaes refer tavarua_probe where we register different ioctl's for FM.
@param radio: structure pointer passed by client.
@param event: event to be queued.
@return None.
*/
static void tavarua_q_event(struct tavarua_device *radio,
enum tavarua_evt_t event)
{
struct kfifo *data_b = &radio->data_buf[TAVARUA_BUF_EVENTS];
unsigned char evt = event;
FMDBG("updating event_q with event %x\n", event);
if (kfifo_in_locked(data_b, &evt, 1, &radio->buf_lock[TAVARUA_BUF_EVENTS]))
wake_up_interruptible(&radio->event_queue);
}
/*=============================================================================
FUNCTION: tavarua_start_xfr
=============================================================================*/
/**
This function is called to process interrupts which require multiple XFR
operations (RDS search, RDS PS, RDS RT, etc). if any XFR operation is
already in progress we store information about pending interrupt, which
will be processed in future when current pending operation is done.
@param radio: structure pointer passed by client.
@param pending_id: XFR operation (which requires multiple XFR operations in
steps) to start.
@param xfr_id: XFR mode to write in XFRCTRL register.
@return None.
*/
static void tavarua_start_xfr(struct tavarua_device *radio,
enum tavarua_xfr_t pending_id, enum tavarua_xfr_ctrl_t xfr_id)
{
if (radio->xfr_in_progress)
radio->pending_xfrs[pending_id] = 1;
else {
radio->xfr_in_progress = 1;
request_read_xfr(radio, xfr_id);
}
}
/*=============================================================================
FUNCTION: tavarua_handle_interrupts
=============================================================================*/
/**
This function processes the interrupts.
NOTE:
tavarua_q_event is used to queue events in App buffer. i.e. App calls the
VIDIOC_QBUF ioctl to enqueue an empty (capturing) buffer, which is filled
by tavarua_q_event call.
Any async event that requires multiple steps, i.e. search, RT, PS, etc is
handled one at a time. (We preserve other interrupts when processing one).
Sync interrupts are given priority.
@param radio: structure pointer passed by client.
@return None.
*/
static void tavarua_handle_interrupts(struct tavarua_device *radio)
{
int i;
int retval, adj_channel_tune_req = 0;
unsigned char xfr_status;
if (!radio->handle_irq) {
FMDBG("IRQ happend, but I wont handle it\n");
return;
}
mutex_lock(&radio->lock);
tavarua_read_registers(radio, STATUS_REG1, STATUS_REG_NUM);
FMDBG("INTSTAT1 <%x>\n", radio->registers[STATUS_REG1]);
FMDBG("INTSTAT2 <%x>\n", radio->registers[STATUS_REG2]);
FMDBG("INTSTAT3 <%x>\n", radio->registers[STATUS_REG3]);
if (radio->registers[STATUS_REG1] & READY) {
complete(&radio->sync_req_done);
tavarua_q_event(radio, TAVARUA_EVT_RADIO_READY);
}
/* Tune completed */
if (radio->registers[STATUS_REG1] & TUNE) {
if (radio->tune_req) {
complete(&radio->sync_req_done);
radio->tune_req = 0;
}
/*
* Do not queue the TUNE event while validating if the station
* is good or not. As part of channel validation we tune to the
* adjacent station, measure its MPX_DCC value, then tune back
* to the original station and measure its MPX_DCC value.
* Compare the MPX_DCC values of curent and adjacent stations
* and decide if the channel is valid or not. During this period
* we should not queue the TUNE event to the upper layers.
*/
adj_channel_tune_req = atomic_read(&radio->validate_channel);
if (adj_channel_tune_req) {
complete(&radio->sync_req_done);
FMDBG("Tune event for adjacent channel\n");
} else {
tavarua_q_event(radio, TAVARUA_EVT_TUNE_SUCC);
FMDBG("Queueing Tune event\n");
}
if (radio->srch_params.get_list) {
tavarua_start_xfr(radio, TAVARUA_XFR_SRCH_LIST,
RX_STATIONS_0);
}
radio->srch_params.get_list = 0;
radio->xfr_in_progress = 0;
radio->xfr_bytes_left = 0;
for (i = 0; i < TAVARUA_BUF_MAX; i++) {
if (i >= TAVARUA_BUF_RT_RDS)
kfifo_reset(&radio->data_buf[i]);
}
for (i = 0; i < TAVARUA_XFR_MAX; i++) {
if (i >= TAVARUA_XFR_RT_RDS)
radio->pending_xfrs[i] = 0;
}
retval = tavarua_read_registers(radio, TUNECTRL, 1);
/* send to user station parameters */
if (retval > -1) {
/* Signal strength */
if (!(radio->registers[TUNECTRL] & SIGSTATE))
tavarua_q_event(radio, TAVARUA_EVT_BELOW_TH);
else
tavarua_q_event(radio, TAVARUA_EVT_ABOVE_TH);
/* mono/stereo */
if ((radio->registers[TUNECTRL] & MOSTSTATE))
tavarua_q_event(radio, TAVARUA_EVT_STEREO);
else
tavarua_q_event(radio, TAVARUA_EVT_MONO);
/* is RDS available */
if ((radio->registers[TUNECTRL] & RDSSYNC))
tavarua_q_event(radio, TAVARUA_EVT_RDS_AVAIL);
else
tavarua_q_event(radio,
TAVARUA_EVT_RDS_NOT_AVAIL);
}
} else {
if (radio->tune_req) {
FMDERR("Tune INT is pending\n");
mutex_unlock(&radio->lock);
return;
}
}
/* Search completed (read FREQ) */
if (radio->registers[STATUS_REG1] & SEARCH)
tavarua_q_event(radio, TAVARUA_EVT_SEEK_COMPLETE);
/* Scanning for next station */
if (radio->registers[STATUS_REG1] & SCANNEXT)
tavarua_q_event(radio, TAVARUA_EVT_SCAN_NEXT);
/* Signal indicator change (read SIGSTATE) */
if (radio->registers[STATUS_REG1] & SIGNAL) {
retval = tavarua_read_registers(radio, TUNECTRL, 1);
if (retval > -1) {
if (!(radio->registers[TUNECTRL] & SIGSTATE))
tavarua_q_event(radio, TAVARUA_EVT_BELOW_TH);
else
tavarua_q_event(radio, TAVARUA_EVT_ABOVE_TH);
}
}
/* RDS synchronization state change (read RDSSYNC) */
if (radio->registers[STATUS_REG1] & SYNC) {
retval = tavarua_read_registers(radio, TUNECTRL, 1);
if (retval > -1) {
if ((radio->registers[TUNECTRL] & RDSSYNC))
tavarua_q_event(radio, TAVARUA_EVT_RDS_AVAIL);
else
tavarua_q_event(radio,
TAVARUA_EVT_RDS_NOT_AVAIL);
}
}
/* Audio Control indicator (read AUDIOIND) */
if (radio->registers[STATUS_REG1] & AUDIO) {
retval = tavarua_read_registers(radio, AUDIOIND, 1);
if (retval > -1) {
if ((radio->registers[AUDIOIND] & 0x01))
tavarua_q_event(radio, TAVARUA_EVT_STEREO);
else
tavarua_q_event(radio, TAVARUA_EVT_MONO);
}
}
/* interrupt register 2 */
/* New unread RDS data group available */
if (radio->registers[STATUS_REG2] & RDSDAT) {
FMDBG("Raw RDS Available\n");
tavarua_rds_read(radio);
tavarua_q_event(radio, TAVARUA_EVT_NEW_RAW_RDS);
}
/* New RDS Program Service Table available */
if (radio->registers[STATUS_REG2] & RDSPS) {
FMDBG("New PS RDS\n");
tavarua_start_xfr(radio, TAVARUA_XFR_PS_RDS, RDS_PS_0);
}
/* New RDS Radio Text available */
if (radio->registers[STATUS_REG2] & RDSRT) {
FMDBG("New RT RDS\n");
tavarua_start_xfr(radio, TAVARUA_XFR_RT_RDS, RDS_RT_0);
}
/* New RDS Radio Text available */
if (radio->registers[STATUS_REG2] & RDSAF) {
FMDBG("New AF RDS\n");
tavarua_start_xfr(radio, TAVARUA_XFR_AF_LIST, RDS_AF_0);
}
/* Trasmitter an RDS Group */
if (radio->registers[STATUS_REG2] & TXRDSDAT) {
FMDBG("New TXRDSDAT\n");
tavarua_q_event(radio, TAVARUA_EVT_TXRDSDAT);
}
/* Complete RDS buffer is available for transmission */
if (radio->registers[STATUS_REG2] & TXRDSDONE) {
FMDBG("New TXRDSDAT\n");
tavarua_q_event(radio, TAVARUA_EVT_TXRDSDONE);
}
/* interrupt register 3 */
/* Data transfer (XFR) completed */
if (radio->registers[STATUS_REG3] & TRANSFER) {
FMDBG("XFR Interrupt\n");
tavarua_read_registers(radio, XFRCTRL, XFR_REG_NUM+1);
FMDBG("XFRCTRL IS: %x\n", radio->registers[XFRCTRL]);
xfr_status = radio->registers[XFRCTRL];
switch (xfr_status) {
case RDS_PS_0:
FMDBG("PS Header\n");
copy_from_xfr(radio, TAVARUA_BUF_PS_RDS, 5);
radio->xfr_bytes_left = (radio->registers[XFRCTRL+1] &
0x0F) * 8;
FMDBG("PS RDS Length: %d\n", radio->xfr_bytes_left);
if ((radio->xfr_bytes_left > 0) &&
(radio->xfr_bytes_left < 97))
request_read_xfr(radio, RDS_PS_1);
else
radio->xfr_in_progress = 0;
break;
case RDS_PS_1:
case RDS_PS_2:
case RDS_PS_3:
case RDS_PS_4:
case RDS_PS_5:
case RDS_PS_6:
FMDBG("PS Data\n");
copy_from_xfr(radio, TAVARUA_BUF_PS_RDS, XFR_REG_NUM);
radio->xfr_bytes_left -= XFR_REG_NUM;
if (radio->xfr_bytes_left > 0) {
if ((xfr_status + 1) > RDS_PS_6)
request_read_xfr(radio, RDS_PS_6);
else
request_read_xfr(radio, xfr_status+1);
} else {
radio->xfr_in_progress = 0;
tavarua_q_event(radio, TAVARUA_EVT_NEW_PS_RDS);
}
break;
case RDS_RT_0:
FMDBG("RT Header\n");
copy_from_xfr(radio, TAVARUA_BUF_RT_RDS, 5);
radio->xfr_bytes_left = radio->registers[XFRCTRL+1]
& 0x7F;
FMDBG("RT RDS Length: %d\n", radio->xfr_bytes_left);
/*RT_1 to RT_4 16 byte registers so 64 bytes */
if ((radio->xfr_bytes_left > 0)
&& (radio->xfr_bytes_left < 65))
request_read_xfr(radio, RDS_RT_1);
break;
case RDS_RT_1:
case RDS_RT_2:
case RDS_RT_3:
case RDS_RT_4:
FMDBG("xfr interrupt RT data\n");
copy_from_xfr(radio, TAVARUA_BUF_RT_RDS, XFR_REG_NUM);
radio->xfr_bytes_left -= XFR_REG_NUM;
if (radio->xfr_bytes_left > 0)
request_read_xfr(radio, xfr_status+1);
else {
radio->xfr_in_progress = 0;
tavarua_q_event(radio, TAVARUA_EVT_NEW_RT_RDS);
}
break;
case RDS_AF_0:
copy_from_xfr(radio, TAVARUA_BUF_AF_LIST,
XFR_REG_NUM);
radio->xfr_bytes_left = radio->registers[XFRCTRL+5]-11;
if (radio->xfr_bytes_left > 0)
request_read_xfr(radio, RDS_AF_1);
else
radio->xfr_in_progress = 0;
break;
case RDS_AF_1:
copy_from_xfr(radio, TAVARUA_BUF_AF_LIST,
radio->xfr_bytes_left);
tavarua_q_event(radio, TAVARUA_EVT_NEW_AF_LIST);
radio->xfr_in_progress = 0;
break;
case RX_CONFIG:
case RADIO_CONFIG:
case RDS_CONFIG:
memcpy(radio->sync_xfr_regs,
&radio->registers[XFRCTRL+1], XFR_REG_NUM);
complete(&radio->sync_req_done);
break;
case RX_STATIONS_0:
FMDBG("Search list has %d stations\n",
radio->registers[XFRCTRL+1]);
radio->xfr_bytes_left = radio->registers[XFRCTRL+1]*2;
if (radio->xfr_bytes_left > 14) {
copy_from_xfr(radio, TAVARUA_BUF_SRCH_LIST,
XFR_REG_NUM);
request_read_xfr(radio, RX_STATIONS_1);
} else if (radio->xfr_bytes_left) {
FMDBG("In else RX_STATIONS_0\n");
copy_from_xfr(radio, TAVARUA_BUF_SRCH_LIST,
radio->xfr_bytes_left+1);
tavarua_q_event(radio,
TAVARUA_EVT_NEW_SRCH_LIST);
radio->xfr_in_progress = 0;
}
break;
case RX_STATIONS_1:
FMDBG("In RX_STATIONS_1");
copy_from_xfr(radio, TAVARUA_BUF_SRCH_LIST,
radio->xfr_bytes_left);
tavarua_q_event(radio, TAVARUA_EVT_NEW_SRCH_LIST);
radio->xfr_in_progress = 0;
break;
case PHY_TXGAIN:
FMDBG("read PHY_TXGAIN is successful");
complete(&radio->sync_req_done);
break;
case (XFR_EXT | 0x80):
FMDBG("Set tone generator successful\n");
complete(&radio->sync_req_done);
break;
case (0x80 | RX_CONFIG):
case (0x80 | RADIO_CONFIG):
case (0x80 | RDS_CONFIG):
case (0x80 | INT_CTRL):
complete(&radio->sync_req_done);
break;
case (0x80 | RDS_RT_0):
FMDBG("RT Header Sent\n");
complete(&radio->sync_req_done);
break;
case (0x80 | RDS_RT_1):
case (0x80 | RDS_RT_2):
case (0x80 | RDS_RT_3):
case (0x80 | RDS_RT_4):
FMDBG("xfr interrupt RT data Sent\n");
complete(&radio->sync_req_done);
break;
/*TX Specific transfer */
case (0x80 | RDS_PS_0):
FMDBG("PS Header Sent\n");
complete(&radio->sync_req_done);
break;
case (0x80 | RDS_PS_1):
case (0x80 | RDS_PS_2):
case (0x80 | RDS_PS_3):
case (0x80 | RDS_PS_4):
case (0x80 | RDS_PS_5):
case (0x80 | RDS_PS_6):
FMDBG("xfr interrupt PS data Sent\n");
complete(&radio->sync_req_done);
break;
case (0x80 | PHY_TXGAIN):
FMDBG("write PHY_TXGAIN is successful");
complete(&radio->sync_req_done);
break;
case (XFR_POKE_COMPLETE | LSH_DATA(ONE_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(TWO_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(THREE_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(FOUR_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(FIVE_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(SIX_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(SEVEN_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(EIGHT_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(NINE_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(TEN_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(ELEVEN_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(TWELVE_BYTE, 1)):
case (XFR_POKE_COMPLETE | LSH_DATA(THIRTEEN_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(ONE_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(TWO_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(THREE_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(FOUR_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(FIVE_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(SIX_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(SEVEN_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(EIGHT_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(NINE_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(TEN_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(ELEVEN_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(TWELVE_BYTE, 1)):
case (XFR_PEEK_COMPLETE | LSH_DATA(THIRTEEN_BYTE, 1)):
FMDBG("XFR interrupt for PEEK/POKE complete\n");
complete(&radio->sync_req_done);
break;
default:
FMDERR("UNKNOWN XFR = %d\n", xfr_status);
}
if (!radio->xfr_in_progress)
start_pending_xfr(radio);
}
/* Error occurred. Read ERRCODE to determine cause */
if (radio->registers[STATUS_REG3] & ERROR) {
#ifdef FM_DEBUG
unsigned char xfr_buf[XFR_REG_NUM];
int retval = sync_read_xfr(radio, ERROR_CODE, xfr_buf);
FMDBG("retval of ERROR_CODE read : %d\n", retval);
#endif
FMDERR("ERROR STATE\n");
}
mutex_unlock(&radio->lock);
FMDBG("Work is done\n");
}
/*=============================================================================
FUNCTION: read_int_stat
=============================================================================*/
/**
This function is scheduled whenever there is an interrupt pending in interrupt
queue. i.e. kfmradio.
Whenever there is a GPIO interrupt, a delayed work will be queued in to the
'kfmradio' work queue. Upon execution of this work in the queue, a a call
to read_int_stat function will be made , which would in turn handle the
interrupts by reading the INTSTATx registers.
NOTE:
Tasks to be run out of a workqueue need to be packaged in a struct
work_struct structure.
@param work: work_struct structure.
@return None.
*/
static void read_int_stat(struct work_struct *work)
{
struct tavarua_device *radio = container_of(work,
struct tavarua_device, work.work);
tavarua_handle_interrupts(radio);
}
static void fm_shutdown(struct work_struct *work)
{
struct tavarua_device *radio = container_of(work,
struct tavarua_device, work.work);
FMDERR("%s: Releasing the FM I2S GPIO\n", __func__);
if (radio->pdata->config_i2s_gpio != NULL)
radio->pdata->config_i2s_gpio(FM_I2S_OFF);
FMDERR("%s: Shutting down FM SOC\n", __func__);
radio->pdata->fm_shutdown(radio->pdata);
complete(&radio->shutdown_done);
}
/*************************************************************************
* irq helper functions
************************************************************************/
/*=============================================================================
FUNCTION: tavarua_request_irq
=============================================================================*/
/**
This function is called to acquire a FM GPIO and enable FM interrupts.
@param radio: structure pointer passed by client.
@return 0 if success else otherwise.
*/
static int tavarua_request_irq(struct tavarua_device *radio)
{
int retval;
int irq = radio->pdata->irq;
if (radio == NULL)
return -EINVAL;
/* A workqueue created with create_workqueue() will have one worker thread
* for each CPU on the system; create_singlethread_workqueue(), instead,
* creates a workqueue with a single worker process. The name of the queue
* is limited to ten characters; it is only used for generating the "command"
* for the kernel thread(s) (which can be seen in ps or top).
*/
/* allocate an interrupt line */
/* On success, request_irq() returns 0 if everything goes as
planned. Your interrupt handler will start receiving its
interrupts immediately. On failure, request_irq()
returns:
-EINVAL
The IRQ number you requested was either
invalid or reserved, or your passed a NULL
pointer for the handler() parameter.
-EBUSY The IRQ you requested is already being
handled, and the IRQ cannot be shared.
-ENXIO The m68k returns this value for an invalid
IRQ number.
*/
/* Use request_any_context_irq, So that it might work for nested or
nested interrupts. in MSM8x60, FM is connected to PMIC GPIO and it
is a nested interrupt*/
retval = request_any_context_irq(irq, tavarua_isr,
IRQ_TYPE_EDGE_FALLING, "fm interrupt", radio);
if (retval < 0) {
FMDERR("Couldn't acquire FM gpio %d\n", irq);
return retval;
} else {
FMDBG("FM GPIO %d registered\n", irq);
}
retval = enable_irq_wake(irq);
if (retval < 0) {
FMDERR("Could not enable FM interrupt\n ");
free_irq(irq , radio);
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_disable_irq
=============================================================================*/
/**
This function is called to disable FM irq and free up FM interrupt handling
resources.
@param radio: structure pointer passed by client.
@return 0 if success else otherwise.
*/
static int tavarua_disable_irq(struct tavarua_device *radio)
{
int irq;
if (!radio)
return -EINVAL;
irq = radio->pdata->irq;
disable_irq_wake(irq);
free_irq(irq, radio);
cancel_delayed_work_sync(&radio->work);
flush_workqueue(radio->wqueue);
return 0;
}
static int optimized_search_algorithm(struct tavarua_device *radio,
int region)
{
unsigned char adie_type_bahma;
int retval = 0;
unsigned int rdsMask = 0;
unsigned char value = 0;
adie_type_bahma = is_bahama();
switch (region) {
case TAVARUA_REGION_US:
/*
Radio band for all the 200KHz channel-spaced regions
coming under EUROPE too, have been set as TAVARUA_REGION_US.
*/
FMDBG("%s: The region selected from APP is"
" : TAVARUA_REGION_US", __func__);
break;
case TAVARUA_REGION_EU:
/*
Radio band for all the 50KHz channel-spaced regions
coming under EUROPE, have been set as TAVARUA_REGION_EU.
*/
FMDBG("%s: The region selected from APP is : "
"TAVARUA_REGION_EU", __func__);
break;
case TAVARUA_REGION_JAPAN:
/*
Radio band for the 100KHz channel-spaced JAPAN region
has been set as TAVARUA_REGION_JAPAN.
*/
FMDBG("%s: The region selected from APP is"
" : TAVARUA_REGION_JAPAN", __func__);
break;
case TAVARUA_REGION_JAPAN_WIDE:
/*
Radio band for the 50KHz channel-spaced JAPAN WIDE region
has been set as TAVARUA_REGION_JAPAN_WIDE.
*/
FMDBG("%s: The region selected from APP is"
" : TAVARUA_REGION_JAPAN_WIDE", __func__);
break;
case TAVARUA_REGION_OTHER:
/*
Radio band for all the 100KHz channel-spaced regions
including those coming under EUROPE have been set as
TAVARUA_REGION_OTHER.
*/
FMDBG("%s: The region selected from APP is"
" : TAVARUA_REGION_OTHER", __func__);
break;
default:
pr_err("%s: Should not reach here.", __func__);
break;
}
/* Enable or Disable the 200KHz enforcer */
switch (region) {
case TAVARUA_REGION_US:
case TAVARUA_REGION_JAPAN:
case TAVARUA_REGION_OTHER:
/*
These are the 3 bands for which we need to enable the
200KHz enforcer in ADVCTL reg.
*/
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
FMDBG("%s: Enabling the 200KHz enforcer for"
" Region : %d", __func__, region);
/*Enable the 200KHz enforcer*/
retval = tavarua_read_registers(radio,
ADVCTRL, 1);
if (retval >= 0) {
rdsMask = radio->registers[ADVCTRL];
SET_REG_FIELD(rdsMask, ENF_SRCH200khz,
SRCH200KHZ_OFFSET, SRCH_MASK);
retval = tavarua_write_register(radio,
ADVCTRL, rdsMask);
} else
return retval;
} /* if Marimba do nothing */
break;
case TAVARUA_REGION_EU:
case TAVARUA_REGION_JAPAN_WIDE:
/*
These are the 2 bands for which we need to disable the
200KHz enforcer in ADVCTL reg.
Radio band for all the 50KHz channel-spaced regions
coming under EUROPE have been set as TAVARUA_REGION_EU.
*/
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
FMDBG("%s: Disabling the 200KHz enforcer for"
" Region : %d", __func__, region);
/*
Disable 200KHz enforcer for all 50 KHz
spaced regions.
*/
retval = tavarua_read_registers(radio,
ADVCTRL, 1);
if (retval >= 0) {
rdsMask = radio->registers[ADVCTRL];
SET_REG_FIELD(rdsMask, NO_SRCH200khz,
SRCH200KHZ_OFFSET, SRCH_MASK);
retval = tavarua_write_register(radio,
ADVCTRL, rdsMask);
} else
return retval;
} /* if Marimba do nothing */
break;
default:
FMDBG("%s: Defaulting in case of Enabling/Disabling"
"the 200KHz Enforcer", __func__);
break;
}
/* Set channel spacing */
switch (region) {
case TAVARUA_REGION_US:
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
/*
Configuring all 200KHZ spaced regions as 100KHz due to
change in the new Bahma FM SoC search algorithm.
*/
value = FM_CH_SPACE_100KHZ;
} else {
FMDBG("Adie type : Marimba\n");
value = FM_CH_SPACE_200KHZ;
}
break;
case TAVARUA_REGION_JAPAN:
case TAVARUA_REGION_OTHER:
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
FMDBG("%s: Configuring the channel-spacing as 50KHz"
"for the Region : %d", __func__, region);
/*
Configuring all 100KHZ spaced regions as 50KHz due to
change in the new Bahma FM SoC search algorithm.
*/
value = FM_CH_SPACE_50KHZ;
} else {
FMDBG("Adie type : Marimba\n");
value = FM_CH_SPACE_100KHZ;
}
break;
case TAVARUA_REGION_EU:
case TAVARUA_REGION_JAPAN_WIDE:
value = FM_CH_SPACE_50KHZ;
break;
default:
FMDBG("%s: Defualting in case of Channel-Spacing", __func__);
break;
}
SET_REG_FIELD(radio->registers[RDCTRL], value,
RDCTRL_CHSPACE_OFFSET, RDCTRL_CHSPACE_MASK);
return retval;
}
/*************************************************************************
* fops/IOCTL helper functions
************************************************************************/
/*=============================================================================
FUNCTION: tavarua_search
=============================================================================*/
/**
This interface sets the search control features.
@param radio: structure pointer passed by client.
@param on: The value of a control.
@param dir: FM search direction.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_search(struct tavarua_device *radio, int on, int dir)
{
enum search_t srch = radio->registers[SRCHCTRL] & SRCH_MODE;
FMDBG("In tavarua_search\n");
if (on) {
radio->registers[SRCHRDS1] = 0x00;
radio->registers[SRCHRDS2] = 0x00;
/* Set freq band */
switch (srch) {
case SCAN_FOR_STRONG:
case SCAN_FOR_WEAK:
radio->srch_params.get_list = 1;
radio->registers[SRCHRDS2] =
radio->srch_params.preset_num;
break;
case RDS_SEEK_PTY:
case RDS_SCAN_PTY:
radio->registers[SRCHRDS2] =
radio->srch_params.srch_pty;
break;
case RDS_SEEK_PI:
radio->registers[SRCHRDS1] =
(radio->srch_params.srch_pi & 0xFF00) >> 8;
radio->registers[SRCHRDS2] =
(radio->srch_params.srch_pi & 0x00FF);
break;
default:
break;
}
radio->registers[SRCHCTRL] |= SRCH_ON;
} else {
radio->registers[SRCHCTRL] &= ~SRCH_ON;
radio->srch_params.get_list = 0;
}
radio->registers[SRCHCTRL] = (dir << 3) |
(radio->registers[SRCHCTRL] & 0xF7);
FMDBG("SRCHCTRL <%x>\n", radio->registers[SRCHCTRL]);
FMDBG("Search Started\n");
return tavarua_write_registers(radio, SRCHRDS1,
&radio->registers[SRCHRDS1], 3);
}
/*=============================================================================
FUNCTION: tavarua_set_region
=============================================================================*/
/**
This interface configures the FM radio.
@param radio: structure pointer passed by client.
@param req_region: FM band types. These types defines the FM band minimum and
maximum frequencies in the FM band.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_set_region(struct tavarua_device *radio,
int req_region)
{
int retval = 0;
unsigned int rdsMask = 0;
unsigned char xfr_buf[XFR_REG_NUM];
unsigned char value;
unsigned int spacing = 0.100 * FREQ_MUL;
unsigned int band_low, band_high;
unsigned int low_band_limit = 76.0 * FREQ_MUL;
enum tavarua_region_t region = req_region;
unsigned char adie_type_bahma;
adie_type_bahma = is_bahama();
/* Set freq band */
if (region == TAVARUA_REGION_JAPAN)
SET_REG_FIELD(radio->registers[RDCTRL], 1,
RDCTRL_BAND_OFFSET, RDCTRL_BAND_MASK);
else
SET_REG_FIELD(radio->registers[RDCTRL], 0,
RDCTRL_BAND_OFFSET, RDCTRL_BAND_MASK);
/* Set De-emphasis and soft band range*/
SET_REG_FIELD(radio->registers[RDCTRL], radio->region_params.emphasis,
RDCTRL_DEEMPHASIS_OFFSET, RDCTRL_DEEMPHASIS_MASK);
/* set RDS standard */
SET_REG_FIELD(radio->registers[RDSCTRL], radio->region_params.rds_std,
RDSCTRL_STANDARD_OFFSET, RDSCTRL_STANDARD_MASK);
FMDBG("RDSCTRLL %x\n", radio->registers[RDSCTRL]);
retval = tavarua_write_register(radio, RDSCTRL,
radio->registers[RDSCTRL]);
if (retval < 0) {
FMDERR("Failed to set RDS/RBDS standard\n");
return retval;
}
/* Set the lower and upper band limits*/
retval = sync_read_xfr(radio, RADIO_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("failed to get RADIO_CONFIG\n");
return retval;
}
band_low = (radio->region_params.band_low -
low_band_limit) / spacing;
band_high = (radio->region_params.band_high -
low_band_limit) / spacing;
xfr_buf[0] = RSH_DATA(band_low, 8);
xfr_buf[1] = GET_ABS_VAL(band_low);
xfr_buf[2] = RSH_DATA(band_high, 8);
xfr_buf[3] = GET_ABS_VAL(band_high);
xfr_buf[4] = 0; /* Active LOW */
retval = sync_write_xfr(radio, RADIO_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("Could not set regional settings\n");
return retval;
}
radio->region_params.region = region;
/* Check for the FM Algorithm used */
if (radio->enable_optimized_srch_alg) {
FMDBG("Optimized Srch Algorithm!!!");
optimized_search_algorithm(radio, region);
} else {
FMDBG("Native Srch Algorithm!!!");
/* Enable/Disable the 200KHz enforcer */
switch (region) {
case TAVARUA_REGION_US:
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
/*Enable the 200KHz enforcer*/
retval = tavarua_read_registers(radio,
ADVCTRL, 1);
if (retval >= 0) {
rdsMask = radio->registers[ADVCTRL];
SET_REG_FIELD(rdsMask, ENF_SRCH200khz,
SRCH200KHZ_OFFSET, SRCH_MASK);
retval = tavarua_write_register(radio,
ADVCTRL, rdsMask);
} else
return retval;
} /* if Marimba do nothing */
break;
case TAVARUA_REGION_EU:
case TAVARUA_REGION_JAPAN:
case TAVARUA_REGION_JAPAN_WIDE:
default:
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
/*
Disable 200KHz enforcer for all 100/50 KHz
spaced regions.
*/
retval = tavarua_read_registers(radio,
ADVCTRL, 1);
if (retval >= 0) {
rdsMask = radio->registers[ADVCTRL];
SET_REG_FIELD(rdsMask, NO_SRCH200khz,
SRCH200KHZ_OFFSET, SRCH_MASK);
retval = tavarua_write_register(radio,
ADVCTRL, rdsMask);
} else
return retval;
} /* if Marimba do nothing */
break;
}
/* Set channel spacing */
if (region == TAVARUA_REGION_US) {
if (adie_type_bahma) {
FMDBG("Adie type : Bahama\n");
/*
Configuring all 200KHZ spaced regions as
100KHz due to change in the new Bahma
FM SoC search algorithm.
*/
value = FM_CH_SPACE_100KHZ;
} else {
FMDBG("Adie type : Marimba\n");
value = FM_CH_SPACE_200KHZ;
}
} else {
/*
Set the channel spacing as configured from
the upper layers.
*/
value = radio->region_params.spacing;
}
SET_REG_FIELD(radio->registers[RDCTRL], value,
RDCTRL_CHSPACE_OFFSET, RDCTRL_CHSPACE_MASK);
}
/* Write the config values into RDCTL register */
FMDBG("RDCTRL: %x\n", radio->registers[RDCTRL]);
retval = tavarua_write_register(radio, RDCTRL,
radio->registers[RDCTRL]);
if (retval < 0) {
FMDERR("Could not set region in rdctrl\n");
return retval;
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_get_freq
=============================================================================*/
/**
This interface gets the current frequency.
@param radio: structure pointer passed by client.
@param freq: struct v4l2_frequency. This will be set to the resultant
frequency in units of 62.5 kHz on success.
NOTE:
To get the current tuner or modulator radio frequency applications set the
tuner field of a struct v4l2_frequency to the respective tuner or modulator
number (only input devices have tuners, only output devices have modulators),
zero out the reserved array and call the VIDIOC_G_FREQUENCY ioctl with a
pointer to this structure. The driver stores the current frequency in the
frequency field.
Tuning frequency is in units of 62.5 kHz, or if the struct v4l2_tuner or
struct v4l2_modulator capabilities flag V4L2_TUNER_CAP_LOW is set, in
units of 62.5 Hz.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_get_freq(struct tavarua_device *radio,
struct v4l2_frequency *freq)
{
int retval;
unsigned short chan;
unsigned int band_bottom;
unsigned int spacing;
band_bottom = radio->region_params.band_low;
spacing = 0.100 * FREQ_MUL;
/* read channel */
retval = tavarua_read_registers(radio, FREQ, 2);
chan = radio->registers[FREQ];
/* Frequency (MHz) = 100 (kHz) x Channel + Bottom of Band (MHz) */
freq->frequency = spacing * chan + band_bottom;
if (radio->registers[TUNECTRL] & ADD_OFFSET)
freq->frequency += 800;
return retval;
}
/*=============================================================================
FUNCTION: tavarua_set_freq
=============================================================================*/
/**
This interface sets the current frequency.
@param radio: structure pointer passed by client.
@param freq: desired frequency sent by the client in 62.5 kHz units.
NOTE:
To change the current tuner or modulator radio frequency, applications
initialize the tuner, type and frequency fields, and the reserved array of a
struct v4l2_frequency and call the VIDIOC_S_FREQUENCY ioctl with a pointer to
this structure. When the requested frequency is not possible the driver
assumes the closest possible value. However VIDIOC_S_FREQUENCY is a
write-only ioctl, it does not return the actual new frequency.
Tuning frequency is in units of 62.5 kHz, or if the struct v4l2_tuner
or struct v4l2_modulator capabilities flag V4L2_TUNER_CAP_LOW is set,
in units of 62.5 Hz.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_set_freq(struct tavarua_device *radio, unsigned int freq)
{
unsigned int band_bottom;
unsigned char chan;
unsigned char cmd[] = {0x00, 0x00};
unsigned int spacing;
int retval;
band_bottom = radio->region_params.band_low;
spacing = 0.100 * FREQ_MUL;
if ((freq % 1600) == 800) {
cmd[1] = ADD_OFFSET;
freq -= 800;
}
/* Chan = [ Freq (Mhz) - Bottom of Band (MHz) ] / 100 (kHz) */
chan = (freq - band_bottom) / spacing;
cmd[0] = chan;
cmd[1] |= TUNE_STATION;
radio->tune_req = 1;
retval = tavarua_write_registers(radio, FREQ, cmd, 2);
if (retval < 0)
radio->tune_req = 0;
return retval;
}
/**************************************************************************
* File Operations Interface
*************************************************************************/
/*=============================================================================
FUNCTION: tavarua_fops_read
=============================================================================*/
/**
This function is called when a process, which already opened the dev file,
attempts to read from it.
In case of tavarua driver, it is called to read RDS data.
@param file: file descriptor.
@param buf: The buffer to fill with data.
@param count: The length of the buffer in bytes.
@param ppos: Our offset in the file.
@return The number of bytes put into the buffer on sucess.
-EFAULT if there is no access to user buffer
*/
static ssize_t tavarua_fops_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
struct kfifo *rds_buf = &radio->data_buf[TAVARUA_BUF_RAW_RDS];
/* block if no new data available */
while (!kfifo_len(rds_buf)) {
if (file->f_flags & O_NONBLOCK)
return -EWOULDBLOCK;
if (wait_event_interruptible(radio->read_queue,
kfifo_len(rds_buf)) < 0)
return -EINTR;
}
/* calculate block count from byte count */
count /= BYTES_PER_BLOCK;
/* check if we can write to the user buffer */
if (!access_ok(VERIFY_WRITE, buf, count*BYTES_PER_BLOCK))
return -EFAULT;
/* copy RDS block out of internal buffer and to user buffer */
return kfifo_out_locked(rds_buf, buf, count*BYTES_PER_BLOCK,
&radio->buf_lock[TAVARUA_BUF_RAW_RDS]);
}
/*=============================================================================
FUNCTION: tavarua_fops_write
=============================================================================*/
/**
This function is called when a process, which already opened the dev file,
attempts to write to it.
In case of tavarua driver, it is called to write RDS data to host.
@param file: file descriptor.
@param buf: The buffer which has data to write.
@param count: The length of the buffer.
@param ppos: Our offset in the file.
@return The number of bytes written from the buffer.
*/
static ssize_t tavarua_fops_write(struct file *file, const char __user *data,
size_t count, loff_t *ppos)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval = 0;
int bytes_to_copy;
int bytes_copied = 0;
int bytes_left;
int chunk_index = 0;
unsigned char tx_data[XFR_REG_NUM];
/* Disable TX of this type first */
switch (radio->tx_mode) {
case TAVARUA_TX_RT:
bytes_left = min((int)count, MAX_RT_LENGTH);
tx_data[1] = 0;
break;
case TAVARUA_TX_PS:
bytes_left = min((int)count, MAX_PS_LENGTH);
tx_data[4] = 0;
break;
default:
FMDERR("%s: Unknown TX mode\n", __func__);
return -1;
}
retval = sync_write_xfr(radio, radio->tx_mode, tx_data);
if (retval < 0)
return retval;
/* send payload to FM hardware */
while (bytes_left) {
chunk_index++;
bytes_to_copy = min(bytes_left, XFR_REG_NUM);
if (copy_from_user(tx_data, data + bytes_copied, bytes_to_copy))
return -EFAULT;
retval = sync_write_xfr(radio, radio->tx_mode +
chunk_index, tx_data);
if (retval < 0)
return retval;
bytes_copied += bytes_to_copy;
bytes_left -= bytes_to_copy;
}
/* send the header */
switch (radio->tx_mode) {
case TAVARUA_TX_RT:
FMDBG("Writing RT header\n");
tx_data[0] = bytes_copied;
tx_data[1] = TX_ON | 0x03; /* on | PTY */
tx_data[2] = 0x12; /* PI high */
tx_data[3] = 0x34; /* PI low */
break;
case TAVARUA_TX_PS:
FMDBG("Writing PS header\n");
tx_data[0] = chunk_index;
tx_data[1] = 0x03; /* PTY */
tx_data[2] = 0x12; /* PI high */
tx_data[3] = 0x34; /* PI low */
tx_data[4] = TX_ON | 0x01;
break;
default:
FMDERR("%s: Unknown TX mode\n", __func__);
return -1;
}
retval = sync_write_xfr(radio, radio->tx_mode, tx_data);
if (retval < 0)
return retval;
FMDBG("done writing: %d\n", retval);
return bytes_copied;
}
/*=============================================================================
FUNCTION: tavarua_fops_open
=============================================================================*/
/**
This function is called when a process tries to open the device file, like
"cat /dev/mycharfile"
@param file: file descriptor.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_fops_open(struct file *file)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval = -ENODEV;
unsigned char value;
/* FM core bring up */
int i = 0;
char fm_ctl0_part1[] = { 0xCA, 0xCE, 0xD6 };
char fm_ctl1[] = { 0x03 };
char fm_ctl0_part2[] = { 0xB6, 0xB7 };
char buffer[] = {0x00, 0x48, 0x8A, 0x8E, 0x97, 0xB7};
int bahama_present = -ENODEV;
INIT_DELAYED_WORK(&radio->work, read_int_stat);
if (!atomic_dec_and_test(&radio->users)) {
pr_err("%s: Device already in use."
"Try again later", __func__);
atomic_inc(&radio->users);
return -EBUSY;
}
/* initial gpio pin config & Power up */
retval = radio->pdata->fm_setup(radio->pdata);
if (retval) {
printk(KERN_ERR "%s: failed config gpio & pmic\n", __func__);
goto open_err_setup;
}
if (radio->pdata->config_i2s_gpio != NULL) {
retval = radio->pdata->config_i2s_gpio(FM_I2S_ON);
if (retval) {
printk(KERN_ERR "%s: failed config gpio\n", __func__);
goto config_i2s_err;
}
}
/* enable irq */
retval = tavarua_request_irq(radio);
if (retval < 0) {
printk(KERN_ERR "%s: failed to request irq\n", __func__);
goto open_err_req_irq;
}
/* call top level marimba interface here to enable FM core */
FMDBG("initializing SoC\n");
bahama_present = is_bahama();
if (bahama_present == -ENODEV)
return -ENODEV;
if (bahama_present)
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
else
radio->marimba->mod_id = MARIMBA_SLAVE_ID_MARIMBA;
value = FM_ENABLE;
retval = marimba_write_bit_mask(radio->marimba,
MARIMBA_XO_BUFF_CNTRL, &value, 1, value);
if (retval < 0) {
printk(KERN_ERR "%s:XO_BUFF_CNTRL write failed\n",
__func__);
goto open_err_all;
}
/* Bring up FM core */
if (bahama_present) {
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
/* Read the Bahama version*/
retval = marimba_read_bit_mask(radio->marimba,
0x00, &bahama_version, 1, 0x1F);
if (retval < 0) {
printk(KERN_ERR "%s: version read failed",
__func__);
goto open_err_all;
}
/* Check for Bahama V2 variant*/
if (bahama_version == 0x09) {
/* In case of Bahama v2, forcefully enable the
* internal analog and digital voltage controllers
*/
value = 0x06;
/* value itself used as mask in these writes*/
retval = marimba_write_bit_mask(radio->marimba,
BAHAMA_LDO_DREG_CTL0, &value, 1, value);
if (retval < 0) {
printk(KERN_ERR "%s:0xF0 write failed\n",
__func__);
goto open_err_all;
}
value = 0x86;
retval = marimba_write_bit_mask(radio->marimba,
BAHAMA_LDO_AREG_CTL0, &value, 1, value);
if (retval < 0) {
printk(KERN_ERR "%s:0xF4 write failed\n",
__func__);
goto open_err_all;
}
}
/*write FM mode*/
retval = tavarua_write_register(radio, BAHAMA_FM_MODE_REG,
BAHAMA_FM_MODE_NORMAL);
if (retval < 0) {
printk(KERN_ERR "failed to set the FM mode: %d\n",
retval);
goto open_err_all;
}
/*Write first sequence of bytes to FM_CTL0*/
for (i = 0; i < 3; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL0_REG, fm_ctl0_part1[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL0:set-1 failure: %d\n",
retval);
goto open_err_all;
}
}
/*Write the FM_CTL1 sequence*/
for (i = 0; i < 1; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL1_REG, fm_ctl1[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL1 write failure: %d\n",
retval);
goto open_err_all;
}
}
/*Write second sequence of bytes to FM_CTL0*/
for (i = 0; i < 2; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL0_REG, fm_ctl0_part2[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL0:set-2 failure: %d\n",
retval);
goto open_err_all;
}
}
} else {
retval = tavarua_write_registers(radio, LEAKAGE_CNTRL,
buffer, 6);
if (retval < 0) {
printk(KERN_ERR "%s: failed to bring up FM Core\n",
__func__);
goto open_err_all;
}
}
/* Wait for interrupt i.e. complete(&radio->sync_req_done); call */
/*Initialize the completion variable for
for the proper behavior*/
init_completion(&radio->sync_req_done);
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout))) {
retval = -1;
FMDERR("Timeout waiting for initialization\n");
}
/* get Chip ID */
retval = tavarua_write_register(radio, XFRCTRL, CHIPID);
if (retval < 0)
goto open_err_all;
msleep(TAVARUA_DELAY);
tavarua_read_registers(radio, XFRCTRL, XFR_REG_NUM+1);
if (radio->registers[XFRCTRL] != CHIPID)
goto open_err_all;
radio->chipID = (radio->registers[XFRCTRL+2] << 24) |
(radio->registers[XFRCTRL+5] << 16) |
(radio->registers[XFRCTRL+6] << 8) |
(radio->registers[XFRCTRL+7]);
printk(KERN_WARNING DRIVER_NAME ": Chip ID %x\n", radio->chipID);
if (radio->chipID == MARIMBA_A0) {
printk(KERN_WARNING DRIVER_NAME ": Unsupported hardware: %x\n",
radio->chipID);
retval = -1;
goto open_err_all;
}
radio->handle_irq = 0;
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
marimba_set_fm_status(radio->marimba, true);
return 0;
open_err_all:
/*Disable FM in case of error*/
value = 0x00;
marimba_write_bit_mask(radio->marimba, MARIMBA_XO_BUFF_CNTRL,
&value, 1, value);
tavarua_disable_irq(radio);
open_err_req_irq:
if (radio->pdata->config_i2s_gpio != NULL)
radio->pdata->config_i2s_gpio(FM_I2S_OFF);
config_i2s_err:
radio->pdata->fm_shutdown(radio->pdata);
open_err_setup:
radio->handle_irq = 1;
atomic_inc(&radio->users);
return retval;
}
/*=============================================================================
FUNCTION: tavarua_fops_release
=============================================================================*/
/**
This function is called when a process closes the device file.
@param file: file descriptor.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_fops_release(struct file *file)
{
int retval;
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
unsigned char value;
int i = 0;
/*FM Core shutdown sequence for Bahama*/
char fm_ctl0_part1[] = { 0xB7 };
char fm_ctl1[] = { 0x03 };
char fm_ctl0_part2[] = { 0x9F, 0x48, 0x02 };
int bahama_present = -ENODEV;
/*FM Core shutdown sequence for Marimba*/
char buffer[] = {0x18, 0xB7, 0x48};
bool bt_status = false;
int index;
/* internal regulator controllers DREG_CTL0, AREG_CTL0
* has to be kept in the valid state based on the bt status.
* 1st row is the state when no clients are active,
* and the second when bt is in on state.
*/
char internal_vreg_ctl[2][2] = {
{ 0x04, 0x84 },
{ 0x00, 0x80 }
};
if (!radio) {
pr_err("%s: Radio device not available...", __func__);
return -ENODEV;
}
FMDBG("In %s", __func__);
FMDBG("%s, Disabling the IRQs\n", __func__);
/* disable irq */
retval = tavarua_disable_irq(radio);
if (retval < 0) {
printk(KERN_ERR "%s: failed to disable irq\n", __func__);
return retval;
}
/* disable radio ctrl */
retval = tavarua_write_register(radio, RDCTRL, 0x00);
if (retval < 0) {
printk(KERN_ERR "%s: failed to disable FM\n", __func__);
return retval;
}
init_completion(&radio->shutdown_done);
bahama_present = is_bahama();
if (bahama_present == -ENODEV)
return -ENODEV;
INIT_DELAYED_WORK(&radio->work, fm_shutdown);
if (bahama_present) {
/*Write first sequence of bytes to FM_CTL0*/
for (i = 0; i < 1; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL0_REG, fm_ctl0_part1[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL0:Set-1 failure: %d\n",
retval);
break;
}
}
/*Write the FM_CTL1 sequence*/
for (i = 0; i < 1; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL1_REG, fm_ctl1[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL1 failure: %d\n",
retval);
break;
}
}
/*Write second sequence of bytes to FM_CTL0*/
for (i = 0; i < 3; i++) {
retval = tavarua_write_register(radio,
BAHAMA_FM_CTL0_REG, fm_ctl0_part2[i]);
if (retval < 0) {
printk(KERN_ERR "FM_CTL0:Set-2 failure: %d\n",
retval);
break;
}
}
} else {
retval = tavarua_write_registers(radio, FM_CTL0,
buffer, sizeof(buffer)/sizeof(buffer[0]));
if (retval < 0) {
printk(KERN_ERR "%s: failed to bring down the FM Core\n",
__func__);
return retval;
}
}
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
bt_status = marimba_get_bt_status(radio->marimba);
/* Set the index based on the bt status*/
index = bt_status ? 1 : 0;
/* Check for Bahama's existance and Bahama V2 variant*/
if (bahama_present && (bahama_version == 0x09)) {
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
/* actual value itself used as mask*/
retval = marimba_write_bit_mask(radio->marimba,
BAHAMA_LDO_DREG_CTL0, &internal_vreg_ctl[bt_status][0],
1, internal_vreg_ctl[index][0]);
if (retval < 0) {
printk(KERN_ERR "%s:0xF0 write failed\n", __func__);
goto exit;
}
/* actual value itself used as mask*/
retval = marimba_write_bit_mask(radio->marimba,
BAHAMA_LDO_AREG_CTL0, &internal_vreg_ctl[bt_status][1],
1, internal_vreg_ctl[index][1]);
if (retval < 0) {
printk(KERN_ERR "%s:0xF4 write failed\n", __func__);
goto exit;
}
} else {
/* disable fm core */
radio->marimba->mod_id = MARIMBA_SLAVE_ID_MARIMBA;
}
value = 0x00;
retval = marimba_write_bit_mask(radio->marimba, MARIMBA_XO_BUFF_CNTRL,
&value, 1, FM_ENABLE);
if (retval < 0) {
printk(KERN_ERR "%s:XO_BUFF_CNTRL write failed\n", __func__);
goto exit;
}
exit:
FMDBG("%s, Calling fm_shutdown\n", __func__);
queue_delayed_work(radio->wqueue, &radio->work,
msecs_to_jiffies(TAVARUA_DELAY/2));
/* teardown gpio and pmic */
marimba_set_fm_status(radio->marimba, false);
wait_for_completion(&radio->shutdown_done);
radio->handle_irq = 1;
radio->lp_mode = 1;
radio->spur_table_size = 0;
atomic_inc(&radio->users);
radio->marimba->mod_id = SLAVE_ID_BAHAMA;
flush_workqueue(radio->wqueue);
return retval;
}
/*
* tavarua_fops - file operations interface
*/
static const struct v4l2_file_operations tavarua_fops = {
.owner = THIS_MODULE,
.read = tavarua_fops_read,
.write = tavarua_fops_write,
.ioctl = video_ioctl2,
.open = tavarua_fops_open,
.release = tavarua_fops_release,
};
/*************************************************************************
* Video4Linux Interface
*************************************************************************/
/*
* tavarua_v4l2_queryctrl - query control
*/
static struct v4l2_queryctrl tavarua_v4l2_queryctrl[] = {
{
.id = V4L2_CID_AUDIO_VOLUME,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Volume",
.minimum = 0,
.maximum = 15,
.step = 1,
.default_value = 15,
},
{
.id = V4L2_CID_AUDIO_BALANCE,
.flags = V4L2_CTRL_FLAG_DISABLED,
},
{
.id = V4L2_CID_AUDIO_BASS,
.flags = V4L2_CTRL_FLAG_DISABLED,
},
{
.id = V4L2_CID_AUDIO_TREBLE,
.flags = V4L2_CTRL_FLAG_DISABLED,
},
{
.id = V4L2_CID_AUDIO_MUTE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Mute",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1,
},
{
.id = V4L2_CID_AUDIO_LOUDNESS,
.flags = V4L2_CTRL_FLAG_DISABLED,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SRCHMODE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Search mode",
.minimum = 0,
.maximum = 7,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SCANDWELL,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Search dwell time",
.minimum = 0,
.maximum = 7,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SRCHON,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Search on/off",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_STATE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "radio 0ff/rx/tx/reset",
.minimum = 0,
.maximum = 3,
.step = 1,
.default_value = 1,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_REGION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "radio standard",
.minimum = 0,
.maximum = 2,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Signal Threshold",
.minimum = 0x80,
.maximum = 0x7F,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SRCH_PTY,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Search PTY",
.minimum = 0,
.maximum = 31,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SRCH_PI,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Search PI",
.minimum = 0,
.maximum = 0xFF,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SRCH_CNT,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Preset num",
.minimum = 0,
.maximum = 12,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_EMPHASIS,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Emphasis",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_RDS_STD,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "RDS standard",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_SPACING,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Channel spacing",
.minimum = 0,
.maximum = 2,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_RDSON,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "RDS on/off",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_MASK,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "RDS group mask",
.minimum = 0,
.maximum = 0xFFFFFFFF,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_PROC,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "RDS processing",
.minimum = 0,
.maximum = 0xFF,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_RDSD_BUF,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "RDS data groups to buffer",
.minimum = 1,
.maximum = 21,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_PSALL,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "pass all ps strings",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_LP_MODE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Low power mode",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_ANTENNA,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "headset/internal",
.minimum = 0,
.maximum = 1,
.default_value = 0,
},
/* Private controls for FM TX*/
{
.id = V4L2_CID_PRIVATE_TAVARUA_TX_SETPSREPEATCOUNT,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Set PS REPEATCOUNT",
.minimum = 0,
.maximum = 15,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_PS_NAME,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Stop PS NAME",
.minimum = 0,
.maximum = 1,
},
{
.id = V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_RT,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Stop RT",
.minimum = 0,
.maximum = 1,
},
{ .id = V4L2_CID_PRIVATE_SET_NOTCH_FILTER,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Notch filter",
.minimum = 0,
.maximum = 2,
},
};
/*=============================================================================
FUNCTION: tavarua_vidioc_querycap
=============================================================================*/
/**
This function is called to query device capabilities.
NOTE:
All V4L2 devices support the VIDIOC_QUERYCAP ioctl. It is used to identify
kernel devices compatible with this specification and to obtain information
about driver and hardware capabilities. The ioctl takes a pointer to a struct
v4l2_capability which is filled by the driver. When the driver is not
compatible with this specification the ioctl returns an EINVAL error code.
@param file: File descriptor returned by open().
@param capability: pointer to struct v4l2_capability.
@return On success 0 is returned, else error code.
@return EINVAL: The device is not compatible with this specification.
*/
static int tavarua_vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *capability)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
strlcpy(capability->driver, DRIVER_NAME, sizeof(capability->driver));
strlcpy(capability->card, DRIVER_CARD, sizeof(capability->card));
sprintf(capability->bus_info, "I2C");
capability->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
capability->version = radio->chipID;
return 0;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_queryctrl
=============================================================================*/
/**
This function is called to query the device and driver for supported video
controls (enumerate control items).
NOTE:
To query the attributes of a control, the applications set the id field of
a struct v4l2_queryctrl and call the VIDIOC_QUERYCTRL ioctl with a pointer
to this structure. The driver fills the rest of the structure or returns an
EINVAL error code when the id is invalid.
@param file: File descriptor returned by open().
@param qc: pointer to struct v4l2_queryctrl.
@return On success 0 is returned, else error code.
@return EINVAL: The struct v4l2_queryctrl id is invalid.
*/
static int tavarua_vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
unsigned char i;
int retval = -EINVAL;
for (i = 0; i < ARRAY_SIZE(tavarua_v4l2_queryctrl); i++) {
if (qc->id && qc->id == tavarua_v4l2_queryctrl[i].id) {
memcpy(qc, &(tavarua_v4l2_queryctrl[i]), sizeof(*qc));
retval = 0;
break;
}
}
if (retval < 0)
printk(KERN_WARNING DRIVER_NAME
": query conv4ltrol failed with %d\n", retval);
return retval;
}
static int update_spur_table(struct tavarua_device *radio)
{
unsigned char xfr_buf[XFR_REG_NUM];
unsigned char size = 0, tbl_size = 0;
int index = 0, offset = 0, addr = 0x0, val = 0;
int retval = 0, temp = 0, cnt = 0, j = 0;
memset(xfr_buf, 0x0, XFR_REG_NUM);
/* Read the SPUR Table Size */
retval = xfr_rdwr_data(radio, XFR_READ, 1, SPUR_TABLE_ADDR, &tbl_size);
if (retval < 0) {
FMDERR("%s: Failed to read SPUR table size\n", __func__);
return retval;
}
/* Calculate the new SPUR Register address */
val = addr = (SPUR_TABLE_START_ADDR + (tbl_size * 3));
/* Save the SPUR Table length configured by user*/
temp = radio->spur_table_size;
/* COnfigure the new spur table length */
size = (radio->spur_table_size + tbl_size);
retval = xfr_rdwr_data(radio, XFR_WRITE, 1, SPUR_TABLE_ADDR, &size);
if (retval < 0) {
FMDERR("%s: Failed to configure SPUR table size\n", __func__);
return retval;
}
/* Program the spur table entries */
for (cnt = 0; cnt < (temp / 4); cnt++) {
offset = 0;
for (j = 0; j < 4; j++) {
xfr_buf[offset++] = GET_FREQ(COMPUTE_SPUR(
radio->spur_data.freq[index]), 1);
xfr_buf[offset++] = GET_FREQ(COMPUTE_SPUR(
radio->spur_data.freq[index]), 0);
xfr_buf[offset++] =
radio->spur_data.rmssi[index];
index++;
}
retval = xfr_rdwr_data(radio, XFR_WRITE, (SPUR_DATA_SIZE * 4),
addr, xfr_buf);
if (retval < 0) {
FMDERR("%s: Failed to program SPUR frequencies\n",
__func__);
return retval;
}
addr += (SPUR_DATA_SIZE * 4);
}
/* Program the additional SPUR Frequencies */
temp = radio->spur_table_size;
temp = (temp % 4);
if (temp > 0) {
offset = 0;
for (j = 0; j < temp; j++) {
xfr_buf[offset++] = GET_FREQ(COMPUTE_SPUR(
radio->spur_data.freq[index]), 1);
xfr_buf[offset++] = GET_FREQ(COMPUTE_SPUR(
radio->spur_data.freq[index]), 0);
xfr_buf[offset++] =
radio->spur_data.rmssi[index];
index++;
}
size = (temp * SPUR_DATA_SIZE);
retval = xfr_rdwr_data(radio, XFR_WRITE, size, addr, xfr_buf);
if (retval < 0) {
FMDERR("%s: Failed to program SPUR frequencies\n",
__func__);
return retval;
}
}
return retval;
}
static int xfr_rdwr_data(struct tavarua_device *radio, int op, int size,
unsigned long offset, unsigned char *buf) {
unsigned char xfr_buf[XFR_REG_NUM + 1];
int retval = 0, temp = 0;
/* zero initialize the buffer */
memset(xfr_buf, 0x0, XFR_REG_NUM);
/* save the 'size' parameter */
temp = size;
/* Populate the XFR bytes */
xfr_buf[XFR_MODE_OFFSET] = LSH_DATA(size, 1);
xfr_buf[XFR_ADDR_MSB_OFFSET] = GET_FREQ(offset, 1);
xfr_buf[XFR_ADDR_LSB_OFFSET] = GET_FREQ(offset, 0);
if (op == XFR_READ) {
if (size > XFR_REG_NUM) {
FMDERR("%s: Cant read more than 16 bytes\n", __func__);
return -EINVAL;
}
xfr_buf[XFR_MODE_OFFSET] |= (XFR_PEEK_MODE);
size = 3;
} else if (op == XFR_WRITE) {
if (size > (XFR_REG_NUM - 2)) {
FMDERR("%s: Cant write more than 14 bytes\n", __func__);
return -EINVAL;
}
xfr_buf[XFR_MODE_OFFSET] |= (XFR_POKE_MODE);
memcpy(&xfr_buf[XFR_DATA_OFFSET], buf, size);
size += 3;
}
/* Perform the XFR READ/WRITE operation */
init_completion(&radio->sync_req_done);
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, size);
if (retval < 0) {
FMDERR("%s: Failed to perform XFR operation\n", __func__);
return retval;
}
/*Wait for the XFR interrupt */
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(WAIT_TIMEOUT))) {
FMDERR("Timeout: No XFR interrupt");
return -ETIMEDOUT;
}
/*
* For XFR READ operation save the XFR data provided by the SOC.
* Firmware reads the data from the address specified and places
* them in to the registers XFRDAT0-XFRDAT15 which the host can read.
*/
size = temp;
if (op == XFR_READ) {
retval = tavarua_read_registers(radio, XFRDAT0, size);
if (retval < 0) {
FMDERR("%s: Failed to read the XFR data\n", __func__);
return retval;
}
if (buf != NULL)
memcpy(buf, &radio->registers[XFRDAT0], size);
else {
FMDERR("%s: No buffer to copy XFR data\n", __func__);
return -EINVAL;
}
}
return retval;
}
static int peek_MPX_DCC(struct tavarua_device *radio)
{
int retval = 0;
unsigned char xfr_buf[XFR_REG_NUM];
int MPX_DCC[] = { 0 };
int DCC = 0;
int ct = 0;
unsigned char size = 0;
/*
Poking the MPX_DCC_BYPASS register to freeze the
value of MPX_DCC from changing while we access it
*/
/*Poking the MPX_DCC_BYPASS register : 0x88C0 */
size = 0x01;
xfr_buf[0] = (XFR_POKE_MODE | (size << 1));
xfr_buf[1] = MPX_DCC_BYPASS_POKE_MSB;
xfr_buf[2] = MPX_DCC_BYPASS_POKE_LSB;
xfr_buf[3] = 0x01;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 4);
if (retval < 0) {
FMDBG("Failed to write\n");
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*15);
for (ct = 0; ct < 5; ct++)
xfr_buf[ct] = 0;
/* Peeking Regs 0x88C2-0x88C4 */
size = 0x03;
xfr_buf[0] = (XFR_PEEK_MODE | (size << 1));
xfr_buf[1] = MPX_DCC_PEEK_MSB_REG1;
xfr_buf[2] = MPX_DCC_PEEK_LSB_REG1;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 3);
if (retval < 0) {
FMDBG("Failed to write\n");
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
retval = tavarua_read_registers(radio, XFRDAT0, 3);
if (retval < 0) {
printk(KERN_INFO "INT_DET: Read failure\n");
return retval;
}
MPX_DCC[0] = (int)radio->registers[XFRDAT0];
MPX_DCC[1] = (int)radio->registers[XFRDAT1];
MPX_DCC[2] = (int)radio->registers[XFRDAT2];
/*
Form the final MPX_DCC parameter
MPX_DCC[0] will form the LSB part
MPX_DCC[1] will be the middle part and 4 bits of
MPX_DCC[2] will be the MSB par of the 20-bit signed MPX_DCC
*/
DCC = ((int)MPX_DCC[2] << 16) | ((int)MPX_DCC[1] << 8) |
((int)MPX_DCC[0]);
/*
if bit-19 is '1',set remaining bits to '1' & make it -tive
*/
if (DCC & 0x00080000) {
FMDBG(KERN_INFO "bit-19 is '1'\n");
DCC |= 0xFFF00000;
}
/*
Poking the MPX_DCC_BYPASS register to be back to normal
*/
/*Poking the MPX_DCC_BYPASS register : 0x88C0 */
size = 0x01;
xfr_buf[0] = (XFR_POKE_MODE | (size << 1));
xfr_buf[1] = MPX_DCC_BYPASS_POKE_MSB;
xfr_buf[2] = MPX_DCC_BYPASS_POKE_LSB;
xfr_buf[3] = 0x00;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 4);
if (retval < 0) {
FMDBG("Failed to write\n");
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
return DCC;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_g_ctrl
=============================================================================*/
/**
This function is called to get the value of a control.
NOTE:
To get the current value of a control, applications initialize the id field
of a struct v4l2_control and call the VIDIOC_G_CTRL ioctl with a pointer to
this structure.
When the id is invalid drivers return an EINVAL error code. When the value is
out of bounds drivers can choose to take the closest valid value or return an
ERANGE error code, whatever seems more appropriate.
@param file: File descriptor returned by open().
@param ctrl: pointer to struct v4l2_control.
@return On success 0 is returned, else error code.
@return EINVAL: The struct v4l2_control id is invalid.
@return ERANGE: The struct v4l2_control value is out of bounds.
@return EBUSY: The control is temporarily not changeable, possibly because
another applications took over control of the device function this control
belongs to.
*/
static int tavarua_vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval = 0;
int cnt = 0;
unsigned char xfr_buf[XFR_REG_NUM];
signed char cRmssiThreshold;
signed char ioc;
unsigned char size = 0;
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
break;
case V4L2_CID_AUDIO_MUTE:
ctrl->value = radio->registers[IOCTRL] & 0x03 ;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCHMODE:
ctrl->value = radio->registers[SRCHCTRL] & SRCH_MODE;
break;
case V4L2_CID_PRIVATE_TAVARUA_SCANDWELL:
ctrl->value = (radio->registers[SRCHCTRL] & SCAN_DWELL) >> 4;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCHON:
ctrl->value = (radio->registers[SRCHCTRL] & SRCH_ON) >> 7 ;
break;
case V4L2_CID_PRIVATE_TAVARUA_STATE:
ctrl->value = (radio->registers[RDCTRL] & 0x03);
break;
case V4L2_CID_PRIVATE_TAVARUA_IOVERC:
retval = tavarua_read_registers(radio, IOVERC, 1);
if (retval < 0)
return retval;
ioc = radio->registers[IOVERC];
ctrl->value = ioc;
break;
case V4L2_CID_PRIVATE_TAVARUA_INTDET:
size = 0x1;
xfr_buf[0] = (XFR_PEEK_MODE | (size << 1));
xfr_buf[1] = INTDET_PEEK_MSB;
xfr_buf[2] = INTDET_PEEK_LSB;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 3);
if (retval < 0) {
FMDBG("Failed to write\n");
return retval;
}
FMDBG("INT_DET:Sync write success\n");
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
/* Read the XFRDAT0 register populated by FM SoC */
retval = tavarua_read_registers(radio, XFRDAT0, 3);
if (retval < 0) {
FMDBG("INT_DET: Read failure\n");
return retval;
}
ctrl->value = radio->registers[XFRDAT0];
break;
case V4L2_CID_PRIVATE_TAVARUA_MPX_DCC:
ctrl->value = peek_MPX_DCC(radio);
break;
case V4L2_CID_PRIVATE_TAVARUA_REGION:
ctrl->value = radio->region_params.region;
break;
case V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH:
retval = sync_read_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDBG("[G IOCTL=V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH]\n");
FMDBG("sync_read_xfr error: [retval=%d]\n", retval);
break;
}
/* Since RMSSI Threshold is signed value */
cRmssiThreshold = (signed char)xfr_buf[0];
ctrl->value = cRmssiThreshold;
FMDBG("cRmssiThreshold: %d\n", cRmssiThreshold);
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_PTY:
ctrl->value = radio->srch_params.srch_pty;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_PI:
ctrl->value = radio->srch_params.srch_pi;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_CNT:
ctrl->value = radio->srch_params.preset_num;
break;
case V4L2_CID_PRIVATE_TAVARUA_EMPHASIS:
ctrl->value = radio->region_params.emphasis;
break;
case V4L2_CID_PRIVATE_TAVARUA_RDS_STD:
ctrl->value = radio->region_params.rds_std;
break;
case V4L2_CID_PRIVATE_TAVARUA_SPACING:
ctrl->value = radio->region_params.spacing;
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSON:
ctrl->value = radio->registers[RDSCTRL] & RDS_ON;
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_MASK:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
if (retval > -1)
ctrl->value = (xfr_buf[8] << 24) |
(xfr_buf[9] << 16) |
(xfr_buf[10] << 8) |
xfr_buf[11];
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_PROC:
retval = tavarua_read_registers(radio, ADVCTRL, 1);
if (retval > -1)
ctrl->value = radio->registers[ADVCTRL];
msleep(TAVARUA_DELAY*5);
break;
case V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA:
retval = sync_read_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA]\n");
FMDERR("sync_read_xfr [retval=%d]\n", retval);
break;
}
ctrl->value = (unsigned char)xfr_buf[4];
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSD_BUF:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
if (retval > -1)
ctrl->value = xfr_buf[1];
break;
case V4L2_CID_PRIVATE_TAVARUA_PSALL:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
if (retval > -1)
ctrl->value = xfr_buf[12] & RDS_CONFIG_PSALL;
break;
case V4L2_CID_PRIVATE_TAVARUA_LP_MODE:
ctrl->value = radio->lp_mode;
break;
case V4L2_CID_PRIVATE_TAVARUA_ANTENNA:
ctrl->value = GET_REG_FIELD(radio->registers[IOCTRL],
IOC_ANTENNA_OFFSET, IOC_ANTENNA_MASK);
break;
case V4L2_CID_PRIVATE_INTF_LOW_THRESHOLD:
size = 0x04;
xfr_buf[0] = (XFR_PEEK_MODE | (size << 1));
xfr_buf[1] = ON_CHANNEL_TH_MSB;
xfr_buf[2] = ON_CHANNEL_TH_LSB;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 3);
if (retval < 0) {
pr_err("%s: Failed to write\n", __func__);
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
retval = tavarua_read_registers(radio, XFRDAT0, 4);
if (retval < 0) {
pr_err("%s: On Ch. DET: Read failure\n", __func__);
return retval;
}
for (cnt = 0; cnt < 4; cnt++)
FMDBG("On-Channel data set is : 0x%x\t",
(int)radio->registers[XFRDAT0+cnt]);
ctrl->value = LSH_DATA(radio->registers[XFRDAT0], 24) |
LSH_DATA(radio->registers[XFRDAT0+1], 16) |
LSH_DATA(radio->registers[XFRDAT0+2], 8) |
(radio->registers[XFRDAT0+3]);
FMDBG("The On Channel Threshold value is : 0x%x", ctrl->value);
break;
case V4L2_CID_PRIVATE_INTF_HIGH_THRESHOLD:
size = 0x04;
xfr_buf[0] = (XFR_PEEK_MODE | (size << 1));
xfr_buf[1] = OFF_CHANNEL_TH_MSB;
xfr_buf[2] = OFF_CHANNEL_TH_LSB;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 3);
if (retval < 0) {
pr_err("%s: Failed to write\n", __func__);
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
retval = tavarua_read_registers(radio, XFRDAT0, 4);
if (retval < 0) {
pr_err("%s: Off Ch. DET: Read failure\n", __func__);
return retval;
}
for (cnt = 0; cnt < 4; cnt++)
FMDBG("Off-channel data set is : 0x%x\t",
(int)radio->registers[XFRDAT0+cnt]);
ctrl->value = LSH_DATA(radio->registers[XFRDAT0], 24) |
LSH_DATA(radio->registers[XFRDAT0+1], 16) |
LSH_DATA(radio->registers[XFRDAT0+2], 8) |
(radio->registers[XFRDAT0+3]);
FMDBG("The Off Channel Threshold value is : 0x%x", ctrl->value);
break;
/*
* These IOCTL's are place holders to keep the
* driver compatible with change in frame works for IRIS
*/
case V4L2_CID_PRIVATE_SINR_THRESHOLD:
case V4L2_CID_PRIVATE_SINR_SAMPLES:
case V4L2_CID_PRIVATE_IRIS_GET_SINR:
retval = 0;
break;
case V4L2_CID_PRIVATE_VALID_CHANNEL:
ctrl->value = radio->is_station_valid;
break;
default:
retval = -EINVAL;
}
if (retval < 0)
printk(KERN_WARNING DRIVER_NAME
": get control failed with %d, id: %d\n", retval, ctrl->id);
return retval;
}
static int tavarua_vidioc_s_ext_ctrls(struct file *file, void *priv,
struct v4l2_ext_controls *ctrl)
{
int retval = 0;
int bytes_to_copy;
int bytes_copied = 0;
int bytes_left = 0;
int chunk_index = 0;
char tx_data[XFR_REG_NUM];
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
char *data = NULL;
int extra_name_byte = 0;
int name_bytes = 0;
switch ((ctrl->controls[0]).id) {
case V4L2_CID_RDS_TX_PS_NAME: {
FMDBG("In V4L2_CID_RDS_TX_PS_NAME\n");
/*Pass a sample PS string */
chunk_index = 0;
bytes_copied = 0;
bytes_left = min((int)(ctrl->controls[0]).size,
MAX_PS_LENGTH);
data = (ctrl->controls[0]).string;
/* send payload to FM hardware */
while (bytes_left) {
chunk_index++;
FMDBG("chunk is %d", chunk_index);
bytes_to_copy = min(bytes_left, XFR_REG_NUM);
/*Clear the tx_data */
memset(tx_data, 0, XFR_REG_NUM);
if (copy_from_user(tx_data,
data + bytes_copied, bytes_to_copy))
return -EFAULT;
retval = sync_write_xfr(radio,
RDS_PS_0 + chunk_index, tx_data);
if (retval < 0) {
FMDBG("sync_write_xfr: %d", retval);
return retval;
}
bytes_copied += bytes_to_copy;
bytes_left -= bytes_to_copy;
}
memset(tx_data, 0, XFR_REG_NUM);
/*Write the PS Header*/
FMDBG("Writing PS header\n");
extra_name_byte = (bytes_copied%8) ? 1 : 0;
name_bytes = (bytes_copied/8) + extra_name_byte;
/*8 bytes are grouped as 1 name */
tx_data[0] = (name_bytes) & MASK_TXREPCOUNT;
tx_data[1] = radio->pty & MASK_PTY; /* PTY */
tx_data[2] = ((radio->pi & MASK_PI_MSB) >> 8);
tx_data[3] = radio->pi & MASK_PI_LSB;
/* TX ctrl + repeatCount*/
tx_data[4] = TX_ON |
(radio->ps_repeatcount & MASK_TXREPCOUNT);
retval = sync_write_xfr(radio, RDS_PS_0, tx_data);
if (retval < 0) {
FMDBG("sync_write_xfr returned %d", retval);
return retval;
}
} break;
case V4L2_CID_RDS_TX_RADIO_TEXT: {
chunk_index = 0;
bytes_copied = 0;
FMDBG("In V4L2_CID_RDS_TX_RADIO_TEXT\n");
/*Pass a sample PS string */
FMDBG("Passed RT String : %s\n",
(ctrl->controls[0]).string);
bytes_left =
min((int)(ctrl->controls[0]).size, MAX_RT_LENGTH);
data = (ctrl->controls[0]).string;
/* send payload to FM hardware */
while (bytes_left) {
chunk_index++;
bytes_to_copy = min(bytes_left, XFR_REG_NUM);
memset(tx_data, 0, XFR_REG_NUM);
if (copy_from_user(tx_data,
data + bytes_copied, bytes_to_copy))
return -EFAULT;
retval = sync_write_xfr(radio,
RDS_RT_0 + chunk_index, tx_data);
if (retval < 0)
return retval;
bytes_copied += bytes_to_copy;
bytes_left -= bytes_to_copy;
}
/*Write the RT Header */
tx_data[0] = bytes_copied;
/* PTY */
tx_data[1] = TX_ON | ((radio->pty & MASK_PTY) >> 8);
/* PI high */
tx_data[2] = ((radio->pi & MASK_PI_MSB) >> 8);
/* PI low */
tx_data[3] = radio->pi & MASK_PI_LSB;
retval = sync_write_xfr(radio, RDS_RT_0 , tx_data);
if (retval < 0)
return retval;
FMDBG("done RT writing: %d\n", retval);
} break;
default:
{
FMDBG("Shouldn't reach here\n");
retval = -1;
}
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_s_ctrl
=============================================================================*/
/**
This function is called to set the value of a control.
NOTE:
To change the value of a control, applications initialize the id and value
fields of a struct v4l2_control and call the VIDIOC_S_CTRL ioctl.
When the id is invalid drivers return an EINVAL error code. When the value is
out of bounds drivers can choose to take the closest valid value or return an
ERANGE error code, whatever seems more appropriate.
@param file: File descriptor returned by open().
@param ctrl: pointer to struct v4l2_control.
@return On success 0 is returned, else error code.
@return EINVAL: The struct v4l2_control id is invalid.
@return ERANGE: The struct v4l2_control value is out of bounds.
@return EBUSY: The control is temporarily not changeable, possibly because
another applications took over control of the device function this control
belongs to.
*/
static int tavarua_vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval = 0, size = 0, cnt = 0;
unsigned char value;
unsigned char xfr_buf[XFR_REG_NUM];
unsigned char tx_data[XFR_REG_NUM];
unsigned char dis_buf[XFR_REG_NUM];
unsigned int freq = 0, mpx_dcc = 0;
unsigned long curr = 0, prev = 0;
memset(xfr_buf, 0x0, XFR_REG_NUM);
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
break;
case V4L2_CID_AUDIO_MUTE:
value = (radio->registers[IOCTRL] & ~IOC_HRD_MUTE) |
(ctrl->value & 0x03);
retval = tavarua_write_register(radio, IOCTRL, value);
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCHMODE:
value = (radio->registers[SRCHCTRL] & ~SRCH_MODE) |
ctrl->value;
radio->registers[SRCHCTRL] = value;
break;
case V4L2_CID_PRIVATE_TAVARUA_SCANDWELL:
value = (radio->registers[SRCHCTRL] & ~SCAN_DWELL) |
(ctrl->value << 4);
radio->registers[SRCHCTRL] = value;
break;
/* start/stop search */
case V4L2_CID_PRIVATE_TAVARUA_SRCHON:
FMDBG("starting search\n");
tavarua_search(radio, ctrl->value, SRCH_DIR_UP);
break;
case V4L2_CID_PRIVATE_TAVARUA_STATE:
/* check if already on */
radio->handle_irq = 1;
if (((ctrl->value == FM_RECV) || (ctrl->value == FM_TRANS))
&& !(radio->registers[RDCTRL] &
ctrl->value)) {
FMDBG("clearing flags\n");
init_completion(&radio->sync_xfr_start);
init_completion(&radio->sync_req_done);
radio->xfr_in_progress = 0;
radio->xfr_bytes_left = 0;
FMDBG("turning on ..\n");
retval = tavarua_start(radio, ctrl->value);
if (retval >= 0) {
/* Enabling 'SoftMute' & 'SignalBlending' */
value = (radio->registers[IOCTRL] |
IOC_SFT_MUTE | IOC_SIG_BLND);
retval = tavarua_write_register(radio,
IOCTRL, value);
if (retval < 0)
FMDBG("SMute and SBlending"
"not enabled\n");
}
}
/* check if off */
else if ((ctrl->value == FM_OFF) && radio->registers[RDCTRL]) {
radio->spur_table_size = 0;
FMDBG("%s: turning off...\n", __func__);
tavarua_write_register(radio, RDCTRL, ctrl->value);
/* flush the event and work queues */
kfifo_reset(&radio->data_buf[TAVARUA_BUF_EVENTS]);
flush_workqueue(radio->wqueue);
/*
* queue the READY event from the host side
* in case of FM off
*/
tavarua_q_event(radio, TAVARUA_EVT_RADIO_DISABLED);
FMDBG("%s, Disable All Interrupts\n", __func__);
/* disable irq */
dis_buf[STATUS_REG1] = 0x00;
dis_buf[STATUS_REG2] = 0x00;
dis_buf[STATUS_REG3] = TRANSFER;
retval = sync_write_xfr(radio, INT_CTRL, dis_buf);
if (retval < 0) {
pr_err("%s: failed to disable"
"Interrupts\n", __func__);
return retval;
}
}
break;
case V4L2_CID_PRIVATE_TAVARUA_SET_AUDIO_PATH:
FMDBG("Setting audio path ...\n");
if (ctrl->value == FM_DIGITAL_PATH) {
FMDBG("Digital audio path enabled ...\n");
retval = tavarua_set_audio_path(
TAVARUA_AUDIO_OUT_DIGITAL_ON,
TAVARUA_AUDIO_OUT_ANALOG_OFF);
if (retval < 0) {
FMDERR("Error in tavarua_set_audio_path"
" %d\n", retval);
}
} else if (ctrl->value == FM_ANALOG_PATH) {
FMDBG("Analog audio path enabled ...\n");
retval = tavarua_set_audio_path(
TAVARUA_AUDIO_OUT_DIGITAL_OFF,
TAVARUA_AUDIO_OUT_ANALOG_ON);
if (retval < 0) {
FMDERR("Error in tavarua_set_audio_path"
" %d\n", retval);
}
}
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_ALGORITHM:
radio->enable_optimized_srch_alg = ctrl->value;
FMDBG("V4L2_CID_PRIVATE_TAVARUA_SRCH_ALGORITHM : %d",
radio->enable_optimized_srch_alg);
break;
case V4L2_CID_PRIVATE_TAVARUA_REGION:
retval = tavarua_set_region(radio, ctrl->value);
break;
case V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH:
retval = sync_read_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH]\n");
FMDERR("sync_read_xfr [retval=%d]\n", retval);
break;
}
/* RMSSI Threshold is a signed 8 bit value */
xfr_buf[0] = (unsigned char)ctrl->value;
xfr_buf[1] = (unsigned char)ctrl->value;
retval = sync_write_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH]\n");
FMDERR("sync_write_xfr [retval=%d]\n", retval);
break;
}
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_PTY:
radio->srch_params.srch_pty = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_PI:
radio->srch_params.srch_pi = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_SRCH_CNT:
radio->srch_params.preset_num = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_EMPHASIS:
radio->region_params.emphasis = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_RDS_STD:
radio->region_params.rds_std = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_SPACING:
radio->region_params.spacing = ctrl->value;
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSON:
retval = 0;
if (ctrl->value != (radio->registers[RDSCTRL] & RDS_ON)) {
value = radio->registers[RDSCTRL] | ctrl->value;
retval = tavarua_write_register(radio, RDSCTRL, value);
}
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_MASK:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
if (retval < 0)
break;
xfr_buf[8] = (ctrl->value & 0xFF000000) >> 24;
xfr_buf[9] = (ctrl->value & 0x00FF0000) >> 16;
xfr_buf[10] = (ctrl->value & 0x0000FF00) >> 8;
xfr_buf[11] = (ctrl->value & 0x000000FF);
retval = sync_write_xfr(radio, RDS_CONFIG, xfr_buf);
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_PROC:
value = radio->registers[ADVCTRL] | ctrl->value;
retval = tavarua_write_register(radio, ADVCTRL, value);
break;
case V4L2_CID_PRIVATE_TAVARUA_AF_JUMP:
retval = tavarua_read_registers(radio, ADVCTRL, 1);
SET_REG_FIELD(radio->registers[ADVCTRL], ctrl->value,
RDSAF_OFFSET, RDSAF_MASK);
msleep(TAVARUA_DELAY*5);
retval = tavarua_write_register(radio,
ADVCTRL, radio->registers[ADVCTRL]);
msleep(TAVARUA_DELAY*5);
break;
case V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA:
retval = sync_read_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA]\n");
FMDERR("sync_read_xfr [retval=%d]\n", retval);
break;
}
xfr_buf[4] = (unsigned char)ctrl->value;
retval = sync_write_xfr(radio, RX_CONFIG, xfr_buf);
if (retval < 0) {
FMDERR("V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA]\n");
FMDERR("sync_write_xfr [retval=%d]\n", retval);
break;
}
break;
case V4L2_CID_PRIVATE_TAVARUA_HLSI:
retval = tavarua_read_registers(radio, RDCTRL, 1);
SET_REG_FIELD(radio->registers[RDCTRL], ctrl->value,
RDCTRL_HLSI_OFFSET, RDCTRL_HLSI_MASK);
retval = tavarua_write_register(radio, RDCTRL,
radio->registers[RDCTRL]);
break;
case V4L2_CID_PRIVATE_TAVARUA_RDSD_BUF:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
if (retval < 0)
break;
xfr_buf[1] = ctrl->value;
retval = sync_write_xfr(radio, RDS_CONFIG, xfr_buf);
break;
case V4L2_CID_PRIVATE_TAVARUA_PSALL:
retval = sync_read_xfr(radio, RDS_CONFIG, xfr_buf);
value = ctrl->value & RDS_CONFIG_PSALL;
if (retval < 0)
break;
xfr_buf[12] &= ~RDS_CONFIG_PSALL;
xfr_buf[12] |= value;
retval = sync_write_xfr(radio, RDS_CONFIG, xfr_buf);
break;
case V4L2_CID_PRIVATE_TAVARUA_LP_MODE:
retval = 0;
if (ctrl->value == radio->lp_mode)
break;
if (ctrl->value) {
FMDBG("going into low power mode\n");
retval = tavarua_disable_interrupts(radio);
} else {
FMDBG("going into normal power mode\n");
tavarua_setup_interrupts(radio,
(radio->registers[RDCTRL] & 0x03));
}
break;
case V4L2_CID_PRIVATE_TAVARUA_ANTENNA:
SET_REG_FIELD(radio->registers[IOCTRL], ctrl->value,
IOC_ANTENNA_OFFSET, IOC_ANTENNA_MASK);
break;
case V4L2_CID_PRIVATE_INTF_LOW_THRESHOLD:
size = 0x04;
/* Poking the value of ON Channel Threshold value */
xfr_buf[0] = (XFR_POKE_MODE | (size << 1));
xfr_buf[1] = ON_CHANNEL_TH_MSB;
xfr_buf[2] = ON_CHANNEL_TH_LSB;
/* Data to be poked into the register */
xfr_buf[3] = (ctrl->value & 0xFF000000) >> 24;
xfr_buf[4] = (ctrl->value & 0x00FF0000) >> 16;
xfr_buf[5] = (ctrl->value & 0x0000FF00) >> 8;
xfr_buf[6] = (ctrl->value & 0x000000FF);
for (cnt = 3; cnt < 7; cnt++) {
FMDBG("On-channel data to be poked is : %d",
(int)xfr_buf[cnt]);
}
retval = tavarua_write_registers(radio, XFRCTRL,
xfr_buf, size+3);
if (retval < 0) {
pr_err("%s: Failed to write\n", __func__);
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
break;
case V4L2_CID_PRIVATE_INTF_HIGH_THRESHOLD:
size = 0x04;
/* Poking the value of OFF Channel Threshold value */
xfr_buf[0] = (XFR_POKE_MODE | (size << 1));
xfr_buf[1] = OFF_CHANNEL_TH_MSB;
xfr_buf[2] = OFF_CHANNEL_TH_LSB;
/* Data to be poked into the register */
xfr_buf[3] = (ctrl->value & 0xFF000000) >> 24;
xfr_buf[4] = (ctrl->value & 0x00FF0000) >> 16;
xfr_buf[5] = (ctrl->value & 0x0000FF00) >> 8;
xfr_buf[6] = (ctrl->value & 0x000000FF);
for (cnt = 3; cnt < 7; cnt++) {
FMDBG("Off-channel data to be poked is : %d",
(int)xfr_buf[cnt]);
}
retval = tavarua_write_registers(radio, XFRCTRL,
xfr_buf, size+3);
if (retval < 0) {
pr_err("%s: Failed to write\n", __func__);
return retval;
}
/*Wait for the XFR interrupt */
msleep(TAVARUA_DELAY*10);
break;
/* TX Controls */
case V4L2_CID_RDS_TX_PTY: {
radio->pty = ctrl->value;
} break;
case V4L2_CID_RDS_TX_PI: {
radio->pi = ctrl->value;
} break;
case V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_PS_NAME: {
FMDBG("In STOP_RDS_TX_PS_NAME\n");
/*Pass a sample PS string */
memset(tx_data, '0', XFR_REG_NUM);
FMDBG("Writing PS header\n");
retval = sync_write_xfr(radio, RDS_PS_0, tx_data);
FMDBG("retval of PS Header write: %d", retval);
} break;
case V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_RT: {
memset(tx_data, '0', XFR_REG_NUM);
FMDBG("Writing RT header\n");
retval = sync_write_xfr(radio, RDS_RT_0, tx_data);
FMDBG("retval of Header write: %d", retval);
} break;
case V4L2_CID_PRIVATE_TAVARUA_TX_SETPSREPEATCOUNT: {
radio->ps_repeatcount = ctrl->value;
} break;
case V4L2_CID_TUNE_POWER_LEVEL: {
unsigned char tx_power_lvl_config[FM_TX_PWR_LVL_MAX+1] = {
0x85, /* tx_da<5:3> = 0 lpf<2:0> = 5*/
0x95, /* tx_da<5:3> = 2 lpf<2:0> = 5*/
0x9D, /* tx_da<5:3> = 3 lpf<2:0> = 5*/
0xA5, /* tx_da<5:3> = 4 lpf<2:0> = 5*/
0xAD, /* tx_da<5:3> = 5 lpf<2:0> = 5*/
0xB5, /* tx_da<5:3> = 6 lpf<2:0> = 5*/
0xBD, /* tx_da<5:3> = 7 lpf<2:0> = 5*/
0xBF /* tx_da<5:3> = 7 lpf<2:0> = 7*/
};
if (ctrl->value > FM_TX_PWR_LVL_MAX)
ctrl->value = FM_TX_PWR_LVL_MAX;
if (ctrl->value < FM_TX_PWR_LVL_0)
ctrl->value = FM_TX_PWR_LVL_0;
retval = sync_read_xfr(radio, PHY_TXGAIN, xfr_buf);
FMDBG("return for PHY_TXGAIN is %d", retval);
if (retval < 0) {
FMDBG("read failed");
break;
}
xfr_buf[2] = tx_power_lvl_config[ctrl->value];
retval = sync_write_xfr(radio, PHY_TXGAIN, xfr_buf);
FMDBG("return for write PHY_TXGAIN is %d", retval);
if (retval < 0)
FMDBG("write failed");
} break;
case V4L2_CID_PRIVATE_SOFT_MUTE:
radio->registers[IOCTRL] &= ~(IOC_SFT_MUTE);
if (ctrl->value)
radio->registers[IOCTRL] |= IOC_SFT_MUTE;
retval = tavarua_write_register(radio, IOCTRL,
radio->registers[IOCTRL]);
if (retval < 0)
FMDERR("Failed to enable/disable SMute\n");
break;
/*These IOCTL's are place holders to keep the
driver compatible with change in frame works for IRIS */
case V4L2_CID_PRIVATE_RIVA_ACCS_ADDR:
case V4L2_CID_PRIVATE_RIVA_ACCS_LEN:
case V4L2_CID_PRIVATE_RIVA_PEEK:
case V4L2_CID_PRIVATE_RIVA_POKE:
case V4L2_CID_PRIVATE_SSBI_ACCS_ADDR:
case V4L2_CID_PRIVATE_SSBI_PEEK:
case V4L2_CID_PRIVATE_SSBI_POKE:
case V4L2_CID_PRIVATE_RDS_GRP_COUNTERS:
case V4L2_CID_PRIVATE_SET_NOTCH_FILTER:
case V4L2_CID_PRIVATE_TAVARUA_DO_CALIBRATION:
case V4L2_CID_PRIVATE_SINR_THRESHOLD:
case V4L2_CID_PRIVATE_SINR_SAMPLES:
case V4L2_CID_PRIVATE_SPUR_SELECTION:
retval = 0;
break;
case V4L2_CID_PRIVATE_SPUR_FREQ:
radio->spur_data.freq[radio->spur_table_size] =
ctrl->value;
break;
case V4L2_CID_PRIVATE_SPUR_FREQ_RMSSI:
radio->spur_data.rmssi[radio->spur_table_size++] =
ctrl->value;
break;
case V4L2_CID_PRIVATE_UPDATE_SPUR_TABLE:
retval = update_spur_table(radio);
break;
case V4L2_CID_PRIVATE_TX_TONE:
retval = 0;
memset(xfr_buf, 0, sizeof(xfr_buf));
switch (ctrl->value) {
case ONE_KHZ_LR_EQUA_0DBFS:
xfr_buf[TONE_CHANNEL_EN_AND_SCALING_BYTE]
= TONE_LEFT_RIGHT_CH_ENABLED;
xfr_buf[TONE_LEFT_FREQ_BYTE] = 0x01;
xfr_buf[TONE_RIGHT_FREQ_BYTE] = 0x01;
break;
case ONE_KHZ_LEFTONLY_EQUA_0DBFS:
xfr_buf[TONE_CHANNEL_EN_AND_SCALING_BYTE]
= TONE_LEFT_CH_ENABLED;
xfr_buf[TONE_LEFT_FREQ_BYTE] = 0x01;
break;
case ONE_KHZ_RIGHTONLY_EQUA_0DBFS:
xfr_buf[TONE_CHANNEL_EN_AND_SCALING_BYTE]
= TONE_RIGHT_CH_ENABLED;
xfr_buf[TONE_RIGHT_FREQ_BYTE] = 0x01;
break;
case ONE_KHZ_LR_EQUA_l8DBFS:
xfr_buf[TONE_CHANNEL_EN_AND_SCALING_BYTE]
= (LSH_DATA(TONE_SCALE_IND_12,
TONE_SCALING_SHIFT)
| TONE_LEFT_RIGHT_CH_ENABLED);
xfr_buf[TONE_LEFT_FREQ_BYTE] = 0x01;
xfr_buf[TONE_RIGHT_FREQ_BYTE] = 0x01;
break;
case FIFTEEN_KHZ_LR_EQUA_l8DBFS:
xfr_buf[TONE_CHANNEL_EN_AND_SCALING_BYTE]
= (LSH_DATA(TONE_SCALE_IND_12,
TONE_SCALING_SHIFT)
| TONE_LEFT_RIGHT_CH_ENABLED);
xfr_buf[TONE_LEFT_FREQ_BYTE] = 0x0F;
xfr_buf[TONE_RIGHT_FREQ_BYTE] = 0x0F;
break;
default:
retval = -1;
FMDERR("tone generator value not valid\n");
break;
}
if (retval >= 0) {
xfr_buf[TONE_GEN_CTRL_BYTE] = 0x01;
retval = sync_write_xfr(radio, XFR_EXT, xfr_buf);
}
if (retval < 0)
FMDERR("Tone generator failed\n");
break;
case V4L2_CID_PRIVATE_VALID_CHANNEL:
/* Do not notify the host of tune event */
atomic_set(&radio->validate_channel, 1);
FMDBG("Going into low power mode\n");
retval = tavarua_disable_interrupts(radio);
/*
* Tune to 50KHz adjacent channel. If the requested station
* falls in JAPAN band and on the lower band-limit, then the
* adjacnet channel to be considered is 50KHz to the right side
* of the requested station as firmware does not allows to tune
* to frequency outside the range: 76000KHz to 108000KHz.
*/
if (ctrl->value == REGION_JAPAN_STANDARD_BAND_LOW)
freq = (ctrl->value + ADJ_CHANNEL_KHZ);
else
freq = (ctrl->value - ADJ_CHANNEL_KHZ);
INIT_COMPLETION(radio->sync_req_done);
retval = tavarua_set_freq(radio, (freq * TUNE_MULT));
if (retval < 0) {
FMDERR("Failed to tune to adjacent station\n");
goto error;
}
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout))) {
FMDERR("Timeout: No Tune response\n");
retval = -ETIMEDOUT;
goto error;
}
/*
* Wait for a minimum of 100ms for the firmware
* to start collecting the MPX_DCC values
*/
msleep(TAVARUA_DELAY * 10);
/* Compute MPX_DCC of adjacent station */
retval = compute_MPX_DCC(radio, &mpx_dcc);
if (retval < 0) {
FMDERR("Failed to get MPX_DCC of adjacent station\n");
goto error;
}
/* Calculate the absolute value of MPX_DCC */
prev = abs(mpx_dcc);
/* Tune back to original station */
INIT_COMPLETION(radio->sync_req_done);
retval = tavarua_set_freq(radio, (ctrl->value * TUNE_MULT));
if (retval < 0) {
FMDERR("Failed to tune to requested station\n");
goto error;
}
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout))) {
FMDERR("Timeout: No Tune response\n");
retval = -ETIMEDOUT;
goto error;
}
/*
* Wait for a minimum of 100ms for the firmware
* to start collecting the MPX_DCC values
*/
msleep(TAVARUA_DELAY * 10);
/* Compute MPX_DCC of current station */
retval = compute_MPX_DCC(radio, &mpx_dcc);
if (retval < 0) {
FMDERR("Failed to get MPX_DCC of current station\n");
goto error;
}
/* Calculate the absolute value of MPX_DCC */
curr = abs(mpx_dcc);
FMDBG("Going into normal power mode\n");
tavarua_setup_interrupts(radio,
(radio->registers[RDCTRL] & 0x03));
FMDBG("Absolute MPX_DCC of current station : %lu\n", curr);
FMDBG("Absolute MPX_DCC of adjacent station : %lu\n", prev);
/*
* For valid stations, the absolute MPX_DCC value will be within
* the range 0 <= MPX_DCC <= 12566 and the MPX_DCC value of the
* adjacent station will be greater than 20,000.
*/
if ((curr <= MPX_DCC_LIMIT) &&
(prev > MPX_DCC_UPPER_LIMIT)) {
FMDBG("%d KHz is A VALID STATION!\n", ctrl->value);
radio->is_station_valid = VALID_CHANNEL;
} else {
FMDBG("%d KHz is NOT A VALID STATION!\n", ctrl->value);
radio->is_station_valid = INVALID_CHANNEL;
}
error:
atomic_set(&radio->validate_channel, 0);
break;
default:
retval = -EINVAL;
}
if (retval < 0)
printk(KERN_WARNING DRIVER_NAME
": set control failed with %d, id : %d\n", retval, ctrl->id);
return retval;
}
static int compute_MPX_DCC(struct tavarua_device *radio, int *val)
{
int DCC = 0, retval = 0;
int MPX_DCC[3];
unsigned char value;
unsigned char xfr_buf[XFR_REG_NUM];
/* Freeze the MPX_DCC value from changing */
value = CTRL_ON;
retval = xfr_rdwr_data(radio, XFR_WRITE, 1, MPX_DCC_BYPASS_REG, &value);
if (retval < 0) {
FMDERR("%s: Failed to freeze MPX_DCC\n", __func__);
return retval;
}
/* Measure the MPX_DCC of current station. */
retval = xfr_rdwr_data(radio, XFR_READ, 3, MPX_DCC_DATA_REG, xfr_buf);
if (retval < 0) {
FMDERR("%s: Failed to read MPX_DCC\n", __func__);
return retval;
}
MPX_DCC[0] = xfr_buf[0];
MPX_DCC[1] = xfr_buf[1];
MPX_DCC[2] = xfr_buf[2];
/*
* Form the final MPX_DCC parameter
* MPX_DCC[0] will form the LSB part
* MPX_DCC[1] will be the middle part and 4 bits of
* MPX_DCC[2] will be the MSB part of the 20-bit signed MPX_DCC
*/
DCC = (LSH_DATA(MPX_DCC[2], 16) | LSH_DATA(MPX_DCC[1], 8) | MPX_DCC[0]);
/* if bit-19 is '1',set remaining bits to '1' & make it -tive */
if (DCC & 0x00080000)
DCC |= 0xFFF00000;
*val = DCC;
/* Un-freeze the MPX_DCC value */
value = CTRL_OFF;
retval = xfr_rdwr_data(radio, XFR_WRITE, 1, 0x88C0, &value);
if (retval < 0) {
FMDERR("%s: Failed to un-freeze MPX_DCC\n", __func__);
return retval;
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_g_tuner
=============================================================================*/
/**
This function is called to get tuner attributes.
NOTE:
To query the attributes of a tuner, applications initialize the index field
and zero out the reserved array of a struct v4l2_tuner and call the
VIDIOC_G_TUNER ioctl with a pointer to this structure. Drivers fill the rest
of the structure or return an EINVAL error code when the index is out of
bounds. To enumerate all tuners applications shall begin at index zero,
incrementing by one until the driver returns EINVAL.
@param file: File descriptor returned by open().
@param tuner: pointer to struct v4l2_tuner.
@return On success 0 is returned, else error code.
@return EINVAL: The struct v4l2_tuner index is out of bounds.
*/
static int tavarua_vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *tuner)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval;
unsigned char xfr_buf[XFR_REG_NUM];
char rmssi = 0;
unsigned char size = 0;
if (tuner->index > 0)
return -EINVAL;
/* read status rssi */
retval = tavarua_read_registers(radio, IOCTRL, 1);
if (retval < 0)
return retval;
/* read RMSSI */
size = 0x1;
xfr_buf[0] = (XFR_PEEK_MODE | (size << 1));
xfr_buf[1] = RMSSI_PEEK_MSB;
xfr_buf[2] = RMSSI_PEEK_LSB;
retval = tavarua_write_registers(radio, XFRCTRL, xfr_buf, 3);
msleep(TAVARUA_DELAY*10);
retval = tavarua_read_registers(radio, XFRDAT0, 3);
rmssi = radio->registers[XFRDAT0];
tuner->signal = rmssi;
strcpy(tuner->name, "FM");
tuner->type = V4L2_TUNER_RADIO;
tuner->rangelow = radio->region_params.band_low;
tuner->rangehigh = radio->region_params.band_high;
tuner->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_STEREO;
tuner->capability = V4L2_TUNER_CAP_LOW;
/* Stereo indicator == Stereo (instead of Mono) */
if (radio->registers[IOCTRL] & IOC_MON_STR)
tuner->audmode = V4L2_TUNER_MODE_STEREO;
else
tuner->audmode = V4L2_TUNER_MODE_MONO;
/* automatic frequency control: -1: freq to low, 1 freq to high */
tuner->afc = 0;
return 0;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_s_tuner
=============================================================================*/
/**
This function is called to set tuner attributes. Used to set mono/stereo mode.
NOTE:
Tuners have two writable properties, the audio mode and the radio frequency.
To change the audio mode, applications initialize the index, audmode and
reserved fields and call the VIDIOC_S_TUNER ioctl. This will not change the
current tuner, which is determined by the current video input. Drivers may
choose a different audio mode if the requested mode is invalid or unsupported.
Since this is a write-only ioctl, it does not return the actually selected
audio mode.
To change the radio frequency the VIDIOC_S_FREQUENCY ioctl is available.
@param file: File descriptor returned by open().
@param tuner: pointer to struct v4l2_tuner.
@return On success 0 is returned, else error code.
@return -EINVAL: The struct v4l2_tuner index is out of bounds.
*/
static int tavarua_vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *tuner)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval;
int audmode;
if (tuner->index > 0)
return -EINVAL;
FMDBG("%s: set low to %d\n", __func__, tuner->rangelow);
radio->region_params.band_low = tuner->rangelow;
radio->region_params.band_high = tuner->rangehigh;
if (tuner->audmode == V4L2_TUNER_MODE_MONO)
/* Mono */
audmode = (radio->registers[IOCTRL] | IOC_MON_STR);
else
/* Stereo */
audmode = (radio->registers[IOCTRL] & ~IOC_MON_STR);
retval = tavarua_write_register(radio, IOCTRL, audmode);
if (retval < 0)
printk(KERN_WARNING DRIVER_NAME
": set tuner failed with %d\n", retval);
return retval;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_g_frequency
=============================================================================*/
/**
This function is called to get tuner or modulator radio frequency.
NOTE:
To get the current tuner or modulator radio frequency applications set the
tuner field of a struct v4l2_frequency to the respective tuner or modulator
number (only input devices have tuners, only output devices have modulators),
zero out the reserved array and call the VIDIOC_G_FREQUENCY ioctl with a
pointer to this structure. The driver stores the current frequency in the
frequency field.
@param file: File descriptor returned by open().
@param freq: pointer to struct v4l2_frequency. This will be set to the
resultant
frequency in 62.5 khz on success.
@return On success 0 is returned, else error code.
@return EINVAL: The tuner index is out of bounds or the value in the type
field is wrong.
*/
static int tavarua_vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
freq->type = V4L2_TUNER_RADIO;
return tavarua_get_freq(radio, freq);
}
/*=============================================================================
FUNCTION: tavarua_vidioc_s_frequency
=============================================================================*/
/**
This function is called to set tuner or modulator radio frequency.
NOTE:
To change the current tuner or modulator radio frequency applications
initialize the tuner, type and frequency fields, and the reserved array of
a struct v4l2_frequency and call the VIDIOC_S_FREQUENCY ioctl with a pointer
to this structure. When the requested frequency is not possible the driver
assumes the closest possible value. However VIDIOC_S_FREQUENCY is a
write-only ioctl, it does not return the actual new frequency.
@param file: File descriptor returned by open().
@param freq: pointer to struct v4l2_frequency.
@return On success 0 is returned, else error code.
@return EINVAL: The tuner index is out of bounds or the value in the type
field is wrong.
*/
static int tavarua_vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int retval = -1;
struct v4l2_frequency getFreq;
FMDBG("%s\n", __func__);
if (freq->type != V4L2_TUNER_RADIO)
return -EINVAL;
FMDBG("Calling tavarua_set_freq\n");
INIT_COMPLETION(radio->sync_req_done);
retval = tavarua_set_freq(radio, freq->frequency);
if (retval < 0) {
printk(KERN_WARNING DRIVER_NAME
": set frequency failed with %d\n", retval);
} else {
/* Wait for interrupt i.e. complete
(&radio->sync_req_done); call */
if (!wait_for_completion_timeout(&radio->sync_req_done,
msecs_to_jiffies(wait_timeout))) {
FMDERR("Timeout: No Tune response");
retval = tavarua_get_freq(radio, &getFreq);
radio->tune_req = 0;
if (retval > 0) {
if (getFreq.frequency == freq->frequency) {
/** This is success, queut the event*/
tavarua_q_event(radio,
TAVARUA_EVT_TUNE_SUCC);
return 0;
} else {
return -EIO;
}
}
}
}
radio->tune_req = 0;
return retval;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_dqbuf
=============================================================================*/
/**
This function is called to exchange a buffer with the driver.
This is main buffer function, in essense its equivalent to a blocking
read call.
Applications call the VIDIOC_DQBUF ioctl to dequeue a filled (capturing) or
displayed (output) buffer from the driver's outgoing queue. They just set
the type and memory fields of a struct v4l2_buffer as above, when VIDIOC_DQBUF
is called with a pointer to this structure the driver fills the remaining
fields or returns an error code.
NOTE:
By default VIDIOC_DQBUF blocks when no buffer is in the outgoing queue.
When the O_NONBLOCK flag was given to the open() function, VIDIOC_DQBUF
returns immediately with an EAGAIN error code when no buffer is available.
@param file: File descriptor returned by open().
@param buffer: pointer to struct v4l2_buffer.
@return On success 0 is returned, else error code.
@return EAGAIN: Non-blocking I/O has been selected using O_NONBLOCK and no
buffer was in the outgoing queue.
@return EINVAL: The buffer type is not supported, or the index is out of
bounds, or no buffers have been allocated yet, or the userptr or length are
invalid.
@return ENOMEM: Not enough physical or virtual memory was available to enqueue
a user pointer buffer.
@return EIO: VIDIOC_DQBUF failed due to an internal error. Can also indicate
temporary problems like signal loss. Note the driver might dequeue an (empty)
buffer despite returning an error, or even stop capturing.
*/
static int tavarua_vidioc_dqbuf(struct file *file, void *priv,
struct v4l2_buffer *buffer)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
enum tavarua_buf_t buf_type = -1;
unsigned char buf_fifo[STD_BUF_SIZE] = {0};
struct kfifo *data_fifo = NULL;
unsigned char *buf = NULL;
unsigned int len = 0, retval = -1;
if ((radio == NULL) || (buffer == NULL)) {
FMDERR("radio/buffer is NULL\n");
return -ENXIO;
}
buf_type = buffer->index;
buf = (unsigned char *)buffer->m.userptr;
len = buffer->length;
FMDBG("%s: requesting buffer %d\n", __func__, buf_type);
if ((buf_type < TAVARUA_BUF_MAX) && (buf_type >= 0)) {
data_fifo = &radio->data_buf[buf_type];
if (buf_type == TAVARUA_BUF_EVENTS) {
if (wait_event_interruptible(radio->event_queue,
kfifo_len(data_fifo)) < 0) {
return -EINTR;
}
}
} else {
FMDERR("invalid buffer type\n");
return -EINVAL;
}
if (len <= STD_BUF_SIZE) {
buffer->bytesused = kfifo_out_locked(data_fifo, &buf_fifo[0],
len, &radio->buf_lock[buf_type]);
} else {
FMDERR("kfifo_out_locked can not use len more than 128\n");
return -EINVAL;
}
retval = copy_to_user(buf, &buf_fifo[0], buffer->bytesused);
if (retval > 0) {
FMDERR("Failed to copy %d bytes of data\n", retval);
return -EAGAIN;
}
return retval;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_g_fmt_type_private
=============================================================================*/
/**
This function is here to make the v4l2 framework happy.
We cannot use private buffers without it.
@param file: File descriptor returned by open().
@param f: pointer to struct v4l2_format.
@return On success 0 is returned, else error code.
@return EINVAL: The tuner index is out of bounds or the value in the type
field is wrong.
*/
static int tavarua_vidioc_g_fmt_type_private(struct file *file, void *priv,
struct v4l2_format *f)
{
return 0;
}
/*=============================================================================
FUNCTION: tavarua_vidioc_s_hw_freq_seek
=============================================================================*/
/**
This function is called to perform a hardware frequency seek.
Start a hardware frequency seek from the current frequency. To do this
applications initialize the tuner, type, seek_upward and wrap_around fields,
and zero out the reserved array of a struct v4l2_hw_freq_seek and call the
VIDIOC_S_HW_FREQ_SEEK ioctl with a pointer to this structure.
This ioctl is supported if the V4L2_CAP_HW_FREQ_SEEK capability is set.
@param file: File descriptor returned by open().
@param seek: pointer to struct v4l2_hw_freq_seek.
@return On success 0 is returned, else error code.
@return EINVAL: The tuner index is out of bounds or the value in the type
field is wrong.
@return EAGAIN: The ioctl timed-out. Try again.
*/
static int tavarua_vidioc_s_hw_freq_seek(struct file *file, void *priv,
struct v4l2_hw_freq_seek *seek)
{
struct tavarua_device *radio = video_get_drvdata(video_devdata(file));
int dir;
if (seek->seek_upward)
dir = SRCH_DIR_UP;
else
dir = SRCH_DIR_DOWN;
FMDBG("starting search\n");
return tavarua_search(radio, CTRL_ON, dir);
}
/*
* tavarua_viddev_tamples - video device interface
*/
static const struct v4l2_ioctl_ops tavarua_ioctl_ops = {
.vidioc_querycap = tavarua_vidioc_querycap,
.vidioc_queryctrl = tavarua_vidioc_queryctrl,
.vidioc_g_ctrl = tavarua_vidioc_g_ctrl,
.vidioc_s_ctrl = tavarua_vidioc_s_ctrl,
.vidioc_g_tuner = tavarua_vidioc_g_tuner,
.vidioc_s_tuner = tavarua_vidioc_s_tuner,
.vidioc_g_frequency = tavarua_vidioc_g_frequency,
.vidioc_s_frequency = tavarua_vidioc_s_frequency,
.vidioc_s_hw_freq_seek = tavarua_vidioc_s_hw_freq_seek,
.vidioc_dqbuf = tavarua_vidioc_dqbuf,
.vidioc_g_fmt_type_private = tavarua_vidioc_g_fmt_type_private,
.vidioc_s_ext_ctrls = tavarua_vidioc_s_ext_ctrls,
};
static struct video_device tavarua_viddev_template = {
.fops = &tavarua_fops,
.ioctl_ops = &tavarua_ioctl_ops,
.name = DRIVER_NAME,
.release = video_device_release,
};
/*==============================================================
FUNCTION: FmQSocCom_EnableInterrupts
==============================================================*/
/**
This function enable interrupts.
@param radio: structure pointer passed by client.
@param state: FM radio state (receiver/transmitter/off/reset).
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_setup_interrupts(struct tavarua_device *radio,
enum radio_state_t state)
{
int retval;
unsigned char int_ctrl[XFR_REG_NUM];
if (!radio->lp_mode)
return 0;
int_ctrl[STATUS_REG1] = READY | TUNE | SEARCH | SCANNEXT |
SIGNAL | INTF | SYNC | AUDIO;
if (state == FM_RECV)
int_ctrl[STATUS_REG2] = RDSDAT | RDSRT | RDSPS | RDSAF;
else
int_ctrl[STATUS_REG2] = TXRDSDAT | TXRDSDONE;
int_ctrl[STATUS_REG3] = TRANSFER | ERROR;
/* use xfr for interrupt setup */
if (radio->chipID == MARIMBA_2_1 || radio->chipID == BAHAMA_1_0
|| radio->chipID == BAHAMA_2_0) {
FMDBG("Setting interrupts\n");
retval = sync_write_xfr(radio, INT_CTRL, int_ctrl);
/* use register write to setup interrupts */
} else {
retval = tavarua_write_register(radio,
STATUS_REG1, int_ctrl[STATUS_REG1]);
if (retval < 0)
return retval;
retval = tavarua_write_register(radio,
STATUS_REG2, int_ctrl[STATUS_REG2]);
if (retval < 0)
return retval;
retval = tavarua_write_register(radio,
STATUS_REG3, int_ctrl[STATUS_REG3]);
if (retval < 0)
return retval;
}
radio->lp_mode = 0;
/* tavarua_handle_interrupts force reads all the interrupt status
* registers and it is not valid for MBA 2.1
*/
if ((radio->chipID != MARIMBA_2_1) && (radio->chipID != BAHAMA_1_0)
&& (radio->chipID != BAHAMA_2_0))
tavarua_handle_interrupts(radio);
return retval;
}
/*==============================================================
FUNCTION: tavarua_disable_interrupts
==============================================================*/
/**
This function disables interrupts.
@param radio: structure pointer passed by client.
@return => 0 if successful.
@return < 0 if failure.
*/
static int tavarua_disable_interrupts(struct tavarua_device *radio)
{
unsigned char lpm_buf[XFR_REG_NUM];
int retval;
if (radio->lp_mode)
return 0;
FMDBG("%s\n", __func__);
/* In Low power mode, disable all the interrupts that are not being
waited by the Application */
lpm_buf[STATUS_REG1] = TUNE | SEARCH | SCANNEXT;
lpm_buf[STATUS_REG2] = 0x00;
lpm_buf[STATUS_REG3] = TRANSFER;
/* use xfr for interrupt setup */
wait_timeout = 100;
if (radio->chipID == MARIMBA_2_1 || radio->chipID == BAHAMA_1_0
|| radio->chipID == BAHAMA_2_0)
retval = sync_write_xfr(radio, INT_CTRL, lpm_buf);
/* use register write to setup interrupts */
else
retval = tavarua_write_registers(radio, STATUS_REG1, lpm_buf,
ARRAY_SIZE(lpm_buf));
/*INT_CTL writes may fail with TIME_OUT as all the
interrupts have been disabled
*/
if (retval > -1 || retval == -ETIME) {
radio->lp_mode = 1;
/*Consider timeout as a valid case here*/
retval = 0;
}
wait_timeout = WAIT_TIMEOUT;
return retval;
}
/*==============================================================
FUNCTION: tavarua_start
==============================================================*/
/**
Starts/enables the device (FM radio).
@param radio: structure pointer passed by client.
@param state: FM radio state (receiver/transmitter/off/reset).
@return On success 0 is returned, else error code.
*/
static int tavarua_start(struct tavarua_device *radio,
enum radio_state_t state)
{
int retval;
FMDBG("%s <%d>\n", __func__, state);
/* set geographic region */
radio->region_params.region = TAVARUA_REGION_US;
/* set radio mode */
retval = tavarua_write_register(radio, RDCTRL, state);
if (retval < 0)
return retval;
/* wait for radio to init */
msleep(RADIO_INIT_TIME);
/* enable interrupts */
tavarua_setup_interrupts(radio, state);
/* default region is US */
radio->region_params.band_low = US_LOW_BAND * FREQ_MUL;
radio->region_params.band_high = US_HIGH_BAND * FREQ_MUL;
return 0;
}
/*==============================================================
FUNCTION: tavarua_suspend
==============================================================*/
/**
Save state and stop all devices in system.
@param pdev: platform device to be suspended.
@param state: Power state to put each device in.
@return On success 0 is returned, else error code.
*/
static int tavarua_suspend(struct platform_device *pdev, pm_message_t state)
{
struct tavarua_device *radio = platform_get_drvdata(pdev);
int retval;
int users = 0;
printk(KERN_INFO DRIVER_NAME "%s: radio suspend\n\n", __func__);
if (radio) {
users = atomic_read(&radio->users);
if (!users) {
retval = tavarua_disable_interrupts(radio);
if (retval < 0) {
printk(KERN_INFO DRIVER_NAME
"tavarua_suspend error %d\n", retval);
return -EIO;
}
}
}
return 0;
}
/*==============================================================
FUNCTION: tavarua_resume
==============================================================*/
/**
Restore state of each device in system.
@param pdev: platform device to be resumed.
@return On success 0 is returned, else error code.
*/
static int tavarua_resume(struct platform_device *pdev)
{
struct tavarua_device *radio = platform_get_drvdata(pdev);
int retval;
int users = 0;
printk(KERN_INFO DRIVER_NAME "%s: radio resume\n\n", __func__);
if (radio) {
users = atomic_read(&radio->users);
if (!users) {
retval = tavarua_setup_interrupts(radio,
(radio->registers[RDCTRL] & 0x03));
if (retval < 0) {
printk(KERN_INFO DRIVER_NAME "Error in \
tavarua_resume %d\n", retval);
return -EIO;
}
}
}
return 0;
}
/*==============================================================
FUNCTION: tavarua_set_audio_path
==============================================================*/
/**
This function will configure the audio path to and from the
FM core.
This interface is expected to be called from the multimedia
driver's thread. This interface should only be called when
the FM hardware is enabled. If the FM hardware is not
currently enabled, this interface will return an error.
@param digital_on: Digital audio from the FM core should be enabled/disbled.
@param analog_on: Analog audio from the FM core should be enabled/disbled.
@return On success 0 is returned, else error code.
*/
int tavarua_set_audio_path(int digital_on, int analog_on)
{
struct tavarua_device *radio = private_data;
int rx_on = radio->registers[RDCTRL] & FM_RECV;
int retval = 0;
if (!radio)
return -ENOMEM;
/* RX */
FMDBG("%s: digital: %d analog: %d\n", __func__, digital_on, analog_on);
if ((radio->pdata != NULL) && (radio->pdata->config_i2s_gpio != NULL)) {
if (digital_on) {
retval = radio->pdata->config_i2s_gpio(FM_I2S_ON);
if (retval) {
pr_err("%s: config_i2s_gpio failed\n",
__func__);
}
} else {
retval = radio->pdata->config_i2s_gpio(FM_I2S_OFF);
if (retval) {
pr_err("%s: config_i2s_gpio failed\n",
__func__);
}
}
}
SET_REG_FIELD(radio->registers[AUDIOCTRL],
((rx_on && analog_on) ? 1 : 0),
AUDIORX_ANALOG_OFFSET,
AUDIORX_ANALOG_MASK);
SET_REG_FIELD(radio->registers[AUDIOCTRL],
((rx_on && digital_on) ? 1 : 0),
AUDIORX_DIGITAL_OFFSET,
AUDIORX_DIGITAL_MASK);
SET_REG_FIELD(radio->registers[AUDIOCTRL],
(rx_on ? 0 : 1),
AUDIOTX_OFFSET,
AUDIOTX_MASK);
/*
I2S Master/Slave configuration:
Setting the FM SoC as I2S Master/Slave
'false' - FM SoC is I2S Slave
'true' - FM SoC is I2S Master
We get this infomation from the respective target's board file :
MSM7x30 - FM SoC is I2S Slave
MSM8x60 - FM SoC is I2S Slave
MSM7x27A - FM SoC is I2S Master
*/
if (!radio->pdata->is_fm_soc_i2s_master) {
FMDBG("FM SoC is I2S Slave\n");
SET_REG_FIELD(radio->registers[AUDIOCTRL],
(0),
I2SCTRL_OFFSET,
I2SCTRL_MASK);
} else {
FMDBG("FM SoC is I2S Master\n");
SET_REG_FIELD(radio->registers[AUDIOCTRL],
(1),
I2SCTRL_OFFSET,
I2SCTRL_MASK);
}
FMDBG("%s: %x\n", __func__, radio->registers[AUDIOCTRL]);
return tavarua_write_register(radio, AUDIOCTRL,
radio->registers[AUDIOCTRL]);
}
/*==============================================================
FUNCTION: tavarua_probe
==============================================================*/
/**
Once called this functions initiates, allocates resources and registers video
tuner device with the v4l2 framework.
NOTE:
probe() should verify that the specified device hardware
actually exists; sometimes platform setup code can't be sure. The probing
can use device resources, including clocks, and device platform_data.
@param pdev: platform device to be probed.
@return On success 0 is returned, else error code.
-ENOMEM in low memory cases
*/
static int __init tavarua_probe(struct platform_device *pdev)
{
struct marimba_fm_platform_data *tavarua_pdata;
struct tavarua_device *radio;
int retval;
int i;
FMDBG("%s: probe called\n", __func__);
/* private data allocation */
radio = kzalloc(sizeof(struct tavarua_device), GFP_KERNEL);
if (!radio) {
retval = -ENOMEM;
goto err_initial;
}
radio->marimba = platform_get_drvdata(pdev);
tavarua_pdata = pdev->dev.platform_data;
radio->pdata = tavarua_pdata;
radio->dev = &pdev->dev;
platform_set_drvdata(pdev, radio);
/* video device allocation */
radio->videodev = video_device_alloc();
if (!radio->videodev)
goto err_radio;
/* initial configuration */
memcpy(radio->videodev, &tavarua_viddev_template,
sizeof(tavarua_viddev_template));
/*allocate internal buffers for decoded rds and event buffer*/
for (i = 0; i < TAVARUA_BUF_MAX; i++) {
int kfifo_alloc_rc=0;
spin_lock_init(&radio->buf_lock[i]);
if (i == TAVARUA_BUF_RAW_RDS)
kfifo_alloc_rc = kfifo_alloc(&radio->data_buf[i],
rds_buf*3, GFP_KERNEL);
else if (i == TAVARUA_BUF_RT_RDS)
kfifo_alloc_rc = kfifo_alloc(&radio->data_buf[i],
STD_BUF_SIZE * 2, GFP_KERNEL);
else
kfifo_alloc_rc = kfifo_alloc(&radio->data_buf[i],
STD_BUF_SIZE, GFP_KERNEL);
if (kfifo_alloc_rc!=0) {
printk(KERN_ERR "%s: failed allocating buffers %d\n",
__func__, kfifo_alloc_rc);
goto err_bufs;
}
}
/* initializing the device count */
atomic_set(&radio->users, 1);
radio->xfr_in_progress = 0;
radio->xfr_bytes_left = 0;
for (i = 0; i < TAVARUA_XFR_MAX; i++)
radio->pending_xfrs[i] = 0;
/* init transmit data */
radio->tx_mode = TAVARUA_TX_RT;
/* Init RT and PS Tx datas*/
radio->pty = 0;
radio->pi = 0;
radio->ps_repeatcount = 0;
/* init search params */
radio->srch_params.srch_pty = 0;
radio->srch_params.srch_pi = 0;
radio->srch_params.preset_num = 0;
radio->srch_params.get_list = 0;
/* radio initializes to low power mode */
radio->lp_mode = 1;
radio->handle_irq = 1;
/* init lock */
mutex_init(&radio->lock);
/* init completion flags */
init_completion(&radio->sync_xfr_start);
init_completion(&radio->sync_req_done);
radio->tune_req = 0;
/* initialize wait queue for event read */
init_waitqueue_head(&radio->event_queue);
/* initialize wait queue for raw rds read */
init_waitqueue_head(&radio->read_queue);
video_set_drvdata(radio->videodev, radio);
/*Start the worker thread for event handling and register read_int_stat
as worker function*/
radio->wqueue = create_singlethread_workqueue("kfmradio");
if (!radio->wqueue)
return -ENOMEM;
/* register video device */
if (video_register_device(radio->videodev, VFL_TYPE_RADIO, radio_nr)) {
printk(KERN_WARNING DRIVER_NAME
": Could not register video device\n");
goto err_all;
}
private_data = radio;
return 0;
err_all:
video_device_release(radio->videodev);
err_bufs:
for (; i > -1; i--)
kfifo_free(&radio->data_buf[i]);
err_radio:
kfree(radio);
err_initial:
return retval;
}
/*==============================================================
FUNCTION: tavarua_remove
==============================================================*/
/**
Removes the device.
@param pdev: platform device to be removed.
@return On success 0 is returned, else error code.
*/
static int __devexit tavarua_remove(struct platform_device *pdev)
{
int i;
struct tavarua_device *radio = platform_get_drvdata(pdev);
/* disable irq */
tavarua_disable_irq(radio);
destroy_workqueue(radio->wqueue);
video_unregister_device(radio->videodev);
/* free internal buffers */
for (i = 0; i < TAVARUA_BUF_MAX; i++)
kfifo_free(&radio->data_buf[i]);
/* free state struct */
kfree(radio);
platform_set_drvdata(pdev, NULL);
return 0;
}
/*
Platform drivers follow the standard driver model convention, where
discovery/enumeration is handled outside the drivers, and drivers
provide probe() and remove() methods. They support power management
and shutdown notifications using the standard conventions.
*/
static struct platform_driver tavarua_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "marimba_fm",
},
.remove = __devexit_p(tavarua_remove),
.suspend = tavarua_suspend,
.resume = tavarua_resume,
}; /* platform device we're adding */
/*************************************************************************
* Module Interface
************************************************************************/
/*==============================================================
FUNCTION: radio_module_init
==============================================================*/
/**
Module entry - add a platform-level device.
@return Returns zero if the driver registered and bound to a device, else
returns a negative error code when the driver not registered.
*/
static int __init radio_module_init(void)
{
printk(KERN_INFO DRIVER_DESC ", Version " DRIVER_VERSION "\n");
return platform_driver_probe(&tavarua_driver, tavarua_probe);
}
/*==============================================================
FUNCTION: radio_module_exit
==============================================================*/
/**
Module exit - removes a platform-level device.
NOTE:
Note that this function will also release all memory- and port-based
resources owned by the device (dev->resource).
@return none.
*/
static void __exit radio_module_exit(void)
{
platform_driver_unregister(&tavarua_driver);
}
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_VERSION(DRIVER_VERSION);
module_init(radio_module_init);
module_exit(radio_module_exit);
| gpl-2.0 |
bigzz/shamu_franc | arch/arm/mach-mmp/time.c | 944 | 5391 | /*
* linux/arch/arm/mach-mmp/time.c
*
* Support for clocksource and clockevents
*
* Copyright (C) 2008 Marvell International Ltd.
* All rights reserved.
*
* 2008-04-11: Jason Chagas <Jason.chagas@marvell.com>
* 2008-10-08: Bin Yang <bin.yang@marvell.com>
*
* The timers module actually includes three timers, each timer with up to
* three match comparators. Timer #0 is used here in free-running mode as
* the clock source, and match comparator #1 used as clock event device.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/clockchips.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/sched_clock.h>
#include <mach/addr-map.h>
#include <mach/regs-timers.h>
#include <mach/regs-apbc.h>
#include <mach/irqs.h>
#include <mach/cputype.h>
#include <asm/mach/time.h>
#include "clock.h"
#define TIMERS_VIRT_BASE TIMERS1_VIRT_BASE
#define MAX_DELTA (0xfffffffe)
#define MIN_DELTA (16)
static void __iomem *mmp_timer_base = TIMERS_VIRT_BASE;
/*
* FIXME: the timer needs some delay to stablize the counter capture
*/
static inline uint32_t timer_read(void)
{
int delay = 100;
__raw_writel(1, mmp_timer_base + TMR_CVWR(1));
while (delay--)
cpu_relax();
return __raw_readl(mmp_timer_base + TMR_CVWR(1));
}
static u32 notrace mmp_read_sched_clock(void)
{
return timer_read();
}
static irqreturn_t timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *c = dev_id;
/*
* Clear pending interrupt status.
*/
__raw_writel(0x01, mmp_timer_base + TMR_ICR(0));
/*
* Disable timer 0.
*/
__raw_writel(0x02, mmp_timer_base + TMR_CER);
c->event_handler(c);
return IRQ_HANDLED;
}
static int timer_set_next_event(unsigned long delta,
struct clock_event_device *dev)
{
unsigned long flags;
local_irq_save(flags);
/*
* Disable timer 0.
*/
__raw_writel(0x02, mmp_timer_base + TMR_CER);
/*
* Clear and enable timer match 0 interrupt.
*/
__raw_writel(0x01, mmp_timer_base + TMR_ICR(0));
__raw_writel(0x01, mmp_timer_base + TMR_IER(0));
/*
* Setup new clockevent timer value.
*/
__raw_writel(delta - 1, mmp_timer_base + TMR_TN_MM(0, 0));
/*
* Enable timer 0.
*/
__raw_writel(0x03, mmp_timer_base + TMR_CER);
local_irq_restore(flags);
return 0;
}
static void timer_set_mode(enum clock_event_mode mode,
struct clock_event_device *dev)
{
unsigned long flags;
local_irq_save(flags);
switch (mode) {
case CLOCK_EVT_MODE_ONESHOT:
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
/* disable the matching interrupt */
__raw_writel(0x00, mmp_timer_base + TMR_IER(0));
break;
case CLOCK_EVT_MODE_RESUME:
case CLOCK_EVT_MODE_PERIODIC:
break;
}
local_irq_restore(flags);
}
static struct clock_event_device ckevt = {
.name = "clockevent",
.features = CLOCK_EVT_FEAT_ONESHOT,
.rating = 200,
.set_next_event = timer_set_next_event,
.set_mode = timer_set_mode,
};
static cycle_t clksrc_read(struct clocksource *cs)
{
return timer_read();
}
static struct clocksource cksrc = {
.name = "clocksource",
.rating = 200,
.read = clksrc_read,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static void __init timer_config(void)
{
uint32_t ccr = __raw_readl(mmp_timer_base + TMR_CCR);
__raw_writel(0x0, mmp_timer_base + TMR_CER); /* disable */
ccr &= (cpu_is_mmp2()) ? (TMR_CCR_CS_0(0) | TMR_CCR_CS_1(0)) :
(TMR_CCR_CS_0(3) | TMR_CCR_CS_1(3));
__raw_writel(ccr, mmp_timer_base + TMR_CCR);
/* set timer 0 to periodic mode, and timer 1 to free-running mode */
__raw_writel(0x2, mmp_timer_base + TMR_CMR);
__raw_writel(0x1, mmp_timer_base + TMR_PLCR(0)); /* periodic */
__raw_writel(0x7, mmp_timer_base + TMR_ICR(0)); /* clear status */
__raw_writel(0x0, mmp_timer_base + TMR_IER(0));
__raw_writel(0x0, mmp_timer_base + TMR_PLCR(1)); /* free-running */
__raw_writel(0x7, mmp_timer_base + TMR_ICR(1)); /* clear status */
__raw_writel(0x0, mmp_timer_base + TMR_IER(1));
/* enable timer 1 counter */
__raw_writel(0x2, mmp_timer_base + TMR_CER);
}
static struct irqaction timer_irq = {
.name = "timer",
.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL,
.handler = timer_interrupt,
.dev_id = &ckevt,
};
void __init timer_init(int irq)
{
timer_config();
setup_sched_clock(mmp_read_sched_clock, 32, CLOCK_TICK_RATE);
ckevt.cpumask = cpumask_of(0);
setup_irq(irq, &timer_irq);
clocksource_register_hz(&cksrc, CLOCK_TICK_RATE);
clockevents_config_and_register(&ckevt, CLOCK_TICK_RATE,
MIN_DELTA, MAX_DELTA);
}
#ifdef CONFIG_OF
static struct of_device_id mmp_timer_dt_ids[] = {
{ .compatible = "mrvl,mmp-timer", },
{}
};
void __init mmp_dt_init_timer(void)
{
struct device_node *np;
int irq, ret;
np = of_find_matching_node(NULL, mmp_timer_dt_ids);
if (!np) {
ret = -ENODEV;
goto out;
}
irq = irq_of_parse_and_map(np, 0);
if (!irq) {
ret = -EINVAL;
goto out;
}
mmp_timer_base = of_iomap(np, 0);
if (!mmp_timer_base) {
ret = -ENOMEM;
goto out;
}
timer_init(irq);
return;
out:
pr_err("Failed to get timer from device tree with error:%d\n", ret);
}
#endif
| gpl-2.0 |
rukin5197/android_kernel_lge_m3s | drivers/net/smc-ultra.c | 944 | 19117 | /* smc-ultra.c: A SMC Ultra ethernet driver for linux. */
/*
This is a driver for the SMC Ultra and SMC EtherEZ ISA ethercards.
Written 1993-1998 by Donald Becker.
Copyright 1993 United States Government as represented by the
Director, National Security Agency.
This software may be used and distributed according to the terms
of the GNU General Public License, 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 driver uses the cards in the 8390-compatible mode.
Most of the run-time complexity is handled by the generic code in
8390.c. The code in this file is responsible for
ultra_probe() Detecting and initializing the card.
ultra_probe1()
ultra_probe_isapnp()
ultra_open() The card-specific details of starting, stopping
ultra_reset_8390() and resetting the 8390 NIC core.
ultra_close()
ultra_block_input() Routines for reading and writing blocks of
ultra_block_output() packet buffer memory.
ultra_pio_input()
ultra_pio_output()
This driver enables the shared memory only when doing the actual data
transfers to avoid a bug in early version of the card that corrupted
data transferred by a AHA1542.
This driver now supports the programmed-I/O (PIO) data transfer mode of
the EtherEZ. It does not use the non-8390-compatible "Altego" mode.
That support (if available) is in smc-ez.c.
Changelog:
Paul Gortmaker : multiple card support for module users.
Donald Becker : 4/17/96 PIO support, minor potential problems avoided.
Donald Becker : 6/6/96 correctly set auto-wrap bit.
Alexander Sotirov : 1/20/01 Added support for ISAPnP cards
Note about the ISA PnP support:
This driver can not autoprobe for more than one SMC EtherEZ PnP card.
You have to configure the second card manually through the /proc/isapnp
interface and then load the module with an explicit io=0x___ option.
*/
static const char version[] =
"smc-ultra.c:v2.02 2/3/98 Donald Becker (becker@cesdis.gsfc.nasa.gov)\n";
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/isapnp.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#include "8390.h"
#define DRV_NAME "smc-ultra"
/* A zero-terminated list of I/O addresses to be probed. */
static unsigned int ultra_portlist[] __initdata =
{0x200, 0x220, 0x240, 0x280, 0x300, 0x340, 0x380, 0};
static int ultra_probe1(struct net_device *dev, int ioaddr);
#ifdef __ISAPNP__
static int ultra_probe_isapnp(struct net_device *dev);
#endif
static int ultra_open(struct net_device *dev);
static void ultra_reset_8390(struct net_device *dev);
static void ultra_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static void ultra_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset);
static void ultra_block_output(struct net_device *dev, int count,
const unsigned char *buf, const int start_page);
static void ultra_pio_get_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static void ultra_pio_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset);
static void ultra_pio_output(struct net_device *dev, int count,
const unsigned char *buf, const int start_page);
static int ultra_close_card(struct net_device *dev);
#ifdef __ISAPNP__
static struct isapnp_device_id ultra_device_ids[] __initdata = {
{ ISAPNP_VENDOR('S','M','C'), ISAPNP_FUNCTION(0x8416),
ISAPNP_VENDOR('S','M','C'), ISAPNP_FUNCTION(0x8416),
(long) "SMC EtherEZ (8416)" },
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(isapnp, ultra_device_ids);
#endif
#define START_PG 0x00 /* First page of TX buffer */
#define ULTRA_CMDREG 0 /* Offset to ASIC command register. */
#define ULTRA_RESET 0x80 /* Board reset, in ULTRA_CMDREG. */
#define ULTRA_MEMENB 0x40 /* Enable the shared memory. */
#define IOPD 0x02 /* I/O Pipe Data (16 bits), PIO operation. */
#define IOPA 0x07 /* I/O Pipe Address for PIO operation. */
#define ULTRA_NIC_OFFSET 16 /* NIC register offset from the base_addr. */
#define ULTRA_IO_EXTENT 32
#define EN0_ERWCNT 0x08 /* Early receive warning count. */
#ifdef CONFIG_NET_POLL_CONTROLLER
static void ultra_poll(struct net_device *dev)
{
disable_irq(dev->irq);
ei_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
/* Probe for the Ultra. This looks like a 8013 with the station
address PROM at I/O ports <base>+8 to <base>+13, with a checksum
following.
*/
static int __init do_ultra_probe(struct net_device *dev)
{
int i;
int base_addr = dev->base_addr;
int irq = dev->irq;
if (base_addr > 0x1ff) /* Check a single specified location. */
return ultra_probe1(dev, base_addr);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
#ifdef __ISAPNP__
/* Look for any installed ISAPnP cards */
if (isapnp_present() && (ultra_probe_isapnp(dev) == 0))
return 0;
#endif
for (i = 0; ultra_portlist[i]; i++) {
dev->irq = irq;
if (ultra_probe1(dev, ultra_portlist[i]) == 0)
return 0;
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init ultra_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_ultra_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static const struct net_device_ops ultra_netdev_ops = {
.ndo_open = ultra_open,
.ndo_stop = ultra_close_card,
.ndo_start_xmit = ei_start_xmit,
.ndo_tx_timeout = ei_tx_timeout,
.ndo_get_stats = ei_get_stats,
.ndo_set_multicast_list = 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 = ultra_poll,
#endif
};
static int __init ultra_probe1(struct net_device *dev, int ioaddr)
{
int i, retval;
int checksum = 0;
const char *model_name;
unsigned char eeprom_irq = 0;
static unsigned version_printed;
/* Values from various config regs. */
unsigned char num_pages, irqreg, addr, piomode;
unsigned char idreg = inb(ioaddr + 7);
unsigned char reg4 = inb(ioaddr + 4) & 0x7f;
if (!request_region(ioaddr, ULTRA_IO_EXTENT, DRV_NAME))
return -EBUSY;
/* Check the ID nibble. */
if ((idreg & 0xF0) != 0x20 /* SMC Ultra */
&& (idreg & 0xF0) != 0x40) { /* SMC EtherEZ */
retval = -ENODEV;
goto out;
}
/* Select the station address register set. */
outb(reg4, ioaddr + 4);
for (i = 0; i < 8; i++)
checksum += inb(ioaddr + 8 + i);
if ((checksum & 0xff) != 0xFF) {
retval = -ENODEV;
goto out;
}
if (ei_debug && version_printed++ == 0)
printk(version);
model_name = (idreg & 0xF0) == 0x20 ? "SMC Ultra" : "SMC EtherEZ";
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + 8 + i);
printk("%s: %s at %#3x, %pM", dev->name, model_name,
ioaddr, dev->dev_addr);
/* Switch from the station address to the alternate register set and
read the useful registers there. */
outb(0x80 | reg4, ioaddr + 4);
/* Enabled FINE16 mode to avoid BIOS ROM width mismatches @ reboot. */
outb(0x80 | inb(ioaddr + 0x0c), ioaddr + 0x0c);
piomode = inb(ioaddr + 0x8);
addr = inb(ioaddr + 0xb);
irqreg = inb(ioaddr + 0xd);
/* Switch back to the station address register set so that the MS-DOS driver
can find the card after a warm boot. */
outb(reg4, ioaddr + 4);
if (dev->irq < 2) {
unsigned char irqmap[] = {0, 9, 3, 5, 7, 10, 11, 15};
int irq;
/* The IRQ bits are split. */
irq = irqmap[((irqreg & 0x40) >> 4) + ((irqreg & 0x0c) >> 2)];
if (irq == 0) {
printk(", failed to detect IRQ line.\n");
retval = -EAGAIN;
goto out;
}
dev->irq = irq;
eeprom_irq = 1;
}
/* The 8390 isn't at the base address, so fake the offset */
dev->base_addr = ioaddr+ULTRA_NIC_OFFSET;
{
int addr_tbl[4] = {0x0C0000, 0x0E0000, 0xFC0000, 0xFE0000};
short num_pages_tbl[4] = {0x20, 0x40, 0x80, 0xff};
dev->mem_start = ((addr & 0x0f) << 13) + addr_tbl[(addr >> 6) & 3] ;
num_pages = num_pages_tbl[(addr >> 4) & 3];
}
ei_status.name = model_name;
ei_status.word16 = 1;
ei_status.tx_start_page = START_PG;
ei_status.rx_start_page = START_PG + TX_PAGES;
ei_status.stop_page = num_pages;
ei_status.mem = ioremap(dev->mem_start, (ei_status.stop_page - START_PG)*256);
if (!ei_status.mem) {
printk(", failed to ioremap.\n");
retval = -ENOMEM;
goto out;
}
dev->mem_end = dev->mem_start + (ei_status.stop_page - START_PG)*256;
if (piomode) {
printk(",%s IRQ %d programmed-I/O mode.\n",
eeprom_irq ? "EEPROM" : "assigned ", dev->irq);
ei_status.block_input = &ultra_pio_input;
ei_status.block_output = &ultra_pio_output;
ei_status.get_8390_hdr = &ultra_pio_get_hdr;
} else {
printk(",%s IRQ %d memory %#lx-%#lx.\n", eeprom_irq ? "" : "assigned ",
dev->irq, dev->mem_start, dev->mem_end-1);
ei_status.block_input = &ultra_block_input;
ei_status.block_output = &ultra_block_output;
ei_status.get_8390_hdr = &ultra_get_8390_hdr;
}
ei_status.reset_8390 = &ultra_reset_8390;
dev->netdev_ops = &ultra_netdev_ops;
NS8390_init(dev, 0);
retval = register_netdev(dev);
if (retval)
goto out;
return 0;
out:
release_region(ioaddr, ULTRA_IO_EXTENT);
return retval;
}
#ifdef __ISAPNP__
static int __init ultra_probe_isapnp(struct net_device *dev)
{
int i;
for (i = 0; ultra_device_ids[i].vendor != 0; i++) {
struct pnp_dev *idev = NULL;
while ((idev = pnp_find_dev(NULL,
ultra_device_ids[i].vendor,
ultra_device_ids[i].function,
idev))) {
/* Avoid already found cards from previous calls */
if (pnp_device_attach(idev) < 0)
continue;
if (pnp_activate_dev(idev) < 0) {
__again:
pnp_device_detach(idev);
continue;
}
/* if no io and irq, search for next */
if (!pnp_port_valid(idev, 0) || !pnp_irq_valid(idev, 0))
goto __again;
/* found it */
dev->base_addr = pnp_port_start(idev, 0);
dev->irq = pnp_irq(idev, 0);
printk(KERN_INFO "smc-ultra.c: ISAPnP reports %s at i/o %#lx, irq %d.\n",
(char *) ultra_device_ids[i].driver_data,
dev->base_addr, dev->irq);
if (ultra_probe1(dev, dev->base_addr) != 0) { /* Shouldn't happen. */
printk(KERN_ERR "smc-ultra.c: Probe of ISAPnP card at %#lx failed.\n", dev->base_addr);
pnp_device_detach(idev);
return -ENXIO;
}
ei_status.priv = (unsigned long)idev;
break;
}
if (!idev)
continue;
return 0;
}
return -ENODEV;
}
#endif
static int
ultra_open(struct net_device *dev)
{
int retval;
int ioaddr = dev->base_addr - ULTRA_NIC_OFFSET; /* ASIC addr */
unsigned char irq2reg[] = {0, 0, 0x04, 0x08, 0, 0x0C, 0, 0x40,
0, 0x04, 0x44, 0x48, 0, 0, 0, 0x4C, };
retval = request_irq(dev->irq, ei_interrupt, 0, dev->name, dev);
if (retval)
return retval;
outb(0x00, ioaddr); /* Disable shared memory for safety. */
outb(0x80, ioaddr + 5);
/* Set the IRQ line. */
outb(inb(ioaddr + 4) | 0x80, ioaddr + 4);
outb((inb(ioaddr + 13) & ~0x4C) | irq2reg[dev->irq], ioaddr + 13);
outb(inb(ioaddr + 4) & 0x7f, ioaddr + 4);
if (ei_status.block_input == &ultra_pio_input) {
outb(0x11, ioaddr + 6); /* Enable interrupts and PIO. */
outb(0x01, ioaddr + 0x19); /* Enable ring read auto-wrap. */
} else
outb(0x01, ioaddr + 6); /* Enable interrupts and memory. */
/* Set the early receive warning level in window 0 high enough not
to receive ERW interrupts. */
outb_p(E8390_NODMA+E8390_PAGE0, dev->base_addr);
outb(0xff, dev->base_addr + EN0_ERWCNT);
ei_open(dev);
return 0;
}
static void
ultra_reset_8390(struct net_device *dev)
{
int cmd_port = dev->base_addr - ULTRA_NIC_OFFSET; /* ASIC base addr */
outb(ULTRA_RESET, cmd_port);
if (ei_debug > 1) printk("resetting Ultra, t=%ld...", jiffies);
ei_status.txing = 0;
outb(0x00, cmd_port); /* Disable shared memory for safety. */
outb(0x80, cmd_port + 5);
if (ei_status.block_input == &ultra_pio_input)
outb(0x11, cmd_port + 6); /* Enable interrupts and PIO. */
else
outb(0x01, cmd_port + 6); /* Enable interrupts and memory. */
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
ultra_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page)
{
void __iomem *hdr_start = ei_status.mem + ((ring_page - START_PG)<<8);
outb(ULTRA_MEMENB, dev->base_addr - ULTRA_NIC_OFFSET); /* shmem on */
#ifdef __BIG_ENDIAN
/* Officially this is what we are doing, but the readl() is faster */
/* unfortunately it isn't endian aware of the struct */
memcpy_fromio(hdr, hdr_start, sizeof(struct e8390_pkt_hdr));
hdr->count = le16_to_cpu(hdr->count);
#else
((unsigned int*)hdr)[0] = readl(hdr_start);
#endif
outb(0x00, dev->base_addr - ULTRA_NIC_OFFSET); /* shmem off */
}
/* Block input and output are easy on shared memory ethercards, the only
complication is when the ring buffer wraps. */
static void
ultra_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset)
{
void __iomem *xfer_start = ei_status.mem + ring_offset - (START_PG<<8);
/* Enable shared memory. */
outb(ULTRA_MEMENB, dev->base_addr - ULTRA_NIC_OFFSET);
if (ring_offset + count > ei_status.stop_page*256) {
/* We must wrap the input move. */
int semi_count = ei_status.stop_page*256 - ring_offset;
memcpy_fromio(skb->data, xfer_start, semi_count);
count -= semi_count;
memcpy_fromio(skb->data + semi_count, ei_status.mem + TX_PAGES * 256, count);
} else {
memcpy_fromio(skb->data, xfer_start, count);
}
outb(0x00, dev->base_addr - ULTRA_NIC_OFFSET); /* Disable memory. */
}
static void
ultra_block_output(struct net_device *dev, int count, const unsigned char *buf,
int start_page)
{
void __iomem *shmem = ei_status.mem + ((start_page - START_PG)<<8);
/* Enable shared memory. */
outb(ULTRA_MEMENB, dev->base_addr - ULTRA_NIC_OFFSET);
memcpy_toio(shmem, buf, count);
outb(0x00, dev->base_addr - ULTRA_NIC_OFFSET); /* Disable memory. */
}
/* The identical operations for programmed I/O cards.
The PIO model is trivial to use: the 16 bit start address is written
byte-sequentially to IOPA, with no intervening I/O operations, and the
data is read or written to the IOPD data port.
The only potential complication is that the address register is shared
and must be always be rewritten between each read/write direction change.
This is no problem for us, as the 8390 code ensures that we are single
threaded. */
static void ultra_pio_get_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page)
{
int ioaddr = dev->base_addr - ULTRA_NIC_OFFSET; /* ASIC addr */
outb(0x00, ioaddr + IOPA); /* Set the address, LSB first. */
outb(ring_page, ioaddr + IOPA);
insw(ioaddr + IOPD, hdr, sizeof(struct e8390_pkt_hdr)>>1);
}
static void ultra_pio_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset)
{
int ioaddr = dev->base_addr - ULTRA_NIC_OFFSET; /* ASIC addr */
char *buf = skb->data;
/* For now set the address again, although it should already be correct. */
outb(ring_offset, ioaddr + IOPA); /* Set the address, LSB first. */
outb(ring_offset >> 8, ioaddr + IOPA);
/* We know skbuffs are padded to at least word alignment. */
insw(ioaddr + IOPD, buf, (count+1)>>1);
}
static void ultra_pio_output(struct net_device *dev, int count,
const unsigned char *buf, const int start_page)
{
int ioaddr = dev->base_addr - ULTRA_NIC_OFFSET; /* ASIC addr */
outb(0x00, ioaddr + IOPA); /* Set the address, LSB first. */
outb(start_page, ioaddr + IOPA);
/* An extra odd byte is OK here as well. */
outsw(ioaddr + IOPD, buf, (count+1)>>1);
}
static int
ultra_close_card(struct net_device *dev)
{
int ioaddr = dev->base_addr - ULTRA_NIC_OFFSET; /* CMDREG */
netif_stop_queue(dev);
if (ei_debug > 1)
printk("%s: Shutting down ethercard.\n", dev->name);
outb(0x00, ioaddr + 6); /* Disable interrupts. */
free_irq(dev->irq, dev);
NS8390_init(dev, 0);
/* We should someday disable shared memory and change to 8-bit mode
"just in case"... */
return 0;
}
#ifdef MODULE
#define MAX_ULTRA_CARDS 4 /* Max number of Ultra cards per module */
static struct net_device *dev_ultra[MAX_ULTRA_CARDS];
static int io[MAX_ULTRA_CARDS];
static int irq[MAX_ULTRA_CARDS];
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
MODULE_PARM_DESC(io, "I/O base address(es)");
MODULE_PARM_DESC(irq, "IRQ number(s) (assigned)");
MODULE_DESCRIPTION("SMC Ultra/EtherEZ ISA/PnP Ethernet driver");
MODULE_LICENSE("GPL");
/* This is set up so that only a single autoprobe takes place per call.
ISA device autoprobes on a running machine are not recommended. */
int __init
init_module(void)
{
struct net_device *dev;
int this_dev, found = 0;
for (this_dev = 0; this_dev < MAX_ULTRA_CARDS; this_dev++) {
if (io[this_dev] == 0) {
if (this_dev != 0) break; /* only autoprobe 1st one */
printk(KERN_NOTICE "smc-ultra.c: Presently autoprobing (not recommended) for a single card.\n");
}
dev = alloc_ei_netdev();
if (!dev)
break;
dev->irq = irq[this_dev];
dev->base_addr = io[this_dev];
if (do_ultra_probe(dev) == 0) {
dev_ultra[found++] = dev;
continue;
}
free_netdev(dev);
printk(KERN_WARNING "smc-ultra.c: No SMC Ultra 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)
{
/* NB: ultra_close_card() does free_irq */
#ifdef __ISAPNP__
struct pnp_dev *idev = (struct pnp_dev *)ei_status.priv;
if (idev)
pnp_device_detach(idev);
#endif
release_region(dev->base_addr - ULTRA_NIC_OFFSET, ULTRA_IO_EXTENT);
iounmap(ei_status.mem);
}
void __exit
cleanup_module(void)
{
int this_dev;
for (this_dev = 0; this_dev < MAX_ULTRA_CARDS; this_dev++) {
struct net_device *dev = dev_ultra[this_dev];
if (dev) {
unregister_netdev(dev);
cleanup_card(dev);
free_netdev(dev);
}
}
}
#endif /* MODULE */
| gpl-2.0 |
Xmister/linux-sunxi | arch/x86/mm/srat.c | 1200 | 4330 | /*
* ACPI 3.0 based NUMA setup
* Copyright 2004 Andi Kleen, SuSE Labs.
*
* Reads the ACPI SRAT table to figure out what memory belongs to which CPUs.
*
* Called from acpi_numa_init while reading the SRAT and SLIT tables.
* Assumes all memory regions belonging to a single proximity domain
* are in one chunk. Holes between them will be included in the node.
*/
#include <linux/kernel.h>
#include <linux/acpi.h>
#include <linux/mmzone.h>
#include <linux/bitmap.h>
#include <linux/module.h>
#include <linux/topology.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/mm.h>
#include <asm/proto.h>
#include <asm/numa.h>
#include <asm/e820.h>
#include <asm/apic.h>
#include <asm/uv/uv.h>
int acpi_numa __initdata;
static __init int setup_node(int pxm)
{
return acpi_map_pxm_to_node(pxm);
}
static __init void bad_srat(void)
{
printk(KERN_ERR "SRAT: SRAT not used.\n");
acpi_numa = -1;
}
static __init inline int srat_disabled(void)
{
return acpi_numa < 0;
}
/* Callback for SLIT parsing */
void __init acpi_numa_slit_init(struct acpi_table_slit *slit)
{
int i, j;
for (i = 0; i < slit->locality_count; i++)
for (j = 0; j < slit->locality_count; j++)
numa_set_distance(pxm_to_node(i), pxm_to_node(j),
slit->entry[slit->locality_count * i + j]);
}
/* Callback for Proximity Domain -> x2APIC mapping */
void __init
acpi_numa_x2apic_affinity_init(struct acpi_srat_x2apic_cpu_affinity *pa)
{
int pxm, node;
int apic_id;
if (srat_disabled())
return;
if (pa->header.length < sizeof(struct acpi_srat_x2apic_cpu_affinity)) {
bad_srat();
return;
}
if ((pa->flags & ACPI_SRAT_CPU_ENABLED) == 0)
return;
pxm = pa->proximity_domain;
node = setup_node(pxm);
if (node < 0) {
printk(KERN_ERR "SRAT: Too many proximity domains %x\n", pxm);
bad_srat();
return;
}
apic_id = pa->apic_id;
if (apic_id >= MAX_LOCAL_APIC) {
printk(KERN_INFO "SRAT: PXM %u -> APIC 0x%04x -> Node %u skipped apicid that is too big\n", pxm, apic_id, node);
return;
}
set_apicid_to_node(apic_id, node);
node_set(node, numa_nodes_parsed);
acpi_numa = 1;
printk(KERN_INFO "SRAT: PXM %u -> APIC 0x%04x -> Node %u\n",
pxm, apic_id, node);
}
/* Callback for Proximity Domain -> LAPIC mapping */
void __init
acpi_numa_processor_affinity_init(struct acpi_srat_cpu_affinity *pa)
{
int pxm, node;
int apic_id;
if (srat_disabled())
return;
if (pa->header.length != sizeof(struct acpi_srat_cpu_affinity)) {
bad_srat();
return;
}
if ((pa->flags & ACPI_SRAT_CPU_ENABLED) == 0)
return;
pxm = pa->proximity_domain_lo;
node = setup_node(pxm);
if (node < 0) {
printk(KERN_ERR "SRAT: Too many proximity domains %x\n", pxm);
bad_srat();
return;
}
if (get_uv_system_type() >= UV_X2APIC)
apic_id = (pa->apic_id << 8) | pa->local_sapic_eid;
else
apic_id = pa->apic_id;
if (apic_id >= MAX_LOCAL_APIC) {
printk(KERN_INFO "SRAT: PXM %u -> APIC 0x%02x -> Node %u skipped apicid that is too big\n", pxm, apic_id, node);
return;
}
set_apicid_to_node(apic_id, node);
node_set(node, numa_nodes_parsed);
acpi_numa = 1;
printk(KERN_INFO "SRAT: PXM %u -> APIC 0x%02x -> Node %u\n",
pxm, apic_id, node);
}
#ifdef CONFIG_MEMORY_HOTPLUG
static inline int save_add_info(void) {return 1;}
#else
static inline int save_add_info(void) {return 0;}
#endif
/* Callback for parsing of the Proximity Domain <-> Memory Area mappings */
void __init
acpi_numa_memory_affinity_init(struct acpi_srat_mem_affinity *ma)
{
u64 start, end;
int node, pxm;
if (srat_disabled())
return;
if (ma->header.length != sizeof(struct acpi_srat_mem_affinity)) {
bad_srat();
return;
}
if ((ma->flags & ACPI_SRAT_MEM_ENABLED) == 0)
return;
if ((ma->flags & ACPI_SRAT_MEM_HOT_PLUGGABLE) && !save_add_info())
return;
start = ma->base_address;
end = start + ma->length;
pxm = ma->proximity_domain;
node = setup_node(pxm);
if (node < 0) {
printk(KERN_ERR "SRAT: Too many proximity domains.\n");
bad_srat();
return;
}
if (numa_add_memblk(node, start, end) < 0) {
bad_srat();
return;
}
printk(KERN_INFO "SRAT: Node %u PXM %u %Lx-%Lx\n", node, pxm,
start, end);
}
void __init acpi_numa_arch_fixup(void) {}
int __init x86_acpi_numa_init(void)
{
int ret;
ret = acpi_numa_init();
if (ret < 0)
return ret;
return srat_disabled() ? -EINVAL : 0;
}
| gpl-2.0 |
DrSauerkraut/kernel_viewpad7e | arch/mips/vr41xx/common/irq.c | 1456 | 3014 | /*
* Interrupt handing routines for NEC VR4100 series.
*
* Copyright (C) 2005-2007 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/interrupt.h>
#include <linux/module.h>
#include <asm/irq_cpu.h>
#include <asm/system.h>
#include <asm/vr41xx/irq.h>
typedef struct irq_cascade {
int (*get_irq)(unsigned int);
} irq_cascade_t;
static irq_cascade_t irq_cascade[NR_IRQS] __cacheline_aligned;
static struct irqaction cascade_irqaction = {
.handler = no_action,
.name = "cascade",
};
int cascade_irq(unsigned int irq, int (*get_irq)(unsigned int))
{
int retval = 0;
if (irq >= NR_IRQS)
return -EINVAL;
if (irq_cascade[irq].get_irq != NULL)
free_irq(irq, NULL);
irq_cascade[irq].get_irq = get_irq;
if (get_irq != NULL) {
retval = setup_irq(irq, &cascade_irqaction);
if (retval < 0)
irq_cascade[irq].get_irq = NULL;
}
return retval;
}
EXPORT_SYMBOL_GPL(cascade_irq);
static void irq_dispatch(unsigned int irq)
{
irq_cascade_t *cascade;
struct irq_desc *desc;
if (irq >= NR_IRQS) {
atomic_inc(&irq_err_count);
return;
}
cascade = irq_cascade + irq;
if (cascade->get_irq != NULL) {
unsigned int source_irq = irq;
int ret;
desc = irq_desc + source_irq;
if (desc->chip->mask_ack)
desc->chip->mask_ack(source_irq);
else {
desc->chip->mask(source_irq);
desc->chip->ack(source_irq);
}
ret = cascade->get_irq(irq);
irq = ret;
if (ret < 0)
atomic_inc(&irq_err_count);
else
irq_dispatch(irq);
if (!(desc->status & IRQ_DISABLED) && desc->chip->unmask)
desc->chip->unmask(source_irq);
} else
do_IRQ(irq);
}
asmlinkage void plat_irq_dispatch(void)
{
unsigned int pending = read_c0_cause() & read_c0_status() & ST0_IM;
if (pending & CAUSEF_IP7)
do_IRQ(TIMER_IRQ);
else if (pending & 0x7800) {
if (pending & CAUSEF_IP3)
irq_dispatch(INT1_IRQ);
else if (pending & CAUSEF_IP4)
irq_dispatch(INT2_IRQ);
else if (pending & CAUSEF_IP5)
irq_dispatch(INT3_IRQ);
else if (pending & CAUSEF_IP6)
irq_dispatch(INT4_IRQ);
} else if (pending & CAUSEF_IP2)
irq_dispatch(INT0_IRQ);
else if (pending & CAUSEF_IP0)
do_IRQ(MIPS_SOFTINT0_IRQ);
else if (pending & CAUSEF_IP1)
do_IRQ(MIPS_SOFTINT1_IRQ);
else
spurious_interrupt();
}
void __init arch_init_irq(void)
{
mips_cpu_irq_init();
}
| gpl-2.0 |
hisilicon/linux-x5hd2 | drivers/gpio/gpio-wm8994.c | 1968 | 7673 | /*
* gpiolib support for Wolfson WM8994
*
* Copyright 2009 Wolfson Microelectronics PLC.
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/gpio.h>
#include <linux/mfd/core.h>
#include <linux/platform_device.h>
#include <linux/seq_file.h>
#include <linux/mfd/wm8994/core.h>
#include <linux/mfd/wm8994/pdata.h>
#include <linux/mfd/wm8994/gpio.h>
#include <linux/mfd/wm8994/registers.h>
struct wm8994_gpio {
struct wm8994 *wm8994;
struct gpio_chip gpio_chip;
};
static inline struct wm8994_gpio *to_wm8994_gpio(struct gpio_chip *chip)
{
return container_of(chip, struct wm8994_gpio, gpio_chip);
}
static int wm8994_gpio_request(struct gpio_chip *chip, unsigned offset)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
switch (wm8994->type) {
case WM8958:
switch (offset) {
case 1:
case 2:
case 3:
case 4:
case 6:
return -EINVAL;
}
break;
default:
break;
}
return 0;
}
static int wm8994_gpio_direction_in(struct gpio_chip *chip, unsigned offset)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
return wm8994_set_bits(wm8994, WM8994_GPIO_1 + offset,
WM8994_GPN_DIR, WM8994_GPN_DIR);
}
static int wm8994_gpio_get(struct gpio_chip *chip, unsigned offset)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
int ret;
ret = wm8994_reg_read(wm8994, WM8994_GPIO_1 + offset);
if (ret < 0)
return ret;
if (ret & WM8994_GPN_LVL)
return 1;
else
return 0;
}
static int wm8994_gpio_direction_out(struct gpio_chip *chip,
unsigned offset, int value)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
if (value)
value = WM8994_GPN_LVL;
return wm8994_set_bits(wm8994, WM8994_GPIO_1 + offset,
WM8994_GPN_DIR | WM8994_GPN_LVL, value);
}
static void wm8994_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
if (value)
value = WM8994_GPN_LVL;
wm8994_set_bits(wm8994, WM8994_GPIO_1 + offset, WM8994_GPN_LVL, value);
}
static int wm8994_gpio_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
if (!wm8994->irq_base)
return -EINVAL;
return wm8994->irq_base + offset;
}
#ifdef CONFIG_DEBUG_FS
static const char *wm8994_gpio_fn(u16 fn)
{
switch (fn) {
case WM8994_GP_FN_PIN_SPECIFIC:
return "pin-specific";
case WM8994_GP_FN_GPIO:
return "GPIO";
case WM8994_GP_FN_SDOUT:
return "SDOUT";
case WM8994_GP_FN_IRQ:
return "IRQ";
case WM8994_GP_FN_TEMPERATURE:
return "Temperature";
case WM8994_GP_FN_MICBIAS1_DET:
return "MICBIAS1 detect";
case WM8994_GP_FN_MICBIAS1_SHORT:
return "MICBIAS1 short";
case WM8994_GP_FN_MICBIAS2_DET:
return "MICBIAS2 detect";
case WM8994_GP_FN_MICBIAS2_SHORT:
return "MICBIAS2 short";
case WM8994_GP_FN_FLL1_LOCK:
return "FLL1 lock";
case WM8994_GP_FN_FLL2_LOCK:
return "FLL2 lock";
case WM8994_GP_FN_SRC1_LOCK:
return "SRC1 lock";
case WM8994_GP_FN_SRC2_LOCK:
return "SRC2 lock";
case WM8994_GP_FN_DRC1_ACT:
return "DRC1 activity";
case WM8994_GP_FN_DRC2_ACT:
return "DRC2 activity";
case WM8994_GP_FN_DRC3_ACT:
return "DRC3 activity";
case WM8994_GP_FN_WSEQ_STATUS:
return "Write sequencer";
case WM8994_GP_FN_FIFO_ERROR:
return "FIFO error";
case WM8994_GP_FN_OPCLK:
return "OPCLK";
case WM8994_GP_FN_THW:
return "Thermal warning";
case WM8994_GP_FN_DCS_DONE:
return "DC servo";
case WM8994_GP_FN_FLL1_OUT:
return "FLL1 output";
case WM8994_GP_FN_FLL2_OUT:
return "FLL1 output";
default:
return "Unknown";
}
}
static void wm8994_gpio_dbg_show(struct seq_file *s, struct gpio_chip *chip)
{
struct wm8994_gpio *wm8994_gpio = to_wm8994_gpio(chip);
struct wm8994 *wm8994 = wm8994_gpio->wm8994;
int i;
for (i = 0; i < chip->ngpio; i++) {
int gpio = i + chip->base;
int reg;
const char *label;
/* We report the GPIO even if it's not requested since
* we're also reporting things like alternate
* functions which apply even when the GPIO is not in
* use as a GPIO.
*/
label = gpiochip_is_requested(chip, i);
if (!label)
label = "Unrequested";
seq_printf(s, " gpio-%-3d (%-20.20s) ", gpio, label);
reg = wm8994_reg_read(wm8994, WM8994_GPIO_1 + i);
if (reg < 0) {
dev_err(wm8994->dev,
"GPIO control %d read failed: %d\n",
gpio, reg);
seq_printf(s, "\n");
continue;
}
if (reg & WM8994_GPN_DIR)
seq_printf(s, "in ");
else
seq_printf(s, "out ");
if (reg & WM8994_GPN_PU)
seq_printf(s, "pull up ");
if (reg & WM8994_GPN_PD)
seq_printf(s, "pull down ");
if (reg & WM8994_GPN_POL)
seq_printf(s, "inverted ");
else
seq_printf(s, "noninverted ");
if (reg & WM8994_GPN_OP_CFG)
seq_printf(s, "open drain ");
else
seq_printf(s, "CMOS ");
seq_printf(s, "%s (%x)\n",
wm8994_gpio_fn(reg & WM8994_GPN_FN_MASK), reg);
}
}
#else
#define wm8994_gpio_dbg_show NULL
#endif
static struct gpio_chip template_chip = {
.label = "wm8994",
.owner = THIS_MODULE,
.request = wm8994_gpio_request,
.direction_input = wm8994_gpio_direction_in,
.get = wm8994_gpio_get,
.direction_output = wm8994_gpio_direction_out,
.set = wm8994_gpio_set,
.to_irq = wm8994_gpio_to_irq,
.dbg_show = wm8994_gpio_dbg_show,
.can_sleep = 1,
};
static int __devinit wm8994_gpio_probe(struct platform_device *pdev)
{
struct wm8994 *wm8994 = dev_get_drvdata(pdev->dev.parent);
struct wm8994_pdata *pdata = wm8994->dev->platform_data;
struct wm8994_gpio *wm8994_gpio;
int ret;
wm8994_gpio = kzalloc(sizeof(*wm8994_gpio), GFP_KERNEL);
if (wm8994_gpio == NULL)
return -ENOMEM;
wm8994_gpio->wm8994 = wm8994;
wm8994_gpio->gpio_chip = template_chip;
wm8994_gpio->gpio_chip.ngpio = WM8994_GPIO_MAX;
wm8994_gpio->gpio_chip.dev = &pdev->dev;
if (pdata && pdata->gpio_base)
wm8994_gpio->gpio_chip.base = pdata->gpio_base;
else
wm8994_gpio->gpio_chip.base = -1;
ret = gpiochip_add(&wm8994_gpio->gpio_chip);
if (ret < 0) {
dev_err(&pdev->dev, "Could not register gpiochip, %d\n",
ret);
goto err;
}
platform_set_drvdata(pdev, wm8994_gpio);
return ret;
err:
kfree(wm8994_gpio);
return ret;
}
static int __devexit wm8994_gpio_remove(struct platform_device *pdev)
{
struct wm8994_gpio *wm8994_gpio = platform_get_drvdata(pdev);
int ret;
ret = gpiochip_remove(&wm8994_gpio->gpio_chip);
if (ret == 0)
kfree(wm8994_gpio);
return ret;
}
static struct platform_driver wm8994_gpio_driver = {
.driver.name = "wm8994-gpio",
.driver.owner = THIS_MODULE,
.probe = wm8994_gpio_probe,
.remove = __devexit_p(wm8994_gpio_remove),
};
static int __init wm8994_gpio_init(void)
{
return platform_driver_register(&wm8994_gpio_driver);
}
subsys_initcall(wm8994_gpio_init);
static void __exit wm8994_gpio_exit(void)
{
platform_driver_unregister(&wm8994_gpio_driver);
}
module_exit(wm8994_gpio_exit);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("GPIO interface for WM8994");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm8994-gpio");
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE550KL | kernel/fs/nfsd/nfs3acl.c | 2480 | 6473 | /*
* Process version 3 NFSACL requests.
*
* Copyright (C) 2002-2003 Andreas Gruenbacher <agruen@suse.de>
*/
#include "nfsd.h"
/* FIXME: nfsacl.h is a broken header */
#include <linux/nfsacl.h>
#include <linux/gfp.h>
#include "cache.h"
#include "xdr3.h"
#include "vfs.h"
#define RETURN_STATUS(st) { resp->status = (st); return (st); }
/*
* NULL call.
*/
static __be32
nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp)
{
return nfs_ok;
}
/*
* Get the Access and/or Default ACL of a file.
*/
static __be32 nfsd3_proc_getacl(struct svc_rqst * rqstp,
struct nfsd3_getaclargs *argp, struct nfsd3_getaclres *resp)
{
svc_fh *fh;
struct posix_acl *acl;
__be32 nfserr = 0;
fh = fh_copy(&resp->fh, &argp->fh);
nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP);
if (nfserr)
RETURN_STATUS(nfserr);
if (argp->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT))
RETURN_STATUS(nfserr_inval);
resp->mask = argp->mask;
if (resp->mask & (NFS_ACL|NFS_ACLCNT)) {
acl = nfsd_get_posix_acl(fh, ACL_TYPE_ACCESS);
if (IS_ERR(acl)) {
int err = PTR_ERR(acl);
if (err == -ENODATA || err == -EOPNOTSUPP)
acl = NULL;
else {
nfserr = nfserrno(err);
goto fail;
}
}
if (acl == NULL) {
/* Solaris returns the inode's minimum ACL. */
struct inode *inode = fh->fh_dentry->d_inode;
acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL);
}
resp->acl_access = acl;
}
if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) {
/* Check how Solaris handles requests for the Default ACL
of a non-directory! */
acl = nfsd_get_posix_acl(fh, ACL_TYPE_DEFAULT);
if (IS_ERR(acl)) {
int err = PTR_ERR(acl);
if (err == -ENODATA || err == -EOPNOTSUPP)
acl = NULL;
else {
nfserr = nfserrno(err);
goto fail;
}
}
resp->acl_default = acl;
}
/* resp->acl_{access,default} are released in nfs3svc_release_getacl. */
RETURN_STATUS(0);
fail:
posix_acl_release(resp->acl_access);
posix_acl_release(resp->acl_default);
RETURN_STATUS(nfserr);
}
/*
* Set the Access and/or Default ACL of a file.
*/
static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp,
struct nfsd3_setaclargs *argp,
struct nfsd3_attrstat *resp)
{
svc_fh *fh;
__be32 nfserr = 0;
fh = fh_copy(&resp->fh, &argp->fh);
nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR);
if (!nfserr) {
nfserr = nfserrno( nfsd_set_posix_acl(
fh, ACL_TYPE_ACCESS, argp->acl_access) );
}
if (!nfserr) {
nfserr = nfserrno( nfsd_set_posix_acl(
fh, ACL_TYPE_DEFAULT, argp->acl_default) );
}
/* argp->acl_{access,default} may have been allocated in
nfs3svc_decode_setaclargs. */
posix_acl_release(argp->acl_access);
posix_acl_release(argp->acl_default);
RETURN_STATUS(nfserr);
}
/*
* XDR decode functions
*/
static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclargs *args)
{
if (!(p = nfs3svc_decode_fh(p, &args->fh)))
return 0;
args->mask = ntohl(*p); p++;
return xdr_argsize_check(rqstp, p);
}
static int nfs3svc_decode_setaclargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_setaclargs *args)
{
struct kvec *head = rqstp->rq_arg.head;
unsigned int base;
int n;
if (!(p = nfs3svc_decode_fh(p, &args->fh)))
return 0;
args->mask = ntohl(*p++);
if (args->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT) ||
!xdr_argsize_check(rqstp, p))
return 0;
base = (char *)p - (char *)head->iov_base;
n = nfsacl_decode(&rqstp->rq_arg, base, NULL,
(args->mask & NFS_ACL) ?
&args->acl_access : NULL);
if (n > 0)
n = nfsacl_decode(&rqstp->rq_arg, base + n, NULL,
(args->mask & NFS_DFACL) ?
&args->acl_default : NULL);
return (n > 0);
}
/*
* XDR encode functions
*/
/* GETACL */
static int nfs3svc_encode_getaclres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclres *resp)
{
struct dentry *dentry = resp->fh.fh_dentry;
p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0 && dentry && dentry->d_inode) {
struct inode *inode = dentry->d_inode;
struct kvec *head = rqstp->rq_res.head;
unsigned int base;
int n;
int w;
*p++ = htonl(resp->mask);
if (!xdr_ressize_check(rqstp, p))
return 0;
base = (char *)p - (char *)head->iov_base;
rqstp->rq_res.page_len = w = nfsacl_size(
(resp->mask & NFS_ACL) ? resp->acl_access : NULL,
(resp->mask & NFS_DFACL) ? resp->acl_default : NULL);
while (w > 0) {
if (!*(rqstp->rq_next_page++))
return 0;
w -= PAGE_SIZE;
}
n = nfsacl_encode(&rqstp->rq_res, base, inode,
resp->acl_access,
resp->mask & NFS_ACL, 0);
if (n > 0)
n = nfsacl_encode(&rqstp->rq_res, base + n, inode,
resp->acl_default,
resp->mask & NFS_DFACL,
NFS_ACL_DEFAULT);
if (n <= 0)
return 0;
} else
if (!xdr_ressize_check(rqstp, p))
return 0;
return 1;
}
/* SETACL */
static int nfs3svc_encode_setaclres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_attrstat *resp)
{
p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh);
return xdr_ressize_check(rqstp, p);
}
/*
* XDR release functions
*/
static int nfs3svc_release_getacl(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclres *resp)
{
fh_put(&resp->fh);
posix_acl_release(resp->acl_access);
posix_acl_release(resp->acl_default);
return 1;
}
#define nfs3svc_decode_voidargs NULL
#define nfs3svc_release_void NULL
#define nfsd3_setaclres nfsd3_attrstat
#define nfsd3_voidres nfsd3_voidargs
struct nfsd3_voidargs { int dummy; };
#define PROC(name, argt, rest, relt, cache, respsize) \
{ (svc_procfunc) nfsd3_proc_##name, \
(kxdrproc_t) nfs3svc_decode_##argt##args, \
(kxdrproc_t) nfs3svc_encode_##rest##res, \
(kxdrproc_t) nfs3svc_release_##relt, \
sizeof(struct nfsd3_##argt##args), \
sizeof(struct nfsd3_##rest##res), \
0, \
cache, \
respsize, \
}
#define ST 1 /* status*/
#define AT 21 /* attributes */
#define pAT (1+AT) /* post attributes - conditional */
#define ACL (1+NFS_ACL_MAX_ENTRIES*3) /* Access Control List */
static struct svc_procedure nfsd_acl_procedures3[] = {
PROC(null, void, void, void, RC_NOCACHE, ST),
PROC(getacl, getacl, getacl, getacl, RC_NOCACHE, ST+1+2*(1+ACL)),
PROC(setacl, setacl, setacl, fhandle, RC_NOCACHE, ST+pAT),
};
struct svc_version nfsd_acl_version3 = {
.vs_vers = 3,
.vs_nproc = 3,
.vs_proc = nfsd_acl_procedures3,
.vs_dispatch = nfsd_dispatch,
.vs_xdrsize = NFS3_SVC_XDRSIZE,
.vs_hidden = 0,
};
| gpl-2.0 |
Tkkg1994/Nova-Kernel | sound/soc/codecs/alc5623.c | 2480 | 34034 | /*
* alc5623.c -- alc562[123] ALSA Soc Audio driver
*
* Copyright 2008 Realtek Microelectronics
* Author: flove <flove@realtek.com> Ethan <eku@marvell.com>
*
* Copyright 2010 Arnaud Patard <arnaud.patard@rtp-net.org>
*
*
* Based on WM8753.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/tlv.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/alc5623.h>
#include "alc5623.h"
static int caps_charge = 2000;
module_param(caps_charge, int, 0);
MODULE_PARM_DESC(caps_charge, "ALC5623 cap charge time (msecs)");
/* codec private data */
struct alc5623_priv {
enum snd_soc_control_type control_type;
u8 id;
unsigned int sysclk;
u16 reg_cache[ALC5623_VENDOR_ID2+2];
unsigned int add_ctrl;
unsigned int jack_det_ctrl;
};
static void alc5623_fill_cache(struct snd_soc_codec *codec)
{
int i, step = codec->driver->reg_cache_step;
u16 *cache = codec->reg_cache;
/* not really efficient ... */
codec->cache_bypass = 1;
for (i = 0 ; i < codec->driver->reg_cache_size ; i += step)
cache[i] = snd_soc_read(codec, i);
codec->cache_bypass = 0;
}
static inline int alc5623_reset(struct snd_soc_codec *codec)
{
return snd_soc_write(codec, ALC5623_RESET, 0);
}
static int amp_mixer_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
/* to power-on/off class-d amp generators/speaker */
/* need to write to 'index-46h' register : */
/* so write index num (here 0x46) to reg 0x6a */
/* and then 0xffff/0 to reg 0x6c */
snd_soc_write(w->codec, ALC5623_HID_CTRL_INDEX, 0x46);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_write(w->codec, ALC5623_HID_CTRL_DATA, 0xFFFF);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_write(w->codec, ALC5623_HID_CTRL_DATA, 0);
break;
}
return 0;
}
/*
* ALC5623 Controls
*/
static const DECLARE_TLV_DB_SCALE(vol_tlv, -3450, 150, 0);
static const DECLARE_TLV_DB_SCALE(hp_tlv, -4650, 150, 0);
static const DECLARE_TLV_DB_SCALE(adc_rec_tlv, -1650, 150, 0);
static const unsigned int boost_tlv[] = {
TLV_DB_RANGE_HEAD(3),
0, 0, TLV_DB_SCALE_ITEM(0, 0, 0),
1, 1, TLV_DB_SCALE_ITEM(2000, 0, 0),
2, 2, TLV_DB_SCALE_ITEM(3000, 0, 0),
};
static const DECLARE_TLV_DB_SCALE(dig_tlv, 0, 600, 0);
static const struct snd_kcontrol_new alc5621_vol_snd_controls[] = {
SOC_DOUBLE_TLV("Speaker Playback Volume",
ALC5623_SPK_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Speaker Playback Switch",
ALC5623_SPK_OUT_VOL, 15, 7, 1, 1),
SOC_DOUBLE_TLV("Headphone Playback Volume",
ALC5623_HP_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Headphone Playback Switch",
ALC5623_HP_OUT_VOL, 15, 7, 1, 1),
};
static const struct snd_kcontrol_new alc5622_vol_snd_controls[] = {
SOC_DOUBLE_TLV("Speaker Playback Volume",
ALC5623_SPK_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Speaker Playback Switch",
ALC5623_SPK_OUT_VOL, 15, 7, 1, 1),
SOC_DOUBLE_TLV("Line Playback Volume",
ALC5623_HP_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Line Playback Switch",
ALC5623_HP_OUT_VOL, 15, 7, 1, 1),
};
static const struct snd_kcontrol_new alc5623_vol_snd_controls[] = {
SOC_DOUBLE_TLV("Line Playback Volume",
ALC5623_SPK_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Line Playback Switch",
ALC5623_SPK_OUT_VOL, 15, 7, 1, 1),
SOC_DOUBLE_TLV("Headphone Playback Volume",
ALC5623_HP_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Headphone Playback Switch",
ALC5623_HP_OUT_VOL, 15, 7, 1, 1),
};
static const struct snd_kcontrol_new alc5623_snd_controls[] = {
SOC_DOUBLE_TLV("Auxout Playback Volume",
ALC5623_MONO_AUX_OUT_VOL, 8, 0, 31, 1, hp_tlv),
SOC_DOUBLE("Auxout Playback Switch",
ALC5623_MONO_AUX_OUT_VOL, 15, 7, 1, 1),
SOC_DOUBLE_TLV("PCM Playback Volume",
ALC5623_STEREO_DAC_VOL, 8, 0, 31, 1, vol_tlv),
SOC_DOUBLE_TLV("AuxI Capture Volume",
ALC5623_AUXIN_VOL, 8, 0, 31, 1, vol_tlv),
SOC_DOUBLE_TLV("LineIn Capture Volume",
ALC5623_LINE_IN_VOL, 8, 0, 31, 1, vol_tlv),
SOC_SINGLE_TLV("Mic1 Capture Volume",
ALC5623_MIC_VOL, 8, 31, 1, vol_tlv),
SOC_SINGLE_TLV("Mic2 Capture Volume",
ALC5623_MIC_VOL, 0, 31, 1, vol_tlv),
SOC_DOUBLE_TLV("Rec Capture Volume",
ALC5623_ADC_REC_GAIN, 7, 0, 31, 0, adc_rec_tlv),
SOC_SINGLE_TLV("Mic 1 Boost Volume",
ALC5623_MIC_CTRL, 10, 2, 0, boost_tlv),
SOC_SINGLE_TLV("Mic 2 Boost Volume",
ALC5623_MIC_CTRL, 8, 2, 0, boost_tlv),
SOC_SINGLE_TLV("Digital Boost Volume",
ALC5623_ADD_CTRL_REG, 4, 3, 0, dig_tlv),
};
/*
* DAPM Controls
*/
static const struct snd_kcontrol_new alc5623_hp_mixer_controls[] = {
SOC_DAPM_SINGLE("LI2HP Playback Switch", ALC5623_LINE_IN_VOL, 15, 1, 1),
SOC_DAPM_SINGLE("AUXI2HP Playback Switch", ALC5623_AUXIN_VOL, 15, 1, 1),
SOC_DAPM_SINGLE("MIC12HP Playback Switch", ALC5623_MIC_ROUTING_CTRL, 15, 1, 1),
SOC_DAPM_SINGLE("MIC22HP Playback Switch", ALC5623_MIC_ROUTING_CTRL, 7, 1, 1),
SOC_DAPM_SINGLE("DAC2HP Playback Switch", ALC5623_STEREO_DAC_VOL, 15, 1, 1),
};
static const struct snd_kcontrol_new alc5623_hpl_mixer_controls[] = {
SOC_DAPM_SINGLE("ADC2HP_L Playback Switch", ALC5623_ADC_REC_GAIN, 15, 1, 1),
};
static const struct snd_kcontrol_new alc5623_hpr_mixer_controls[] = {
SOC_DAPM_SINGLE("ADC2HP_R Playback Switch", ALC5623_ADC_REC_GAIN, 14, 1, 1),
};
static const struct snd_kcontrol_new alc5623_mono_mixer_controls[] = {
SOC_DAPM_SINGLE("ADC2MONO_L Playback Switch", ALC5623_ADC_REC_GAIN, 13, 1, 1),
SOC_DAPM_SINGLE("ADC2MONO_R Playback Switch", ALC5623_ADC_REC_GAIN, 12, 1, 1),
SOC_DAPM_SINGLE("LI2MONO Playback Switch", ALC5623_LINE_IN_VOL, 13, 1, 1),
SOC_DAPM_SINGLE("AUXI2MONO Playback Switch", ALC5623_AUXIN_VOL, 13, 1, 1),
SOC_DAPM_SINGLE("MIC12MONO Playback Switch", ALC5623_MIC_ROUTING_CTRL, 13, 1, 1),
SOC_DAPM_SINGLE("MIC22MONO Playback Switch", ALC5623_MIC_ROUTING_CTRL, 5, 1, 1),
SOC_DAPM_SINGLE("DAC2MONO Playback Switch", ALC5623_STEREO_DAC_VOL, 13, 1, 1),
};
static const struct snd_kcontrol_new alc5623_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("LI2SPK Playback Switch", ALC5623_LINE_IN_VOL, 14, 1, 1),
SOC_DAPM_SINGLE("AUXI2SPK Playback Switch", ALC5623_AUXIN_VOL, 14, 1, 1),
SOC_DAPM_SINGLE("MIC12SPK Playback Switch", ALC5623_MIC_ROUTING_CTRL, 14, 1, 1),
SOC_DAPM_SINGLE("MIC22SPK Playback Switch", ALC5623_MIC_ROUTING_CTRL, 6, 1, 1),
SOC_DAPM_SINGLE("DAC2SPK Playback Switch", ALC5623_STEREO_DAC_VOL, 14, 1, 1),
};
/* Left Record Mixer */
static const struct snd_kcontrol_new alc5623_captureL_mixer_controls[] = {
SOC_DAPM_SINGLE("Mic1 Capture Switch", ALC5623_ADC_REC_MIXER, 14, 1, 1),
SOC_DAPM_SINGLE("Mic2 Capture Switch", ALC5623_ADC_REC_MIXER, 13, 1, 1),
SOC_DAPM_SINGLE("LineInL Capture Switch", ALC5623_ADC_REC_MIXER, 12, 1, 1),
SOC_DAPM_SINGLE("Left AuxI Capture Switch", ALC5623_ADC_REC_MIXER, 11, 1, 1),
SOC_DAPM_SINGLE("HPMixerL Capture Switch", ALC5623_ADC_REC_MIXER, 10, 1, 1),
SOC_DAPM_SINGLE("SPKMixer Capture Switch", ALC5623_ADC_REC_MIXER, 9, 1, 1),
SOC_DAPM_SINGLE("MonoMixer Capture Switch", ALC5623_ADC_REC_MIXER, 8, 1, 1),
};
/* Right Record Mixer */
static const struct snd_kcontrol_new alc5623_captureR_mixer_controls[] = {
SOC_DAPM_SINGLE("Mic1 Capture Switch", ALC5623_ADC_REC_MIXER, 6, 1, 1),
SOC_DAPM_SINGLE("Mic2 Capture Switch", ALC5623_ADC_REC_MIXER, 5, 1, 1),
SOC_DAPM_SINGLE("LineInR Capture Switch", ALC5623_ADC_REC_MIXER, 4, 1, 1),
SOC_DAPM_SINGLE("Right AuxI Capture Switch", ALC5623_ADC_REC_MIXER, 3, 1, 1),
SOC_DAPM_SINGLE("HPMixerR Capture Switch", ALC5623_ADC_REC_MIXER, 2, 1, 1),
SOC_DAPM_SINGLE("SPKMixer Capture Switch", ALC5623_ADC_REC_MIXER, 1, 1, 1),
SOC_DAPM_SINGLE("MonoMixer Capture Switch", ALC5623_ADC_REC_MIXER, 0, 1, 1),
};
static const char *alc5623_spk_n_sour_sel[] = {
"RN/-R", "RP/+R", "LN/-R", "Vmid" };
static const char *alc5623_hpl_out_input_sel[] = {
"Vmid", "HP Left Mix"};
static const char *alc5623_hpr_out_input_sel[] = {
"Vmid", "HP Right Mix"};
static const char *alc5623_spkout_input_sel[] = {
"Vmid", "HPOut Mix", "Speaker Mix", "Mono Mix"};
static const char *alc5623_aux_out_input_sel[] = {
"Vmid", "HPOut Mix", "Speaker Mix", "Mono Mix"};
/* auxout output mux */
static const struct soc_enum alc5623_aux_out_input_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 6, 4, alc5623_aux_out_input_sel);
static const struct snd_kcontrol_new alc5623_auxout_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_aux_out_input_enum);
/* speaker output mux */
static const struct soc_enum alc5623_spkout_input_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 10, 4, alc5623_spkout_input_sel);
static const struct snd_kcontrol_new alc5623_spkout_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_spkout_input_enum);
/* headphone left output mux */
static const struct soc_enum alc5623_hpl_out_input_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 9, 2, alc5623_hpl_out_input_sel);
static const struct snd_kcontrol_new alc5623_hpl_out_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_hpl_out_input_enum);
/* headphone right output mux */
static const struct soc_enum alc5623_hpr_out_input_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 8, 2, alc5623_hpr_out_input_sel);
static const struct snd_kcontrol_new alc5623_hpr_out_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_hpr_out_input_enum);
/* speaker output N select */
static const struct soc_enum alc5623_spk_n_sour_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 14, 4, alc5623_spk_n_sour_sel);
static const struct snd_kcontrol_new alc5623_spkoutn_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_spk_n_sour_enum);
static const struct snd_soc_dapm_widget alc5623_dapm_widgets[] = {
/* Muxes */
SND_SOC_DAPM_MUX("AuxOut Mux", SND_SOC_NOPM, 0, 0,
&alc5623_auxout_mux_controls),
SND_SOC_DAPM_MUX("SpeakerOut Mux", SND_SOC_NOPM, 0, 0,
&alc5623_spkout_mux_controls),
SND_SOC_DAPM_MUX("Left Headphone Mux", SND_SOC_NOPM, 0, 0,
&alc5623_hpl_out_mux_controls),
SND_SOC_DAPM_MUX("Right Headphone Mux", SND_SOC_NOPM, 0, 0,
&alc5623_hpr_out_mux_controls),
SND_SOC_DAPM_MUX("SpeakerOut N Mux", SND_SOC_NOPM, 0, 0,
&alc5623_spkoutn_mux_controls),
/* output mixers */
SND_SOC_DAPM_MIXER("HP Mix", SND_SOC_NOPM, 0, 0,
&alc5623_hp_mixer_controls[0],
ARRAY_SIZE(alc5623_hp_mixer_controls)),
SND_SOC_DAPM_MIXER("HPR Mix", ALC5623_PWR_MANAG_ADD2, 4, 0,
&alc5623_hpr_mixer_controls[0],
ARRAY_SIZE(alc5623_hpr_mixer_controls)),
SND_SOC_DAPM_MIXER("HPL Mix", ALC5623_PWR_MANAG_ADD2, 5, 0,
&alc5623_hpl_mixer_controls[0],
ARRAY_SIZE(alc5623_hpl_mixer_controls)),
SND_SOC_DAPM_MIXER("HPOut Mix", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("Mono Mix", ALC5623_PWR_MANAG_ADD2, 2, 0,
&alc5623_mono_mixer_controls[0],
ARRAY_SIZE(alc5623_mono_mixer_controls)),
SND_SOC_DAPM_MIXER("Speaker Mix", ALC5623_PWR_MANAG_ADD2, 3, 0,
&alc5623_speaker_mixer_controls[0],
ARRAY_SIZE(alc5623_speaker_mixer_controls)),
/* input mixers */
SND_SOC_DAPM_MIXER("Left Capture Mix", ALC5623_PWR_MANAG_ADD2, 1, 0,
&alc5623_captureL_mixer_controls[0],
ARRAY_SIZE(alc5623_captureL_mixer_controls)),
SND_SOC_DAPM_MIXER("Right Capture Mix", ALC5623_PWR_MANAG_ADD2, 0, 0,
&alc5623_captureR_mixer_controls[0],
ARRAY_SIZE(alc5623_captureR_mixer_controls)),
SND_SOC_DAPM_DAC("Left DAC", "Left HiFi Playback",
ALC5623_PWR_MANAG_ADD2, 9, 0),
SND_SOC_DAPM_DAC("Right DAC", "Right HiFi Playback",
ALC5623_PWR_MANAG_ADD2, 8, 0),
SND_SOC_DAPM_MIXER("I2S Mix", ALC5623_PWR_MANAG_ADD1, 15, 0, NULL, 0),
SND_SOC_DAPM_MIXER("AuxI Mix", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("Line Mix", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_ADC("Left ADC", "Left HiFi Capture",
ALC5623_PWR_MANAG_ADD2, 7, 0),
SND_SOC_DAPM_ADC("Right ADC", "Right HiFi Capture",
ALC5623_PWR_MANAG_ADD2, 6, 0),
SND_SOC_DAPM_PGA("Left Headphone", ALC5623_PWR_MANAG_ADD3, 10, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Headphone", ALC5623_PWR_MANAG_ADD3, 9, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpeakerOut", ALC5623_PWR_MANAG_ADD3, 12, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left AuxOut", ALC5623_PWR_MANAG_ADD3, 14, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right AuxOut", ALC5623_PWR_MANAG_ADD3, 13, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left LineIn", ALC5623_PWR_MANAG_ADD3, 7, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right LineIn", ALC5623_PWR_MANAG_ADD3, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left AuxI", ALC5623_PWR_MANAG_ADD3, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right AuxI", ALC5623_PWR_MANAG_ADD3, 4, 0, NULL, 0),
SND_SOC_DAPM_PGA("MIC1 PGA", ALC5623_PWR_MANAG_ADD3, 3, 0, NULL, 0),
SND_SOC_DAPM_PGA("MIC2 PGA", ALC5623_PWR_MANAG_ADD3, 2, 0, NULL, 0),
SND_SOC_DAPM_PGA("MIC1 Pre Amp", ALC5623_PWR_MANAG_ADD3, 1, 0, NULL, 0),
SND_SOC_DAPM_PGA("MIC2 Pre Amp", ALC5623_PWR_MANAG_ADD3, 0, 0, NULL, 0),
SND_SOC_DAPM_MICBIAS("Mic Bias1", ALC5623_PWR_MANAG_ADD1, 11, 0),
SND_SOC_DAPM_OUTPUT("AUXOUTL"),
SND_SOC_DAPM_OUTPUT("AUXOUTR"),
SND_SOC_DAPM_OUTPUT("HPL"),
SND_SOC_DAPM_OUTPUT("HPR"),
SND_SOC_DAPM_OUTPUT("SPKOUT"),
SND_SOC_DAPM_OUTPUT("SPKOUTN"),
SND_SOC_DAPM_INPUT("LINEINL"),
SND_SOC_DAPM_INPUT("LINEINR"),
SND_SOC_DAPM_INPUT("AUXINL"),
SND_SOC_DAPM_INPUT("AUXINR"),
SND_SOC_DAPM_INPUT("MIC1"),
SND_SOC_DAPM_INPUT("MIC2"),
SND_SOC_DAPM_VMID("Vmid"),
};
static const char *alc5623_amp_names[] = {"AB Amp", "D Amp"};
static const struct soc_enum alc5623_amp_enum =
SOC_ENUM_SINGLE(ALC5623_OUTPUT_MIXER_CTRL, 13, 2, alc5623_amp_names);
static const struct snd_kcontrol_new alc5623_amp_mux_controls =
SOC_DAPM_ENUM("Route", alc5623_amp_enum);
static const struct snd_soc_dapm_widget alc5623_dapm_amp_widgets[] = {
SND_SOC_DAPM_PGA_E("D Amp", ALC5623_PWR_MANAG_ADD2, 14, 0, NULL, 0,
amp_mixer_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA("AB Amp", ALC5623_PWR_MANAG_ADD2, 15, 0, NULL, 0),
SND_SOC_DAPM_MUX("AB-D Amp Mux", SND_SOC_NOPM, 0, 0,
&alc5623_amp_mux_controls),
};
static const struct snd_soc_dapm_route intercon[] = {
/* virtual mixer - mixes left & right channels */
{"I2S Mix", NULL, "Left DAC"},
{"I2S Mix", NULL, "Right DAC"},
{"Line Mix", NULL, "Right LineIn"},
{"Line Mix", NULL, "Left LineIn"},
{"AuxI Mix", NULL, "Left AuxI"},
{"AuxI Mix", NULL, "Right AuxI"},
{"AUXOUTL", NULL, "Left AuxOut"},
{"AUXOUTR", NULL, "Right AuxOut"},
/* HP mixer */
{"HPL Mix", "ADC2HP_L Playback Switch", "Left Capture Mix"},
{"HPL Mix", NULL, "HP Mix"},
{"HPR Mix", "ADC2HP_R Playback Switch", "Right Capture Mix"},
{"HPR Mix", NULL, "HP Mix"},
{"HP Mix", "LI2HP Playback Switch", "Line Mix"},
{"HP Mix", "AUXI2HP Playback Switch", "AuxI Mix"},
{"HP Mix", "MIC12HP Playback Switch", "MIC1 PGA"},
{"HP Mix", "MIC22HP Playback Switch", "MIC2 PGA"},
{"HP Mix", "DAC2HP Playback Switch", "I2S Mix"},
/* speaker mixer */
{"Speaker Mix", "LI2SPK Playback Switch", "Line Mix"},
{"Speaker Mix", "AUXI2SPK Playback Switch", "AuxI Mix"},
{"Speaker Mix", "MIC12SPK Playback Switch", "MIC1 PGA"},
{"Speaker Mix", "MIC22SPK Playback Switch", "MIC2 PGA"},
{"Speaker Mix", "DAC2SPK Playback Switch", "I2S Mix"},
/* mono mixer */
{"Mono Mix", "ADC2MONO_L Playback Switch", "Left Capture Mix"},
{"Mono Mix", "ADC2MONO_R Playback Switch", "Right Capture Mix"},
{"Mono Mix", "LI2MONO Playback Switch", "Line Mix"},
{"Mono Mix", "AUXI2MONO Playback Switch", "AuxI Mix"},
{"Mono Mix", "MIC12MONO Playback Switch", "MIC1 PGA"},
{"Mono Mix", "MIC22MONO Playback Switch", "MIC2 PGA"},
{"Mono Mix", "DAC2MONO Playback Switch", "I2S Mix"},
/* Left record mixer */
{"Left Capture Mix", "LineInL Capture Switch", "LINEINL"},
{"Left Capture Mix", "Left AuxI Capture Switch", "AUXINL"},
{"Left Capture Mix", "Mic1 Capture Switch", "MIC1 Pre Amp"},
{"Left Capture Mix", "Mic2 Capture Switch", "MIC2 Pre Amp"},
{"Left Capture Mix", "HPMixerL Capture Switch", "HPL Mix"},
{"Left Capture Mix", "SPKMixer Capture Switch", "Speaker Mix"},
{"Left Capture Mix", "MonoMixer Capture Switch", "Mono Mix"},
/*Right record mixer */
{"Right Capture Mix", "LineInR Capture Switch", "LINEINR"},
{"Right Capture Mix", "Right AuxI Capture Switch", "AUXINR"},
{"Right Capture Mix", "Mic1 Capture Switch", "MIC1 Pre Amp"},
{"Right Capture Mix", "Mic2 Capture Switch", "MIC2 Pre Amp"},
{"Right Capture Mix", "HPMixerR Capture Switch", "HPR Mix"},
{"Right Capture Mix", "SPKMixer Capture Switch", "Speaker Mix"},
{"Right Capture Mix", "MonoMixer Capture Switch", "Mono Mix"},
/* headphone left mux */
{"Left Headphone Mux", "HP Left Mix", "HPL Mix"},
{"Left Headphone Mux", "Vmid", "Vmid"},
/* headphone right mux */
{"Right Headphone Mux", "HP Right Mix", "HPR Mix"},
{"Right Headphone Mux", "Vmid", "Vmid"},
/* speaker out mux */
{"SpeakerOut Mux", "Vmid", "Vmid"},
{"SpeakerOut Mux", "HPOut Mix", "HPOut Mix"},
{"SpeakerOut Mux", "Speaker Mix", "Speaker Mix"},
{"SpeakerOut Mux", "Mono Mix", "Mono Mix"},
/* Mono/Aux Out mux */
{"AuxOut Mux", "Vmid", "Vmid"},
{"AuxOut Mux", "HPOut Mix", "HPOut Mix"},
{"AuxOut Mux", "Speaker Mix", "Speaker Mix"},
{"AuxOut Mux", "Mono Mix", "Mono Mix"},
/* output pga */
{"HPL", NULL, "Left Headphone"},
{"Left Headphone", NULL, "Left Headphone Mux"},
{"HPR", NULL, "Right Headphone"},
{"Right Headphone", NULL, "Right Headphone Mux"},
{"Left AuxOut", NULL, "AuxOut Mux"},
{"Right AuxOut", NULL, "AuxOut Mux"},
/* input pga */
{"Left LineIn", NULL, "LINEINL"},
{"Right LineIn", NULL, "LINEINR"},
{"Left AuxI", NULL, "AUXINL"},
{"Right AuxI", NULL, "AUXINR"},
{"MIC1 Pre Amp", NULL, "MIC1"},
{"MIC2 Pre Amp", NULL, "MIC2"},
{"MIC1 PGA", NULL, "MIC1 Pre Amp"},
{"MIC2 PGA", NULL, "MIC2 Pre Amp"},
/* left ADC */
{"Left ADC", NULL, "Left Capture Mix"},
/* right ADC */
{"Right ADC", NULL, "Right Capture Mix"},
{"SpeakerOut N Mux", "RN/-R", "SpeakerOut"},
{"SpeakerOut N Mux", "RP/+R", "SpeakerOut"},
{"SpeakerOut N Mux", "LN/-R", "SpeakerOut"},
{"SpeakerOut N Mux", "Vmid", "Vmid"},
{"SPKOUT", NULL, "SpeakerOut"},
{"SPKOUTN", NULL, "SpeakerOut N Mux"},
};
static const struct snd_soc_dapm_route intercon_spk[] = {
{"SpeakerOut", NULL, "SpeakerOut Mux"},
};
static const struct snd_soc_dapm_route intercon_amp_spk[] = {
{"AB Amp", NULL, "SpeakerOut Mux"},
{"D Amp", NULL, "SpeakerOut Mux"},
{"AB-D Amp Mux", "AB Amp", "AB Amp"},
{"AB-D Amp Mux", "D Amp", "D Amp"},
{"SpeakerOut", NULL, "AB-D Amp Mux"},
};
/* PLL divisors */
struct _pll_div {
u32 pll_in;
u32 pll_out;
u16 regvalue;
};
/* Note : pll code from original alc5623 driver. Not sure of how good it is */
/* useful only for master mode */
static const struct _pll_div codec_master_pll_div[] = {
{ 2048000, 8192000, 0x0ea0},
{ 3686400, 8192000, 0x4e27},
{ 12000000, 8192000, 0x456b},
{ 13000000, 8192000, 0x495f},
{ 13100000, 8192000, 0x0320},
{ 2048000, 11289600, 0xf637},
{ 3686400, 11289600, 0x2f22},
{ 12000000, 11289600, 0x3e2f},
{ 13000000, 11289600, 0x4d5b},
{ 13100000, 11289600, 0x363b},
{ 2048000, 16384000, 0x1ea0},
{ 3686400, 16384000, 0x9e27},
{ 12000000, 16384000, 0x452b},
{ 13000000, 16384000, 0x542f},
{ 13100000, 16384000, 0x03a0},
{ 2048000, 16934400, 0xe625},
{ 3686400, 16934400, 0x9126},
{ 12000000, 16934400, 0x4d2c},
{ 13000000, 16934400, 0x742f},
{ 13100000, 16934400, 0x3c27},
{ 2048000, 22579200, 0x2aa0},
{ 3686400, 22579200, 0x2f20},
{ 12000000, 22579200, 0x7e2f},
{ 13000000, 22579200, 0x742f},
{ 13100000, 22579200, 0x3c27},
{ 2048000, 24576000, 0x2ea0},
{ 3686400, 24576000, 0xee27},
{ 12000000, 24576000, 0x2915},
{ 13000000, 24576000, 0x772e},
{ 13100000, 24576000, 0x0d20},
};
static const struct _pll_div codec_slave_pll_div[] = {
{ 1024000, 16384000, 0x3ea0},
{ 1411200, 22579200, 0x3ea0},
{ 1536000, 24576000, 0x3ea0},
{ 2048000, 16384000, 0x1ea0},
{ 2822400, 22579200, 0x1ea0},
{ 3072000, 24576000, 0x1ea0},
};
static int alc5623_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id,
int source, unsigned int freq_in, unsigned int freq_out)
{
int i;
struct snd_soc_codec *codec = codec_dai->codec;
int gbl_clk = 0, pll_div = 0;
u16 reg;
if (pll_id < ALC5623_PLL_FR_MCLK || pll_id > ALC5623_PLL_FR_BCK)
return -ENODEV;
/* Disable PLL power */
snd_soc_update_bits(codec, ALC5623_PWR_MANAG_ADD2,
ALC5623_PWR_ADD2_PLL,
0);
/* pll is not used in slave mode */
reg = snd_soc_read(codec, ALC5623_DAI_CONTROL);
if (reg & ALC5623_DAI_SDP_SLAVE_MODE)
return 0;
if (!freq_in || !freq_out)
return 0;
switch (pll_id) {
case ALC5623_PLL_FR_MCLK:
for (i = 0; i < ARRAY_SIZE(codec_master_pll_div); i++) {
if (codec_master_pll_div[i].pll_in == freq_in
&& codec_master_pll_div[i].pll_out == freq_out) {
/* PLL source from MCLK */
pll_div = codec_master_pll_div[i].regvalue;
break;
}
}
break;
case ALC5623_PLL_FR_BCK:
for (i = 0; i < ARRAY_SIZE(codec_slave_pll_div); i++) {
if (codec_slave_pll_div[i].pll_in == freq_in
&& codec_slave_pll_div[i].pll_out == freq_out) {
/* PLL source from Bitclk */
gbl_clk = ALC5623_GBL_CLK_PLL_SOUR_SEL_BITCLK;
pll_div = codec_slave_pll_div[i].regvalue;
break;
}
}
break;
default:
return -EINVAL;
}
if (!pll_div)
return -EINVAL;
snd_soc_write(codec, ALC5623_GLOBAL_CLK_CTRL_REG, gbl_clk);
snd_soc_write(codec, ALC5623_PLL_CTRL, pll_div);
snd_soc_update_bits(codec, ALC5623_PWR_MANAG_ADD2,
ALC5623_PWR_ADD2_PLL,
ALC5623_PWR_ADD2_PLL);
gbl_clk |= ALC5623_GBL_CLK_SYS_SOUR_SEL_PLL;
snd_soc_write(codec, ALC5623_GLOBAL_CLK_CTRL_REG, gbl_clk);
return 0;
}
struct _coeff_div {
u16 fs;
u16 regvalue;
};
/* codec hifi mclk (after PLL) clock divider coefficients */
/* values inspired from column BCLK=32Fs of Appendix A table */
static const struct _coeff_div coeff_div[] = {
{256*8, 0x3a69},
{384*8, 0x3c6b},
{256*4, 0x2a69},
{384*4, 0x2c6b},
{256*2, 0x1a69},
{384*2, 0x1c6b},
{256*1, 0x0a69},
{384*1, 0x0c6b},
};
static int get_coeff(struct snd_soc_codec *codec, int rate)
{
struct alc5623_priv *alc5623 = snd_soc_codec_get_drvdata(codec);
int i;
for (i = 0; i < ARRAY_SIZE(coeff_div); i++) {
if (coeff_div[i].fs * rate == alc5623->sysclk)
return i;
}
return -EINVAL;
}
/*
* Clock after PLL and dividers
*/
static int alc5623_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct alc5623_priv *alc5623 = snd_soc_codec_get_drvdata(codec);
switch (freq) {
case 8192000:
case 11289600:
case 12288000:
case 16384000:
case 16934400:
case 18432000:
case 22579200:
case 24576000:
alc5623->sysclk = freq;
return 0;
}
return -EINVAL;
}
static int alc5623_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface = 0;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iface = ALC5623_DAI_SDP_MASTER_MODE;
break;
case SND_SOC_DAIFMT_CBS_CFS:
iface = ALC5623_DAI_SDP_SLAVE_MODE;
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= ALC5623_DAI_I2S_DF_I2S;
break;
case SND_SOC_DAIFMT_RIGHT_J:
iface |= ALC5623_DAI_I2S_DF_RIGHT;
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= ALC5623_DAI_I2S_DF_LEFT;
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= ALC5623_DAI_I2S_DF_PCM;
break;
case SND_SOC_DAIFMT_DSP_B:
iface |= ALC5623_DAI_I2S_DF_PCM | ALC5623_DAI_I2S_PCM_MODE;
break;
default:
return -EINVAL;
}
/* clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= ALC5623_DAI_MAIN_I2S_BCLK_POL_CTRL;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= ALC5623_DAI_MAIN_I2S_BCLK_POL_CTRL;
break;
case SND_SOC_DAIFMT_NB_IF:
break;
default:
return -EINVAL;
}
return snd_soc_write(codec, ALC5623_DAI_CONTROL, iface);
}
static int alc5623_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct alc5623_priv *alc5623 = snd_soc_codec_get_drvdata(codec);
int coeff, rate;
u16 iface;
iface = snd_soc_read(codec, ALC5623_DAI_CONTROL);
iface &= ~ALC5623_DAI_I2S_DL_MASK;
/* bit size */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
iface |= ALC5623_DAI_I2S_DL_16;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface |= ALC5623_DAI_I2S_DL_20;
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface |= ALC5623_DAI_I2S_DL_24;
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface |= ALC5623_DAI_I2S_DL_32;
break;
default:
return -EINVAL;
}
/* set iface & srate */
snd_soc_write(codec, ALC5623_DAI_CONTROL, iface);
rate = params_rate(params);
coeff = get_coeff(codec, rate);
if (coeff < 0)
return -EINVAL;
coeff = coeff_div[coeff].regvalue;
dev_dbg(codec->dev, "%s: sysclk=%d,rate=%d,coeff=0x%04x\n",
__func__, alc5623->sysclk, rate, coeff);
snd_soc_write(codec, ALC5623_STEREO_AD_DA_CLK_CTRL, coeff);
return 0;
}
static int alc5623_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 hp_mute = ALC5623_MISC_M_DAC_L_INPUT | ALC5623_MISC_M_DAC_R_INPUT;
u16 mute_reg = snd_soc_read(codec, ALC5623_MISC_CTRL) & ~hp_mute;
if (mute)
mute_reg |= hp_mute;
return snd_soc_write(codec, ALC5623_MISC_CTRL, mute_reg);
}
#define ALC5623_ADD2_POWER_EN (ALC5623_PWR_ADD2_VREF \
| ALC5623_PWR_ADD2_DAC_REF_CIR)
#define ALC5623_ADD3_POWER_EN (ALC5623_PWR_ADD3_MAIN_BIAS \
| ALC5623_PWR_ADD3_MIC1_BOOST_AD)
#define ALC5623_ADD1_POWER_EN \
(ALC5623_PWR_ADD1_SHORT_CURR_DET_EN | ALC5623_PWR_ADD1_SOFTGEN_EN \
| ALC5623_PWR_ADD1_DEPOP_BUF_HP | ALC5623_PWR_ADD1_HP_OUT_AMP \
| ALC5623_PWR_ADD1_HP_OUT_ENH_AMP)
#define ALC5623_ADD1_POWER_EN_5622 \
(ALC5623_PWR_ADD1_SHORT_CURR_DET_EN \
| ALC5623_PWR_ADD1_HP_OUT_AMP)
static void enable_power_depop(struct snd_soc_codec *codec)
{
struct alc5623_priv *alc5623 = snd_soc_codec_get_drvdata(codec);
snd_soc_update_bits(codec, ALC5623_PWR_MANAG_ADD1,
ALC5623_PWR_ADD1_SOFTGEN_EN,
ALC5623_PWR_ADD1_SOFTGEN_EN);
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD3, ALC5623_ADD3_POWER_EN);
snd_soc_update_bits(codec, ALC5623_MISC_CTRL,
ALC5623_MISC_HP_DEPOP_MODE2_EN,
ALC5623_MISC_HP_DEPOP_MODE2_EN);
msleep(500);
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD2, ALC5623_ADD2_POWER_EN);
/* avoid writing '1' into 5622 reserved bits */
if (alc5623->id == 0x22)
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD1,
ALC5623_ADD1_POWER_EN_5622);
else
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD1,
ALC5623_ADD1_POWER_EN);
/* disable HP Depop2 */
snd_soc_update_bits(codec, ALC5623_MISC_CTRL,
ALC5623_MISC_HP_DEPOP_MODE2_EN,
0);
}
static int alc5623_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON:
enable_power_depop(codec);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
/* everything off except vref/vmid, */
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD2,
ALC5623_PWR_ADD2_VREF);
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD3,
ALC5623_PWR_ADD3_MAIN_BIAS);
break;
case SND_SOC_BIAS_OFF:
/* everything off, dac mute, inactive */
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD2, 0);
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD3, 0);
snd_soc_write(codec, ALC5623_PWR_MANAG_ADD1, 0);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define ALC5623_FORMATS (SNDRV_PCM_FMTBIT_S16_LE \
| SNDRV_PCM_FMTBIT_S24_LE \
| SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops alc5623_dai_ops = {
.hw_params = alc5623_pcm_hw_params,
.digital_mute = alc5623_mute,
.set_fmt = alc5623_set_dai_fmt,
.set_sysclk = alc5623_set_dai_sysclk,
.set_pll = alc5623_set_dai_pll,
};
static struct snd_soc_dai_driver alc5623_dai = {
.name = "alc5623-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = ALC5623_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = ALC5623_FORMATS,},
.ops = &alc5623_dai_ops,
};
static int alc5623_suspend(struct snd_soc_codec *codec)
{
alc5623_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int alc5623_resume(struct snd_soc_codec *codec)
{
int i, step = codec->driver->reg_cache_step;
u16 *cache = codec->reg_cache;
/* Sync reg_cache with the hardware */
for (i = 2 ; i < codec->driver->reg_cache_size ; i += step)
snd_soc_write(codec, i, cache[i]);
alc5623_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
/* charge alc5623 caps */
if (codec->dapm.suspend_bias_level == SND_SOC_BIAS_ON) {
alc5623_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
codec->dapm.bias_level = SND_SOC_BIAS_ON;
alc5623_set_bias_level(codec, codec->dapm.bias_level);
}
return 0;
}
static int alc5623_probe(struct snd_soc_codec *codec)
{
struct alc5623_priv *alc5623 = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret;
ret = snd_soc_codec_set_cache_io(codec, 8, 16, alc5623->control_type);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
alc5623_reset(codec);
alc5623_fill_cache(codec);
/* power on device */
alc5623_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
if (alc5623->add_ctrl) {
snd_soc_write(codec, ALC5623_ADD_CTRL_REG,
alc5623->add_ctrl);
}
if (alc5623->jack_det_ctrl) {
snd_soc_write(codec, ALC5623_JACK_DET_CTRL,
alc5623->jack_det_ctrl);
}
switch (alc5623->id) {
case 0x21:
snd_soc_add_codec_controls(codec, alc5621_vol_snd_controls,
ARRAY_SIZE(alc5621_vol_snd_controls));
break;
case 0x22:
snd_soc_add_codec_controls(codec, alc5622_vol_snd_controls,
ARRAY_SIZE(alc5622_vol_snd_controls));
break;
case 0x23:
snd_soc_add_codec_controls(codec, alc5623_vol_snd_controls,
ARRAY_SIZE(alc5623_vol_snd_controls));
break;
default:
return -EINVAL;
}
snd_soc_add_codec_controls(codec, alc5623_snd_controls,
ARRAY_SIZE(alc5623_snd_controls));
snd_soc_dapm_new_controls(dapm, alc5623_dapm_widgets,
ARRAY_SIZE(alc5623_dapm_widgets));
/* set up audio path interconnects */
snd_soc_dapm_add_routes(dapm, intercon, ARRAY_SIZE(intercon));
switch (alc5623->id) {
case 0x21:
case 0x22:
snd_soc_dapm_new_controls(dapm, alc5623_dapm_amp_widgets,
ARRAY_SIZE(alc5623_dapm_amp_widgets));
snd_soc_dapm_add_routes(dapm, intercon_amp_spk,
ARRAY_SIZE(intercon_amp_spk));
break;
case 0x23:
snd_soc_dapm_add_routes(dapm, intercon_spk,
ARRAY_SIZE(intercon_spk));
break;
default:
return -EINVAL;
}
return ret;
}
/* power down chip */
static int alc5623_remove(struct snd_soc_codec *codec)
{
alc5623_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_device_alc5623 = {
.probe = alc5623_probe,
.remove = alc5623_remove,
.suspend = alc5623_suspend,
.resume = alc5623_resume,
.set_bias_level = alc5623_set_bias_level,
.reg_cache_size = ALC5623_VENDOR_ID2+2,
.reg_word_size = sizeof(u16),
.reg_cache_step = 2,
};
/*
* ALC5623 2 wire address is determined by A1 pin
* state during powerup.
* low = 0x1a
* high = 0x1b
*/
static int alc5623_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct alc5623_platform_data *pdata;
struct alc5623_priv *alc5623;
int ret, vid1, vid2;
vid1 = i2c_smbus_read_word_data(client, ALC5623_VENDOR_ID1);
if (vid1 < 0) {
dev_err(&client->dev, "failed to read I2C\n");
return -EIO;
}
vid1 = ((vid1 & 0xff) << 8) | (vid1 >> 8);
vid2 = i2c_smbus_read_byte_data(client, ALC5623_VENDOR_ID2);
if (vid2 < 0) {
dev_err(&client->dev, "failed to read I2C\n");
return -EIO;
}
if ((vid1 != 0x10ec) || (vid2 != id->driver_data)) {
dev_err(&client->dev, "unknown or wrong codec\n");
dev_err(&client->dev, "Expected %x:%lx, got %x:%x\n",
0x10ec, id->driver_data,
vid1, vid2);
return -ENODEV;
}
dev_dbg(&client->dev, "Found codec id : alc56%02x\n", vid2);
alc5623 = devm_kzalloc(&client->dev, sizeof(struct alc5623_priv),
GFP_KERNEL);
if (alc5623 == NULL)
return -ENOMEM;
pdata = client->dev.platform_data;
if (pdata) {
alc5623->add_ctrl = pdata->add_ctrl;
alc5623->jack_det_ctrl = pdata->jack_det_ctrl;
}
alc5623->id = vid2;
switch (alc5623->id) {
case 0x21:
alc5623_dai.name = "alc5621-hifi";
break;
case 0x22:
alc5623_dai.name = "alc5622-hifi";
break;
case 0x23:
alc5623_dai.name = "alc5623-hifi";
break;
default:
return -EINVAL;
}
i2c_set_clientdata(client, alc5623);
alc5623->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&client->dev,
&soc_codec_device_alc5623, &alc5623_dai, 1);
if (ret != 0)
dev_err(&client->dev, "Failed to register codec: %d\n", ret);
return ret;
}
static int alc5623_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id alc5623_i2c_table[] = {
{"alc5621", 0x21},
{"alc5622", 0x22},
{"alc5623", 0x23},
{}
};
MODULE_DEVICE_TABLE(i2c, alc5623_i2c_table);
/* i2c codec control layer */
static struct i2c_driver alc5623_i2c_driver = {
.driver = {
.name = "alc562x-codec",
.owner = THIS_MODULE,
},
.probe = alc5623_i2c_probe,
.remove = alc5623_i2c_remove,
.id_table = alc5623_i2c_table,
};
module_i2c_driver(alc5623_i2c_driver);
MODULE_DESCRIPTION("ASoC alc5621/2/3 driver");
MODULE_AUTHOR("Arnaud Patard <arnaud.patard@rtp-net.org>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mikshepard/android_kernel_samsung_klte | drivers/power/bq27520_fuelgauger.c | 3504 | 24461 | /* Copyright (C) 2008 Rodolfo Giometti <giometti@linux.it>
* Copyright (C) 2008 Eurotech S.p.A. <info@eurotech.it>
* Based on a previous work by Copyright (C) 2008 Texas Instruments, Inc.
*
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/param.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/idr.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <linux/time.h>
#include <linux/i2c/bq27520.h>
#include <linux/mfd/pmic8058.h>
#include <linux/regulator/pmic8058-regulator.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <linux/err.h>
#include <linux/msm-charger.h>
#define DRIVER_VERSION "1.1.0"
/* Bq27520 standard data commands */
#define BQ27520_REG_CNTL 0x00
#define BQ27520_REG_AR 0x02
#define BQ27520_REG_ARTTE 0x04
#define BQ27520_REG_TEMP 0x06
#define BQ27520_REG_VOLT 0x08
#define BQ27520_REG_FLAGS 0x0A
#define BQ27520_REG_NAC 0x0C
#define BQ27520_REG_FAC 0x0e
#define BQ27520_REG_RM 0x10
#define BQ27520_REG_FCC 0x12
#define BQ27520_REG_AI 0x14
#define BQ27520_REG_TTE 0x16
#define BQ27520_REG_TTF 0x18
#define BQ27520_REG_SI 0x1a
#define BQ27520_REG_STTE 0x1c
#define BQ27520_REG_MLI 0x1e
#define BQ27520_REG_MLTTE 0x20
#define BQ27520_REG_AE 0x22
#define BQ27520_REG_AP 0x24
#define BQ27520_REG_TTECP 0x26
#define BQ27520_REG_SOH 0x28
#define BQ27520_REG_SOC 0x2c
#define BQ27520_REG_NIC 0x2e
#define BQ27520_REG_ICR 0x30
#define BQ27520_REG_LOGIDX 0x32
#define BQ27520_REG_LOGBUF 0x34
#define BQ27520_FLAG_DSC BIT(0)
#define BQ27520_FLAG_FC BIT(9)
#define BQ27520_FLAG_BAT_DET BIT(3)
#define BQ27520_CS_DLOGEN BIT(15)
#define BQ27520_CS_SS BIT(13)
/* Control subcommands */
#define BQ27520_SUBCMD_CTNL_STATUS 0x0000
#define BQ27520_SUBCMD_DEVCIE_TYPE 0x0001
#define BQ27520_SUBCMD_FW_VER 0x0002
#define BQ27520_SUBCMD_HW_VER 0x0003
#define BQ27520_SUBCMD_DF_CSUM 0x0004
#define BQ27520_SUBCMD_PREV_MACW 0x0007
#define BQ27520_SUBCMD_CHEM_ID 0x0008
#define BQ27520_SUBCMD_BD_OFFSET 0x0009
#define BQ27520_SUBCMD_INT_OFFSET 0x000a
#define BQ27520_SUBCMD_CC_VER 0x000b
#define BQ27520_SUBCMD_OCV 0x000c
#define BQ27520_SUBCMD_BAT_INS 0x000d
#define BQ27520_SUBCMD_BAT_REM 0x000e
#define BQ27520_SUBCMD_SET_HIB 0x0011
#define BQ27520_SUBCMD_CLR_HIB 0x0012
#define BQ27520_SUBCMD_SET_SLP 0x0013
#define BQ27520_SUBCMD_CLR_SLP 0x0014
#define BQ27520_SUBCMD_FCT_RES 0x0015
#define BQ27520_SUBCMD_ENABLE_DLOG 0x0018
#define BQ27520_SUBCMD_DISABLE_DLOG 0x0019
#define BQ27520_SUBCMD_SEALED 0x0020
#define BQ27520_SUBCMD_ENABLE_IT 0x0021
#define BQ27520_SUBCMD_DISABLE_IT 0x0023
#define BQ27520_SUBCMD_CAL_MODE 0x0040
#define BQ27520_SUBCMD_RESET 0x0041
#define ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN (-2731)
#define BQ27520_INIT_DELAY ((HZ)*1)
#define BQ27520_POLLING_STATUS ((HZ)*3)
#define BQ27520_COULOMB_POLL ((HZ)*30)
/* If the system has several batteries we need a different name for each
* of them...
*/
static DEFINE_IDR(battery_id);
static DEFINE_MUTEX(battery_mutex);
struct bq27520_device_info;
struct bq27520_access_methods {
int (*read)(u8 reg, int *rt_value, int b_single,
struct bq27520_device_info *di);
};
struct bq27520_device_info {
struct device *dev;
int id;
struct bq27520_access_methods *bus;
struct i2c_client *client;
const struct bq27520_platform_data *pdata;
struct work_struct counter;
/* 300ms delay is needed after bq27520 is powered up
* and before any successful I2C transaction
*/
struct delayed_work hw_config;
uint32_t irq;
};
enum {
GET_BATTERY_STATUS,
GET_BATTERY_TEMPERATURE,
GET_BATTERY_VOLTAGE,
GET_BATTERY_CAPACITY,
NUM_OF_STATUS,
};
struct bq27520_status {
/* Informations owned and maintained by Bq27520 driver, updated
* by poller or SOC_INT interrupt, decoupling from I/Oing
* hardware directly
*/
int status[NUM_OF_STATUS];
spinlock_t lock;
struct delayed_work poller;
};
static struct bq27520_status current_battery_status;
static struct bq27520_device_info *bq27520_di;
static int coulomb_counter;
static spinlock_t lock; /* protect access to coulomb_counter */
static struct timer_list timer; /* charge counter timer every 30 secs */
static int bq27520_i2c_txsubcmd(u8 reg, unsigned short subcmd,
struct bq27520_device_info *di);
static int bq27520_read(u8 reg, int *rt_value, int b_single,
struct bq27520_device_info *di)
{
return di->bus->read(reg, rt_value, b_single, di);
}
/*
* Return the battery temperature in tenths of degree Celsius
* Or < 0 if something fails.
*/
static int bq27520_battery_temperature(struct bq27520_device_info *di)
{
int ret, temp = 0;
ret = bq27520_read(BQ27520_REG_TEMP, &temp, 0, di);
if (ret) {
dev_err(di->dev, "error %d reading temperature\n", ret);
return ret;
}
return temp + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN;
}
/*
* Return the battery Voltage in milivolts
* Or < 0 if something fails.
*/
static int bq27520_battery_voltage(struct bq27520_device_info *di)
{
int ret, volt = 0;
ret = bq27520_read(BQ27520_REG_VOLT, &volt, 0, di);
if (ret) {
dev_err(di->dev, "error %d reading voltage\n", ret);
return ret;
}
return volt;
}
/*
* Return the battery Relative State-of-Charge
* Or < 0 if something fails.
*/
static int bq27520_battery_rsoc(struct bq27520_device_info *di)
{
int ret, rsoc = 0;
ret = bq27520_read(BQ27520_REG_SOC, &rsoc, 0, di);
if (ret) {
dev_err(di->dev,
"error %d reading relative State-of-Charge\n", ret);
return ret;
}
return rsoc;
}
static void bq27520_cntl_cmd(struct bq27520_device_info *di,
int subcmd)
{
bq27520_i2c_txsubcmd(BQ27520_REG_CNTL, subcmd, di);
}
/*
* i2c specific code
*/
static int bq27520_i2c_txsubcmd(u8 reg, unsigned short subcmd,
struct bq27520_device_info *di)
{
struct i2c_msg msg;
unsigned char data[3];
if (!di->client)
return -ENODEV;
memset(data, 0, sizeof(data));
data[0] = reg;
data[1] = subcmd & 0x00FF;
data[2] = (subcmd & 0xFF00) >> 8;
msg.addr = di->client->addr;
msg.flags = 0;
msg.len = 3;
msg.buf = data;
if (i2c_transfer(di->client->adapter, &msg, 1) < 0)
return -EIO;
return 0;
}
static int bq27520_chip_config(struct bq27520_device_info *di)
{
int flags = 0, ret = 0;
bq27520_cntl_cmd(di, BQ27520_SUBCMD_CTNL_STATUS);
udelay(66);
ret = bq27520_read(BQ27520_REG_CNTL, &flags, 0, di);
if (ret < 0) {
dev_err(di->dev, "error %d reading register %02x\n",
ret, BQ27520_REG_CNTL);
return ret;
}
udelay(66);
bq27520_cntl_cmd(di, BQ27520_SUBCMD_ENABLE_IT);
udelay(66);
if (di->pdata->enable_dlog && !(flags & BQ27520_CS_DLOGEN)) {
bq27520_cntl_cmd(di, BQ27520_SUBCMD_ENABLE_DLOG);
udelay(66);
}
return 0;
}
static void bq27520_every_30secs(unsigned long data)
{
struct bq27520_device_info *di = (struct bq27520_device_info *)data;
schedule_work(&di->counter);
mod_timer(&timer, jiffies + BQ27520_COULOMB_POLL);
}
static void bq27520_coulomb_counter_work(struct work_struct *work)
{
int value = 0, temp = 0, index = 0, ret = 0, count = 0;
struct bq27520_device_info *di;
unsigned long flags;
di = container_of(work, struct bq27520_device_info, counter);
/* retrieve 30 values from FIFO of coulomb data logging buffer
* and average over time
*/
do {
ret = bq27520_read(BQ27520_REG_LOGBUF, &temp, 0, di);
if (ret < 0)
break;
if (temp != 0x7FFF) {
++count;
value += temp;
}
udelay(66);
ret = bq27520_read(BQ27520_REG_LOGIDX, &index, 0, di);
if (ret < 0)
break;
udelay(66);
} while (index != 0 || temp != 0x7FFF);
if (ret < 0) {
dev_err(di->dev, "Error %d reading datalog register\n", ret);
return;
}
if (count) {
spin_lock_irqsave(&lock, flags);
coulomb_counter = value/count;
spin_unlock_irqrestore(&lock, flags);
}
}
static int bq27520_is_battery_present(void)
{
return 1;
}
static int bq27520_is_battery_temp_within_range(void)
{
return 1;
}
static int bq27520_is_battery_id_valid(void)
{
return 1;
}
static int bq27520_status_getter(int function)
{
int status = 0;
unsigned long flags;
spin_lock_irqsave(¤t_battery_status.lock, flags);
status = current_battery_status.status[function];
spin_unlock_irqrestore(¤t_battery_status.lock, flags);
return status;
}
static int bq27520_get_battery_mvolts(void)
{
return bq27520_status_getter(GET_BATTERY_VOLTAGE);
}
static int bq27520_get_battery_temperature(void)
{
return bq27520_status_getter(GET_BATTERY_TEMPERATURE);
}
static int bq27520_get_battery_status(void)
{
return bq27520_status_getter(GET_BATTERY_STATUS);
}
static int bq27520_get_remaining_capacity(void)
{
return bq27520_status_getter(GET_BATTERY_CAPACITY);
}
static struct msm_battery_gauge bq27520_batt_gauge = {
.get_battery_mvolts = bq27520_get_battery_mvolts,
.get_battery_temperature = bq27520_get_battery_temperature,
.is_battery_present = bq27520_is_battery_present,
.is_battery_temp_within_range = bq27520_is_battery_temp_within_range,
.is_battery_id_valid = bq27520_is_battery_id_valid,
.get_battery_status = bq27520_get_battery_status,
.get_batt_remaining_capacity = bq27520_get_remaining_capacity,
};
static void update_current_battery_status(int data)
{
int status[4], ret = 0;
unsigned long flag;
memset(status, 0, sizeof status);
ret = bq27520_battery_rsoc(bq27520_di);
status[GET_BATTERY_CAPACITY] = (ret < 0) ? 0 : ret;
status[GET_BATTERY_VOLTAGE] = bq27520_battery_voltage(bq27520_di);
status[GET_BATTERY_TEMPERATURE] =
bq27520_battery_temperature(bq27520_di);
spin_lock_irqsave(¤t_battery_status.lock, flag);
current_battery_status.status[GET_BATTERY_STATUS] = data;
current_battery_status.status[GET_BATTERY_VOLTAGE] =
status[GET_BATTERY_VOLTAGE];
current_battery_status.status[GET_BATTERY_TEMPERATURE] =
status[GET_BATTERY_TEMPERATURE];
current_battery_status.status[GET_BATTERY_CAPACITY] =
status[GET_BATTERY_CAPACITY];
spin_unlock_irqrestore(¤t_battery_status.lock, flag);
}
/* only if battery charging satus changes then notify msm_charger. otherwise
* only refresh current_batter_status
*/
static int if_notify_msm_charger(int *data)
{
int ret = 0, flags = 0, status = 0;
unsigned long flag;
ret = bq27520_read(BQ27520_REG_FLAGS, &flags, 0, bq27520_di);
if (ret < 0) {
dev_err(bq27520_di->dev, "error %d reading register %02x\n",
ret, BQ27520_REG_FLAGS);
status = POWER_SUPPLY_STATUS_UNKNOWN;
} else {
if (flags & BQ27520_FLAG_FC)
status = POWER_SUPPLY_STATUS_FULL;
else if (flags & BQ27520_FLAG_DSC)
status = POWER_SUPPLY_STATUS_DISCHARGING;
else
status = POWER_SUPPLY_STATUS_CHARGING;
}
*data = status;
spin_lock_irqsave(¤t_battery_status.lock, flag);
ret = (status != current_battery_status.status[GET_BATTERY_STATUS]);
spin_unlock_irqrestore(¤t_battery_status.lock, flag);
return ret;
}
static void battery_status_poller(struct work_struct *work)
{
int status = 0, temp = 0;
temp = if_notify_msm_charger(&status);
update_current_battery_status(status);
if (temp)
msm_charger_notify_event(NULL, CHG_BATT_STATUS_CHANGE);
schedule_delayed_work(¤t_battery_status.poller,
BQ27520_POLLING_STATUS);
}
static void bq27520_hw_config(struct work_struct *work)
{
int ret = 0, flags = 0, type = 0, fw_ver = 0, status = 0;
struct bq27520_device_info *di;
di = container_of(work, struct bq27520_device_info, hw_config.work);
pr_debug(KERN_INFO "Enter bq27520_hw_config\n");
ret = bq27520_chip_config(di);
if (ret) {
dev_err(di->dev, "Failed to config Bq27520 ret = %d\n", ret);
return;
}
/* bq27520 is ready for access, update current_battery_status by reading
* from hardware
*/
if_notify_msm_charger(&status);
update_current_battery_status(status);
msm_battery_gauge_register(&bq27520_batt_gauge);
msm_charger_notify_event(NULL, CHG_BATT_STATUS_CHANGE);
enable_irq(di->irq);
/* poll battery status every 3 seconds, if charging status changes,
* notify msm_charger
*/
schedule_delayed_work(¤t_battery_status.poller,
BQ27520_POLLING_STATUS);
if (di->pdata->enable_dlog) {
schedule_work(&di->counter);
init_timer(&timer);
timer.function = &bq27520_every_30secs;
timer.data = (unsigned long)di;
timer.expires = jiffies + BQ27520_COULOMB_POLL;
add_timer(&timer);
}
bq27520_cntl_cmd(di, BQ27520_SUBCMD_CTNL_STATUS);
udelay(66);
bq27520_read(BQ27520_REG_CNTL, &flags, 0, di);
bq27520_cntl_cmd(di, BQ27520_SUBCMD_DEVCIE_TYPE);
udelay(66);
bq27520_read(BQ27520_REG_CNTL, &type, 0, di);
bq27520_cntl_cmd(di, BQ27520_SUBCMD_FW_VER);
udelay(66);
bq27520_read(BQ27520_REG_CNTL, &fw_ver, 0, di);
dev_info(di->dev, "DEVICE_TYPE is 0x%02X, FIRMWARE_VERSION\
is 0x%02X\n", type, fw_ver);
dev_info(di->dev, "Complete bq27520 configuration 0x%02X\n", flags);
}
static int bq27520_read_i2c(u8 reg, int *rt_value, int b_single,
struct bq27520_device_info *di)
{
struct i2c_client *client = di->client;
struct i2c_msg msg[1];
unsigned char data[2];
int err;
if (!client->adapter)
return -ENODEV;
msg->addr = client->addr;
msg->flags = 0;
msg->len = 1;
msg->buf = data;
data[0] = reg;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
msg->len = 2;
else
msg->len = 1;
msg->flags = I2C_M_RD;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
*rt_value = get_unaligned_le16(data);
else
*rt_value = data[0];
return 0;
}
}
return err;
}
#ifdef CONFIG_BQ27520_TEST_ENABLE
static int reg;
static int subcmd;
static ssize_t bq27520_read_stdcmd(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
int temp = 0;
struct platform_device *client;
struct bq27520_device_info *di;
client = to_platform_device(dev);
di = platform_get_drvdata(client);
if (reg <= BQ27520_REG_ICR && reg > 0x00) {
ret = bq27520_read(reg, &temp, 0, di);
if (ret)
ret = snprintf(buf, PAGE_SIZE, "Read Error!\n");
else
ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp);
} else
ret = snprintf(buf, PAGE_SIZE, "Register Error!\n");
return ret;
}
static ssize_t bq27520_write_stdcmd(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
ssize_t ret = strnlen(buf, PAGE_SIZE);
int cmd;
sscanf(buf, "%x", &cmd);
reg = cmd;
dev_info(dev, "recv'd cmd is 0x%02X\n", reg);
return ret;
}
static ssize_t bq27520_read_subcmd(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret, temp = 0;
struct platform_device *client;
struct bq27520_device_info *di;
client = to_platform_device(dev);
di = platform_get_drvdata(client);
if (subcmd == BQ27520_SUBCMD_DEVCIE_TYPE ||
subcmd == BQ27520_SUBCMD_FW_VER ||
subcmd == BQ27520_SUBCMD_HW_VER ||
subcmd == BQ27520_SUBCMD_CHEM_ID) {
bq27520_cntl_cmd(di, subcmd);/* Retrieve Chip status */
udelay(66);
ret = bq27520_read(BQ27520_REG_CNTL, &temp, 0, di);
if (ret)
ret = snprintf(buf, PAGE_SIZE, "Read Error!\n");
else
ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp);
} else
ret = snprintf(buf, PAGE_SIZE, "Register Error!\n");
return ret;
}
static ssize_t bq27520_write_subcmd(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
ssize_t ret = strnlen(buf, PAGE_SIZE);
int cmd;
sscanf(buf, "%x", &cmd);
subcmd = cmd;
return ret;
}
static DEVICE_ATTR(std_cmd, S_IRUGO|S_IWUGO, bq27520_read_stdcmd,
bq27520_write_stdcmd);
static DEVICE_ATTR(sub_cmd, S_IRUGO|S_IWUGO, bq27520_read_subcmd,
bq27520_write_subcmd);
static struct attribute *fs_attrs[] = {
&dev_attr_std_cmd.attr,
&dev_attr_sub_cmd.attr,
NULL,
};
static struct attribute_group fs_attr_group = {
.attrs = fs_attrs,
};
static struct platform_device this_device = {
.name = "bq27520-test",
.id = -1,
.dev.platform_data = NULL,
};
#endif
static irqreturn_t soc_irqhandler(int irq, void *dev_id)
{
int status = 0, temp = 0;
temp = if_notify_msm_charger(&status);
update_current_battery_status(status);
if (temp)
msm_charger_notify_event(NULL, CHG_BATT_STATUS_CHANGE);
return IRQ_HANDLED;
}
static struct regulator *vreg_bq27520;
static int bq27520_power(bool enable, struct bq27520_device_info *di)
{
int rc = 0, ret;
const struct bq27520_platform_data *platdata;
platdata = di->pdata;
if (enable) {
/* switch on Vreg_S3 */
rc = regulator_enable(vreg_bq27520);
if (rc < 0) {
dev_err(di->dev, "%s: vreg %s %s failed (%d)\n",
__func__, platdata->vreg_name, "enable", rc);
goto vreg_fail;
}
/* Battery gauge enable and switch on onchip 2.5V LDO */
rc = gpio_request(platdata->chip_en, "GAUGE_EN");
if (rc) {
dev_err(di->dev, "%s: fail to request gpio %d (%d)\n",
__func__, platdata->chip_en, rc);
goto vreg_fail;
}
gpio_direction_output(platdata->chip_en, 0);
gpio_set_value(platdata->chip_en, 1);
rc = gpio_request(platdata->soc_int, "GAUGE_SOC_INT");
if (rc) {
dev_err(di->dev, "%s: fail to request gpio %d (%d)\n",
__func__, platdata->soc_int, rc);
goto gpio_fail;
}
gpio_direction_input(platdata->soc_int);
di->irq = gpio_to_irq(platdata->soc_int);
rc = request_threaded_irq(di->irq, NULL, soc_irqhandler,
IRQF_TRIGGER_FALLING|IRQF_TRIGGER_RISING,
"BQ27520_IRQ", di);
if (rc) {
dev_err(di->dev, "%s: fail to request irq %d (%d)\n",
__func__, platdata->soc_int, rc);
goto irqreq_fail;
} else {
disable_irq_nosync(di->irq);
}
} else {
free_irq(di->irq, di);
gpio_free(platdata->soc_int);
/* switch off on-chip 2.5V LDO and disable Battery gauge */
gpio_set_value(platdata->chip_en, 0);
gpio_free(platdata->chip_en);
/* switch off Vreg_S3 */
rc = regulator_disable(vreg_bq27520);
if (rc < 0) {
dev_err(di->dev, "%s: vreg %s %s failed (%d)\n",
__func__, platdata->vreg_name, "disable", rc);
goto vreg_fail;
}
}
return rc;
irqreq_fail:
gpio_free(platdata->soc_int);
gpio_fail:
gpio_set_value(platdata->chip_en, 0);
gpio_free(platdata->chip_en);
vreg_fail:
ret = !enable ? regulator_enable(vreg_bq27520) :
regulator_disable(vreg_bq27520);
if (ret < 0) {
dev_err(di->dev, "%s: vreg %s %s failed (%d) in err path\n",
__func__, platdata->vreg_name,
!enable ? "enable" : "disable", ret);
}
return rc;
}
static int bq27520_dev_setup(bool enable, struct bq27520_device_info *di)
{
int rc;
const struct bq27520_platform_data *platdata;
platdata = di->pdata;
if (enable) {
/* enable and set voltage Vreg_S3 */
vreg_bq27520 = regulator_get(NULL,
platdata->vreg_name);
if (IS_ERR(vreg_bq27520)) {
dev_err(di->dev, "%s: regulator get of %s\
failed (%ld)\n", __func__, platdata->vreg_name,
PTR_ERR(vreg_bq27520));
rc = PTR_ERR(vreg_bq27520);
goto vreg_get_fail;
}
rc = regulator_set_voltage(vreg_bq27520,
platdata->vreg_value, platdata->vreg_value);
if (rc) {
dev_err(di->dev, "%s: regulator_set_voltage(%s) failed\
(%d)\n", __func__, platdata->vreg_name, rc);
goto vreg_get_fail;
}
} else {
regulator_put(vreg_bq27520);
}
return 0;
vreg_get_fail:
regulator_put(vreg_bq27520);
return rc;
}
static int bq27520_battery_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct bq27520_device_info *di;
struct bq27520_access_methods *bus;
const struct bq27520_platform_data *pdata;
int num, retval = 0;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
pdata = client->dev.platform_data;
/* Get new ID for the new battery device */
retval = idr_pre_get(&battery_id, GFP_KERNEL);
if (retval == 0)
return -ENOMEM;
mutex_lock(&battery_mutex);
retval = idr_get_new(&battery_id, client, &num);
mutex_unlock(&battery_mutex);
if (retval < 0)
return retval;
di = kzalloc(sizeof(*di), GFP_KERNEL);
if (!di) {
dev_err(&client->dev, "failed to allocate device info data\n");
retval = -ENOMEM;
goto batt_failed_1;
}
di->id = num;
di->pdata = pdata;
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus) {
dev_err(&client->dev, "failed to allocate data\n");
retval = -ENOMEM;
goto batt_failed_2;
}
i2c_set_clientdata(client, di);
di->dev = &client->dev;
bus->read = &bq27520_read_i2c;
di->bus = bus;
di->client = client;
#ifdef CONFIG_BQ27520_TEST_ENABLE
platform_set_drvdata(&this_device, di);
retval = platform_device_register(&this_device);
if (!retval) {
retval = sysfs_create_group(&this_device.dev.kobj,
&fs_attr_group);
if (retval)
goto batt_failed_3;
} else
goto batt_failed_3;
#endif
retval = bq27520_dev_setup(true, di);
if (retval) {
dev_err(&client->dev, "failed to setup ret = %d\n", retval);
goto batt_failed_3;
}
retval = bq27520_power(true, di);
if (retval) {
dev_err(&client->dev, "failed to powerup ret = %d\n", retval);
goto batt_failed_3;
}
spin_lock_init(&lock);
bq27520_di = di;
if (pdata->enable_dlog)
INIT_WORK(&di->counter, bq27520_coulomb_counter_work);
INIT_DELAYED_WORK(¤t_battery_status.poller,
battery_status_poller);
INIT_DELAYED_WORK(&di->hw_config, bq27520_hw_config);
schedule_delayed_work(&di->hw_config, BQ27520_INIT_DELAY);
return 0;
batt_failed_3:
kfree(bus);
batt_failed_2:
kfree(di);
batt_failed_1:
mutex_lock(&battery_mutex);
idr_remove(&battery_id, num);
mutex_unlock(&battery_mutex);
return retval;
}
static int bq27520_battery_remove(struct i2c_client *client)
{
struct bq27520_device_info *di = i2c_get_clientdata(client);
if (di->pdata->enable_dlog) {
del_timer_sync(&timer);
cancel_work_sync(&di->counter);
bq27520_cntl_cmd(di, BQ27520_SUBCMD_DISABLE_DLOG);
udelay(66);
}
bq27520_cntl_cmd(di, BQ27520_SUBCMD_DISABLE_IT);
cancel_delayed_work_sync(&di->hw_config);
cancel_delayed_work_sync(¤t_battery_status.poller);
bq27520_dev_setup(false, di);
bq27520_power(false, di);
kfree(di->bus);
mutex_lock(&battery_mutex);
idr_remove(&battery_id, di->id);
mutex_unlock(&battery_mutex);
kfree(di);
return 0;
}
#ifdef CONFIG_PM
static int bq27520_suspend(struct device *dev)
{
struct bq27520_device_info *di = dev_get_drvdata(dev);
disable_irq_nosync(di->irq);
if (di->pdata->enable_dlog) {
del_timer_sync(&timer);
cancel_work_sync(&di->counter);
}
cancel_delayed_work_sync(¤t_battery_status.poller);
return 0;
}
static int bq27520_resume(struct device *dev)
{
struct bq27520_device_info *di = dev_get_drvdata(dev);
enable_irq(di->irq);
if (di->pdata->enable_dlog)
add_timer(&timer);
schedule_delayed_work(¤t_battery_status.poller,
BQ27520_POLLING_STATUS);
return 0;
}
static const struct dev_pm_ops bq27520_pm_ops = {
.suspend = bq27520_suspend,
.resume = bq27520_resume,
};
#endif
static const struct i2c_device_id bq27520_id[] = {
{ "bq27520", 1 },
{},
};
MODULE_DEVICE_TABLE(i2c, BQ27520_id);
static struct i2c_driver bq27520_battery_driver = {
.driver = {
.name = "bq27520-battery",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &bq27520_pm_ops,
#endif
},
.probe = bq27520_battery_probe,
.remove = bq27520_battery_remove,
.id_table = bq27520_id,
};
static void init_battery_status(void)
{
spin_lock_init(¤t_battery_status.lock);
current_battery_status.status[GET_BATTERY_STATUS] =
POWER_SUPPLY_STATUS_UNKNOWN;
}
static int __init bq27520_battery_init(void)
{
int ret;
/* initialize current_battery_status, and register with msm-charger */
init_battery_status();
ret = i2c_add_driver(&bq27520_battery_driver);
if (ret)
printk(KERN_ERR "Unable to register driver ret = %d\n", ret);
return ret;
}
module_init(bq27520_battery_init);
static void __exit bq27520_battery_exit(void)
{
i2c_del_driver(&bq27520_battery_driver);
msm_battery_gauge_unregister(&bq27520_batt_gauge);
}
module_exit(bq27520_battery_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Qualcomm Innovation Center, Inc.");
MODULE_DESCRIPTION("BQ27520 battery monitor driver");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.